Sie sind auf Seite 1von 19

IPTables

Contents Contenido 1. 2. 3. 4. 5. 6. 7. 8. 9. Introduction Introduccin Getting Started Primeros pasos Writing a Simple Rule Set Escribir un conjunto de reglas simples Interfaces Interfaces IP Addresses Direcciones IP Ports and Protocols Puertos y protocolos Putting It All Together Poniendo todo junto Summary Resumen Links Enlaces

1. 1. Introduction Introduccin
CentOS has an extremely powerful firewall built in, commonly referred to as iptables, but more accurately is iptables/netfilter. CentOS tiene un firewall muy potente integrado, comnmente conocido como iptables, pero ms exactamente es iptables / netfilter. Iptables is the userspace module, the bit that you, the user, interact with at the command line to enter firewall rules into predefined tables. Iptables es el mdulo de espacio de usuario, la parte que usted, el usuario, interactuar con la lnea de comandos para introducir las reglas del firewall en tablas predefinidas. Netfilter is a kernel module, built into the kernel, that actually does the filtering. Netfilter es un mdulo del kernel, construido en el ncleo, que en realidad hace el filtrado. There are many GUI front ends for iptables that allow users to add or define rules based on a point and click user interface, but these often lack the flexibility of using the command line interface and limit the users understanding of what's really happening. Hay muchos GUI para iptables extremos que permiten a los usuarios agregar o definir reglas basadas en un punto y haga clic en la interfaz de usuario, pero estos a menudo carecen de la flexibilidad de usar la interfaz de lnea de comandos y limitar los usuarios la comprensin de lo que realmente est sucediendo. We're going to learn the command line interface of iptables. Vamos a aprender la interfaz de lnea de comandos de iptables. Before we can really get to grips with iptables, we need to have at least a basic understanding of the way it works. Antes de que podamos conseguir a los apretones con iptables, es necesario tener al menos un conocimiento bsico de la forma en que funciona. Iptables uses the concept of IP addresses, protocols (tcp, udp, icmp) and ports. Iptables utiliza el concepto de direcciones IP, protocolos (TCP, UDP, ICMP) y puertos. We don't need to be experts in these to get started (as we can look up any of the information we need), but it helps to have a general understanding. No necesitamos ser expertos en estas para empezar (como podemos ver a ninguno de la informacin que necesitamos), pero ayuda a tener un conocimiento general. Iptables places rules into predefined chains (INPUT, OUTPUT and FORWARD) that are checked against any network traffic (IP packets) relevant to those chains and a decision is made about what to do with each packet based upon the outcome of those rules, ie accepting or dropping the packet. Iptables lugares reglas en las cadenas predefinidas (INPUT, OUTPUT y FORWARD) que se comparan con cualquier trfico

de red (paquetes IP) correspondientes a las cadenas y la decisin se hace acerca de qu hacer con cada paquete en funcin del resultado de dichas normas, es decir, aceptar o dejar caer el paquete. These actions are referred to as targets, of which the two most common predefined targets are DROP to drop a packet or ACCEPT to accept a packet. Estas acciones se conocen como los objetivos, de los cuales los dos objetivos predefinidos ms comunes son DROP para descartar un paquete o ACEPTAR para aceptar un paquete. Chains Cadenas These are 3 predefined chains in the filter table to which we can add rules for processing IP packets passing through those chains. Estas son las tres cadenas predefinidas en la tabla de filtros que podemos agregar reglas para el procesamiento de paquetes IP que pasan a travs de esas cadenas. These chains are: Estas cadenas son:

INPUT - All packets destined for the host computer. ENTRADA - Todos los paquetes destinados para el equipo anfitrin. OUTPUT - All packets originating from the host computer. SALIDA - Todos los paquetes provenientes de la computadora host. FORWARD - All packets neither destined for nor originating from the host computer, but passing through (routed by) the host computer. ADELANTE Todos los paquetes no destinados a la ni originarios del equipo anfitrin, pero que pasa por (derrotado por) el equipo host. This chain is used if you are using your computer as a router. Esta cadena se utiliza si est utilizando el ordenador como un router.

For the most part, we are going to be dealing with the INPUT chain to filter packets entering our machine - that is, keeping the bad guys out. En su mayor parte, vamos a tener trato con la cadena INPUT para filtrar los paquetes que entran en nuestra mquina - es decir, mantener a los chicos malos. Rules are added in a list to each chain. Las reglas se agreg en una lista de cada cadena. A packet is checked against each rule in turn, starting at the top, and if it matches that rule, then an action is taken such as accepting (ACCEPT) or dropping (DROP) the packet. Un paquete se compara con cada regla, a su vez, comenzando en la parte superior, y si coincide con esa regla, a continuacin, se realice una accin como aceptar (ACCEPT) o dejar caer (DROP) el paquete. Once a rule has been matched and an action taken, then the packet is processed according to the outcome of that rule and isn't processed by further rules in the chain. Una vez que el Estado ha ido a la par y una accin tomada, entonces el paquete es procesado de acuerdo a los resultados de dicha norma, y no est procesado por otras normas de la cadena. If a packet passes down through all the rules in the chain and reaches the bottom without being matched against any rule, then the default action for that chain is taken. Si el paquete pasa a travs de todas las reglas de la cadena y llega al fondo sin que se compara con ninguna norma, entonces la accin predeterminada para que la cadena se toma. This is referred to as the default policy and may be set to either ACCEPT or DROP the packet. Esto se conoce como la poltica por defecto y puede ser configurado como ACCEPT o DROP el paquete.

The concept of default policies within chains raises two fundamental possibilities that we must first consider before we decide how we are going to organize our firewall. El concepto de las polticas por defecto dentro de las cadenas plantea dos posibilidades fundamentales que debemos considerar primero antes de decidir cmo vamos a organizar nuestro cortafuegos. 1. 1. We can set a default policy to DROP all packets and then add rules to specifically allow (ACCEPT) packets that may be from trusted IP addresses, or for certain ports on which we have services running such as bittorrent, FTP server, Web Server, Samba file server etc. Podemos establecer una poltica por defecto a DROP todos los paquetes y luego agregar reglas para permitir especficamente (ACCEPT) paquetes que pueden ser de confianza las direcciones IP, o para ciertos puertos en los que tenemos servicios que se ejecutan como bittorrent, servidor FTP, servidor Web, Samba servidor de archivos, etc or alternatively, o, alternativamente, 2. 2. We can set a default policy to ACCEPT all packets and then add rules to specifically block (DROP) packets that may be from specific nuisance IP addresses or ranges, or for certain ports on which we have private services or no services running. Podemos establecer una poltica ACCEPT todos los paquetes y luego agregar reglas para bloquear especficamente (DROP) los paquetes que pueden ser especficos de molestia o rangos de direcciones IP, o para ciertos puertos en los que tenemos los servicios privados o no servicios en ejecucin. Generally, option 1 above is used for the INPUT chain where we want to control what is allowed to access our machine and option 2 would be used for the OUTPUT chain where we generally trust the traffic that is leaving (originating from) our machine. En general, la opcin 1 anterior se utiliza para la cadena INPUT en el que desea controlar lo que est permitido el acceso a nuestra mquina y la opcin 2 se utilizarn para la cadena OUTPUT, donde por lo general, la confianza del trfico que se va (procedente de) nuestra mquina.

2. 2. Getting Started Primeros pasos


Working with iptables from the command line requires root privileges, so you will need to become root for most things we will be doing. Trabajar con iptables desde la lnea de comando requiere privilegios de root, por lo que tendr que convertirse en root para la mayora de las cosas que vamos a hacer. IMPORTANT: We will be turning off iptables and resetting your firewall rules, so if you are reliant on your Linux firewall as your primary line of defense you should be aware of this. IMPORTANTE: Vamos a apagar iptables y restablecer las reglas de cortafuegos, as que si dependen de su firewall de Linux como su primera lnea de defensa debe ser consciente de ello. Iptables should be installed by default on all CentOS 3.x, 4.x and 5.x installations. Iptables debe ser instalado por defecto en todas las CentOS 3.x, 4.xy 5.x instalaciones.

You can check to see if iptables is installed on your system by: Usted puede comprobar para ver si iptables est instalado en su sistema:
$ rpm -q iptables iptables $ rpm-q iptables-1.3.5-1.2.1 iptables-1.3.5-1.2.1

And to see if iptables is actually running, we can check that the iptables modules are loaded and use the -L switch to inspect the currently loaded rules: Y para ver si realmente se est ejecutando iptables, podemos comprobar que los mdulos de iptables se cargan y utilizar la opcin-L para inspeccionar las normas actualmente cargado:
# lsmod | grep ip_tables # Lsmod | grep ip_tables ip_tables 29288 1 iptable_filter ip_tables 29288 1 iptable_filter x_tables 29192 6 ip6t_REJECT,ip6_tables,ipt_REJECT,xt_state,xt_tcpudp,ip_tables x_tables 29.192 6 ip6t_REJECT, ip6_tables, ipt_REJECT, xt_state, xt_tcpudp, ip_tables # iptables -L # Iptables-L Chain INPUT (policy ACCEPT) Chain INPUT (policy ACCEPT) target prot opt source destination prot objetivo optar origen destino RH-Firewall-1-INPUT all -- anywhere anywhere RHFirewall-1-input todos - en cualquier lugar en cualquier lugar Chain FORWARD (policy ACCEPT) Cadena FORWARD (policy ACCEPT) target prot opt source destination prot objetivo optar origen destino RH-Firewall-1-INPUT all -- anywhere anywhere RHFirewall-1-input todos - en cualquier lugar en cualquier lugar Chain OUTPUT (policy ACCEPT) Cadena OUTPUT (policy ACCEPT) target prot opt source destination prot objetivo optar origen destino Chain RH-Firewall-1-INPUT (2 references) Cadena RH-Firewall-1-input (2 referencias) target prot opt source destination prot objetivo optar origen destino ACCEPT all -- anywhere anywhere ACEPTAR todos - en cualquier lugar en cualquier lugar ACCEPT icmp -- anywhere anywhere icmp any ACCEPT icmp - en cualquier lugar en cualquier lugar icmp cualquier ACCEPT esp -- anywhere anywhere ACEPTAR especialmente - en cualquier lugar en cualquier lugar ACCEPT ah -- anywhere anywhere ah ACEPTAR - en cualquier lugar en cualquier lugar ACCEPT udp -- anywhere 224.0.0.251 udp dpt:mdns ACCEPT udp - en cualquier lugar 224.0.0.251 dpt udp: mdns ACCEPT udp -- anywhere anywhere udp dpt:ipp ACCEPT udp - en cualquier lugar en cualquier lugar udp dpt: ipp ACCEPT tcp -- anywhere anywhere tcp dpt:ipp tcp ACCEPT - en cualquier lugar en cualquier lugar tcp dpt: ipp ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED ACEPTAR todos - en cualquier lugar en cualquier parte del estado RELACIONADOS, ESTABLECIDO ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:ssh tcp ACCEPT - en cualquier lugar en cualquier parte del estado tcp dpt NUEVO: ssh

REJECT all -- anywhere anywhere rejectwith icmp-host-prohibited RECHAZAR todos - en cualquier lugar en cualquier lugar de desecho con icmp-host-prohibida

Above we see the default set of rules in addition to access to the SSH service. Arriba vemos el conjunto predeterminado de reglas, adems de acceso al servicio SSH. If iptables is not running, you can enable it by running: Si iptables no se est ejecutando, se puede activar mediante la ejecucin de:
# system-config-securitylevel # System-config-securitylevel

3. 3. Writing a Simple Rule Set Escribir un conjunto de reglas simples


IMPORTANT: At this point we are going to clear the default rule set. IMPORTANTE: En este punto vamos a borrar la regla por defecto. If you are connecting remotely to a server via SSH for this tutorial then there is a very real possibility that you could lock yourself out of your machine. Si se conecta remotamente a un servidor va SSH para este tutorial, entonces hay una posibilidad muy real de que usted podra dejarlo fuera de su mquina. You must set the default input policy to accept before flushing the current rules, and then add a rule at the start to explicitly allow yourself access to prevent against locking yourself out. Debe establecer la poltica de entrada por defecto para aceptar antes de enjuagar las normas vigentes, y luego agregar una regla al comienzo mismo de manera explcita permitir el acceso a prevenir contra el bloqueo a ti mismo. We will use an example based approach to examine the various iptables commands. Vamos a utilizar un enfoque basado en ejemplos para examinar los comandos iptables diferentes. In this first example, we will create a very simple set of rules to set up a Stateful Packet Inspection (SPI) firewall that will allow all outgoing connections but block all unwanted incoming connections: En este primer ejemplo, vamos a crear un conjunto muy simple de reglas para establecer un Stateful Packet Inspection (SPI) que permitir a todas las conexiones salientes, pero bloquear todas las conexiones entrantes no deseados:
# iptables -P INPUT ACCEPT # Iptables-P INPUT ACCEPT # iptables -F # Iptables-F # iptables -A INPUT -i lo -j ACCEPT # Iptables-A INPUT-i lo-j ACCEPT # iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # Iptables-Un estado de la entrada-m - el estado ESTABLISHED, RELATED-j ACCEPT # iptables -A INPUT -p tcp --dport 22 j ACCEPT # Iptables-A INPUT-p tcp - dport 22-j ACCEPT # iptables -P INPUT DROP # Iptables-P INPUT GOTA # iptables -P FORWARD DROP # Iptables-P FORWARD DROP # iptables -P OUTPUT ACCEPT # Iptables-P OUTPUT ACCEPT # iptables -L -v # Iptables-L-v

which should give the following output: que debe dar el siguiente resultado:
Chain INPUT (policy DROP 0 packets, 0 bytes) Cadena INPUT (poltica GOTA 0 paquetes, 0 bytes) pkts bytes target prot opt in out source destination pkts prot objetivo bytes optar a cabo origen destino 0 0 ACCEPT all -- lo any anywhere

anywhere 0 0 ACEPTA todas - lo que ninguna de cualquier lugar en cualquier lugar 0 0 ACCEPT all -- any any anywhere anywhere state RELATED,ESTABLISHED 0 0 ACEPTAR todos cualquier cualquier lugar en cualquier parte del estado RELACIONADOS, ESTABLECIDO 0 0 ACCEPT tcp -- any any anywhere anywhere tcp dpt:ssh 0 0 ACCEPT tcp - cualquiera cualquiera en cualquier lugar en cualquier lugar tcp dpt: ssh Chain FORWARD (policy DROP 0 packets, 0 bytes) Cadena FORWARD (poltica GOTA 0 paquetes, 0 bytes) pkts bytes target prot opt in out source destination pkts prot objetivo bytes optar a cabo origen destino Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes) Cadena OUTPUT (policy ACCEPT 0 paquetes, 0 bytes) pkts bytes target prot opt in out source destination pkts prot objetivo bytes optar a cabo origen destino

Now lets look at each of the 8 commands above in turn and understand exactly what we've just done: Ahora echemos un vistazo a cada uno de los ocho comandos de arriba, a su vez y entender exactamente lo que acabas de hacer: 1. iptables -P INPUT ACCEPT If connecting remotely we must first temporarily set the default policy on the INPUT chain to ACCEPT otherwise once we flush the current rules we will be locked out of our server. iptables-P INPUT ACCEPT Si se conecta de forma remota, debemos primero establecer temporalmente la poltica por defecto en la cadena INPUT para ACEPTAR lo contrario una vez que lave la normativa vigente que se cerr la puerta de nuestro servidor. 2. iptables -F We used the -F switch to flush all existing rules so we start with a clean state from which to add new rules. iptables-F Se utiliz el modificador-F para eliminar todas las normas existentes por lo que comenzar con un estado limpio desde el que aadir las nuevas normas. 3. iptables -A INPUT -i lo -j ACCEPT Now it's time to start adding some rules. iptables-A INPUT-i lo-j ACCEPT Ahora es el momento para empezar a aadir algunas reglas. We use the -A switch to append (or add) a rule to a specific chain, the INPUT chain in this instance. Nosotros usamos el parmetro-A para aadir (o aadir) una regla a una cadena especfica, la cadena INPUT en este caso. Then we use the -i switch (for interface) to specify packets matching or destined for the lo (localhost, 127.0.0.1) interface and finally -j (jump) to the target action for packets matching the rule - in this case ACCEPT. Luego usamos la opcin-i (para la interfaz) para especificar los paquetes que coinciden o destinados a la LO (localhost, 127.0.0.1) interfaz y, finalmente,-j (salto) a la accin de destino para paquetes que coincidan con el Estado - en este caso ACEPTAR. So this rule will allow all incoming packets destined for the localhost interface to be accepted. As que esta norma permitir a todos los paquetes entrantes destinados a la interfaz de la mquina local para ser aceptado. This is generally required as many software applications expect to be able to communicate with the localhost adaptor. Esto generalmente se requiere mayor nmero de aplicaciones de software esperar ser capaz de comunicarse con el adaptador de host local. 4. iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT This is the rule that does most of the work, and again we are adding (-A) it to the INPUT chain. iptables-A-m estado de la entrada - el estado ESTABLISHED, RELATED-j ACCEPT Esta es la regla que hace la mayor parte de la obra, y de nuevo estamos aadiendo (-A) a la cadena INPUT. Here we're using the -m

5.

6.

7.

8.

9.

switch to load a module (state). Aqu estamos usando el modificador-m para cargar el mdulo (del estado). The state module is able to examine the state of a packet and determine if it is NEW, ESTABLISHED or RELATED. El mdulo de estado es capaz de examinar el estado de un paquete y determinar si es nueva, creada o relacionados. NEW refers to incoming packets that are new incoming connections that weren't initiated by the host system. NEW se refiere a los paquetes entrantes que son nuevas conexiones entrantes que no fueron iniciadas por el sistema host. ESTABLISHED and RELATED refers to incoming packets that are part of an already established connection or related to and already established connection. ESTABLISHED y RELATED se refiere a los paquetes entrantes que forman parte de una conexin ya establecida o relacionada y conexin ya establecida. iptables -A INPUT -p tcp --dport 22 -j ACCEPT Here we add a rule allowing SSH connections over tcp port 22. iptables-A-p tcp ENTRADA - dport 22-j ACCEPT Aqu aadimos una regla que permite conexiones SSH a travs del puerto TCP 22. This is to prevent accidental lockouts when working on remote systems over an SSH connection. Esto es para evitar cierres accidentales cuando se trabaja en sistemas remotos a travs de una conexin SSH. We will explain this rule in more detail later. Vamos a explicar esta regla en ms detalle ms adelante. iptables -P INPUT DROP The -P switch sets the default policy on the specified chain. iptables-P INPUT DROP-P El parmetro establece la poltica por defecto en la cadena especificada. So now we can set the default policy on the INPUT chain to DROP. As que ahora podemos poner la poltica por defecto en la cadena INPUT a DROP. This means that if an incoming packet does not match one of the following rules it will be dropped. Esto significa que si un paquete entrante no coincide con una de las siguientes reglas que ser dado de baja. If we were connecting remotely via SSH and had not added the rule above, we would have just locked ourself out of the system at this point. Si se conecta remotamente a travs de SSH y no se haba aadido la norma anterior, se acaba de nosotros mismos cerrado del sistema en este momento. iptables -P FORWARD DROP Similarly, here we've set the default policy on the FORWARD chain to DROP as we're not using our computer as a router so there should not be any packets passing through our computer. iptables-P FORWARD DROP Del mismo modo, aqu nos hemos propuesto la poltica por defecto en la cadena FORWARD a DROP, ya que no est usando nuestro ordenador como un router por lo que no debera haber paquetes que pasan a travs de nuestro equipo. iptables -P OUTPUT ACCEPT and finally, we've set the default policy on the OUTPUT chain to ACCEPT as we want to allow all outgoing traffic (as we trust our users). iptables-P OUTPUT ACCEPT y, por ltimo, hemos cambiado la poltica por defecto en la cadena OUTPUT a aceptar como queremos permitir todo el trfico saliente (como la confianza de nuestros usuarios). iptables -L -v Finally, we can list (-L) the rules we've just added to check they've been loaded correctly. iptables-L-v Por ltimo, podemos listar (-L) las normas que acabamos de agregar para comprobar que han sido cargados correctamente.

Finally, the last thing we need to do is save our rules so that next time we reboot our computer our rules are automatically reloaded: Finalmente, la ltima cosa que

necesitamos hacer es salvar a nuestras reglas para que la prxima vez que reinicie nuestro ordenador nuestras reglas son automticamente vuelve a cargar:
# /sbin/service iptables save # / Sbin / service iptables save

This executes the iptables init script, which runs /sbin/iptables-save and writes the current iptables configuration to /etc/sysconfig/iptables. Esto ejecuta el script de inicio de iptables, que se ejecuta / sbin / iptables-save y escribe la configuracin actual de iptables a / etc / sysconfig / iptables. Upon reboot, the iptables init script reapplies the rules saved in /etc/sysconfig/iptables by using the /sbin/iptables-restore command. En el arranque, el script de inicio de iptables volver a aplicar las reglas guardadas en / etc / sysconfig / iptables usando el comando / sbin / iptables-restore. Obviously typing all these commands at the shell can become tedious, so by far the easiest way to work with iptables is to create a simple script to do it all for you. Es evidente que escribir a todos estos comandos en el intrprete puede llegar a ser tedioso, por lo que, con mucho, la forma ms fcil de trabajar con iptables es crear un script sencillo que hacerlo todo para usted. The above commands may be entered into your favourite text editor and saved as myfirewall, for example: Los comandos de arriba puede ser introducido en su editor de texto favorito y se guarda como MyFirewall, por ejemplo:
#!/bin/bash #! / Bin / bash # # # iptables example configuration script # Iptables ejemplo script de configuracin # # # Flush all current rules from iptables # Lavar toda la reglamentacin vigente de iptables # # iptables -F iptables-F # # # Allow SSH connections on tcp port 22 # Permitir conexiones SSH en el puerto TCP 22 # This is essential when working on remote servers via SSH to prevent locking yourself out of the system # Esto es esencial cuando se trabaja en servidores remotos a travs de SSH para impedir el bloqueo mismo del sistema # # iptables -A INPUT -p tcp --dport 22 -j ACCEPT iptables-A INPUT-p tcp - dport 22-j ACCEPT # # # Set default policies for INPUT, FORWARD and OUTPUT chains # Establezca las polticas por defecto para INPUT, FORWARD y OUTPUT cadenas # # iptables -P INPUT DROP iptables-P INPUT GOTA iptables -P FORWARD DROP iptables-P FORWARD DROP iptables -P OUTPUT ACCEPT iptables-P OUTPUT ACCEPT # # # Set access for localhost # Establecer el acceso a localhost # # iptables -A INPUT -i lo -j ACCEPT iptables-A INPUT-i lo-j ACCEPT # # # Accept packets belonging to established and related connections # Acepta los paquetes que pertenecen a las conexiones establecidas y relacionadas # # iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT iptables-Un estado de la entrada-m - el estado ESTABLISHED, RELATED-j ACCEPT # # # Save settings # Guardar las opciones # # /sbin/service iptables save / Sbin / service iptables guardar # # # List rules # Lista de normas # # iptables L -v iptables-L-v

Note: We can also comment our script to remind us what were doing. Nota: Tambin puede comentar nuestro script para recordarnos lo que estaban haciendo. now make the script executable: ahora hacer el script ejecutable:
# chmod +x myfirewall # Chmod + x MyFirewall

We can now simply edit our script and run it from the shell with the following command: Ahora podemos simplemente modificar el script y ejecutarlo desde la shell con el siguiente comando:
# ./myfirewall #. / MyFirewall

4. 4. Interfaces Interfaces
In our previous example, we saw how we could accept all packets incoming on a particular interface, in this case the localhost interface: En nuestro ejemplo anterior, vimos cmo podramos aceptar todos los paquetes entrantes en una interfaz en particular, en este caso la interfaz localhost:
iptables -A INPUT -i lo -j ACCEPT iptables-A INPUT-i lo-j ACCEPT

Suppose we have 2 separate interfaces, eth0 which is our internal LAN connection and ppp0 dialup modem (or maybe eth1 for a nic) which is our external internet connection. Supongamos que tenemos dos interfaces separadas, eth0, que es nuestra conexin LAN interna y ppp0 mdem de acceso telefnico (o tal vez de una tarjeta de red eth1), que es nuestra conexin a Internet externos. We may want to allow all incoming packets on our internal LAN but still filter incoming packets on our external internet connection. Es posible que desea permitir todos los paquetes entrantes en nuestra LAN interna, pero an filtrar los paquetes entrantes en nuestra conexin a Internet externos. We could do this as follows: Podramos hacerlo de la siguiente manera:
iptables -A INPUT -i lo -j ACCEPT iptables-A INPUT-i lo-j ACCEPT iptables -A INPUT -i eth0 -j ACCEPT iptables-A INPUT-i eth0-j ACCEPT

But be very careful - if we were to allow all packets for our external internet interface (for example, ppp0 dialup modem): Pero tenga mucho cuidado - si furamos a permitir que todos los paquetes para nuestra interfaz web externos (por ejemplo, un mdem de acceso telefnico ppp0):
iptables -A INPUT -i ppp0 -j ACCEPT iptables-A INPUT-i ppp0-j ACCEPT

we would have effectively just disabled our firewall! tendramos que efectivamente slo discapacitados nuestro cortafuegos!

5. 5. IP Addresses Direcciones IP
Opening up a whole interface to incoming packets may not be restrictive enough and you may want more control as to what to allow and what to reject. La apertura de una interfaz de todo a los paquetes entrantes no puede ser restrictiva suficiente y que quieren un mayor control en cuanto a qu permitir y qu rechazar. Lets suppose we have a small network of computers that use the 192.168.0.x private subnet. Supongamos que tenemos una pequea red de ordenadores que utilizan la subred privada 192.168.0.x. We can open up our firewall to incoming packets from a single trusted IP address (for example, 192.168.0.4): Podemos abrir nuestro servidor de seguridad para los paquetes entrantes desde una nica direccin IP de confianza (por ejemplo, 192.168.0.4):

# Accept packets from trusted IP addresses # Acepta los paquetes de las direcciones IP de confianza iptables -A INPUT -s 192.168.0.4 -j ACCEPT # change the IP address as appropriate iptables-A INPUT-s 192.168.0.4-j ACCEPT # cambiar la direccin IP en su caso

Breaking this command down, we first append (-A) a rule to the INPUT chain for the source (-s) IP address 192.168.0.4 to ACCEPT all packets (also note how we can use the # symbol to add comments inline to document our script with anything after the # being ignored and treated as a comment). El incumplimiento de esta orden se establecen, en primer lugar de agregar (-A) una regla para la cadena INPUT de la fuente (-s) la direccin IP 192.168.0.4 a aceptar todos los paquetes (tambin en cuenta la forma en que puede utilizar el smbolo # para aadir comentarios en lnea para el documento nuestro script con cualquier cosa despus de la # siendo ignorado y tratado como un comentario). Obviously if we want to allow incoming packets from a range of IP addresses, we could simply add a rule for each trusted IP address and that would work fine. Obviamente si queremos permitir que los paquetes entrantes de un rango de direcciones IP, que podra simplemente aadir una regla para cada direccin IP confiable y que funcione bien. But if we have a lot of them, it may be easier to add a range of IP addresses in one go. Pero si tenemos un montn de ellos, puede ser ms fcil para agregar un rango de direcciones IP en una sola vez. To do this, we can use a netmask or standard slash notation to specify a range of IP address. Para ello, podemos utilizar una mscara de red o notacin estndar para especificar un rango de direcciones IP. For example, if we wanted to open our firewall to all incoming packets from the complete 192.168.0.x (where x=1 to 254) range, we could use either of the following methods: Por ejemplo, si queremos abrir nuestro servidor de seguridad para todos los paquetes entrantes de la completa 192.168.0.x (donde x = 1 a 254) amplia, podemos utilizar cualquiera de los siguientes mtodos:
# Accept packets from trusted IP addresses # Acepta los paquetes de las direcciones IP de confianza iptables -A INPUT -s 192.168.0.0/24 -j ACCEPT # using standard slash notation iptables-A INPUT-s 192.168.0.0/24-j ACCEPT # utilizando notacin estndar iptables -A INPUT -s 192.168.0.0/255.255.255.0 -j ACCEPT # using a subnet mask iptables-A INPUT-s 192.168.0.0/255.255.255.0-j ACCEPT # con una mscara de subred

Finally, as well as filtering against a single IP address, we can also match against the MAC address for the given device. Por ltimo, as como el filtrado en contra de una nica direccin IP, tambin podemos coincidir con la direccin MAC para el dispositivo dado. To do this, we need to load a module (the mac module) that allows filtering against mac addresses. Para ello, tenemos que cargar un mdulo (el mdulo de Mac) que permite el filtrado de direcciones MAC en contra. Earlier we saw another example of using modules to extend the functionality of iptables when we used the state module to match for ESTABLISHED and RELATED packets. Antes vimos otro ejemplo del uso de mdulos para extender la funcionalidad de iptables cuando se utiliz el mdulo de estado a la altura de los paquetes ESTABLISHED y RELATED. Here we use the mac module to check the mac address of the source of the packet in addition to it's IP address: Aqu se utiliza el mdulo de mac para verificar la direccin MAC de la fuente del paquete, adems de su direccin IP:

# Accept packets from trusted IP addresses # Acepta los paquetes de las direcciones IP de confianza iptables -A INPUT -s 192.168.0.4 -m mac --mac-source 00:50:8D:FD:E6:32 -j ACCEPT iptables-A INPUT-s 192.168.0.4-m mac mac-source 00:50:8 D: FD: E6: 32-j ACCEPT

First we use -m mac to load the mac module and then we use --mac-source to specify the mac address of the source IP address (192.168.0.4). En primer lugar, el uso-m mac para cargar el mdulo mac y luego usamos - mac-source para especificar la direccin MAC de la direccin IP de origen (192.168.0.4). You will need to find out the mac address of each ethernet device you wish to filter against. Usted tendr que averiguar la direccin MAC de cada dispositivo de red que desea filtrar en contra. Running ifconfig (or iwconfig for wireless devices) as root will provide you with the mac address. Ejecutando ifconfig (o iwconfig para dispositivos inalmbricos) como root le proporcionar la direccin MAC. This may be useful for preventing spoofing of the source IP address as it will allow any packets that genuinely originate from 192.168.0.4 (having the mac address 00:50:8D:FD:E6:32) but will block any packets that are spoofed to have come from that address. Esto puede ser til para prevenir la suplantacin de la direccin IP de origen, ya que permitir que todos los paquetes que realmente vienen de 192.168.0.4 (que tiene la direccin mac 00:50:8 D: FD: E6: 32), pero bloquear cualquier paquete que se imitan que han venido de esa direccin. Note, mac address filtering won't work across the internet but it certainly works fine on a LAN. Tenga en cuenta, filtrado de direcciones MAC no funcionar a travs de Internet, pero ciertamente funciona bien en una LAN.

6. 6. Ports and Protocols Puertos y protocolos


Above we have seen how we can add rules to our firewall to filter against packets matching a particular interface or a source IP address. Arriba hemos visto cmo podemos agregar reglas a nuestro servidor de seguridad para filtrar los paquetes que coinciden en contra de una interfaz en particular o una direccin IP de origen. This allows full access through our firewall to certain trusted sources (host PCs). Esto permite un acceso completo a travs de nuestro servidor de seguridad para ciertas fuentes de confianza (PC anfitrin). Now we'll look at how we can filter against protocols and ports to further refine what incoming packets we allow and what we block. Ahora veremos cmo podemos filtro contra los protocolos y puertos para perfeccionar lo que los paquetes entrantes que aprobamos y lo bloqueamos. Before we can begin, we need to know what protocol and port number a given service uses. Antes de que podamos empezar, necesitamos saber qu protocolo y nmero de puerto usa un determinado servicio. For a simple example, lets look at bittorrent. Para un ejemplo sencillo, veamos bittorrent. Bittorrent uses the tcp protocol on port 6881, so we would need to allow all tcp packets on destination port (the port on which they arrive at our machine) 6881: Bittorrent utiliza el protocolo TCP en el puerto 6881, por lo que tendra que permitir que todos los paquetes TCP en el puerto de destino (el puerto en el que llegan a nuestra mquina) 6881:
# Accept tcp packets on destination port 6881 (bittorrent) # Aceptar paquetes tcp en el puerto de destino 6881 (bittorrent)

iptables -A INPUT -p tcp --dport 6881 -j ACCEPT iptables-A INPUT-p tcp - dport 6881-j ACCEPT

Here we append (-A) a rule to the INPUT chain for packets matching the tcp protocol ( -p tcp ) and entering our machine on destination port 6881 ( --dport 6881 ). Aqu aadimos (-A) una regla para la cadena INPUT para paquetes que coincidan con el protocolo tcp (-p tcp) y entrar en nuestra mquina en el puerto de destino 6881 (dport 6881).

Note: In order to use matches such as destination or source ports ( --dport or --sport ), you must first specify the protocol (tcp, udp, icmp, all). Nota: Para utilizar los partidos como los puertos de destino o de origen (- dport o - el deporte), primero debe especificar el protocolo (TCP, UDP, ICMP, todos). We can also extend the above to include a port range, for example, allowing all tcp packets on the range 6881 to 6890: Tambin puede extender la parte superior para incluir un rango de puertos, por ejemplo, permitiendo que todos los paquetes TCP en el rango de 6881 a 6890:
# Accept tcp packets on destination ports 6881-6890 # Aceptar paquetes TCP en puertos de destino 6881-6890 iptables -A INPUT -p tcp --dport 6881:6890 -j ACCEPT iptables-A INPUT-p tcp - dport 6881:6890-j ACCEPT

7. 7. Putting It All Together Poniendo todo junto


Now we've seen the basics, we can start combining these rules. Ahora que hemos visto los conceptos bsicos, podemos empezar a combinar estas normas. A popular UNIX/Linux service is the secure shell (SSH) service allowing remote logins. Un popular de UNIX / Linux es el shell seguro (SSH), servicio que permite conexiones remotas. By default SSH uses port 22 and again uses the tcp protocol. Por defecto SSH usa el puerto 22 y vuelve a utilizar el protocolo TCP. So if we want to allow remote logins, we would need to allow tcp connections on port 22: As que si queremos permitir el acceso remoto, tendramos que permitir conexiones TCP en el puerto 22:
# Accept tcp packets on destination port 22 (SSH) # Aceptar paquetes tcp en el puerto de destino 22 (SSH) iptables -A INPUT -p tcp --dport 22 -j ACCEPT iptables-A INPUT-p tcp - dport 22-j ACCEPT

This will open up port 22 (SSH) to all incoming tcp connections which poses a potential security threat as hackers could try brute force cracking on accounts with weak passwords. Esto abrir el puerto 22 (SSH) para todas las conexiones TCP entrantes que constituye una amenaza para la seguridad que los hackers podran tratar de fuerza bruta en las cuentas con contraseas dbiles. However, if we know the IP addresses of trusted remote machines that will be used to log on using SSH, we can limit access to only these source IP addresses. Sin embargo, si sabemos que las direcciones IP de confianza equipos remotos que se utilizar para iniciar la sesin SSH usando, podemos limitar el acceso slo a las direcciones IP de origen. For example, if we just wanted to open up SSH access on our private lan (192.168.0.x), we can limit access to just this source IP

address range: Por ejemplo, si slo queramos abrir el acceso SSH en nuestra LAN privada (192.168.0.x), que puede limitar el acceso slo a este rango de direccin IP de origen:
# Accept tcp packets on destination port 22 (SSH) from private LAN # Aceptar paquetes tcp en el puerto de destino 22 (SSH) de LAN privada iptables -A INPUT -p tcp -s 192.168.0.0/24 --dport 22 -j ACCEPT iptables-A INPUT-p tcp-s 192.168.0.0/24 - dport 22-j ACCEPT

Using source IP filtering allows us to securely open up SSH access on port 22 to only trusted IP addresses. Usando fuentes de filtrado de IP nos permite abrir de forma segura el acceso SSH en el puerto 22 a slo las direcciones IP de confianza. For example, we could use this method to allow remote logins between work and home machines. Por ejemplo, podramos utilizar este mtodo para permitir el acceso remoto entre los equipos de trabajo y el hogar. To all other IP addresses, the port (and service) would appear closed as if the service were disabled so hackers using port scanning methods are likely to pass us by. Para el resto de direcciones IP, el puerto (y servicios) parece cerrado, como si el servicio se desactiva para los piratas informticos utilizando mtodos de escaneo de puertos es probable que nos pase por encima.

8. 8. Summary Resumen
We've barely scratched the surface of what can be achieved with iptables, but hopefully this HOWTO has provided a good grounding in the basics from which one may build more complicated rule sets. Apenas hemos araado la superficie de lo que puede lograrse con iptables, pero espero que esta gua ha proporcionado una buena base en los fundamentos de la que se pueden construir conjuntos de reglas ms complicadas.

9. 9. Links Enlaces
http://www.centos.org/docs/5/html/Deployment_Guide-en-US/ch-fw.html http://www.centos.org/docs/5/html/Deployment_Guide-en-US/ch-fw.html http://www.centos.org/docs/5/html/Deployment_Guide-en-US/ch-iptables.html http://www.centos.org/docs/5/html/Deployment_Guide-en-US/ch-iptables.html

CMO de Red Hat Enterprise Linux 5 configurar la tarjeta de red


by Vivek Gite on April 10, 2007 48 comments por Vivek Gite el 10 de abril de 2007 48 comentarios

Q. I've installed Red Hat enterprise Linux 5 and now added one more LAN card (NIC). P. He instalado Red Hat Enterprise Linux 5 y ahora agreg una ms tarjeta LAN (NIC).

How do I configure the network card from the command line? Cmo puedo configurar la tarjeta de red desde la lnea de comandos? I can see 2nd my network card detected while booting the IBM server. Puedo ver mi segunda tarjeta de red detectada durante el arranque del servidor de IBM. A. Red hat Linux provides following tools to make changes to Network configuration such as add new card, assign IP address, change DNS server etc. A. Red Hat Linux proporciona las siguientes herramientas para hacer cambios en la configuracin de redes, tales como agregar nueva tarjeta, asignar la direccin IP, el cambio de servidor DNS, etc [a] GUI tool (X Windows required) - system-config-network [Una] herramienta de interfaz grfica de usuario (X Windows es necesario) - system-config-red [b] Command line text based GUI tool (No X Windows required) - system-confignetwork [B] texto de la lnea de comandos basada herramienta de interfaz grfica de usuario (no requiere Windows X) - system-config-red [c] Edit configuration files stored in /etc/sysconfig/network-scripts/ directory. [C] Editar archivos de configuracin almacenados en / etc / sysconfig / network-scripts /. Following instructions are compatible with Siguiendo las instrucciones son compatibles con (1) Cent OS Linux (1) el sistema operativo Linux Cent (2) Fedora Core Linux (2) Linux Fedora Core (3) Red Hat Enterprise Linux (RHEL) 3/4/5 (3) de Red Hat Enterprise Linux (RHEL) 3/4/5 Note: If you are using Debian or Ubuntu Linux, please see this configuration howto. Nota: Si usted est usando Debian o Ubuntu Linux, por favor ver esta configuracin howto.

Method # 1: GUI tool system-config-network Mtodo # 1: GUI herramienta system-config-red


Type the following command at shell prompt (open x terminal): Escriba el siguiente comando en el intrprete de comandos (terminal de apertura x):
$ system-config-network &

You will see Window as above. Ver la ventana de arriba. Now s elect your Ethernet card (eth0 or eth1) and click on Edit button. Ahora s elegir a su tarjeta Ethernet (eth0 o eth1) y haga clic en el botn Editar. You can now setup IP address, netmask, default gateway and other properties. Ahora puede configurar la direccin IP, mscara de red,

puerta de enlace predeterminada y otras propiedades.

You can obtain IP address using DHCP or setup manually. Usted puede obtener la direccin IP mediante DHCP o configuracin manual. Once IP address assigned, click on Ok button to save the changes. Una vez que la direccin IP asignada, haga clic en Ok para guardar los cambios. You can activate card by clicking on Activate button. Puede activar la tarjeta haciendo clic en el botn Activar.

Method # 2: Command line tool system-config-network-tui Mtodo # 2: sistema de la herramienta de lnea de comandos-config-network-tui
If you don't have X windows GUI installed type the following command at shell prompt: Si usted no tiene ventanas X tipo GUI instalado el comando siguiente en el intrprete de comandos:
# system-config-network-tui &

(click to enlarge image) (Click para ampliar la imagen) You will see text based GUI as above. Usted ver un texto basado en interfaz grfica de usuario que el anterior. Select your Ethernet card (eth0 or eth1) and hit [Enter] or [F12] special key. Seleccione la tarjeta Ethernet (eth0 o eth1) y pulsa [Enter] o [F12] llave especial.

(click to enlarge image) (Click para ampliar la imagen) You can obtain IP address using DHCP or setup manually. Usted puede obtener la direccin IP mediante DHCP o configuracin manual. Once IP address assigned, click on Ok button to save the changes Una vez que la direccin IP asignada, haga clic en Ok para guardar los cambios

Method #3: Edit configuration files stored in /etc/sysconfig/networkscripts/ Mtodo # 3: Editar archivos de configuracin almacenados en / etc / sysconfig / network-scripts /
You can configure network card by editing text files stored in /etc/sysconfig/networkscripts/ directory. Puede configurar la tarjeta de red por los archivos de edicin de texto almacenados en / etc / sysconfig / network-scripts /. First change directory to /etc/sysconfig/network-scripts/: Primer anuario cambio a / etc / sysconfig / networkscripts /:
# cd /etc/sysconfig/network-scripts/

You need to edit / create files as follows: Hay que editar / crear archivos de la siguiente manera:

/etc/sysconfig/network-scripts/ifcfg-eth0 : First Ethernet card configuration file / Etc/sysconfig/network-scripts/ifcfg-eth0: Primera tarjeta Ethernet archivo de configuracin /etc/sysconfig/network-scripts/ifcfg-eth1 : Second Ethernet card configuration file / Etc/sysconfig/network-scripts/ifcfg-eth1: segunda tarjeta Ethernet archivo de configuracin

To edit/create first NIC file, type command: Para modificar / crear el primer archivo de la NIC, escriba command:
# vi ifcfg-eth0

Append/modify as follows: Aadir / modificar la siguiente manera:


# Intel Corporation 82573E Gigabit Ethernet Controller (Copper) DEVICE=eth0 BOOTPROTO=static

DHCPCLASS= HWADDR=00:30:48:56:A6:2E IPADDR=10.10.29.66 NETMASK=255.255.255.192 ONBOOT=yes

Save and close the file. Guarde y cierre el archivo. Define default gateway (router IP) and hostname in /etc/sysconfig//network file: Definicin de puerta de enlace predeterminada (enrutador IP) y nombre de host en / etc / sysconfig / network /:
# vi /etc/sysconfig/network

Append/modify configuration as follows: Aadir / modificar la configuracin de la siguiente manera:


NETWORKING=yes HOSTNAME=www1.nixcraft.in GATEWAY=10.10.29.65

Save and close the file. Guarde y cierre el archivo. Restart networking: Reinicie la creacin de redes:
# /etc/init.d/network restart

Make sure you have correct DNS server defined in /etc/resolv.conf file: Asegrese de que tenga el servidor DNS correcto se define en el archivo / etc / resolv.conf:
# vi /etc/resolv.conf

Setup DNS Server as follows: Configuracin del servidor DNS de la siguiente manera:
nameserver 10.0.80.11 nameserver 10.0.80.12 nameserver 202.67.222.222

Save and close the file. Guarde y cierre el archivo. Now you can ping the gateway/other hosts: Ahora usted puede hacer ping a la puerta de enlace / hosts:
$ ping 10.0.80.12

Output: Salida:
PING 10.0.80.12 (10.0.80.12) 56(84) (10.0.80.12) 56 (84) bytes de datos. 64 bytes from 10.0.80.12: icmp_seq=1 10.0.80.12: icmp_seq \ = 1 ttl = 251 64 bytes from 10.0.80.12: icmp_seq=2 10.0.80.12: icmp_seq \ = 2 ttl = 251 bytes of data. PING 10.0.80.12 ttl=251 time=0.972 ms 64 bytes de tiempo = 0.972 ms ttl=251 time=1.11 ms 64 bytes de = tiempo de 1.11 ms

You can also check for Internet connectivity with nslookup or host command: Tambin puede comprobar si hay conexin a Internet con el comando nslookup o host:
$ nslookup cyberciti.biz

Output: Salida:
Server: Address: 10.0.80.11 Servidor: 10.0.80.11 10.0.80.11#53 Direccin: 10.0.80.11 # 53

Non-authoritative answer: Respuesta no autoritativa: Name: cyberciti.biz Nombre: cyberciti.biz Address: 75.126.43.232 Direccin: 75.126.43.232

You can also use host command: Tambin puede usar el comando de acogida:
$ host nixcraft.in

Output: Salida:

nixcraft.in has address 75.126.43.232 nixcraft.in tiene la direccin 75.126.43.232 nixcraft.in mail is handled by 10 mail.nixcraft.in. mail nixcraft.in se maneja en un 10 mail.nixcraft.in.

http://translate.googleusercontent.com/translate_c?hl=es&langpair=en|es&u=http://www.ce ntos.org/docs/5/html/Deployment_Guide-en-US/chfw.html&rurl=translate.google.com.ec&usg=ALkJrhjPOBkX1HikWBc2H62b2j4aDpwBcQ

Das könnte Ihnen auch gefallen