One place for hosting & domains

      Pasos recomendados para reforzar un servidor HTTP de Apache en FreeBSD 12.0


      El autor seleccionó la Free and Open Source Fund para recibir una donación como parte del programa Write for DOnations.

      Introducción

      Aunque la instalación predeterminada de un servidor HTTP Apache ya es segura, la configuración puede mejorar en gran medida con algunas modificaciones. Puede complementar los mecanismos de seguridad ya existentes, por ejemplo, estableciendo protecciones en torno a las cookies y los encabezados, de modo que las conexiones no se puedan manipular al nivel de cliente del usuario. Realizando esto puede reducir notablemente las posibilidades de exponerse a varios métodos de ataque, como los de secuencias de comandos entre sitios (también conocidos como XSS). También puede evitar otros tipos de ataques, como la falsificación de solicitudes entre sitios, los secuestros de sesiones o la denegación de servicios.

      A lo largo de este tutorial, implementará algunos pasos recomendados para reducir la cantidad de información expuesta en su servidor. Verificará los listados de directorios y desactivará la indexación para chequear el acceso a recursos. También cambiará el valor predeterminado de la directiva timeout para poder mitigar el tipo de ataque de denegación de servicio. Además, desactivará el método TRACE para que las sesiones no se puedan revocar ni secuestrar. Por último, protegerá los encabezados y las cookies.

      La mayoría de los ajustes de configuración se aplicarán al archivo de configuración principal del servidor HTTP Apache ubicado en /usr/local/etc/apache24/httpd.conf.

      Requisitos previos

      Para completar esta guía, necesitará lo siguiente:

      Una vez completados los requisitos previos tendrá un sistema de FreeBSD con una pila adicional capaz de proporcionar contenido web usando cualquier cosa escrita en PHP, como un software importante de CMS. Además, cifró conexiones seguras a través de Let´s Encrypt.

      Reducir la información del servidor

      El banner del sistema operativo es un método utilizado por computadoras, servidores y dispositivos de todo tipo para presentarse en las redes. Individuos malintencionados pueden usar esta información para obtener beneficios de explotación en los sistemas en cuestión. En esta sección, reducirá la cantidad de información publicada por este banner.

      En los conjuntos de directivas se controla la manera en la que se muestra esta información. Para esto, es importante la directiva ServerTokens; por defecto, muestra toda la información sobre el sistema operativo y los módulos compilados al cliente que establece conexión.

      Antes de aplicar cualquier cambio, usará una herramienta para escanear la red y verificar la información que se muestra actualmente. Para instalar nmap ejecute el siguiente comando:

      Para obtener la dirección IP de su servidor, puede ejecutar el siguiente comando:

      • ifconfig vtnet0 | awk '/inet / {print $2}'

      Puede verificar la respuesta del servidor web usando el siguiente comando:

      • nmap -sV -p 80 your-server-ip

      Invoca nmap para hacer un escaneo (por ello se usa el indicador -s), a fin de mostrar la versión (el indicador -V) en el puerto 80 (el indicador -p) en el IP o dominio determinado.

      Recibirá información sobre su servidor web similar a la siguiente:

      Output

      Starting Nmap 7.80 ( https://nmap.org ) at 2020-01-22 00:30 CET Nmap scan report for 206.189.123.232 Host is up (0.054s latency). PORT STATE SERVICE VERSION 80/tcp open http Apache httpd 2.4.41 ((FreeBSD) OpenSSL/1.1.1d-freebsd Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 7.59 seconds

      En el resultado se muestra que la información como la del sistema operativo, la versión del servidor HTTP Apache y OpenSSL es visible. Esto puede ser útil para que los atacantes obtengan información sobre el servidor y elijan las herramientas adecuadas para explotar, por ejemplo, una vulnerabilidad en el software que se ejecuta en el servidor.

      Disponga la directiva ServerTokens en el archivo de configuración principal, ya que no viene configurada por defecto. La falta de esta configuración hace que el servidor HTTP Apache muestre su información completa como se indica en la documentación. Para limitar la información que se muestra acerca de su servidor y configuración, dispondrá la directiva ServerTokens dentro del archivo de configuración principal.

      Dispondrá esta directiva después de la entrada de ServerName en el archivo de configuración. Ejecute el siguiente comando para encontrar la directiva:

      • grep -n 'ServerName' /usr/local/etc/apache24/httpd.conf

      Encontrará el número de línea que luego podrá buscar con vi:

      Output

      226 #ServerName www.example.com:80

      Ejecute el siguiente comando:

      • sudo vi +226 /usr/local/etc/apache24/httpd.conf

      Añada la siguiente línea resaltada:

      /usr/local/etc/apache24/httpd.conf

      . . .
      #ServerName www.example.com:80
      ServerTokens Prod
      

      Guarde y cierre el archivo con :wq e INTRO.

      Fijar la directiva ServerTokens en Prod hará que solo se muestre que este es un servidor web de Apache.

      Para que esto se implemente, reinicie el servidor HTTP Apache:

      Para probar los cambios, ejecute el siguiente comando:

      • nmap -sV -p 80 your-server-ip

      Verá un resultado similar al siguiente con la información mínima adicional acerca de su servidor web de Apache:

      Output

      Starting Nmap 7.80 ( https://nmap.org ) at 2020-01-22 00:58 CET Nmap scan report for WPressBSD (206.189.123.232) Host is up (0.056s latency). PORT STATE SERVICE VERSION 80/tcp open http Apache httpd Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 7.59 seconds

      Vio la información que se anunciaba en el servidor antes del cambio y ahora la redujo al mínimo. Con esto, proporcionará a un agente externo menos pistas acerca de su servidor. En el siguiente paso, administrará los listados de directorios para su servidor web.

      Administrar los listados de directorios

      En este paso, se asegurará de que el listado de directorios esté configurado correctamente para que las partes adecuadas del sistema estén disponibles públicamente como se espera, mientras el resto quede protegido.

      Nota: Cuando se declara un argumento, este está activo, pero el signo + puede reforzar por medios visuales la sugerencia de que efectivamente se encuentra habilitado. Cuando se dispone un signo menos - el argumento se niega; por ejemplo, Options -Indexes.

      Los argumentos con + o con - no se pueden mezclar, se consideran como elementos de mala sintaxis en el servidor HTTP Apache y se pueden rechazar al inicio.

      Añadir la instrucción Options -Indexes establecerá el contenido dentro de la ruta de datos /usr/local/www/apache24/data para no realizar la indexación (leer listado) de forma automática si no existe un archivo .html y no mostrar si una URL asigna este directorio. Esto también se aplicará al utilizar configuraciones de host virtuales como la que se emplea para el tutorial de requisitos previos para el certificado de Let´s Encrypt.

      Establecerá la directiva Options con el argumento -Indexes y con la directiva +FollowSymLinks, que permitirá el seguimiento de los enlaces simbólicos. Usará el símbolo + para cumplir con las convenciones HTTP de Apache.

      Ejecute el siguiente comando para encontrar la línea que editará en el archivo de configuración:

      • grep -n 'Options Indexes FollowSymLinks' /usr/local/etc/apache24/httpd.conf

      Visualizará un resultado similar al siguiente:

      Output

      263 : Options Indexes FollowSymLinks

      Ejecute este comando para acceder de manera directa a la línea para editar:

      • sudo vi +263 /usr/local/etc/apache24/httpd.conf

      Ahora, edite la línea conforme a la configuración:

      /usr/local/etc/apache24/httpd.conf

      . . .
      #
      Options -Indexes +FollowSymLinks
      
      #
      . . .
      

      Guarde y cierre el archivo con :wq e INTRO.

      Reinicie el servidor HTTP Apache para implementar estos cambios:

      En su dominio en el navegador, verá un mensaje de acceso prohibido, también conocido como el error 403. Esto se debe a los cambios que implementó. Con la disposición de -Indexes en la directiva Options se desactivó la capacidad de aplicar indexación de forma automática en el servidor HTTP Apache y, por lo tanto, no existe un archivo index.html dentro de la ruta de datos.

      Puede solucionar esto disponiendo un archivo index.html dentro del VirtualHost habilitado en el tutorial de requisitos previos para el certificado de Let´s Encrypt. Usará el bloque predeterminado dentro de HTTP Apache y lo dispondrá en la misma carpeta que el DocumentRoot que declaró en el host virtual.

      /usr/local/etc/apache24/extra/httpd-vhosts.conf

      <VirtualHost *:80>
          ServerAdmin your_email@your_domain.com
          DocumentRoot "/usr/local/www/apache24/data/your_domain.com"
          ServerName your_domain.com
          ServerAlias www.your_domain.com
          ErrorLog "/var/log/your_domain.com-error_log"
          CustomLog "/var/log/your_domain.com-access_log" common
      </VirtualHost>
      

      Para hacerlo utilice el siguiente comando:

      • sudo cp /usr/local/www/apache24/data/index.html /usr/local/www/apache24/data/your_domain.com/index.html

      Ahora, cuando visite su dominio verá un mensaje It works!

      En esta sección, estableció restricciones a la directiva Indexes para no escribir y mostrar de forma automática contenido diferente del que pretende. Si no existe un archivo index.html dentro de la ruta de datos, en el servidor HTTP Apache no se creará de manera automática un índice de contenidos. En el siguiente paso, irá más allá del ocultamiento de información y personalizará diferentes directivas.

      Reducir el valor de la directiva Timeout

      La directiva Timeout establece el límite de tiempo que el servidor HTTP Apache otorgará para nuevas entradas o salidas antes de que falle la solicitud de conexión. Esta falla puede producirse debido a diferentes circunstancias, como los casos en que los paquetes no llegan al servidor o el cliente no confirma como recibidos los datos.

      Por defecto, el tiempo de espera se fija en 60 segundos. En los entornos en los cuales el servicio de Internet es lento, este valor predeterminado puede ser razonable, pero un minuto es bastante tiempo; en particular, si el servidor abarca un grupo de usuarios con un servicio de Internet más rápido. Además, el tiempo durante el cual no se cierra la conexión en el servidor puede aprovecharse para ataques de denegación de servicio (DoS). Si se produce una sobrecarga de estas conexiones malintencionadas, el servidor se bloqueará, y posiblemente se saturará y no responderá.

      Para cambiar el valor encontrará las entradas de Timeout en el archivo httpd-default.conf:

      • grep -n 'Timeout' /usr/local/etc/apache24/extra/httpd-default.conf

      Verá un resultado similar al siguiente:

      Output

      8 # Timeout: The number of seconds before receives and sends time out. 10 Timeout 60 26 # KeepAliveTimeout: Number of seconds to wait for the next request from the 29 KeepAliveTimeout 5 89 RequestReadTimeout header=20-40,MinRate=500 body=20,MinRate=500

      En la línea de salida, se fija el valor de la directiva Timeout en 10. Para acceder directamente a esta línea, ejecute el siguiente comando:

      • sudo vi +10 /usr/local/etc/apache24/extra/httpd-default.conf

      La cambiará a 30 segundos, por ejemplo, como en el siguiente ejemplo:

      /usr/local/etc/apache24/extra/httpd-default.conf

      #
      # Timeout: The number of seconds before receives and sends time out.
      #
      Timeout 30
      

      Guarde y cierre el archivo con :wq e INTRO.

      En el valor de la directiva Timeout se debe equilibrar un rango de tiempo suficientemente extenso como para que estos eventos permitan que se establezca una conexión legítima y exitosa, pero suficientemente breve como para evitar los intentos de conexiones no deseadas.

      Nota: Los ataques de denegación de servicio pueden drenar los recursos del servidor de forma eficaz. Una medida complementaria y muy eficaz para contrarrestar esto consiste en usar un MPM anidado para obtener el mejor rendimiento en cuanto a la forma en que se manejan las conexiones y los procesos en el servidor HTTP Apache. En el tutorial Cómo configurar HTTP Apache con MPM Event y PHP-FPM en FreeBSD 12.0 se ofrecen pasos para habilitar esta capacidad.

      Para que este cambio tenga efecto, reinicie el servidor HTTP Apache:

      Cambió el valor predeterminado de la directiva Timeout para mitigar parcialmente los ataques de DoS.

      Deshabilitar el método TRACE

      El Protocolo de transferencia de hipertexto se desarrolló siguiendo un modelo de servidor y cliente y, como tal, en el protocolo existen métodos de solicitud para recuperar o disponer información desde el servidor o en él. El servidor debe interpretar estos conjuntos de métodos y la interacción entre ellos. En este paso, configurará los métodos básicos necesarios.

      El método TRACE, que se consideraba inofensivo, se aprovechó para realizar ataques de rastreo entre sitios. Este tipo de ataques permite a individuos malintencionados robar sesiones de los usuarios a través del método. El método se diseñó para la depuración a través del servidor devolviendo la misma solicitud originalmente enviada por el cliente. Debido a que la cookie de la sesión del navegador se envía al servidor, se enviará de regreso nuevamente. Sin embargo, un individuo malintencionado podría interceptar esto y luego redirigir la conexión de un navegador a un sitio bajo su control y no al servidor original.

      Debido a la posibilidad del mal uso que se puede dar al método TRACE, se recomienda usarlo únicamente para la depuración y no en la producción. En esta sección, desactivará este método.

      Edite el archivo httpd.conf con el siguiente comando y presione G para llegar al final del archivo:

      • sudo vi /usr/local/etc/apache24/httpd.conf

      Añada la siguiente ruta de entrada al final del archivo:

      /usr/local/etc/apache24/httpd.conf

      . . .
      TraceEnable off
      

      Se recomienda especificar únicamente los métodos que usará en su servidor web HTTP Apache. Esto ayudará a limitar los puntos de entrada potenciales para los individuos malintencionados.

      LimitExcept puede ser útil para este propósito, ya que no se permitirán otros métodos aparte de los declarados en este. Por ejemplo, puede establecer una configuración como la siguiente:

      /usr/local/etc/apache24/httpd.conf

      DocumentRoot "/usr/local/www/apache24/data"
      <Directory "/usr/local/www/apache24/data">
          Options -Indexes +FollowSymLinks -Includes
          AllowOverride none
           <LimitExcept GET POST HEAD>
             deny from all
          </LimitExcept>
          Require all granted
      </Directory>
      

      Como se declara en la directiva LimitExcept solo se permiten los métodos GET, POST y Head en la configuración.

      • El método GET es parte del protocolo HTTP y se utiliza para recuperar datos.
      • El método POST también es parte del protocolo HTTP y se utiliza para enviar datos al servidor.
      • El método HEAD es similar a GET. Sin embargo, no tiene cuerpo de respuesta.

      Usará el siguiente comando y dispondrá el bloque de LimitExcept dentro del archivo:

      • sudo vi +272 /usr/local/etc/apache24/httpd.conf

      Para establecer esta configuración, dispondrá el siguiente bloque en la entrada de la directiva DocumentRoot de donde se leerá el contenido, más específicamente dentro de la entrada Directory.

      /usr/local/etc/apache24/httpd.conf

      . . .
      <LimitExcept GET POST HEAD>
         deny from all
      </LimitExcept>
      . . .
      

      Para implementar los cambios, reinicie el servidor HTTP Apache:

      En la directiva más reciente AllowedMethods se proporciona una funcionalidad similar, aunque su estado es aún experimental.

      Vio los métodos HTTP, su uso y la protección que ofrecen contra la actividad malintencionada que se aprovecha del método TRACE, así como la forma de declarar los métodos que se usarán. A continuación, trabajará con más protecciones dedicadas a los encabezados y las cookies HTTP.

      Proteger los encabezados y las cookies

      En este paso, establecerá directivas específicas para proteger las sesiones que se abrirán en las máquinas cliente cuando visite su servidor web HTTP Apache. De esta manera, en su servidor no se cargará contenido no deseado, el cifrado no se degradará y evitará el espionaje de contenido.

      Los encabezados son componentes de los métodos de solicitudes. Existen encabezados para ajustar la autenticación, la comunicación entre el servidor y el cliente, el almacenamiento en caché y la negociación de contenido, entre otros aspectos.

      Las cookies son pequeños fragmentos de información que el servidor envía al navegador. Estos pequeños fragmentos permiten que en el servidor se reconozca el navegador del cliente de una computadora a otra. También permiten que en los servidores se reconozcan sesiones de usuarios. Por ejemplo, se puede hacer un seguimiento del carrito de compras de un usuario que inició sesión, la información de pago y el historial, entre otros datos. Las cookies se utilizan y se conservan en el navegador web del cliente, ya que HTTP es un protocolo sin estado; esto significa que cuando la conexión se cierra en el servidor no se registra la solicitud enviada por uno u otro cliente.

      Es importante proteger los encabezados y las cookies porque permiten la comunicación entre el cliente del navegador web y el servidor web.

      El módulo headers viene activado por defecto. Para verificar si está cargado, usará el siguiente comando:

      • sudo apachectl -M | grep 'headers'

      Verá el siguiente resultado:

      Output

      headers_module (shared)

      Si no ve un resultado, verifique si el módulo está activo dentro del archivo httpd.conf de Apache:

      • grep -n 'mod_headers' /usr/local/etc/apache24/httpd.conf

      Como resultado, verá una línea sin comentarios con referencia al módulo específico para encabezados:

      /usr/local/etc/apache24/httpd.conf

      . . .
      122  LoadModule headers_module libexec/apache24/mod_headers.so
      . . .
      

      Si está presente, elimine el hashtag al inicio de la línea mod_headers.so para activar la directiva.

      Usando las siguientes directivas HTTP de Apache, protegerá los encabezados y las cookies contra actividades malintencionadas para reducir el riesgo al que se exponen los clientes y los servidores.

      Ahora, configurará la protección del encabezado. Dispondrá todos estos valores de encabezado en un bloque. Puede optar por aplicar estos valores como lo desee, pero todos se recomiendan.

      Edite el archivo httpd.conf con el siguiente comando y presione G para llegar al final del archivo:

      • sudo vi /usr/local/etc/apache24/httpd.conf

      Disponga el siguiente bloque al final del archivo:

      /usr/local/etc/apache24/httpd.conf

      . . .
      <IfModule mod_headers.c>
        # Add security and privacy related headers
        Header set Content-Security-Policy "default-src 'self'; upgrade-insecure-requests;"
        Header set Strict-Transport-Security "max-age=31536000; includeSubDomains"
        Header always edit Set-Cookie (.*) "$1; HttpOnly; Secure"
        Header set X-Content-Type-Options "nosniff"
        Header set X-XSS-Protection "1; mode=block"
        Header set Referrer-Policy "strict-origin"
        Header set X-Frame-Options: "deny"
        SetEnv modHeadersAvailable true
      </IfModule>
      
      • Header set Strict-Transport-Security "max-age=31536000; includeSubDomains": la seguridad estricta de transporte de HTTP (HTSTS) es un mecanismo para que los servidores y clientes web (principalmente navegadores) establezcan comunicaciones utilizando solo HTTPS. Al implementar esto evitará la presencia de atacantes desconocidos, en cuyo caso un tercero en medio de la comunicación podría acceder a los fragmentos de información y manipularlos.

      • Header always edit Set-Cookie (. *) "$1; HttpOnly; Secure": los indicadores HttpOnly y Secure en los encabezados ayudan a prevenir las secuencias de comandos entre sitios, también conocidas como XSS. Los atacantes pueden utilizar las cookies de forma indebida para simular ser visitantes legítimos al presentarse como otras personas (robo de identidad), o para ser manipuladas.

      • Header set Referrer-Policy "strict-origin": en el encabezado Referrer-Policy se establece la información que se incluye como información de referencia en el campo de encabezado.

      • Header set Content-Security-Policy "default-src 'self'; upgrade-insecure-requests;": en el encabezado de Content-Security-Policy (CSP) se evitará por completo la carga de contenido que no esté especificada en los parámetros, lo cual es útil para evitar las secuencias de comandos en sitios cruzados (XSS). Existen muchos parámetros posibles para configurar la política de este encabezado. El objetivo final es configurarlo para cargar contenido del mismo sitio y actualizar cualquier contenido con un origen HTTP.

      • Header set X-XSS-Protection "1; mode=block": esto es compatible con navegadores antiguos en los que no se procesan encabezados Content-Security-Policy. En el encabezado ‘X-XSS-Protection’ se ofrece protección contra secuencias de comandos entre sitios. No necesita configurar este encabezado a menos que se necesite compatibilidad con versiones anteriores de navegadores, lo cual es poco común.

      • Header set X-Frame-Options: "deny": con esto se evitan ataques de clickjacking (secuestro de clics). En el encabezado ‘X-Frame-Options’ se indica a un navegador si una página se puede presentar en <frame>, <iframe>, <embed> o <object>. De esta manera, los contenidos de sitios diferentes no pueden integrarse a otros, lo cual previene los ataques de clickjacking. Aquí, niega toda la presentación de marco para que la página web no se pueda integrar en otro lugar, ni siquiera dentro del mismo sitio web. Puede adecuar esto a sus necesidades si, por ejemplo, debe autorizar la presentación de algunas páginas debido a que son anuncios o colaboraciones con sitios web específicos.

      • Header set X-Content-Type-Options "nosniff": en el encabezado ‘X-Content-Type-Options’ se controlan los tipos MIME para que no se sometan a cambios ni a seguimiento. Los tipos MIME son estándares de formatos de archivo; funcionan para texto, audio, video e imagen, entre otros. Con este encabezado se bloquean los intentos de espiar dichos archivos y modificar sus tipos por parte de individuos malintencionados.

      Ahora, reinicie Apache para implementar los cambios:

      Para evaluar los niveles de seguridad de sus configuraciones, consulte el sitio web de Security Headers. Después de seguir los pasos de este tutorial, la calificación de su dominio será A.

      Nota: Si evalúa sus encabezados visitando https://securityheaders.com/ y obtiene una calificación F, podría deberse a que index.html no se encuentra dentro del DocumentRoot de su sitio, como se indica al final del paso 2. Si cuando evalúa sus encabezados obtiene una calificación que no sea a A o sea F, revise cada línea Header set en busca de cualquier error ortográfico que pueda haber causado una calificación menor.

      En este paso, trabajó con hasta siete configuraciones para mejorar la seguridad de sus encabezados y cookies. Esto permitirá evitar las secuencias de comandos entre sitios, el clickjacking y otros tipos de ataques.

      Conclusión

      En este tutorial, se abordaron varios aspectos relacionados con la seguridad, desde la divulgación de información hasta la protección de las sesiones y el ajuste de parámetros de configuración alternativos para funciones importantes.

      Si desea obtener más información sobre el reforzamiento de Apache, a continuación se ofrecen algunas otras referencias:

      Si desea acceder a más herramientas para la protección del servidor HTTP Apache:

      • mod_evasive es una herramienta útil para ayudar a mitigar los ataques de DoS. Puede encontrar más información en el tutorial Cómo protegerse contra DoS y DDoS con mod_evasive para Apache.

      • freail2ban es un software de prevención de intrusiones que es útil para bloquear intentos de inicio de sesión repetidos por parte de usuarios no autorizados. Puede obtener más información acerca de esto en el tutorial Cómo proteger un servidor Apache con Fail2Ban.

      • ModSecurity es un Firewall de aplicación web (o WAF) y, como tal, ofrece una amplia variedad de posibilidades basada en reglas predefinidas escritas por SpyderLabs y miembros de la comunidad. Puede leer más acerca de esto en el tutorial Cómo configurar ModSecurity con Apache.



      Source link

      Рекомендованные меры для усиления безопасности Apache HTTP во FreeBSD 12.0


      Автор выбрал фонд Free and Open Source Fund для получения пожертвования в рамках программы Write for DOnations.

      Введение

      Хотя используемая по умолчанию установка сервера Apache HTTP безопасна для использования, ее конфигурацию можно значительно улучшить с помощью нескольких изменений. Вы можете дополнить уже существующие механизмы безопасности, например, настроив защиту для cookie-файлов и заголовков, чтобы подключения нельзя было перехватывать на уровне клиента пользователя. Благодаря этому вы сможете значительно снизить вероятность атак с использованием ряда методов, например, атаки с помощью межсайтового выполнения сценариев (XSS). Также вы можете предотвратить другие виды атак, в том числе подделку межсайтовых запросов, перехват сеанса, а также DoS-атаки.

      В этом обучающем руководстве мы реализуем некоторые рекомендуемые меры, которые помогут снизить видимость информации, размещенной на вашем сервере. Вы научитесь проверять списки директорий и отключать индексирование для проверки доступа к ресурсам. Также вы сможете изменять используемое по умолчанию значение директивы timeout для борьбы с последствиями DoS-атак. Кроме того, вы узнаете, как отключить метод TRACE, чтобы сеансы нельзя было переключить или взломать. А в конце вы научитесь обеспечивать безопасность заголовков и cookie-файлов.

      Большинство настроек конфигурации будет применяться для основного файла конфигурации Apache HTTP, расположенного по адресу /usr/local/etc/apache24/httpd.conf.

      Предварительные требования

      Для прохождения этого обучающего руководства вам потребуется следующее:

      Когда все необходимое будет у вас в распоряжении, вы получите систему FreeBSD со стеком, позволяющим обслуживать веб-контент с помощью любого ПО, написанного на PHP, например, популярных CMS-систем. За безопасность подключений будет отвечать Let’s Encrypt.

      Сокращение доступной информации о сервере

      Баннер операционной системы — это метод, используемый компьютерами, серверами и устройствами всех типов для представления информации о себе в сетях. Злоумышленники могут использовать эту информацию для применения эксплойтов в соответствующих системах. В этом разделе вы сможете сократить количество информации, которое содержит этот баннер.

      Набор директив контролирует то, как отображается эта информация. Для нашей цели самой важной директивой будет ServerTokens; по умолчанию она отображает все данные об операционной системе и скомпилированных модулях для клиента, который подключается к ней.

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

      Чтобы получить IP-адрес вашего сервера, вы можете воспользоваться следующей командой:

      • ifconfig vtnet0 | awk '/inet / {print $2}'

      Для проверки ответа веб-сервера используйте следующую команду:

      • nmap -sV -p 80 your-server-ip

      Вызовите nmap для выполнения сканирования (используйте флаг -s), для вывода версии (используйте флаг -V) на порту 80 (используйте флаг -p) на указанном IP-адресе или домене.

      Вы получите информацию о вашем веб-сервере примерно в следующем виде:

      Output

      Starting Nmap 7.80 ( https://nmap.org ) at 2020-01-22 00:30 CET Nmap scan report for 206.189.123.232 Host is up (0.054s latency). PORT STATE SERVICE VERSION 80/tcp open http Apache httpd 2.4.41 ((FreeBSD) OpenSSL/1.1.1d-freebsd Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 7.59 seconds

      Данный вывод показывает, что такая информация, как операционная система, версия Apache HTTP и OpenSSL, является видимой. Она может использоваться злоумышленниками для получения данных о сервере и выбора необходимых инструментов для использования уязвимостей, например, уязвимостей установленного на сервере ПО.

      Добавьте директиву ServerTokens в основной файл конфигурации, поскольку она не настроена по умолчанию. Отсутствие такой настройки заставляет Apache HTTP отображать полную информацию о сервере согласно требованиям документации. Чтобы ограничить объем отображаемой информации о вашем сервере и конфигурации, поместите директиву ServerTokens в основной файл конфигурации.

      Добавьте эту директиву после записи ServerName в файле конфигурации. Запустите следующую команду для поиска директивы:

      • grep -n 'ServerName' /usr/local/etc/apache24/httpd.conf

      Вы получите номер строки, которую затем сможете найти с помощью vi:

      Output

      226 #ServerName www.example.com:80

      Запустите следующую команду:

      • sudo vi +226 /usr/local/etc/apache24/httpd.conf

      Затем добавьте следующую выделенную строку:

      /usr/local/etc/apache24/httpd.conf

      . . .
      #ServerName www.example.com:80
      ServerTokens Prod
      

      Сохраните и закройте файл, введя :wq и нажав ENTER.

      Если для директивы ServerTokens указано значение Prod, она будет отображать только информацию о том, что это веб-сервер Apache.

      Чтобы изменения вступили в силу, перезапустите сервер Apache HTTP:

      Чтобы протестировать изменения, запустите следующую команду:

      • nmap -sV -p 80 your-server-ip

      Вывод будет выглядеть примерно следующим образом и содержать более сжатую информацию о веб-сервере Apache:

      Output

      Starting Nmap 7.80 ( https://nmap.org ) at 2020-01-22 00:58 CET Nmap scan report for WPressBSD (206.189.123.232) Host is up (0.056s latency). PORT STATE SERVICE VERSION 80/tcp open http Apache httpd Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 7.59 seconds

      Вы видели, какая информация о сервере отображалась до внесения изменений, а сейчас мы смогли сократить ее количество до минимума. Благодаря этому вы предоставляете меньше данных о вашем сервере сторонним акторам. На следующем шаге вы научитесь управлять списками директорий вашего веб-сервера.

      Управление списками директорий

      На этом шаге вы сможете убедиться, что список директорий настроен корректно, поэтому необходимые части системы доступны публично, а остальная часть закрыта.

      Примечание. Когда аргумент объявляется, он становится активен, но символ + может визуально подтверждать, что он активен. Использование знака минус - говорит о том, что аргумент отклонен, например, Options -Indexes.

      Аргументы со знаками + и/или - нельзя смешивать, подобная конструкция считается некорректным синтаксисом в Apache HTTP и может быть отклонена при запуске.

      Добавление оператора Options -Indexes​​​ отключает индексирование контента внутри пути /usr/local/www/apache24/data (read listed) автоматически, если файл .html отсутствует, и запрещает отображение, если URL видит эту директорию. Также подобная практика будет применяться при использовании конфигураций виртуального хоста, например, хоста, используемого согласно предварительным требованиям для размещения сертификата Let’s Encrypt.

      Вы задаете для директивы Options аргумент -Indexes и используете директиву +FollowSymLinks, которая позволит использовать символьные ссылки. Вы должны также воспользоваться символом + для соблюдения конвенций Apache HTTP.

      Запустите следующую команду для получения строки для редактирования в файле конфигурации:

      • grep -n 'Options Indexes FollowSymLinks' /usr/local/etc/apache24/httpd.conf

      Результат будет выглядеть примерно так:

      Output

      263 : Options Indexes FollowSymLinks

      Запустите следующую команду для прямого доступа к строке для редактирования:

      • sudo vi +263 /usr/local/etc/apache24/httpd.conf

      Теперь вы можете изменить строку согласно желаемой конфигурации:

      /usr/local/etc/apache24/httpd.conf

      . . .
      #
      Options -Indexes +FollowSymLinks
      
      #
      . . .
      

      Сохраните и закройте файл, введя :wq и нажав ENTER.

      Перезапустите Apache HTTP для вступления изменений в силу:

      В браузере при попытке входа на домен вы увидите сообщение о запрете доступа (ошибку 403). Это результат внесенных вами изменений. Добавление -Indexes в директиву Options позволило отключить автоматическое индексирование Apache HTTP, в результате чего файл index.html по указанному пути отсутствует.

      Вы можете решить эту проблему, разместив файл index.html внутри виртуального хоста (VirtualHost), который вы активировали согласно предварительным требованиям для использования сертификата Let’s Encrypt. Вам нужно будет воспользоваться блоком по умолчанию внутри Apache HTTP и разместить его в той же папке, что и DocumentRoot, объявленный в виртуальном хосте.

      /usr/local/etc/apache24/extra/httpd-vhosts.conf

      <VirtualHost *:80>
          ServerAdmin your_email@your_domain.com
          DocumentRoot "/usr/local/www/apache24/data/your_domain.com"
          ServerName your_domain.com
          ServerAlias www.your_domain.com
          ErrorLog "/var/log/your_domain.com-error_log"
          CustomLog "/var/log/your_domain.com-access_log" common
      </VirtualHost>
      

      Для этого используйте следующую команду:

      • sudo cp /usr/local/www/apache24/data/index.html /usr/local/www/apache24/data/your_domain.com/index.html

      Теперь вы должны увидеть сообщение It works! при посещении вашего домена.

      В этом разделе вы добавили ограничения для директивы Indexes и запретили автоматическое включение в список и отображение контента, за исключением того, который вы опубликовали намеренно. Теперь, если файл index.html отсутствует внутри пути данных, Apache HTTP не будет автоматически создавать индекс содержимого. На следующем шаге мы перейдем к дальнейшему сокрытию данных и настроим другие директивы.

      Снижение значения директивы Timeout

      Директива Timeout задает лимит времени, в течение которого Apache HTTP будет ждать нового ввода/вывода, прежде чем отклонять запрос подключения. Такие проблемы могут возникать в силу разных обстоятельств, например, в случае, если пакеты не будут поступать на сервер или данные не будут подтверждены как полученные клиентом.

      По умолчанию для директивы timeout задается значение 60 секунд. В условиях медленного подключения к Интернету такое значение по умолчанию может быть разумным, но одна минута — это довольно долго, особенно если сервер обслуживает пользователей с быстрым доступом в Интернет. Кроме того, время, когда сервер не закрывает соединение, может быть использовано для совершения DoS-атак. При большом количестве злонамеренных подключений сервер может не справляться, а его работа может замедляться.

      Чтобы изменить значение, найдите записи Timeout в файле httpd-default.conf:

      • grep -n 'Timeout' /usr/local/etc/apache24/extra/httpd-default.conf

      Вывод будет выглядеть примерно следующим образом:

      Output

      8 # Timeout: The number of seconds before receives and sends time out. 10 Timeout 60 26 # KeepAliveTimeout: Number of seconds to wait for the next request from the 29 KeepAliveTimeout 5 89 RequestReadTimeout header=20-40,MinRate=500 body=20,MinRate=500

      В строке вывода 10 задается значение директивы Timeout. Чтобы получить доступ к этой строке, запустите следующую команду:

      • sudo vi +10 /usr/local/etc/apache24/extra/httpd-default.conf

      Вы должны изменить значение на 30 секунд, например, следующим образом:

      /usr/local/etc/apache24/extra/httpd-default.conf

      #
      # Timeout: The number of seconds before receives and sends time out.
      #
      Timeout 30
      

      Сохраните и закройте файл, введя :wq и нажав ENTER.

      Значение директивы Timeout должно обеспечивать баланс между временем, достаточно долгим, чтобы создавать надежные и успешные подключения, но достаточно коротким, чтобы не допустить нежелательных попыток подключения.

      Примечание. DoS-атаки могут очень легко истощать все ресурсы сервера. Дополнительной и очень эффективной контрмерой является использование поточного MPM для достижения наилучших результатов работы Apache HTTP с подключениями и процессами. В руководстве Настройка Apache HTTP с MPM Event и PHP-FPM во FreeBSD 12.0 описаны шаги для активации этой возможности.

      Чтобы изменения вступили в силу, перезапустите сервер Apache HTTP:

      Вы изменили значение директивы Timeout по умолчанию для частичного смягчения последствий DoS-атак.

      Отключение метода TRACE

      Гипертекстовый транспортный протокол был разработан в соответствии с моделью клиент-сервер, и как таковой этот протокол имеет методы для получения или размещения информации от сервера и на сервере. Сервер должен понимать эти наборы методов и взаимодействие между ними. На этом шаге вы настроите минимальный набор необходимых методов.

      Метод TRACE, который считался безвредным, стал инструментом для совершения атак с помощью межсайтового отслеживания. Атаки такого типа позволяют злоумышленникам красть сеансы пользователя с помощью этого метода. Метод был создан для отладки, когда сервер возвращает тот же запрос, который первоначально отправляется клиентом. Поскольку cookie из сеанса браузера отправляются на сервер, они будут отправлены обратно. Однако эти cookie могут быть перехвачены злоумышленником, который затем может перенаправлять соединение браузера на находящийся под его контролем сайт, а не на оригинальный сервер.

      Из-за подобной возможности злонамеренного использования метода TRACE рекомендуется использовать его только в процессе отладки, не допуская в продакшен. В этом разделе вы отключите этот метод.

      Откройте файл httpd.conf с помощью следующей команды и нажмите G, чтобы перейти в самый конец файла:

      • sudo vi /usr/local/etc/apache24/httpd.conf

      Добавьте следующий путь входа в конце файла:

      /usr/local/etc/apache24/httpd.conf

      . . .
      TraceEnable off
      

      Рекомендуется использовать только методы, которые вы будете использовать в вашем веб-сервере Apache HTTP. Это позволит ограничить потенциальные точки входа для злоумышленников.

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

      /usr/local/etc/apache24/httpd.conf

      DocumentRoot "/usr/local/www/apache24/data"
      <Directory "/usr/local/www/apache24/data">
          Options -Indexes +FollowSymLinks -Includes
          AllowOverride none
           <LimitExcept GET POST HEAD>
             deny from all
          </LimitExcept>
          Require all granted
      </Directory>
      

      Как указано в директиве LimitExcept, в данной конфигурации допускаются только методы GET, POST и HEAD.

      • Метод GET является частью протокола HTTP и используется для получения данных.
      • Метод POST также является частью протокола HTTP и используется для отправки данных на сервер.
      • Метод HEAD похож на GET, но не имеет код для отправки ответа.

      Вы должны будете воспользоваться следующей командой и разместить блок LimitExcept внутри файла:

      • sudo vi +272 /usr/local/etc/apache24/httpd.conf

      Чтобы настроить конфигурацию, вы должны разместить следующий блок в строке директивы DocumentRoot, откуда будет считываться содержимое, а именно внутрь записи Directory:

      /usr/local/etc/apache24/httpd.conf

      . . .
      <LimitExcept GET POST HEAD>
         deny from all
      </LimitExcept>
      . . .
      

      Чтобы применить изменения, перезапустите Apache HTTP:

      Новая версия директивы AllowedMethods предоставляет аналогичный функционал, хотя она пока используется в экспериментальном порядке.

      Вы увидели, что такое методы HTTP, порядок их использования и защиту от злоумышленников, которую они обеспечивают, на примере метода TRACE, а также процесс объявления того, какие методы разрешено использовать. Далее вам предстоит поработать над дополнительными мерами защиты для HTTP-заголовков и cookie-файлов.

      На этом шаге вы настроите конкретные директивы для защиты сеансов, которые будут создавать клиентские устройства при посещении вашего веб-сервера Apache HTTP. Таким образом ваш сервер не будет загружать нежелательный контент, средства шифрования не пострадают, а вы не станете жертвой отслеживания контента.

      Заголовки — это компоненты методов запроса. Существует заголовки для настройки аутентификации, связи между сервером и клиентом, кэширования, согласования содержимого и т. д.

      Cookie — это элементы информации, передаваемые сервером в браузер. Эти элементы позволяют серверу распознавать браузер клиента на разных компьютерах. Также они позволяют серверам распознавать сеансы пользователя. Например, они могут отслеживать корзину покупок зарегистрированного пользователя, платежную информацию, историю и т. д. Cookie-файлы используются и хранятся в браузере клиента, поскольку HTTP — это протокол без состояния, что означает, что после закрытия соединения сервер не запоминает запрос, отправленный тем или иным клиентом.

      Важно обеспечить защиту заголовков, а также cookie-файлов, поскольку они обеспечивают связь между веб-браузером клиента и веб-сервером.

      Модуль headers активирован по умолчанию. Чтобы убедиться, что он загружен, вы должны воспользоваться следующей командой:

      • sudo apachectl -M | grep 'headers'

      Вывод должен выглядеть так:

      Output

      headers_module (shared)

      Если вы не получили какого-либо результата, проверьте, включен ли модуль в файл Apache httpd.conf:

      • grep -n 'mod_headers' /usr/local/etc/apache24/httpd.conf

      В выводе вы должны увидеть незакомментированную строку, которая будет указывать на конкретный модуль для заголовков:

      /usr/local/etc/apache24/httpd.conf

      . . .
      122  LoadModule headers_module libexec/apache24/mod_headers.so
      . . .
      

      Удалите хэштег в начале строки mod_headers.so, если он присутствует, чтобы активировать директиву.

      Используя следующие директивы Apache HTTP, вы сможете защитить заголовки и cookie от вредоносной активности, а также снизить возможные риски для клиентов и серверов.

      Теперь вы можете настроить защиту заголовка. Необходимо разместить все эти значения заголовка в одном блоке. Вы можете указывать любые значения, но рекомендуется использовать их все.

      Откройте файл httpd.conf с помощью следующей команды и нажмите G, чтобы перейти в самый конец файла:

      • sudo vi /usr/local/etc/apache24/httpd.conf

      Добавьте следующий блок в конце файла:

      /usr/local/etc/apache24/httpd.conf

      . . .
      <IfModule mod_headers.c>
        # Add security and privacy related headers
        Header set Content-Security-Policy "default-src 'self'; upgrade-insecure-requests;"
        Header set Strict-Transport-Security "max-age=31536000; includeSubDomains"
        Header always edit Set-Cookie (.*) "$1; HttpOnly; Secure"
        Header set X-Content-Type-Options "nosniff"
        Header set X-XSS-Protection "1; mode=block"
        Header set Referrer-Policy "strict-origin"
        Header set X-Frame-Options: "deny"
        SetEnv modHeadersAvailable true
      </IfModule>
      
      • Header set Strict-Transport-Security "max-age=31536000; includeSubDomains": строгая безопасность передачи информации по протоколу HTTP (HTTP Strict Transport Security, HTSTS) — это используемый веб-серверами и клиентами (в основном браузерами) механизм коммуникации строго с помощью HTTPS. С помощью этого метода вы сможете избежать атак через посредника, когда третья сторона в процессе коммуникации может получить доступ к битам, а также вскрыть их.

      • Header always edit Set-Cookie (. *) "$1; HttpOnly; Secure":`флагиHttpOnlyиSecure` в заголовках помогают предотвратить атаки с использованием межсайтового выполнения сценариев (XSS). Cookie-файлы могут использоваться злоумышленниками, которые представляются кем-то другим (кража личности), или похищаться.

      • Header set Referrer-Policy "strict-origin": заголовок Referrer-Policy указывает, какая информация указывается в качестве информации об источнике ссылки в поле заголовка.

      • Header set Content-Security-Policy "default-src 'self'; upgrade-insecure-requests;": заголовок Content-Security-Policy (CSP) позволяет практически полностью предотвратить загрузку контента, не указанного в параметрах, что очень полезно для предотвращения атак с использованием межсайтового выполнения сценариев (XSS). Существует множество возможных параметров для настройки политики для этого заголовка. В целом необходимо настроить его для загрузки контента из одного сайта и обновления любого контента с происхождением из HTTP.

      • Header set X-XSS-Protection "1; mode=block": данный заголовок поддерживает старые браузеры, которые не работают с заголовками Content-Security-Policy. Заголовок ‘X-XSS-Protection’ обеспечивает защиту от атак с использованием межсайтового выполнения сценариев. Вам не нужно задавать этот заголовок, если только вам не нужно поддерживать старые версии браузера, что бывает очень редко.

      • Header set X-Frame-Options: "deny": предотвращение атак с использованием кликджекинга. Заголовок ‘X-Frame-Options’ говорит браузеру, может ли страница отображаться в <frame>, <iframe>, <embed> или <object>. Таким образом содержимое других сайтов не может быть встроено в другие сайты, что не позволяет выполнять атаки с использованием кликджекинга. Здесь вы запрещаете любое отображение во фрейме, чтобы веб-страница не могла быть встроена куда-либо еще, даже внутри одного веб-сайта. Вы можете изменить эту настройку согласно вашим потребностям, если, например, вам нужно разрешить отображение некоторых страниц, в частности, рекламных публикаций или взаимодействие с конкретными веб-сайтами.

      • Header set X-Content-Type-Options "nosniff": заголовок ‘X-Content-Type-Options’ контролирует типы MIME, запрещая их изменение или выполнение. Типы MIME — это стандарты формата файлов; они работают для текста, аудио, видео, изображений и т. д. Эти блоки заголовков не дают злоумышленникам получать информацию об этих файлах и пытаться изменить типы файлов.

      Перезапустите Apache для вступления изменений в силу:

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

      Примечание. Если в результате проверки заголовков на сайте https://securityheaders.com/ вы получили оценку F, причиной этому может быть отсутствие index.html внутри DocumentRoot вашего сайта, как указано в конце шага 2. Если в результате проверки вы получили любую оценку, кроме A и F, еще раз проверьте каждый набор заголовков на наличие опечаток, которые могли привести к снижению оценки.

      На этом шаге мы поработали с семью настройками для повышения безопасности заголовков и cookie-файлов. Эти действия помогут предотвратить межсайтовое выполнение сценариев, кликджекинг и другие типы атак.

      Заключение

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

      Дополнительную информацию о ресурсах или методах повышения безопасности Apache можно найти по этим ссылкам:

      Дополнительные инструменты для защиты Apache HTTP:

      • mod_evasive — полезный инструмент для смягчения последствий DoS-атак. Дополнительную информацию см. в статье Защита от DoS и DDoS с помощью mod_evasive в руководстве по работе с Apache.

      • fail2ban — это программное обеспечение для предотвращения повторных попыток входа в систему несанкционированных пользователей. Дополнительную информацию см. в руководстве Защита сервера Apache с помощью Fail2Ban.

      • ModSecurity — это брандмауэр веб-приложения (или WAF), который предоставляет широкий диапазон возможностей на основе предварительно заданных правил, написанный SpyderLabs и участниками сообщества. Дополнительную информацию об этом инструменте см. в руководстве Настройка ModSecurity в Apache.



      Source link

      Recommended Steps To Harden Apache HTTP on FreeBSD 12.0


      The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Although the default installation of an Apache HTTP server is already safe to use, its configuration can be substantially improved with a few modifications. You can complement already present security mechanisms, for example, by setting protections around cookies and headers, so connections can’t be tampered with at the user’s client level. By doing this you can dramatically reduce the possibilities of several attack methods, like Cross-Site Scripting attacks (also known as XSS). You can also prevent other types of attacks, such as Cross-Site Request Forgery, or session hijacking, as well as Denial of Service attacks.

      In this tutorial you’ll implement some recommended steps to reduce how much information on your server is exposed. You will verify the directory listings and disable indexing to check the access to resources. You’ll also change the default value of the timeout directive to help mitigate Denial of Service type of attacks. Furthermore you’ll disable the TRACE method so sessions can’t be reversed and hijacked. Finally you’ll secure headers and cookies.

      Most of the configuration settings will be applied to the Apache HTTP main configuration file found at /usr/local/etc/apache24/httpd.conf.

      Prerequisites

      Before you begin this guide you’ll need the following:

      With the prerequisites in place you have a FreeBSD system with a stack on top able to serve web content using anything written in PHP, such as major CMS software. Furthermore, you’ve encrypted safe connections through Let’s Encrypt.

      Reducing Server Information

      The operating system banner is a method used by computers, servers, and devices of all kinds to present themselves into networks. Malicious actors can use this information to gain exploits into the relevant systems. In this section you’ll reduce the amount of information published by this banner.

      Sets of directives control how this information is displayed. For this purpose the ServerTokens directive is important; by default it displays all details about the operating system and compiled modules to the client that’s connecting to it.

      You’ll use a tool for network scanning to check what information is currently revealed prior to applying any changes. To install nmap run the following command:

      To get your server’s IP address, you can run the following command:

      • ifconfig vtnet0 | awk '/inet / {print $2}'

      You can check the web server response by using the following command:

      • nmap -sV -p 80 your-server-ip

      You invoke nmap to make a scan (hence the -s flag), to display the version (the -V flag) on port 80 (the -p flag) on the given IP or domain.

      You’ll receive information about your web server, similar to the following:

      Output

      Starting Nmap 7.80 ( https://nmap.org ) at 2020-01-22 00:30 CET Nmap scan report for 206.189.123.232 Host is up (0.054s latency). PORT STATE SERVICE VERSION 80/tcp open http Apache httpd 2.4.41 ((FreeBSD) OpenSSL/1.1.1d-freebsd Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 7.59 seconds

      This output shows that information such as the operating system, the Apache HTTP version, and OpenSSL are visible. This can be useful for attackers to gain information about the server and choose the right tools to exploit, for example, a vulnerability in the software running on the server.

      You’ll place the ServerTokens directive in the main configuration file since it doesn’t come configured by default. The lack of this configuration makes Apache HTTP display the full information about the server as the documentation states. To limit the information that is revealed about your server and configuration, you’ll place the ServerTokens directive inside the main configuration file.

      You’ll place this directive following the ServerName entry in the configuration file. Run the following command to find the directive

      • grep -n 'ServerName' /usr/local/etc/apache24/httpd.conf

      You’ll find the line number that you can then search with vi:

      Output

      226 #ServerName www.example.com:80

      Run the following command:

      • sudo vi +226 /usr/local/etc/apache24/httpd.conf

      Add the following highlighted line:

      /usr/local/etc/apache24/httpd.conf

      . . .
      #ServerName www.example.com:80
      ServerTokens Prod
      

      Save and exit the file with :wq and ENTER.

      Setting the ServerTokens directive to Prod will make it only display that this is an Apache web server.

      For this to take effect restart the Apache HTTP server:

      To test the changes, run the following command:

      • nmap -sV -p 80 your-server-ip

      You’ll see similar output to the following with more minimal information on your Apache web server:

      Output

      Starting Nmap 7.80 ( https://nmap.org ) at 2020-01-22 00:58 CET Nmap scan report for WPressBSD (206.189.123.232) Host is up (0.056s latency). PORT STATE SERVICE VERSION 80/tcp open http Apache httpd Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 7.59 seconds

      You’ve seen what information the server was announcing prior to the change and you’ve now reduced this to the minimum. With this you’re providing fewer clues about your server to an external actor. In the next step you’ll manage the directory listings for your web server.

      Managing Directory Listings

      In this step you’ll ensure the directory listing is correctly configured, so the right parts of the system are publicly available as intended, while the remainder are protected.

      Note: When an argument is declared it is active, but the + can visually reinforce it is in fact enabled. When a minus sign - is placed the argument is denied, for example, Options -Indexes.

      Arguments with + and/or - can not be mixed, it is considered bad syntax in Apache HTTP and it may be rejected at the start up.

      Adding the statement Options -Indexes will set the content inside the data path /usr/local/www/apache24/data to not index (read listed) automatically if an .html file doesn’t exist, and not show if a URL maps this directory. This will also apply when using virtual host configurations such as the one used for the prerequisite tutorial for the Let’s Encrypt certificate.

      You will set the Options directive with the -Indexes argument and with the +FollowSymLinks directive, which will allow symbolic links to be followed. You’ll use the + symbol in order to comply with Apache’s HTTP conventions.

      Run the following command to find the line to edit in the configuration file:

      • grep -n 'Options Indexes FollowSymLinks' /usr/local/etc/apache24/httpd.conf

      You’ll see output similar to the following:

      Output

      263 : Options Indexes FollowSymLinks

      Run this command to directly access the line for editing:

      • sudo vi +263 /usr/local/etc/apache24/httpd.conf

      Now edit the line as per the configuration:

      /usr/local/etc/apache24/httpd.conf

      . . .
      #
      Options -Indexes +FollowSymLinks
      
      #
      . . .
      

      Save and exit the file with :wq and ENTER.

      Restart Apache HTTP to implement these changes:

      At your domain in the browser, you’ll see a forbidden access message, also known as the 403 error. This is due to the changes you’ve applied. Placing -Indexes into the Options directive has disabled the auto-index capability of Apache HTTP and therefore there’s no index.html file inside the data path.

      You can solve this by placing an index.html file inside the VirtualHost you enabled in the prerequisite tutorial for the Let’s Encrypt certificate. You’ll use the default block within Apache HTTP and place it in the same folder as the DocumentRootthat you declared in the virtual host.

      /usr/local/etc/apache24/extra/httpd-vhosts.conf

      <VirtualHost *:80>
          ServerAdmin your_email@your_domain.com
          DocumentRoot "/usr/local/www/apache24/data/your_domain.com"
          ServerName your_domain.com
          ServerAlias www.your_domain.com
          ErrorLog "/var/log/your_domain.com-error_log"
          CustomLog "/var/log/your_domain.com-access_log" common
      </VirtualHost>
      

      Use the following command to do this:

      • sudo cp /usr/local/www/apache24/data/index.html /usr/local/www/apache24/data/your_domain.com/index.html

      Now you’ll see an It works! message when visiting your domain.

      In this section you’ve placed restrictions to the Indexes directive to not automatically enlist and display content other than what you intend. Now if there is not an index.html file inside the data path Apache HTTP will not automatically create an index of contents. In the next step you’ll move beyond obscuring information and customize different directives.

      Reducing the Timeout Directive Value

      The Timeout directive sets the limit of time Apache HTTP will wait for new input/output before failing the connection request. This failure can occur due to different circumstances such as packets not arriving to the server or data not being confirmed as received by the client.

      By default the timeout is set to 60 seconds. In environments where the internet service is slow this default value may be sensible, but one minute is quite a long time particularly if the server is covering a target of users with faster internet service. Furthermore the time during which the server is not closing the connection can be abused to perform Denial of Service attacks (DoS). If a flood of these malicious connections occurs the server will stumble and possibly become saturated and irresponsive.

      To change the value you’ll find the Timeout entries in the httpd-default.conf file:

      • grep -n 'Timeout' /usr/local/etc/apache24/extra/httpd-default.conf

      You’ll see similar output to:

      Output

      8 # Timeout: The number of seconds before receives and sends time out. 10 Timeout 60 26 # KeepAliveTimeout: Number of seconds to wait for the next request from the 29 KeepAliveTimeout 5 89 RequestReadTimeout header=20-40,MinRate=500 body=20,MinRate=500

      In the output line 10 sets the Timeout directive value. To directly access this line run the following command:

      • sudo vi +10 /usr/local/etc/apache24/extra/httpd-default.conf

      You’ll change it to 30 seconds, for example, like the following:

      /usr/local/etc/apache24/extra/httpd-default.conf

      #
      # Timeout: The number of seconds before receives and sends time out.
      #
      Timeout 30
      

      Save and exit the file with :wq and ENTER.

      The value of the Timeout directive has to balance a time range large enough for those events to allow a legitimate and successful connection to happen, but short enough to prevent undesired connection attempts.

      Note: Denial of Service attacks can drain the server’s resources quite effectively. A complementary and very capable counter measure is using a threaded MPM to get the best performance out of how Apache HTTP handles connections and processes. In this tutorial How To Configure Apache HTTP with MPM Event and PHP-FPM on FreeBSD 12.0 there are steps on enabling this capability.

      For this change to take effect restart the Apache HTTP server:

      You’ve changed the default value of the Timeout directive in order to partially mitigate DoS attacks.

      Disabling the TRACE method

      The Hypertext Transport Protocol was developed following a client-server model and as such, the protocol has request methods to retrieve or place information from/to the server. The server needs to understand these sets of methods and the interaction between them. In this step you’ll configure the minimum necessary methods.

      TheTRACE method, which was considered harmless, was leveraged to perform Cross Site Tracing attacks. These types of attacks allow malicious actors to steal user sessions through that method. The method was designed for debugging purposes by the server returning the same request originally sent by the client. Because the cookie from the browser’s session is sent to the server it will be sent back again. However, this could potentially be intercepted by a malicious actor, who can then redirect a browser’s connection to a site of their control and not to the original server.

      Because of the possibility of the misuse of the TRACE method it is recommended to only use it for debugging and not in production. In this section you’ll disable this method.

      Edit the httpd.conf file with the following command and then press G to reach the end of the file:

      • sudo vi /usr/local/etc/apache24/httpd.conf

      Add the following entry path at the end of the file:

      /usr/local/etc/apache24/httpd.conf

      . . .
      TraceEnable off
      

      A good practice is to only specify the methods you’ll use in your Apache HTTP web server. This will help limit potential entry points for malicious actors.

      LimitExcept can be useful for this purpose since it will not allow any other methods than those declared in it. For example a configuration can be established like this one:

      /usr/local/etc/apache24/httpd.conf

      DocumentRoot "/usr/local/www/apache24/data"
      <Directory "/usr/local/www/apache24/data">
          Options -Indexes +FollowSymLinks -Includes
          AllowOverride none
           <LimitExcept GET POST HEAD>
             deny from all
          </LimitExcept>
          Require all granted
      </Directory>
      

      As declared within the LimitExcept directive only the GET, POST, and HEAD methods are allowed in the configuration.

      • The GET method is part of the HTTP protocol and it is used to retrieve data.
      • The POST method is also part of the HTTP protocol and is used to send data to the server.
      • The HEAD method is similar to GET, however this has no response body.

      You’ll use the following command and place the LimitExcept block inside the file:

      • sudo vi +272 /usr/local/etc/apache24/httpd.conf

      To set this configuration you’ll place the following block into the DocumentRoot directive entry where the content will be read from, more specifically inside the Directory entry:

      /usr/local/etc/apache24/httpd.conf

      . . .
      <LimitExcept GET POST HEAD>
         deny from all
      </LimitExcept>
      . . .
      

      To apply the changes restart Apache HTTP:

      The newer directive AllowedMethods provides similar functionality, although its status is still experimental.

      You’ve seen what HTTP methods are, their use, and the protection they offer from malicious activity leveraging the TRACE method as well as how to declare what methods to use. Next you’ll work with further protections dedicated to HTTP headers and cookies.

      Securing Headers and Cookies

      In this step you’ll set specific directives to protect the sessions that the client machines will open when visiting your Apache HTTP web server. This way your server will not load unwanted content, encryption will not be downgraded, and you’ll avoid content sniffing.

      Headers are components of the requests methods. There are headers to adjust authentication, communication between server and client, caching, content negotiation, and so on.

      Cookies are bits of information sent by the server to the browser. These bits allow the server to recognize the client browser from one computer to another. They also allow servers to recognize user sessions. For example, they can track a shopping cart of a logged-in user, payment information, history, and so on. Cookies are used and retained in the client’s web browser since HTTP is a stateless protocol, meaning once the connection closes the server does not remember the request sent by one client, or another one.

      It is important to protect headers as well as cookies because they provide communication between the web browser client and the web server.

      The headers module comes activated by default. To check if it’s loaded you’ll use the following command:

      • sudo apachectl -M | grep 'headers'

      You’ll see the following output:

      Output

      headers_module (shared)

      If you don’t see any output, check if the module is activated inside Apache’s httpd.conf file:

      • grep -n 'mod_headers' /usr/local/etc/apache24/httpd.conf

      As output you’ll see an uncommented line referring to the specific module for headers:

      /usr/local/etc/apache24/httpd.conf

      . . .
      122  LoadModule headers_module libexec/apache24/mod_headers.so
      . . .
      

      Remove the hashtag at the beginning of the mod_headers.so line, if present, to activate the directive.

      By making use of the following Apache HTTP directives you’ll protect headers and cookies from malicious activity to reduce the risk for clients and servers.

      Now you’ll set the header’s protection. You’ll place all these header values in one block. You can choose to apply these values as you wish, but all are recommended.

      Edit the httpd.conf file with the following command and then press G to reach the end of the file:

      • sudo vi /usr/local/etc/apache24/httpd.conf

      Place the following block at the end of the file:

      /usr/local/etc/apache24/httpd.conf

      . . .
      <IfModule mod_headers.c>
        # Add security and privacy related headers
        Header set Content-Security-Policy "default-src 'self'; upgrade-insecure-requests;"
        Header set Strict-Transport-Security "max-age=31536000; includeSubDomains"
        Header always edit Set-Cookie (.*) "$1; HttpOnly; Secure"
        Header set X-Content-Type-Options "nosniff"
        Header set X-XSS-Protection "1; mode=block"
        Header set Referrer-Policy "strict-origin"
        Header set X-Frame-Options: "deny"
        SetEnv modHeadersAvailable true
      </IfModule>
      
      • Header set Strict-Transport-Security "max-age=31536000; includeSubDomains": HTTP Strict Transport Security (HTSTS) is a mechanism for web servers and clients (mainly browsers) to establish communications using only HTTPS. By implementing this you’re avoiding man-in-the-middle attacks, where a third party in between the communication could potentially access the bits, but also tamper with them.

      • Header always edit Set-Cookie (.*) "$1; HttpOnly; Secure": The HttpOnly and Secure flags on headers help prevent cross-site scripting attacks, also known as XSS. Cookies can be misused by attackers to pose as legitimate visitors presenting themselves as someone else (identity theft), or be tampered.

      • Header set Referrer-Policy "strict-origin": The Referrer-Policy header sets what information is included as the referrer information in the header field.

      • Header set Content-Security-Policy "default-src 'self'; upgrade-insecure-requests;": The Content-Security-Policy header (CSP) will completely prevent loading content not specified in the parameters, which is helpful to prevent cross-site scripting (XSS) attacks. There are many possible parameters to configure the policy for this header. The bottom line is configuring it to load content from the same site and upgrade any content with an HTTP origin.

      • Header set X-XSS-Protection "1; mode=block": This supports older browsers that do not cope with Content-Security-Policy headers. The ‘X-XSS-Protection’ header provides protection against Cross-Site Scripting attacks. You do not need to set this header unless you need to support old browser versions, which is rare.

      • Header set X-Frame-Options: "deny": This prevents clickjacking attacks. The 'X-Frame-Options’ header tells a browser if a page can be rendered in a <frame>, <iframe>, <embed>, or <object>. This way content from other sites cannot be embedded into others, preventing clickjacking attacks. Here you’re denying all frame render so the web page can’t be embedded anywhere else, not even inside the same web site. You can adapt this to your needs, if, for example, you must authorize rendering some pages because they are advertisements or collaborations with specific websites.

      • Header set X-Content-Type-Options "nosniff": The 'X-Content-Type-Options’ header controls MIME types so they’re not changed and followed. MIME types are file format standards; they work for text, audio, video, image, and so on. This header blocks malicious actors from content sniffing those files and trying to alter the file types.

      Now restart Apache for the changes to take effect:

      To check the security levels of your configuration settings, visit the security headers website. Having followed the steps in this tutorial, your domain will score an A grade.

      Note: If you make your headers check by visiting https://securityheaders.com/ and get an F grade it could be because there is no index.html inside the DocumentRoot of your site as instructed at the end of Step 2. If checking your headers you get a different grade than an A or an F, check each Header set line looking for any misspelling that may have caused the downgrade.

      In this step you have worked with up to seven settings to improve the security of your headers and cookies. These will help prevent cross-site scripting, clickjacking, and other types of attacks.

      Conclusion

      In this tutorial you’ve addressed several security aspects, from information disclosure, to protecting sessions, through setting alternative configuration settings for important functionality.

      For further resources on hardening Apache, here are some other references:

      For extra tools to protect Apache HTTP:



      Source link