#iptables-translate
Explore tagged Tumblr posts
elwonplacenta · 9 days ago
Text
Setting up a Raspberry Pi is always an adventure, and our latest project has been no exception! We've been diving deep into the world of network configuration, and after a bit of head-scratching (and a few "aha!" moments), we've made some significant progress in understanding how to get our Pi to share its internet connection.
Initially, like many, we fell into a common trap. Our goal was to share the internet connection from our Raspberry Pi, and our first thought was to assign a static IP address to wlan0 – the wireless interface. The logic seemed sound: wlan0 is how the Pi connects to the internet (via a hotspot, in our case), so surely that's where the magic needed to happen, right?
Not quite!
After some experimentation and a healthy dose of troubleshooting, we realized a crucial distinction. While wlan0 receives the internet connection, it's not the ideal interface for sharing it in the way we envisioned. Think of it this way: wlan0 is like the person receiving a package at the door. They've got the package, but they're not the ones distributing it to everyone else in the house.
This led us to eth0 – the trusty wired Ethernet port. And that's where the real breakthrough happened! We had a lightbulb moment: eth0 is perfectly suited for sharing the connection.
Here's why eth0 is our new best friend for internet sharing:
* Dedicated Connection: eth0 allows for a direct, dedicated connection to another device, like a router or even another computer. This is ideal for creating a stable and reliable shared network.
* Logical Separation: By using eth0 to share, we can keep the wlan0 interface focused on its primary job: connecting to the internet. This simplifies the network topology and makes it easier to manage.
* Foundation for a Robust Setup: With eth0 as our sharing interface, we can now configure it to act as a DHCP server, enable IP forwarding, and set up Network Address Translation (NAT). These are the essential ingredients for turning our Raspberry Pi into a powerful internet gateway.
So, what's the plan moving forward?
Our focus has now shifted to configuring eth0. We'll be looking at:
* Assigning a static IP address to eth0: This will be the gateway for any devices connected to it.
* Enabling IP forwarding: This is the key to telling the Pi to route traffic between our wlan0 internet source and our eth0 shared network.
* Setting up a DHCP server (like dnsmasq) on eth0: This will allow devices connected to eth0 to automatically get an IP address from our Pi.
* Configuring iptables for NAT: This crucial step will ensure that devices on our eth0 network can access the internet through our wlan0 connection.
This project has been a fantastic learning experience, highlighting the importance of understanding the fundamental roles of different network interfaces. We're excited to get eth0 fully configured and unlock the full potential of our Raspberry Pi as an internet sharing hub.
Stay tuned for more updates as we continue to build out this network!
- I used ai for this post.
0 notes
playstationvii · 8 months ago
Text
Building a self-functioning Wi-Fi network requires both hardware and software components. The software part includes a script that configures the network settings (such as the SSID, security protocols, IP allocation, etc.) and raw code that manages the functioning of the network. Here’s a basic outline for a self-functioning Wi-Fi network setup using a Raspberry Pi, Linux server, or similar device.
Key Components:
• Router: Acts as the hardware for the network.
• Access Point (AP): Software component that makes a device act as a wireless access point.
• DHCP Server: Automatically assigns IP addresses to devices on the network.
• Firewall and Security: Ensure that only authorized users can connect.
Scripting a Wi-Fi Access Point
1. Set Up the Host Access Point (hostapd):
• hostapd turns a Linux device into a wireless AP.
2. Install Necessary Packages:
sudo apt-get update
sudo apt-get install hostapd dnsmasq
sudo systemctl stop hostapd
sudo systemctl stop dnsmasq
3. Configure the DHCP server (dnsmasq):
• Create a backup of the original configuration file and configure your own.
sudo mv /etc/dnsmasq.conf /etc/dnsmasq.conf.orig
sudo nano /etc/dnsmasq.conf
Add the following configuration:
interface=wlan0 # Use the wireless interface
dhcp-range=192.168.4.2,192.168.4.20,255.255.255.0,24h
This tells the server to use the wlan0 interface and provide IP addresses from 192.168.4.2 to 192.168.4.20.
4. Configure the Wi-Fi Access Point (hostapd):
Create a new configuration file for hostapd.
sudo nano /etc/hostapd/hostapd.conf
Add the following:
interface=wlan0
driver=nl80211
ssid=YourNetworkName
hw_mode=g
channel=7
wmm_enabled=0
macaddr_acl=0
auth_algs=1
ignore_broadcast_ssid=0
wpa=2
wpa_passphrase=YourSecurePassphrase
wpa_key_mgmt=WPA-PSK
wpa_pairwise=TKIP
rsn_pairwise=CCMP
Set up hostapd to use this configuration file:
sudo nano /etc/default/hostapd
Add:
DAEMON_CONF="/etc/hostapd/hostapd.conf"
5. Enable IP Forwarding:
Edit sysctl.conf to enable packet forwarding so traffic can flow between your devices:
sudo nano /etc/sysctl.conf
Uncomment the following line:
net.ipv4.ip_forward=1
6. Configure NAT (Network Address Translation):
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
sudo sh -c "iptables-save > /etc/iptables.ipv4.nat"
Edit /etc/rc.local to restore the NAT rule on reboot:
sudo nano /etc/rc.local
Add the following before the exit 0 line:
iptables-restore < /etc/iptables.ipv4.nat
7. Start the Services:
sudo systemctl start hostapd
sudo systemctl start dnsmasq
8. Auto-Start on Boot:
Enable the services to start on boot:
sudo systemctl enable hostapd
sudo systemctl enable dnsmasq
Raw Code for Wi-Fi Network Management
You may want a custom script to manage the network, auto-configure settings, or monitor status.
Here’s a basic Python script that can be used to start/stop the network, check connected clients, and monitor activity.
import subprocess
def start_network():
"""Start the hostapd and dnsmasq services."""
subprocess.run(['sudo', 'systemctl', 'start', 'hostapd'])
subprocess.run(['sudo', 'systemctl', 'start', 'dnsmasq'])
print("Wi-Fi network started.")
def stop_network():
"""Stop the hostapd and dnsmasq services."""
subprocess.run(['sudo', 'systemctl', 'stop', 'hostapd'])
subprocess.run(['sudo', 'systemctl', 'stop', 'dnsmasq'])
print("Wi-Fi network stopped.")
def check_clients():
"""Check the connected clients using arp-scan."""
clients = subprocess.run(['sudo', 'arp-scan', '-l'], capture_output=True, text=True)
print("Connected Clients:\n", clients.stdout)
def restart_network():
"""Restart the network services."""
stop_network()
start_network()
if __name__ == "__main__":
while True:
print("1. Start Wi-Fi")
print("2. Stop Wi-Fi")
print("3. Check Clients")
print("4. Restart Network")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
start_network()
elif choice == '2':
stop_network()
elif choice == '3':
check_clients()
elif choice == '4':
restart_network()
elif choice == '5':
break
else:
print("Invalid choice. Try again.")
Optional Security Features
To add further security features like firewalls, you could set up UFW (Uncomplicated Firewall) or use iptables rules to block/allow specific ports and traffic types.
sudo ufw allow 22/tcp # Allow SSH
sudo ufw allow 80/tcp # Allow HTTP
sudo ufw allow 443/tcp # Allow HTTPS
sudo ufw enable # Enable the firewall
Final Notes:
This setup is intended for a small, controlled environment. In a production setup, you’d want to configure more robust security measures, load balancing, and possibly use a more sophisticated router OS like OpenWRT or DD-WRT.
Would you like to explore the hardware setup too?
1 note · View note
akrnd085 · 1 year ago
Text
Comprehensive Guide to Linux Firewalls: iptables, nftables, ufw, and firewalld
Tumblr media
In the dynamic landscape of network security, firewalls play a pivotal role in fortifying systems against potential threats. Within the Linux ecosystem, where robust security measures are paramount, understanding and navigating tools like iptables vs ufw ,nftables and firewalld becomes crucial. This comprehensive guide aims to delve into the intricacies of each tool, shedding light on their core concepts, functionalities, and use cases.
iptables: Understanding the Core Concepts Overview of iptables: Iptables stands as a cornerstone tool for controlling firewalls on Linux systems. Operating directly with the Linux kernel for packet filtering, iptables provides a versatile but verbose interface.
Organizational Structure: The organizational structure of iptables involves tables, chains, rules, and targets. Three primary tables — filter, nat, and mangle — categorize rules. The filter table manages incoming and outgoing packets, nat facilitates Network Address Translation (NAT), and mangle is employed for advanced packet alteration.
Default Policies and Rule Creation: By default, iptables adds rules to the filter table, with default policies for INPUT, OUTPUT, and FORWARD chains set to ACCEPT. Security best practices recommend setting at least FORWARD and INPUT policies to DROP. Loopback interface access is usually allowed, and established or related connections are accepted.
Example Rules for Common Protocols: Allowing HTTP and HTTPS traffic: sudo iptables -A INPUT -p tcp — dport 80 -j ACCEPT sudo iptables -A INPUT -p tcp — dport 443 -j ACCEPT Allowing SSH traffic for remote access: sudo iptables -A INPUT -p tcp — dport 22 -j ACCEPT Common iptables Options: Iptables provides various options for rule management, including -A or –append, -I or –insert, -D or –delete, -P or –policy, -j or –jump, -s or –source, -d or –destination, -p or –protocol, -i or –in-interface, -o or –out-interface, –sport or –source-port, –dport or –destination-port, and -m or –match.
Advanced Features in iptables: Iptables offers advanced features such as NAT, interface bonding, TCP multipath, and more, making it a versatile tool for complex network configurations.
nftables: The Next Generation Firewall Overview of nftables: Nftables emerges as a user-friendly alternative to iptables, offering a more logical and streamlined structure. While positioned as a replacement for iptables, both tools coexist in modern systems.
Organizational Structure in nftables: Nftables adopts a logical structure comprising tables, chains, rules, and verdicts. It simplifies rule organization with various table types, including ip, arp, ip6, bridge, inet, and netdev.
Setting Default Policies and Example Rules: sudo nft add rule ip filter input drop sudo nft add rule ip filter forward drop sudo nft add rule ip filter input iifname “lo” accept sudo nft add rule ip filter input ct state established,related accept sudo nft add rule ip filter input tcp dport {80, 443} accept sudo nft add rule ip filter input tcp dport 22 accept Common nftables Options: Nftables options include add, insert, delete, chain, ip saddr, ip daddr, ip protocol, iifname, oifname, tcp sport, tcp dport, and ct state.
nftables vs iptables: While nftables provides a more streamlined approach, both tools coexist, allowing users to choose based on preferences and familiarity.
ufw: Simplifying Firewall Management Overview of ufw: Uncomplicated Firewall (ufw) serves as a frontend for iptables, offering a simplified interface for managing firewall configurations. It is designed to be user-friendly and automatically sets up iptables rules based on specified configurations.Ufw not only simplifies iptables but also integrates well with applications and services. Its simplicity makes it an ideal choice for those who want a quick setup without delving into intricate firewall configurations. Moreover, ufw supports application profiles, allowing users to define rules specific to applications.
Enabling ufw and Example Rules: sudo ufw enable sudo ufw allow 80/tcp sudo ufw allow 443/tcp sudo ufw allow 80,443/tcp Checking ufw Status: sudo ufw status firewalld: Dynamic Firewall Configuration Overview of firewalld: Firewalld streamlines dynamic firewall configuration, featuring zones to declare trust levels in interfaces and networks. It comes pre-installed in distributions like Red Hat Enterprise Linux, Fedora, CentOS, and can be installed on others.Firewalld excels in dynamic environments where network configurations change frequently. Its zone-based approach allows administrators to define different trust levels for various network interfaces.
Opening Ports with firewalld: sudo firewall-cmd — add-port=80/tcp — permanent sudo firewall-cmd — add-port=443/tcp — permanent sudo firewall-cmd — add-port=80/tcp — add-port=443/tcp — permanent sudo firewall-cmd — reload sudo firewall-cmd — list-ports Conclusion: Linux firewalls, comprising iptables vs ufw, nftables and firewalld, offer robust defense mechanisms for network security. While iptables and nftables cater to experienced users, ufw and firewalld provide simplified interfaces for ease of use. The choice of tools depends on user expertise and specific requirements, ensuring a secure and well-managed network environment. This extended guide provides additional insights into ufw and firewalld, enhancing your understanding of Linux firewall tools for configuring and securing systems effectively.
0 notes
sololinuxes · 6 years ago
Text
nftables vs IPtables
Tumblr media
nftables vs IPtables. IPtables es la herramienta por excelencia en línea de comandos, que nos permite configurar de manera sencilla las reglas de firewall (normalmente se combina con una interfaz, pero no es necesario). IPtables es capaz de inspeccionar, modificar o eliminar paquetes de la red. Las tablas de iptables se componen de cadenas que contienen lo que se conoce como las "reglas de IPtables". Las reglas se procesan por el orden definido, para que me entiendas mejor, son condicionantes que nosotros o el sistema hemos definido previamente y que deben cumplirse estrictamente de forma que coincidan con la acción definida al ejecutarse. Todos los paquetes entrantes, independientemente de la fuente son procesados ​​por las mismas reglas. Las tablas de IP contienen cinco tablas estándar (raw, filter, NAT, mangle, security), aunque las más utilizadas son dos (NAT y sobre todo filter). Bueno, eso es IPtables, pero ¿qué es nftables? Nftables al igual que IPtables es desarrollado por netfilter y básicamente es una herramienta de filtrado de paquetes, que fue creado para sustituir a IPtables porque estas tenían algún problema en aspectos como el rendimiento y la escalabilidad. nftables se agrego al kernel de Linux en 2014, por tanto desde la versión 3.13 esta incluido en el.
Tumblr media
nftables vs iptables comparativa  
nftables vs IPtables
nftables es aun más fácil de utilizar que IPtables, y como no podría ser de otra manera se combina con todas sus herramientas, por ejemplo, iptables, ip6tables, arptables, etc..., pero todo ello en una sola herramienta. La sintaxis es mejor y más simple, pero no te preocupes por que es totalmente compatible (puedes seguir usando la sintaxis de IPtables). Aunque nftables hace el mismo trabajo que IPtables, su arquitectura no se parece en nada. Destacamos que a diferencia de IPtables, nftables no crea tablas, ni cadenas, ni reglas de manera predeterminada (eso lo tienes que tener claro). Otro detalle importante de nftables es que permite hacer multiples acciones en una sola regla. Un ejemplo de la sintaxis de nftables: nft add rule ip filter output ip daddr 192.168.0.1 drop Con las iptables sería... iptables -A OUTPUT -d 192.168.0.1 -j DROP nftables no solo es más fácil de escribir, sino que el filtrado también es mucho más eficiente trabajando directamente desde el kernel. Después de todo lo dicho, deberíamos todos replantearnos el uso de nftables en vez de IPtables. Ademas si ya tienes un servidor en producción que trabaja con iptables, debes saber que existe una herramienta llamada "iptables-translate" que te ayudara enormemente a migrar de IPtables a nftables. Dado que este tema suscita un interés general, en el próximo articulo profundizaremos aun más en "nftables".   En Sololinux.es seguimos creciendo gracias a nuestros lectores, puedes colaborar con el simple gesto de compartir nuestros artículos en tu sitio web, blog,  foro o redes sociales.   Read the full article
0 notes
kiloplot · 3 years ago
Text
Firewall builder policy read from bottom up
Tumblr media
FIREWALL BUILDER POLICY READ FROM BOTTOM UP SOFTWARE
You will be able to manage your home server, but if you want to do more serious work, you’ll need to really understand how TCP/IP works, and after that, read a lot about the details of routing and packet filtering in Linux. Having said that, a warning to the newcomers to netfilter: there’s no tool that will magically allow you to write non-trivial rule-sets if you don’t understand the underlying stuff. Thanks to this, I was able to write very complicated rule-sets, which were still readable to the point that the more junior SysAdmins, with little exprience on netfilter, have no difficult modifying it to open up ports or creating a new NAT rule. To me, being able to write your rules in clean structures, with blocks, variables and ‘functions’ is, by far, the most important feature of ferm. Being a SysAdmin, I’ve been using netfilter/iptables for many years, after migrating away from ipchains and the day I’ve found ferm my work changed completely. Update, editor’s note: I’d like to add to this article my personal experience with ferm. To top it off, ferm seems to be under active development with bugs being squashed and features being added relatively regularly.įerm has been available in Debian since Etch and in Ubuntu since Dapper. It uses a reasonably powerful configuration language (including support for variables, function definitions, and arrays) which facilitates addressing more complex situations than the one I faced. However, ferm can also be used to put together more complex firewall rulesets. The bottom line is that, for simple rulesets, using ferm is definitely easier than preparing iptables rules by hand. A few tweaks of the default system configuration file -primarily opening a few ports-:Ī simple /etc/init.d/ferm restart and things were running smoothly. In contrast, ferm gave me no such problems. In my experience, preparing a firehol configuration file which didn’t trigger multiple errors from firehol/iptables did not prove to be straightforward. Unfortunately, I found that firehol ended up being a time-consumer. Other front-ends (e.g., shorewall and firewall builder) appear to be designed for complex rule-sets and require a substantial investment of effort to learn the syntax of configuration files or a ‘rule-making language’.Īlong with ferm, another front-end, firehol seemed to also hit the mark with respect to having a straightforward syntax. My main concern wasn’t with whether the application had a GUI or console interface but was with whether the application facilitated straightforward configuration of an iptables ruleset (translation: it shouldn’t take 20 min of reading documentation to get a simple firewall up). This may be a desirable feature for running on a box with limited disk space as GUI interfaces generally require the presence of X windows-related packages, often along with several KDE- or Gnome-related packages. Rather than using a GUI interface (e.g., firestarter, gnome lokkit, guarddog, kmyfirewall, knetfilter, …), ferm is configured via a text configuration file and can be controlled in a straightforward manner from the console. Even better, ferm has a ‘try-before-you-buy’ feature (shared with a few other packages such as firehol): ferm -interactive activates a specific ruleset and, if a user response isn’t given within 30 sec, the system reverts to the previous ruleset. Ferm starts with a default configuration which leaves the default SSH port open. Like several other firewall front-ends, ferm is aware of the issues associated with working on servers hundreds of miles away from one’s physical location. After firestarter crashed again with a memory error, I decided to move on… Otherwise I would have been hundreds of miles away from an inaccessible server. Fortunately, I had altered the firestarter rule set and opened port 22 before firestarter segfaulted. It turns out that there was one: ferm.Ī revisit to firestarter, a straightforward GUI interface, ended when firestarter segfaulted and then, when started again, automatically started its firewall. Rather than wading through a bunch of iptables commands, it seemed time to revisit the world of iptables front-ends on the off-chance there was an undiscovered treasure I’d missed on earlier visits. The culprit was a misconfigured firewall. Grumble… a postgresql server on an old Sun workstation isn’t visible to another old Sun workstation which (in theory…) is storing data on the postgresql server.
FIREWALL BUILDER POLICY READ FROM BOTTOM UP SOFTWARE
We’re running out of articles! If you like Debian Package of the Day please submit good articles about software you like!
Tumblr media
0 notes
borgpsi · 3 years ago
Text
EXPLORING THE APPLICATIONS OF IOT WITH KUBERNETES
Kubernetes is a cloud-native application deployment service. Because cloud apps are related to our IoT devices and products, we need to design IoT applications with Kubernetes.
Because of security, latency, autonomy, and cost, IoT analytics is shifting from the cloud to the edge. However, spreading and controlling loads to hundreds of edge nodes can be a difficult process. As a result, a lightweight production-grade solution, such as Kubernetes, is required to distribute and control the loads on edge devices.
WHAT EXACTLY IS KUBERNETES?
Kubernetes, often known as K8s, is a container-management system that assists application developers in easily deploying, scaling, and maintaining cloud-native applications. Furthermore, containerization simplifies the lifespan of cloud-native apps.
Tumblr media
HOW DOES KUBERNETES WORK?
When we have a functional Kubernetes deployment, we usually refer to it as a cluster. A Kubernetes cluster may be divided into two parts: the control plane and the nodes.
Each node in Kubernetes is its own Linux environment. There is some leeway in that it might be a real or virtual machine. Kubernetes nodes operate pods, which are made up of containers.
The control plane is primarily responsible for managing the cluster’s needed state, such as the sorts of applications that are executing and which container images are being utilised by them. It is worth mentioning that computer machines are in charge of executing apps and workloads.
Kubernetes runs on top of an operating system, such as Linux, and communicates with pods of containers that operate on nodes.
The Kubernetes control plane receives instructions from an administrator (or DevOps team) and routes them to the computer devices.
This method works well with a variety of services to determine which node is most suited for the particular task. Following that, it allotted the required resources and delegated the job to the pods in that node.
Kubernetes is a Greek term that translates to “captain” or “sailing master,” and it inspired the container ship analogy. The captain commands the ship. As a result, Kubernetes is compared to a captain or orchestrator of containers in the information technology domain.
Consider Docker containers to be packing crates. Boxes that must go to the same location should be kept together and placed into the same shipping containers. Packing crates are Docker containers in this instance, while shipping containers are pods.
Kubernetes assigns IP addresses to Pods, whereas iptables allows users to regulate network traffic.
In Kubernetes, iptables is replaced by eBPF, as demonstrated in the creative.
WHY IS LOAD BALANCE REQUIRED IN IOT APPLICATIONS?
The efficient and systematic distribution of network or application traffic across several hosts in a server farm is known as load balancing. Each load balancer sits between the backed servers and client devices. It takes incoming requests and then distributes them to any available server that can handle the request/work.
The most basic type of load balancing in Kubernetes is load distribution, which is simple to implement at the dispatch level. Kubernetes has two load distribution mechanisms, both of which operate through a feature called Kube-proxy, which maintains the virtual IPs used by services.
THE FORCE DRIVING THE ADOPTION OF CLOUD-NATIVE PLATFORMS LIKE KUBERNETES
Many firms are currently undergoing digital transformation. During this phase, their major goal is to transform the way they interact with their customers, suppliers, and partners. These firms are modernising their enterprise IT and OT systems by using advancements provided by technologies such as IoT platforms, IoT data analytics, and machine learning. They recognise that the difficulty of developing and deploying new digital goods necessitates the adoption of new development procedures. As a result, they turn to agile development and infrastructure solutions like Kubernetes.
Kubernetes has recently emerged as the most widely used standard container orchestration platform for cloud-native deployments. Kubernetes has emerged as the top choice for development teams looking to help their transition to new microservices architecture. It also contributes to the DevOps ethos of continuous integration (CI) and continuous deployment (CD).
Indeed, Kubernetes addresses many of the complicated issues that development teams face while developing and delivering IoT solutions. As a result, designing IoT applications with microservices has become popular.
WHY IS IT NECESSARY TO DEVELOP IOT APPLICATIONS WITH KUBERNETES?
Tumblr media
KUBERNETES DEVOPS FOR IOT APP DEVELOPMENT
To fulfil the needs of consumers and the market, IoT systems must be able to offer new features and upgrades quickly. Kubernetes offers DevOps teams with a standardised deployment process that enables them to test and deploy new services quickly and autonomously. Kubernetes enables zero-downtime deployments with rolling updates. Mission-critical IoT solutions, such as those used in essential industrial operations, may now be upgraded without interrupting processes or having a negative impact on customers and end users.
IN IOT APPLICATIONS, SCALABILITY
Scalability, defined as a system’s capacity to manage an increasing quantity of work efficiently by leveraging additional resources, remains a challenge for IoT developers. As a result, scalability is a major issue for many IoT systems.
The capacity to manage and serve innumerable device connections, convey massive amounts of data, and deliver high-end services such as real-time analytics involves a deployment architecture that can dynamically scale up and down in response to IoT deployment demands. Kubernetes enables developers to autonomously scale up and down across various network clusters.
SYSTEM WITH HIGH AVAILABILITY
Many IoT solutions are classified as business/mission-critical systems that must be extremely dependable and available. As an example, an IoT solution crucial to a hospital’s emergency healthcare facility must be available at all times. Kubernetes provides developers with the tools they need to deploy highly available systems.
Kubernetes’ design also allows workloads to run independently of one another. They may also be restarted with little impact on end customers.
PROPER USE OF CLOUD RESOURCES
Kubernetes improves efficiency by making the most use of cloud resources. IoT cloud integration is often a set of linked services that handle, among other things, device connectivity and administration, data intake, data integration, analytics, and integration with IT and OT systems. These services will most likely be hosted on public cloud providers such as Amazon Web Services or Microsoft Azure.
As a result, when evaluating the total cost of maintaining and deploying these services, making the most use of cloud provider resources is crucial. Kubernetes puts an abstract layer on top of the underlying virtual machines. Instead of delivering a single service on a single VM, administrators may focus on spreading IoT services across the most suitable number of VMs.
DEPLOYMENT OF IOT EDGE
The deployment of IoT services to the edge network is a significant advancement in the IoT industry. To increase the responsiveness of a predictive maintenance solution, it may be more effective to install data analytics and machine learning services closer to the equipment being monitored. It may be more efficient to place data analytics and machine learning services closer to the monitored equipment.
When deploying distributed and federated IoT services, system administrators and developers face a new management challenge. Kubernetes, on the other hand, provides a unified platform for establishing edge IoT services. A new Kubernetes IoT Working Group is investigating how it may provide a uniform deployment architecture for IoT cloud and IoT Edge.
KUBERNETES FUTURE TRENDS FOR IOT APP DEVELOPMENT
KUBERNETES 2.0 IN PRODUCTION OPERATION
Companies in the production and manufacturing area are looking to further scale up workloads inside a Kubernetes cluster to satisfy different requirements after the success of deploying Kubernetes in production environments with impressive levels of agility and flexibility.
BOOM OF KUBERNETES-NATIVE SOFTWARE
The software that must be executed as part of the containers existed in the early days of Kubernetes, complete with functional purpose and architectural aspects. To properly exploit Kubernetes, however, we must modify and adjust it to our own needs. However, modifications are necessary to properly leverage Kubernetes’ benefits and better suit current operating models. Kubernetes has now progressed to the point where developers may create apps directly on the platform. As a result, in the next few years, Kubernetes will become increasingly important as a determinant of modern app architecture.
KUBERNETES AT THE CORNER
Kube Edge is a new project that will improve the administration and deployment capabilities of Kubernetes and Docker. It will also result in bundled apps running seamlessly on devices or at the edge.
As a result, we are already seeing the Kubernetes community grow and advance fast. These developments have allowed for the development of cloud-native IoT systems that are scalable and dependable, as well as easily deployable in the most difficult circumstances.
PsiBorg creates Kubernetes based IoT applications for a wide range of IoT technologies and products.
This article was originally published here: BUILDING IOT APPLICATIONS WITH KUBERNETES
1 note · View note
certificacaolinux-blog · 4 years ago
Text
Comando ping e ping6 no Linux (testa conexão ICMP) [Guia Básico]
Tumblr media
O Comando ping e ping6 no Linux utiliza o protocolo ICMP para enviar mensagens ECHO REQUEST e receber ECHO RESPONSE para testar a conexão entre o sistema e outra máquina na rede. Ele retorna o tempo de resposta que um pacote de rede demora para ir e voltar. Muito útil para realizar o diagnóstico de uma conexão. O ping irá testar indefinidamente até que o Crtl-c seja pressionado. O ping também possui uma versão para o IPv6, chamada de ping6. Seu funcionamento é similar ao ping do IPv4. As opções mais frequentes são: - -c num: Esta opção faz com que o ping teste a conexão um determinado número de vezes. - -q: Esta opção faz com que o ping somente apresente a estatística final do teste de conexão. Exemplo: $ ping 192.168.1.1PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.64 bytes from 192.168.1.1: icmp_seq=1 ttl=64 time=0.175 ms64 bytes from 192.168.1.1: icmp_seq=2 ttl=64 time=0.120 ms64 bytes from 192.168.1.1: icmp_seq=3 ttl=64 time=0.115 ms— 192.168.1.1 ping statistics —5 packets transmitted, 5 received, 0% packet loss, time 4000msrtt min/avg/max/mdev = 0.115/0.128/0.175/0.026 ms O ping é muito utilizado para testar se uma máquina está conectada na rede local ou se ela é alcançável na rede remota. Para que o ping funcione corretamente, a rede em questão não deve ter nenhum filtro de ICMP, especialmente os tipos ECHO REQUEST e ECHO RESPONSE. O comando ping pode indicar os seguintes possíveis problemas de rede: Problema com a Resolução de Nomes: Se ao executar o ping em um determinado host utilizando um nome de rede (host.certificacaolinux.com.br) o ping demorar para responder, e não conseguir resolver o nome para o IP, significa que: - O servidor de DNS pode estar errado (verifique o arquivo /etc/resolv.conf); - O servidor de DNS não pode ser acessado (faça um ping com o IP do servidor de DNS); - Existe um filtro de porta UDP 53 entre o computador e o servidor de DNS (verifique o iptables); Problema de Conectividade: Se ao executar o ping, um determinado host não responder, pode significar que: - O host destino está fora do ar; - Não há rota entre a rede do computador e o host destino (verifique a tabela de rotas); - O default gateway está errado (verifique a tabela de rotas); - O Network Address Translation está com algum problema de encaminhamento ou tradução de endereços (verifique o firewall); - Existe um filtro de ICMP ECHO e ECHO-REPLY na rede; https://youtu.be/lvcgrEZ2PKk Aprenda muito mais sobre Linux em nosso curso online. Você pode efetuar a matrícula aqui. Se você já tem uma conta, ou quer criar uma, basta entrar ou criar seu usuário aqui. Gostou? Compartilhe Read the full article
0 notes
esatyabca · 5 years ago
Text
FIREWALL SET UP
HOW TO SET UP A FIREWALL UNDER LINUX?
To configure a Linux firewall, you will likely use the latest implementation of firewalling, called IPTables. IPTables is a packet filter for kernels 2.4 and above. It is a tremendous improvement over IPChains and provides enhanced features such as stateful packet filtering, Network Address Translation, MAC Address filtering and much more.
Creating a firewall…
View On WordPress
0 notes
terabitweb · 6 years ago
Text
Original Post from Amazon Security Author: Nicolas Malaval
Note from September 4, 2019: We’ve updated this blog post, initially published on January 26, 2016. Major changes include: support of Amazon Linux 2, no longer having to compile Squid 3.5, and a high availability version of the solution across two availability zones.
Amazon Virtual Private Cloud (Amazon VPC) enables you to launch AWS resources on a virtual private network that you’ve defined. On an Amazon VPC, many people use network address translation (NAT) instances and NAT gateways to enable instances in a private subnet to initiate outbound traffic to the Internet, while preventing the instances from receiving inbound traffic initiated by someone on the Internet.
For security and compliance purposes, you might have to filter the requests initiated by these instances (also known as “egress filtering”). Using iptables rules, you could restrict outbound traffic with your NAT instance based on a predefined destination port or IP address. However, you might need to enforce more complex security policies, such as allowing requests to AWS endpoints only, or blocking fraudulent websites, which you can’t easily achieve by using iptables rules.
In this post, I discuss and give an example of how to use Squid, a leading open-source proxy, to implement a “transparent proxy” that can restrict both HTTP and HTTPS outbound traffic to a given set of Internet domains, while being fully transparent for instances in the private subnet.
The solution architecture
In this section, I present the architecture of the high availability NAT solution and explain how to configure Squid to filter traffic transparently. Later in this post, I’ll provide instructions about how to implement and test the solution.
The following diagram illustrates how the components in this process interact with each other. Squid Instance 1 intercepts HTTP/S requests sent by instances in Private Subnet 1, including the Testing Instance. Squid Instance 1 then initiates a connection with the destination host on behalf of the Testing Instance, which goes through the Internet gateway. This solution spans two Availability Zones, with Squid Instance 2 intercepting requests sent from the other Availability Zone. Note that you may adapt the solution to span additional Availability Zones.  
Figure 1: The solution spans two Availability Zones
Intercepting and filtering traffic
In each availability zone, the route table associated to the private subnet sends the outbound traffic to the Squid instance (see Route Tables for a NAT Device). Squid intercepts the requested domain, then applies the following filtering policy:
For HTTP requests, Squid retrieves the host header field included in all HTTP/1.1 request messages. This specifies the Internet host being requested.
For HTTPS requests, the HTTP traffic is encapsulated in a TLS connection between the instance in the private subnet and the remote host. Squid cannot retrieve the host header field because the header is encrypted. A feature called SslBump would allow Squid to decrypt the traffic, but this would not be transparent for the client because the certificate would be considered invalid in most cases. The feature I use instead, called SslPeekAndSplice, retrieves the Server Name Indication (SNI) from the TLS initiation. The SNI contains the requested Internet host. As a result, Squid can make filtering decisions without decrypting the HTTPS traffic.
Note 1: Some older client-side software stacks do not support SNI. Here are the minimum versions of some important stacks and programming languages that support SNI: Python 2.7.9 and 3.2, Java 7 JSSE, wget 1.14, OpenSSL 0.9.8j, cURL 7.18.1
Note 2: TLS 1.3 introduced an optional extension that allows the client to encrypt the SNI, which may prevent Squid from intercepting the requested domain.
The SslPeekAndSplice feature was introduced in Squid 3.5 and is implemented in the same Squid module as SslBump. To enable this module, Squid requires that you provide a certificate, though it will not be used to decode HTTPS traffic. The solution creates a certificate using OpenSSL.
mkdir /etc/squid/ssl cd /etc/squid/ssl openssl genrsa -out squid.key 4096 openssl req -new -key squid.key -out squid.csr -subj "/C=XX/ST=XX/L=squid/O=squid/CN=squid" openssl x509 -req -days 3650 -in squid.csr -signkey squid.key -out squid.crt cat squid.key squid.crt >> squid.pem
The following code shows the Squid configuration file. For HTTPS traffic, note the ssl_bump directives instructing Squid to “peek” (retrieve the SNI) and then “splice” (become a TCP tunnel without decoding) or “terminate” the connection depending on the requested host.
visible_hostname squid cache deny all # Log format and rotation logformat squid %ts.%03tu %6tr %>a %Ss/%03>Hs %sni %Sh/%
The text file located at /etc/squid/whitelist.txt contains the list of whitelisted domains, with one domain per line. In this blog post, I’ll show you how to configure Squid to allow requests to *.amazonaws.com, which corresponds to AWS endpoints. Note that you can restrict access to a specific set of AWS services that you’ve defined (see Regions and Endpoints for a detailed list of endpoints), or you can set your own list of domains.
Note: An alternate approach is to use VPC endpoints to privately connect your VPC to supported AWS services without requiring access over the Internet (see VPC Endpoints). Some supported AWS services allow you to create a policy that controls the use of the endpoint to access AWS resources (see VPC Endpoint Policies, and VPC Endpoints for a list of supported services).
You may have noticed that Squid listens on port 3129 for HTTP traffic and 3130 for HTTPS. Because Squid cannot directly listen to 80 and 443, you have to redirect the incoming requests from instances in the private subnets to the Squid ports using iptables. You do not have to enable IP forwarding or add any FORWARD rule, as you would do with a standard NAT instance.
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 3129 sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 3130
The solution stores the files squid.conf and whitelist.txt in an Amazon Simple Storage Service (S3) bucket and runs the following script every minute on the Squid instances to download and update the Squid configuration from S3. This makes it easy to maintain the Squid configuration from a central location. Note that it first validates the files with squid -k parse and then reload the configuration with squid -k reconfigure if no error was found.
cp /etc/squid/* /etc/squid/old/ aws s3 sync s3:// /etc/squid squid -k parse && squid -k reconfigure || (cp /etc/squid/old/* /etc/squid/; exit 1)
The solution then uses the CloudWatch Agent on the Squid instances to collect and store Squid logs in Amazon CloudWatch Logs. The log group /filtering-nat-instance/cache.log contains the error and debug messages that Squid generates and /filtering-nat-instance/access.log contains the access logs.
An access log record is a space-delimited string that has the following format:
The following table describes the fields of an access log record.
Field Description time Request time in seconds since epoch response_time Response time in milliseconds client_ip Client source IP address status_code Squid request status and HTTP response code sent to the client. For example, a HTTP request to an unallowed domain logs TCP_DENIED/403, and a HTTPS request to a whitelisted domain logs TCP_TUNNEL/200 size Total size of the response sent to client method Request method like GET or POST. url Request URL received from the client. Logged for HTTP requests only sni Domain name intercepted in the SNI. Logged for HTTPS requests only remote_host Squid hierarchy status and remote host IP address mime MIME content type. Logged for HTTP requests only
The following are some examples of access log records:
1563718817.184 14 10.0.0.28 TCP_DENIED/403 3822 GET http://example.com/ - HIER_NONE/- text/html 1563718821.573 7 10.0.0.28 TAG_NONE/200 0 CONNECT 172.217.7.227:443 example.com HIER_NONE/- - 1563718872.923 32 10.0.0.28 TCP_TUNNEL/200 22927 CONNECT 52.216.187.19:443 calculator.s3.amazonaws.com ORIGINAL_DST/52.216.187.19 –
Designing a high availability solution
The Squid instances introduce a single point of failure for the private subnets. If a Squid instance fails, the instances in its associated private subnet cannot send outbound traffic anymore. The following diagram illustrates the architecture that I propose to address this situation within an Availability Zone.  
Figure 2: The architecture to address if a Squid instance fails within an Availability Zone
Each Squid instance is launched in an Amazon EC2 Auto Scaling group that has a minimum size and a maximum size of one instance. A shell script is run at startup to configure the instances. That includes installing and configuring Squid (see Running Commands on Your Linux Instance at Launch).
The solution uses the CloudWatch Agent and its procstat plugin to collect the CPU usage of the Squid process every 10 seconds. For each Squid instance, the solution creates a CloudWatch alarm that watches this custom metric and goes to an ALARM state when a data point is missing. This can happen, for example, when Squid crashes or the Squid instance fails. Note that for my use case, I consider watching the Squid process a sufficient approach to determining the health status of a Squid instance, although it cannot detect eventual cases of the Squid process being alive but unable to forward traffic. As a workaround, you can use an end-to-end monitoring approach, like using witness instances in the private subnets to send test requests at regular intervals and collect the custom metric.
When an alarm goes to ALARM state, CloudWatch sends a notification to an Amazon Simple Notification Service (SNS) topic which then triggers an AWS Lambda function. The Lambda function marks the Squid instance as unhealthy in its Auto Scaling group, retrieves the list of healthy Squid instances based on the state of other CloudWatch alarms, and updates the route tables that currently route traffic to the unhealthy Squid instance to instead route traffic to the first available healthy Squid instance. While the Auto Scaling group automatically replaces the unhealthy Squid instance, private instances can send outbound traffic through the Squid instance in the other Availability Zone.
When the CloudWatch agent starts collecting the custom metric again on the replacement Squid instance, the alarm reverts to OK state. Similarly, CloudWatch sends a notification to the SNS topic, which then triggers the Lambda function. The Lambda function completes the lifecycle action (see Amazon EC2 Auto Scaling Lifecycle Hooks) to indicate that the replacement instance is ready to serve traffic, and updates the route table associated to the private subnet in the same availability zone to route traffic to the replacement instance.
Implementing and testing the solution
Now that you understand the architecture behind this solution, you can follow the instructions in this section to implement and test the solution in your AWS account.
Implementing the solution
First, you’ll use AWS CloudFormation to provision the required resources. Select the Launch Stack button below to open the CloudFormation console and create a stack from the template. Then, follow the on-screen instructions.
CloudFormation will create the following resources:
An Amazon Virtual Private Cloud (Amazon VPC) with an internet gateway attached.
Two public subnets and two private subnets on the Amazon VPC.
Three route tables. The first route table is associated to the public subnets to make them publicly accessible. The other two route tables are associated to the private subnets.
An S3 bucket to store the Squid configuration files, and two Lambda-based custom resources to add the files squid.conf and whitelist.txt to this bucket.
An IAM role to grant the Squid instances permissions to read from the S3 bucket and use the CloudWatch agent.
A security group to allow HTTP and HTTPS traffic from instances in the private subnets.
A launch configuration to specify the template of Squid instances. That includes commands to run at startup for automating the initial configuration.
Two Auto Scaling groups that use this launch configuration to launch the Squid instances.
A Lambda function to redirect the outbound traffic and recover a Squid instance when it fails.
Two CloudWatch alarms to watch the custom metric sent by Squid instances and trigger the Lambda function when the health status of Squid instances changes.
An EC2 instance in the first private subnet to test the solution, and an IAM role to grant this instance permissions to use the SSM agent. Session Manager, which I introduce in the next paragraph, uses this SSM agent (see Working with SSM Agent)
Testing the solution
After the stack creation has completed (it can take up to 10 minutes), connect onto the Testing Instance using Session Manager, a capability of AWS Systems Manager that lets you manage instances through an interactive shell without the need to open an SSH port:
Open the AWS Systems Manager console.
In the navigation pane, choose Session Manager.
Choose Start Session.
For Target instances, choose the option button to the left of Testing Instance.
Choose Start Session.
Note: Session Manager makes calls to several AWS endpoints (see Working with SSM Agent). If you prefer to restrict access to a defined set of AWS services, make sure to whitelist the associated domains.
After the connection is made, you can test the solution with the following commands. Only the last three requests should return a valid response, because Squid allows traffic to *.amazonaws.com only.
curl http://www.amazon.com curl https://www.amazon.com curl http://calculator.s3.amazonaws.com/index.html curl https://calculator.s3.amazonaws.com/index.html aws ec2 describe-regions --region us-east-1
To find the requests you just made in the access logs, here’s how to browse the Squid logs in Amazon CloudWatch Logs:
Open the Amazon CloudWatch console.
In the navigation pane, choose Logs.
For Log Groups, choose the log group /filtering-nat-instance/access.log.
Choose Search Log Group to view and search log records.
To test how the solution behaves when a Squid instance fails, you can terminate one of the Squid instances manually in the Amazon EC2 console. Then, watch the CloudWatch alarm change its state in the Amazon CloudWatch console, or watch the solution change the default route of the impacted route table in the Amazon VPC console.
You can now delete the CloudFormation stack to clean up the resources that were just created.
Discussion: Transparent or forward proxy?
The solution that I describe in this blog is fully transparent for instances in the private subnets, which means that instances don’t need to be aware of the proxy and can make requests as if they were behind a standard NAT instance. An alternate solution is to deploy a forward proxy in your Amazon VPC and configure instances in private subnets to use it (see the blog post How to set up an outbound VPC proxy with domain whitelisting and content filtering for an example). In this section, I discuss some of the differences between the two solutions.
Supportability
A major drawback with forward proxies is that the proxy must be explicitly configured on every instance within the private subnets. For example, you can configure the HTTP_PROXY and HTTPS_PROXY environment variables on Linux instances, but some applications or services, like yum, require their own proxy configuration, or don’t support proxy usage. Note also that some AWS services and features, like Amazon EMR or Amazon SageMaker notebook instances, don’t support using a forward proxy at the time of this post. However, with TLS 1.3, a forward proxy is the only option to restrict outbound traffic if the SNI is encrypted.
Scalability
Deploying a forward proxy on AWS usually consists of a load balancer distributing traffic to a set of proxy instances launched in an Auto Scaling group. Proxy instances can be launched or terminated dynamically depending on the demand (also known as “horizontal scaling”). With forward proxies, each route table can route traffic to a single instance at a time, and changing the type of the instance is the only way to increase or decrease the capacity (also known as “vertical scaling”).
The solution I present in this post does not dynamically adapt the instance type of the Squid instances based on the demand. However, you might consider a mechanism in which the traffic from a private subnet is temporarily redirected through another Availability Zone while the Squid instance is being relaunched by Auto Scaling with a smaller or larger instance type.
Mutualization
Deploying a centralized proxy solution and using it across multiple VPCs is a way of reducing cost and operational complexity.
With a forward proxy, instances in private subnets send IP packets to the proxy load balancer. Therefore, sharing a forward proxy across multiple VPCs only requires connectivity between the “instance VPCs” and a proxy VPC that has VPC Peering or equivalent capabilities.
With a transparent proxy, instances in private subnets sends IP packets to the remote host. VPC Peering does not support transitive routing (see Unsupported VPC Peering Configurations) and cannot be used to share a transparent proxy across multiple VPCs. However, you can now use an AWS Transit Gateway that acts as a network transit hub to share a transparent proxy across multiple VPCs. I give an example in the next section.
Sharing the solution across multiple VPCs using AWS Transit Gateway
In this section, I give an example of how to share a transparent proxy across multiple VPCs using AWS Transit Gateway. The architecture is illustrated in the following diagram. For the sake of simplicity, the diagram does not include Availability Zones.  
Figure 3: The architecture for a transparent proxy across multiple VPCs using AWS Transit Gateway
Here’s how instances in the private subnet of “VPC App” can make requests via the shared transparent proxy in “VPC Shared:”
When instances in VPC App make HTTP/S requests, the network packets they send have the public IP address of the remote host as the destination address. These packets are forwarded to the transit gateway, based on the route table associated to the private subnet.
The transit gateway receives the packets and forwards them to VPC Shared, based on the default route of the transit gateway route table.
Note that the transit gateway attachment resides in the transit gateway subnet. When the packets arrive in VPC Shared, they are forwarded to the Squid instance because the next destination has been determined based on the route table associated to the transit gateway subnet.
The Squid instance makes requests on behalf of the source instance (“Instances” in the schema). Then, it sends the response to the source instance. The packets that it emits have the IP address of the source instance as the destination address and are forwarded to the transit gateway according to the route table associated to the public subnet.
The transit gateway receives and forwards the response packets to VPC App.
Finally, the response reaches the source instance.
In a high availability deployment, you could have one transit gateway subnet per Availability Zone that sends traffic to the Squid instance that resides in the same Availability Zone, or to the Squid instance in another Availability Zone if the instance in the same Availability Zone fails.
You could also use AWS Transit Gateway to implement a transparent proxy solution that scales horizontally. This allows you to add or remove proxy instances based on the demand, instead of changing the instance type. With this approach, you must deploy a fleet of proxy instances – launched by an Auto Scaling group, for example – and mount a VPN connection between each instance and the transit gateway. The proxy instances need to support ECMP (“Equal Cost Multipath routing”; see Transit Gateways) to equally spread the outbound traffic between instances. I don’t describe this alternative architecture further in this blog post.
Conclusion
In this post, I’ve shown how you can use Squid to implement a high availability solution that filters outgoing traffic to the Internet and helps meet your security and compliance needs, while being fully transparent for the back-end instances in your VPC. I’ve also discussed the key differences between transparent proxies and forward proxies. Finally, I gave an example of how to share a transparent proxy solution across multiple VPCs using AWS Transit Gateway.
If you have any questions or suggestions, please leave a comment below or on the Amazon VPC forum.
If you have feedback about this blog post, submit comments in the Comments section below.
Want more AWS Security news? Follow us on Twitter.
Nicolas Malaval
Nicolas is a Solution Architect for Amazon Web Services. He lives in Paris and helps our healthcare customers in France adopt cloud technology and innovate with AWS. Before that, he spent three years as a Consultant for AWS Professional Services, working with enterprise customers.
#gallery-0-5 { margin: auto; } #gallery-0-5 .gallery-item { float: left; margin-top: 10px; text-align: center; width: 33%; } #gallery-0-5 img { border: 2px solid #cfcfcf; } #gallery-0-5 .gallery-caption { margin-left: 0; } /* see gallery_shortcode() in wp-includes/media.php */
Go to Source Author: Nicolas Malaval How to add DNS filtering to your NAT instance with Squid Original Post from Amazon Security Author: Nicolas Malaval Note from September 4, 2019: We’ve updated this blog post, initially published on January 26, 2016.
0 notes
clunite · 7 years ago
Photo
Tumblr media
Well, I didn't know you can get sued for using OpenSource. "Linux beats legal threat from one of its own developers" https://buff.ly/2oYOp6O The last thing Linux at large wants is for a single rogue developer to be shaking down companies. GPLv2 defenders want companies that use Linux to abide by the GPLv2 -- not pay a programmer off. Indeed, one of the Principles of Community-Oriented GPL Enforcement is "Community-oriented enforcement must never prioritize financial gain." McHardy was able to start taking these actions because he'd contributed some code to the Linux kernel and had been the chair of Linux's Netfilter core development team. Netfilter is a Linux network utility that handles Network Address Translation (NAT), and with IPTables, firewalls. As a Linux developer, McHardy owns the copyright to his code contributions, but not to the whole Linux kernel. . .. . . . . . . #Linux #legal #developers #roguedeveloper #GPLv2 #sued #opensource #redhat #mchardy #gpl #fedora #ubuntu #suse #linuxkernal #kernal
0 notes
Quote
There are different ways of building your own anti-DDoS rules for iptables. We will be discussing the most effective iptables DDoS protection methods in this comprehensive tutorial. This guide will teach you how to: Select the best iptables table and chain to stop DDoS attacks Tweak your kernel settings to mitigate the effects of DDoS attacks Use iptables to block most TCP-based DDoS attacks Use iptables SYNPROXY to block SYN floods Please note that this article is written for professionals who deal with Linux servers on a daily basis. If you just want to protect your online application from DDoS attacks, you can use our remote protection, a VPS with DDoS protection or a DDoS protected bare metal server. While one can do a lot with iptables to block DDoS attacks, there isn’t a way around actual hardware firewalls (we recently reviewed RioRey DDoS mitigation hardware) to detect and stop large DDoS floods. However, it isn’t impossible to filter most bad traffic at line rate using iptables! We’ll only cover protection from TCP-based attacks. Most UDP-based attacks are amplified reflection attacks that will exhaust the network interface card of any common server. The only mitigation approach that makes sense against these types of attacks is to block them at the edge or core network or even at the carrier already. Did you know we now offer VPS with unmetered bandwidth and DDoS protection in Chicago, Illinois and Bucharest, Romania? If they are able to reach your server, there isn’t much you can do against those multi-Gbit/s attacks except to move to a DDoS protected network. What Is IPtables? netfilter iptables (soon to be replaced by nftables) is a user-space command line utility to configure kernel packet filtering rules developed by netfilter. It’s the default firewall management utility on Linux systems – everyone working with Linux systems should be familiar with it or have at least heard of it. iptables can be used to filter certain packets, block source or destination ports and IP addresses, forward packets via NAT and a lot of other things. Most commonly it’s used to block destination ports and source IP addresses. Why Your IPtables Anti-DDoS Rules Suck To understand why your current iptables rules to prevent DDoS attacks suck, we first have to dig into how iptables works. iptables is a command line tool used to set up and control the tables of IP packet filter rules. There are different tables for different purposes. IPtables Tables Filter: The filter table is the default and most commonly used table that rules go to if you don’t use the -t (–table) option. Nat: This table is used for Network Address Translation (NAT). If a packet creates a new connection, the nat table gets checked for rules. Mangle: The mangle table is used to modify or mark packets and their header information. Raw: This table’s purpose is mainly to exclude certain packets from connection tracking using the NOTRACK target. As you can see there are four different tables on an average Linux system that doesn’t have non-standard kernel modules loaded. Each of these tables supports a different set of iptables chains. IPtables Chains PREROUTING: raw, nat, mangle Applies to packets that enter the network interface card (NIC) INPUT: filter, mangle Applies to packets destined to a local socket FORWARD: filter, mangle Applies to packets that are being routed through the server OUTPUT: raw, filter, nat, mangle Applies to packets that the server sends (locally generated) POSTROUTING: nat, mangle Applies to packets that leave the server Depending on what kind of packets you want to block or modify, you select a certain iptables table and a chain that the selected table supports. Of course, we’re still missing an explanation of iptables targets (ACCEPT, DROP, REJECT, etc.), but we’re assuming that if you’re reading this article, you already know how to deal with iptables. We’re going to explain why your iptables rules suck to stop DDoS and not teach you how to use iptables. Let’s get back to that. If you want to block a DDoS attack with iptables, performance of the iptables rules is extremely important. Most TCP-based DDoS attack types use a high packet rate, meaning the sheer number of packets per second is what causes the server to go down. That’s why you want to make sure that you can process and block as many packets per second as possible. You’ll find that most if not all guides on how to block DDoS attacks using iptables use the filter table and the INPUT chain for anti-DDoS rules. The issue with this approach is that the INPUT chain is only processed after the PREROUTING and FORWARD chains and therefore only applies if the packet doesn’t match any of these two chains. This causes a delay in the filtering of the packet which consumes resources. In conclusion, to make our rules as effective as possible, we need to move our anti-DDoS rules as far up the chains as possible. The first chain that can apply to a packet is the PREROUTING chain, so ideally we’ll want to filter the bad packets in this chain already. However, the filter table doesn’t support the PREROUTING chain. To get around this problem, we can simply use the mangle table instead of the filter table for our anti-DDoS iptables rules. It supports most if not all rules that the filter table supports while also supporting all iptables chains. So you want to know why your iptables DDoS protection rules suck? It’s because you use the filter table and the INPUT chain to block the bad packets! The best solution to dramatically increase the performance of your iptables rules and therefore the amount of (TCP) DDoS attack traffic they can filter is to use the mangle table and the PREROUTING chain! The Best Linux Kernel Settings to Mitigate DDoS Another common mistake is that people don’t use optimized kernel settings to better mitigate the effects of DDoS attacks. Note that this guide focuses on CentOS 7 as the operating system of choice. CentOS 7 includes a recent version of iptables and support of the new SYNPROXY target. We won’t cover every single kernel setting that you need to adjust in order to better mitigate DDoS with iptables. Instead, we provide a set of CentOS 7 kernel settings that we would use. Just put the below in your /etc/sysctl.conf file and apply the settings with sysctl -p. Anti-DDoS Kernel Settings (sysctl.conf) kernel.printk = 4 4 1 7 kernel.panic = 10 kernel.sysrq = 0 kernel.shmmax = 4294967296 kernel.shmall = 4194304 kernel.core_uses_pid = 1 kernel.msgmnb = 65536 kernel.msgmax = 65536 vm.swappiness = 20 vm.dirty_ratio = 80 vm.dirty_background_ratio = 5 fs.file-max = 2097152 net.core.netdev_max_backlog = 262144 net.core.rmem_default = 31457280 net.core.rmem_max = 67108864 net.core.wmem_default = 31457280 net.core.wmem_max = 67108864 net.core.somaxconn = 65535 net.core.optmem_max = 25165824 net.ipv4.neigh.default.gc_thresh1 = 4096 net.ipv4.neigh.default.gc_thresh2 = 8192 net.ipv4.neigh.default.gc_thresh3 = 16384 net.ipv4.neigh.default.gc_interval = 5 net.ipv4.neigh.default.gc_stale_time = 120 net.netfilter.nf_conntrack_max = 10000000 net.netfilter.nf_conntrack_tcp_loose = 0 net.netfilter.nf_conntrack_tcp_timeout_established = 1800 net.netfilter.nf_conntrack_tcp_timeout_close = 10 net.netfilter.nf_conntrack_tcp_timeout_close_wait = 10 net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 20 net.netfilter.nf_conntrack_tcp_timeout_last_ack = 20 net.netfilter.nf_conntrack_tcp_timeout_syn_recv = 20 net.netfilter.nf_conntrack_tcp_timeout_syn_sent = 20 net.netfilter.nf_conntrack_tcp_timeout_time_wait = 10 net.ipv4.tcp_slow_start_after_idle = 0 net.ipv4.ip_local_port_range = 1024 65000 net.ipv4.ip_no_pmtu_disc = 1 net.ipv4.route.flush = 1 net.ipv4.route.max_size = 8048576 net.ipv4.icmp_echo_ignore_broadcasts = 1 net.ipv4.icmp_ignore_bogus_error_responses = 1 net.ipv4.tcp_congestion_control = htcp net.ipv4.tcp_mem = 65536 131072 262144 net.ipv4.udp_mem = 65536 131072 262144 net.ipv4.tcp_rmem = 4096 87380 33554432 net.ipv4.udp_rmem_min = 16384 net.ipv4.tcp_wmem = 4096 87380 33554432 net.ipv4.udp_wmem_min = 16384 net.ipv4.tcp_max_tw_buckets = 1440000 net.ipv4.tcp_tw_recycle = 0 net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_max_orphans = 400000 net.ipv4.tcp_window_scaling = 1 net.ipv4.tcp_rfc1337 = 1 net.ipv4.tcp_syncookies = 1 net.ipv4.tcp_synack_retries = 1 net.ipv4.tcp_syn_retries = 2 net.ipv4.tcp_max_syn_backlog = 16384 net.ipv4.tcp_timestamps = 1 net.ipv4.tcp_sack = 1 net.ipv4.tcp_fack = 1 net.ipv4.tcp_ecn = 2 net.ipv4.tcp_fin_timeout = 10 net.ipv4.tcp_keepalive_time = 600 net.ipv4.tcp_keepalive_intvl = 60 net.ipv4.tcp_keepalive_probes = 10 net.ipv4.tcp_no_metrics_save = 1 net.ipv4.ip_forward = 0 net.ipv4.conf.all.accept_redirects = 0 net.ipv4.conf.all.send_redirects = 0 net.ipv4.conf.all.accept_source_route = 0 net.ipv4.conf.all.rp_filter = 1 These sysctl.conf settings help to maximize the performance of your server under DDoS as well as the effectiveness of the iptables rules that we’re going to provide in this guide. Do you want REAL DDoS protection? View DDoS Solutions The Actual IPtables Anti-DDoS Rules Considering you now know that you need to use the mangle table and the PREROUTING chain as well as optimized kernel settings to mitigate the effects of DDoS attacks, we’ll now move on to a couple of example rules to mitigate most TCP DDoS attacks. DDoS attacks are complex. There are many different types of DDoS and it’s close to impossible to maintain signature-based rules against all of them. But luckily there is something called connection tracking (nf_conntrack kernel module), which can help us to mitigate almost any TCP-based DDoS attack that doesn’t use SYN packets that seem legitimate. This includes all types of ACK and SYN-ACK DDoS attacks as well as DDoS attacks that use bogus TCP flags. We’ll start with just five simple iptables rules that will already drop many TCP-based DDoS attacks. Block Invalid Packets iptables -t mangle -A PREROUTING -m conntrack --ctstate INVALID -j DROP This rule blocks all packets that are not a SYN packet and don’t belong to an established TCP connection. Block New Packets That Are Not SYN iptables -t mangle -A PREROUTING -p tcp ! --syn -m conntrack --ctstate NEW -j DROP This blocks all packets that are new (don’t belong to an established connection) and don’t use the SYN flag. This rule is similar to the “Block Invalid Packets” one, but we found that it catches some packets that the other one doesn’t. Block Uncommon MSS Values iptables -t mangle -A PREROUTING -p tcp -m conntrack --ctstate NEW -m tcpmss ! --mss 536:65535 -j DROP The above iptables rule blocks new packets (only SYN packets can be new packets as per the two previous rules) that use a TCP MSS value that is not common. This helps to block dumb SYN floods. Block Packets With Bogus TCP Flags iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN FIN,SYN -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags SYN,RST SYN,RST -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,RST FIN,RST -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,ACK FIN -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,URG URG -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,FIN FIN -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,PSH PSH -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL ALL -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL NONE -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL FIN,PSH,URG -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,FIN,PSH,URG -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP The above ruleset blocks packets that use bogus TCP flags, ie. TCP flags that legitimate packets wouldn’t use. Block Packets From Private Subnets (Spoofing) iptables -t mangle -A PREROUTING -s 224.0.0.0/3 -j DROP iptables -t mangle -A PREROUTING -s 169.254.0.0/16 -j DROP iptables -t mangle -A PREROUTING -s 172.16.0.0/12 -j DROP iptables -t mangle -A PREROUTING -s 192.0.2.0/24 -j DROP iptables -t mangle -A PREROUTING -s 192.168.0.0/16 -j DROP iptables -t mangle -A PREROUTING -s 10.0.0.0/8 -j DROP iptables -t mangle -A PREROUTING -s 0.0.0.0/8 -j DROP iptables -t mangle -A PREROUTING -s 240.0.0.0/5 -j DROP iptables -t mangle -A PREROUTING -s 127.0.0.0/8 ! -i lo -j DROP These rules block spoofed packets originating from private (local) subnets. On your public network interface you usually don’t want to receive packets from private source IPs. These rules assume that your loopback interface uses the 127.0.0.0/8 IP space. These five sets of rules alone already block many TCP-based DDoS attacks at very high packet rates. With the kernel settings and rules mentioned above, you’ll be able to filter ACK and SYN-ACK attacks at line rate. Additional Rules iptables -t mangle -A PREROUTING -p icmp -j DROP This drops all ICMP packets. ICMP is only used to ping a host to find out if it’s still alive. Because it’s usually not needed and only represents another vulnerability that attackers can exploit, we block all ICMP packets to mitigate Ping of Death (ping flood), ICMP flood and ICMP fragmentation flood. iptables -A INPUT -p tcp -m connlimit --connlimit-above 80 -j REJECT --reject-with tcp-reset This iptables rule helps against connection attacks. It rejects connections from hosts that have more than 80 established connections. If you face any issues you should raise the limit as this could cause troubles with legitimate clients that establish a large number of TCP connections. iptables -A INPUT -p tcp -m conntrack --ctstate NEW -m limit --limit 60/s --limit-burst 20 -j ACCEPT iptables -A INPUT -p tcp -m conntrack --ctstate NEW -j DROP Limits the new TCP connections that a client can establish per second. This can be useful against connection attacks, but not so much against SYN floods because the usually use an endless amount of different spoofed source IPs. iptables -t mangle -A PREROUTING -f -j DROP This rule blocks fragmented packets. Normally you don’t need those and blocking fragments will mitigate UDP fragmentation flood. But most of the time UDP fragmentation floods use a high amount of bandwidth that is likely to exhaust the capacity of your network card, which makes this rule optional and probably not the most useful one. iptables -A INPUT -p tcp --tcp-flags RST RST -m limit --limit 2/s --limit-burst 2 -j ACCEPT iptables -A INPUT -p tcp --tcp-flags RST RST -j DROP This limits incoming TCP RST packets to mitigate TCP RST floods. Effectiveness of this rule is questionable. Mitigating SYN Floods With SYNPROXY SYNPROXY is a new target of iptables that has been added in Linux kernel version 3.12 and iptables 1.4.21. CentOS 7 backported the feature and it’s available in its 3.10 default kernel. The purpose of SYNPROXY is to check whether the host that sent the SYN packet actually establishes a full TCP connection or just does nothing after it sent the SYN packet. If it does nothing, it discards the packet with minimal performance impact. While the iptables rules that we provided above already block most TCP-based attacks, the attack type that can still slip through them if sophisticated enough is a SYN flood. It’s important to note that the performance of the rules will always be better if we find a certain pattern or signature to block, such as packet length (-m length), TOS (-m tos), TTL (-m ttl) or strings and hex values (-m string and -m u32 for the more advanced users). But in some rare cases that’s not possible or at least not easy to achieve. So, in these cases, you can make use of SYNPROXY. Here are iptables SYNPROXY rules that help mitigate SYN floods that bypass our other rules: iptables -t raw -A PREROUTING -p tcp -m tcp --syn -j CT --notrack iptables -A INPUT -p tcp -m tcp -m conntrack --ctstate INVALID,UNTRACKED -j SYNPROXY --sack-perm --timestamp --wscale 7 --mss 1460 iptables -A INPUT -m conntrack --ctstate INVALID -j DROP These rules apply to all ports. If you want to use SYNPROXY only on certain TCP ports that are active (recommended – also you should block all TCP ports that are not in use using the mangle table and PREROUTING chain), you can just add –dport 80 to each of the rules if you want to use SYNPROXY on port 80 only. To verify that SYNPROXY is working, you can do watch -n1 cat /proc/net/stat/synproxy. If the values change when you establish a new TCP connection to the port you use SYNPROXY on, it works. The Complete IPtables Anti-DDoS Rules If you don’t want to copy & paste each single rule we discussed in this article, you can use the below ruleset for basic DDoS protection of your Linux server. ### 1: Drop invalid packets ### /sbin/iptables -t mangle -A PREROUTING -m conntrack --ctstate INVALID -j DROP ### 2: Drop TCP packets that are new and are not SYN ### /sbin/iptables -t mangle -A PREROUTING -p tcp ! --syn -m conntrack --ctstate NEW -j DROP ### 3: Drop SYN packets with suspicious MSS value ### /sbin/iptables -t mangle -A PREROUTING -p tcp -m conntrack --ctstate NEW -m tcpmss ! --mss 536:65535 -j DROP ### 4: Block packets with bogus TCP flags ### /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN FIN,SYN -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags SYN,RST SYN,RST -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,RST FIN,RST -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,ACK FIN -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,URG URG -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,FIN FIN -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,PSH PSH -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL ALL -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL NONE -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL FIN,PSH,URG -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,FIN,PSH,URG -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP ### 5: Block spoofed packets ### /sbin/iptables -t mangle -A PREROUTING -s 224.0.0.0/3 -j DROP /sbin/iptables -t mangle -A PREROUTING -s 169.254.0.0/16 -j DROP /sbin/iptables -t mangle -A PREROUTING -s 172.16.0.0/12 -j DROP /sbin/iptables -t mangle -A PREROUTING -s 192.0.2.0/24 -j DROP /sbin/iptables -t mangle -A PREROUTING -s 192.168.0.0/16 -j DROP /sbin/iptables -t mangle -A PREROUTING -s 10.0.0.0/8 -j DROP /sbin/iptables -t mangle -A PREROUTING -s 0.0.0.0/8 -j DROP /sbin/iptables -t mangle -A PREROUTING -s 240.0.0.0/5 -j DROP /sbin/iptables -t mangle -A PREROUTING -s 127.0.0.0/8 ! -i lo -j DROP ### 6: Drop ICMP (you usually don't need this protocol) ### /sbin/iptables -t mangle -A PREROUTING -p icmp -j DROP ### 7: Drop fragments in all chains ### /sbin/iptables -t mangle -A PREROUTING -f -j DROP ### 8: Limit connections per source IP ### /sbin/iptables -A INPUT -p tcp -m connlimit --connlimit-above 111 -j REJECT --reject-with tcp-reset ### 9: Limit RST packets ### /sbin/iptables -A INPUT -p tcp --tcp-flags RST RST -m limit --limit 2/s --limit-burst 2 -j ACCEPT /sbin/iptables -A INPUT -p tcp --tcp-flags RST RST -j DROP ### 10: Limit new TCP connections per second per source IP ### /sbin/iptables -A INPUT -p tcp -m conntrack --ctstate NEW -m limit --limit 60/s --limit-burst 20 -j ACCEPT /sbin/iptables -A INPUT -p tcp -m conntrack --ctstate NEW -j DROP ### 11: Use SYNPROXY on all ports (disables connection limiting rule) ### # Hidden - unlock content above in "Mitigating SYN Floods With SYNPROXY" section Bonus Rules Here are some more iptables rules that are useful to increase the overall security of a Linux server: ### SSH brute-force protection ### /sbin/iptables -A INPUT -p tcp --dport ssh -m conntrack --ctstate NEW -m recent --set /sbin/iptables -A INPUT -p tcp --dport ssh -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 10 -j DROP ### Protection against port scanning ### /sbin/iptables -N port-scanning /sbin/iptables -A port-scanning -p tcp --tcp-flags SYN,ACK,FIN,RST RST -m limit --limit 1/s --limit-burst 2 -j RETURN /sbin/iptables -A port-scanning -j DROP Conclusion This tutorial demonstrates some of the most powerful and effective methods to stop DDoS attacks using iptables. We’ve successfully mitigated DDoS attacks that peaked at multiple million packets per second using these iptables rules. Every single guide on the same topic that we had researched provided inefficient methods to stop DDoS traffic or only a very limited number of iptables rules. If used correctly, iptables is an extremely powerful tool that’s able to block different types of DDoS attacks at line-rate of 1GigE NICs and close to line-rate of 10GigE NICs. Don’t underestimate the power of iptables! Stay in Touch Join our exclusive hosting & security newsletter. Keep me updated! Thank you for keeping in touch! You'll hear from us. 🙂 DDoS Protection Mitigates Attacks up to 750Gbps Custom DDoS Filtering Rules Remote & On-Site Solutions     Get DDoS Protection   DDoS Protection With IPtables: The Ultimate Guide appeared on JavaPipe
http://javapipe1.blogspot.com/2017/12/ddos-protection-with-iptables-ultimate.html
0 notes
javapipe1 · 8 years ago
Text
DDoS Protection With IPtables: The Ultimate Guide
Tumblr media
There are different ways of building your own anti-DDoS rules for iptables. We will be discussing the most effective iptables DDoS protection methods in this comprehensive tutorial.
This guide will teach you how to:
Select the best iptables table and chain to stop DDoS attacks
Tweak your kernel settings to mitigate the effects of DDoS attacks
Use iptables to block most TCP-based DDoS attacks
Use iptables SYNPROXY to block SYN floods
Please note that this article is written for professionals who deal with Linux servers on a daily basis.
If you just want to protect your online application from DDoS attacks, you can use our remote protection, a VPS with DDoS protection or a DDoS protected bare metal server.
While one can do a lot with iptables to block DDoS attacks, there isn’t a way around actual hardware firewalls (we recently reviewed RioRey DDoS mitigation hardware) to detect and stop large DDoS floods.
However, it isn’t impossible to filter most bad traffic at line rate using iptables!
We’ll only cover protection from TCP-based attacks. Most UDP-based attacks are amplified reflection attacks that will exhaust the network interface card of any common server.
The only mitigation approach that makes sense against these types of attacks is to block them at the edge or core network or even at the carrier already.
Did you know we now offer VPS with unmetered bandwidth and DDoS protection in Chicago, Illinois and Bucharest, Romania?
If they are able to reach your server, there isn’t much you can do against those multi-Gbit/s attacks except to move to a DDoS protected network.
Tumblr media
What Is IPtables?
netfilter iptables (soon to be replaced by nftables) is a user-space command line utility to configure kernel packet filtering rules developed by netfilter.
It’s the default firewall management utility on Linux systems – everyone working with Linux systems should be familiar with it or have at least heard of it.
iptables can be used to filter certain packets, block source or destination ports and IP addresses, forward packets via NAT and a lot of other things.
Most commonly it’s used to block destination ports and source IP addresses.
Why Your IPtables Anti-DDoS Rules Suck
To understand why your current iptables rules to prevent DDoS attacks suck, we first have to dig into how iptables works.
iptables is a command line tool used to set up and control the tables of IP packet filter rules. There are different tables for different purposes.
IPtables Tables
Filter: The filter table is the default and most commonly used table that rules go to if you don’t use the -t (–table) option.
Nat: This table is used for Network Address Translation (NAT). If a packet creates a new connection, the nat table gets checked for rules.
Mangle: The mangle table is used to modify or mark packets and their header information.
Raw: This table’s purpose is mainly to exclude certain packets from connection tracking using the NOTRACK target.
As you can see there are four different tables on an average Linux system that doesn’t have non-standard kernel modules loaded. Each of these tables supports a different set of iptables chains.
IPtables Chains
PREROUTING: raw, nat, mangle
Applies to packets that enter the network interface card (NIC)
INPUT: filter, mangle
Applies to packets destined to a local socket
FORWARD: filter, mangle
Applies to packets that are being routed through the server
OUTPUT: raw, filter, nat, mangle
Applies to packets that the server sends (locally generated)
POSTROUTING: nat, mangle
Applies to packets that leave the server
Depending on what kind of packets you want to block or modify, you select a certain iptables table and a chain that the selected table supports.
Of course, we’re still missing an explanation of iptables targets (ACCEPT, DROP, REJECT, etc.), but we’re assuming that if you’re reading this article, you already know how to deal with iptables.
We’re going to explain why your iptables rules suck to stop DDoS and not teach you how to use iptables. Let’s get back to that.
If you want to block a DDoS attack with iptables, performance of the iptables rules is extremely important. Most TCP-based DDoS attack types use a high packet rate, meaning the sheer number of packets per second is what causes the server to go down.
That’s why you want to make sure that you can process and block as many packets per second as possible.
You’ll find that most if not all guides on how to block DDoS attacks using iptables use the filter table and the INPUT chain for anti-DDoS rules.
The issue with this approach is that the INPUT chain is only processed after the PREROUTING and FORWARD chains and therefore only applies if the packet doesn’t match any of these two chains.
This causes a delay in the filtering of the packet which consumes resources. In conclusion, to make our rules as effective as possible, we need to move our anti-DDoS rules as far up the chains as possible.
The first chain that can apply to a packet is the PREROUTING chain, so ideally we’ll want to filter the bad packets in this chain already.
However, the filter table doesn’t support the PREROUTING chain. To get around this problem, we can simply use the mangle table instead of the filter table for our anti-DDoS iptables rules.
It supports most if not all rules that the filter table supports while also supporting all iptables chains.
So you want to know why your iptables DDoS protection rules suck? It’s because you use the filter table and the INPUT chain to block the bad packets!
The best solution to dramatically increase the performance of your iptables rules and therefore the amount of (TCP) DDoS attack traffic they can filter is to use the mangle table and the PREROUTING chain!
The Best Linux Kernel Settings to Mitigate DDoS
Another common mistake is that people don’t use optimized kernel settings to better mitigate the effects of DDoS attacks.
Note that this guide focuses on CentOS 7 as the operating system of choice. CentOS 7 includes a recent version of iptables and support of the new SYNPROXY target.
We won’t cover every single kernel setting that you need to adjust in order to better mitigate DDoS with iptables.
Instead, we provide a set of CentOS 7 kernel settings that we would use. Just put the below in your /etc/sysctl.conf file and apply the settings with sysctl -p.
Anti-DDoS Kernel Settings (sysctl.conf)
kernel.printk = 4 4 1 7 kernel.panic = 10 kernel.sysrq = 0 kernel.shmmax = 4294967296 kernel.shmall = 4194304 kernel.core_uses_pid = 1 kernel.msgmnb = 65536 kernel.msgmax = 65536 vm.swappiness = 20 vm.dirty_ratio = 80 vm.dirty_background_ratio = 5 fs.file-max = 2097152 net.core.netdev_max_backlog = 262144 net.core.rmem_default = 31457280 net.core.rmem_max = 67108864 net.core.wmem_default = 31457280 net.core.wmem_max = 67108864 net.core.somaxconn = 65535 net.core.optmem_max = 25165824 net.ipv4.neigh.default.gc_thresh1 = 4096 net.ipv4.neigh.default.gc_thresh2 = 8192 net.ipv4.neigh.default.gc_thresh3 = 16384 net.ipv4.neigh.default.gc_interval = 5 net.ipv4.neigh.default.gc_stale_time = 120 net.netfilter.nf_conntrack_max = 10000000 net.netfilter.nf_conntrack_tcp_loose = 0 net.netfilter.nf_conntrack_tcp_timeout_established = 1800 net.netfilter.nf_conntrack_tcp_timeout_close = 10 net.netfilter.nf_conntrack_tcp_timeout_close_wait = 10 net.netfilter.nf_conntrack_tcp_timeout_fin_wait = 20 net.netfilter.nf_conntrack_tcp_timeout_last_ack = 20 net.netfilter.nf_conntrack_tcp_timeout_syn_recv = 20 net.netfilter.nf_conntrack_tcp_timeout_syn_sent = 20 net.netfilter.nf_conntrack_tcp_timeout_time_wait = 10 net.ipv4.tcp_slow_start_after_idle = 0 net.ipv4.ip_local_port_range = 1024 65000 net.ipv4.ip_no_pmtu_disc = 1 net.ipv4.route.flush = 1 net.ipv4.route.max_size = 8048576 net.ipv4.icmp_echo_ignore_broadcasts = 1 net.ipv4.icmp_ignore_bogus_error_responses = 1 net.ipv4.tcp_congestion_control = htcp net.ipv4.tcp_mem = 65536 131072 262144 net.ipv4.udp_mem = 65536 131072 262144 net.ipv4.tcp_rmem = 4096 87380 33554432 net.ipv4.udp_rmem_min = 16384 net.ipv4.tcp_wmem = 4096 87380 33554432 net.ipv4.udp_wmem_min = 16384 net.ipv4.tcp_max_tw_buckets = 1440000 net.ipv4.tcp_tw_recycle = 0 net.ipv4.tcp_tw_reuse = 1 net.ipv4.tcp_max_orphans = 400000 net.ipv4.tcp_window_scaling = 1 net.ipv4.tcp_rfc1337 = 1 net.ipv4.tcp_syncookies = 1 net.ipv4.tcp_synack_retries = 1 net.ipv4.tcp_syn_retries = 2 net.ipv4.tcp_max_syn_backlog = 16384 net.ipv4.tcp_timestamps = 1 net.ipv4.tcp_sack = 1 net.ipv4.tcp_fack = 1 net.ipv4.tcp_ecn = 2 net.ipv4.tcp_fin_timeout = 10 net.ipv4.tcp_keepalive_time = 600 net.ipv4.tcp_keepalive_intvl = 60 net.ipv4.tcp_keepalive_probes = 10 net.ipv4.tcp_no_metrics_save = 1 net.ipv4.ip_forward = 0 net.ipv4.conf.all.accept_redirects = 0 net.ipv4.conf.all.send_redirects = 0 net.ipv4.conf.all.accept_source_route = 0 net.ipv4.conf.all.rp_filter = 1
These sysctl.conf settings help to maximize the performance of your server under DDoS as well as the effectiveness of the iptables rules that we’re going to provide in this guide.
Do you want REAL DDoS protection?
View DDoS Solutions
The Actual IPtables Anti-DDoS Rules
Considering you now know that you need to use the mangle table and the PREROUTING chain as well as optimized kernel settings to mitigate the effects of DDoS attacks, we’ll now move on to a couple of example rules to mitigate most TCP DDoS attacks.
DDoS attacks are complex.
There are many different types of DDoS and it’s close to impossible to maintain signature-based rules against all of them.
But luckily there is something called connection tracking (nf_conntrack kernel module), which can help us to mitigate almost any TCP-based DDoS attack that doesn’t use SYN packets that seem legitimate.
This includes all types of ACK and SYN-ACK DDoS attacks as well as DDoS attacks that use bogus TCP flags.
We’ll start with just five simple iptables rules that will already drop many TCP-based DDoS attacks.
Block Invalid Packets
iptables -t mangle -A PREROUTING -m conntrack --ctstate INVALID -j DROP
This rule blocks all packets that are not a SYN packet and don’t belong to an established TCP connection.
Block New Packets That Are Not SYN
iptables -t mangle -A PREROUTING -p tcp ! --syn -m conntrack --ctstate NEW -j DROP
This blocks all packets that are new (don’t belong to an established connection) and don’t use the SYN flag. This rule is similar to the “Block Invalid Packets” one, but we found that it catches some packets that the other one doesn’t.
Block Uncommon MSS Values
iptables -t mangle -A PREROUTING -p tcp -m conntrack --ctstate NEW -m tcpmss ! --mss 536:65535 -j DROP
The above iptables rule blocks new packets (only SYN packets can be new packets as per the two previous rules) that use a TCP MSS value that is not common. This helps to block dumb SYN floods.
Block Packets With Bogus TCP Flags
iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN FIN,SYN -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags SYN,RST SYN,RST -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,RST FIN,RST -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,ACK FIN -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,URG URG -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,FIN FIN -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,PSH PSH -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL ALL -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL NONE -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL FIN,PSH,URG -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,FIN,PSH,URG -j DROP iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP
The above ruleset blocks packets that use bogus TCP flags, ie. TCP flags that legitimate packets wouldn’t use.
Block Packets From Private Subnets (Spoofing)
iptables -t mangle -A PREROUTING -s 224.0.0.0/3 -j DROP iptables -t mangle -A PREROUTING -s 169.254.0.0/16 -j DROP iptables -t mangle -A PREROUTING -s 172.16.0.0/12 -j DROP iptables -t mangle -A PREROUTING -s 192.0.2.0/24 -j DROP iptables -t mangle -A PREROUTING -s 192.168.0.0/16 -j DROP iptables -t mangle -A PREROUTING -s 10.0.0.0/8 -j DROP iptables -t mangle -A PREROUTING -s 0.0.0.0/8 -j DROP iptables -t mangle -A PREROUTING -s 240.0.0.0/5 -j DROP iptables -t mangle -A PREROUTING -s 127.0.0.0/8 ! -i lo -j DROP
These rules block spoofed packets originating from private (local) subnets. On your public network interface you usually don’t want to receive packets from private source IPs.
These rules assume that your loopback interface uses the 127.0.0.0/8 IP space.
These five sets of rules alone already block many TCP-based DDoS attacks at very high packet rates.
With the kernel settings and rules mentioned above, you’ll be able to filter ACK and SYN-ACK attacks at line rate.
Additional Rules
iptables -t mangle -A PREROUTING -p icmp -j DROP
This drops all ICMP packets. ICMP is only used to ping a host to find out if it’s still alive. Because it’s usually not needed and only represents another vulnerability that attackers can exploit, we block all ICMP packets to mitigate Ping of Death (ping flood), ICMP flood and ICMP fragmentation flood.
iptables -A INPUT -p tcp -m connlimit --connlimit-above 80 -j REJECT --reject-with tcp-reset
This iptables rule helps against connection attacks. It rejects connections from hosts that have more than 80 established connections. If you face any issues you should raise the limit as this could cause troubles with legitimate clients that establish a large number of TCP connections.
iptables -A INPUT -p tcp -m conntrack --ctstate NEW -m limit --limit 60/s --limit-burst 20 -j ACCEPT iptables -A INPUT -p tcp -m conntrack --ctstate NEW -j DROP
Limits the new TCP connections that a client can establish per second. This can be useful against connection attacks, but not so much against SYN floods because the usually use an endless amount of different spoofed source IPs.
iptables -t mangle -A PREROUTING -f -j DROP
This rule blocks fragmented packets. Normally you don’t need those and blocking fragments will mitigate UDP fragmentation flood. But most of the time UDP fragmentation floods use a high amount of bandwidth that is likely to exhaust the capacity of your network card, which makes this rule optional and probably not the most useful one.
iptables -A INPUT -p tcp --tcp-flags RST RST -m limit --limit 2/s --limit-burst 2 -j ACCEPT iptables -A INPUT -p tcp --tcp-flags RST RST -j DROP
This limits incoming TCP RST packets to mitigate TCP RST floods. Effectiveness of this rule is questionable.
Mitigating SYN Floods With SYNPROXY
SYNPROXY is a new target of iptables that has been added in Linux kernel version 3.12 and iptables 1.4.21. CentOS 7 backported the feature and it’s available in its 3.10 default kernel.
The purpose of SYNPROXY is to check whether the host that sent the SYN packet actually establishes a full TCP connection or just does nothing after it sent the SYN packet.
If it does nothing, it discards the packet with minimal performance impact.
While the iptables rules that we provided above already block most TCP-based attacks, the attack type that can still slip through them if sophisticated enough is a SYN flood.
It’s important to note that the performance of the rules will always be better if we find a certain pattern or signature to block, such as packet length (-m length), TOS (-m tos), TTL (-m ttl) or strings and hex values (-m string and -m u32 for the more advanced users).
But in some rare cases that’s not possible or at least not easy to achieve. So, in these cases, you can make use of SYNPROXY.
Here are iptables SYNPROXY rules that help mitigate SYN floods that bypass our other rules:
iptables -t raw -A PREROUTING -p tcp -m tcp --syn -j CT --notrack iptables -A INPUT -p tcp -m tcp -m conntrack --ctstate INVALID,UNTRACKED -j SYNPROXY --sack-perm --timestamp --wscale 7 --mss 1460 iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
These rules apply to all ports. If you want to use SYNPROXY only on certain TCP ports that are active (recommended – also you should block all TCP ports that are not in use using the mangle table and PREROUTING chain), you can just add –dport 80 to each of the rules if you want to use SYNPROXY on port 80 only.
To verify that SYNPROXY is working, you can do watch -n1 cat /proc/net/stat/synproxy. If the values change when you establish a new TCP connection to the port you use SYNPROXY on, it works.
The Complete IPtables Anti-DDoS Rules
If you don’t want to copy & paste each single rule we discussed in this article, you can use the below ruleset for basic DDoS protection of your Linux server.
### 1: Drop invalid packets ### /sbin/iptables -t mangle -A PREROUTING -m conntrack --ctstate INVALID -j DROP ### 2: Drop TCP packets that are new and are not SYN ### /sbin/iptables -t mangle -A PREROUTING -p tcp ! --syn -m conntrack --ctstate NEW -j DROP ### 3: Drop SYN packets with suspicious MSS value ### /sbin/iptables -t mangle -A PREROUTING -p tcp -m conntrack --ctstate NEW -m tcpmss ! --mss 536:65535 -j DROP ### 4: Block packets with bogus TCP flags ### /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN,RST,PSH,ACK,URG NONE -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,SYN FIN,SYN -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags SYN,RST SYN,RST -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,RST FIN,RST -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags FIN,ACK FIN -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,URG URG -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,FIN FIN -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ACK,PSH PSH -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL ALL -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL NONE -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL FIN,PSH,URG -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,FIN,PSH,URG -j DROP /sbin/iptables -t mangle -A PREROUTING -p tcp --tcp-flags ALL SYN,RST,ACK,FIN,URG -j DROP ### 5: Block spoofed packets ### /sbin/iptables -t mangle -A PREROUTING -s 224.0.0.0/3 -j DROP /sbin/iptables -t mangle -A PREROUTING -s 169.254.0.0/16 -j DROP /sbin/iptables -t mangle -A PREROUTING -s 172.16.0.0/12 -j DROP /sbin/iptables -t mangle -A PREROUTING -s 192.0.2.0/24 -j DROP /sbin/iptables -t mangle -A PREROUTING -s 192.168.0.0/16 -j DROP /sbin/iptables -t mangle -A PREROUTING -s 10.0.0.0/8 -j DROP /sbin/iptables -t mangle -A PREROUTING -s 0.0.0.0/8 -j DROP /sbin/iptables -t mangle -A PREROUTING -s 240.0.0.0/5 -j DROP /sbin/iptables -t mangle -A PREROUTING -s 127.0.0.0/8 ! -i lo -j DROP ### 6: Drop ICMP (you usually don't need this protocol) ### /sbin/iptables -t mangle -A PREROUTING -p icmp -j DROP ### 7: Drop fragments in all chains ### /sbin/iptables -t mangle -A PREROUTING -f -j DROP ### 8: Limit connections per source IP ### /sbin/iptables -A INPUT -p tcp -m connlimit --connlimit-above 111 -j REJECT --reject-with tcp-reset ### 9: Limit RST packets ### /sbin/iptables -A INPUT -p tcp --tcp-flags RST RST -m limit --limit 2/s --limit-burst 2 -j ACCEPT /sbin/iptables -A INPUT -p tcp --tcp-flags RST RST -j DROP ### 10: Limit new TCP connections per second per source IP ### /sbin/iptables -A INPUT -p tcp -m conntrack --ctstate NEW -m limit --limit 60/s --limit-burst 20 -j ACCEPT /sbin/iptables -A INPUT -p tcp -m conntrack --ctstate NEW -j DROP ### 11: Use SYNPROXY on all ports (disables connection limiting rule) ### # Hidden - unlock content above in "Mitigating SYN Floods With SYNPROXY" section
Bonus Rules
Here are some more iptables rules that are useful to increase the overall security of a Linux server:
### SSH brute-force protection ### /sbin/iptables -A INPUT -p tcp --dport ssh -m conntrack --ctstate NEW -m recent --set /sbin/iptables -A INPUT -p tcp --dport ssh -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 10 -j DROP ### Protection against port scanning ### /sbin/iptables -N port-scanning /sbin/iptables -A port-scanning -p tcp --tcp-flags SYN,ACK,FIN,RST RST -m limit --limit 1/s --limit-burst 2 -j RETURN /sbin/iptables -A port-scanning -j DROP
Conclusion
This tutorial demonstrates some of the most powerful and effective methods to stop DDoS attacks using iptables.
We’ve successfully mitigated DDoS attacks that peaked at multiple million packets per second using these iptables rules.
Every single guide on the same topic that we had researched provided inefficient methods to stop DDoS traffic or only a very limited number of iptables rules.
If used correctly, iptables is an extremely powerful tool that’s able to block different types of DDoS attacks at line-rate of 1GigE NICs and close to line-rate of 10GigE NICs.
Don’t underestimate the power of iptables!
.et_bloom .et_bloom_optin_1 .et_bloom_form_content { background-color: #dd4242 !important; } .et_bloom .et_bloom_optin_1 .et_bloom_form_container .et_bloom_form_header { background-color: #ffffff !important; } .et_bloom .et_bloom_optin_1 .et_bloom_form_content button { background-color: #ffffff !important; } .et_bloom .et_bloom_optin_1 .et_bloom_form_content button { background-color: #ffffff !important; } .et_bloom .et_bloom_optin_1 .et_bloom_form_container h2, .et_bloom .et_bloom_optin_1 .et_bloom_form_container h2 span, .et_bloom .et_bloom_optin_1 .et_bloom_form_container h2 strong { font-family: "Open Sans", Helvetica, Arial, Lucida, sans-serif; }.et_bloom .et_bloom_optin_1 .et_bloom_form_container p, .et_bloom .et_bloom_optin_1 .et_bloom_form_container p span, .et_bloom .et_bloom_optin_1 .et_bloom_form_container p strong, .et_bloom .et_bloom_optin_1 .et_bloom_form_container form input, .et_bloom .et_bloom_optin_1 .et_bloom_form_container form button span { font-family: "Open Sans", Helvetica, Arial, Lucida, sans-serif; }
Stay in Touch
Join our exclusive hosting & security newsletter.
Keep me updated!
Thank you for keeping in touch! You'll hear from us. 🙂
DDoS Protection
Mitigates Attacks up to 750Gbps
Custom DDoS Filtering Rules
Remote & On-Site Solutions
   Get DDoS Protection
  DDoS Protection With IPtables: The Ultimate Guide appeared on JavaPipe
0 notes
javatutorialcorner · 8 years ago
Text
iptables Linux Command
iptables
iptables command [options]
System administration command. Configure netfilter filtering rules for kernels 2.4 and later. Rules for iptables consist of some matching criteria and a target, a result to be applied if the packet matches the criteria. The rules are organized into chains. You can use these rules to build a firewall, masquerade your local area network, or just reject certain kinds of network connections. There are three built-in tables for iptables: one for network filtering (filter), one for Network Address Translation (nat), and the last for specialized packet alterations (mangle). Firewall rules are organized into chains, ordered checklists of rules that the kernel works through looking for matches. The filter table has three built-in chains: INPUT, OUTPUT, and FORWARD. The INPUT and OUTPUT chains handle packets originating from or destined for the host system. The FORWARD chain handles packets just passing through the host system. The nat table also has three built-in chains: PREROUTING, POSTROUTING, and OUTPUT. mangle has only two chains: PREROUTING and OUTPUT. netfilter checks packets entering the system. After applying any PREROUTING rules, it passes them to the INPUT chain, or to the FORWARD chain if the packet is just passing through. Upon leaving, the system packets are passed to the OUTPUT chain and then on to any POSTROUTING rules. Each of these chains has a default target (a policy) in case no match is found. User-defined chains can also be created and used as targets for packets but do not have default policies. If no match can be found in a user-defined chain, the packet is returned to the chain from which it was called and tested against the next rule in that chain. iptables changes only the rules in the running kernel. When the system is powered off, all changes are lost. You can use the iptables-save command to make a script you can run with iptables-restore to restore your firewall settings. Such a script is often called at bootup. Many distributions have an iptables initialization script that uses the output from iptables-save.
Commands
iptables is almost always invoked with one of the following commands: -A chain rules, --append chain rules Append new rules to chain. -D chain rules, --delete chain rules Delete rules from chain. Rules can be specified by their ordinal number in the chain as well as by a general rule description. -E old-chain new-chain, --rename-chain old-chain new-chain Rename old-chain to new-chain. -F [chain] , --flush [chain] Remove all rules from chain, or from all chains if chain is not specified. -I chain number rules, --insert chain number rules Insert rules into chain at the ordinal position given by number. -L [chain] , --list [chain] List the rules in chain, or all chains if chain is not specified. -N chain, --new-chain chain Create a new chain. The chain's name must be unique. This is how user-defined chains are created. -P chain target, --policy chain target Set the default policy for a built-in chain; the target itself cannot be a chain. -R chain number rule, --replace chain number rule Replace a rule in chain. The rule to be replaced is specified by its ordinal number. -X [chain] , --delete-chain [chain] Delete the specified user-defined chain, or all user-defined chains if chain is not specified. -Z [chain] , --zero [chain] Zero the packet and byte counters in chain. If no chain is specified, all chains will be reset. When used without specifying a chain and combined with the -L command, list the current counter values before they are reset.
Targets
A target may be the name of a chain or one of the following special values: ACCEPT Let the packet through. DROP Drop the packet. QUEUE Send packets to the user space for processing. RETURN Stop traversing the current chain and return to the point in the previous chain from which this one was called. If RETURN is the target of a rule in a built-in chain, the built-in chain's default policy is applied.
Rule specification parameters
These options are used to create rules for use with the preceding commands. Rules consist of some matching criteria and usually a target to jump to (-j) if the match is made. Many of the parameters for these matching rules can be expressed as a negative with an exclamation point (!) meaning "not." Those rules will match everything except the given parameter. -c packets bytes, --set-counters packets bytes Initialize packet and byte counters to the specified values. -d [!] address[/mask] [!] [port] , --destination [!] address[/mask] [port] Match packets from the destination address. The address may be supplied as a hostname, a network name, or an IP address. The optional mask is the netmask to use and may be supplied either in the traditional form (e.g., /255.255.255.0) or in the modern form (e.g., /24). [!] -f, [!] --fragment The rule applies only to the second or further fragments of a fragmented packet. -i [!] name[+] , --in-interface name[+] Match packets being received from interface name. name is the network interface used by your system (e.g., eth0 or ppp0). A + can be used as a wildcard, so ppp+ would match any interface name beginning with ppp. -j target, --jump target Jump to a special target or a user-defined chain. If this option is not specified for a rule, matching the rule only increases the rule's counters, and the packet is tested against the next rule. -o [!] name[+] , --out-interface name[+] Match packets being sent from interface name. See the description of -i for the syntax for name. -p [!] name, --protocol [!] name Match packets of protocol name. The value of name can be given as a name or number, as found in the file /etc/protocols. The most common values are tcp, udp, icmp, or the special value all. The number 0 is equivalent to all, and this is the default value when this option is not used. If there are extended matching rules associated with the specified protocol, they will be loaded automatically. You need not use the -m option to load them. -s [!] address[/mask] [!] [port] , --source [!] address[/mask] [!] [port] Match packets with the source address. See the description of -d for the syntax of this option.
Options
-h [icmp] , --help [icmp] Print help message. If icmp is specified, a list of valid ICMP type names will be printed. -h can also be used with the -m option to get help on an extension module. --line-numbers Used with the -L command. Add the line number to the beginning of each rule in a listing, indicating its position in the chain. -m module, --match module Explicitly load matching rule extensions associated with module. See the next section. --modprobe=command Use specified command to load any necessary kernel modules while adding or inserting rules into a chain. -n, --numeric Print all IP address and port numbers in numeric form. By default, text names are displayed when possible. -t name, --table name Apply rules to the specified table. Rules apply to the filter table by default. -v, --verbose Verbose mode. -x, --exact Expand all numbers in a listing (-L). Display the exact value of the packet and byte counters instead of rounded figures.
Match extensions
Several modules extend the matching capabilities of netfilter rules. Using the -p option will cause iptables to load associated modules implicitly. Others need to be loaded explicitly with the -m or --match options. Here we document those modules used most frequently. icmp Loaded when -p icmp is the only protocol specified: --icmp-type [!] type Match the specified ICMP type. type may be a numeric ICMP type or one of the ICMP type names shown by the command iptables -p icmp -h. multiport Loaded explicitly with the -m option. The multiport extensions match sets of source or destination ports. These rules can be used only in conjunction with -p tcp and -p udp. Up to 15 ports can be specified in a comma-separated list: --source-port [ports] Match the given source ports. --destination-port [ports] Match the given destination ports. --port [ports] Match if the packet has the same source and destination port and that port is one of the given ports. state Loaded explicitly with the -m option. This module matches the connection state of a packet: --state states Match the packet if it has one of the states in the comma-separated list states. Valid states are INVALID, ESTABLISHED, NEW, and RELATED. tcp Loaded when -p tcp is the only protocol specified: --source-port [!] [port] [:port] , --sport [!] [port] [:port] Match the specified source ports. Using the colon specifies an inclusive range of services to match. If the first port is omitted, 0 is the default. If the second port is omitted, 65535 is the default. You can also use a dash instead of a colon to specify the range. --destination-port [!] [port] [:port] , --dport [!] [port] [:port] Match the specified destination ports. The syntax is the same as for --source-port. --mss n[:n] Match if TCP SYN or SYN/ACK packets have the specified MSS value or fall within the specified range. Use this to control the maximum packet size for a connection. [!] --syn Match packets with the SYN bit set and the ACK and FIN bits cleared. These are packets that request TCP connections; blocking them prevents incoming connections. Shorthand for --tcp-flags SYN,RST,ACK SYN. --tcp-flags [!] mask comp Match the packets with the TCP flags specified by mask and comp. mask is a comma-separated list of flags that should be examined. comp is a comma-separated list of flags that must be set for the rule to match. Valid flags are SYN, ACK, FIN, RST, URG, PSH, ALL, and NONE. --tcp-option [!] n Match if TCP option is set. udp Loaded when -p udp is the only protocol specified: --source-port [!] [port] [:port] , --sport [!] [port] [:port] Match the specified source ports. The syntax is the same as for the --source-port option of the TCP extension. --destination-port [!] [port] [:port] , --dport [!] [port] [:port] Match the specified destination ports. The syntax is the same as for the --source-port option of the TCP extension.
Target extensions
Extension targets are optional additional targets supported by separate kernel modules. They have their own associated options. We cover the most frequently used target extensions below. DNAT Modify the destination address of the packet and all future packets in the current connection. DNAT is valid only as a part of the POSTROUTING chain in the nat table: --to-destination address[-address] [port-port] Specify the new destination address or range of addresses. The arguments for this option are the same as the --to-source argument for the SNAT extension target. LOG Log the packet's information in the system log: --log-level level Set the syslog level by name or number (as defined by syslog.conf). --log-prefix prefix Begin each log entry with the string prefix. The prefix string may be up to 30 characters long. --log-tcp-sequence Log the TCP sequence numbers. This is a security risk if your log is readable by users. --log-tcp-options Log options from the TCP packet header. --log-ip-options Log options from the IP packet header. MASQUERADE Masquerade the packet so it appears that it originated from the current system. Reverse packets from masqueraded connections are unmasqueraded automatically. This is a legal target only for chains in the nat table that handle incoming packets and should be used only with dynamic IP addresses (like dial-up.) For static addresses use DNAT: --to-ports port[-port] Specify the port or range of ports to use when masquerading. This option is valid only if a tcp or udp protocol has been specified with the -p option. If this option is not used, the masqueraded packet's port will not be changed. REJECT Drop the packet and, if appropriate, send an ICMP message back to the sender indicating the packet was dropped. If the packet was an ICMP error message, an unknown ICMP type, or a nonhead fragment, or if too many ICMP messages have already been sent to this address, no message is sent: --reject-with type Send specified ICMP message type. Valid values are icmp-net-unreachable, icmp-host-unreachable, icmp-port-unreachable, or icmp-proto-unreachable. If the packet was an ICMP ping packet, type may also be echo-reply. SNAT Modify the source address of the packet and all future packets in the current connection. SNAT is valid only as a part of the POSTROUTING chain in the nat table: --to-source address[-address] [port-port] Specify the new source address or range of addresses. If a tcp or udp protocol has been specified with the -p option, source ports may also be specified. If none is specified, map the new source to the same port if possible. If not, map ports below 512 to other ports below 512, those between 512 and 1024 to other ports below 1024, and ports above 1024 to other ports above 1024.
Examples
To reject all incoming ICMP traffic on eth0:
iptables -A INPUT -p ICMP -i eth0 -j REJECT
from Java Tutorials Corner http://ift.tt/2wrFelW via IFTTT
0 notes
certificacaolinux-blog · 4 years ago
Text
Comando ping e ping6 no Linux (testa conexão ICMP) [Guia Básico]
Tumblr media
O Comando ping e ping6 no Linux utiliza o protocolo ICMP para enviar mensagens ECHO REQUEST e receber ECHO RESPONSE para testar a conexão entre o sistema e outra máquina na rede. Ele retorna o tempo de resposta que um pacote de rede demora para ir e voltar. Muito útil para realizar o diagnóstico de uma conexão. O ping irá testar indefinidamente até que o Crtl-c seja pressionado. O ping também possui uma versão para o IPv6, chamada de ping6. Seu funcionamento é similar ao ping do IPv4. As opções mais frequentes são: - -c num: Esta opção faz com que o ping teste a conexão um determinado número de vezes. - -q: Esta opção faz com que o ping somente apresente a estatística final do teste de conexão. Exemplo: $ ping 192.168.1.1PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.64 bytes from 192.168.1.1: icmp_seq=1 ttl=64 time=0.175 ms64 bytes from 192.168.1.1: icmp_seq=2 ttl=64 time=0.120 ms64 bytes from 192.168.1.1: icmp_seq=3 ttl=64 time=0.115 ms— 192.168.1.1 ping statistics —5 packets transmitted, 5 received, 0% packet loss, time 4000msrtt min/avg/max/mdev = 0.115/0.128/0.175/0.026 ms O ping é muito utilizado para testar se uma máquina está conectada na rede local ou se ela é alcançável na rede remota. Para que o ping funcione corretamente, a rede em questão não deve ter nenhum filtro de ICMP, especialmente os tipos ECHO REQUEST e ECHO RESPONSE. O comando ping pode indicar os seguintes possíveis problemas de rede: Problema com a Resolução de Nomes: Se ao executar o ping em um determinado host utilizando um nome de rede (host.certificacaolinux.com.br) o ping demorar para responder, e não conseguir resolver o nome para o IP, significa que: - O servidor de DNS pode estar errado (verifique o arquivo /etc/resolv.conf); - O servidor de DNS não pode ser acessado (faça um ping com o IP do servidor de DNS); - Existe um filtro de porta UDP 53 entre o computador e o servidor de DNS (verifique o iptables); Problema de Conectividade: Se ao executar o ping, um determinado host não responder, pode significar que: - O host destino está fora do ar; - Não há rota entre a rede do computador e o host destino (verifique a tabela de rotas); - O default gateway está errado (verifique a tabela de rotas); - O Network Address Translation está com algum problema de encaminhamento ou tradução de endereços (verifique o firewall); - Existe um filtro de ICMP ECHO e ECHO-REPLY na rede; https://youtu.be/lvcgrEZ2PKk Aprenda muito mais sobre Linux em nosso curso online. Você pode efetuar a matrícula aqui. Se você já tem uma conta, ou quer criar uma, basta entrar ou criar seu usuário aqui. Gostou? Compartilhe   Read the full article
0 notes