One place for hosting & domains

      Firewall

      Firewall Best Practices for Securing Your Cloud-Based Applications

      Moving to the cloud has many advantages, including flexibility, reduced management overhead, performance, and security. Cloud-based firewalls can offer finer-grained access control and more comprehensive threat mitigation than their traditional hardware-based counterparts.

      This guide outlines best practices for cloud-based firewall deployment. This includes network design review, creation of a security policy, firewall rule ordering, log analysis, and regular auditing.

      What Is a Firewall?

      A common misperception is that firewalls are just access-control devices that limit reachability to hosts and applications. While firewalls do provide access control, they also mitigate security threats in many other ways. In the broadest sense, a firewall is a device that enforces a security policy.

      Because firewalls often sit between network segments, they may also function as routers. Many commercial firewall products include some form of unified threat management (UTM). UTM bundles antivirus, anti-phishing, intrusion detection/prevention, and DDoS protection features along with access control.

      Over time, firewalls have moved up the application stack. The first implementations were simple filters that blocked or allowed individual packets based on IP address and port number. The next wave of products added stateful inspection, which monitor flows instead of individual packets.

      Modern firewalls, including so-called next-generation firewalls (NGFWs), operate at the application layer (L7). They may control access based on HTTP URLs, specific types of SQL queries, or other application-layer criteria.

      As part of a UTM bundle, some also perform deep-packet inspection (DPI). DPI peers into each packet’s application headers or body content to make forwarding/blocking decisions. This can be especially important given that poorly written web applications are often the weakest link in any security chain.

      At the heart of any firewall is its rule set, the configuration that determines how the firewall implements a given security policy.

      Develop a Security Policy

      Before deploying a cloud-based firewall, it’s important to first write a security policy. Think of this document as a set of specifications defining exactly what you expect your networks and firewalls to do.

      A security policy should be as specific as possible. Include network diagrams showing which resources you need to protect, and list all permitted applications, services, hosts, and networks.

      Understanding your cloud-based applications is critical. If a custom web application requires access to a non-standard set of ports, or if your back-end servers only need to respond to certain types of SQL queries, your security policy and firewall rules must reflect that.

      The document may also cover user groups by defining which resources different teams can reach. For example, marketing can reach DNS, email, and web servers, but only engineering can reach build servers.

      Once you have a clear and comprehensive security policy, you’re ready to review your cloud network design and configure your firewall(s).

      Segment Your Network

      For decades, information security professionals have warned about the “M&M” approach to network design, which wraps “a hard crunchy shell around a soft chewy center”.

      Researchers Bill Cheswick and Steve Bellovin famously warned that a firewall at the network perimeter “only provides security if there is no way to get to the interior. Today, that may be unrealistic.” That was in 1994, and yet perimeter-only use of firewalls persists today, even in some cloud deployments.

      Before you decide on firewall placement for your cloud-based applications, first consider how to segment your network design to protect against unauthorized access.

      Cloud-based firewalls have an advantage because they allow microsegmentation. Here, virtual boundaries between trusted and untrusted resources can exist at many places in the network. This is an advantage over hardware-based firewalls, where cost and management overhead may limit firewall deployment to the network edge.

      Many cloud-based services use multi-tier network designs. Here, an Internet-facing tier of web servers are backed by one or more additional tiers of content and database servers. Access control is important not only for the front-line web servers but also for communications between tiers.

      A best practice is to use IP subnetting to segment each server tier and use firewall rules that enforce access policies between tiers. This is the opposite of the M&M model as it protects against unauthorized traffic at every tier, not just at the perimeter.

      Block All Traffic by Default

      “Live and let live” may be excellent advice in real life, but when it comes to information security the opposite is true. The general principle of building a firewall rule set is that everything is prohibited except that which is explicitly permitted.

      Many firewall implementations read rules from first to last. Your very first firewall rule needs to deny all traffic by default. After that, you can add rules that allow the specific users and applications your security policy allows. The initial default-deny rule drops everything else.

      Allow Specific Traffic Only as Needed

      The firewall rules you add after the default-deny policy need to forward only that traffic your security policy explicitly allows. This is known as the “principle of least privilege”, where firewall rules implement the exact specifications from the security policy, and nothing more.

      For example, if DNS lookups go through a firewall, its rules must permit access for UDP port 53 traffic, but not TCP port 53, which is usually reserved for zone transfers. The least-privileged approach applies to servers or server groups as well as traffic types. The same rule that allows DNS lookups could also permit forwarding only to an authorized set of DNS servers rather than to any host.

      The opposite of the principle of the least privilege is a very common error in firewall rule set design. This is the idea that “my network can do no wrong” and thus it’s okay to allow all outbound traffic.

      Allowing unlimited outbound access is a common attack vector because it can allow internal hosts to send unauthorized and possibly malicious traffic.

      Many applications use “phone home” features where a client behind a firewall initiates connections. Benign examples include remote-control applications used by IT teams for troubleshooting and the telemetry services built into many operating systems and applications. A malicious example is malware installed on a client. Benign or not, these applications bypass firewall rules governing inbound traffic.

      This is where the principle of least privilege comes in. It’s important to define a security policy that covers the exact user groups, hosts, and traffic types allowed. Then let the default-deny policy drop everything else. For example, networks that use proxy servers need to have firewall rules that permit HTTP and HTTPS traffic to, and only to, the proxy servers. The default-deny rule then drops any client’s attempt to reach outside web servers.

      Run Frequent Audits

      The axiom “security is a process, not a product” means that all security policies and firewall rule sets must change over time. Network administrators may poke holes through firewalls for web applications that require access on non-standard ports. Users may require access to work from home, something perhaps not contemplated in the original security policy. New classes of threats regularly appear.

      As a result, your organization’s security readiness weakens over time unless you regularly review the policies and rules in place.

      Regular audits of security policies and firewall rule sets can help answer questions like:

      • Which applications and services are running on the network right now?
      • Does the security policy cover every application and user group, both new and existing?
      • Do firewall rule sets contain entries that cover everything in the current security policy?
      • Do firewall rule sets contain stale entries for applications, services, or host groups that are no longer in use? Many firewalls have the ability to show how many times network traffic invokes a particular rule. A rule that’s never invoked might no longer belong in the rule set.
      • Do firewall rule sets allow access to external hosts for services provided internally?

      Regular policy and rule set audits can answer these questions. They can also help ensure your security posture comprehensively and adequately reflects current conditions in your cloud network.

      Monitor Security Logs

      Most firewalls produce voluminous logging about network traffic, and this information often goes unchecked. Ignore the logs, and you’re likely to miss important security breaches. However, triggering an alert for every firewall rule violation is likely to leave you swamped, and unable to respond when a serious incident does occur. Prioritization and automation is key when it comes to making effective use of log data.

      When determining which log entries are most important, outbound connection attempts are a good place to start. Internal hosts attempting email or SSH connections with external hosts should trigger log entries. For firewalls with application-layer access controls such as URL filtering, look for attempts to reach known malware and hacking sites.

      In other cases, log entries may be noteworthy depending on who initiates a connection. A developer uploading source code onto GitHub from a cloud-based build server is one thing. The same code coming from a user in marketing or HR is quite another.

      Once you’ve picked the most critical log entries to watch, automation can reduce a firehose of log data into a trickle of useful and actionable alerts. A monitoring system that automatically triggers an alert for each and every attempt to reach a blocked site would be useless. However, a system that automatically alerts you only for high-severity events, based on log criteria you define, can help you spot attempted attacks as they happen.

      This advice applies tenfold for firewalls with UTM capabilities, especially those with intrusion detection/prevention systems (IDS/IPS). A well-known issue with IDS/IPS devices is that they require extensive tuning of rule sets. Many products help by classifying attack signatures into high-, medium-, and low-priority buckets. At least at first, enabling only the high-priority signatures can help prevent overloading your logs and alerting systems.

      Update Firewall Software

      While it’s best practice to keep all cloud-based hosts, containers, and applications updated, it’s especially important to apply patches to firewalls as soon as they’re available. Any security policy carries an implicit assumption that firewalls and related security tools are capable of protecting users and hosts. However, that assumption becomes false if the firewall itself is vulnerable.

      An important corollary is that firewalls with UTM features must keep their antivirus and IDS/IPS signature libraries up to date. Security researchers uncover new attacks on a daily basis. Additionally, many attackers “fuzz” a given attack, slightly altering it in the hope of eluding a matching IDS/IPS signature. If your firewall provider offers an automatic update service, use it.

      This is one area where some cloud-based firewalls have a major advantage over their hardware-based counterparts. Many cloud firewalls operate on a firewall-as-a-service (FWasS) model. You don’t need to perform updates because your provider handles that for you.

      If you do use a cloud-based version of a standalone firewall, be sure it’s hardened as well as updated. Disable unused services and accounts. Limit management access. Make regular backups of all configurations and databases. Securely send logs to a centralized security information and event management (SIEM) server that is itself hardened.

      Conclusion

      Cloud-based firewalls allow fine-grained control over all your platforms and applications. With the right combination of best practices, including microsegmentation, logical rule ordering, monitoring, auditing, and updating, you can ensure equal or better protection of your resources than a conventional hardware-based firewall provides.

      Comparing Linux-Based Network Firewall Software

      Implementing a firewall is crucial for securing your Linux system. There are an array of popular software firewalls to choose from, and each offers unique features. So understanding how these tools compare can help you choose the best firewall for your needs.

      In this guide, learn more about each of the most common software firewall tools on Linux and how they compare. When available, follow links to our in-depth guides on each of these tools and compare examples of how each handles common firewall configurations.

      An Overview of Netfilter (The Linux Kernel-Space Firewall Module)

      Netfilter is a packet-filtering framework included in the Linux kernel (since 2.4.0). This framework provides kernel-level hooks that are used to implement packet filtering and network address and port translation (NAT and NPT). Ultimately, it is this framework that all firewall tools leverage for managing packets.

      Low-level tools, like nftables and iptables, are the default interfaces for Netfilter. These tools provide a lot of control over firewall rules but they can also be difficult to learn and work with. You can also find high-level tools, like UFW and firewalld, built on top of these low-level tools. Such high-level tools can further simplify firewall configuration.

      Low-Level User-Space Firewall Utilities

      Linux utilizes dedicated packet classification tools for users to manage network/firewall rules. These tools — nftables and iptables — are built on Netfilter and provide low-level firewall configurations. They are especially helpful when you need fine-grained control of your network’s package filtering.

      nftables

      nftables has become the default low-level packet classification tool, replacing iptables. Leveraging the Netfilter framework, nftables allows users to configure network rulesets that filter and route packets and ultimately define network traffic.

      nftables uses a tables -> chains -> rules structure for managing network rules. Tables organize sets of chains, and each chain consists of a list of rules, processed in order.

      Because nftables has superseded iptables, you should opt to use it when possible. The main exception is older Linux systems, many of which do not support nftables. Alternatively, you may prefer a high-level tool like those covered below.

      You can learn more about nftables and its usage in our Getting Started with nftables guide.

      iptables

      iptables traditionally filled the space now occupied by nftables. iptables is, like nftables, a low-level tool for packet classification, providing firewall and network traffic management through the configuration of rulesets. iptables uses a similar tables -> chains -> rules hierarchical model as well.

      Even though nftables has replaced iptables as the default, some systems, particularly ones using older Linux versions, only support iptables. Unless you are looking for higher-level firewall configuration (see High-Level Firewall Configuration Managers section below), you need to use iptables in those cases.

      You can learn more about iptables and how to configure network rules with them in our Controlling Network Traffics with iptables guide.

      High-Level Firewall Configuration Managers

      To some users, low-level tools may prove overly cumbersome. High-level tools offer simpler solutions for implementing firewalls that may better fit your needs. By abstracting lower-level details, these tools can make it easier to manage network rules.

      UFW

      UFW (short for UncomplicatedFirewall) offers firewall management in a user-friendly command-line interface. It comes by default on Ubuntu systems and is typically the go-to choice on Debian and Arch Linux systems as well.

      What especially sets UFW apart is the simplicity its commands bring to firewall configuration. Setting up your desired firewall rules and enabling the firewall follows an uncomplicated set of commands.

      See more on UFW and steps for getting started in our How to Configure a Firewall with UFW guide.

      Firewalld

      Firewalld provides an interface for configuring firewall rules both dynamically and persistently. The dynamic configuration feature allows firewalld to set up rules that apply immediately, without having to restart the service or interrupt existing connections. Additionally, firewalld’s zones system provides convenience for categorizing and managing levels of trust.

      Firewalld supports most Linux distributions, and it is included by default on RHEL-related systems (e.g., CentOS, Fedora, AlmaLinux, Rocky Linux) and openSUSE.

      Take a look at our Configure a Firewall with Firewalld guide to find out more about using firewalld.

      Managed Cloud Firewall Service

      Cloud firewall services, like Akamai’s Cloud Firewall, offer a different approach to cloud security and have some advantages over local software firewalls. For instance, Akamai’s Cloud Firewall can configure and manage firewall rules across multiple cloud instances.

      That said, cloud firewalls often do not cover all of the features of software firewalls. Typically, a software firewall can offer more configuration options and advanced control of network traffic.

      One solution — cloud or software firewall — is likely to better fit your needs than the other. But often you can get the best results by using both together. As an example, you can use a cloud firewall to apply “absolute” network rules across multiple cloud instances and prevent unwanted traffic from ever reaching your servers. Then, use a software firewall to fine-tune your network filtering on each server.

      Learn more about cloud firewalls and how they compare to software firewalls in our Comparing Cloud Firewalls to Linux Firewall Software guide.

      Basic Usage Comparison

      To further compare the software firewall tools, what follows are a series of example network filtering rules. Each covers a common scenario and shows how each of the four tools above implements the necessary ruleset. These examples offer a sense of how the tools differ, and for even more, you can refer to the guides linked above.

      View Existing Configuration

      Whether at the outset of configuring a firewall or when revising an existing configuration, it is helpful to get an overview of existing settings.

      table inet filter {
          chain input {
              type filter hook input priority filter; policy accept;
          }
      
          chain forward {
              type filter hook forward priority filter; policy accept;
          }
      
          chain output {
              type filter hook output priority filter; policy accept;
          }
      }

      To see IPv4 rules:

      -P INPUT ACCEPT
      -P FORWARD ACCEPT
      -P OUTPUT ACCEPT

      To see IPv6 rules:

      For firewall status and rules:

      Status: active
      
      To                         Action      From
      --                         ------      ----
      22/tcp                     ALLOW       Anywhere
      22/tcp (v6)                ALLOW       Anywhere (v6)

      For more details, including default policies:

      To see firewall rules for a specific zone (public in this example):

      sudo firewall-cmd --zone=public --list-all
      public (active)
        target: default
        icmp-block-inversion: no
        interfaces: eth0
        sources:
        services: cockpit dhcpv6-client ssh
        ports:
        protocols:
        forward: no
        masquerade: no
        forward-ports:
        source-ports:
        icmp-blocks:
        rich rules:

      To see firewall rules for all zones:

      sudo firewall-cmd --list-all-zones

      Block All Traffic

      For firewall configuration, it is crucial to be able to block traffic. The examples that follow first show how to block all traffic, then show the more typical policy configuration — denying incoming traffic and allowing outgoing.

      Important

      Configuring default reject or deny rules can lock you out of your Linode unless explicit allow rules are in place. Ensure that you have configured allow rules for SSH and other critical services before trying any of the following.

      Set policies to block incoming and outgoing traffic:

      sudo nft add chain inet filter input '{type filter hook input priority 0; policy drop; }'
      sudo nft add chain inet filter forward '{type filter hook forward priority 0; policy drop; }'
      sudo nft add chain inet filter output '{type filter hook output priority 0; policy drop; }'

      Set policies to block incoming traffic and allow outgoing:

      sudo nft add chain inet filter input '{type filter hook input priority 0; policy drop; }'
      sudo nft add chain inet filter forward '{type filter hook forward priority 0; policy drop; }'
      sudo nft add chain inet filter output '{type filter hook output priority 0; policy accept; }'

      Set policies to block incoming and outgoing traffic:

      sudo iptables -P INPUT DROP
      sudo iptables -P FORWARD DROP
      sudo iptables -P OUTPUT DROP

      Set policies to block incoming traffic and allow outgoing:

      sudo iptables -P INPUT DROP
      sudo iptables -P FORWARD DROP
      sudo iptables -P OUTPUT DROP

      The same can be done for IPv6 traffic, replacing iptables with ip6tables.

      To configure policies for blocking all traffic:

      sudo ufw default deny incoming
      sudo ufw default deny outgoing

      To set policies blocking incoming and allowing outgoing traffic:

      sudo ufw default deny incoming
      sudo ufw default allow outgoing

      Firewalld blocks incoming traffic by default. But to ensure that policy is in place:

      sudo firewall-cmd --zone=public --set-target=DROP --permanent

      Firewalld does not regulate outbound traffic by default. To block all outbound traffic, create a custom policy:

      sudo firewall-cmd --new-policy outgoing-default --permanent
      sudo firewall-cmd --policy outgoing-default --add-ingress-zone HOST --permanent
      sudo firewall-cmd --policy outgoing-default --add-egress-zone ANY --permanent
      sudo firewall-cmd --policy outgoing-default --set-target DROP --permanent
      sudo firewall-cmd --policy outgoing-default --set-priority -100 --permanent

      Allow All Traffic From a Specific IP Address

      Tighter network security stipulates specifically which IP address has access to the system. Denying incoming traffic by default — as shown above — and adding exceptions as needed helps to ensure access only by known systems.

      To allow traffic from an IPv4 source address:

      sudo nft add rule inet filter input ip saddr 192.0.2.0 accept

      The same command works for an IPv6 address:

      sudo nft add rule inet filter input ip6 saddr 2001:db8:e001:1b8c::2 accept

      Allow traffic from an IPv4 source address:

      sudo iptables -A INPUT -p tcp -s 192.0.2.0 -j ACCEPT

      Use the same approach with the ip6tables command for IPv6 source addresses:

      sudo ip6tables -A INPUT -p tcp -s 2001:db8:e001:1b8c::2 -j ACCEPT

      Allow traffic from a given IP address; the command operates the same whether the address is IPv4 or IPv6:

      sudo ufw allow from 192.0.2.0
      sudo ufw allow from 2001:db8:e001:1b8c::2

      Use the trusted zone to allow traffic from a given source address. The operation is the same regardless of IPv4 or IPv6:

      sudo firewall-cmd --zone=trusted --add-source=192.0.2.0
      sudo firewall-cmd --zone=trusted --add-source=2001:db8:e001:1b8c::2

      Block All Traffic From a Specific IP Address

      Each firewall management tool covered here offers an option for blocking traffic from a given IP. Recommended setups and some default policies in these tools may already block all incoming traffic that is not explicitly approved. However, being able to explicitly block a given IP address gives you much more control and may be particularly useful in certain setups.

      To block traffic from a given IP address:

      sudo nft add rule inet filter input ip saddr 192.0.2.0 drop

      Use the same process for IPv6 addresses:

      sudo nft add rule inet filter input ip6 saddr 2001:db8:e001:1b8c::2 drop

      To block connections from an IPv4 address:

      sudo iptables -A INPUT -p tcp -s 192.0.2.0 -j DROP

      To block connections from an IPv6 address:

      sudo ip6tables -A INPUT -p tcp -s 2001:db8:e001:1b8c::2 -j DROP

      Use commands like the ones below to block traffic from a given IP, whether IPv4 or IPv6:

      sudo ufw deny from 192.0.2.0
      sudo ufw deny from 2001:db8:e001:1b8c::2

      Use firwalld’s drop zone to block specific IP addresses. The same method holds whether IPv4 or IPv6:

      sudo firewall-cmd --zone=drop --add-source=192.0.2.0
      sudo firewall-cmd --zone=drop --add-source=2001:db8:e001:1b8c::2

      Allow Incoming Traffic From a Specific Port

      Allowing traffic on specific ports is common, especially for web servers. Opening ports allow access for SSH connections (port 22) and for web application usage (ports 80 and 443), among other use cases.

      In addition, the firewall tools covered here can use port specifications alongside IP address specifications. Doing so can ensure even tighter security, relegating incoming traffic from specific addresses to specific ports.

      Allow traffic on port 22:

      sudo nft add rule inet filter input tcp dport 22 accept

      Allow traffic from a given IP address to port 22:

      sudo nft add rule inet filter input ip saddr 192.0.2.0 tcp dport 22 accept

      Open port 22 for traffic:

      sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

      Allow traffic from a given address to port 22:

      sudo iptables -A INPUT -p tcp -s 192.0.2.0 --dport 22 -j ACCEPT

      Use ip6tables instead of iptables above to set rules for IPv6 traffic.

      To allow traffic on a given port:

      To allow a given IP address to connect via a given port:

      sudo ufw allow from 192.0.2.0 proto tcp to any port 22

      To open port 22 for traffic:

      sudo firewall-cmd --zone=public --allow-port=22/tcp

      Create a rich rule to allow traffic from a given IP address into port 22:

      sudo firewall-cmd --zone=public --add-rich-rule 'rule source address="192.0.2.0" port port=22 protocol=tcp accept'

      Cómo listar y eliminar reglas de firewall de Iptables


      Introducción

      Iptables es un firewall que tiene una función esencial en la seguridad de la red para la mayoría de los sistemas Linux. Aunque muchos tutoriales de iptables enseñan cómo crear reglas de firewall para proteger el servidor, este se centrará en un aspecto diferente de la administración de firewall: cómo listar y eliminar reglas.

      En este tutorial, explicaremos cómo hacer las siguientes tareas de iptables:

      • Listar reglas
      • Borrar contadores de paquetes y bytes
      • Eliminar reglas
      • Vaciar cadenas (eliminar todas las reglas de una cadena)
      • Vaciar todas las cadenas y tablas, eliminar todas las cadenas y aceptar todo el tráfico

      Nota: Cuando trabaje con firewalls, tenga precaución de no bloquearse a sí mismo de su propio servidor al bloquear el tráfico SSH (puerto 22, de forma predeterminada). Si pierde acceso debido a la configuración del firewall, es posible que deba conectarse a este mediante una consola fuera de banda para solucionar su problema de acceso.

      Requisitos previos

      En este tutorial, se asume que está usando un servidor Linux con el comando iptables instalado y que el usuario tiene privilegios sudo.

      Si necesita ayuda para esta configuración inicial, consulte nuestra guía Configuración inicial del servidor con Ubuntu 20.04. También está disponible para Debian y CentOS

      Veamos primero cómo enumerar reglas. Hay dos formas diferentes de ver las reglas de iptables activas: en una tabla o como una lista de especificaciones de reglas. Ambos métodos proporcionan aproximadamente la misma información en diferentes formatos.

      Para enumerar todas las reglas de iptables activas por especificación, ejecute el comando iptables con la opción -S:

      Output

      -P INPUT DROP -P FORWARD DROP -P OUTPUT ACCEPT -N ICMP -N TCP -N UDP -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT -A INPUT -i lo -j ACCEPT -A INPUT -m conntrack --ctstate INVALID -j DROP -A INPUT -p udp -m conntrack --ctstate NEW -j UDP -A INPUT -p tcp -m tcp --tcp-flags FIN,SYN,RST,ACK SYN -m conntrack --ctstate NEW -j TCP -A INPUT -p icmp -m conntrack --ctstate NEW -j ICMP -A INPUT -p udp -j REJECT --reject-with icmp-port-unreachable -A INPUT -p tcp -j REJECT --reject-with tcp-reset -A INPUT -j REJECT --reject-with icmp-proto-unreachable -A TCP -p tcp -m tcp --dport 22 -j ACCEPT

      Como se puede ver, el resultado se parece a los comandos que se utilizaron para crearlas, sin el comando iptables anterior. Esto también tendrá un aspecto similar a los archivos de configuración de reglas de iptables, si alguna vez se utilizó iptables-persistent o iptables save.

      Cómo enumerar una cadena específica

      Si desea limitar el resultado a una cadena específica (ENTRADA, SALIDA, TCP, etc.), puede especificar el nombre de la cadena directamente después de la opción -S. Por ejemplo, para mostrar todas las especificaciones de reglas en la cadena TCP, debe ejecutar este comando:

      Output

      -N TCP -A TCP -p tcp -m tcp --dport 22 -j ACCEPT

      Ahora vamos a echar un vistazo a la forma alternativa de ver las reglas de iptables activas, como un cuadro de reglas.

      Cómo listar reglas como tablas

      El listado de las reglas de iptables en la vista de tabla puede ser útil para comparar diferentes reglas entre sí.

      Para generar todas las reglas de iptables activas en una tabla, ejecute el comando iptables con la opción -L:

      Esto generará todas las reglas actuales ordenadas por cadena.

      Si desea limitar el resultado a una cadena específica (ENTRADA, SALIDA, TCP, etc.), puede especificar el nombre de la cadena directamente después de la opción -L.

      Veamos un ejemplo de cadena ENTRADA:

      Output

      Chain INPUT (policy DROP) target prot opt source destination ACCEPT all -- anywhere anywhere ctstate RELATED,ESTABLISHED ACCEPT all -- anywhere anywhere DROP all -- anywhere anywhere ctstate INVALID UDP udp -- anywhere anywhere ctstate NEW TCP tcp -- anywhere anywhere tcp flags:FIN,SYN,RST,ACK/SYN ctstate NEW ICMP icmp -- anywhere anywhere ctstate NEW REJECT udp -- anywhere anywhere reject-with icmp-port-unreachable REJECT tcp -- anywhere anywhere reject-with tcp-reset REJECT all -- anywhere anywhere reject-with icmp-proto-unreachable

      La primera línea de resultado indica el nombre de la cadena (ENTRADA, en este caso), seguido por su directiva predeterminada (ANULAR). La siguiente línea consiste en los encabezados de cada columna de la tabla y viene seguida de las reglas de la cadena. Veamos qué indica cada encabezado:

      • target: si un paquete coincide con la regla, el objetivo especifica qué debe hacerse con él. Por ejemplo, un paquete puede aceptar, anularse, registrarse o enviarse a otra cadena para compararse con más reglas
      • prot: el protocolo, como tcp, udp, icmp o all
      • opt: rara vez se utiliza. Esta columna indica opciones IP
      • source: la dirección IP o de subred de origen del tráfico o anywhere
      • destination: la dirección IP o de subred de destino del tráfico o anywhere

      La última columna, que no está etiquetada, indica las opciones de una regla. Es decir, cualquier parte de la regla que no esté indicada mediante las columnas anteriores. Puede ser cualquier cosa, desde puertos de origen y destino hasta el estado de conexión del paquete.

      Cómo mostrar recuentos de paquetes y tamaño total

      Cuando se listan reglas de iptables, también es posible mostrar el número de paquetes y el tamaño total de estos en bytes, que coinciden con cada regla particular. Esto a menudo es útil cuando se trata de tener una idea aproximada de qué reglas coinciden con los paquetes. Para hacerlo, utilice la opción -L y -v juntos.

      Por ejemplo, volvamos a ver la cadena INPUT, con la opción -v:

      • sudo iptables -L INPUT -v

      Output

      Chain INPUT (policy DROP 0 packets, 0 bytes) pkts bytes target prot opt in out source destination 284K 42M ACCEPT all -- any any anywhere anywhere ctstate RELATED,ESTABLISHED 0 0 ACCEPT all -- lo any anywhere anywhere 0 0 DROP all -- any any anywhere anywhere ctstate INVALID 396 63275 UDP udp -- any any anywhere anywhere ctstate NEW 17067 1005K TCP tcp -- any any anywhere anywhere tcp flags:FIN,SYN,RST,ACK/SYN ctstate NEW 2410 154K ICMP icmp -- any any anywhere anywhere ctstate NEW 396 63275 REJECT udp -- any any anywhere anywhere reject-with icmp-port-unreachable 2916 179K REJECT all -- any any anywhere anywhere reject-with icmp-proto-unreachable 0 0 ACCEPT tcp -- any any anywhere anywhere tcp dpt:ssh ctstate NEW,ESTABLISHED

      Tenga en cuenta que la lista ahora tiene dos columnas adicionales, pkts y bytes.

      Ahora que sabe cómo listar las reglas de firewall activas de diversas maneras, vamos a ver cómo puede restablecer los contadores de paquetes y bytes.

      Cómo restablecer los recuentos de paquetes y el tamaño total

      Si desea borrar, o dejar en cero, los contadores de paquetes y bytes para sus reglas, utilice la opción -Z. También se restablecen si se produce un reinicio. Esto es útil cuando desea ver si el servidor está recibiendo tráfico nuevo que coincida con las reglas existentes.

      Para borrar los contadores de todas las cadenas y reglas, utilice la opción -Z sola:

      Para borrar los contadores de todas las reglas de una cadena específica, utilice la opción -Z y especifique la cadena. Por ejemplo, para borrar los contadores de la cadena ENTRADA, ejecute este comando:

      Si desea borrar los contadores de una regla determinada, especifique el nombre de la cadena y el número de la regla. Por ejemplo, para dejar en cero los contadores de la primera regla en la cadena ENTRADA, ejecute esto:

      Ahora que aprendió a restablecer los contadores de paquetes y bytes de iptables, vamos a ver los dos métodos que pueden utilizarse para eliminarlos.

      Una de las formas de eliminar reglas de iptables es mediante la especificación de reglas. Para hacerlo, puede ejecutar el comando iptables con la opción -D seguida de la especificación de reglas. Si desea eliminar reglas usando este método, puede utilizar el resultado de la lista de reglas, iptables -S, para obtener ayuda.

      Por ejemplo, si desea borrar la regla que anula paquetes entrantes inválidos (-A INPUT -m conntrack -ctstate INVALID -j DROP), podría ejecutar este comando:

      • sudo iptables -D INPUT -m conntrack --ctstate INVALID -j DROP

      Tenga en cuenta que aquí debería excluirse la opción -A, que se utiliza para indicar la posición de la regla en el momento de la creación.

      Cómo eliminar reglas por cadena y número

      La otra forma de eliminar reglas de iptables es mediante su número de línea y cadena. Para determinar el número de línea de una regla, liste las reglas en el formato de tabla y agregue la opción --line-numbers:

      • sudo iptables -L --line-numbers
      [secondary_output Output]
      Chain INPUT (policy DROP)
      num  target     prot opt source               destination
      1    ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
      2    ACCEPT     all  --  anywhere             anywhere
      3    DROP       all  --  anywhere             anywhere             ctstate INVALID
      4    UDP        udp  --  anywhere             anywhere             ctstate NEW
      5    TCP        tcp  --  anywhere             anywhere             tcp flags:FIN,SYN,RST,ACK/SYN ctstate NEW
      6    ICMP       icmp --  anywhere             anywhere             ctstate NEW
      7    REJECT     udp  --  anywhere             anywhere             reject-with icmp-port-unreachable
      8    REJECT     tcp  --  anywhere             anywhere             reject-with tcp-reset
      9    REJECT     all  --  anywhere             anywhere             reject-with icmp-proto-unreachable
      10   ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ssh ctstate NEW,ESTABLISHED
      ...
      

      Con esto se agrega el número de línea a cada fila de reglas, lo que se indica mediante el encabezado num.

      Una vez que sepa qué regla desea eliminar, tome nota del número de cadena y línea de la regla. Luego, ejecute el comando iptables -D seguido por el número de cadena y regla.

      Por ejemplo, si queremos eliminar la regla de entrada que anula paquetes inválidos, podemos ver que es la regla 3 de la cadena ENTRADA. Por ello, debemos ejecutar este comando:

      Ahora que sabe cómo eliminar reglas de firewall individuales, vamos a revisar cómo puede vaciar cadenas de reglas.

      Cómo vaciar cadenas

      Iptables ofrece una forma de eliminar todas las reglas de una cadena, o de vaciar una cadena. En esta sección se cubrirá la variedad de formas de hacer esto.

      Nota: Tenga cuidado de no bloquearse de su servidor mediante SSH, al vaciar una cadena con una directiva predeterminada de anular o denegar. Si lo hace, es posible que necesite conectarse a él a través de la consola para solucionar su problema de acceso.

      Cómo vaciar una cadena única

      Para vaciar una cadena específica, lo que eliminará todas las reglas de la cadena, puede usar la opción -F o la opción equivalente --flush, y el nombre de la cadena para vaciar.

      Por ejemplo, para eliminar todas las reglas de la ENTRADA cadena, ejecute este comando:

      Cómo vaciar todas las cadenas

      Para vaciar todas las cadenas, lo que eliminará todas las reglas de firewall, puede usar la opción -F o la opción equivalente --flush sola:

      Cómo vaciar todas las reglas, eliminar todas las cadenas y aceptar todas

      En esta sección, explicaremos cómo vaciar todas sus reglas, tablas y cadenas de firewall y permitir todo el tráfico de red.

      Nota: Con esto se deshabilitará efectivamente el firewall. Solo debe seguir esta sección si desea volver a iniciar la configuración del firewall.

      Primero, establezca las directivas predeterminadas para cada una de las cadenas incorporadas en ACEPTAR. El motivo principal para hacer esto es garantizar que no quede bloqueado del servidor mediante SSH:

      • sudo iptables -P INPUT ACCEPT
      • sudo iptables -P FORWARD ACCEPT
      • sudo iptables -P OUTPUT ACCEPT

      Luego, vacíe las tablas nat y mangle, vacíe todas las cadenas (-F) y elimine todas las cadenas no predeterminadas (-X):

      • sudo iptables -t nat -F
      • sudo iptables -t mangle -F
      • sudo iptables -F
      • sudo iptables -X

      El firewall ahora permitirá todo el tráfico de red. Si lista las reglas ahora, verá que no hay ninguna, y que solo permanecerán las tres cadenas predeterminadas (ENTRADA, REENVÍO y SALIDA).

      Conclusión

      Después de revisar este tutorial, debería quedar familiarizado con cómo listar y eliminar las reglas de firewall de iptables.

      Recuerde que cualquier cambio de iptables mediante el comando iptables es efímero y debe guardarse para que persista durante reinicios del servidor. Esto se trata en la sección Reglas de almacenamiento del tutorial Reglas y comandos comunes de firewall.



      Source link