Linux Avanzado

no sólo ofrece componentes disponibles como módulos del núcleo sino que también ofrece ... prácticamente todas las distr
57KB Größe 6 Downloads 91 Ansichten
Linux Avanzado Tema 13: Iptables - Firewall IPTABLES Es una herramienta de cortafuegos que permite no solamente filtrar paquetes, sino también realizar traducción de direcciones de red (NAT) para IPv4 o mantener registros de log. El proyecto Netfilter no sólo ofrece componentes disponibles como módulos del núcleo sino que también ofrece herramientas de espacio de usuario y librerías. iptables es el nombre de la herramienta de espacio de usuario mediante la cual el administrador puede definir políticas de filtrado del tráfico que circula por la red. El nombre iptables se utiliza frecuentemente de forma errónea para referirse a toda la infraestructura ofrecida por el proyecto Netfilter. Sin embargo, el proyecto ofrece otros subsistemas independientes de iptables tales como el connection tracking system o sistema de seguimiento de conexiones, o que, que permite encolar paquetes para que sean tratados desde espacio de usuario. iptables es unsoftware disponible en prácticamente todas las distribuciones de Linux actuales. Puede ser local o perimetral. 1 # iptables -L Chain INPUT (policy ACCEPT) target prot opt source

destination

Chain FORWARD (policy ACCEPT) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination 1 #iptables -A añade una nueva regla 2 #iptables -D borra una regla Cualquier accion minima lleva el comando con una opcion 1 iptables -N chain (cadena) -----------> crea nueva cadena Los tipos de cadena son :input, output o forward. Pero se pueden crear nuevas. rulenum indica que las reglas se van numerando, y podemos usarlo posteriormente en las reglas name es el nombre de la interfaz Opciones: * la opcion -p indica protocolos: TCP, UDP, etc… una ! (exclamacion) en un comando es para negar

1

* -s source. mask va de 0-32 * -d destino se especifica igual con una direccion/mascara Ejercicio: Bloquear la ip de un ordenador para que no pueda acceder al puerto 80 1 # iptables -A INPUT -s 192.168.2.23 -p tcp --dport 80 -j DROP modificador: -A INPUT, Añado regla a la cadena entrante Especifcacion de la cadena: -s 192.168.2.23 -p tcp –dport 80 Accion: -j DROP Listamos lo que hay ahora: 1 # iptables -nL (-n es para que no muestra los nombres de domino, es decir resolucion de dominos) 1 [root@pventura ~]# iptables -L Chain INPUT (policy ACCEPT) target prot opt source DROP tcp – 192.168.2.23

destination anywhere

tcp dpt:http

Chain FORWARD (policy ACCEPT) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination [root@pventura ~]# Muestro las lineas de cada regla 1 # iptables -nL --line-numbers Chain INPUT (policy ACCEPT) num target prot opt source 1 DROP tcp – 192.168.2.23

destination 0.0.0.0/0 tcp dpt:80

Chain FORWARD (policy ACCEPT) num target prot opt source

destination

Chain OUTPUT (policy ACCEPT) num target prot opt source destination Ejercicio: Activar el ftp modo activo, (puerto 20 y 21) para un usuario y denegarlo para el resto.

2

1 # iptables -A INPUT -s 192.168.1.144 -p tcp --dport 21 -j ACCEPT 2 # iptables -A INPUT -s 192.168.1.144 -p tcp --dport 20 -j ACCEPT 3 4 # iptables -A INPUT -s 0.0.0.0 -p tcp --dport 21 -j DROP 5 # iptables -A INPUT -s 0.0.0.0 -p tcp --dport 20 -j DROP El los firewall en produccion todo se bloquea como politica por defecto. Despues se va habilitando poco a poco reglas de excepcion. 1 # iptables -L Chain INPUT (policy ACCEPT) ———————->> Politica por defecto acepta target prot opt source destination DROP tcp – 192.168.2.23 anywhere DROP tcp – 192.168.2.217 anywhere DROP tcp – 192.168.2.215 anywhere Chain FORWARD (policy ACCEPT) target prot opt source destination

tcp dpt:http tcp dpt:http tcp dpt:http

Chain OUTPUT (policy ACCEPT) target prot opt source destination Para cambiar las políticas por defecto y bloquearlo todo se ejecuta el siguiente comando: 1 # iptables -P INPUT DROP Importantes antes de aplicar una política restrictiva introducir antes la política para poder conectar por ssh con nuestra ip.Ahora ya se ha cambiado. 1 # iptables -nL Chain INPUT (policy DROP) target prot opt source destination ACCEPT tcp – 192.168.1.217 0.0.0.0/0 tcp dpt:22 DROP tcp – 192.168.2.23 0.0.0.0/0 tcp dpt:80 DROP tcp – 192.168.2.217 0.0.0.0/0 tcp dpt:80 DROP tcp – 192.168.2.215 0.0.0.0/0 tcp dpt:80 ACCEPT tcp – 192.168.1.217 0.0.0.0/0 tcp dpt:22 Chain FORWARD (policy ACCEPT) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination

3

Para cambiar el orden de una politica para subirla y o bajarla es con la opcion -I INPUT NUMERO_POSICION 1

# iptables -I INPUT 1 -s 192.168.1.217 -p tcp --dport 22 -j ACCEPT -------------->>> subimos el ssh a la linea 1 ya que el servicio ssh es de los mas importantes

Ejerccio: Bloquear todas las webs salvo una. 1 #iptables - A OUTPUT -d 192.168.1.231 -p tcp --dport 80 -j ACCEPT 2 bloquer todo 3

#iptables - A OUTPUT -p tcp --dport 80 -j DROP no hace falta poner ip porque directamente lo bloquea todo.

Importante siempre que se hace una modificacion en el iptables despues hay que guardar una copia de seguridad de lo que hay, porque los registros del firewall en el iptables se guardan en memoria ram, de manera que sino hay copia de seguridad y se reinicia la maquina se pierde todas las reglas. Para hacer una copia de seguridad se usa iptables-save 1 # iptables-save > /root/iptables-20110126.txt Para restaurar copias de segurridad se usa el comando iptables-restore, es capaz de recoger las reglas que hay en un fichero y restaurarlas. 1 # iptables-restore < /root/iptables-20110126.txt

Otras Opciones para enrutado TABLES There are currently three independent tables (which tables are present at any time depends on the kernel configuration options and which modules are present). -t, –table table This option specifies the packet matching table which the command should operate on. If the kernel is configured with automatic module loading, an attempt will be made to load the appropriate module for that table if it is not already there. The tables are as follows: filter: This is the default table (if no -t option is passed). It contains the built-in chains INPUT (for packets

4

destined to local sockets), FORWARD (for packets being routed through the box), and OUTPUT (for locally-generated packets). nat: This table is consulted when a packet that creates a new connection is encountered. It consists of three built-ins: PREROUTING (for altering packets as soon as they come in), OUTPUT (for altering locally-generated packets before routing), and POSTROUTING (for altering packets as they are about to go out). mangle: This table is used for specialized packet alteration. Until kernel 2.4.17 it had two built-in chains: PREROUTING (for altering incoming packets before routing) and OUTPUT (for altering locallygenerated packets before routing). Since kernel 2.4.18, three other built-in chains are also supported: INPUT (for packets coming into the box itself), FORWARD (for altering packets being routed through the box), and POSTROUTING (for altering packets as they are about to go out). raw: This table is used mainly for configuring exemptions from connection tracking in combination with the NOTRACK target. It registers at the netfilter hooks with higher priority and is thus called before ip_conntrack, or any other IP tables. It provides the following built-in chains: PREROUTING (for packets arriving via any network interface) OUTPUT (for packets generated by local processes) 1 # iptables -t nat -nL Chain PREROUTING (policy ACCEPT) target prot opt source destination Chain POSTROUTING (policy ACCEPT) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination 1 # iptables -t filter -nL Chain PREROUTING (policy ACCEPT) target prot opt source destination Chain POSTROUTING (policy ACCEPT) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination

5

1 # iptables -t mangle -nL Chain PREROUTING (policy ACCEPT) target prot opt source destination Chain POSTROUTING (policy ACCEPT) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination

Usando la tabla NAT Ejercicio. enrutar el trafico desde wi-fi hasta el disco duro multimedia. Esta directiva es para enrutar lo que viene del disco duro y se envia a la wlan0, ya que ésta tiene otra red 1

iptables -t nat -A POSTROUTING -s 192.168.2.10/24 -o 192.168.3.2 -j MASQUERADE --------> con ips

2 iptables -t nat -A POSTROUTING -i eth0 -o wlan0 -j MASQUERADE --------->> con interfaces Las dos directivas anteriores son iguales 1 # iptables -t nat -A POSTROUTING -s 192.168.2.10/24 -o 192.168.3.2 -j MASQUERADE 2 3

# iptables -t nat -nL ------->>>> para mostrar reglas nuevas introducidas desde nat

Chain PREROUTING (policy ACCEPT) target prot opt source destination Chain POSTROUTING (policy ACCEPT) target prot opt source destination MASQUERADE all – 192.168.2.0/24 0.0.0.0/0 Chain OUTPUT (policy ACCEPT) target prot opt source destination Los paquetes tcp tienen flasgs en el en cabezado, iptables es capaz de filtrar los flags activos.

Firewall perimetral Se suelen crear firewall para proteger redes, se debe crear bridge;br0 Se crea una estructura de árbol para crear reglas con el nombre del servicio o de la maquina. Para crear nuevas cadenas es con el comando iptables -N rama1

6

Otras fuentes de ayuda. http://linux.die.net/man/8/iptables http://web.mit.edu/rhel-doc/4/RH-DOCS/rhel-sg-es-4/ch-fw.html http://web.mit.edu/rhel-doc/5/RHEL-5-manual/Deployment_Guide-en-US/ch-iptables.html Martes 27/03/2012 1845hs.

Autor:

David Mertz es Turing completo, pero probablemente no apruebe la Prueba de Turing. Para conocer más acerca de su vida, consulte su página Web personal. David escribe las columnas developerWorks Charming Python y XML Matters desde el año 2000. Consulte su libroText Processing in Python [Procesamiento de texto en Python].

Compilación y edición: Ing. Sergio Aguilera. Facultad de Tecnología Informática. Universidad de Belgrano. [email protected] Todos los Derechos Reservados a IBM Corp. – Marzo 2012.

7