You are on page 1of 35

Gua para montaje de Servidor con Firewall y proxy transparente de WEB y POP3

El objetivo de esta gua es montar un servidor que haga las funciones de: firewall + router + gateway + dhcp server y proxy transparente de WEB y POP3 (con revisin de antivirus y spam) entre una red de rea local y una red con salida a internet. Algunas notas introductorias:

La distro utilizada para estas pruebas fue la Debian Etch 4.0 (mi preferida). Probablemente se pueda adaptar sin mucho problema a otras distros de Linux. Las ubicaciones de los archivos tratados en este documento pueden variar dependiendo de la distro y versin que tenga. El procedimiento del montaje descrito en esta gua se hizo con base en mi necesidad especfica. De acuerdo con su necesidad particular, puede que necesite llevar a cabo pasos adicionales/diferentes que los citados en este documento. Esta gua se ha elaborado tomando como base diversa documentacin obtenida en Internet en conjunto con partes personalizadas a mi gusto. Todos los comandos ejecutados desde la consola deben llevarse a cabo como usuario root. Para cualquier script elaborado en este documento recordar que debe tener los permisos de ejecucin para que pueda servir, p.ej: chmod +x script.sh La configuracin de red utilizada en este documento es la siguiente: eth0 = 192.168.1.2 (conectada a internet) eth1 = 192.168.0.1 (conectada a la red de rea local)

Mucha suerte y paciencia con este montaje. Ing. Rolando V. (Pish)


1

NDICE GENERAL

SECCIN 1. Instalacin del servidor DHCP, SSH y DNS.................................................................... .....................................3 1.1 Instalacin del servicio bind9 (servidor DNS)............................................................................................................. ..3 1.2 Instalacin del servidor dhcp3-server.................................................................................................... ......................3 1.3 Instalacin del servicio ssh...................................................................................................... ....................................5 SECCIN 2. Instalacin del proxy transparente para WEB................................................................................................ .....6 2.1 Configuracin de proxy transparente SQUID para WEB................................................................................ ...............6 2.2 Instalacin del squidGuard para el filtrado del contenido WEB................................................... ................................8 SECCIN 3. Instalacin del proxy transparente para correo POP3...................................................................................... .13 3.1 Instalacin del antivirus ClamAV................................................................................................................ ................13 3.2 Instalacin de SpamPd (usando SpamAssassin)................................................................................. .......................14 3.3 Instalacin del proxy POP3 (p3scan).......................................................................................................... ................17 SECCIN 4. Configuracin del Firewall como Gateway y Router (iptables)........................................................................19 .

SECCIN 1. Instalacin del servidor DHCP SSH y bind9 , 1.1 Instalacin del servicio bind9 Instalamos el servicio:
# apt-get install bind9

La instalacin de este servicio es nicamente para poder brindar salida a internet a las mquinas cliente de la red de rea local. Configurar adecuadamente un servidor DNS no est en el alcance de este documento. 1.2 Instalacin del servidor dhcp3-server Instalamos el servidor DHCP con el siguiente comando:
# apt-get install dhcp3-server

OJO: al final de la instalacin el servidor dhcp3-server intentar correr; sin embargo lo ms probable es que muestre un error. No preocuparnos por esto, ya que tenemos que co nfigurar el servidor dhcp3. El archivo de configuracin a editar es /etc/dhcp3/dhcpd.conf y a continuacin muestro el contenido sin las lneas comentadas no importantes para no hacerlo largo:
# The ddns-updates-style parameter controls whether or not the server will # attempt to do a DNS update when a lease is confirmed. We default to the # behavior of the version 2 packages ('none', since DHCP v2 didn't # have support for DDNS.) ddns-update-style none; # definiciones comunes para todas las redes soportadas... option domain-name "home"; # puede ser midominio.com option domain-name-servers 192.168.0.1; default-lease-time 86400; # esto es en segundos. 86400=1 dia max-lease-time 86400;

# Si el servidor es el oficial DHCP para la red activar la siguiente directiva: authoritative; # Use this to send dhcp log messages to a different log file (you also # have to hack syslog.conf to complete the redirection). log-facility local7; # Definicion de una red de area local subnet 192.168.0.0 netmask 255.255.255.0 { # Rango de ips disponibles para asignacin por dhcp range 192.168.0.10 192.168.0.100; # Gateway option routers 192.168.0.1; # Direccin de broadcast option broadcast-address 192.168.0.255; # Servidor WINS option netbios-name-servers 192.168.0.1; }

Si usted desea asignar una IP fija a una computadora especfica puede agregar lo siguiente al archivo de configuracin /etc/dhcp3/dhcpd.conf:
# Asignacin de una ip fija a una computadora concreta (se pueden poner tantas como se quiera) host pcfija { # Direccin MAC de la tarjeta de red. hardware ethernet 00:D0:59:32:AF:6B; # IP asignada fixed-address 192.168.0.101; # esta direccion NO puede estar en el rango declarado arriba }

La direccin MAC de la tarjeta de red se puede obtener con el comando "ifconfig" en linux o "ipconfig /all" en dos/windows. Ahora reiniciamos el servidor dhcp3 con el siguiente comando:
# /etc/init.d/dhcp3-server restart

1.3 Instalacin del servicio ssh Ahora vamos a instalar el servicio ssh para loggearnos al servidor remotamente va consola:
# apt-get install ssh

Vamos a reducir el tiempo de login y en caso de quererlo as no permitiremos conexiones de root. Para esto editaremos nicamente las siguientes lneas en el archivo /etc/ssh/sshd_config:
LoginGraceTime 45 PermitRootLogin no # esto es si no queremos que nadie se conecte como root remotamente

Ahora, slo permitiremos acceder por ssh a los usuarios indicados explcitamente en el archivo /etc/loginusers. Para esto, las siguientes lneas del archivo /etc/pam.d/ssh deben quedar as:
#auth #auth auth required required required pam_env.so # [1] pam_env.so envfile=/etc/default/locale pam_listfile.so sense=allow onerr=fail item=user file=/etc/loginusers

Creamos el archivo /etc/loginusers (# echo pish > /etc/loginusers) con el siguiente contenido:
pish

Reiniciamos el servicio ssh con el situiente comando:


# /etc/init.d/ssh restart

SECCIN 2. Instalacin del proxy transparente para WEB 2.1 Configuracin de proxy transparente SQUID para WEB Procederemos a instalar el proxy transparente para la web. Para este fin, instalaremos el paquete squid:
# apt-get install squid

OJO: despus de la instalacin lo ms probable es que squid no levante y muestre un error. Al igual que el caso con el servidor DHCP, no preocuparnos ya que esto es porque necesitamos configurar a squid. Antes de editar el archivo de configuracin de squid: /etc/squid/squid.conf hagamos un respaldo de este archivo (por simple prevencin). A continuacin se muestra el contenido del archivo /etc/squid/squid.conf ms bsico. Las lneas comentadas no importantes se han removido, las que s se muestren son extras para nuestro proxy: (asumimos los parmetros de red ya citados)
http_port 192.168.0.1:3128 transparent hierarchy_stoplist cgi-bin ? acl QUERY urlpath_regex cgi-bin \? # acl avi urlpath_regex -i \.avi$ # acl mpeg urlpath_regex -i \.m1v$ \.mpeg$ \.mpg$ # acl mpeg2 urlpath_regex -i \.m2v$ \.vob$ # acl mpeg_audio urlpath_regex -i \.mpa$ \.mp2$ \.mp3$ \.aac$ # acl asf urlpath_regex -i \.asf$ \.wma$ \.asx$ \.wmv$ # no_cache deny avi # no_cache deny mpeg # no_cache deny mpeg2 # no_cache deny mpeg_audio # no_cache deny asf cache deny QUERY acl apache rep_header Server ^Apache broken_vary_encoding allow apache cache_mem 8 MB access_log /var/log/squid/access.log squid hosts_file /etc/hosts refresh_pattern ^ftp: 1440 20% 10080 refresh_pattern ^gopher: 1440 0% 1440 6

refresh_pattern . 0 20% 4320 acl all src 0.0.0.0/0.0.0.0 acl manager proto cache_object acl localhost src 127.0.0.1/255.255.255.255 acl to_localhost dst 127.0.0.0/8 acl SSL_ports port 443 # https acl SSL_ports port 563 # snews acl SSL_ports port 873 # rsync acl Safe_ports port 80 # http acl Safe_ports port 21 # ftp acl Safe_ports port 443 # https acl Safe_ports port 70 # gopher acl Safe_ports port 210 # wais acl Safe_ports port 1025-65535 # unregistered ports acl Safe_ports port 280 # http-mgmt acl Safe_ports port 488 # gss-http acl Safe_ports port 591 # filemaker acl Safe_ports port 777 # multiling http acl Safe_ports port 631 # cups acl Safe_ports port 873 # rsync acl Safe_ports port 901 # SWAT acl purge method PURGE acl CONNECT method CONNECT # maximum_object_size 36864 KB # tamano maximo de archivo a cachear # cache_dir ufs /var/spool/squid 25000 16 256 # 10GB en 16 niveles con 256 subniveles http_access allow manager localhost http_access deny manager http_access allow purge localhost http_access deny purge http_access deny !Safe_ports http_access deny CONNECT !SSL_ports # 192.168.0.0/24 significa: 192.168.0.x # 192.168.0.0/16 significa: 192.168.x.x acl lan src 192.168.1.2 192.168.0.0/24 # acl arch_bloqueados url_regex -i \.exe$ \.com$ \.bat$ \.pif$ http_access allow localhost # http_access deny arch_bloqueados http_access allow lan 7

http_access deny all http_reply_access allow all icp_access allow all visible_hostname localhost cache_effective_group proxy coredump_dir /var/spool/squid

Luego se debe reiniciar el servicio con el siguiente comando:


# /etc/init.d/squid restart

2.2 Instalacin del squidGuard para el filtrado del contenido WEB Para poner en accin el filtrado de la web y prohibir las visitas a ciertas pginas, utilizaremos el squidGuard, el cual utiliza listas negras (blacklists) para identificar explcitamente los sitios que vamos a bloquear. Para instalarlo ejecutamos:
# apt-get install squidguard

Una vez instalado debemos decirle al squid que utilice a squidGuard para los fines del filtrado web. Para eso hay que agregar estas lneas al final del archivo /etc/squid/squid.conf:
redirect_program /usr/bin/squidGuard -c /etc/squid/squidGuard.conf redirect_children 5 redirector_bypass on

Antes de continuar con el paso siguiente, me gustara detenerme un momento a hablar de las listas negras. Las listas negras son archivos de texto plano con los sitios que explcitamente se quieren prohibir. Por ejemplo, el contenido de un archivo de lista negra puede ser el siguiente: (los sitios son inventados para evitar cualquier problema)
sitioinventado.com otrositioinventado.com otromasinventado.com

Seguidamente se debe convertir el archivo plano de la lista negra en un archivo de base de datos Berkeley (.db) que es
8

el formato que utilizar squidGuard para agilizar las bsquedas de sitios a prohibir. No se preocupe por buscar o instalar el motor de base de datos Berkeley ya que la instalacin limpia y fresca de Debian Etch ya la incluye en los paquetes predeterminados del sistema. Bien, hasta este momento todo esto suena muy tedioso y difcil de hacer. Afortunadamente existen blacklists completsimas listas para bajar. Entre las ms populares no comerciales estn las de shalla y MESD, ambas indicadas en la pgina de squidGuard. Yo recomiendo que usted visite los sitios de ambas listas negras para que lea los trminos y las condiciones de uso de cualquiera de ellas. Viendo el contenido de ambas, me quedo con la de shalla porque es mucho ms completa. Adicionalmente, mostrar un script que automatiza el trabajo de descargar y configurar para su uso las listas negras de shalla adems de reiniciar el servicio squid para que los cambios entren en vigencia. Por lo tanto la nica tarea que le tocar a usted ser editar el archivo de configuracin de squidGuard a su gusto. Para editar el archivo de configuracin de squidGuard, cabe destacar que estas listas negras estn clasificadas en carpetas segn su fin; por ejemplo, en las listas de shalla podremos ver carpetas como: aggressive, gamble, hacking, porn, entre muchas otras. Cada una de las carpetas contiene los archivos domains y urls que son archivos de texto plano con los sitios a prohibir (tal y como se mencion con anterioridad). Usted deber escoger cules de esas clasificaciones de listas negras va a utilizar, supeditado obviamente a las clasificaciones disponibles de la lista negra descargada. No es obligatorio que las utilice todas. Para esta gua yo escog (a manera de ejemplo) utilizar solamente las siguientes clasificaciones: hacking, adv, aggressive, drugs, gamble, spyware y violence. Con base en las clasificaciones que usted vaya a utilizar, as deber indicarlo en el archivo de configuracin /etc/squid/squidGuard.conf. El siguiente es el archivo de configuracin segn lo que yo escog:
#---------------------------------------------------------------# SquidGuard CONFIGURATION FILE #---------------------------------------------------------------# DIRECTORIOS DE CONFIGURACION dbhome /var/lib/squidguard/db logdir /var/log/squid # GRUPOS DE DIRECCIONES dest hacking { domainlist hacking/domains 9

urllist hacking/urls } dest adv { domainlist adv/domains urllist adv/urls # la publicidad es reemplazada por una imagen vacia redirect http://127.0.0.1/nulbanner.png } dest aggressive { domainlist aggressive/domains urllist aggressive/urls } dest drugs { domainlist drugs/domains urllist drugs/urls } dest gamble { domainlist gamble/domains urllist gamble/urls } dest spyware { domainlist spyware/domains urllist spyware/urls } dest violence { domainlist violence/domains urllist violence/urls } # CONTROL DE ACCESO acl { # por defecto bloqueamos los grupos de direcciones creados default { pass !hacking !adv !aggressive !drugs !gamble !spyware !violence all # redireccionamos a una pagina web disuasoria redirect http://127.0.0.1/prohibit.html } }

Como pudo observar, este archivo de configuracin es muy bsico y fcil de entender. El smbolo ! significa NO o NOT. Y tambin usted puede redireccionar a una pgina construida por usted (prohibit.html) para mostrar el mensaje de
10

prohibicin de acceso al sitio solicitado. Esta es una configuracin muy bsica; usted podr investigar ms y se encontrar con muchas opciones adicionales que se pueden incluir en este archivo de configuracin. A continuacin muestro el contenido del script que automatiza la descarga y configuracin de la lista negra de Shalla adems del reinicio del servicio squid. Si desea, usted puede programar este script para que se ejecute automticamente a cada cierto tiempo utilizando el comando crontab. El script se llama shalla_update.sh y a como est programado debe alojarse en la carpeta /root. Si usted desea ubicarlo en otra carpeta, entonces tendr que modificar el cdigo del script para que se ajuste a la nueva carpeta donde lo vaya a ubicar. Tome en consideracin que este proceso demorar segn la velocidad de su conexin a Internet y a la cantidad y tamao de clasificaciones que vaya a utilizar. Si durante este proceso ocurre un error, significa que hay un error en el archivo de configuracin de squidGuard. NOTA: el script fue tomado del propio sitio de blacklists de shalla. No obstante, tuve que corregirlo porque tena
algunos errores y para adaptarlo a mi necesidad especfica. ##!/bin/sh # # squidGuard blacklists - download & install script # download from Shalla's Blacklists @ # http://squidguard.shalla.de/Downloads/shallalist.tar.gz # # created by Steve Olive - oz.ollie(at)gmail.com # ver 0.3 20070302 10:00 GMT+10 # Creative Commons Attribution-Share Alike 3.0 License # http://creativecommons.org/licenses/by-sa/3.0/ # # SCRIPT MODIFICADO POR PISH # cd /root # download latest file - overwrite any existing file wget -N http://squidguard.shalla.de/Downloads/shallalist.tar.gz -a /var/log/shalla.log # removemos la carpeta temporal BL por aquello de las moscas rm -Rf /root/BL # extract blacklists tar -zxf shallalist.tar.gz # remove old databases rm -Rf /var/lib/squidguard/db/* 11

# copy blacklists to db home cp -R /root/BL/* /var/lib/squidguard/db # se convierten las listas a formato Berkeley squidGuard -C all -d # se convierte al usuario proxy en propietario de la carpeta de las blacklists chown -R proxy:proxy /var/lib/squidguard/db # se reinicia el servicio squid squid -k reconfigure # se remueve la carpeta temporal BL rm -Rf /root/BL

Si queremos, podemos reiniciar el squid con el siguiente comando (OJO: NO es necesario ya que el script shalla_update.sh ya lo hace automticamente):
# squid -k reconfigure

Comprobamos que aparecen los procesos SquidGuard, (el nmero de procesos es el definido en el archivo /etc/squid.conf por la directiva redirect_children <numero>):
# ps -e | grep squidGuard

Comprobamos el log: (al final debe salir el mensaje squidGuard ready for requests)
#cat /var/log/squid/squidGuard.log

Tomando en cuenta el archivo de configuracin de squidGuard que se muestra ms arriba, no hay que olvidar crear la pgina web prohibit.html y ubicarla en la raz de su servidor web. Tambin hay poner una imagen vaca nullbanner.png para la prohibicin de publicidad.

12

SECCIN 3. Instalacin del proxy transparente para correo POP3 Los servicios a instalar en esta seccin son: clamav (antivirus), spamassassin (chequeador de spam) y p3scan (proxy transparente de correo POP3). Antes de instalar el p3scan, vamos a instalar primeramente los servicios que va a utilizar: clamav y spamassassin. Al finalizar la instalacin de estos 2 servicios y del proxy p3scan, haremos que los usuarios creados por clamav, spamassassin y p3scan pertenezcan entre s a sus correspondientes grupos, para dar la impresin de que los usuarios de estos 3 servicios pertenecen al mismo grupo. No obstante, veremos que los demonios de estos servicios utilizarn al usuario clamav para la ejecucin de sus demonios. 3.1 Instalacin del antivirus ClamAV Vamos a instalar el antivirus que en especial lo va a usar el proxy de correo para escanear los correos entrantes por el POP3. Sin embargo, este antivirus puede ser utilizado como cualquier otro antivirus, para escanear archivos, carpetas, etc. Dicho esto, instalamos el paquete clamav:
# apt-get install clamav

OJO: puede que al final de la instalacin del clamav ocurra un error indicando que no puede configurar el paquete por problemas de dependencias aunque dichas dependencias acaban de ser descargadas. Esto es muy fcil de arreglar: simplemente volver a ejecutar el comando # apt-get install clamav para reinstalarlo y reconfigurarlo de manera automtica. Luego de instalado lo probamos analizando el archivo test de eicar, el cual es un archivo cuyo contenido es nicamente una lnea: (OJO: este virus es inofensivo, se ha hecho nicamente con el fin de probar los antivirus) X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H* Para escanear hacemos lo siguiente (asumiendo que hemos creado el archivo con el virus eicar en /home/pish):
# clamscan -rv /home/pish/ 13

(OJO: tal vez el primer escaneo comience a tardarse mucho; esto significa que el clamav est actualizando sus definiciones de virus antes de ejecutar el escaneo. Si el escaneo devuelve un error indicando que no pudo bloquear la carpeta de base de datos de clamav: /var/lib/clamav simplemente ignorar este error y volver a ejecutar el escaneo). Y el resultado puede decir algo as (tomando en cuenta que el archivo de prueba eicar se llame archivoeicar.txt):
/home/pish/archivoeicar.txt: Eicar-Test-Signature FOUND ----------- SCAN SUMMARY ----------Known viruses: 115361 Engine version: 0.90.1 Scanned directories: 25 Scanned files: 42 Infected files: 1 Data scanned: 3.02 MB Time: 29.217 sec (0 m 29 s)

3.2 Instalacin de SpamPd (usando SpamAssassin) Instalamos el paquete spampd y el cliente spamc:
# apt-get install spampd spamc

Luego editamos las siguientes lneas en el archivo /etc/default/spampd para que el spampd utilice el mismo usuario del antivirus (clamav):
USERID=clamav GRPID=clamav

Ahora activamos el SpamAssassin con la directiva ENABLED en el archivo /etc/default/spamassassin:


ENABLED=1

14

Configuramos el SpamAssassin editando las siguientes lneas en el archivo /etc/spamassassin/local.cf para que queden as:
rewrite_header Subject *****SPAM***** report_safe 1 required_score 3.0 use_bayes 1 bayes_auto_learn 1

Preparamos un script para que mantenga las reglas del SpamAssassin actualizadas (va Internet). El script puede alojarse en la carpeta personal del root (/root) y se puede llamar actualiza_sa.sh:
#!/bin/bash # # Script para actualizar las reglas de SpamAssassin # Cambiamos al directorio adecuado cd /etc/spamassassin/ # Actualizamos las reglas wget http://www.nospamtoday.com/download/mime_validate.cf wget http://www.rulesemporium.com/rules/70_sare_adult.cf wget http://www.rulesemporium.com/rules/70_sare_bayes_poison_nxm.cf wget http://www.rulesemporium.com/rules/70_sare_evilnum0.cf wget http://www.rulesemporium.com/rules/70_sare_genlsubj0.cf wget http://www.rulesemporium.com/rules/70_sare_genlsubj_eng.cf wget http://www.rulesemporium.com/rules/70_sare_header0.cf wget http://www.rulesemporium.com/rules/70_sare_header_eng.cf wget http://www.rulesemporium.com/rules/70_sare_html0.cf wget http://www.rulesemporium.com/rules/70_sare_html_eng.cf wget http://www.rulesemporium.com/rules/70_sare_obfu0.cf wget http://www.rulesemporium.com/rules/70_sare_oem.cf wget http://www.rulesemporium.com/rules/70_sare_random.cf wget http://www.rulesemporium.com/rules/70_sare_specific.cf wget http://www.rulesemporium.com/rules/70_sare_spoof.cf wget http://www.rulesemporium.com/rules/70_sare_stocks.cf wget http://www.rulesemporium.com/rules/70_sare_unsub.cf wget http://www.rulesemporium.com/rules/70_sare_uri0.cf wget http://www.rulesemporium.com/rules/72_sare_bml_post25x.cf 15

wget wget wget wget wget wget wget wget wget wget wget wget wget

http://www.rulesemporium.com/rules/72_sare_redirect_post3.0.0.cf http://www.rulesemporium.com/rules/88_FVGT_body.cf http://www.rulesemporium.com/rules/88_FVGT_headers.cf http://www.rulesemporium.com/rules/88_FVGT_rawbody.cf http://www.rulesemporium.com/rules/88_FVGT_subject.cf http://www.rulesemporium.com/rules/88_FVGT_uri.cf http://www.rulesemporium.com/rules/99_FVGT_DomainDigits.cf http://www.rulesemporium.com/rules/99_FVGT_meta.cf http://www.rulesemporium.com/rules/99_FVGT_Tripwire.cf http://www.rulesemporium.com/rules/99_sare_fraud_post25x.cf http://www.stearns.org/sa-blacklist/random.current.cf http://www.timj.co.uk/linux/bogus-virus-warnings.cf http://www.yackley.org/sa-rules/evilnumbers.cf

# Reiniciamos los servicios /etc/init.d/spamassassin restart /etc/init.d/spampd restart

Si queremos, podemos reiniciar los servicios del spamassassin con el siguiente comando (OJO: NO es necesario ya que el script actualiza_sa.sh ya lo hace automticamente):
# /etc/init.d/spamassassin restart # /etc/init.d/spampd restart

Una vez que el script est creado, si quisiramos automatizarlo, programamos el sistema para que actualice al menos una vez a la semana:
# crontab -e

Y digitar lo siguiente:
#m h 00 05 dom mon dow * * 1 command (hagase el primer dia de cada semana a las 5am) /root/actualiza-sa.sh

3.3 Instalacin del proxy POP3 (p3scan)


16

Ahora instalaremos el otro proxy, el de correo POP3. Se instala el paquete p3scan con el siguiente comando:
# apt-get install p3scan

OJO: al final de la instalacin puede darse un error. No preocuparnos ya que tenemos que configurar a p3scan. Una vez instalado configuramos las siguientes lneas del archivo /etc/p3scan/p3scan.conf para que queden as:
pidfile = /var/run/p3scan/p3scan.pid maxchilds = 10 ip = 0.0.0.0 port = 8110 targetip = 0.0.0.0 targetport = 8110 user = clamav notifydir = /var/spool/p3scan/notify virusdir = /var/spool/p3scan scannertype = basic scanner = /usr/bin/clamscan --no-summary virusregexp = .*: (.*) FOUND demime checkspam spamcheck = /usr/bin/spamc subject = [Virus Encontrado] Un mensaje enviado para usted contenia virus:

Como hemos podido observar en la lnea que dice user = clamav, significa que cada vez que el demonio de p3scan se ejecute lo har por medio del usuario clamav (que es el del antivirus). Finalmente, hacemos que los usuarios creados por clamav, spamassassin y p3scan pertenezcan entre s a sus correspondientes grupos, aunque en la realidad slo utilizaremos al usuario clamav. Editamos el archivo /etc/group y buscamos las siguientes lneas (que seguramente estarn al final del archivo) para que queden de la siguiente manera: (GID es el group-id asignado por linux, el cual NO se cambia)
clamav:x:GID:spampd,p3scan spampd:x:GID:clamav,p3scan 17

p3scan:x:GID:clamav,spampd

Convertimos al usuario clamav en el propietario de las carpetas del p3scan y reiniciamos los servicios:
# # # # # chown clamav:clamav -R /var/spool/p3scan chown clamav:clamav -R /var/run/p3scan /etc/init.d/p3scan restart /etc/init.d/spamassassin restart /etc/init.d/spampd restart

18

SECCIN 4. Configuracin del Firewall como Gateway y Router (iptables) Una vez que ya tenemos todos los servicios activados, vamos a proceder con la configuracin del firewall-gateway-router. Esto lo llevaremos a cabo con el comando iptables. Para cumplir con este objetivo vamos a mostrar un script que hace todo esto por nosotros generado por un robot muy til. Ms adelante indicar cmo y dnde ubicarlo para que se active de manera automtica. Para el script vamos a asumir lo siguiente: eth0 = interfaz conectada al internet (192.168.1.2) eth1 = interfaz conectada a la LAN (192.168.0.1) A continuacin mostrar el contenido del script sin las lneas comentadas no importantes. Ponga especial atencin en las lneas de redireccin del proxy transparente de web y de POP3. El script debe llamarse iprules.sh
#!/bin/sh # ############################################################################### # # Local Settings # # IPTables Location - adjust if needed IPT="/sbin/iptables" # Internet Interface INET_IFACE="eth0" INET_ADDRESS="192.168.1.2" # Local Interface Information LOCAL_IFACE="eth1" LOCAL_IP="192.168.0.1" LOCAL_NET="192.168.0.0/24" LOCAL_BCAST="192.168.0.255" # Localhost Interface 19

LO_IFACE="lo" LO_IP="127.0.0.1" ############################################################################### # # Load Modules # echo "Cargando modulos del Kernel ..." # You should uncomment the line below and run it the first time just to # ensure all kernel module dependencies are OK. There is no need to run # every time, however. # /sbin/depmod -a # # # # # # Unless you have kernel module auto-loading disabled, you should not need to manually load each of these modules. Other than ip_tables, ip_conntrack, and some of the optional modules, I've left these commented by default. Uncomment if you have any problems or if you have disabled module autoload. Note that some modules must be loaded by another kernel module.

# core netfilter module /sbin/modprobe ip_tables # the stateful connection tracking module /sbin/modprobe ip_conntrack # filter table module # /sbin/modprobe iptable_filter # mangle table module # /sbin/modprobe iptable_mangle # nat table module # /sbin/modprobe iptable_nat # LOG target module # /sbin/modprobe ipt_LOG 20

# This is used to limit the number of packets per sec/min/hr # /sbin/modprobe ipt_limit # masquerade target module # /sbin/modprobe ipt_MASQUERADE # filter using owner as part of the match # /sbin/modprobe ipt_owner # REJECT target drops the packet and returns an ICMP response. # The response is configurable. By default, connection refused. # /sbin/modprobe ipt_REJECT # This target allows packets to be marked in the mangle table # /sbin/modprobe ipt_mark # This target affects the TCP MSS # /sbin/modprobe ipt_tcpmss # This match allows multiple ports instead of a single port or range # /sbin/modprobe multiport # This match checks against the TCP flags # /sbin/modprobe ipt_state # This match catches packets with invalid flags # /sbin/modprobe ipt_unclean # The ftp nat module is required for non-PASV ftp support /sbin/modprobe ip_nat_ftp # the module for full ftp connection tracking /sbin/modprobe ip_conntrack_ftp # the module for full irc connection tracking #/sbin/modprobe ip_conntrack_irc ############################################################################### # 21

# Kernel Parameter Configuration # # Required to enable IPv4 forwarding. # Redhat users can try setting FORWARD_IPV4 in /etc/sysconfig/network to true echo "1" > /proc/sys/net/ipv4/ip_forward # This enables dynamic address hacking. # Set this if you have a dynamic IP address \(e.g. slip, ppp, dhcp\). #if [ "$SYSCTL" = "" ] #then # echo "1" > /proc/sys/net/ipv4/ip_dynaddr #else # $SYSCTL net.ipv4.ip_dynaddr="1" #fi # This enables source validation by reversed path according to RFC1812. # In other words, did the response packet originate from the same interface # through which the source packet was sent? It's recommended for single-homed # systems and routers on stub networks. Since those are the configurations # this firewall is designed to support, I turn it on by default. # Turn it off if you use multiple NICs connected to the same network. echo "1" > /proc/sys/net/ipv4/conf/all/rp_filter # This option allows a subnet to be firewalled with a single IP address. # It's used to build a DMZ. Since that's not a focus of this firewall # script, it's not enabled by default, but is included for reference. # See: http://www.sjdjweis.com/linux/proxyarp/ #if [ "$SYSCTL" = "" ] #then # echo "1" > /proc/sys/net/ipv4/conf/all/proxy_arp #else # $SYSCTL net.ipv4.conf.all.proxy_arp="1" #fi ############################################################################### # # Flush Any Existing Rules or Chains #

22

echo "Limpiando reglas ..." # Reset $IPT -P $IPT -P $IPT -P $IPT -t $IPT -t $IPT -t $IPT -t $IPT -t Default Policies INPUT ACCEPT FORWARD ACCEPT OUTPUT ACCEPT nat -P PREROUTING ACCEPT nat -P POSTROUTING ACCEPT nat -P OUTPUT ACCEPT mangle -P PREROUTING ACCEPT mangle -P OUTPUT ACCEPT

# Flush all rules $IPT -F $IPT -t nat -F $IPT -t mangle -F # Erase all non-default chains $IPT -X $IPT -t nat -X $IPT -t mangle -X if [ "$1" = "stop" ] then echo "Firewall limpio..." exit 0 fi ############################################################################### # # Rules Configuration # ############################################################################### # # Filter Table # ############################################################################### # Set Policies

23

$IPT -P INPUT DROP $IPT -P OUTPUT DROP $IPT -P FORWARD DROP ############################################################################### # # User-Specified Chains # # Create user chains to reduce the number of rules each packet # must traverse. echo "Creando reglas personalizadas ..." # Create a chain to filter INVALID packets $IPT -N bad_packets # Create another chain to filter bad tcp packets $IPT -N bad_tcp_packets # Create separate chains for icmp, tcp (incoming and outgoing), # and incoming udp packets. $IPT -N icmp_packets # Used for UDP packets inbound from the Internet $IPT -N udp_inbound # Used to block outbound UDP services from internal network # Default to allow all $IPT -N udp_outbound # Used to allow inbound services if desired # Default fail except for established sessions $IPT -N tcp_inbound # Used to block outbound services from internal network # Default to allow all $IPT -N tcp_outbound

24

############################################################################### # # Populate User Chains # # bad_packets chain # # Drop INVALID packets immediately $IPT -A bad_packets -p ALL -m state --state INVALID -j LOG \ --log-prefix "Paquete invalido:" $IPT -A bad_packets -p ALL -m state --state INVALID -j DROP # Then check the tcp packets for additional problems $IPT -A bad_packets -p tcp -j bad_tcp_packets # All good, so return $IPT -A bad_packets -p ALL -j RETURN # # # # # # # bad_tcp_packets chain All tcp packets will traverse this chain. Every new connection attempt should begin with a syn packet. If it doesn't, it is likely a port scan. This drops packets in state NEW that are not flagged as syn packets.

# Return to the calling chain if the bad packets originate # from the local interface. This maintains the approach # throughout this firewall of a largely trusted internal # network. $IPT -A bad_tcp_packets -p tcp -i $LOCAL_IFACE -j RETURN # # # # # # # # However, I originally did apply this filter to the forward chain for packets originating from the internal network. While I have not conclusively determined its effect, it appears to have the interesting side effect of blocking some of the ad systems. Apparently some ad systems have the browser initiate a NEW connection that is not flagged as a syn packet to retrieve the ad image. If you wish to experiment further comment the rule above. If you try it, you may also wish to uncomment the 25

# rule below. It will keep those packets from being logged. # There are a lot of them. # $IPT -A bad_tcp_packets -p tcp -i $LOCAL_IFACE ! --syn -m state \ # --state NEW -j DROP $IPT -A bad_tcp_packets -p tcp ! --syn -m state --state NEW -j LOG \ --log-prefix "Nuevo no syn:" $IPT -A bad_tcp_packets -p tcp ! --syn -m state --state NEW -j DROP # All good, so return $IPT -A bad_tcp_packets -p tcp -j RETURN # # # # # # # # # # # # # # icmp_packets chain This chain is for inbound (from the Internet) icmp packets only. Type 8 (Echo Request) is not accepted by default Enable it if you want remote hosts to be able to reach you. 11 (Time Exceeded) is the only one accepted that would not already be covered by the established connection rule. Applied to INPUT on the external interface. See: http://www.ee.siue.edu/~rwalden/networking/icmp.html for more info on ICMP types. Note that the stateful settings allow replies to ICMP packets. These rules allow new packets of the specified types.

# Echo - uncomment to allow your system to be pinged. # $IPT -A icmp_packets -p ICMP -s 0/0 --icmp-type 8 -j ACCEPT # Time Exceeded $IPT -A icmp_packets -p ICMP -s 0/0 --icmp-type 11 -j ACCEPT # Not matched, so return so it will be logged $IPT -A icmp_packets -p ICMP -j RETURN # TCP & UDP # Identify ports at: # http://www.chebucto.ns.ca/~rakerman/port-table.html # http://www.iana.org/assignments/port-numbers

26

# # # # # # #

udp_inbound chain This chain describes the inbound UDP packets it will accept. It's applied to INPUT on the external or Internet interface. Note that the stateful settings allow replies. These rules are for new requests. It drops netbios packets (windows) immediately without logging.

# Drop netbios calls # Please note that these rules do not really change the way the firewall # treats netbios connections. Connections from the localhost and # internal interface (if one exists) are accepted by default. # Responses from the Internet to requests initiated by or through # the firewall are also accepted by default. To get here, the # packets would have to be part of a new request received by the # Internet interface. You would have to manually add rules to # accept these. I added these rules because some network connections, # such as those via cable modems, tend to be filled with noise from # unprotected Windows machines. These rules drop those packets # quickly and without logging them. This prevents them from traversing # the whole chain and keeps the log from getting cluttered with # chatter from Windows systems. $IPT -A udp_inbound -p UDP -s 0/0 --destination-port 137 -j DROP $IPT -A udp_inbound -p UDP -s 0/0 --destination-port 138 -j DROP # Not matched, so return for logging $IPT -A udp_inbound -p UDP -j RETURN # # # # # udp_outbound chain This chain is used with a private network to prevent forwarding for UDP requests on specific protocols. Applied to the FORWARD rule from the internal network. Ends with an ACCEPT

# ICQ uses UDP 4000 - Instant messaging blocked $IPT -A udp_outbound -p UDP -s 0/0 --destination-port 4000 -j REJECT # No match, so ACCEPT $IPT -A udp_outbound -p UDP -s 0/0 -j ACCEPT 27

# # # # #

tcp_inbound chain This chain is used to allow inbound connections to the system/gateway. Use with care. It defaults to none. It's applied on INPUT from the external or Internet interface.

# Web Server # HTTP $IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 80 -j ACCEPT # HTTPS (Secure Web Server) $IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 443 -j ACCEPT # FTP Server (Control) $IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 21 -j ACCEPT # FTP Client (Data Port for non-PASV transfers) $IPT -A tcp_inbound -p TCP -s 0/0 --source-port 20 -j ACCEPT # Email Server (SMTP) $IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 25 -j ACCEPT # Email Server (POP3) $IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 110 -j ACCEPT # Email Server (IMAP4) $IPT -A tcp_inbound -p TCP -s 0/0 --destination-port 143 -j ACCEPT # Not matched, so return so it will be logged $IPT -A tcp_inbound -p TCP -j RETURN # # # # # tcp_outbound chain This chain is used with a private network to prevent forwarding for requests on specific protocols. Applied to the FORWARD rule from the internal network. Ends with an ACCEPT

# Block IRC 28

$IPT -A tcp_outbound -p TCP -s 0/0 --destination-port 194 -j REJECT # Block Usenet Access $IPT -A tcp_outbound -p TCP -s 0/0 --destination-port 119 -j REJECT # Block Instant Messaging # AIM $IPT -A tcp_outbound -p TCP -s 0/0 --destination-port 5190 -j REJECT # AIM Images $IPT -A tcp_outbound -p TCP -s 0/0 --destination-port 4443 -j REJECT # MSN Messenger $IPT -A tcp_outbound -p TCP -s 0/0 --destination-port 1863 -j REJECT # No match, so ACCEPT $IPT -A tcp_outbound -p TCP -s 0/0 -j ACCEPT ############################################################################### # # INPUT Chain # echo "Procesando cadena INPUT ..." # Allow all on localhost interface $IPT -A INPUT -p ALL -i $LO_IFACE -j ACCEPT # Drop bad packets $IPT -A INPUT -p ALL -j bad_packets # Rules for the private network (accessing gateway system itself) $IPT -A INPUT -p ALL -i $LOCAL_IFACE -s $LOCAL_NET -j ACCEPT $IPT -A INPUT -p ALL -i $LOCAL_IFACE -d $LOCAL_BCAST -j ACCEPT # Allow DHCP client request packets inbound from internal network $IPT -A INPUT -p UDP -i $LOCAL_IFACE --source-port 68 --destination-port 67 \ -j ACCEPT

29

# Inbound Internet Packet Rules # Accept Established Connections $IPT -A INPUT -p ALL -i $INET_IFACE -m state --state ESTABLISHED,RELATED \ -j ACCEPT # Route $IPT -A $IPT -A $IPT -A the rest INPUT -p INPUT -p INPUT -p to the appropriate user chain TCP -i $INET_IFACE -j tcp_inbound UDP -i $INET_IFACE -j udp_inbound ICMP -i $INET_IFACE -j icmp_packets

# Drop without logging broadcasts that get this far. # Cuts down on log clutter. # Comment this line if testing new rules that impact # broadcast protocols. $IPT -A INPUT -p ALL -d 255.255.255.255 -j DROP # Log packets that still don't match $IPT -A INPUT -m limit --limit 3/minute --limit-burst 3 -j LOG \ --log-prefix "Paquete INPUT descartado: " ############################################################################### # # FORWARD Chain # echo "Procesando cadena FORWARD ..." # Used if forwarding for a private network # Drop bad packets$IPT -A FORWARD -p ALL -j bad_packets # Accept TCP packets we want to forward from internal sources $IPT -A FORWARD -p tcp -i $LOCAL_IFACE -j tcp_outbound # Accept UDP packets we want to forward from internal sources $IPT -A FORWARD -p udp -i $LOCAL_IFACE -j udp_outbound # If not blocked, accept any other packets from the internal interface $IPT -A FORWARD -p ALL -i $LOCAL_IFACE -j ACCEPT 30

# Deal with responses from the internet $IPT -A FORWARD -i $INET_IFACE -m state --state ESTABLISHED,RELATED \ -j ACCEPT # Log packets that still don't match $IPT -A FORWARD -m limit --limit 3/minute --limit-burst 3 -j LOG \ --log-prefix "FORWARD packet died: " ############################################################################### # # OUTPUT Chain # echo "Procesando cadena OUTPUT ..." # Generally trust the firewall on output # However, invalid icmp packets need to be dropped # to prevent a possible exploit. $IPT -A OUTPUT -m state -p icmp --state INVALID -j DROP # Localhost $IPT -A OUTPUT -p ALL -s $LO_IP -j ACCEPT $IPT -A OUTPUT -p ALL -o $LO_IFACE -j ACCEPT # To internal network $IPT -A OUTPUT -p ALL -s $LOCAL_IP -j ACCEPT $IPT -A OUTPUT -p ALL -o $LOCAL_IFACE -j ACCEPT # To internet $IPT -A OUTPUT -p ALL -o $INET_IFACE -j ACCEPT # Log packets that still don't match $IPT -A OUTPUT -m limit --limit 3/minute --limit-burst 3 -j LOG \ --log-prefix "Paquete OUTPUT descartado: " ############################################################################### # # nat table 31

# ############################################################################### # # # # # # # The nat table is where network address translation occurs if there is a private network. If the gateway is connected to the Internet with a static IP, snat is used. If the gateway has a dynamic address, masquerade must be used instead. There is more overhead associated with masquerade, so snat is better when it can be used. The nat table has a builtin chain, PREROUTING, for dnat and redirects. Another, POSTROUTING, handles snat and masquerade.

echo "Cargando reglas para tabla la NAT ..." ############################################################################### # # PREROUTING chain # # This is a sample that will exempt a specific host from the transparent proxy #$IPT -t nat -A PREROUTING -p tcp -s 192.168.1.50 --destination-port 80 \ # -j RETURN #$IPT -t nat -A PREROUTING -p tcp -s 192.168.1.50 --destination-port 443 \ # -j RETURN # Redirect HTTP for a transparent proxy $IPT -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-ports 3128 # Redirect HTTPS for a transparent proxy #$IPT -t nat -A PREROUTING -p tcp --destination-port 443 -j REDIRECT --to-ports 3128 # Redirect POP3 for a transparent POP3 proxy $IPT -t nat -A PREROUTING -p tcp --destination-port 110 -j REDIRECT --to-ports 8110 ############################################################################### # # POSTROUTING chain # $IPT -t nat -A POSTROUTING -o $INET_IFACE -j SNAT --to-source $INET_ADDRESS

32

############################################################################### # # mangle table # ############################################################################### # # # # # # # # # The mangle table is used to alter packets. It can alter or mangle them in several ways. For the purposes of this generator, we only use its ability to alter the TTL in packets. However, it can be used to set netfilter mark values on specific packets. Those marks could then be used in another table like filter, to limit activities associated with a specific host, for instance. The TOS target can be used to set the Type of Service field in the IP header. Note that the TTL target might not be included in the distribution on your system. If it is not and you require it, you will have to add it. That may require that you build from source.

# echo "Load rules for mangle table ..."

Adems tenemos el script que limpia todo el firewall-gateway-router y lo inactiva: (debe llamarse ipflush.sh)
#!/bin/bash # # # Binario de iptables IPT=/sbin/iptables # Resetear las politicas locales $IPT -P INPUT ACCEPT $IPT -P FORWARD ACCEPT $IPT -P OUTPUT ACCEPT $IPT -t nat -P PREROUTING ACCEPT $IPT -t nat -P POSTROUTING ACCEPT $IPT -t nat -P OUTPUT ACCEPT $IPT -t mangle -P PREROUTING ACCEPT $IPT -t mangle -P OUTPUT ACCEPT # Limpiar todas las reglas $IPT -F $IPT -t nat -F 33

$IPT -t mangle -F # Limpiar todas las reglas no-predeterminadas $IPT -X $IPT -t nat -X $IPT -t mangle -X # Desactivamos el bit de forward echo 0 > /proc/sys/net/ipv4/ip_forward

Finalmente tendremos el script principal parametrizado que limpia o levanta las reglas de iptables llamando a iprules.sh o a ipflush.sh segn sea el parmetro que le indiquemos. En mi caso yo lo llam myiptables y se invoca de la siguiente forma:

# # # #

myiptables stop myiptables start myiptables reload myiptables restart

(limpia e inactiva las reglas) (levanta y activa las reglas) (reactiva las reglas) (limpia e inactiva las reglas para despus de un par de segundos activarlas nuevamente)

#! /bin/sh # # case "$1" in start|reload) echo -n "Cargando reglas de iptables... " /etc/network/iptables/iprules.sh rc=$? [ $rc = 0 ] && echo [OK] || echo [ERROR] ;; stop) echo -n "Anulando iptables... " ### Esta opcion anula el FW totalmente ### como si nunca se hubiese instalado /etc/network/iptables/ipflush.sh rc=$? [ $rc = 0 ] && echo [OK] || echo [ERROR] ;; 34

restart) sh $0 stop sleep 2 sh $0 start ;; *) echo "Uso:`basename $0` {start|stop|restart|reload}" exit 1 ;; esac exit 0

Estos scripts se debern guardar en la carpeta /etc/network/iptables Ahora configuramos la red para que se activen o desactiven las reglas de iptables cuando se levante o tumbe la tarjeta de red que est conectada al Internet. El archivo a editar es /etc/network/interfaces:
(...) ### Interfaz EXTERNA iface eth0 inet static (...) pre-up /etc/network/iptables/myiptables start post-down /etc/network/iptables/myiptables stop ### Interfaz INTERNA (...)

En este momento podemos reiniciar el servicio networking para que comience a funcionar todo esto:
# /etc/init.d/networking restart

35

You might also like