35
Guía para montaje de Servidor con Firewall y proxy transparente de WEB y POP3 El objetivo de esta guía es montar un servidor que haga las funciones de: firewall + router + gateway + dhcp server y proxy transparente de WEB y POP3 (con revisión 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 versión que tenga. El procedimiento del montaje descrito en esta guía se hizo con base en mi necesidad específica. De acuerdo con su necesidad particular, puede que necesite llevar a cabo pasos adicionales/diferentes que los citados en este documento. Esta guía se ha elaborado tomando como base diversa documentación 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 ejecución para que pueda servir, p.ej: chmod +x script.sh La configuración 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

Firewall Gateway Router Dhcp Proxy Web Pop3

  • Upload
    ridanox

  • View
    64

  • Download
    8

Embed Size (px)

Citation preview

Page 1: Firewall Gateway Router Dhcp Proxy Web Pop3

Guía para montaje de Servidor con Firewall y proxy transparente de WEB y POP3

El objetivo de esta guía es montar un servidor que haga las funciones de: firewall + router + gateway + dhcp server y proxy transparente de WEB y POP3 (con revisión 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 versión que tenga.

El procedimiento del montaje descrito en esta guía se hizo con base en mi necesidad específica. De acuerdo con su necesidad particular, puede que necesite llevar a cabo pasos adicionales/diferentes que los citados en este documento.

Esta guía se ha elaborado tomando como base diversa documentación 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 ejecución para que pueda servir, p.ej: chmod +x script.sh

La configuración 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

Page 2: Firewall Gateway Router Dhcp Proxy Web Pop3

ÍNDICE GENERAL

SECCIÓN 1. Instalación del servidor DHCP, SSH y DNS.........................................................................................................31.1 Instalación del servicio bind9 (servidor DNS)...............................................................................................................31.2 Instalación del servidor dhcp3-server..........................................................................................................................31.3 Instalación del servicio ssh..........................................................................................................................................5

SECCIÓN 2. Instalación del proxy transparente para WEB.....................................................................................................62.1 Configuración de proxy transparente SQUID para WEB...............................................................................................62.2 Instalación del squidGuard para el filtrado del contenido WEB...................................................................................8

SECCIÓN 3. Instalación del proxy transparente para correo POP3.......................................................................................133.1 Instalación del antivirus ClamAV................................................................................................................................133.2 Instalación de SpamPd (usando SpamAssassin)........................................................................................................143.3 Instalación del proxy POP3 (p3scan)..........................................................................................................................17

SECCIÓN 4. Configuración del Firewall como Gateway y Router (iptables).........................................................................19

2

Page 3: Firewall Gateway Router Dhcp Proxy Web Pop3

SECCIÓN 1. Instalación del servidor DHCP, SSH y bind9

1.1 Instalación del servicio bind9

Instalamos el servicio:

# apt-get install bind9

La instalación de este servicio es únicamente para poder brindar salida a internet a las máquinas cliente de la red de área local. Configurar adecuadamente un servidor DNS no está en el alcance de este documento.

1.2 Instalación del servidor dhcp3-server

Instalamos el servidor DHCP con el siguiente comando:

# apt-get install dhcp3-server

OJO: al final de la instalación el servidor dhcp3-server intentará correr; sin embargo lo más probable es que muestre un error. No preocuparnos por esto, ya que tenemos que configurar el servidor dhcp3.

El archivo de configuración a editar es /etc/dhcp3/dhcpd.conf y a continuación muestro el contenido sin las líneas 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 diamax-lease-time 86400;

3

Page 4: Firewall Gateway Router Dhcp Proxy Web Pop3

# 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 localsubnet 192.168.0.0 netmask 255.255.255.0 { # Rango de ips disponibles para asignación por dhcp range 192.168.0.10 192.168.0.100; # Gateway option routers 192.168.0.1; # Dirección 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 específica puede agregar lo siguiente al archivo de configuración /etc/dhcp3/dhcpd.conf:

# Asignación de una ip fija a una computadora concreta (se pueden poner tantas como se quiera)host pcfija { # Dirección 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 dirección 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

4

Page 5: Firewall Gateway Router Dhcp Proxy Web Pop3

1.3 Instalación del servicio ssh

Ahora vamos a instalar el servicio ssh para loggearnos al servidor remotamente vía 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 líneas en el archivo /etc/ssh/sshd_config:

LoginGraceTime 45PermitRootLogin no # esto es si no queremos que nadie se conecte como root remotamente

Ahora, sólo permitiremos acceder por ssh a los usuarios indicados explícitamente en el archivo /etc/loginusers. Para esto, las siguientes líneas del archivo /etc/pam.d/ssh deben quedar así:

#auth required pam_env.so # [1]#auth required pam_env.so envfile=/etc/default/localeauth required 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

5

Page 6: Firewall Gateway Router Dhcp Proxy Web Pop3

SECCIÓN 2. Instalación del proxy transparente para WEB

2.1 Configuración 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: después de la instalación lo más 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 configuración de squid: /etc/squid/squid.conf hagamos un respaldo de este archivo (por simple prevención). A continuación se muestra el contenido del archivo /etc/squid/squid.conf más básico. Las líneas comentadas no importantes se han removido, las que sí se muestren son extras para nuestro proxy: (asumimos los parámetros de red ya citados)

http_port 192.168.0.1:3128 transparenthierarchy_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 QUERYacl apache rep_header Server ^Apachebroken_vary_encoding allow apachecache_mem 8 MBaccess_log /var/log/squid/access.log squidhosts_file /etc/hostsrefresh_pattern ^ftp: 1440 20% 10080refresh_pattern ^gopher: 1440 0% 1440

6

Page 7: Firewall Gateway Router Dhcp Proxy Web Pop3

refresh_pattern . 0 20% 4320acl all src 0.0.0.0/0.0.0.0acl manager proto cache_objectacl localhost src 127.0.0.1/255.255.255.255acl to_localhost dst 127.0.0.0/8acl SSL_ports port 443 # httpsacl SSL_ports port 563 # snewsacl SSL_ports port 873 # rsyncacl Safe_ports port 80 # httpacl Safe_ports port 21 # ftpacl Safe_ports port 443 # httpsacl Safe_ports port 70 # gopheracl Safe_ports port 210 # waisacl Safe_ports port 1025-65535 # unregistered portsacl Safe_ports port 280 # http-mgmtacl Safe_ports port 488 # gss-httpacl Safe_ports port 591 # filemakeracl Safe_ports port 777 # multiling httpacl Safe_ports port 631 # cupsacl Safe_ports port 873 # rsyncacl Safe_ports port 901 # SWATacl purge method PURGEacl 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 subniveleshttp_access allow manager localhosthttp_access deny managerhttp_access allow purge localhosthttp_access deny purgehttp_access deny !Safe_portshttp_access deny CONNECT !SSL_ports

# 192.168.0.0/24 significa: 192.168.0.x# 192.168.0.0/16 significa: 192.168.x.xacl 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_bloqueadoshttp_access allow lan

7

Page 8: Firewall Gateway Router Dhcp Proxy Web Pop3

http_access deny allhttp_reply_access allow allicp_access allow allvisible_hostname localhostcache_effective_group proxycoredump_dir /var/spool/squid

Luego se debe reiniciar el servicio con el siguiente comando:

# /etc/init.d/squid restart

2.2 Instalación del squidGuard para el filtrado del contenido WEB

Para poner en acción el filtrado de la web y prohibir las visitas a ciertas páginas, utilizaremos el squidGuard, el cual utiliza listas negras (“blacklists”) para identificar explícitamente 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 líneas al final del archivo /etc/squid/squid.conf:

redirect_program /usr/bin/squidGuard -c /etc/squid/squidGuard.confredirect_children 5redirector_bypass on

Antes de continuar con el paso siguiente, me gustaría detenerme un momento a hablar de las listas negras. Las listas negras son archivos de texto plano con los sitios que explícitamente 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.comotrositioinventado.comotromasinventado.com

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

8

Page 9: Firewall Gateway Router Dhcp Proxy Web Pop3

el formato que utilizará squidGuard para agilizar las búsquedas de sitios a prohibir. No se preocupe por buscar o instalar el motor de base de datos Berkeley ya que la instalación 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 difícil de hacer. Afortunadamente existen “blacklists” completísimas listas para bajar. Entre las más populares no comerciales están las de shalla y MESD, ambas indicadas en la página de squidGuard. Yo recomiendo que usted visite los sitios de ambas listas negras para que lea los términos y las condiciones de uso de cualquiera de ellas. Viendo el contenido de ambas, me quedo con la de shalla porque es mucho más completa.Adicionalmente, mostraré un script que automatiza el trabajo de descargar y configurar para su uso las listas negras de shalla además 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 configuración de squidGuard a su gusto.

Para editar el archivo de configuración de squidGuard, cabe destacar que estas listas negras están clasificadas en carpetas según 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 cuáles 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 guía 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 configuración /etc/squid/squidGuard.conf. El siguiente es el archivo de configuración según lo que yo escogí:

#----------------------------------------------------------------# SquidGuard CONFIGURATION FILE#----------------------------------------------------------------

# DIRECTORIOS DE CONFIGURACIONdbhome /var/lib/squidguard/dblogdir /var/log/squid

# GRUPOS DE DIRECCIONESdest hacking { domainlist hacking/domains

9

Page 10: Firewall Gateway Router Dhcp Proxy Web Pop3

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 ACCESOacl { # 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 configuración es muy básico y fácil de entender. El símbolo ! significa NO o NOT. Y también usted puede redireccionar a una página construida por usted (prohibit.html) para mostrar el mensaje de

10

Page 11: Firewall Gateway Router Dhcp Proxy Web Pop3

prohibición de acceso al sitio solicitado. Esta es una configuración muy básica; usted podrá investigar más y se encontrará con muchas opciones adicionales que se pueden incluir en este archivo de configuración.

A continuación muestro el contenido del script que automatiza la descarga y configuración de la lista negra de Shalla además del reinicio del servicio squid. Si desea, usted puede programar este script para que se ejecute automáticamente 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 código del script para que se ajuste a la nueva carpeta donde lo vaya a ubicar.Tome en consideración que este proceso demorará según la velocidad de su conexión a Internet y a la cantidad y tamaño de clasificaciones que vaya a utilizar. Si durante este proceso ocurre un error, significa que hay un error en el archivo de configuración de squidGuard.

NOTA: el script fue tomado del propio sitio de “blacklists” de shalla. No obstante, tuve que corregirlo porque tenía algunos errores y para adaptarlo a mi necesidad específica.

##!/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 filewget -N http://squidguard.shalla.de/Downloads/shallalist.tar.gz -a /var/log/shalla.log# removemos la carpeta temporal BL por aquello de las moscasrm -Rf /root/BL# extract blackliststar -zxf shallalist.tar.gz# remove old databasesrm -Rf /var/lib/squidguard/db/*

11

Page 12: Firewall Gateway Router Dhcp Proxy Web Pop3

# copy blacklists to db homecp -R /root/BL/* /var/lib/squidguard/db# se convierten las listas a formato BerkeleysquidGuard -C all -d# se convierte al usuario proxy en propietario de la carpeta de las blacklistschown -R proxy:proxy /var/lib/squidguard/db# se reinicia el servicio squidsquid -k reconfigure# se remueve la carpeta temporal BLrm -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 automáticamente):

# squid -k reconfigure

Comprobamos que aparecen los procesos SquidGuard, (el número 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 configuración de squidGuard que se muestra más arriba, no hay que olvidar crear la página web prohibit.html y ubicarla en la raíz de su servidor web. También hay poner una imagen vacía nullbanner.png para la prohibición de publicidad.

12

Page 13: Firewall Gateway Router Dhcp Proxy Web Pop3

SECCIÓN 3. Instalación del proxy transparente para correo POP3

Los servicios a instalar en esta sección 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 instalación 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 impresión de que los usuarios de estos 3 servicios pertenecen al mismo grupo. No obstante, veremos que los demonios de estos servicios utilizarán al usuario clamav para la ejecución de sus demonios.

3.1 Instalación 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 instalación 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 fácil de arreglar: simplemente volver a ejecutar el comando # apt-get install clamav para reinstalarlo y reconfigurarlo de manera automática.

Luego de instalado lo probamos analizando el archivo test de eicar, el cual es un archivo cuyo contenido es únicamente una línea: (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

Page 14: Firewall Gateway Router Dhcp Proxy Web Pop3

(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: 115361Engine version: 0.90.1Scanned directories: 25Scanned files: 42Infected files: 1Data scanned: 3.02 MBTime: 29.217 sec (0 m 29 s)

3.2 Instalación de SpamPd (usando SpamAssassin)

Instalamos el paquete spampd y el cliente spamc:

# apt-get install spampd spamc

Luego editamos las siguientes líneas en el archivo /etc/default/spampd para que el spampd utilice el mismo usuario del antivirus (clamav):

USERID=clamavGRPID=clamav

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

ENABLED=1

14

Page 15: Firewall Gateway Router Dhcp Proxy Web Pop3

Configuramos el SpamAssassin editando las siguientes líneas en el archivo /etc/spamassassin/local.cf para que queden así:

rewrite_header Subject *****SPAM*****report_safe 1required_score 3.0use_bayes 1bayes_auto_learn 1

Preparamos un script para que mantenga las reglas del SpamAssassin actualizadas (vía 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 adecuadocd /etc/spamassassin/

# Actualizamos las reglaswget http://www.nospamtoday.com/download/mime_validate.cfwget http://www.rulesemporium.com/rules/70_sare_adult.cfwget http://www.rulesemporium.com/rules/70_sare_bayes_poison_nxm.cfwget http://www.rulesemporium.com/rules/70_sare_evilnum0.cfwget http://www.rulesemporium.com/rules/70_sare_genlsubj0.cfwget http://www.rulesemporium.com/rules/70_sare_genlsubj_eng.cfwget http://www.rulesemporium.com/rules/70_sare_header0.cfwget http://www.rulesemporium.com/rules/70_sare_header_eng.cfwget http://www.rulesemporium.com/rules/70_sare_html0.cfwget http://www.rulesemporium.com/rules/70_sare_html_eng.cfwget http://www.rulesemporium.com/rules/70_sare_obfu0.cfwget http://www.rulesemporium.com/rules/70_sare_oem.cfwget http://www.rulesemporium.com/rules/70_sare_random.cfwget http://www.rulesemporium.com/rules/70_sare_specific.cfwget http://www.rulesemporium.com/rules/70_sare_spoof.cfwget http://www.rulesemporium.com/rules/70_sare_stocks.cfwget http://www.rulesemporium.com/rules/70_sare_unsub.cfwget http://www.rulesemporium.com/rules/70_sare_uri0.cfwget http://www.rulesemporium.com/rules/72_sare_bml_post25x.cf

15

Page 16: Firewall Gateway Router Dhcp Proxy Web Pop3

wget http://www.rulesemporium.com/rules/72_sare_redirect_post3.0.0.cfwget http://www.rulesemporium.com/rules/88_FVGT_body.cfwget http://www.rulesemporium.com/rules/88_FVGT_headers.cfwget http://www.rulesemporium.com/rules/88_FVGT_rawbody.cfwget http://www.rulesemporium.com/rules/88_FVGT_subject.cfwget http://www.rulesemporium.com/rules/88_FVGT_uri.cfwget http://www.rulesemporium.com/rules/99_FVGT_DomainDigits.cfwget http://www.rulesemporium.com/rules/99_FVGT_meta.cfwget http://www.rulesemporium.com/rules/99_FVGT_Tripwire.cfwget http://www.rulesemporium.com/rules/99_sare_fraud_post25x.cfwget http://www.stearns.org/sa-blacklist/random.current.cfwget http://www.timj.co.uk/linux/bogus-virus-warnings.cfwget 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 automáticamente):

# /etc/init.d/spamassassin restart# /etc/init.d/spampd restart

Una vez que el script está creado, si quisiéramos automatizarlo, programamos el sistema para que actualice al menos una vez a la semana:

# crontab -e

Y digitar lo siguiente:

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

3.3 Instalación del proxy POP3 (p3scan)

16

Page 17: Firewall Gateway Router Dhcp Proxy Web Pop3

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 instalación puede darse un error. No preocuparnos ya que tenemos que configurar a p3scan.

Una vez instalado configuramos las siguientes líneas del archivo /etc/p3scan/p3scan.conf para que queden así:

pidfile = /var/run/p3scan/p3scan.pidmaxchilds = 10ip = 0.0.0.0port = 8110targetip = 0.0.0.0targetport = 8110user = clamavnotifydir = /var/spool/p3scan/notifyvirusdir = /var/spool/p3scanscannertype = basicscanner = /usr/bin/clamscan --no-summaryvirusregexp = .*: (.*) FOUNDdemimecheckspamspamcheck = /usr/bin/spamcsubject = [Virus Encontrado] Un mensaje enviado para usted contenia virus:

Como hemos podido observar en la línea 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 sólo utilizaremos al usuario clamav. Editamos el archivo /etc/group y buscamos las siguientes líneas (que seguramente estarán 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,p3scanspampd:x:GID:clamav,p3scan

17

Page 18: Firewall Gateway Router Dhcp Proxy Web Pop3

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

Page 19: Firewall Gateway Router Dhcp Proxy Web Pop3

SECCIÓN 4. Configuración del Firewall como Gateway y Router (iptables)

Una vez que ya tenemos todos los servicios activados, vamos a proceder con la configuración 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. Más adelante indicaré cómo y dónde ubicarlo para que se active de manera automática.

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 continuación mostraré el contenido del script sin las líneas comentadas no importantes. Ponga especial atención en las líneas de redirección 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 InterfaceINET_IFACE="eth0"INET_ADDRESS="192.168.1.2"

# Local Interface InformationLOCAL_IFACE="eth1"LOCAL_IP="192.168.0.1"LOCAL_NET="192.168.0.0/24"LOCAL_BCAST="192.168.0.255"

# Localhost Interface

19

Page 20: Firewall Gateway Router Dhcp Proxy Web Pop3

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

Page 21: Firewall Gateway Router Dhcp Proxy Web Pop3

# 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

Page 22: Firewall Gateway Router Dhcp Proxy Web Pop3

# Kernel Parameter Configuration#

# Required to enable IPv4 forwarding.# Redhat users can try setting FORWARD_IPV4 in /etc/sysconfig/network to trueecho "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

Page 23: Firewall Gateway Router Dhcp Proxy Web Pop3

echo "Limpiando reglas ..."

# Reset Default Policies$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

# 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

Page 24: Firewall Gateway Router Dhcp Proxy Web Pop3

$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

Page 25: Firewall Gateway Router Dhcp Proxy Web Pop3

################################################################################# 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

Page 26: Firewall Gateway Router Dhcp Proxy Web Pop3

# 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

Page 27: Firewall Gateway Router Dhcp Proxy Web Pop3

# 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

Page 28: Firewall Gateway Router Dhcp Proxy Web Pop3

# 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

Page 29: Firewall Gateway Router Dhcp Proxy Web Pop3

$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

Page 30: Firewall Gateway Router Dhcp Proxy Web Pop3

# Inbound Internet Packet Rules

# Accept Established Connections$IPT -A INPUT -p ALL -i $INET_IFACE -m state --state ESTABLISHED,RELATED \ -j ACCEPT

# Route the rest to the appropriate user chain$IPT -A INPUT -p TCP -i $INET_IFACE -j tcp_inbound$IPT -A INPUT -p UDP -i $INET_IFACE -j udp_inbound$IPT -A INPUT -p 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

Page 31: Firewall Gateway Router Dhcp Proxy Web Pop3

# 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

Page 32: Firewall Gateway Router Dhcp Proxy Web Pop3

################################################################################

# 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

Page 33: Firewall Gateway Router Dhcp Proxy Web Pop3

################################################################################# 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 ..."

Además tenemos el script que limpia todo el firewall-gateway-router y lo inactiva: (debe llamarse ipflush.sh)

#!/bin/bash##

# Binario de iptablesIPT=/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

Page 34: Firewall Gateway Router Dhcp Proxy Web Pop3

$IPT -t mangle -F

# Limpiar todas las reglas no-predeterminadas$IPT -X$IPT -t nat -X$IPT -t mangle -X

# Desactivamos el bit de forwardecho 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 según sea el parámetro que le indiquemos. En mi caso yo lo llamé myiptables y se invoca de la siguiente forma:

➔ # myiptables stop (limpia e inactiva las reglas)➔ # myiptables start (levanta y activa las reglas)➔ # myiptables reload (reactiva las reglas)➔ # myiptables restart (limpia e inactiva las reglas para después 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

Page 35: Firewall Gateway Router Dhcp Proxy Web Pop3

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 deberán 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 EXTERNAiface 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