SlideShare une entreprise Scribd logo
1  sur  74
AISI
Administración de Servidores Web: APACHE
MWS apache
apache
MWS apache
Servidor web altamente extendido
Proyecto de código abierto
Creado por Apache Software Foundation
 Versión 2.4
introducción
MWS apache
Altamente configurable
 Diseño modular
 Ampliación
Multiplataforma
 Linux
 Unix
 Windows (desde versión
1.3)
 Amiga OS 3x
 OS/2
Soporta HTTP 1.1
(solicitudes múltiples)
Soporta HTTP 2.0
(mod_http2 para
>=2.4.17)
características
Soporta CGI y Fast
CGI
Soporta Host Virtuales
Autenticación HTTP
Perl Integrado
Soporta PHP
Con Tomcat ->
servlets y JSP
Puede actuar como
servidor proxy
SSI (Server Side
Includes)
SSL
MWS apache
Info:https://httpd.apache.org/docs/2.4/mpm
.html
Posibilidad de configurar la distribución de los
procesos (versión 2 de apache)
Establecen la manera de atender las
peticiones de los clientes
Optimizan el servidor en función del uso que
se le quiera dar
Tipos:
 Prefork (para sitios que requieran estabilidad)
 Worked (escalabilidad)
 event
 Winnt (para sistema windows. Muy eficiente)
Módulos de MultiProceso
MWS apache
Igual que en la versión 1 de apache.
El proceso principal crea un conjunto de hijos
que sirven las peticiones
El número de hijos está establecido entre un
mínimo y un máximo
Cada hijo ejecuta un único hilo (una petición
por hijo simultáneamente)
mmp prefork
Cliente
Proceso hijo
(www-data)
Proceso hijo
(www-data)
Proceso hijo
(www-data)
Poceso princ.
(httpd) root
Servidor
80
MWS apache
Es el que más CPU y RAM consume por proceso -
petición
MaxClients/MaxRequestWorkers deben ser lo
suficientemente:
l
grande para las peticiones simultáneas que esperes
recibir
l
Pequeño para la RAM y procesos del servidor donde
se ejecuta
MaxClients=(RAM – size_all_other_processes)/
(max_size_apache_process)
MaxClients=(RAM-Shared_RAM_per_Child)/
(Max_Process_Size-Shared_RAM_per_Child)
mmp prefork
MWS apache
Directivas a tener en cuenta para regular cómo el proceso padre crea
procesos hijos para atender las peticiones entrantes:
l StarServers indica el número de procesos que se lanzarán en el
arranque
l MinSpareServers: número procesos mínimo desocupados
l MaxSpareServers: número procesos máximo desocupados
l MaxRequestWorkers: debe ser lo suficientemente grande para
tratar las solicitudes que esperamos recibir y lo suficientemente
pequeño para los asegurar que tenemos memoria RAM para todos los
procesos (solo si esperamos más de 256 peticiones simultáneas,
podríamos necesitar incrementarlo)
l MaxConnectionsPerChild: limita el número de conexiones que un
proceso puede atender durante su existencia. Superado, muere y se
lanza otro. Si es 0, ilimitado. ¿Ventajas?
l User/Group (para procesos hijos)
l Comportamiento:
si hijos idle < MinSpareServers, padre crea otros, 1, 2, 4
esperando 1” y no más de 32,
si hijos idle > MaxSpareServers, padre mata exceso de hijos
mpm prefork
MWS apache
Los procesos hijos pueden tener más de un hilo
(TheadsPerChild) Cada hilo dentro de un proceso atiende una
petición
Permite atender gran número de peticiones con menor consumo
de recursos que con prefork y conservando parte de la
estabilidad que proporciona éste
Los procesos hijos se crean o destruyen para que el número de
hilos libres se mantengan entre un mínimo (MinSpareThreads) y
un máximo (MaxSpareThreads)
Número máximo de clientes: MaxRequestWorkers
mmp worked
Cliente
Proceso hijo
www-data
Proceso hijo
www-data
Proceso hijo
www-data
Poceso princ.
(httpd) root
StartServers=3
threadsperchild=3
Servidor
80
MWS apache
Más directivas a tener en cuenta para
regular cómo el proceso padre crea
procesos hijos para atender las
peticiones entrantes:
l Las vistas para prefork más
l ServerLimit número de procesos hijos
l ThreadLimit número de hilos en el
servidor
l MaxConnectionsPerChild controla
cómo se recicla los procesos
l User/group
mpm worker
MWS apache
¿Número máximo de clientes que pueden ser
atendidos simultáneamente?
l Valor de MaxRequestWorkers
¿Número máximo de procesos hijos activos?
l MaxRequestWorkers / ThreadsPerChild
MinSpareThreads<#hijos<MaxSpareThreads
ServerLimit>=MaxRequestWorkers/ThreadsP
erChild
ThreadLimit >=ThreadsPerChild
mpm worker
MWS apache
https://httpd.apache.org/docs/2.4/mod/event.html
Está basado en el mpm worker con sockets no
bloqueantes para manejar varias conexiones por un
proceso/hilo (las indicadas por
AsyncRequestWorkerFactor)
Tiene un hilo por proceso dedicado a:
l
Escucha del socket
l
Conexiones KeepAlive
l
Sockets en los que el protocolo ya ha hecho su trabajo
l
Y aquellos en los que solo queda mandar los datos al
cliente
mpm event
Cliente
Proceso hijo
Proceso hijo
Proceso hijo
Poceso princ.
(httpd)
Servidor
80
uid=apache1
uid=apache2
uid=apache3
MWS apache
Las directivas relacionadas son las mismas que mpm
worker más AsyncRequestWorkerFactor
El número total de conexiones concurrentes para un
proceso/hilo puede manejar está regulado por
AsyncRequestWorkerFactor:
Un proceso solo aceptará nuevas conexiones si en número actual de estas es menor de:
ThreadsPerChild + (AsyncRequestWorkerFactor * number of idle workers)
Podemos calcular una estimación del número máximo de conexiones para todos los procesos con:
(ThreadsPerChild + (AsyncRequestWorkerFactor * number of idle workers)) * ServerLimit
Ejemplo
SI ThreadsPerChild = 10, ServerLimit = 4, AsyncRequestWorkerFactor = 2, MaxRequestWorkers = 40, idle_workers = 4
max_connections = (ThreadsPerChild + (AsyncRequestWorkerFactor * idle_workers)) * ServerLimit = (10 + (2 * 4)) * 4 = 72
Si todos los hilos está desocupados: max_connections = (AsyncRequestWorkerFactor + 1) * MaxRequestWorkers
mpm event
MWS apache
Optimizado para las plataformas Windows
Un proceso padre y un proceso hijo
El proceso hijo es multi-hilo
Utiliza funcionalidades de Windows
mmp winnt
Cliente Proceso hijoPoceso princ.
(httpd)
Servidor
80
MWS apache
Bajar software de www.apache.org
Instalación mediante binarios (fácil pero no
configurable)
Instalación personalizada
 Bajar fuentes
 Configurar la instalación
l ./configure [opciones]
l Esto crea un makefile personalizado
 Compilar el servidor
l make
l Entre otras cosas crea el ejecutable de Apache (httpd)
 Instalar el servidor
l make install
instalación
./configure --prefix=/usr/local/apache
(indica el directorio de instalación de
apache)
MWS apache
Configuración mediante fichero de texto
La ubicación y nombre del fichero puede cambiar según
la distribución:
 http.conf
 apache2.conf
La configuración puede estar distribuida en distintos
ficheros:
 /etc/apache2/apache2.conf (configuración general
del servidor. Desde este se incluyen el resto)
 /etc/apache2/ports.conf (configuración de puertos)
 /etc/apache2/sites-enabled/000-default
 /etc/apache2/sites-enabled/001-site1
 /etc/apache2/sites-enabled/002-site2
 (configuración de los sitios web: directorios, contenidos,
etc.)
Directiva “include”
Configuración de módulos
 /etc/apache2/mods-enabled/*.load
l LoadModule jk_module /usr/apache2/modules/mod_jk.so
 /etc/apache2/mods-enabled/*.conf
configuración
MWS apache
En Windows: http://pistachitos.com/guias/instalar-php-5-
6-sobre-apache-2-4-windows/
Activar PHP:
l
Primero instalarlo: apt-get install libapache2-mod-php5
 /etc/apache2/mods-enabled/*.load
 /etc/apache2/mods-enabled/*.conf
 En /etc/php5/apache2/php.ini configuraremos las
opciones que necesitemos para PHP
l Safe Mode = Off (Todas las funciones activas)
l Display errors = On (No para producción)
l max_execution_time=30 (Tiempo máx ejecución)
l post_max_size=8M (Máximo tamaño POST)
l upload_max_filesize = 8M
l extension=mysql.so (acceso a MySQL, necesita
también php5-mysql)
PHP
MWS apache
Configuración Windows
https://httpd.apache.org/docs/2.4/es/platform/windows.htm
l
MWS apache
Configuración Windows
MWS apache
Debemos tener en cuenta:
l
MaxConnectionsPerChild Al igual que en
GNU/Linux, controla el número de conexiones para
un único proceso, pero por el contrario, en
Windows, no se creará un proceso de reemplazo
instantáneamente (por lo general, estará a 0 a
menos que haya problemas con la memoria)
l
ThreadsPerChild: Número máximo de hijos →
número máximo de conexiones a la vez
(recomendación: 150)
l
¡Cuidado con '' que Apache puede interpretarlo
como carácter de escape
l
Los nombres de archivo son case-insensitive en
Windows, por lo que:
RewriteEngine On
RewriteMap lowercase int:tolower
RewriteCond "%{REQUEST_URI}" "[A-Z]"
RewriteRule "(.*)" "${lowercase:$1}" [R,L]
Configuración Windows
MWS apache
configuración – apache2.conf
# apache2.conf -- Archivo de configuración de apache
# Sección 1: Entorno Global
ServerRoot "/usr/local/apache"
PidFile /var/run/apache.pid
<IfModule !perchild.c>
ScoreBoardFile logs/apache_runtime_status
</IfModule>
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
<IfModule prefork.c>
StartServers 3
MaxClients 8
MinSpareServers 5
MaxSpareServers 10
MaxRequestPerChild 0
</IfModule>
Indica el directorio base del servidor
/usr/local/apache
└ bin
└ conf
└ htdocs
└ manual
└ icons
└ small
└ logs
└ cgi-bin
└ include
MWS apache
configuración – apache2.conf
# apache2.conf -- Archivo de configuración de apache
# Sección 1: Entorno Global
ServerRoot "/usr/local/apache"
PidFile /var/run/apache.pid
<IfModule !perchild.c>
ScoreBoardFile logs/apache_runtime_status
</IfModule>
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
<IfModule prefork.c>
StartServers 3
MaxClients 8
MinSpareServers 5
MaxSpareServers 10
MaxRequestPerChild 0
</IfModule>
Fichero donde se almacena el PID del proceso padre
MWS apache
configuración – apache2.conf
# apache2.conf -- Archivo de configuración de apache
# Sección 1: Entorno Global
ServerRoot "/usr/local/apache"
PidFile /var/run/apache.pid
<IfModule !perchild.c>
ScoreBoardFile logs/apache_runtime_status
</IfModule>
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
<IfModule prefork.c>
StartServers 3
MaxClients 8
MinSpareServers 5
MaxSpareServers 10
MaxRequestPerChild 0
</IfModule>
Fichero para la comunciación
entre el proceso padre y los
hijos
MWS apache
configuración – apache2.conf
# apache2.conf -- Archivo de configuración de apache
# Sección 1: Entorno Global
ServerRoot "/usr/local/apache"
PidFile /var/run/apache.pid
<IfModule !perchild.c>
ScoreBoardFile logs/apache_runtime_status
</IfModule>
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
<IfModule prefork.c>
StartServers 3
MaxClients 8
MinSpareServers 5
MaxSpareServers 10
MaxRequestPerChild 0
</IfModule>
Segundos máximos de espera entre la
recepción de una petición y la respuesta
MWS apache
configuración – apache2.conf
# apache2.conf -- Archivo de configuración de apache
# Sección 1: Entorno Global
ServerRoot "/usr/local/apache"
PidFile /var/run/apache.pid
<IfModule !perchild.c>
ScoreBoardFile logs/apache_runtime_status
</IfModule>
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
<IfModule prefork.c>
StartServers 3
MaxClients 8
MinSpareServers 5
MaxSpareServers 10
MaxRequestPerChild 0
</IfModule>
Permite conexiones persistentes (más de
una solicitud por conexión)
MWS apache
configuración – apache2.conf
# apache2.conf -- Archivo de configuración de apache
# Sección 1: Entorno Global
ServerRoot "/usr/local/apache"
PidFile /var/run/apache.pid
<IfModule !perchild.c>
ScoreBoardFile logs/apache_runtime_status
</IfModule>
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
<IfModule prefork.c>
StartServers 3
MaxClients 8
MinSpareServers 5
MaxSpareServers 10
MaxRequestPerChild 0
</IfModule>
Nº máximo de solicitudes por conexión
persistente
MWS apache
configuración – apache2.conf
# apache2.conf -- Archivo de configuración de apache
# Sección 1: Entorno Global
ServerRoot "/usr/local/apache"
PidFile /var/run/apache.pid
<IfModule !perchild.c>
ScoreBoardFile logs/apache_runtime_status
</IfModule>
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
<IfModule prefork.c>
StartServers 3
MaxClients 8
MinSpareServers 5
MaxSpareServers 10
MaxRequestPerChild 0
</IfModule>
Segundos máximos de espera de una
nueva solicitud en una conexión
persistente
MWS apache
configuración – apache2.conf
# apache2.conf -- Archivo de configuración de apache
# Sección 1: Entorno Global
ServerRoot "/usr/local/apache"
PidFile /var/run/apache.pid
<IfModule !perchild.c>
ScoreBoardFile logs/apache_runtime_status
</IfModule>
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
<IfModule prefork.c>
StartServers 3
MaxClients 8
MinSpareServers 5
MaxSpareServers 10
MaxRequestPerChild 0
</IfModule>
Nº inicial de procesos hijo
MWS apache
configuración – apache2.conf
# apache2.conf -- Archivo de configuración de apache
# Sección 1: Entorno Global
ServerRoot "/usr/local/apache"
PidFile /var/run/apache.pid
<IfModule !perchild.c>
ScoreBoardFile logs/apache_runtime_status
</IfModule>
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
<IfModule prefork.c>
StartServers 3
MaxClients 8
MinSpareServers 5
MaxSpareServers 10
MaxRequestPerChild 0
</IfModule>
Límite de clientes conectados simultáneamente
MWS apache
configuración – apache2.conf
# apache2.conf -- Archivo de configuración de apache
# Sección 1: Entorno Global
ServerRoot "/usr/local/apache"
PidFile /var/run/apache.pid
<IfModule !perchild.c>
ScoreBoardFile logs/apache_runtime_status
</IfModule>
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
<IfModule prefork.c>
StartServers 3
MaxClients 8
MinSpareServers 5
MaxSpareServers 10
MaxRequestPerChild 0
</IfModule>
Nº mínimo y máximo de hilos parados
MWS apache
configuración – apache2.conf
# apache2.conf -- Archivo de configuración de apache
# Sección 1: Entorno Global
ServerRoot "/usr/local/apache"
PidFile /var/run/apache.pid
<IfModule !perchild.c>
ScoreBoardFile logs/apache_runtime_status
</IfModule>
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 15
<IfModule prefork.c>
StartServers 3
MaxClients 8
MinSpareServers 5
MaxSpareServers 10
MaxRequestPerChild 0
</IfModule> Nº máximo de solicitudes que puede servir un
hijo antes de ser ‘asesinado’. Con 0 indicamos
que no se maten nunca.
MWS apache
configuración – apache2.conf
# Sección 2 Configuración del servidor principal
Listen 80.90.56.12 80
User www-data
Group www-data
ServerAdmin yo@micorreo.com
ServerName www.miservidor.com
DocumentRoot /usr/local/apache/htdocs
<Directory />
Options SymLinksIfOwnerMatch
AllowOverride None
</Directory>
<Directory /usr/local/apache/htdocs >
Options Indexes Includes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
UserDir public_html
DirectoryIndex index.html index.htm index.shtml index.cgi
AccessFileName .htaccess
MWS apache
configuración – apache2.conf
# Sección 2 Configuración del servidor principal
Listen 80.90.56.12 80
User www-data
Group www-data
ServerAdmin yo@micorreo.com
ServerName www.miservidor.com
DocumentRoot /usr/local/apache/htdocs
<Directory />
Options SymLinksIfOwnerMatch
AllowOverride None
</Directory>
<Directory /usr/local/apache/htdocs >
Options Indexes Includes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
UserDir public_html
DirectoryIndex index.html index.htm index.shtml index.cgi
AccessFileName .htaccess
IP y puerto de escucha del servidor
Usuario y grupo de los procesos hijo
MWS apache
configuración – apache2.conf
# Sección 2 Configuración del servidor principal
Listen 80.90.56.12 80
User www-data
Group www-data
ServerAdmin yo@micorreo.com
ServerName www.miservidor.com
DocumentRoot /usr/local/apache/htdocs
<Directory />
Options SymLinksIfOwnerMatch
AllowOverride None
</Directory>
<Directory /usr/local/apache/htdocs >
Options Indexes Includes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
UserDir public_html
DirectoryIndex index.html index.htm index.shtml index.cgi
AccessFileName .htaccess
Email del administrador del servidor
Nombre DNS del servidor
MWS apache
configuración – apache2.conf
# Sección 2 Configuración del servidor principal
Listen 80.90.56.12 80
User www-data
Group www-data
ServerAdmin yo@micorreo.com
ServerName www.miservidor.com
DocumentRoot /usr/local/apache/htdocs
<Directory />
Options SymLinksIfOwnerMatch
AllowOverride None
</Directory>
<Directory /usr/local/apache/htdocs >
Options Indexes Includes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
UserDir public_html
DirectoryIndex index.html index.htm index.shtml index.cgi
AccessFileName .htaccess
Directorio raiz de los documentos web
MWS apache
configuración – apache2.conf
# Sección 2 Configuración del servidor principal
Listen 80.90.56.12 80
User www-data
Group www-data
ServerAdmin yo@micorreo.com
ServerName www.miservidor.com
DocumentRoot /usr/local/apache/htdocs
<Directory />
Options SymLinksIfOwnerMatch
AllowOverride None
</Directory>
<Directory /usr/local/apache/htdocs >
Options Indexes Includes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
UserDir public_html
DirectoryIndex index.html index.htm index.shtml index.cgi
AccessFileName .htaccess
Definición de un directorio del servidor
El argumento es un directorio del sistema
de archivos
También se puede usar la directiva
Location que tiene como argumento
una ruta de la URL
MWS apache
configuración – apache2.conf
# Sección 2 Configuración del servidor principal
Listen 80.90.56.12 80
User www-data
Group www-data
ServerAdmin yo@micorreo.com
ServerName www.miservidor.com
DocumentRoot /usr/local/apache/htdocs
<Directory />
Options SymLinksIfOwnerMatch
AllowOverride None
</Directory>
<Directory /usr/local/apache/htdocs >
Options Indexes Includes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
UserDir public_html
DirectoryIndex index.html index.htm index.shtml index.cgi
AccessFileName .htaccess
OPCIONES
ExecCGI: Se permite la ejecución de CGI’s
Indexes: Si se solicita un directorio se muestra
una página con el contenido del mismo
FollowSymLinks: resolver enlaces simbólicos
SymLinksIfOwnerMatch: resolver enlaces
simbólicos si el destino es propiedad del mismo
usuario que el enlace
MWS apache
configuración – apache2.conf
# Sección 2 Configuración del servidor principal
Listen 80.90.56.12 80
User www-data
Group www-data
ServerAdmin yo@micorreo.com
ServerName www.miservidor.com
DocumentRoot /usr/local/apache/htdocs
<Directory />
Options SymLinksIfOwnerMatch
AllowOverride None
</Directory>
<Directory /usr/local/apache/htdocs >
Options Indexes Includes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
UserDir public_html
DirectoryIndex index.html index.htm index.shtml index.cgi
AccessFileName .htaccess
No utilizar los ficheros de acceso
.htaccess
Los ficheros .htaccess se utilizan para
distribuir la configuración por directorios.
Un fichero .htaccess en un directorio
es un fragmento de la configuración para
ese directorio
MWS apache
La configuración distribuida permite fragmentar la
configuración en pequeños archivos de configuración
(.htaccess) alojados en los directorios de la web
configuración distribuida
#...
DocumentRoot /var/www
<Directory /var/www/fotos>
# Configuración del directorio fotos
</Directory>
<Directory /var/www/videos>
# Configuración del directorio videos
</Directory>
#...
/etc/apache2/httpd.conf
#...
DocumentRoot /var/www
<Directory /var/www>
AllowOverride All
</Directory>
#...
/etc/apache2/httpd.conf
/var/www/fotos/.htaccess
# Configuración del directorio fotos
#...
/var/www/videos/.htaccess
# Configuración del directorio videos
#...
Configuración CENTRALIZADA Configuración DISTRIBUIDA
MWS apache
configuración – apache2.conf
# Sección 2 Configuración del servidor principal
Listen 80.90.56.12 80
User www-data
Group www-data
ServerAdmin yo@micorreo.com
ServerName www.miservidor.com
DocumentRoot /usr/local/apache/htdocs
<Directory />
Options SymLinksIfOwnerMatch
AllowOverride None
</Directory>
<Directory /usr/local/apache/htdocs >
Options Indexes Includes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
UserDir public_html
DirectoryIndex index.html index.htm index.shtml index.cgi
AccessFileName .htaccess
Orden de las directivas de acceso
Acceso por defecto
MWS apache
configuración – apache2.conf
# Sección 2 Configuración del servidor principal
Listen 80.90.56.12 80
User www-data
Group www-data
ServerAdmin yo@micorreo.com
ServerName www.miservidor.com
DocumentRoot /usr/local/apache/htdocs
<Directory />
Options SymLinksIfOwnerMatch
AllowOverride None
</Directory>
<Directory /usr/local/apache/htdocs >
Options Indexes Includes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
UserDir public_html
DirectoryIndex index.html index.htm index.shtml index.cgi
AccessFileName .htaccess
Utiliza una carpeta en el HOME de cada
usuario del equipo para acceder como:
http://www.miservidor.com/~usuario
MWS apache
configuración – apache2.conf
# Sección 2 Configuración del servidor principal
Listen 80.90.56.12 80
User www-data
Group www-data
ServerAdmin yo@micorreo.com
ServerName www.miservidor.com
DocumentRoot /usr/local/apache/htdocs
<Directory />
Options SymLinksIfOwnerMatch
AllowOverride None
</Directory>
<Directory /usr/local/apache/htdocs >
Options Indexes Includes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
UserDir public_html
DirectoryIndex index.html index.htm index.shtml index.cgi
AccessFileName .htaccess
Páginas índice cuando se
accede a un directorio
MWS apache
configuración – apache2.conf
# Sección 2 Configuración del servidor principal
Listen 80.90.56.12 80
User www-data
Group www-data
ServerAdmin yo@micorreo.com
ServerName www.miservidor.com
DocumentRoot /usr/local/apache/htdocs
<Directory />
Options SymLinksIfOwnerMatch
AllowOverride None
</Directory>
<Directory /usr/local/apache/htdocs >
Options Indexes Includes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
UserDir public_html
DirectoryIndex index.html index.htm index.shtml index.cgi
AccessFileName .htaccess
Nombre del archivo de configuración del control de acceso
MWS apache
configuración – apache2.conf
TypesConfig /etc/mime.types
DefaultType text/plain
<IfModule mod_mime_magic.c>
MIMEMagicFile conf/magic
</IfModule>
HostnameLookups Off
ErrorLog /var/log/apache/error.log
LogLevel warn
LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"time: %T seg %v"full
# ...
ServerSignature On
Alias /icons/ "/usr/local/apache/icons/"
<Directory "/usr/local/apache/icons">
Options Indexes MultiViews
AllowOverride None
Order allow,deny
Allow from all
</Directory>
ScriptAlias /cgi-bin/ "/usr/local/apache/cgi-bin/"
<Directory /usr/lib/cgi-bin/>
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>
AddLanguage da .dk
AddLanguage nl .nl
# ...
LanguagePriority en da nl et fr de el it ja pl pt pt-br ltz ca es sv
AddDefaultCharset ISO-8859-1
Configuración MIME
MWS apache
configuración – apache2.conf
TypesConfig /etc/mime.types
DefaultType text/plain
<IfModule mod_mime_magic.c>
MIMEMagicFile conf/magic
</IfModule>
HostnameLookups Off
ErrorLog /var/log/apache/error.log
LogLevel warn
LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"time: %T seg %v" full
# ...
ServerSignature On
Alias /icons/ "/usr/local/apache/icons/"
<Directory "/usr/local/apache/icons">
Options Indexes MultiViews
AllowOverride None
Order allow,deny
Allow from all
</Directory>
ScriptAlias /cgi-bin/ "/usr/local/apache/cgi-bin/"
<Directory /usr/lib/cgi-bin/>
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>
AddLanguage da .dk
AddLanguage nl .nl
# ...
LanguagePriority en da nl et fr de el it ja pl pt pt-br ltz ca es sv
AddDefaultCharset ISO-8859-1
Tipo MIME por defecto
Patrones para averiguar el tipo MIME
No usar DNS
MWS apache
configuración – apache2.conf
TypesConfig /etc/mime.types
DefaultType text/plain
<IfModule mod_mime_magic.c>
MIMEMagicFile conf/magic
</IfModule>
HostnameLookups Off
ErrorLog /var/log/apache/error.log
LogLevel warn
LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"time: %T seg %v" full
# ...
ServerSignature On
Alias /icons/ "/usr/local/apache/icons/"
<Directory "/usr/local/apache/icons">
Options Indexes MultiViews
AllowOverride None
Order allow,deny
Allow from all
</Directory>
ScriptAlias /cgi-bin/ "/usr/local/apache/cgi-bin/"
<Directory /usr/lib/cgi-bin/>
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>
AddLanguage da .dk
AddLanguage nl .nl
# ...
LanguagePriority en da nl et fr de el it ja pl pt pt-br ltz ca es sv
AddDefaultCharset ISO-8859-1
Configuración del log
MWS apache
configuración – apache2.conf
TypesConfig /etc/mime.types
DefaultType text/plain
<IfModule mod_mime_magic.c>
MIMEMagicFile conf/magic
</IfModule>
HostnameLookups Off
ErrorLog /var/log/apache/error.log
LogLevel warn
LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i" %T %v" full
# ...
ServerSignature On
Alias /icons/ "/usr/local/apache/icons/"
<Directory "/usr/local/apache/icons">
Options Indexes MultiViews
AllowOverride None
Order allow,deny
Allow from all
</Directory>
ScriptAlias /cgi-bin/ "/usr/local/apache/cgi-bin/"
<Directory /usr/lib/cgi-bin/>
AllowOverride None
Options ExecCGI
Order allow,deny
Allow from all
</Directory>
AddLanguage da .dk
AddLanguage nl .nl
# ...
LanguagePriority en da nl et fr de el it ja pl pt pt-br ltz ca es sv
AddDefaultCharset ISO-8859-1
Muestra un pie de pagina con información sobre el
servidor en las páginas de error
Directorio de Iconos
Directorio de CGI’s
Lenguajes
Juego de caracteres por defecto
MWS apache
Un alias se utiliza para mapear una URL a
una localización concreta del sistema de
archivos
Rompe la secuencia jerárquica normal
alias
Espacio de URLs
http://????/
└ documentos
└ imagenes
└ fotos
└ videos
└ recursos
Espacio de archivos
/var/www
└ documentos
└ imagenes
└ fotos
└ videos
/media/disco2
└ recursos
DocumentRoot /var/www
Alias /recursos /media/disco2/recursos
MWS apache
Crear directorios del servidor web que
requieren autenticación para su acceso
autenticación
Cliente
(navegador)
Servidor
(httpd)
GET http://www.misitio.com/protegido/a.htm
Error 401: “Necesita autorización”Acceso restringido
Usuario:
Contraseña:
pepe
********
GET http://www.misitio.com/protegido/a.htm
Incluye el usuario y la contraseña en la cabecera
Contenido de a.htm
MWS apache
Configurar en apache2.conf la zona
restringida
Crear el archivo .members de
usuarios/contraseñas
autenticación básica
<Location "/protegido/">
AuthName "Acceso restringido“
AuthType Basic
AuthUserFile /usr/local/apache/secrets/.members
Require valid-user
</Location>
# htpasswd –c .members pepe
New password: ****
Re-type new password: ****
Adding password for user pepe
# htpasswd .members juan
New password: ****
Re-type new password: ****
Adding password for user pepe
# cat .members
pepe:b8p3dfj093478
juan:03l43f89sfl43
#
MWS apache
Tener diferentes sitios web en un único
equipo servidor
Ahorro en infraestructuras
Posibilidad de configuración compartida
Administración centralizada
Tipos:
 Basada en nombres
 Basada en IP
 Varios servidores principales
servidores virtuales
MWS apache
Existe un servidor principal
Existen diferentes nombres DNS que apuntan
a la IP del servidor
servidor virtual basado en nombres
# Definición del servidor principal
# ...
ServerName www.miservidor.com
DocumentRoot /www/miservidor/htdocs
# ...
<VirtualHost 192.168.1.20>
ServerName www.miservidor2.com
DocumentRoot /www/miservidor2/htdocs
# ...
</VirtualHost>
<VirtualHost 192.168.1.20>
ServerName www.miservidor3.com
DocumentRoot /www/miservidor3/htdocs
# ...
</VirtualHost>
MWS apache
Existe un servidor principal
Existen diferentes IP’s en el servidor
servidor virtual basado en ip
# Definición del servidor principal
# ...
ServerName www.miservidor.com
DocumentRoot /www/miservidor/htdocs
# ...
<VirtualHost 192.168.1.21>
ServerName www.miservidor2.com
DocumentRoot /www/miservidor2/htdocs
# ...
</VirtualHost>
<VirtualHost 192.168.1.22>
ServerName www.miservidor3.com
DocumentRoot /www/miservidor3/htdocs
# ...
</VirtualHost>
MWS
Reescrituras URL
•Transformar una solicitud en otra
•Tipos:
l
Internas: el cliente no lo nota
l
Reescritura: el cliente cambia la
URL
apache
MWS
cómo
apache
MWS
l
Se necesita activar mod_rewrite (instalar el plugin + RewriteEngine on en
configuración)
l
Utiliza un conjunto de reglas computas por: patrón a buscar, cadena de
sustitución y acción a realizar.
l
Se pueden encadenar varias reglas
l
Sintaxis:
l
RewriteRule Patron Sustitucion [flags]
l
Patron: expresión regular a buscar dentro de la URL (entre host y QueryString)
l
Ejemplo:
l
RewriteRule ^/$ /inicio/ [L,R]
apache
Reescrituras URL
MWS
comodines
apache
MWS
l
Puede ser:
l
Relativa (sin el nombre del servidor)
l
Completa
l
Puede utilizar $1...$9 para indicar los fragmentos encontrados en el patrón
l
Ejemplo:
l
RewriteRule ^/productos/(.*)/.*)$ /producto.php?categoria=$1&id=$2 [L]
apache
Cadena de sustitución
MWS apache
flags
https://httpd.apache.org/docs/current/rewrite/flags.htm
l
MWS
Condiciones extra
l
RewriteCond
l
Tantas como necesitemos
l
Preceden a la regla
l
Deben cumplirse todas
l
Sintaxis:
l
RewriteCond cadena condicion [flags]
l
Flags: se pueden combinar varios separados con ',':
l
NC | nocase → Ignorar mayúsculas/minúsculas
l
OR | ornext → Realiza un 'o' lógico con la condición siguiente
l
Ejemplo:
l
RewriteCond %{HTTP_USER_AGENT} ^Mozilla
l
RewriteRule ^/$ /homepage.html [L]
l
RewriteCond %{HTTP_USER_AGENT} ^Lynx
l
RewriteRule ^/$ /homepage.min.html [L]
l
RewriteRule ^/$ /homepage.std.html [L]
apache
MWS
Condiciones extra
apache
MWS apache
https://httpd.apache.org/docs/2.4/caching.html
Mejora del rendimiento:
l
Three-state RFC2616 HTTP caching:
mod_cache, mod_cache_disk. Los estados
son: Fresh (más reciente que), Stale (más
viejo que) y Non Existent
l
Two-state key/value shared object caching:
https://httpd.apache.org/docs/2.4/socache.h
tml
l
Specialized file caching: mod_file_cache
Precarga de ficheros en memoria en el
arranque. Puede ser útil para ficheros muy
accedidos.
caché
MWS apache
Ejemplo:
caché
# Caching to Disk
CacheRoot "/var/cache/apache/"
CacheEnable disk /
CacheDirLevels 2
CacheDirLength 1
#Caching to memcached (http://memcached.org/)
#https://httpd.apache.org/docs/2.4/mod/mod_socache_memcache.html
CacheEnable socache /
CacheSocache memcache:memcd.example.com:11211,mem2.example.com:11212
# Caching files (¡cuidado con el número máximo de ficheros
# abiertos establecido para el SO!) vs SSD vs caché del SO
CacheFile /usr/local/apache2/htdocs/index.html
MWS apache
Necesitamos el certificado que identifique al
servidor
mod_ssl (LoadModule ssl_module
modules/mod_ssl.so)
SSL
# Definición del servidor principal
# ...
Listen 443
# ...
<VirtualHost *:443>
ServerName www.example.es
DocumentRoot /www/example/htdocs
SSLEngine On
SSLCertificateFile “path_to_cert”
SSLCertificateKeyFile “path_to_key”
# ...
</VirtualHost>
MWS apache
Tener instalado openSSL
Crear llave:
Crear CSR (Certificate Signing Request)
Generar el certificado (esto es lo que haría
una autoridad certificadora) Así para
autofirmado:
OpenSSL y certificados
openssl req -new -key server.key -out server.csr
openssl genrsa -out server.key 1024
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
MWS apache
Eliminar la versión de Apache y SO
Deshabilita el listado de directorio
Hardening (I)
ServerTokens ProductOnly
ServerSignature Off #footer
<Directory /opt/apache/htdocs>
Options ­Indexes|None
Order allow,deny
Allow from all
</Directory> 
MWS apache
Para impedir obtener información de número
de inodo, límite en MIME y procesos hijos con
ETag
Deshabilita .htaccess
Limitar métodos HTTP:
Hardening (II)
FileETag None
<Directory /opt/apache/htdocs>
Options ­Indexes
AllowOverride None
</Directory> 
<LimitExcept GET POST PUT DELETE>
deny from all #si ponemos nombres, DNS
</LimitExcept>
 TraceEnable off #Solo TRACE
MWS apache
Mitigar Cross usando HttpOnly and Secure
flag en cookie minimizabdo robo y
manipulación
Clickjacking Attack (frames)
l
SAMEORIGIN: Solo desde el mismo sitio
l
DENY: Ninguno
l
ALLOW-FROM uri: Solo desde URI
especificada
Deshabilitar SSI
Hardening (III)
Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure
Header always append X­Frame­Options SAMEORIGIN
#En web compartido (.htaccess):
Header append X­FRAME­OPTIONS "SAMEORIGIN"
<Directory /opt/apache/htdocs>
Options –Indexes ­Includes
Order allow,deny
Allow from all
</Directory>
MWS apache
X-XSS Protection (incluso si el usuario lo
deshabilita en el navegador)
Solo HTTP/1.1
Deshabilitar SSL 1,..., solo TLS 1.0
Tipo MIME y contenido debe ser el mismo
Hardening (IV)
Header set X-XSS-Protection “1; mode=block”
RewriteEngine On
RewriteCond %{THE_REQUEST} !HTTP/1.1$
RewriteRule .* ­ [F]
 SSLProtocol –ALL +TLSv1 +TLSv1.1 +TLSv1.2
<IfModule mod_headers.c>
# Disable content sniffing, since it's an attack vector.
Header always set X-Content-Type-Options nosniff
</IfModule>
MWS apache
Mod Security
(https://www.howtoforge.com/apache_mod_
security)
Deshabilita los módulos no utilizados
Habilita registros:
https://httpd.apache.org/docs/2.4/mod/mod
_log_config.html
Más en https://geekflare.com/apache-web-
server-hardening-security/#2-Information-
Leakage
Hardening (IV)
LogFormat "%h %l %u %t "%{sessionID}C" "%r" %>s %b %T" common
MWS apache
PHP /etc/php/apache2/php.ini
l
expose_php = Off #no indicar versión
l
display_errors = Off
l
open_basedir = ubicación # impedir path
Traversal
l
disable_functions = phpinfo, system, excec,
shell_exec, ini_set, Dl, eval
l
allow_url_fopen= Off
l
allow_url_include = Off
Suhosin: componente para proteger servidores con
PHP (php5-suhosin)
Hardening (V)
MWS apache
HostnameLookups y DNS
FollowSymLinks and SymLinksIfOwnerMatch
(For highest performance, and no symlink
protection, set FollowSymLinks everywhere,
and never set SymLinksIfOwnerMatch)
Caché
MPM
Cluster
CDN
Cloud
…
rendimiento
MWS apache
add
The response header is added to the existing set of headers, even if this header already exists. This can result in two (or more)
headers having the same name. This can lead to unforeseen consequences, and in general set, append or merge should be used
instead.
append
The response header is appended to any existing header of the same name. When a new value is merged onto an existing header it
is separated from the existing header with a comma. This is the HTTP standard way of giving a header multiple values.
echo
Request headers with this name are echoed back in the response headers. header may be a regular expression. value must be
omitted.
edit
edit*
If this response header exists, its value is transformed according to a regular expression search-and-replace. The value argument is
a regular expression, and the replacement is a replacement string, which may contain backreferences or format specifiers. The edit
form will match and replace exactly once in a header value, whereas the edit* form will replace every instance of the search pattern if
it appears more than once.
merge
The response header is appended to any existing header of the same name, unless the value to be appended already appears in the
header's comma-delimited list of values. When a new value is merged onto an existing header it is separated from the existing header
with a comma. This is the HTTP standard way of giving a header multiple values. Values are compared in a case sensitive manner, and
after all format specifiers have been processed. Values in double quotes are considered different from otherwise identical unquoted
values.
set
The response header is set, replacing any previous header with this name. The value may be a format string.
setifempty
The request header is set, but only if there is no previous header with this name.
The Content-Type header is a special use case since there might be the chance that its value have been determined but the header is
not part of the response when setifempty is evaluated. It is safer to use set for this use case like in the following example:
Header set Content-Type "text/plain" "expr=-z %{CONTENT_TYPE}"
unset
The response header of this name is removed, if it exists. If there are multiple headers of the same name, all will be removed. value
must be omitted.
header
MWS apache
https://httpd.apache.org/docs/
current/
Hardening de servidores
GNU/Linux, OxWord, Carlos
Álvarez y Pablo González
Referencias

Contenu connexe

Tendances

Tendances (19)

Node.js - Eventos para Todos
Node.js - Eventos para TodosNode.js - Eventos para Todos
Node.js - Eventos para Todos
 
Servidores web de altas prestaciones. Tema 5
Servidores web de altas prestaciones. Tema 5Servidores web de altas prestaciones. Tema 5
Servidores web de altas prestaciones. Tema 5
 
Filtrado der contenido web con GNU/Linux y Squid
Filtrado der contenido web con GNU/Linux y SquidFiltrado der contenido web con GNU/Linux y Squid
Filtrado der contenido web con GNU/Linux y Squid
 
Varnish http cache
Varnish http cacheVarnish http cache
Varnish http cache
 
1212
12121212
1212
 
Manual de squid creado por juanextk
Manual de squid creado por juanextkManual de squid creado por juanextk
Manual de squid creado por juanextk
 
Rendimiento extremo en php
Rendimiento extremo en phpRendimiento extremo en php
Rendimiento extremo en php
 
Nodejs
NodejsNodejs
Nodejs
 
Tools for High Availability
Tools for High AvailabilityTools for High Availability
Tools for High Availability
 
Proxy
ProxyProxy
Proxy
 
Tuning Lamp
Tuning LampTuning Lamp
Tuning Lamp
 
Servidores web de altas prestaciones. Tema 1
Servidores web de altas prestaciones. Tema 1Servidores web de altas prestaciones. Tema 1
Servidores web de altas prestaciones. Tema 1
 
Curso Squid avanzado
Curso Squid avanzadoCurso Squid avanzado
Curso Squid avanzado
 
Squid
Squid Squid
Squid
 
Alta Disponibilidad con SQL Server 2012
Alta Disponibilidad con SQL Server 2012Alta Disponibilidad con SQL Server 2012
Alta Disponibilidad con SQL Server 2012
 
AlwaysOn en SQL Server 2016
AlwaysOn en SQL Server 2016AlwaysOn en SQL Server 2016
AlwaysOn en SQL Server 2016
 
servidor proxy squid
servidor proxy squidservidor proxy squid
servidor proxy squid
 
Cluster sql server
Cluster sql serverCluster sql server
Cluster sql server
 
Semana 7 Despliegue a producción
Semana 7   Despliegue a producciónSemana 7   Despliegue a producción
Semana 7 Despliegue a producción
 

Similaire à Administración Apache

Apache2 dia1
Apache2 dia1Apache2 dia1
Apache2 dia1lyonel_cc
 
Sacándole el jugo a apache
Sacándole el jugo a apacheSacándole el jugo a apache
Sacándole el jugo a apacheJavier Aroche
 
Web Services buscador de localizaciones de IP’s (Presentación)
Web Services buscador de localizaciones de IP’s (Presentación)Web Services buscador de localizaciones de IP’s (Presentación)
Web Services buscador de localizaciones de IP’s (Presentación)Pablo Pellegrinet
 
Apache, getting the best version
Apache, getting the best versionApache, getting the best version
Apache, getting the best versionIvan Ortega
 
Introducción a Servidor HTTP Apache
Introducción a Servidor HTTP ApacheIntroducción a Servidor HTTP Apache
Introducción a Servidor HTTP ApacheIker Canarias
 
Apache.http ftp-smtp
Apache.http ftp-smtpApache.http ftp-smtp
Apache.http ftp-smtpgh02
 
Interchange How-To for Red Hat Linux ES4
Interchange How-To for Red Hat Linux ES4Interchange How-To for Red Hat Linux ES4
Interchange How-To for Red Hat Linux ES4David Ramirez
 
Interchange CMS - e-commerce
Interchange CMS - e-commerceInterchange CMS - e-commerce
Interchange CMS - e-commerceDavid Ramirez
 
Servicio apache gnu linux-centos ::: http://leymebamba.com
Servicio apache  gnu linux-centos  ::: http://leymebamba.comServicio apache  gnu linux-centos  ::: http://leymebamba.com
Servicio apache gnu linux-centos ::: http://leymebamba.com{|::::::. ELDAVAN .:::::::|}
 
Web Performance para Magento
Web Performance para MagentoWeb Performance para Magento
Web Performance para MagentoJordi Rosell
 
Sistemas operativos unidad 2
Sistemas operativos unidad 2Sistemas operativos unidad 2
Sistemas operativos unidad 2Luis Cigarroa
 

Similaire à Administración Apache (20)

Curso de php
Curso de phpCurso de php
Curso de php
 
Apache2 dia1
Apache2 dia1Apache2 dia1
Apache2 dia1
 
Sacándole el jugo a apache
Sacándole el jugo a apacheSacándole el jugo a apache
Sacándole el jugo a apache
 
Web Services buscador de localizaciones de IP’s (Presentación)
Web Services buscador de localizaciones de IP’s (Presentación)Web Services buscador de localizaciones de IP’s (Presentación)
Web Services buscador de localizaciones de IP’s (Presentación)
 
Apache, getting the best version
Apache, getting the best versionApache, getting the best version
Apache, getting the best version
 
Introducción a Servidor HTTP Apache
Introducción a Servidor HTTP ApacheIntroducción a Servidor HTTP Apache
Introducción a Servidor HTTP Apache
 
Protocolo http
Protocolo httpProtocolo http
Protocolo http
 
Servidor web Apache
Servidor web ApacheServidor web Apache
Servidor web Apache
 
Apache Server vs Nginx
Apache Server vs NginxApache Server vs Nginx
Apache Server vs Nginx
 
Entorno PHP
Entorno PHPEntorno PHP
Entorno PHP
 
Apache.http ftp-smtp
Apache.http ftp-smtpApache.http ftp-smtp
Apache.http ftp-smtp
 
Interchange How-To for Red Hat Linux ES4
Interchange How-To for Red Hat Linux ES4Interchange How-To for Red Hat Linux ES4
Interchange How-To for Red Hat Linux ES4
 
Interchange CMS - e-commerce
Interchange CMS - e-commerceInterchange CMS - e-commerce
Interchange CMS - e-commerce
 
Mrtg ubuntu
Mrtg ubuntuMrtg ubuntu
Mrtg ubuntu
 
Servidor web
Servidor webServidor web
Servidor web
 
Servicio apache gnu linux-centos ::: http://leymebamba.com
Servicio apache  gnu linux-centos  ::: http://leymebamba.comServicio apache  gnu linux-centos  ::: http://leymebamba.com
Servicio apache gnu linux-centos ::: http://leymebamba.com
 
200310 - Apache Web Server
200310 - Apache Web Server200310 - Apache Web Server
200310 - Apache Web Server
 
Web Performance para Magento
Web Performance para MagentoWeb Performance para Magento
Web Performance para Magento
 
Monit optim iis6_2
Monit optim iis6_2Monit optim iis6_2
Monit optim iis6_2
 
Sistemas operativos unidad 2
Sistemas operativos unidad 2Sistemas operativos unidad 2
Sistemas operativos unidad 2
 

Plus de Juan Antonio Gil Martínez-Abarca (11)

03 asor gestión de usuarios y ldap
03 asor   gestión de usuarios y ldap03 asor   gestión de usuarios y ldap
03 asor gestión de usuarios y ldap
 
06 airc firewalls
06 airc   firewalls06 airc   firewalls
06 airc firewalls
 
08 airc hackingbuscadores - mod
08 airc   hackingbuscadores - mod08 airc   hackingbuscadores - mod
08 airc hackingbuscadores - mod
 
Aisi 1415 06 correo
Aisi 1415 06 correoAisi 1415 06 correo
Aisi 1415 06 correo
 
05 airc dns
05 airc   dns05 airc   dns
05 airc dns
 
04 girc servicio dhcp
04 girc   servicio dhcp 04 girc   servicio dhcp
04 girc servicio dhcp
 
Snortpracticas 2006
Snortpracticas 2006Snortpracticas 2006
Snortpracticas 2006
 
Snort 2006
Snort 2006Snort 2006
Snort 2006
 
Tripwire 2006
Tripwire 2006Tripwire 2006
Tripwire 2006
 
Honeypotsprácticas2006
Honeypotsprácticas2006Honeypotsprácticas2006
Honeypotsprácticas2006
 
Honeypots2006 2007
Honeypots2006 2007Honeypots2006 2007
Honeypots2006 2007
 

Dernier

GRUPO 10 SOFTWARE DE EL CAMPO DE LA SAULD
GRUPO 10 SOFTWARE DE EL CAMPO DE LA SAULDGRUPO 10 SOFTWARE DE EL CAMPO DE LA SAULD
GRUPO 10 SOFTWARE DE EL CAMPO DE LA SAULDLeslie Villar
 
rodriguez_DelAngel_MariaGPE_M1S3AL6.pptx
rodriguez_DelAngel_MariaGPE_M1S3AL6.pptxrodriguez_DelAngel_MariaGPE_M1S3AL6.pptx
rodriguez_DelAngel_MariaGPE_M1S3AL6.pptxssuser61dda7
 
FLUIDEZ-Teatro-Leido-4to-Grado-El-leon-y-el-raton- (1).pdf
FLUIDEZ-Teatro-Leido-4to-Grado-El-leon-y-el-raton- (1).pdfFLUIDEZ-Teatro-Leido-4to-Grado-El-leon-y-el-raton- (1).pdf
FLUIDEZ-Teatro-Leido-4to-Grado-El-leon-y-el-raton- (1).pdfYuriFuentesMartinez2
 
El uso de las tic en la vida continúa , ambiente positivo y negativo.
El uso de las tic  en la vida continúa , ambiente positivo y negativo.El uso de las tic  en la vida continúa , ambiente positivo y negativo.
El uso de las tic en la vida continúa , ambiente positivo y negativo.ayalayenifer617
 
actividad.06_crea_un_recurso_multimedia_M01_S03_M01.ppsx
actividad.06_crea_un_recurso_multimedia_M01_S03_M01.ppsxactividad.06_crea_un_recurso_multimedia_M01_S03_M01.ppsx
actividad.06_crea_un_recurso_multimedia_M01_S03_M01.ppsx241532171
 
libro de Ciencias Sociales_6to grado.pdf
libro de Ciencias Sociales_6to grado.pdflibro de Ciencias Sociales_6to grado.pdf
libro de Ciencias Sociales_6to grado.pdfFAUSTODANILOCRUZCAST
 
que es Planimetría definición importancia en topografia.pptx
que es Planimetría definición importancia en topografia.pptxque es Planimetría definición importancia en topografia.pptx
que es Planimetría definición importancia en topografia.pptxmrzreyes12
 
ChatGPT Inteligencia artificial, funciones, limitaciones y ventajas.
ChatGPT Inteligencia artificial, funciones, limitaciones y ventajas.ChatGPT Inteligencia artificial, funciones, limitaciones y ventajas.
ChatGPT Inteligencia artificial, funciones, limitaciones y ventajas.Aldo Fernandez
 
Fisica General.pdf ESCUELA D QUIMICA E INGENIERIA
Fisica General.pdf ESCUELA D QUIMICA E INGENIERIAFisica General.pdf ESCUELA D QUIMICA E INGENIERIA
Fisica General.pdf ESCUELA D QUIMICA E INGENIERIAcoloncopias5
 
GRUPO 5 Software en el campo de la salud.pptx
GRUPO 5 Software en el campo de la salud.pptxGRUPO 5 Software en el campo de la salud.pptx
GRUPO 5 Software en el campo de la salud.pptxNicolas Villarroel
 
Practica guiada Menu_ tecnología (Tic's)
Practica guiada Menu_ tecnología (Tic's)Practica guiada Menu_ tecnología (Tic's)
Practica guiada Menu_ tecnología (Tic's)BrianaFrancisco
 
2º SOY LECTOR PART 2- MD EDUCATIVO (6).pdf
2º SOY LECTOR PART 2- MD  EDUCATIVO (6).pdf2º SOY LECTOR PART 2- MD  EDUCATIVO (6).pdf
2º SOY LECTOR PART 2- MD EDUCATIVO (6).pdfFernandaHernandez312615
 
COMPETENCIAS CIUDADANASadadadadadadada .pdf
COMPETENCIAS CIUDADANASadadadadadadada .pdfCOMPETENCIAS CIUDADANASadadadadadadada .pdf
COMPETENCIAS CIUDADANASadadadadadadada .pdfOscarBlas6
 
Tema 1 - Fundamentos de gestión contable.pptx
Tema 1 - Fundamentos de gestión contable.pptxTema 1 - Fundamentos de gestión contable.pptx
Tema 1 - Fundamentos de gestión contable.pptxchinojosa17
 
CamposGarcia_MariaMagdalena_M1S3AI6.pptx
CamposGarcia_MariaMagdalena_M1S3AI6.pptxCamposGarcia_MariaMagdalena_M1S3AI6.pptx
CamposGarcia_MariaMagdalena_M1S3AI6.pptx241518192
 
Producto académico 03 - Habilidades Comunicativas.pptx
Producto académico 03 - Habilidades Comunicativas.pptxProducto académico 03 - Habilidades Comunicativas.pptx
Producto académico 03 - Habilidades Comunicativas.pptx46828205
 

Dernier (16)

GRUPO 10 SOFTWARE DE EL CAMPO DE LA SAULD
GRUPO 10 SOFTWARE DE EL CAMPO DE LA SAULDGRUPO 10 SOFTWARE DE EL CAMPO DE LA SAULD
GRUPO 10 SOFTWARE DE EL CAMPO DE LA SAULD
 
rodriguez_DelAngel_MariaGPE_M1S3AL6.pptx
rodriguez_DelAngel_MariaGPE_M1S3AL6.pptxrodriguez_DelAngel_MariaGPE_M1S3AL6.pptx
rodriguez_DelAngel_MariaGPE_M1S3AL6.pptx
 
FLUIDEZ-Teatro-Leido-4to-Grado-El-leon-y-el-raton- (1).pdf
FLUIDEZ-Teatro-Leido-4to-Grado-El-leon-y-el-raton- (1).pdfFLUIDEZ-Teatro-Leido-4to-Grado-El-leon-y-el-raton- (1).pdf
FLUIDEZ-Teatro-Leido-4to-Grado-El-leon-y-el-raton- (1).pdf
 
El uso de las tic en la vida continúa , ambiente positivo y negativo.
El uso de las tic  en la vida continúa , ambiente positivo y negativo.El uso de las tic  en la vida continúa , ambiente positivo y negativo.
El uso de las tic en la vida continúa , ambiente positivo y negativo.
 
actividad.06_crea_un_recurso_multimedia_M01_S03_M01.ppsx
actividad.06_crea_un_recurso_multimedia_M01_S03_M01.ppsxactividad.06_crea_un_recurso_multimedia_M01_S03_M01.ppsx
actividad.06_crea_un_recurso_multimedia_M01_S03_M01.ppsx
 
libro de Ciencias Sociales_6to grado.pdf
libro de Ciencias Sociales_6to grado.pdflibro de Ciencias Sociales_6to grado.pdf
libro de Ciencias Sociales_6to grado.pdf
 
que es Planimetría definición importancia en topografia.pptx
que es Planimetría definición importancia en topografia.pptxque es Planimetría definición importancia en topografia.pptx
que es Planimetría definición importancia en topografia.pptx
 
ChatGPT Inteligencia artificial, funciones, limitaciones y ventajas.
ChatGPT Inteligencia artificial, funciones, limitaciones y ventajas.ChatGPT Inteligencia artificial, funciones, limitaciones y ventajas.
ChatGPT Inteligencia artificial, funciones, limitaciones y ventajas.
 
Fisica General.pdf ESCUELA D QUIMICA E INGENIERIA
Fisica General.pdf ESCUELA D QUIMICA E INGENIERIAFisica General.pdf ESCUELA D QUIMICA E INGENIERIA
Fisica General.pdf ESCUELA D QUIMICA E INGENIERIA
 
GRUPO 5 Software en el campo de la salud.pptx
GRUPO 5 Software en el campo de la salud.pptxGRUPO 5 Software en el campo de la salud.pptx
GRUPO 5 Software en el campo de la salud.pptx
 
Practica guiada Menu_ tecnología (Tic's)
Practica guiada Menu_ tecnología (Tic's)Practica guiada Menu_ tecnología (Tic's)
Practica guiada Menu_ tecnología (Tic's)
 
2º SOY LECTOR PART 2- MD EDUCATIVO (6).pdf
2º SOY LECTOR PART 2- MD  EDUCATIVO (6).pdf2º SOY LECTOR PART 2- MD  EDUCATIVO (6).pdf
2º SOY LECTOR PART 2- MD EDUCATIVO (6).pdf
 
COMPETENCIAS CIUDADANASadadadadadadada .pdf
COMPETENCIAS CIUDADANASadadadadadadada .pdfCOMPETENCIAS CIUDADANASadadadadadadada .pdf
COMPETENCIAS CIUDADANASadadadadadadada .pdf
 
Tema 1 - Fundamentos de gestión contable.pptx
Tema 1 - Fundamentos de gestión contable.pptxTema 1 - Fundamentos de gestión contable.pptx
Tema 1 - Fundamentos de gestión contable.pptx
 
CamposGarcia_MariaMagdalena_M1S3AI6.pptx
CamposGarcia_MariaMagdalena_M1S3AI6.pptxCamposGarcia_MariaMagdalena_M1S3AI6.pptx
CamposGarcia_MariaMagdalena_M1S3AI6.pptx
 
Producto académico 03 - Habilidades Comunicativas.pptx
Producto académico 03 - Habilidades Comunicativas.pptxProducto académico 03 - Habilidades Comunicativas.pptx
Producto académico 03 - Habilidades Comunicativas.pptx
 

Administración Apache

  • 3. MWS apache Servidor web altamente extendido Proyecto de código abierto Creado por Apache Software Foundation  Versión 2.4 introducción
  • 4. MWS apache Altamente configurable  Diseño modular  Ampliación Multiplataforma  Linux  Unix  Windows (desde versión 1.3)  Amiga OS 3x  OS/2 Soporta HTTP 1.1 (solicitudes múltiples) Soporta HTTP 2.0 (mod_http2 para >=2.4.17) características Soporta CGI y Fast CGI Soporta Host Virtuales Autenticación HTTP Perl Integrado Soporta PHP Con Tomcat -> servlets y JSP Puede actuar como servidor proxy SSI (Server Side Includes) SSL
  • 5. MWS apache Info:https://httpd.apache.org/docs/2.4/mpm .html Posibilidad de configurar la distribución de los procesos (versión 2 de apache) Establecen la manera de atender las peticiones de los clientes Optimizan el servidor en función del uso que se le quiera dar Tipos:  Prefork (para sitios que requieran estabilidad)  Worked (escalabilidad)  event  Winnt (para sistema windows. Muy eficiente) Módulos de MultiProceso
  • 6. MWS apache Igual que en la versión 1 de apache. El proceso principal crea un conjunto de hijos que sirven las peticiones El número de hijos está establecido entre un mínimo y un máximo Cada hijo ejecuta un único hilo (una petición por hijo simultáneamente) mmp prefork Cliente Proceso hijo (www-data) Proceso hijo (www-data) Proceso hijo (www-data) Poceso princ. (httpd) root Servidor 80
  • 7. MWS apache Es el que más CPU y RAM consume por proceso - petición MaxClients/MaxRequestWorkers deben ser lo suficientemente: l grande para las peticiones simultáneas que esperes recibir l Pequeño para la RAM y procesos del servidor donde se ejecuta MaxClients=(RAM – size_all_other_processes)/ (max_size_apache_process) MaxClients=(RAM-Shared_RAM_per_Child)/ (Max_Process_Size-Shared_RAM_per_Child) mmp prefork
  • 8. MWS apache Directivas a tener en cuenta para regular cómo el proceso padre crea procesos hijos para atender las peticiones entrantes: l StarServers indica el número de procesos que se lanzarán en el arranque l MinSpareServers: número procesos mínimo desocupados l MaxSpareServers: número procesos máximo desocupados l MaxRequestWorkers: debe ser lo suficientemente grande para tratar las solicitudes que esperamos recibir y lo suficientemente pequeño para los asegurar que tenemos memoria RAM para todos los procesos (solo si esperamos más de 256 peticiones simultáneas, podríamos necesitar incrementarlo) l MaxConnectionsPerChild: limita el número de conexiones que un proceso puede atender durante su existencia. Superado, muere y se lanza otro. Si es 0, ilimitado. ¿Ventajas? l User/Group (para procesos hijos) l Comportamiento: si hijos idle < MinSpareServers, padre crea otros, 1, 2, 4 esperando 1” y no más de 32, si hijos idle > MaxSpareServers, padre mata exceso de hijos mpm prefork
  • 9. MWS apache Los procesos hijos pueden tener más de un hilo (TheadsPerChild) Cada hilo dentro de un proceso atiende una petición Permite atender gran número de peticiones con menor consumo de recursos que con prefork y conservando parte de la estabilidad que proporciona éste Los procesos hijos se crean o destruyen para que el número de hilos libres se mantengan entre un mínimo (MinSpareThreads) y un máximo (MaxSpareThreads) Número máximo de clientes: MaxRequestWorkers mmp worked Cliente Proceso hijo www-data Proceso hijo www-data Proceso hijo www-data Poceso princ. (httpd) root StartServers=3 threadsperchild=3 Servidor 80
  • 10. MWS apache Más directivas a tener en cuenta para regular cómo el proceso padre crea procesos hijos para atender las peticiones entrantes: l Las vistas para prefork más l ServerLimit número de procesos hijos l ThreadLimit número de hilos en el servidor l MaxConnectionsPerChild controla cómo se recicla los procesos l User/group mpm worker
  • 11. MWS apache ¿Número máximo de clientes que pueden ser atendidos simultáneamente? l Valor de MaxRequestWorkers ¿Número máximo de procesos hijos activos? l MaxRequestWorkers / ThreadsPerChild MinSpareThreads<#hijos<MaxSpareThreads ServerLimit>=MaxRequestWorkers/ThreadsP erChild ThreadLimit >=ThreadsPerChild mpm worker
  • 12. MWS apache https://httpd.apache.org/docs/2.4/mod/event.html Está basado en el mpm worker con sockets no bloqueantes para manejar varias conexiones por un proceso/hilo (las indicadas por AsyncRequestWorkerFactor) Tiene un hilo por proceso dedicado a: l Escucha del socket l Conexiones KeepAlive l Sockets en los que el protocolo ya ha hecho su trabajo l Y aquellos en los que solo queda mandar los datos al cliente mpm event Cliente Proceso hijo Proceso hijo Proceso hijo Poceso princ. (httpd) Servidor 80 uid=apache1 uid=apache2 uid=apache3
  • 13. MWS apache Las directivas relacionadas son las mismas que mpm worker más AsyncRequestWorkerFactor El número total de conexiones concurrentes para un proceso/hilo puede manejar está regulado por AsyncRequestWorkerFactor: Un proceso solo aceptará nuevas conexiones si en número actual de estas es menor de: ThreadsPerChild + (AsyncRequestWorkerFactor * number of idle workers) Podemos calcular una estimación del número máximo de conexiones para todos los procesos con: (ThreadsPerChild + (AsyncRequestWorkerFactor * number of idle workers)) * ServerLimit Ejemplo SI ThreadsPerChild = 10, ServerLimit = 4, AsyncRequestWorkerFactor = 2, MaxRequestWorkers = 40, idle_workers = 4 max_connections = (ThreadsPerChild + (AsyncRequestWorkerFactor * idle_workers)) * ServerLimit = (10 + (2 * 4)) * 4 = 72 Si todos los hilos está desocupados: max_connections = (AsyncRequestWorkerFactor + 1) * MaxRequestWorkers mpm event
  • 14. MWS apache Optimizado para las plataformas Windows Un proceso padre y un proceso hijo El proceso hijo es multi-hilo Utiliza funcionalidades de Windows mmp winnt Cliente Proceso hijoPoceso princ. (httpd) Servidor 80
  • 15. MWS apache Bajar software de www.apache.org Instalación mediante binarios (fácil pero no configurable) Instalación personalizada  Bajar fuentes  Configurar la instalación l ./configure [opciones] l Esto crea un makefile personalizado  Compilar el servidor l make l Entre otras cosas crea el ejecutable de Apache (httpd)  Instalar el servidor l make install instalación ./configure --prefix=/usr/local/apache (indica el directorio de instalación de apache)
  • 16. MWS apache Configuración mediante fichero de texto La ubicación y nombre del fichero puede cambiar según la distribución:  http.conf  apache2.conf La configuración puede estar distribuida en distintos ficheros:  /etc/apache2/apache2.conf (configuración general del servidor. Desde este se incluyen el resto)  /etc/apache2/ports.conf (configuración de puertos)  /etc/apache2/sites-enabled/000-default  /etc/apache2/sites-enabled/001-site1  /etc/apache2/sites-enabled/002-site2  (configuración de los sitios web: directorios, contenidos, etc.) Directiva “include” Configuración de módulos  /etc/apache2/mods-enabled/*.load l LoadModule jk_module /usr/apache2/modules/mod_jk.so  /etc/apache2/mods-enabled/*.conf configuración
  • 17. MWS apache En Windows: http://pistachitos.com/guias/instalar-php-5- 6-sobre-apache-2-4-windows/ Activar PHP: l Primero instalarlo: apt-get install libapache2-mod-php5  /etc/apache2/mods-enabled/*.load  /etc/apache2/mods-enabled/*.conf  En /etc/php5/apache2/php.ini configuraremos las opciones que necesitemos para PHP l Safe Mode = Off (Todas las funciones activas) l Display errors = On (No para producción) l max_execution_time=30 (Tiempo máx ejecución) l post_max_size=8M (Máximo tamaño POST) l upload_max_filesize = 8M l extension=mysql.so (acceso a MySQL, necesita también php5-mysql) PHP
  • 20. MWS apache Debemos tener en cuenta: l MaxConnectionsPerChild Al igual que en GNU/Linux, controla el número de conexiones para un único proceso, pero por el contrario, en Windows, no se creará un proceso de reemplazo instantáneamente (por lo general, estará a 0 a menos que haya problemas con la memoria) l ThreadsPerChild: Número máximo de hijos → número máximo de conexiones a la vez (recomendación: 150) l ¡Cuidado con '' que Apache puede interpretarlo como carácter de escape l Los nombres de archivo son case-insensitive en Windows, por lo que: RewriteEngine On RewriteMap lowercase int:tolower RewriteCond "%{REQUEST_URI}" "[A-Z]" RewriteRule "(.*)" "${lowercase:$1}" [R,L] Configuración Windows
  • 21. MWS apache configuración – apache2.conf # apache2.conf -- Archivo de configuración de apache # Sección 1: Entorno Global ServerRoot "/usr/local/apache" PidFile /var/run/apache.pid <IfModule !perchild.c> ScoreBoardFile logs/apache_runtime_status </IfModule> Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 15 <IfModule prefork.c> StartServers 3 MaxClients 8 MinSpareServers 5 MaxSpareServers 10 MaxRequestPerChild 0 </IfModule> Indica el directorio base del servidor /usr/local/apache └ bin └ conf └ htdocs └ manual └ icons └ small └ logs └ cgi-bin └ include
  • 22. MWS apache configuración – apache2.conf # apache2.conf -- Archivo de configuración de apache # Sección 1: Entorno Global ServerRoot "/usr/local/apache" PidFile /var/run/apache.pid <IfModule !perchild.c> ScoreBoardFile logs/apache_runtime_status </IfModule> Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 15 <IfModule prefork.c> StartServers 3 MaxClients 8 MinSpareServers 5 MaxSpareServers 10 MaxRequestPerChild 0 </IfModule> Fichero donde se almacena el PID del proceso padre
  • 23. MWS apache configuración – apache2.conf # apache2.conf -- Archivo de configuración de apache # Sección 1: Entorno Global ServerRoot "/usr/local/apache" PidFile /var/run/apache.pid <IfModule !perchild.c> ScoreBoardFile logs/apache_runtime_status </IfModule> Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 15 <IfModule prefork.c> StartServers 3 MaxClients 8 MinSpareServers 5 MaxSpareServers 10 MaxRequestPerChild 0 </IfModule> Fichero para la comunciación entre el proceso padre y los hijos
  • 24. MWS apache configuración – apache2.conf # apache2.conf -- Archivo de configuración de apache # Sección 1: Entorno Global ServerRoot "/usr/local/apache" PidFile /var/run/apache.pid <IfModule !perchild.c> ScoreBoardFile logs/apache_runtime_status </IfModule> Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 15 <IfModule prefork.c> StartServers 3 MaxClients 8 MinSpareServers 5 MaxSpareServers 10 MaxRequestPerChild 0 </IfModule> Segundos máximos de espera entre la recepción de una petición y la respuesta
  • 25. MWS apache configuración – apache2.conf # apache2.conf -- Archivo de configuración de apache # Sección 1: Entorno Global ServerRoot "/usr/local/apache" PidFile /var/run/apache.pid <IfModule !perchild.c> ScoreBoardFile logs/apache_runtime_status </IfModule> Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 15 <IfModule prefork.c> StartServers 3 MaxClients 8 MinSpareServers 5 MaxSpareServers 10 MaxRequestPerChild 0 </IfModule> Permite conexiones persistentes (más de una solicitud por conexión)
  • 26. MWS apache configuración – apache2.conf # apache2.conf -- Archivo de configuración de apache # Sección 1: Entorno Global ServerRoot "/usr/local/apache" PidFile /var/run/apache.pid <IfModule !perchild.c> ScoreBoardFile logs/apache_runtime_status </IfModule> Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 15 <IfModule prefork.c> StartServers 3 MaxClients 8 MinSpareServers 5 MaxSpareServers 10 MaxRequestPerChild 0 </IfModule> Nº máximo de solicitudes por conexión persistente
  • 27. MWS apache configuración – apache2.conf # apache2.conf -- Archivo de configuración de apache # Sección 1: Entorno Global ServerRoot "/usr/local/apache" PidFile /var/run/apache.pid <IfModule !perchild.c> ScoreBoardFile logs/apache_runtime_status </IfModule> Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 15 <IfModule prefork.c> StartServers 3 MaxClients 8 MinSpareServers 5 MaxSpareServers 10 MaxRequestPerChild 0 </IfModule> Segundos máximos de espera de una nueva solicitud en una conexión persistente
  • 28. MWS apache configuración – apache2.conf # apache2.conf -- Archivo de configuración de apache # Sección 1: Entorno Global ServerRoot "/usr/local/apache" PidFile /var/run/apache.pid <IfModule !perchild.c> ScoreBoardFile logs/apache_runtime_status </IfModule> Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 15 <IfModule prefork.c> StartServers 3 MaxClients 8 MinSpareServers 5 MaxSpareServers 10 MaxRequestPerChild 0 </IfModule> Nº inicial de procesos hijo
  • 29. MWS apache configuración – apache2.conf # apache2.conf -- Archivo de configuración de apache # Sección 1: Entorno Global ServerRoot "/usr/local/apache" PidFile /var/run/apache.pid <IfModule !perchild.c> ScoreBoardFile logs/apache_runtime_status </IfModule> Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 15 <IfModule prefork.c> StartServers 3 MaxClients 8 MinSpareServers 5 MaxSpareServers 10 MaxRequestPerChild 0 </IfModule> Límite de clientes conectados simultáneamente
  • 30. MWS apache configuración – apache2.conf # apache2.conf -- Archivo de configuración de apache # Sección 1: Entorno Global ServerRoot "/usr/local/apache" PidFile /var/run/apache.pid <IfModule !perchild.c> ScoreBoardFile logs/apache_runtime_status </IfModule> Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 15 <IfModule prefork.c> StartServers 3 MaxClients 8 MinSpareServers 5 MaxSpareServers 10 MaxRequestPerChild 0 </IfModule> Nº mínimo y máximo de hilos parados
  • 31. MWS apache configuración – apache2.conf # apache2.conf -- Archivo de configuración de apache # Sección 1: Entorno Global ServerRoot "/usr/local/apache" PidFile /var/run/apache.pid <IfModule !perchild.c> ScoreBoardFile logs/apache_runtime_status </IfModule> Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 15 <IfModule prefork.c> StartServers 3 MaxClients 8 MinSpareServers 5 MaxSpareServers 10 MaxRequestPerChild 0 </IfModule> Nº máximo de solicitudes que puede servir un hijo antes de ser ‘asesinado’. Con 0 indicamos que no se maten nunca.
  • 32. MWS apache configuración – apache2.conf # Sección 2 Configuración del servidor principal Listen 80.90.56.12 80 User www-data Group www-data ServerAdmin yo@micorreo.com ServerName www.miservidor.com DocumentRoot /usr/local/apache/htdocs <Directory /> Options SymLinksIfOwnerMatch AllowOverride None </Directory> <Directory /usr/local/apache/htdocs > Options Indexes Includes FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> UserDir public_html DirectoryIndex index.html index.htm index.shtml index.cgi AccessFileName .htaccess
  • 33. MWS apache configuración – apache2.conf # Sección 2 Configuración del servidor principal Listen 80.90.56.12 80 User www-data Group www-data ServerAdmin yo@micorreo.com ServerName www.miservidor.com DocumentRoot /usr/local/apache/htdocs <Directory /> Options SymLinksIfOwnerMatch AllowOverride None </Directory> <Directory /usr/local/apache/htdocs > Options Indexes Includes FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> UserDir public_html DirectoryIndex index.html index.htm index.shtml index.cgi AccessFileName .htaccess IP y puerto de escucha del servidor Usuario y grupo de los procesos hijo
  • 34. MWS apache configuración – apache2.conf # Sección 2 Configuración del servidor principal Listen 80.90.56.12 80 User www-data Group www-data ServerAdmin yo@micorreo.com ServerName www.miservidor.com DocumentRoot /usr/local/apache/htdocs <Directory /> Options SymLinksIfOwnerMatch AllowOverride None </Directory> <Directory /usr/local/apache/htdocs > Options Indexes Includes FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> UserDir public_html DirectoryIndex index.html index.htm index.shtml index.cgi AccessFileName .htaccess Email del administrador del servidor Nombre DNS del servidor
  • 35. MWS apache configuración – apache2.conf # Sección 2 Configuración del servidor principal Listen 80.90.56.12 80 User www-data Group www-data ServerAdmin yo@micorreo.com ServerName www.miservidor.com DocumentRoot /usr/local/apache/htdocs <Directory /> Options SymLinksIfOwnerMatch AllowOverride None </Directory> <Directory /usr/local/apache/htdocs > Options Indexes Includes FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> UserDir public_html DirectoryIndex index.html index.htm index.shtml index.cgi AccessFileName .htaccess Directorio raiz de los documentos web
  • 36. MWS apache configuración – apache2.conf # Sección 2 Configuración del servidor principal Listen 80.90.56.12 80 User www-data Group www-data ServerAdmin yo@micorreo.com ServerName www.miservidor.com DocumentRoot /usr/local/apache/htdocs <Directory /> Options SymLinksIfOwnerMatch AllowOverride None </Directory> <Directory /usr/local/apache/htdocs > Options Indexes Includes FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> UserDir public_html DirectoryIndex index.html index.htm index.shtml index.cgi AccessFileName .htaccess Definición de un directorio del servidor El argumento es un directorio del sistema de archivos También se puede usar la directiva Location que tiene como argumento una ruta de la URL
  • 37. MWS apache configuración – apache2.conf # Sección 2 Configuración del servidor principal Listen 80.90.56.12 80 User www-data Group www-data ServerAdmin yo@micorreo.com ServerName www.miservidor.com DocumentRoot /usr/local/apache/htdocs <Directory /> Options SymLinksIfOwnerMatch AllowOverride None </Directory> <Directory /usr/local/apache/htdocs > Options Indexes Includes FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> UserDir public_html DirectoryIndex index.html index.htm index.shtml index.cgi AccessFileName .htaccess OPCIONES ExecCGI: Se permite la ejecución de CGI’s Indexes: Si se solicita un directorio se muestra una página con el contenido del mismo FollowSymLinks: resolver enlaces simbólicos SymLinksIfOwnerMatch: resolver enlaces simbólicos si el destino es propiedad del mismo usuario que el enlace
  • 38. MWS apache configuración – apache2.conf # Sección 2 Configuración del servidor principal Listen 80.90.56.12 80 User www-data Group www-data ServerAdmin yo@micorreo.com ServerName www.miservidor.com DocumentRoot /usr/local/apache/htdocs <Directory /> Options SymLinksIfOwnerMatch AllowOverride None </Directory> <Directory /usr/local/apache/htdocs > Options Indexes Includes FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> UserDir public_html DirectoryIndex index.html index.htm index.shtml index.cgi AccessFileName .htaccess No utilizar los ficheros de acceso .htaccess Los ficheros .htaccess se utilizan para distribuir la configuración por directorios. Un fichero .htaccess en un directorio es un fragmento de la configuración para ese directorio
  • 39. MWS apache La configuración distribuida permite fragmentar la configuración en pequeños archivos de configuración (.htaccess) alojados en los directorios de la web configuración distribuida #... DocumentRoot /var/www <Directory /var/www/fotos> # Configuración del directorio fotos </Directory> <Directory /var/www/videos> # Configuración del directorio videos </Directory> #... /etc/apache2/httpd.conf #... DocumentRoot /var/www <Directory /var/www> AllowOverride All </Directory> #... /etc/apache2/httpd.conf /var/www/fotos/.htaccess # Configuración del directorio fotos #... /var/www/videos/.htaccess # Configuración del directorio videos #... Configuración CENTRALIZADA Configuración DISTRIBUIDA
  • 40. MWS apache configuración – apache2.conf # Sección 2 Configuración del servidor principal Listen 80.90.56.12 80 User www-data Group www-data ServerAdmin yo@micorreo.com ServerName www.miservidor.com DocumentRoot /usr/local/apache/htdocs <Directory /> Options SymLinksIfOwnerMatch AllowOverride None </Directory> <Directory /usr/local/apache/htdocs > Options Indexes Includes FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> UserDir public_html DirectoryIndex index.html index.htm index.shtml index.cgi AccessFileName .htaccess Orden de las directivas de acceso Acceso por defecto
  • 41. MWS apache configuración – apache2.conf # Sección 2 Configuración del servidor principal Listen 80.90.56.12 80 User www-data Group www-data ServerAdmin yo@micorreo.com ServerName www.miservidor.com DocumentRoot /usr/local/apache/htdocs <Directory /> Options SymLinksIfOwnerMatch AllowOverride None </Directory> <Directory /usr/local/apache/htdocs > Options Indexes Includes FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> UserDir public_html DirectoryIndex index.html index.htm index.shtml index.cgi AccessFileName .htaccess Utiliza una carpeta en el HOME de cada usuario del equipo para acceder como: http://www.miservidor.com/~usuario
  • 42. MWS apache configuración – apache2.conf # Sección 2 Configuración del servidor principal Listen 80.90.56.12 80 User www-data Group www-data ServerAdmin yo@micorreo.com ServerName www.miservidor.com DocumentRoot /usr/local/apache/htdocs <Directory /> Options SymLinksIfOwnerMatch AllowOverride None </Directory> <Directory /usr/local/apache/htdocs > Options Indexes Includes FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> UserDir public_html DirectoryIndex index.html index.htm index.shtml index.cgi AccessFileName .htaccess Páginas índice cuando se accede a un directorio
  • 43. MWS apache configuración – apache2.conf # Sección 2 Configuración del servidor principal Listen 80.90.56.12 80 User www-data Group www-data ServerAdmin yo@micorreo.com ServerName www.miservidor.com DocumentRoot /usr/local/apache/htdocs <Directory /> Options SymLinksIfOwnerMatch AllowOverride None </Directory> <Directory /usr/local/apache/htdocs > Options Indexes Includes FollowSymLinks AllowOverride None Order allow,deny Allow from all </Directory> UserDir public_html DirectoryIndex index.html index.htm index.shtml index.cgi AccessFileName .htaccess Nombre del archivo de configuración del control de acceso
  • 44. MWS apache configuración – apache2.conf TypesConfig /etc/mime.types DefaultType text/plain <IfModule mod_mime_magic.c> MIMEMagicFile conf/magic </IfModule> HostnameLookups Off ErrorLog /var/log/apache/error.log LogLevel warn LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"time: %T seg %v"full # ... ServerSignature On Alias /icons/ "/usr/local/apache/icons/" <Directory "/usr/local/apache/icons"> Options Indexes MultiViews AllowOverride None Order allow,deny Allow from all </Directory> ScriptAlias /cgi-bin/ "/usr/local/apache/cgi-bin/" <Directory /usr/lib/cgi-bin/> AllowOverride None Options ExecCGI Order allow,deny Allow from all </Directory> AddLanguage da .dk AddLanguage nl .nl # ... LanguagePriority en da nl et fr de el it ja pl pt pt-br ltz ca es sv AddDefaultCharset ISO-8859-1 Configuración MIME
  • 45. MWS apache configuración – apache2.conf TypesConfig /etc/mime.types DefaultType text/plain <IfModule mod_mime_magic.c> MIMEMagicFile conf/magic </IfModule> HostnameLookups Off ErrorLog /var/log/apache/error.log LogLevel warn LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"time: %T seg %v" full # ... ServerSignature On Alias /icons/ "/usr/local/apache/icons/" <Directory "/usr/local/apache/icons"> Options Indexes MultiViews AllowOverride None Order allow,deny Allow from all </Directory> ScriptAlias /cgi-bin/ "/usr/local/apache/cgi-bin/" <Directory /usr/lib/cgi-bin/> AllowOverride None Options ExecCGI Order allow,deny Allow from all </Directory> AddLanguage da .dk AddLanguage nl .nl # ... LanguagePriority en da nl et fr de el it ja pl pt pt-br ltz ca es sv AddDefaultCharset ISO-8859-1 Tipo MIME por defecto Patrones para averiguar el tipo MIME No usar DNS
  • 46. MWS apache configuración – apache2.conf TypesConfig /etc/mime.types DefaultType text/plain <IfModule mod_mime_magic.c> MIMEMagicFile conf/magic </IfModule> HostnameLookups Off ErrorLog /var/log/apache/error.log LogLevel warn LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"time: %T seg %v" full # ... ServerSignature On Alias /icons/ "/usr/local/apache/icons/" <Directory "/usr/local/apache/icons"> Options Indexes MultiViews AllowOverride None Order allow,deny Allow from all </Directory> ScriptAlias /cgi-bin/ "/usr/local/apache/cgi-bin/" <Directory /usr/lib/cgi-bin/> AllowOverride None Options ExecCGI Order allow,deny Allow from all </Directory> AddLanguage da .dk AddLanguage nl .nl # ... LanguagePriority en da nl et fr de el it ja pl pt pt-br ltz ca es sv AddDefaultCharset ISO-8859-1 Configuración del log
  • 47. MWS apache configuración – apache2.conf TypesConfig /etc/mime.types DefaultType text/plain <IfModule mod_mime_magic.c> MIMEMagicFile conf/magic </IfModule> HostnameLookups Off ErrorLog /var/log/apache/error.log LogLevel warn LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i" %T %v" full # ... ServerSignature On Alias /icons/ "/usr/local/apache/icons/" <Directory "/usr/local/apache/icons"> Options Indexes MultiViews AllowOverride None Order allow,deny Allow from all </Directory> ScriptAlias /cgi-bin/ "/usr/local/apache/cgi-bin/" <Directory /usr/lib/cgi-bin/> AllowOverride None Options ExecCGI Order allow,deny Allow from all </Directory> AddLanguage da .dk AddLanguage nl .nl # ... LanguagePriority en da nl et fr de el it ja pl pt pt-br ltz ca es sv AddDefaultCharset ISO-8859-1 Muestra un pie de pagina con información sobre el servidor en las páginas de error Directorio de Iconos Directorio de CGI’s Lenguajes Juego de caracteres por defecto
  • 48. MWS apache Un alias se utiliza para mapear una URL a una localización concreta del sistema de archivos Rompe la secuencia jerárquica normal alias Espacio de URLs http://????/ └ documentos └ imagenes └ fotos └ videos └ recursos Espacio de archivos /var/www └ documentos └ imagenes └ fotos └ videos /media/disco2 └ recursos DocumentRoot /var/www Alias /recursos /media/disco2/recursos
  • 49. MWS apache Crear directorios del servidor web que requieren autenticación para su acceso autenticación Cliente (navegador) Servidor (httpd) GET http://www.misitio.com/protegido/a.htm Error 401: “Necesita autorización”Acceso restringido Usuario: Contraseña: pepe ******** GET http://www.misitio.com/protegido/a.htm Incluye el usuario y la contraseña en la cabecera Contenido de a.htm
  • 50. MWS apache Configurar en apache2.conf la zona restringida Crear el archivo .members de usuarios/contraseñas autenticación básica <Location "/protegido/"> AuthName "Acceso restringido“ AuthType Basic AuthUserFile /usr/local/apache/secrets/.members Require valid-user </Location> # htpasswd –c .members pepe New password: **** Re-type new password: **** Adding password for user pepe # htpasswd .members juan New password: **** Re-type new password: **** Adding password for user pepe # cat .members pepe:b8p3dfj093478 juan:03l43f89sfl43 #
  • 51. MWS apache Tener diferentes sitios web en un único equipo servidor Ahorro en infraestructuras Posibilidad de configuración compartida Administración centralizada Tipos:  Basada en nombres  Basada en IP  Varios servidores principales servidores virtuales
  • 52. MWS apache Existe un servidor principal Existen diferentes nombres DNS que apuntan a la IP del servidor servidor virtual basado en nombres # Definición del servidor principal # ... ServerName www.miservidor.com DocumentRoot /www/miservidor/htdocs # ... <VirtualHost 192.168.1.20> ServerName www.miservidor2.com DocumentRoot /www/miservidor2/htdocs # ... </VirtualHost> <VirtualHost 192.168.1.20> ServerName www.miservidor3.com DocumentRoot /www/miservidor3/htdocs # ... </VirtualHost>
  • 53. MWS apache Existe un servidor principal Existen diferentes IP’s en el servidor servidor virtual basado en ip # Definición del servidor principal # ... ServerName www.miservidor.com DocumentRoot /www/miservidor/htdocs # ... <VirtualHost 192.168.1.21> ServerName www.miservidor2.com DocumentRoot /www/miservidor2/htdocs # ... </VirtualHost> <VirtualHost 192.168.1.22> ServerName www.miservidor3.com DocumentRoot /www/miservidor3/htdocs # ... </VirtualHost>
  • 54. MWS Reescrituras URL •Transformar una solicitud en otra •Tipos: l Internas: el cliente no lo nota l Reescritura: el cliente cambia la URL apache
  • 56. MWS l Se necesita activar mod_rewrite (instalar el plugin + RewriteEngine on en configuración) l Utiliza un conjunto de reglas computas por: patrón a buscar, cadena de sustitución y acción a realizar. l Se pueden encadenar varias reglas l Sintaxis: l RewriteRule Patron Sustitucion [flags] l Patron: expresión regular a buscar dentro de la URL (entre host y QueryString) l Ejemplo: l RewriteRule ^/$ /inicio/ [L,R] apache Reescrituras URL
  • 58. MWS l Puede ser: l Relativa (sin el nombre del servidor) l Completa l Puede utilizar $1...$9 para indicar los fragmentos encontrados en el patrón l Ejemplo: l RewriteRule ^/productos/(.*)/.*)$ /producto.php?categoria=$1&id=$2 [L] apache Cadena de sustitución
  • 60. MWS Condiciones extra l RewriteCond l Tantas como necesitemos l Preceden a la regla l Deben cumplirse todas l Sintaxis: l RewriteCond cadena condicion [flags] l Flags: se pueden combinar varios separados con ',': l NC | nocase → Ignorar mayúsculas/minúsculas l OR | ornext → Realiza un 'o' lógico con la condición siguiente l Ejemplo: l RewriteCond %{HTTP_USER_AGENT} ^Mozilla l RewriteRule ^/$ /homepage.html [L] l RewriteCond %{HTTP_USER_AGENT} ^Lynx l RewriteRule ^/$ /homepage.min.html [L] l RewriteRule ^/$ /homepage.std.html [L] apache
  • 62. MWS apache https://httpd.apache.org/docs/2.4/caching.html Mejora del rendimiento: l Three-state RFC2616 HTTP caching: mod_cache, mod_cache_disk. Los estados son: Fresh (más reciente que), Stale (más viejo que) y Non Existent l Two-state key/value shared object caching: https://httpd.apache.org/docs/2.4/socache.h tml l Specialized file caching: mod_file_cache Precarga de ficheros en memoria en el arranque. Puede ser útil para ficheros muy accedidos. caché
  • 63. MWS apache Ejemplo: caché # Caching to Disk CacheRoot "/var/cache/apache/" CacheEnable disk / CacheDirLevels 2 CacheDirLength 1 #Caching to memcached (http://memcached.org/) #https://httpd.apache.org/docs/2.4/mod/mod_socache_memcache.html CacheEnable socache / CacheSocache memcache:memcd.example.com:11211,mem2.example.com:11212 # Caching files (¡cuidado con el número máximo de ficheros # abiertos establecido para el SO!) vs SSD vs caché del SO CacheFile /usr/local/apache2/htdocs/index.html
  • 64. MWS apache Necesitamos el certificado que identifique al servidor mod_ssl (LoadModule ssl_module modules/mod_ssl.so) SSL # Definición del servidor principal # ... Listen 443 # ... <VirtualHost *:443> ServerName www.example.es DocumentRoot /www/example/htdocs SSLEngine On SSLCertificateFile “path_to_cert” SSLCertificateKeyFile “path_to_key” # ... </VirtualHost>
  • 65. MWS apache Tener instalado openSSL Crear llave: Crear CSR (Certificate Signing Request) Generar el certificado (esto es lo que haría una autoridad certificadora) Así para autofirmado: OpenSSL y certificados openssl req -new -key server.key -out server.csr openssl genrsa -out server.key 1024 openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
  • 66. MWS apache Eliminar la versión de Apache y SO Deshabilita el listado de directorio Hardening (I) ServerTokens ProductOnly ServerSignature Off #footer <Directory /opt/apache/htdocs> Options ­Indexes|None Order allow,deny Allow from all </Directory> 
  • 67. MWS apache Para impedir obtener información de número de inodo, límite en MIME y procesos hijos con ETag Deshabilita .htaccess Limitar métodos HTTP: Hardening (II) FileETag None <Directory /opt/apache/htdocs> Options ­Indexes AllowOverride None </Directory>  <LimitExcept GET POST PUT DELETE> deny from all #si ponemos nombres, DNS </LimitExcept>  TraceEnable off #Solo TRACE
  • 68. MWS apache Mitigar Cross usando HttpOnly and Secure flag en cookie minimizabdo robo y manipulación Clickjacking Attack (frames) l SAMEORIGIN: Solo desde el mismo sitio l DENY: Ninguno l ALLOW-FROM uri: Solo desde URI especificada Deshabilitar SSI Hardening (III) Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure Header always append X­Frame­Options SAMEORIGIN #En web compartido (.htaccess): Header append X­FRAME­OPTIONS "SAMEORIGIN" <Directory /opt/apache/htdocs> Options –Indexes ­Includes Order allow,deny Allow from all </Directory>
  • 69. MWS apache X-XSS Protection (incluso si el usuario lo deshabilita en el navegador) Solo HTTP/1.1 Deshabilitar SSL 1,..., solo TLS 1.0 Tipo MIME y contenido debe ser el mismo Hardening (IV) Header set X-XSS-Protection “1; mode=block” RewriteEngine On RewriteCond %{THE_REQUEST} !HTTP/1.1$ RewriteRule .* ­ [F]  SSLProtocol –ALL +TLSv1 +TLSv1.1 +TLSv1.2 <IfModule mod_headers.c> # Disable content sniffing, since it's an attack vector. Header always set X-Content-Type-Options nosniff </IfModule>
  • 70. MWS apache Mod Security (https://www.howtoforge.com/apache_mod_ security) Deshabilita los módulos no utilizados Habilita registros: https://httpd.apache.org/docs/2.4/mod/mod _log_config.html Más en https://geekflare.com/apache-web- server-hardening-security/#2-Information- Leakage Hardening (IV) LogFormat "%h %l %u %t "%{sessionID}C" "%r" %>s %b %T" common
  • 71. MWS apache PHP /etc/php/apache2/php.ini l expose_php = Off #no indicar versión l display_errors = Off l open_basedir = ubicación # impedir path Traversal l disable_functions = phpinfo, system, excec, shell_exec, ini_set, Dl, eval l allow_url_fopen= Off l allow_url_include = Off Suhosin: componente para proteger servidores con PHP (php5-suhosin) Hardening (V)
  • 72. MWS apache HostnameLookups y DNS FollowSymLinks and SymLinksIfOwnerMatch (For highest performance, and no symlink protection, set FollowSymLinks everywhere, and never set SymLinksIfOwnerMatch) Caché MPM Cluster CDN Cloud … rendimiento
  • 73. MWS apache add The response header is added to the existing set of headers, even if this header already exists. This can result in two (or more) headers having the same name. This can lead to unforeseen consequences, and in general set, append or merge should be used instead. append The response header is appended to any existing header of the same name. When a new value is merged onto an existing header it is separated from the existing header with a comma. This is the HTTP standard way of giving a header multiple values. echo Request headers with this name are echoed back in the response headers. header may be a regular expression. value must be omitted. edit edit* If this response header exists, its value is transformed according to a regular expression search-and-replace. The value argument is a regular expression, and the replacement is a replacement string, which may contain backreferences or format specifiers. The edit form will match and replace exactly once in a header value, whereas the edit* form will replace every instance of the search pattern if it appears more than once. merge The response header is appended to any existing header of the same name, unless the value to be appended already appears in the header's comma-delimited list of values. When a new value is merged onto an existing header it is separated from the existing header with a comma. This is the HTTP standard way of giving a header multiple values. Values are compared in a case sensitive manner, and after all format specifiers have been processed. Values in double quotes are considered different from otherwise identical unquoted values. set The response header is set, replacing any previous header with this name. The value may be a format string. setifempty The request header is set, but only if there is no previous header with this name. The Content-Type header is a special use case since there might be the chance that its value have been determined but the header is not part of the response when setifempty is evaluated. It is safer to use set for this use case like in the following example: Header set Content-Type "text/plain" "expr=-z %{CONTENT_TYPE}" unset The response header of this name is removed, if it exists. If there are multiple headers of the same name, all will be removed. value must be omitted. header
  • 74. MWS apache https://httpd.apache.org/docs/ current/ Hardening de servidores GNU/Linux, OxWord, Carlos Álvarez y Pablo González Referencias

Notes de l'éditeur

  1. Solicitudes múltiples  acceso concurrente o única llamada para obtener todos los recursos (multiples peticiones por concexión) Version 1.1 of the protocol made bandwidth optimization improvements to HTTP/1.0. For example, HTTP/1.1 introduced chunked transfer encoding to allow content on persistent connections to be streamed, rather than buffered. HTTP pipelining further reduces lag time, allowing clients to send multiple requests before a previous response has been received to the first one. Another improvement to the protocol was byte serving, which is when a server transmits just the portion of a resource explicitly requested by a client. FastCGI es una alternativa al CGI estándar, cuya diferencia radica principalmente en el hecho de que el servidor crea un único proceso persistente por cada programa FastCGI en lugar de uno por cada solicitud del cliente. Ventajas [editar] Ahorro de Tráfico: Las peticiones de páginas Web se hacen al servidor Proxy y no a Internet directamente. Por lo tanto, aligera el tráfico en la red y descarga los servidores destino, a los que llegan menos peticiones. Velocidad en Tiempo de respuesta: El servidor Proxy crea un caché que evita transferencias idénticas de la información entre servidores durante un tiempo (configurado por el administrador) así que el usuario recibe una respuesta más rápida. Demanda a Usuarios: Puede cubrir a un gran número de usuarios, para solicitar, a través de él, los contenidos Web. Filtrado de contenidos: El servidor proxy puede hacer un filtrado de páginas o contenidos basándose en criterios de restricción establecidos por el administrador dependiendo valores y características de lo que no se permite, creando una restricción cuando sea necesario. Modificación de contenidos: Basándose en la misma función del filtrado, y llamado Privoxy, tiene el objetivo de proteger la privacidad en Internet, puede ser configurado para bloquear direcciones y Cookies por expresiones regulares y modifica en la petición el contenido. Desventajas [editar] Las páginas mostradas pueden no estar actualizadas si éstas han sido modificadas desde la última carga que realizó el proxy caché. Un diseñador de páginas web puede indicar en el contenido de su web que los navegadores no hagan una caché de sus páginas, pero este método no funciona habitualmente para un proxy. El hecho de acceder a Internet a través de un Proxy, en vez de mediante conexión directa, impide realizar operaciones avanzadas a través de algunos puertos o protocolos. Almacenar las páginas y objetos que los usuarios solicitan puede suponer una violación de la intimidad para algunas personas. SSI (Server Side Includes) are directives that are placed in HTML pages, and evaluated on the server while the pages are being served. They let you add dynamically generated content to an existing HTML page, without having to serve the entire page via a CGI program, or other dynamic technology. The decision of when to use SSI, and when to have your page entirely generated by some program, is usually a matter of how much of the page is static, and how much needs to be recalculated every time the page is served. SSI is a great way to add small pieces of information, such as the current time. But if a majority of your page is being generated at the time that it is served, you need to look for some other solution.
  2. Apache inicia varios subprocesos y cada petición es atendida por uno de estos; cuando termina con esta petición este subproceso podría atender a otro cliente o ser terminado, según al valor de MaxRequestsPerChild. Es el modo más estable, ya que un error crítico solo afectaría a una petición. Este es el único modo en que se pueden usar módulos / extensiones que no sean Thread-Safe. Requiere más recursos (Memoria RAM y CPU) para atender cierto número de peticiones simultaneas, respecto a otras configuraciones. Esto limita drásticamente la escabilidad del servidor. Favorece el uso intensivo de PHP. Los aceleradores de PHP no son Thread-Safe, pero al usarlos junto a Prefork podemos justificar el mayor uso de php (o páginas sin ningún tipo de caché, aparte del acelerador en sí). Prefork es la configuración predeterminada en la mayoría de instalaciones.
  3. Apache inicia varios subprocesos y cada petición es atendida por uno de estos; cuando termina con esta petición este subproceso podría atender a otro cliente o ser terminado, según al valor de MaxRequestsPerChild. Es el modo más estable, ya que un error crítico solo afectaría a una petición. Este es el único modo en que se pueden usar módulos / extensiones que no sean Thread-Safe. Requiere más recursos (Memoria RAM y CPU) para atender cierto número de peticiones simultaneas, respecto a otras configuraciones. Esto limita drásticamente la escabilidad del servidor. Favorece el uso intensivo de PHP. Los aceleradores de PHP no son Thread-Safe, pero al usarlos junto a Prefork podemos justificar el mayor uso de php (o páginas sin ningún tipo de caché, aparte del acelerador en sí). Prefork es la configuración predeterminada en la mayoría de instalaciones. EN 2.4, MaxClients es MaxRequestWorkers
  4. StarServers: prefork defaults to 5 MaxSpareServers: Tuning of this parameter should only be necessary on very busy sites. Setting this parameter to a large number is almost always a bad idea. If you are trying to set the value equal to or lower than MinSpareServers, Apache HTTP Server will automatically adjust it to MinSpareServers + 1. MinSpareServers: Tuning of this parameter should only be necessary on very busy sites. Setting this parameter to a large number is almost always a bad idea. Setting MaxConnectionsPerChild to a non-zero value limits the amount of memory that process can consume by (accidental) memory leakage.
  5. StarServers: prefork defaults to 5 MaxSpareServers: Tuning of this parameter should only be necessary on very busy sites. Setting this parameter to a large number is almost always a bad idea. If you are trying to set the value equal to or lower than MinSpareServers, Apache HTTP Server will automatically adjust it to MinSpareServers + 1. MinSpareServers: Tuning of this parameter should only be necessary on very busy sites. Setting this parameter to a large number is almost always a bad idea. Setting MaxConnectionsPerChild to a non-zero value limits the amount of memory that process can consume by (accidental) memory leakage.
  6. StarServers: prefork defaults to 5 MaxSpareServers: Tuning of this parameter should only be necessary on very busy sites. Setting this parameter to a large number is almost always a bad idea. If you are trying to set the value equal to or lower than MinSpareServers, Apache HTTP Server will automatically adjust it to MinSpareServers + 1. MinSpareServers: Tuning of this parameter should only be necessary on very busy sites. Setting this parameter to a large number is almost always a bad idea. Setting MaxConnectionsPerChild to a non-zero value limits the amount of memory that process can consume by (accidental) memory leakage.
  7. AsyncRequestWorkerFactor This directive can be used to fine-tune the per-process connection limit. A process will only accept new connections if the current number of connections (not counting connections in the &amp;quot;closing&amp;quot; state) is lower than: ThreadsPerChild + (AsyncRequestWorkerFactor * number of idle workers) An estimation of the maximum concurrent connections across all the processes given an average value of idle worker threads can be calculated with: (ThreadsPerChild + (AsyncRequestWorkerFactor * number of idle workers)) * ServerLimit Example ThreadsPerChild = 10 ServerLimit = 4 AsyncRequestWorkerFactor = 2 MaxRequestWorkers = 40 idle_workers = 4 (average for all the processes to keep it simple) max_connections = (ThreadsPerChild + (AsyncRequestWorkerFactor * idle_workers)) * ServerLimit = (10 + (2 * 4)) * 4 = 72
  8. AsyncRequestWorkerFactor This directive can be used to fine-tune the per-process connection limit. A process will only accept new connections if the current number of connections (not counting connections in the &amp;quot;closing&amp;quot; state) is lower than: ThreadsPerChild + (AsyncRequestWorkerFactor * number of idle workers) An estimation of the maximum concurrent connections across all the processes given an average value of idle worker threads can be calculated with: (ThreadsPerChild + (AsyncRequestWorkerFactor * number of idle workers)) * ServerLimit Example ThreadsPerChild = 10 ServerLimit = 4 AsyncRequestWorkerFactor = 2 MaxRequestWorkers = 40 idle_workers = 4 (average for all the processes to keep it simple) max_connections = (ThreadsPerChild + (AsyncRequestWorkerFactor * idle_workers)) * ServerLimit = (10 + (2 * 4)) * 4 = 72
  9. La directiva MaxSpareServers determina el número máximo de procesos hijo en espera deseado. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay más de MaxSpareServers procesos hijo en espera, entonces el proceso padre elimina el exceso. La directiva MinSpareServers fija el número mínimo de procesos hijo en espera. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay menos procesos hijo en espera que MinSpareServers, entonces el proceso padre crea nuevos procesos hijo a un ritmo máximo de uno por segundo.
  10. La directiva MaxSpareServers determina el número máximo de procesos hijo en espera deseado. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay más de MaxSpareServers procesos hijo en espera, entonces el proceso padre elimina el exceso. La directiva MinSpareServers fija el número mínimo de procesos hijo en espera. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay menos procesos hijo en espera que MinSpareServers, entonces el proceso padre crea nuevos procesos hijo a un ritmo máximo de uno por segundo.
  11. La directiva MaxSpareServers determina el número máximo de procesos hijo en espera deseado. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay más de MaxSpareServers procesos hijo en espera, entonces el proceso padre elimina el exceso. La directiva MinSpareServers fija el número mínimo de procesos hijo en espera. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay menos procesos hijo en espera que MinSpareServers, entonces el proceso padre crea nuevos procesos hijo a un ritmo máximo de uno por segundo.
  12. La directiva MaxSpareServers determina el número máximo de procesos hijo en espera deseado. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay más de MaxSpareServers procesos hijo en espera, entonces el proceso padre elimina el exceso. La directiva MinSpareServers fija el número mínimo de procesos hijo en espera. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay menos procesos hijo en espera que MinSpareServers, entonces el proceso padre crea nuevos procesos hijo a un ritmo máximo de uno por segundo.
  13. La directiva MaxSpareServers determina el número máximo de procesos hijo en espera deseado. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay más de MaxSpareServers procesos hijo en espera, entonces el proceso padre elimina el exceso. La directiva MinSpareServers fija el número mínimo de procesos hijo en espera. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay menos procesos hijo en espera que MinSpareServers, entonces el proceso padre crea nuevos procesos hijo a un ritmo máximo de uno por segundo.
  14. La directiva MaxSpareServers determina el número máximo de procesos hijo en espera deseado. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay más de MaxSpareServers procesos hijo en espera, entonces el proceso padre elimina el exceso. La directiva MinSpareServers fija el número mínimo de procesos hijo en espera. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay menos procesos hijo en espera que MinSpareServers, entonces el proceso padre crea nuevos procesos hijo a un ritmo máximo de uno por segundo.
  15. La directiva MaxSpareServers determina el número máximo de procesos hijo en espera deseado. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay más de MaxSpareServers procesos hijo en espera, entonces el proceso padre elimina el exceso. La directiva MinSpareServers fija el número mínimo de procesos hijo en espera. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay menos procesos hijo en espera que MinSpareServers, entonces el proceso padre crea nuevos procesos hijo a un ritmo máximo de uno por segundo.
  16. La directiva MaxSpareServers determina el número máximo de procesos hijo en espera deseado. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay más de MaxSpareServers procesos hijo en espera, entonces el proceso padre elimina el exceso. La directiva MinSpareServers fija el número mínimo de procesos hijo en espera. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay menos procesos hijo en espera que MinSpareServers, entonces el proceso padre crea nuevos procesos hijo a un ritmo máximo de uno por segundo.
  17. La directiva MaxSpareServers determina el número máximo de procesos hijo en espera deseado. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay más de MaxSpareServers procesos hijo en espera, entonces el proceso padre elimina el exceso. La directiva MinSpareServers fija el número mínimo de procesos hijo en espera. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay menos procesos hijo en espera que MinSpareServers, entonces el proceso padre crea nuevos procesos hijo a un ritmo máximo de uno por segundo.
  18. La directiva MaxSpareServers determina el número máximo de procesos hijo en espera deseado. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay más de MaxSpareServers procesos hijo en espera, entonces el proceso padre elimina el exceso. La directiva MinSpareServers fija el número mínimo de procesos hijo en espera. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay menos procesos hijo en espera que MinSpareServers, entonces el proceso padre crea nuevos procesos hijo a un ritmo máximo de uno por segundo.
  19. La directiva MaxSpareServers determina el número máximo de procesos hijo en espera deseado. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay más de MaxSpareServers procesos hijo en espera, entonces el proceso padre elimina el exceso. La directiva MinSpareServers fija el número mínimo de procesos hijo en espera. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay menos procesos hijo en espera que MinSpareServers, entonces el proceso padre crea nuevos procesos hijo a un ritmo máximo de uno por segundo.
  20. La directiva MaxSpareServers determina el número máximo de procesos hijo en espera deseado. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay más de MaxSpareServers procesos hijo en espera, entonces el proceso padre elimina el exceso. La directiva MinSpareServers fija el número mínimo de procesos hijo en espera. Un proceso en espera es aquel que no está atendiendo ninguna petición. Si hay menos procesos hijo en espera que MinSpareServers, entonces el proceso padre crea nuevos procesos hijo a un ritmo máximo de uno por segundo.
  21. Relacionada con ellas está la directiva Order que indica a Apache2 en qué orden tiene que aplicar las directivas Allow y Deny UserDir indica el directorio que se añade al directorio personal de los usuarios para servior páginas cuando se realiza una peticion del tipo ~usuario Esta directiva activa la resolución de DNS de manera que los nombres de host puedan ser guardados en los archivos log (y pasados a CGIs/SSIs en REMOTE_HOST). El valor Double se refiere a hacer una busqueda de DNSs inversa doble. Esto es, después de hacer una busqueda inversa, se hace una busqueda normal posteriormente sobre ese resultado. Al menos una de las direcciones IP en la búsqueda posterior debe equivaler a la dirección IP original. (En terminología de &amp;quot;tcpwrappers&amp;quot; se llama PARANOID.)
  22. Relacionada con ellas está la directiva Order que indica a Apache2 en qué orden tiene que aplicar las directivas Allow y Deny UserDir indica el directorio que se añade al directorio personal de los usuarios para servior páginas cuando se realiza una peticion del tipo ~usuario Esta directiva activa la resolución de DNS de manera que los nombres de host puedan ser guardados en los archivos log (y pasados a CGIs/SSIs en REMOTE_HOST). El valor Double se refiere a hacer una busqueda de DNSs inversa doble. Esto es, después de hacer una busqueda inversa, se hace una busqueda normal posteriormente sobre ese resultado. Al menos una de las direcciones IP en la búsqueda posterior debe equivaler a la dirección IP original. (En terminología de &amp;quot;tcpwrappers&amp;quot; se llama PARANOID.)
  23. Relacionada con ellas está la directiva Order que indica a Apache2 en qué orden tiene que aplicar las directivas Allow y Deny UserDir indica el directorio que se añade al directorio personal de los usuarios para servior páginas cuando se realiza una peticion del tipo ~usuario Esta directiva activa la resolución de DNS de manera que los nombres de host puedan ser guardados en los archivos log (y pasados a CGIs/SSIs en REMOTE_HOST). El valor Double se refiere a hacer una busqueda de DNSs inversa doble. Esto es, después de hacer una busqueda inversa, se hace una busqueda normal posteriormente sobre ese resultado. Al menos una de las direcciones IP en la búsqueda posterior debe equivaler a la dirección IP original. (En terminología de &amp;quot;tcpwrappers&amp;quot; se llama PARANOID.)
  24. Relacionada con ellas está la directiva Order que indica a Apache2 en qué orden tiene que aplicar las directivas Allow y Deny UserDir indica el directorio que se añade al directorio personal de los usuarios para servior páginas cuando se realiza una peticion del tipo ~usuario Esta directiva activa la resolución de DNS de manera que los nombres de host puedan ser guardados en los archivos log (y pasados a CGIs/SSIs en REMOTE_HOST). El valor Double se refiere a hacer una busqueda de DNSs inversa doble. Esto es, después de hacer una busqueda inversa, se hace una busqueda normal posteriormente sobre ese resultado. Al menos una de las direcciones IP en la búsqueda posterior debe equivaler a la dirección IP original. (En terminología de &amp;quot;tcpwrappers&amp;quot; se llama PARANOID.)
  25. Relacionada con ellas está la directiva Order que indica a Apache2 en qué orden tiene que aplicar las directivas Allow y Deny UserDir indica el directorio que se añade al directorio personal de los usuarios para servior páginas cuando se realiza una peticion del tipo ~usuario Esta directiva activa la resolución de DNS de manera que los nombres de host puedan ser guardados en los archivos log (y pasados a CGIs/SSIs en REMOTE_HOST). El valor Double se refiere a hacer una busqueda de DNSs inversa doble. Esto es, después de hacer una busqueda inversa, se hace una busqueda normal posteriormente sobre ese resultado. Al menos una de las direcciones IP en la búsqueda posterior debe equivaler a la dirección IP original. (En terminología de &amp;quot;tcpwrappers&amp;quot; se llama PARANOID.)
  26. Operating System Caching Almost all modern operating systems cache file-data in memory managed directly by the kernel. This is a powerful feature, and for the most part operating systems get it right. For example, on Linux, let&amp;apos;s look at the difference in the time it takes to read a file for the first time and the second time; colm@coroebus:~$ time cat testfile &amp;gt; /dev/null real 0m0.065s user 0m0.000s sys 0m0.001s colm@coroebus:~$ time cat testfile &amp;gt; /dev/null real 0m0.003s user 0m0.003s sys 0m0.000s Even for this small file, there is a huge difference in the amount of time it takes to read the file. This is because the kernel has cached the file contents in memory. By ensuring there is &amp;quot;spare&amp;quot; memory on your system, you can ensure that more and more file-contents will be stored in this cache. This can be a very efficient means of in-memory caching, and involves no extra configuration of httpd at all. Additionally, because the operating system knows when files are deleted or modified, it can automatically remove file contents from the cache when necessary. This is a big advantage over httpd&amp;apos;s in-memory caching which has no way of knowing when a file has changed. Despite the performance and advantages of automatic operating system caching there are some circumstances in which in-memory caching may be better performed by httpd.
  27. If the HttpOnly flag (optional) is included in the HTTP response header, the cookie cannot be accessed through client side script (again if the browser supports this flag). As a result, even if a cross-site scripting (XSS) flaw exists, and a user accidentally accesses a link that exploits this flaw, the browser (primarily Internet Explorer) will not reveal the cookie to a third party.
  28. If the HttpOnly flag (optional) is included in the HTTP response header, the cookie cannot be accessed through client side script (again if the browser supports this flag). As a result, even if a cross-site scripting (XSS) flaw exists, and a user accidentally accesses a link that exploits this flaw, the browser (primarily Internet Explorer) will not reveal the cookie to a third party.
  29. If the HttpOnly flag (optional) is included in the HTTP response header, the cookie cannot be accessed through client side script (again if the browser supports this flag). As a result, even if a cross-site scripting (XSS) flaw exists, and a user accidentally accesses a link that exploits this flaw, the browser (primarily Internet Explorer) will not reveal the cookie to a third party.
  30. If the HttpOnly flag (optional) is included in the HTTP response header, the cookie cannot be accessed through client side script (again if the browser supports this flag). As a result, even if a cross-site scripting (XSS) flaw exists, and a user accidentally accesses a link that exploits this flaw, the browser (primarily Internet Explorer) will not reveal the cookie to a third party.
  31. Wherever in your URL-space you do not have an Options FollowSymLinks, or you do have an Options SymLinksIfOwnerMatch, Apache will need to issue extra system calls to check up on symlinks. (One extra call per filename component.) For example, if you had: DocumentRoot &amp;quot;/www/htdocs&amp;quot; &amp;lt;Directory &amp;quot;/&amp;quot;&amp;gt; Options SymLinksIfOwnerMatch &amp;lt;/Directory&amp;gt; and a request is made for the URI /index.html, then Apache will perform lstat(2) on /www, /www/htdocs, and /www/htdocs/index.html. The results of these lstats are never cached, so they will occur on every single request. If you really desire the symlinks security checking, you can do something like this: DocumentRoot &amp;quot;/www/htdocs&amp;quot; &amp;lt;Directory &amp;quot;/&amp;quot;&amp;gt; Options FollowSymLinks &amp;lt;/Directory&amp;gt; &amp;lt;Directory &amp;quot;/www/htdocs&amp;quot;&amp;gt; Options -FollowSymLinks +SymLinksIfOwnerMatch &amp;lt;/Directory&amp;gt;
  32. Wherever in your URL-space you do not have an Options FollowSymLinks, or you do have an Options SymLinksIfOwnerMatch, Apache will need to issue extra system calls to check up on symlinks. (One extra call per filename component.) For example, if you had: DocumentRoot &amp;quot;/www/htdocs&amp;quot; &amp;lt;Directory &amp;quot;/&amp;quot;&amp;gt; Options SymLinksIfOwnerMatch &amp;lt;/Directory&amp;gt; and a request is made for the URI /index.html, then Apache will perform lstat(2) on /www, /www/htdocs, and /www/htdocs/index.html. The results of these lstats are never cached, so they will occur on every single request. If you really desire the symlinks security checking, you can do something like this: DocumentRoot &amp;quot;/www/htdocs&amp;quot; &amp;lt;Directory &amp;quot;/&amp;quot;&amp;gt; Options FollowSymLinks &amp;lt;/Directory&amp;gt; &amp;lt;Directory &amp;quot;/www/htdocs&amp;quot;&amp;gt; Options -FollowSymLinks +SymLinksIfOwnerMatch &amp;lt;/Directory&amp;gt;
  33. Wherever in your URL-space you do not have an Options FollowSymLinks, or you do have an Options SymLinksIfOwnerMatch, Apache will need to issue extra system calls to check up on symlinks. (One extra call per filename component.) For example, if you had: DocumentRoot &amp;quot;/www/htdocs&amp;quot; &amp;lt;Directory &amp;quot;/&amp;quot;&amp;gt; Options SymLinksIfOwnerMatch &amp;lt;/Directory&amp;gt; and a request is made for the URI /index.html, then Apache will perform lstat(2) on /www, /www/htdocs, and /www/htdocs/index.html. The results of these lstats are never cached, so they will occur on every single request. If you really desire the symlinks security checking, you can do something like this: DocumentRoot &amp;quot;/www/htdocs&amp;quot; &amp;lt;Directory &amp;quot;/&amp;quot;&amp;gt; Options FollowSymLinks &amp;lt;/Directory&amp;gt; &amp;lt;Directory &amp;quot;/www/htdocs&amp;quot;&amp;gt; Options -FollowSymLinks +SymLinksIfOwnerMatch &amp;lt;/Directory&amp;gt;
  34. Wherever in your URL-space you do not have an Options FollowSymLinks, or you do have an Options SymLinksIfOwnerMatch, Apache will need to issue extra system calls to check up on symlinks. (One extra call per filename component.) For example, if you had: DocumentRoot &amp;quot;/www/htdocs&amp;quot; &amp;lt;Directory &amp;quot;/&amp;quot;&amp;gt; Options SymLinksIfOwnerMatch &amp;lt;/Directory&amp;gt; and a request is made for the URI /index.html, then Apache will perform lstat(2) on /www, /www/htdocs, and /www/htdocs/index.html. The results of these lstats are never cached, so they will occur on every single request. If you really desire the symlinks security checking, you can do something like this: DocumentRoot &amp;quot;/www/htdocs&amp;quot; &amp;lt;Directory &amp;quot;/&amp;quot;&amp;gt; Options FollowSymLinks &amp;lt;/Directory&amp;gt; &amp;lt;Directory &amp;quot;/www/htdocs&amp;quot;&amp;gt; Options -FollowSymLinks +SymLinksIfOwnerMatch &amp;lt;/Directory&amp;gt;