GNU/Linux >> Tutoriales Linux >  >> Debian

El servidor perfecto - Debian 8.4 Jessie (Apache2, BIND, Dovecot, ISPConfig 3.1)

Este tutorial muestra cómo preparar un servidor Debian Jessie (con Apache2, BIND, Dovecot) para la instalación de ISPConfig 3.1 y cómo instalar ISPConfig. El panel de control de alojamiento web ISPConfig 3 le permite configurar los siguientes servicios a través de un navegador web:servidor web Apache o nginx, servidor de correo Postfix, servidor Courier o Dovecot IMAP/POP3, servidor de nombres MySQL, BIND o MyDNS, PureFTPd, SpamAssassin, ClamAV, y muchos más. Esta configuración cubre Apache (en lugar de nginx), BIND y Dovecot (en lugar de Courier).

1 Nota Preliminar

En este tutorial, usaré el nombre de host server1.example.com con la dirección IP 192.168.1.100 y la puerta de enlace 192.168.1.1. Estas configuraciones pueden diferir para usted, por lo que debe reemplazarlas cuando corresponda. Antes de continuar, debe tener una instalación mínima de Debian 8. Esta puede ser una imagen mínima de Debian de su proveedor de alojamiento o puede usar el tutorial del servidor Debian mínimo para configurar el sistema base.

¿Qué hay de nuevo en esta versión del tutorial?

  • Soporte para las nuevas características de ISPConfig 3.1.
  • Soporte para certificados Let's Encrypt SSL.
  • Soporte para HHVM (HipHop Virtual Machine) para ejecutar scripts PHP.
  • Soporte para XMPP (metrónomo).
  • Compatibilidad con listas grises de correo electrónico con Postgrey.
  • UFW como Firewall para reemplazar a Bastille.
  • Webmail de RoundCube en lugar de Squirrelmail.

2 Instalar el servidor SSH (Opcional)

Si no instaló el servidor OpenSSH durante la instalación del sistema, puede hacerlo ahora:

apt-get install ssh openssh-server

A partir de ahora, puede usar un cliente SSH como PuTTY y conectarse desde su estación de trabajo a su servidor Debian Jessie y seguir los pasos restantes de este tutorial.

3 Instalar un editor de texto de shell (Opcional)

Usaremos nano editor de texto en este tutorial. Algunos usuarios prefieren el editor vi clásico, por lo que instalaremos ambos editores aquí. El programa vi predeterminado tiene un comportamiento extraño en Debian y Ubuntu; para arreglar esto, instalamos vim-nox:

apt-get install nano vim-nox

Si vi es su editor favorito, reemplace nano con vi en los siguientes comandos para editar archivos.

4 Configure el nombre de host

El nombre de host de su servidor debe ser un subdominio como "server1.example.com". No use un nombre de dominio sin parte de subdominio como "example.com" como nombre de host, ya que esto causará problemas más adelante con la configuración de su correo. Primero, debe verificar el nombre de host en /etc/hosts y cambiarlo cuando sea necesario. La línea debe ser:"Dirección IP - espacio - nombre de host completo, incluido el dominio - espacio - parte del subdominio". Para nuestro nombre de host server1.example.com, el archivo se verá así:

nano /etc/hosts
127.0.0.1       localhost.localdomain   localhost
192.168.1.100   server1.example.com     server1

# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

Luego edite el archivo /etc/hostname:

nano /etc/hostname

Contendrá solo la parte del subdominio, en nuestro caso:

server1

Finalmente, reinicia el servidor para aplicar el cambio:

reboot

Inicie sesión nuevamente y verifique si el nombre de host es correcto ahora con estos comandos:

hostname
hostname -f

La salida será así:

[email protected]:/tmp# hostname
server1
[email protected]:/tmp# hostname -f
server1.example.com

5 Actualice su instalación de Debian

Primero, asegúrese de que su /etc/apt/sources.list contenga el repositorio jessie/updates (esto asegura que siempre obtenga las actualizaciones de seguridad más recientes) y que los repositorios contrib y non-free estén habilitados (algunos paquetes como libapache2- mod-fastcgi no están en el repositorio principal).

nano /etc/apt/sources.list
#deb cdrom:[Debian GNU/Linux 8.0.0 _Jessie_ - Official amd64 NETINST Binary-1 20150425-12:50]/ jessie main

deb http://ftp.us.debian.org/debian/ jessie main contrib non-free
deb-src http://ftp.us.debian.org/debian/ jessie main contrib non-free

deb http://security.debian.org/ jessie/updates main contrib non-free
deb-src http://security.debian.org/ jessie/updates main contrib non-free

Ejecutar:

apt-get update

Para actualizar la base de datos de paquetes apt

apt-get upgrade

y para instalar las últimas actualizaciones (si las hay).

6 Cambiar el shell predeterminado

/bin/sh es un enlace simbólico a /bin/dash, sin embargo, necesitamos /bin/bash, no /bin/dash. Por lo tanto hacemos esto:

dpkg-reconfigure dash

¿Usar guión como shell del sistema predeterminado (/bin/sh)? <- no

Si no hace esto, la instalación de ISPConfig fallará.

7 Sincronizar el reloj del sistema

Es una buena idea sincronizar el reloj del sistema con un NTP (n red t tiempo p rotocol) servidor a través de Internet. Simplemente ejecuta

apt-get install ntp

y la hora de su sistema siempre estará sincronizada.

8 Instale Postfix, Dovecot, MySQL, rkhunter y Binutils

Podemos instalar Postfix, Dovecot, MySQL, rkhunter y binutils con un solo comando:

apt-get install postfix postfix-mysql postfix-doc mariadb-client mariadb-server openssl getmail4 rkhunter binutils dovecot-imapd dovecot-pop3d dovecot-mysql dovecot-sieve dovecot-lmtpd sudo

Cuando prefiera MySQL sobre MariaDB, reemplace los paquetes "mariadb-client mariadb-server" en el comando anterior con "mysql-client mysql-server".

Se le harán las siguientes preguntas:

Tipo general de configuración de correo:<-- Sitio de Internet
Nombre de correo del sistema:<-- server1.example.com
Nueva contraseña para el usuario "root" de MariaDB:<-- yourrootsqlpassword
Repetir contraseña para el usuario "root" de MariaDB: <-- yourrootsqlpassword

Para proteger la instalación de MariaDB/MySQL y deshabilitar la base de datos de prueba, ejecute este comando:

mysql_secure_installation

No tenemos que cambiar la contraseña raíz de MySQL, ya que simplemente configuramos una nueva durante la instalación. Responda las preguntas de la siguiente manera:

Change the root password? [Y/n] <-- n
Remove anonymous users? [Y/n] <-- y
Disallow root login remotely? [Y/n] <-- y
Remove test database and access to it? [Y/n] <-- y
Reload privilege tables now? [Y/n] <-- y

A continuación, abra los puertos TLS/SSL y de envío en Postfix:

nano /etc/postfix/master.cf

Descomente las secciones de envío y smtps de la siguiente manera y agregue líneas donde sea necesario para que esta sección del archivo master.cf se vea exactamente como la siguiente.

[...]
submission inet n - - - - smtpd
-o syslog_name=postfix/submission
-o smtpd_tls_security_level=encrypt
-o smtpd_sasl_auth_enable=yes
-o smtpd_client_restrictions=permit_sasl_authenticated,reject
# -o smtpd_reject_unlisted_recipient=no
# -o smtpd_client_restrictions=$mua_client_restrictions
# -o smtpd_helo_restrictions=$mua_helo_restrictions
# -o smtpd_sender_restrictions=$mua_sender_restrictions
# -o smtpd_recipient_restrictions=
# -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
# -o milter_macro_daemon_name=ORIGINATING
smtps inet n - - - - smtpd
-o syslog_name=postfix/smtps
-o smtpd_tls_wrappermode=yes
-o smtpd_sasl_auth_enable=yes
-o smtpd_client_restrictions=permit_sasl_authenticated,reject
# -o smtpd_reject_unlisted_recipient=no
# -o smtpd_client_restrictions=$mua_client_restrictions
# -o smtpd_helo_restrictions=$mua_helo_restrictions
# -o smtpd_sender_restrictions=$mua_sender_restrictions
# -o smtpd_recipient_restrictions=
# -o smtpd_relay_restrictions=permit_sasl_authenticated,reject
# -o milter_macro_daemon_name=ORIGINATING [...]

Reinicie Postfix después:

service postfix restart

Queremos que MariaDB escuche en todas las interfaces, no solo en localhost, por lo tanto, editamos /etc/mysql/my.cnf y comentamos la línea bind-address =127.0.0.1:

nano /etc/mysql/my.cnf
[...]
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
#bind-address           = 127.0.0.1
[...]

Luego reiniciamos MySQL:

service mysql restart

Ahora verifique que la red esté habilitada. Ejecutar

netstat -tap | grep mysql

La salida debería verse así:

[email protected]:/# netstat -tap | grep mysql
tcp6 0 0 [::]:mysql [::]:* LISTEN 16806/mysqld

9 Instale Amavisd-new, SpamAssassin y ClamAV

Para instalar amavisd-new, SpamAssassin y ClamAV, ejecutamos

apt-get install amavisd-new spamassassin clamav clamav-daemon zoo unzip bzip2 arj nomarch lzop cabextract apt-listchanges libnet-ldap-perl libauthen-sasl-perl clamav-docs daemon libio-string-perl libio-socket-ssl-perl libnet-ident-perl zip libnet-dns-perl postgrey

La configuración de ISPConfig 3 usa amavisd que carga la biblioteca de filtros SpamAssassin internamente, por lo que podemos detener SpamAssassin para liberar RAM:

service spamassassin stop
systemctl disable spamassassin

9.1 Instalar el servidor Metronome XMPP (opcional)

Este paso instala el servidor Metronome XMPP, que proporciona un servidor de chat que es compatible con el protocolo XMPP. Este paso es opcional, si no necesita un servidor de chat, puede omitir este paso. Ninguna otra función de ISPConfig depende de este software.

Agregue el repositorio de paquetes Prosody en Debian.

echo "deb http://packages.prosody.im/debian jessie main" > /etc/apt/sources.list.d/metronome.list
wget http://prosody.im/files/prosody-debian-packages.key -O - | sudo apt-key add -

Actualice la lista de paquetes:

apt-get update

e instale los paquetes con apt.

apt-get install git lua5.1 liblua5.1-0-dev lua-filesystem libidn11-dev libssl-dev lua-zlib lua-expat lua-event lua-bitop lua-socket lua-sec luarocks luarocks
luarocks install lpc

Agregue un usuario shell para Metronome.

adduser --no-create-home --disabled-login --gecos 'Metronome' metronome

Descargue Metronome en el directorio /opt y compílelo.

cd /opt; git clone https://github.com/maranda/metronome.git metronome
cd ./metronome; ./configure --ostype=debian --prefix=/usr
make
make install

El metrónomo ahora se ha instalado en /opt/metronome.

10 Instale Apache2, PHP, FCGI, suExec, Pear, phpMyAdmin y mcrypt

Apache2, PHP5, phpMyAdmin, FCGI, suExec, Pear y mcrypt se pueden instalar de la siguiente manera:

apt-get install apache2 apache2.2-common apache2-doc apache2-mpm-prefork apache2-utils libexpat1 ssl-cert libapache2-mod-php5 php5 php5-common php5-gd php5-mysql php5-imap phpmyadmin php5-cli php5-cgi libapache2-mod-fcgid apache2-suexec php-pear php-auth php5-mcrypt mcrypt php5-imagick imagemagick libruby libapache2-mod-python php5-curl php5-intl php5-memcache php5-memcached php5-pspell php5-recode php5-sqlite php5-tidy php5-xmlrpc php5-xsl memcached libapache2-mod-passenger

Verá las siguientes preguntas:

Web server to reconfigure automatically: <- apache2
Configure database for phpmyadmin with dbconfig-common? <- yes
Enter the password of the administrative user? <- yourrootmysqlpassword
Enter the phpmyadmin application password? <-  Just press enter

Luego ejecute el siguiente comando para habilitar los módulos de Apache suexec, rewrite, ssl, actions e include (además de dav, dav_fs y auth_digest si desea usar WebDAV):

a2enmod suexec rewrite ssl actions include dav_fs dav auth_digest cgi headers

Para garantizar que el servidor no pueda ser atacado a través de la vulnerabilidad HTTPOXY, deshabilitaremos el encabezado HTTP_PROXY en apache globalmente agregando el archivo de configuración /etc/apache2/conf-disponible/httpoxy.conf.

sudo nano /etc/apache2/conf-available/httpoxy.conf

Pegue el siguiente contenido en el archivo:

<IfModule mod_headers.c>
    RequestHeader unset Proxy early
</IfModule>

Y habilite el módulo ejecutando:

a2enconf httpoxy
service apache2 restart

10.1 Instalar HHVM (HipHop Virtual Machine)

En este paso instalaremos HHVM desde su repositorio oficial de Debian. Agregue el repositorio HHVM e importe la clave.

sudo apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0x5a16e7281be7a449
echo deb http://dl.hhvm.com/debian jessie main | sudo tee /etc/apt/sources.list.d/hhvm.list

Actualice la lista de paquetes:

sudo apt-get update

e instalar HHVM:

sudo apt-get install hhvm

10.2 Instalar SuPHP (opcional, pero no recomendado)

NOTA ACTUALIZADA:SuPHP ya no debe instalarse, continúe con el paso 11

SuPHP ya no está disponible para Debian Jessie. El modo suphp ya no debe usarse en ISPConfig ya que hay mejores modos PHP como php-fpm y php-fcgi disponibles. Si realmente necesita suphp por motivos heredados, siga los pasos de este capítulo para compilarlo manualmente. Pero no recomendamos su instalación.

apt-get install apache2-dev build-essential autoconf automake libtool flex bison debhelper binutils
cd /usr/local/src
wget http://suphp.org/download/suphp-0.7.2.tar.gz
tar zxvf suphp-0.7.2.tar.gz
wget -O suphp.patch https://lists.marsching.com/pipermail/suphp/attachments/20130520/74f3ac02/attachment.patch
patch -Np1 -d suphp-0.7.2 < suphp.patch
cd suphp-0.7.2
autoreconf -if
./configure --prefix=/usr/ --sysconfdir=/etc/suphp/ --with-apr=/usr/bin/apr-1-config --with-apache-user=www-data --with-setid-mode=owner --with-logfile=/var/log/suphp/suphp.log
make
make install

Cree el directorio de configuración de suphp y el archivo suphp.conf:

mkdir /var/log/suphp
mkdir /etc/suphp
nano /etc/suphp/suphp.conf
[global]
;Path to logfile
logfile=/var/log/suphp/suphp.log

;Loglevel
loglevel=info

;User Apache is running as
webserver_user=www-data

;Path all scripts have to be in
docroot=/var/www

;Path to chroot() to before executing script
;chroot=/mychroot

; Security options
allow_file_group_writeable=false
allow_file_others_writeable=false
allow_directory_group_writeable=false
allow_directory_others_writeable=false

;Check wheter script is within DOCUMENT_ROOT
check_vhost_docroot=true

;Send minor error messages to browser
errors_to_browser=false

;PATH environment variable
env_path=/bin:/usr/bin

;Umask to set, specify in octal notation
umask=0022

; Minimum UID
min_uid=100

; Minimum GID
min_gid=100


[handlers]
;Handler for php-scripts
x-httpd-suphp="php:/usr/bin/php-cgi"

;Handler for CGI-scripts
x-suphp-cgi=execute:!self
umask=0022

A continuación, agregaremos un archivo de configuración para cargar el módulo suphp en apache:

echo "LoadModule suphp_module /usr/lib/apache2/modules/mod_suphp.so" > /etc/apache2/mods-available/suphp.load

Y luego abra /etc/apache2/mods-disponible/suphp.conf...

nano /etc/apache2/mods-available/suphp.conf

... y agregue el siguiente contenido:

<IfModule mod_suphp.c>
        AddType application/x-httpd-suphp .php .php3 .php4 .php5 .phtml
        suPHP_AddHandler application/x-httpd-suphp

    <Directory />
        suPHP_Engine on
    </Directory>

    # By default, disable suPHP for debian packaged web applications as files
    # are owned by root and cannot be executed by suPHP because of min_uid.
    <Directory /usr/share>
        suPHP_Engine off
    </Directory>

# # Use a specific php config file (a dir which contains a php.ini file)
#       suPHP_ConfigPath /etc/php5/cgi/suphp/
# # Tells mod_suphp NOT to handle requests with the type <mime-type>.
#       suPHP_RemoveHandler <mime-type>
</IfModule>

Habilite el módulo suphp en apache:

a2enmod suphp

Reinicie Apache después:

service apache2 restart

11 Instalar Let's Encrypt

ISPConfig 3.1 tiene soporte para la autoridad de certificación SSL gratuita Let's encrypt. La función Let's Encrypt le permite crear certificados SSL gratuitos para su sitio web desde ISPConfig.

Ahora agregaremos soporte para Let's encrypt.

mkdir /opt/certbot
cd /opt/certbot
wget https://dl.eff.org/certbot-auto
chmod a+x ./certbot-auto

Ahora ejecute el comando certboot-auto que descargará e instalará el software y sus dependencias.

./certbot-auto

Luego, el comando le dirá que "no se encontraron nombres en sus archivos de configuración" y le preguntará si continuará, elija "no" aquí ya que los certificados serán creados por ISPConfig.

12 Instalar PHP-FPM y XCache

XCache es un caché de código de operación de PHP gratuito y abierto para almacenar en caché y optimizar el código intermedio de PHP. Es similar a otros cachés de código de operación de PHP, como eAccelerator y APC. Se recomienda encarecidamente tener uno de estos instalados para acelerar su página PHP.

12.1 PHP-FPM (recomendado)

A partir de ISPConfig 3.0.5, hay un modo PHP adicional que puede seleccionar para usar con Apache:PHP-FPM.

Para usar PHP-FPM con Apache, necesitamos el módulo de Apache mod_fastcgi (no mezcle esto con mod_fcgid; son muy similares, pero no puede usar PHP-FPM con mod_fcgid). Podemos instalar PHP-FPM y mod_fastcgi de la siguiente manera:

apt-get install libapache2-mod-fastcgi php5-fpm

Asegúrese de habilitar el módulo y reiniciar Apache:

a2enmod actions fastcgi alias
service apache2 restart

12.2 Instalar XCache

XCache se puede instalar de la siguiente manera:

apt-get install php5-xcache

Ahora reinicie Apache:

service apache2 restart

13 Instalar Mailman

ISPConfig le permite administrar (crear/modificar/eliminar) listas de correo de Mailman. Si desea utilizar esta función, instale Mailman de la siguiente manera:

apt-get install mailman

Seleccione al menos un idioma, por ejemplo:

Languages to support: <-- en (English)
Missing site list <-- Ok

Antes de que podamos iniciar Mailman, se debe crear una primera lista de correo llamada mailman:

newlist mailman
[email protected]:~# newlist mailman
Enter the email of the person running the list: <-- admin email address, e.g. [email protected]
Initial mailman password: <-- admin password for the mailman list
To finish creating your mailing list, you must edit your /etc/aliases (or
equivalent) file by adding the following lines, and possibly running the
`newaliases' program:

## mailman mailing list
mailman:              "|/var/lib/mailman/mail/mailman post mailman"
mailman-admin:        "|/var/lib/mailman/mail/mailman admin mailman"
mailman-bounces:      "|/var/lib/mailman/mail/mailman bounces mailman"
mailman-confirm:      "|/var/lib/mailman/mail/mailman confirm mailman"
mailman-join:         "|/var/lib/mailman/mail/mailman join mailman"
mailman-leave:        "|/var/lib/mailman/mail/mailman leave mailman"
mailman-owner:        "|/var/lib/mailman/mail/mailman owner mailman"
mailman-request:      "|/var/lib/mailman/mail/mailman request mailman"
mailman-subscribe:    "|/var/lib/mailman/mail/mailman subscribe mailman"
mailman-unsubscribe:  "|/var/lib/mailman/mail/mailman unsubscribe mailman"

Hit enter to notify mailman owner... <-- ENTER

[email protected]:~#

Abra /etc/aliases luego...

nano /etc/aliases

... y agregue las siguientes líneas:

[...]
## mailman mailing list
mailman:              "|/var/lib/mailman/mail/mailman post mailman"
mailman-admin:        "|/var/lib/mailman/mail/mailman admin mailman"
mailman-bounces:      "|/var/lib/mailman/mail/mailman bounces mailman"
mailman-confirm:      "|/var/lib/mailman/mail/mailman confirm mailman"
mailman-join:         "|/var/lib/mailman/mail/mailman join mailman"
mailman-leave:        "|/var/lib/mailman/mail/mailman leave mailman"
mailman-owner:        "|/var/lib/mailman/mail/mailman owner mailman"
mailman-request:      "|/var/lib/mailman/mail/mailman request mailman"
mailman-subscribe:    "|/var/lib/mailman/mail/mailman subscribe mailman"
mailman-unsubscribe:  "|/var/lib/mailman/mail/mailman unsubscribe mailman"

Ejecutar:

newaliases

y reinicie Postfix:

service postfix restart

Finalmente, debemos habilitar la configuración de Mailman Apache:

ln -s /etc/mailman/apache.conf /etc/apache2/conf-enabled/mailman.conf

Esto define el alias /cgi-bin/mailman/ para todos los vhosts de Apache, lo que significa que puede acceder a la interfaz de administración de Mailman para obtener una lista en http://server1.example.com/cgi-bin/mailman/admin/, y el La página web para usuarios de una lista de correo se puede encontrar en http://server1.example.com/cgi-bin/mailman/listinfo/.

En http://server1.example.com/pipermail puede encontrar los archivos de la lista de correo.

Reinicie Apache después:

service apache2 restart

Luego inicie el demonio Mailman:

service mailman start

14 Instalar PureFTPd y Quota

PureFTPd y la cuota se pueden instalar con el siguiente comando:

apt-get install pure-ftpd-common pure-ftpd-mysql quota quotatool

Edite el archivo /etc/default/pure-ftpd-common...

nano /etc/default/pure-ftpd-common

... y asegúrese de que el modo de inicio esté configurado como autónomo y establezca VIRTUALCHROOT=true:

[...]
STANDALONE_OR_INETD=standalone
[...]
VIRTUALCHROOT=true
[...]

Ahora configuramos PureFTPd para permitir sesiones FTP y TLS. FTP es un protocolo muy inseguro porque todas las contraseñas y todos los datos se transfieren en texto claro. Mediante el uso de TLS, toda la comunicación se puede cifrar, lo que hace que el FTP sea mucho más seguro.

Si desea permitir sesiones FTP y TLS, ejecute

echo 1 > /etc/pure-ftpd/conf/TLS

Para usar TLS, debemos crear un certificado SSL. Lo creo en /etc/ssl/private/, por lo tanto, primero creo ese directorio:

mkdir -p /etc/ssl/private/

Posteriormente, podemos generar el certificado SSL de la siguiente manera:

openssl req -x509 -nodes -days 7300 -newkey rsa:2048 -keyout /etc/ssl/private/pure-ftpd.pem -out /etc/ssl/private/pure-ftpd.pem
Country Name (2 letter code) [AU]: <-- Enter your Country Name (e.g., "DE").
State or Province Name (full name) [Some-State]: <-- Enter your State or Province Name.
Locality Name (eg, city) []: <-- Enter your City.
Organization Name (eg, company) [Internet Widgits Pty Ltd]: <-- Enter your Organization Name (e.g., the name of your company).
Organizational Unit Name (eg, section) []: <-- Enter your Organizational Unit Name (e.g. "IT Department").
Common Name (eg, YOUR name) []: <-- Enter the Fully Qualified Domain Name of the system (e.g. "server1.example.com").
Email Address []: <-- Enter your Email Address.

Cambiar los permisos del certificado SSL:

chmod 600 /etc/ssl/private/pure-ftpd.pem

Luego reinicie PureFTPd:

service pure-ftpd-mysql restart

Edite /etc/fstab. El mío se ve así (agregué, usrjquota=quota.user,grpjquota=quota.group,jqfmt=vfsv0 a la partición con el punto de montaje /):

nano /etc/fstab
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point> <type> <options> <dump> <pass>
# / was on /dev/sda1 during installation
UUID=3dc3b58d-97e5-497b-8254-a913fdfc5408 / ext4 errors=remount-ro,usrjquota=quota.user,grpjquota=quota.group,jqfmt=vfsv0 0 1
# swap was on /dev/sda5 during installation
UUID=36bf486e-8f76-492d-89af-5a8eb3ce8a02 none swap sw 0 0
/dev/sr0 /media/cdrom0 udf,iso9660 user,noauto 0 0

Para habilitar la cuota, ejecute estos comandos:

mount -o remount /
quotacheck -avugm
quotaon -avug

15 Instalar servidor BIND DNS

BIND se puede instalar de la siguiente manera:

apt-get install bind9 dnsutils

Si su servidor es una máquina virtual, se recomienda encarecidamente instalar el demonio hasged para obtener una mayor entropía para la firma de DNSSEC. También puede instalar haveged en servidores no virtuales, no debería doler.

apt-get install haveged

Puede encontrar una explicación sobre ese tema aquí.

16 Instalar Webalizer y AWStats

Webalizer y AWStats se pueden instalar de la siguiente manera:

apt-get install webalizer awstats geoip-database libclass-dbi-mysql-perl libtimedate-perl

Abra /etc/cron.d/awstats luego...

nano /etc/cron.d/awstats

... y comentar todo en ese archivo:

#MAILTO=root

#*/10 * * * * www-data [ -x /usr/share/awstats/tools/update.sh ] && /usr/share/awstats/tools/update.sh

# Generate static reports:
#10 03 * * * www-data [ -x /usr/share/awstats/tools/buildstatic.sh ] && /usr/share/awstats/tools/buildstatic.sh

17 Instalar Jailkit

Solo se necesita Jailkit si desea chrootear a los usuarios de SSH. Se puede instalar de la siguiente manera (importante:Jailkit se debe instalar antes de ISPConfig - ¡no se puede instalar después!):

apt-get install build-essential autoconf automake libtool flex bison debhelper binutils
cd /tmp
wget http://olivier.sessink.nl/jailkit/jailkit-2.19.tar.gz
tar xvfz jailkit-2.19.tar.gz
cd jailkit-2.19
./debian/rules binary

Ahora puede instalar el paquete Jailkit .deb de la siguiente manera:

cd ..
dpkg -i jailkit_2.19-1_*.deb
rm -rf jailkit-2.19*

18 Instalar fail2ban y UFW Firewall

Esto es opcional pero recomendado, porque el monitor ISPConfig intenta mostrar el registro:

apt-get install fail2ban

Para hacer que fail2ban monitoree PureFTPd y Dovecot, cree el archivo /etc/fail2ban/jail.local:

nano /etc/fail2ban/jail.local

[pureftpd]
enabled  = true
port     = ftp
filter   = pureftpd
logpath  = /var/log/syslog
maxretry = 3

[dovecot-pop3imap]
enabled = true
filter = dovecot-pop3imap
action = iptables-multiport[name=dovecot-pop3imap, port="pop3,pop3s,imap,imaps", protocol=tcp]
logpath = /var/log/mail.log
maxretry = 5

[postfix-sasl]
enabled  = true
port     = smtp
filter   = postfix-sasl
logpath  = /var/log/mail.log
maxretry = 3

Luego cree los siguientes dos archivos de filtro:

nano /etc/fail2ban/filter.d/pureftpd.conf
[Definition]
failregex = .*pure-ftpd: \(.*@<HOST>\) \[WARNING\] Authentication failed for user.*
ignoreregex =
nano /etc/fail2ban/filter.d/dovecot-pop3imap.conf
[Definition]
failregex = (?: pop3-login|imap-login): .*(?:Authentication failure|Aborted login \(auth failed|Aborted login \(tried to use disabled|Disconnected \(auth failed|Aborted login \(\d+ authentication attempts).*rip=(?P<host>\S*),.*
ignoreregex =

Luego, para agregar la línea ignoreregex en el archivo de filtro postfix-sasl, ejecute:

echo "ignoreregex =" >> /etc/fail2ban/filter.d/postfix-sasl.conf

Reinicie fail2ban después:

service fail2ban restart

Para instalar el cortafuegos UFW, ejecute este comando apt:

apt-get install ufw

19 Instalar RoundCube

Roundcube no está disponible en el repositorio principal de Debian 8, pero podemos obtenerlo a través de los backports.

Agregue el repositorio de Backports al archivo /etc/apt/sources.list:

echo "deb http://ftp.debian.org/debian jessie-backports main" >> /etc/apt/sources.list

y ejecute apt-get update.

apt-get update

Luego instala RoundCube con este comando:

apt-get install roundcube roundcube-core roundcube-mysql roundcube-plugins

El instalador le hará las siguientes preguntas:

Configure database for roundcube with dbconfig.common? <-- yes
Select the database type: <-- mysql
Password of the databases administrative user: <-- enter the MySQL root password here.
MySQL application password for roundcube: <-- press enter

Luego edite el archivo RoundCube /etc/roundcube/config.inc.php y ajuste algunas configuraciones:

nano /etc/roundcube/config.inc.php

Establezca default_host y smtp_server en localhost.

$config['default_host'] = 'localhost';
$config['smtp_server'] = 'localhost';

Luego edite el archivo de configuración de Apache roundcube /etc/apache2/conf-enabled/roundcube.conf:

nano /etc/apache2/conf-enabled/roundcube.conf

Y agregue una línea de alias para el alias de apache/webmail, puede agregar la línea justo al comienzo del archivo. NOTA:¡No use /mail como alias o el módulo de correo electrónico ispconfig dejará de funcionar!

Alias /webmail /var/lib/roundcube

Luego recargar Apache:

service apache2 reload

Ahora puede acceder a RoundCube de la siguiente manera:

http://192.168.1.100/webmail
http://www.example.com/webmail
http://server1.example.com:8080/webmail (después de haber instalado ISPConfig, consulte la próximo capítulo)

20 Descargar ISPConfig 3

Para instalar ISPConfig 3 desde la última versión publicada, haga lo siguiente:

cd /tmp
wget http://www.ispconfig.org/downloads/ISPConfig-3-stable.tar.gz
tar xfz ISPConfig-3-stable.tar.gz
cd ispconfig3_install/install/

A fecha de hoy (12 de abril de 2016), la versión final de ISPConfig 3.1 aún no está disponible para su descarga. Si desea probar la versión preliminar de la próxima versión 3.1, descárguela con este comando:

cd /tmp
wget -O ISPConfig-3.1-beta.tar.gz  https://git.ispconfig.org/ispconfig/ispconfig3/repository/archive.tar.gz?ref=stable-3.1
tar xfz ISPConfig-3.1-beta.tar.gz
cd ispconfig3-stable-3.1*
cd install

21 Instalar ISPConfig

El siguiente paso es ejecutar el instalador de ISPConfig.

php -q install.php

Esto iniciará el instalador de ISPConfig 3. El instalador configurará todos los servicios como Postfix, Dovecot, etc. por usted. No es necesaria una configuración manual como se requiere para ISPConfig 2 (guías de configuración perfectas).

NOTA:No se alarme si el instalador de ISPConfig 3 identifica a Debian Jessie como una versión desconocida. Esto no interfiere con ninguna funcionalidad y se solucionará con la próxima actualización de ISPConfig.

# php -q install.php

--------------------------------------------------------------------------------
_____ ___________ _____ __ _ ____
|_ _/ ___| ___ \ / __ \ / _(_) /__ \
| | \ `--.| |_/ / | / \/ ___ _ __ | |_ _ __ _ _/ /
| | `--. \ __/ | | / _ \| '_ \| _| |/ _` | |_ |
_| |_/\__/ / | | \__/\ (_) | | | | | | | (_| | ___\ \
\___/\____/\_| \____/\___/|_| |_|_| |_|\__, | \____/
__/ |
|___/
--------------------------------------------------------------------------------

>> Initial configuration
Operating System: Debian 8.0 (Jessie) or compatible
Following will be a few questions for primary configuration so be careful.
Default values are in [brackets] and can be accepted with <ENTER>.
Tap in "quit" (without the quotes) to stop the installer.

Select language (en,de) [en]: <-- Hit Enter
Installation mode (standard,expert) [standard]: <-- Hit Enter
Full qualified hostname (FQDN) of the server, eg server1.domain.tld [server1.canomi.com]: <-- Hit Enter
MySQL server hostname [localhost]: <-- Hit Enter
MySQL server port [3306]: <-- Hit Enter
MySQL root username [root]: <-- Hit Enter
MySQL root password []: <-- Enter your MySQL root password
MySQL database to create [dbispconfig]: <-- Hit Enter
MySQL charset [utf8]: <-- Hit Enter
Configuring Postgrey
Configuring Postfix
Generating a 4096 bit RSA private key
.......................................................................++
........................................................................................................................................++
writing new private key to 'smtpd.key'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]: <-- Enter 2 letter country code
State or Province Name (full name) [Some-State]: <-- Enter the name of the  state
Locality Name (eg, city) []: <-- Enter your city
Organization Name (eg, company) [Internet Widgits Pty Ltd]: <-- Enter company name or press enter
Organizational Unit Name (eg, section) []: <-- Hit Enter
Common Name (e.g. server FQDN or YOUR name) []: <-- Enter the server hostname, in my case: server1.example.com
Email Address []: <-- Hit Enter
Configuring Mailman
Configuring Dovecot
Configuring Spamassassin
Configuring Amavisd
Configuring Getmail
Configuring BIND
Configuring Jailkit
Configuring Pureftpd
Configuring Apache
Configuring vlogger
Configuring Metronome XMPP Server
writing new private key to 'localhost.key'
-----
Country Name (2 letter code) [AU]: <-- Enter 2 letter country code
Locality Name (eg, city) []: <-- Enter your city
Organization Name (eg, company) [Internet Widgits Pty Ltd]: <-- Enter company name or press enter
Organizational Unit Name (eg, section) []: <-- Hit Enter
Common Name (e.g. server FQDN or YOUR name) [server1.canomi.com]: <-- Enter the server hostname, in my case: server1.example.com
Email Address []: <-- Hit Enter
Configuring Ubuntu Firewall
Configuring Fail2ban
[INFO] service OpenVZ not detected
Configuring Apps vhost
Installing ISPConfig
ISPConfig Port [8080]:
Admin password [admin]:
Do you want a secure (SSL) connection to the ISPConfig web interface (y,n) [y]: <-- Hit Enter
Generating RSA private key, 4096 bit long modulus
.......................++
................................................................................................................................++
e is 65537 (0x10001)
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]: <-- Enter 2 letter country code
State or Province Name (full name) [Some-State]: <-- Enter the name of the  state
Locality Name (eg, city) []: <-- Enter your city
Organization Name (eg, company) [Internet Widgits Pty Ltd]: <-- Enter company name or press enter
Organizational Unit Name (eg, section) []: <-- Hit Enter
Common Name (e.g. server FQDN or YOUR name) []: <-- Enter the server hostname, in my case: server1.example.com
Email Address []: <-- Hit Enter
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []: <-- Hit Enter
An optional company name []: <-- Hit Enter
writing RSA key

Configuring DBServer
Installing ISPConfig crontab
no crontab for root
no crontab for getmail
Detect IP addresses
Restarting services ...
Installation completed.

El instalador configura automáticamente todos los servicios subyacentes, por lo que no es necesaria una configuración manual.

Luego puede acceder a ISPConfig 3 en http(s)://server1.example.com:8080/ o http(s)://192.168.1.100:8080/ (http o https depende de lo que elija durante la instalación). Inicie sesión con el nombre de usuario admin y la contraseña admin (debe cambiar la contraseña predeterminada después de su primer inicio de sesión):

El sistema ahora está listo para ser utilizado.

21.1 Manual ISPConfig 3

Para aprender a usar ISPConfig 3, recomiendo descargar el Manual de ISPConfig 3.

En más de 300 páginas, cubre el concepto detrás de ISPConfig (administrador, revendedores, clientes), explica cómo instalar y actualizar ISPConfig 3, incluye una referencia para todos los formularios y campos de formulario en ISPConfig junto con ejemplos de entradas válidas y proporciona tutoriales para las tareas más comunes en ISPConfig 3. También explica cómo hacer que su servidor sea más seguro y viene con una sección de resolución de problemas al final.

22 Notas Adicionales

22.1 OpenVZ

Si el servidor Debian que acaba de configurar en este tutorial es un contenedor OpenVZ (máquina virtual), debe hacer esto en el sistema host (supongo que el ID del contenedor OpenVZ es 101; reemplácelo con el VPSID correcto en su sistema):

VPSID=101
for CAP in CHOWN DAC_READ_SEARCH SETGID SETUID NET_BIND_SERVICE NET_ADMIN SYS_CHROOT SYS_NICE CHOWN DAC_READ_SEARCH SETGID SETUID NET_BIND_SERVICE NET_ADMIN SYS_CHROOT SYS_NICE
do
  vzctl set $VPSID --capability ${CAP}:on --save
done

23 Enlaces

  • Debian:http://www.debian.org/
  • ISPConfig:http://www.ispconfig.org/

Debian
  1. El servidor perfecto:CentOS 7 (Apache2, Dovecot, ISPConfig 3)

  2. El servidor perfecto - OpenSUSE 12.3 x86_64 (Apache2, Dovecot, ISPConfig 3)

  3. El servidor perfecto:CentOS 7.1 con Apache2, Postfix, Dovecot, Pure-FTPD, BIND e ISPConfig 3

  4. El servidor perfecto - Debian 8 Jessie (Apache2, BIND, Dovecot, ISPConfig 3)

  5. El servidor perfecto - Debian 8.6 (nginx, BIND, Dovecot, ISPConfig 3.1)

El servidor perfecto - Ubuntu 12.10 (Apache2, BIND, Dovecot, ISPConfig 3)

El servidor perfecto - OpenSUSE 12.2 x86_64 (Apache2, Dovecot, ISPConfig 3)

El servidor perfecto - Debian Wheezy (nginx, BIND, Dovecot, ISPConfig 3)

El servidor perfecto - Ubuntu 13.04 (Apache2, BIND, Dovecot, ISPConfig 3)

El servidor perfecto - CentOS 6.4 x86_64 (Apache2, Dovecot, ISPConfig 3)

El servidor perfecto - Debian Wheezy (Apache2, BIND, Dovecot, ISPConfig 3)