Sign In
Sign In

iptables: Overview and Practical Use

iptables: Overview and Practical Use
Hostman Team
Technical writer
Network
05.11.2024
Reading time: 11 min

The iptables utility allows you to manage the network firewall in Linux distributions. iptables is a popular command-line utility for interacting with the built-in Linux kernel firewall called Netfilter, which has been included in the Linux kernel since version 2.4. 

In this article, we will examine how iptables works and go through practical usage examples.

Installing iptables

As mentioned, iptables is included in nearly all Linux distributions, from the most common (Ubuntu, Debian, RHEL) to distributions like openSUSE, Arch Linux, Gentoo, and others. First, let's check if iptables is already installed on your cloud server by displaying its version with the command:

iptables --version

If this command returns a version number, iptables is already installed on the system. However, if you see the message iptables: command not found, you’ll need to install it manually. Below are instructions for installing iptables using package managers across various Linux distributions. Alternatively, you can compile and install iptables from the source code.

APT

For APT-based distributions (Ubuntu/Debian/Linux Mint/Kali Linux), use the command:

apt -y install iptables

RPM

For RPM-based distributions (CentOS, Fedora, Red Hat Enterprise Linux, ALT Linux), use one of the following commands:

For the YUM package manager:

yum -y install iptables

For the DNF package manager:

dnf -y install iptables

Pacman

For Pacman-based distributions (Arch Linux, ArchLabs, Manjaro), use the command:

pacman -S iptables

All commands must be run as the root user or as a regular user with sudo privileges.

How iptables Works

iptables operates using a system of rules. These rules control incoming and outgoing traffic, organized into chains that either allow or block traffic.

A more detailed breakdown of how iptables works is as follows:

  • Network packets pass through one or more chains.
  • As a network packet moves through a chain, each rule in that chain is applied to it. During this process, the packet is checked against specified criteria. If it does not meet a criterion, a specific action is applied to it. These actions can include allowing or blocking traffic, among other operations.

Key iptables Terminology

While working with iptables, you may encounter the following terms:

  • Chain: A sequence or set of rules that determine how traffic will be handled.
  • Rules: Defined actions that contain criteria and a target or goal.
  • Module: An added feature that provides extra options for iptables, allowing for more extensive and complex traffic filtering rules.
  • Table: An abstraction in iptables that stores chains of rules. iptables includes the following tables: Security, Raw, NAT, Filter, and Mangle. Each table has a specific function, described below.

iptables Tables

Filter Table

The Filter table is the default table, using three chains: OUTPUT, FORWARD, and INPUT.

  • INPUT: Controls incoming connections. For instance, this might manage incoming SSH connections.
  • FORWARD: Manages incoming connections not directed to the local device, typically used on a router.
  • OUTPUT: Controls outgoing connections, such as navigating to a website using a browser.

NAT Table

The NAT (Network Address Translation) table includes three chains: PREROUTING, POSTROUTING, and OUTPUT.

  • PREROUTING: Determines the destination IP address of a packet.
  • POSTROUTING: Alters the source IP address.
  • OUTPUT: Changes the target address of outgoing packets.

Mangle Table

The Mangle table is used to modify packet IP headers.

Raw Table

The Raw table provides a mechanism for marking packets to bypass connection tracking.

Security Table

The Security table enables interaction with various OS security mechanisms, such as SELinux.

iptables Rules

The rules in iptables are designed to control incoming and outgoing network traffic. Rules can also be used to configure port forwarding and create protocol-specific rules.

Each rule is made up of criteria and a target. The criteria of a rule are matched, and the specified actions are applied to the target object. If a packet doesn’t match a rule’s criteria, the next rule is processed. The decisions made by iptables are called actions. Below is a list of key actions for handling connections:

  • ACCEPT: Opens (allows) the connection.
  • DROP: Closes the connection without sending a response to the client.
  • QUEUE: Sends the packet to a queue for further processing by an external application.
  • RETURN: Returns the packet to the previous rule, stopping the processing of the current rule.
  • REJECT: Blocks the connection and sends an error message in response.
  • DENY: Drops the incoming connection without sending a response.
  • ESTABLISHED: Marks an already established connection, as the session has already received at least one packet

Practical Application of iptables

Let's look at using iptables in practice. All the commands below will work on any Linux distribution. iptables commands must be run as the root user or a regular user with sudo privileges.

To display the current iptables configuration (including all existing rules), use the command:

iptables --list

85c00f9e 64b3 4cea 9647 13304c7bb8c6

For a more detailed output, which includes the number and size of processed packets in the INPUT, FORWARD, and OUTPUT chains, along with IP addresses and port numbers in numeric format, use:

iptables --line-numbers -L -v -n

Ee0b2682 A15a 4737 Ad14 F4f1ebefd20e

You can also specify a specific chain to display rules for just that chain, such as:

iptables -L INPUT
iptables -L FORWARD
iptables -L OUTPUT

Initially, iptables does not create or store any rule chains, so the output of these commands may be empty.

Blocking IP Addresses

To block a specific IP address, add a rule to the INPUT chain and specify the appropriate table. In the command below, the table is explicitly set. If the -t option is omitted, the rule is added to the default Filter table. For example, to block the IP address 10.0.36.126:

iptables -t filter -A INPUT -s 10.0.36.126 -j REJECT

This command uses the following options:

  • -t: Specifies the table for the rule.
  • -A: Adds the rule to the specified chain, in this case, the INPUT chain.
  • -s: Specifies the source IP address to which the action applies.
  • -j: Specifies the action to take; here, traffic is rejected (action REJECT).

To block an entire subnet, specify it with the -s option:

iptables -A INPUT -s 10.0.36.0/24 -j REJECT

Or, you can specify the subnet mask in full format:

iptables -A INPUT -s 10.0.36.0/255.255.255.0 -j REJECT

To block outgoing traffic to a specific IP address, use the OUTPUT chain and the -d option:

iptables -A OUTPUT -d 10.0.36.126 -j REJECT

Blocking Ports

Ports can be blocked by specifying them directly. This is done with the --dport option, which designates the port of the service. Instead of a port number, you can use the service name. You must specify the protocol as well. For example, to block SSH connections from host 10.0.36.126 using the TCP protocol:

iptables -A INPUT -p tcp --dport ssh -s 10.0.36.126 -j REJECT

For the UDP protocol, use:

iptables -A INPUT -p udp --dport ssh -s 10.0.36.126 -j REJECT

Alternatively, to block SSH connections from 10.0.36.126 using the SSH service port (22), use:

iptables -A INPUT -p tcp --dport 22 -s 10.0.36.126 -j REJECT

To block SSH connections from any IP address over TCP:

iptables -A INPUT -p tcp --dport ssh -j DROP

Allowing an IP Address

To allow traffic from a specific IP address, use the ACCEPT action. In the example below, all traffic from the IP address 10.0.36.126 is allowed:

iptables -A INPUT -s 10.0.36.126 -j ACCEPT

To allow traffic from a specific range of IP addresses, for example, from 10.0.36.126 to 10.0.36.156, use the iprange module and the --src-range option:

iptables -A INPUT -m iprange --src-range 10.0.36.126-10.0.36.156 -j ACCEPT

Here:

  • iprange: A module for working with IP address ranges.
  • --src-range: Specifies the source IP address range.

To perform the reverse operation (allowing all traffic from the server to a specific IP range from 10.0.36.126 to 10.0.36.156), use the --dst-range option:

iptables -A OUTPUT -m iprange --dst-range 10.0.36.126-10.0.36.156 -j ACCEPT
  • --dst-range: Specifies the destination IP address range.

Opening Ports

To open a port, specify the protocol using the -p option. Supported protocols include tcp, udp, etc. A full list of supported protocols can be found in /etc/protocols:

cat /etc/protocols

Specify the port using the --dport option. You can use either numeric values or service names. The ACCEPT action is used to open ports.

To open port 22 for TCP traffic from IP address 10.0.36.126:

iptables -A INPUT -p tcp --dport 22 -s 10.0.36.126 -j ACCEPT

To open multiple ports at once, use the multiport module and the --dports option, listing the ports separated by commas. For example, to open ports 22, 80, and 443 over TCP from IP address 10.0.36.126:

iptables -A INPUT -p tcp -m multiport --dports 22,80,443 -s 10.0.36.126 -j ACCEPT
  • multiport: A module for managing multiple ports simultaneously.
  • --dports: Specifies multiple ports, unlike --dport, which supports only a single port.

Blocking ICMP Traffic

One commonly used feature in iptables is blocking ICMP traffic, often generated by the ping utility. To block incoming ICMP traffic, use the following command:

iptables -A INPUT -j DROP -p icmp --icmp-type echo-request

Image7

This command will prevent the ping command from receiving a response without displaying an error message. If you want to display an error message like "Destination Port Unreachable," replace the DROP action with REJECT:

iptables -A INPUT -j REJECT -p icmp --icmp-type echo-request

123

Allowing ICMP Traffic

To allow previously blocked ICMP traffic, run the following command:

iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

However, it’s important to note that if ICMP traffic was previously blocked with this command:

iptables -A INPUT -j DROP -p icmp --icmp-type echo-request

and then allowed with:

iptables -A INPUT -p icmp --icmp-type echo-request -j ACCEPT

the ICMP traffic will still be blocked, as the drop rule will be the first rule in the INPUT chain.

Blocking Traffic by MAC Address

In addition to IP addresses, traffic can be blocked based on the device’s MAC address. Below is an example to block traffic from a device with the MAC address 00:0c:29:ed:a9:60:

iptables -A INPUT -m mac --mac-source 00:0c:29:ed:a9:60 -j DROP
  • mac: A module for working with device MAC addresses.
  • mac-source: Specifies the MAC address of the device.

Allowing Traffic by MAC Address

To allow traffic from a specific MAC address, use this command:

iptables -A INPUT -m mac --mac-source 00:0c:29:ed:a9:60 -j ACCEPT

Blocking traffic by MAC address with iptables will only work if the devices are on the same network segment. For broader use cases, blocking traffic by IP address is generally more effective.

Allowing Traffic on the Loopback Interface

Traffic on the loopback interface can also be controlled. To allow incoming traffic on the loopback interface, use:

iptables -A INPUT -i lo -j ACCEPT

For outgoing traffic on the loopback interface, the command is:

iptables -A OUTPUT -o lo -j ACCEPT

Restricting Network Access by Schedule

One of the useful features of iptables is the ability to temporarily allow or restrict traffic to specific services or ports based on a schedule. For example, let’s say we want to allow incoming SSH access only on weekdays, Monday through Friday, from 9 AM to 6 PM. The command would look like this:

iptables -A INPUT -p tcp --dport 22 -m time --timestart 09:00 --timestop 18:00 --weekdays Mon,Tue,Wed,Thu,Fri -j ACCEPT
  • time: Module for working with time-based rules.
  • timestart: Specifies the start time for the rule.
  • timestop: Specifies the end time for the rule.
  • weekdays: Specifies the days of the week when the rule will be active, separated by commas. Supported values are: Mon, Tue, Wed, Thu, Fri, Sat, Sun, or numbers 1 to 7.

Saving iptables Rules

By default, user-created iptables rules are not saved automatically. This means that the rules are cleared after a server reboot or shutdown. To save the rules, install the iptables-persistent package with the following command:

apt -y install iptables-persistent

During the installation, two dialog boxes will appear, allowing you to save the current rules to /etc/iptables/rules.v4 for IPv4 and /etc/iptables/rules.v6 for IPv6.

To manually save all rules for the IPv4 protocol, use:

iptables-save > /etc/iptables/rules.v4

For IPv6 rules, use:

ip6tables-save > /etc/iptables/rules.v6

This method has a significant advantage: saved rules can be restored from the file, which is helpful, for example, when transferring rules to another host. To restore previously saved rules, run:

iptables-restore < /etc/iptables/rules.v4

If executing this command on a different host, transfer the rule file first and then execute the restore command.

Deleting Rules in iptables

You can delete rules in iptables using several methods.

Deleting a Specific Rule

One way to delete a rule is to target a specific rule in a chain using its line number. To display the rule numbers, use:

iptables -L --line-numbers

Image10

For example, in the INPUT chain, we might see two rules that open ports 80 and 443 over TCP for IP addresses 10.0.36.126 (rule number 1) and 10.0.36.127 (rule number 2). To delete rule number 2, use:

iptables -D INPUT 2

Then, display the list of all current rules to verify:

iptables -L --line-numbers

Rule number 2 should now be removed successfully.

Image1

Deleting All Rules in a Specific Chain

You can also delete all rules in a specific chain at once. For example, to clear all rules in the OUTPUT chain:

iptables -F OUTPUT

Deleting All Rules

To delete all rules across all chains, simply run:

iptables -F

Use caution with this command, as it will remove all existing rules, including potentially essential ones.

Conclusion

In summary, iptables is a powerful tool for managing the built-in firewall in Linux-based operating systems. Its extensive features and modular support allow flexible configuration for controlling network traffic.

For more detailed information on iptables, consult the official documentation or use the man iptables command in Linux-based systems.

Network
05.11.2024
Reading time: 11 min

Similar

Linux

Port Forwarding in Linux with Iptables

Have you ever hosted a server (game or web) on your home computer and shared your IP address with friends, but no one could connect? The issue lies in your router, which hides connected devices behind its own IP address. Everything within the router is a local network, while everything outside is a global network. However, there is no direct mediator between them, only a barrier preventing external connections. The solution is port forwarding, a technology that directs external requests to an internal device and vice versa. In Linux operating systems, the iptables utility is used for this purpose, which will be the focus of this article. The commands shown in this guide were executed on a Hostman cloud server running Ubuntu 22.04. What Is Port Forwarding? Port forwarding (also known as port mapping) redirects network traffic from one port to another, either through a router (hardware-level) or a firewall (software-level). With port forwarding, devices within a local network become accessible from the global network. Without it, external requests cannot reach internal devices. Common scenarios where port forwarding is needed: Connecting to a home server (game server, surveillance cameras, data storage). Hosting game servers or websites on a home PC. Accessing a remote desktop. Remote device management. For example, if a server in a local network operates on port 8080, port forwarding allows it to be accessed from the global network through port 80. Example Setup: A computer with IP 192.168.1.100 (internal/gray IP) runs a web server listening on port 8080. The computer is within a Wi-Fi router’s local network, which has an external IP 203.0.113.10 (public/white IP), listening on port 80. All global network requests to port 80 on the router are forwarded to port 8080 on the internal computer. This setup allows us to redirect incoming traffic from the global network to the local network. How Does Port Forwarding Work in Linux? Linux has built-in tools for handling incoming and outgoing traffic. These tools act as a packet filtering and modification pipeline. Port forwarding in Linux is based on NAT (Network Address Translation), configured using the iptables system utility. What Is NAT? NAT (Network Address Translation) is a technique that converts external requests from the global network into internal requests within the local network (and vice versa). Technically, NAT modifies IP addresses and ports in data packets. It is not a standalone utility but a concept or approach. There are two main types of NAT: SNAT (Source NAT) – Modifies the source IP address in outgoing packets. DNAT (Destination NAT) – Modifies the destination IP address in incoming packets. While NAT protects the local network from external access, it requires port forwarding for incoming connections. What Is Iptables and How Does It Work? Iptables is a Linux utility used to configure NAT (and more) by modifying tables with rule chains that control traffic. Iptables has five main rule chains: INPUT – Handles incoming packets. FORWARD – Handles forwarded packets. OUTPUT – Handles outgoing packets. PREROUTING – Handles packets before routing. POSTROUTING – Handles packets after routing. Iptables has five tables, each using specific rule chains: filter – Allows or blocks packets (INPUT, FORWARD, OUTPUT). nat – Modifies IP addresses and ports (OUTPUT, PREROUTING, POSTROUTING). mangle – Alters packet headers (INPUT, FORWARD, OUTPUT, PREROUTING, POSTROUTING). raw – Controls connection filtering (OUTPUT, PREROUTING). security – Applies additional security policies (INPUT, FORWARD, OUTPUT). The rule chains act as hooks in the packet processing pipeline, allowing iptables to implement port forwarding in Linux. How Port Forwarding Works in Iptables Port forwarding in iptables follows a standard packet processing flow based on three possible directions: Incoming (INPUT) – Packets sent to the local system. Outgoing (OUTPUT) – Packets sent from the local system. Forwarded (FORWARD) – Packets routed through the system. Incoming Packets (INPUT) Processing Order raw (PREROUTING) – Connection filtering. mangle (PREROUTING) – Packet modification. nat (PREROUTING) – Changes the destination address. If the packet is for this system, continue to INPUT processing. Otherwise, forward it. mangle (INPUT) – Final packet modification. filter (INPUT) – Packet filtering. security (INPUT) – Security policy enforcement. Outgoing Packets (OUTPUT) Processing Order raw (OUTPUT) – Connection filtering. mangle (OUTPUT) – Packet modification. nat (OUTPUT) – Changes the destination address. filter (OUTPUT) – Final packet filtering. security (OUTPUT) – Security policy enforcement. mangle (POSTROUTING) – Final packet modification. nat (POSTROUTING) – Changes the source address. Forwarded Packets (FORWARD) Processing Order raw (PREROUTING) – Connection filtering. mangle (PREROUTING) – Packet modification. nat (PREROUTING) – Changes the destination address. Forwarding decision is made. mangle (FORWARD) – Packet modification. filter (FORWARD) – Packet filtering. security (FORWARD) – Security policy enforcement. mangle (POSTROUTING) – Final packet modification. nat (POSTROUTING) – Changes the source address. General Processing Order of Tables: raw mangle nat filter security Types of Port Forwarding Common types of port forwarding include: Local Forwarding – Redirects traffic within the same machine. Example: An application on a local server sends a request to a specific port. Interface Forwarding – Redirects traffic between different network interfaces. Example: A packet from the global network arrives on one interface and is forwarded to another. Remote Host Forwarding – Redirects traffic from a remote server to a local host. Example: A request from a remote server is forwarded to a local machine. Each type of port forwarding is implemented using a specific set of rules in the iptables tables. Using the Iptables Command In most Linux distributions, the iptables utility is already installed. You can check this by querying its version: iptables --version If iptables is not installed, you need to install it manually. First, update the package list: sudo apt update Then, install it: sudo apt install iptables -y By default, Linux uses the ufw firewall, which automatically configures iptables. To avoid conflicts, you must stop the ufw service first: sudo systemctl stop ufw Then, disable it: sudo systemctl disable ufw Iptables Command Structure The basic syntax of the iptables command is as follows: iptables [TABLE] [COMMAND] [CHAIN] [NUMBER] [CONDITION] [ACTION] In each specific command, only some of these parameters are used: TABLE: The name of one of the five tables where the rule is added. COMMAND: The operation to perform on a specific rule or chain. CHAIN: The name of the chain where the operation is performed. NUMBER: The rule number to manipulate. CONDITION: The condition under which the rule applies. ACTION: The transformation to be applied to the packet. Selecting a Table The -t flag specifies the table to operate within: For filter: iptables -t filter For nat: iptables -t nat For mangle: iptables -t mangle For raw: iptables -t raw For security: iptables -t security If the -t flag is not specified, the default table is filter. The security table is rarely used. Manipulating Rules We can perform different operations on rules within each chain: Add a rule to the end of a chain (-A): iptables -A INPUT -s 192.168.123.132 -j DROP This rule blocks incoming connections from the specified IP address. Delete a rule by its number (-D): iptables -D OUTPUT 7 Insert a rule at a specific position (-I): iptables -I INPUT 5 -s 192.168.123.132 -j DROP Replace a rule (-R): iptables -R INPUT 5 -s 192.168.123.132 -j ACCEPT This replaces a previously added blocking rule with an allow rule. Flush all rules in a chain (-F): iptables -F INPUT Manipulating Chains We can also perform operations on entire chains: Create a new chain (-N): iptables -N SOMENAME Delete a chain (-X): iptables -X SOMENAME Rename a chain (-E): iptables -E SOMENAME NEWNAME Set default policy for a chain (-P): iptables -P INPUT DROP This blocks all incoming connections to the server. Reset statistics for a chain (-Z): iptables -Z INPUT Setting Conditions Each rule can have conditions for its execution: Specify the protocol (-p): iptables -A INPUT -p tcp -j ACCEPT This allows incoming connections using the TCP protocol. Specify the source address (-s): iptables -A INPUT -s 192.168.123.132 -j DROP Specify the destination address (-d): iptables -A OUTPUT -d 192.168.123.132 -j DROP Specify network interface for incoming traffic (-i): iptables -A INPUT -i eth2 -j DROP Specify network interface for outgoing traffic (-o): iptables -A OUTPUT -o eth3 -j ACCEPT Specify the destination port (--dport): iptables -A INPUT -p tcp --dport 80 -j ACCEPT Specify the source port (--sport): iptables -A INPUT -p tcp --sport 1023 -j DROP Negate a condition (!): iptables -A INPUT ! -s 192.168.123.132 -j DROP This blocks all incoming connections except from the specified IP address. Specifying Actions Each table supports different actions: For the filter table: ACCEPT – Allow the packet. DROP – Block the packet. REJECT – Block the packet and send a response. LOG – Log packet information. RETURN – Stop processing in the current chain. For the nat table: DNAT – Change the packet’s destination address. SNAT – Change the packet’s source address. MASQUERADE – Change the source address dynamically. REDIRECT – Redirect traffic to the local machine. Port Forwarding with Iptables Local Port Forwarding To redirect local traffic from one port to another: sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j REDIRECT --to-port 80 To remove the rule: sudo iptables -t nat -D PREROUTING -p tcp --dport 8080 -j REDIRECT --to-port 80 Forwarding Between Interfaces To forward port 8080 from interface eth0 to port 80 on eth1: sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8080 -j DNAT --to-destination 10.0.0.100:80 Then, allow packet forwarding: sudo iptables -A FORWARD -p tcp -d 10.0.0.100 --dport 80 -j ACCEPT Forwarding to a Remote Host To forward incoming packets to a remote server: Enable packet forwarding in the system settings: echo 1 > /proc/sys/net/ipv4/ip_forward Add a port forwarding rule: sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.100:80 Allow forwarded packets to be sent out: sudo iptables -t nat -A POSTROUTING -p tcp -d 192.168.1.100 --dport 80 -j MASQUERADE Alternatives to iptables for Port Forwarding It should be noted that iptables is not the only tool for traffic management. There are several popular alternatives. nftables nftables is a more modern tool for managing traffic in Linux. Unlike iptables, it does not have predefined tables, and its syntax is more straightforward and concise. Additionally, this utility uses a single command, nft, to manage all types of traffic: IPv4, IPv6, ARP, and Ethernet. In contrast, iptables requires additional commands such as ip6tables, arptables, and ebtables for these tasks. firewalld firewalld is a more complex traffic management tool in Linux, built around the concept of zones and services. This allows network resources to be assigned different levels of security. The configuration of firewalld is broader and more flexible. For example, instead of manually defining rules for each port, we can specify specific services. Additionally, firewalld provides a more interactive command-line interface, allowing real-time traffic management. Conclusion While there are alternatives, iptables remains the primary tool for traffic control in Linux. It provides a structured way to filter, modify, and forward packets, making it a powerful solution for managing network traffic.
09 April 2025 · 10 min to read
Network

Introduction to OAuth 2

The OAuth 2 is an authorization protocol designed to restrict access to personal accounts created on HTTP resources. Typical implementations include DigitalOcean, GitHub, and Facebook. OAuth 2 works by delegating the authentication process to the server where the account is located. This approach allows third-party applications to request access to user data, such as for registration using pre-filled credentials. OAuth 2 can be used in cloud services, desktop computers, and mobile applications for smartphones and tablets. In this guide, we will explore how OAuth works and discuss the main practical applications of this tool. OAuth Roles OAuth 2 defines four main roles: the resource owner, the client, the resource server, and the authorization server. Let’s go through each role in detail. Resource Owner The resource owner is the user who is authenticated using their credentials to access their personal account. The accessible area may have restricted permissions—either read-only or with write and modification capabilities. Server (Resource Server and Authorization Server) The resource server stores user account data in a protected form. The authorization server verifies the authenticity of entered login credentials and generates authorization tokens for applications. These tokens allow applications to access user data. Both servers are logically combined into a unified system, which is perceived by external services through the API interface. Thus, we will refer to the resource and authorization servers collectively as the Service or API. Client (Application) The client refers to the application requesting access to the user’s account. Before activation, two conditions must be met: authentication within the application and a positive response from the API. Protocol Overview Having reviewed the OAuth 2 roles, let's look at the authorization protocol and the information exchange process. Below is a sequence of typical operations: The application prompts the user to enter authentication credentials. If the login and password are correct, an authorization grant is issued. The application sends a request to the API, including the authorization grant. If the application is authenticated, the server generates an access token for the specific instance, completing the authorization process. The application requests resources using the API. The resource server validates the token and provides data only upon confirmation. The sequence may vary depending on the developer and the software’s purpose, but the general scheme remains consistent. Registering an Application Before using OAuth, an application must be registered with the service. This is typically done under the Developer or API section on the website. The following details are required: Application name Website where the application is hosted Callback URL (Redirect URL) The Callback URL is a link to the page that the service will open in case of access denial or after successful authorization. Client Identification Upon registering the application, user credentials are created—these include the Client ID and Client Secret: Client ID is a public string used by the API to verify the application's legitimacy and generate URLs for authorized users. Client Secret is used for authentication within the API and is only visible to the API and the application. Authorization Grants OAuth 2 provides four types of authorization grants depending on the situation: Authorization Code – Used for server-side applications. Implicit Grant – Suitable for mobile applications, including web versions. Resource Owner Password Credentials – Used for trusted applications, such as those integrated with an online service. Client Credentials – Used for API-based operations. Now, let's examine each type in more detail. Authorization Code Grant This is the most common authorization method, as it is secure and suitable for applications where the source code and client secret are stored on a protected server. Step 1: Create an Authorization Link The application presents the user with the following link: https://cloud.example.com/v1/oauth/authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=CALLBACK_URL&scope=read Components: authorize endpoint: Used for OAuth authentication via API. client_id: Identifies the requesting application. redirect_uri: Redirects the user after authorization. response_type=code: Requests an authorization code. scope=read: Specifies read-only access. Step 2: User Authentication When the user clicks the link, they are prompted to log in. Upon successful authentication, the application is either authorized or denied access. Step 3: Authorization Code is Sent to the Application If authorization is granted, the system redirects the browser to: https://example.com/callback?code=AUTHORIZATION_CODE Step 4: Request an Access Token The application sends the authorization code to the server along with authentication details: https://cloud.example.com/v1/oauth/token?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&grant_type=authorization_code&code=AUTHORIZATION_CODE&redirect_uri=CALLBACK_URL Step 5: Server Returns an Access Token If authentication is successful, the API returns an access token: { "access_token":"ACCESS_TOKEN", "token_type":"bearer", "expires_in":2592000, "refresh_token":"REFRESH_TOKEN", "scope":"read", "uid":100101, "info":{ "name":"User", "email":"info@example.com" } } The application is now connected to the server. Implicit Grant This method is used in mobile applications and web browsers. Unlike the Authorization Code Grant, it does not ensure the confidentiality of the client secret. Step 1: Generate an Authorization Link The authorization service provides a link: https://cloud.example.com/v1/oauth/authorize?response_type=token&client_id=CLIENT_ID&redirect_uri=CALLBACK_URL&scope=read Step 2: Authenticate the User Upon successful authentication, the server returns an access token directly to the browser: https://example.com/callback#token=ACCESS_TOKEN Step 3: Extract and Use the Token The application extracts the token from the URL and uses it for API requests. Resource Owner Password Credentials Grant This method involves the user entering credentials directly into the service. It is used when other methods are not viable, such as system-integrated applications. https://oauth.example.com/token?grant_type=password&username=USERNAME&password=PASSWORD&client_id=CLIENT_ID Upon successful authentication, the server returns an access token. Client Credentials Grant This method allows access to the service’s own resources: https://oauth.example.com/token?grant_type=client_credentials&client_id=CLIENT_ID&client_secret=CLIENT_SECRET If authentication is successful, an access token is returned. Refreshing an Access Token To refresh an access token before it expires: https://cloud.example.com/v1/oauth/token?grant_type=refresh_token&client_id=CLIENT_ID&client_secret=CLIENT_SECRET&refresh_token=REFRESH_TOKEN Conclusion We have explored the different ways to use OAuth in applications, depending on their requirements. Now, users understand how access to remote services is managed and what factors to consider when choosing an authorization method.
04 April 2025 · 6 min to read
Linux

How to Open Ports and List Open Ports in Linux

When working with networks in Linux, you may need to open or close a network port. Port management is essential for security — the fewer open ports in a system, the fewer potential attack vectors it has. Furthermore, if a port is closed, an attacker cannot gather information about the service running on that specific port. This guide will explain how to open or close ports as well as how to check open ports in Linux distributions such as Ubuntu/Debian and CentOS/RHEL using firewalls like ufw, firewalld, and iptables. It will also  We will demonstrate this process on two Linux distributions: Ubuntu 22.04 and CentOS 9, run on Hostman VPS. All commands provided here will work on any Debian-based or RHEL-based distributions. What is a Network Port? Ports are used to access specific applications and protocols. For example, a server can host both a web server and a database—ports direct traffic to the appropriate service. Technically, a network port is a non-negative integer ranging from 0 to 65535. Reserved Ports (0-1023): Used by popular protocols and network services like SSH (port 22), FTP (port 21), HTTP (port 80), and HTTPS (port 443). Registered Ports (1024-49151): These ports can be used by specific applications for communication. Dynamic Ports (49151-65535): These are used for temporary connections and can be dynamically assigned to applications. How to Open Ports in Debian-Based Linux Distributions On Debian-based systems (Ubuntu, Debian, Linux Mint, etc.), you can use ufw (Uncomplicated Firewall). ufw comes pre-installed on most popular APT-based distributions. To check if ufw is installed, run: ufw version If the version is displayed, ufw is installed. Otherwise, install it with: apt update && apt -y install ufw By default, ufw is inactive, meaning all ports are open. You can check its status with: ufw status To activate it, use: ufw enable You will need to confirm by entering y. Note that enabling ufw may interrupt current SSH connections. By default, ufw blocks all incoming traffic and allows all outgoing traffic. To check the default policy, use: cat /etc/default/ufw Opening Ports in ufw To open a port, use the command: ufw allow <port_number> For example, to open port 22 for SSH, run: ufw allow 22 You can list multiple port numbers separated by commas, followed by the protocol (tcp or udp): ufw allow 80,443,8081,8443/tcpufw allow 80,443,8081,8443/udp Instead of specifying port numbers, you can use the service name as defined in /etc/services. For example, to open the Telnet service, which uses port 23 by default: ufw allow telnet Note: You cannot specify multiple service names at once; ufw will return an error: To open a port range, use the following syntax: ufw allow <start_port>:<end_port>/<protocol> Example: ufw allow 8000:8080/tcp Closing Ports in ufw To close a port using ufw, use the command: ufw deny <port_number> For example, to close port 80, run: ufw deny 80 You can also use the service name instead of the port number. For example, to close port 21 used by the FTP protocol: ufw deny ftp Checking Open Ports in ufw To list all open and closed ports in the Linux system, use: ufw status Another option to view open ports in Linux is: ufw status verbose How to Open a Port in RHEL-Based Linux Distributions Linux RHEL-based distributions (CentOS 7+, RHEL 7+, Fedora 18+, OpenSUSE 15+) use firewalld by default. Opening Ports in firewalld To check if firewalld is installed, run: firewall-offline-cmd -V If the version is displayed, firewalld is installed. Otherwise, install it manually: dnf install firewalld By default, firewalld is disabled. Check its status with: firewall-cmd --state To enable firewalld, run: systemctl start firewalld To open port 8080 for the TCP protocol, use: firewall-cmd --zone=public --add-port=8080/tcp --permanent --zone=public: Specifies the zone for the rule. --add-port=8080/tcp: Specifies the port and protocol (TCP or UDP). --permanent: Saves the rule to persist after a system reboot. Without this parameter, the change will only last until the next reboot. Alternatively, you can open a port in Linux by specifying a service name instead of a port number. For example, to open the HTTP (port 80) protocol: firewall-cmd --zone=public --add-service=http --permanent Reload firewalld to apply the changes: firewall-cmd --reload Closing Ports in firewalld You can close a port using either its number or service name. To close a port using its number, run: firewall-cmd --zone=public --remove-port=8080/tcp --permanent To close a port using the service name, run: firewall-cmd --zone=public --remove-service=http --permanent After opening or closing a port, always reload firewalld to apply the changes: firewall-cmd --reload Listing Open Ports in firewalld To list all open ports in your Linux system, you can use: firewall-cmd --list-ports Managing Ports in iptables Unlike ufw and firewalld, iptables comes pre-installed in many Linux distributions, including Ubuntu, Debian, RHEL, Rocky Linux, and AlmaLinux. Opening Ports in iptables To open port 8182 for incoming connections, use: iptables -A INPUT -p tcp --dport 8182 -j ACCEPT -A INPUT: The -A flag is used to add one or more rules. INPUT specifies the chain to which the rule will be added (in this case, incoming connections). -p tcp: Specifies the protocol. Supported values include tcp, udp, udplite, icmp, esp, ah, and sctp. --dport 8182: Specifies the port to be opened or closed. -j ACCEPT: Defines the action for the port. ACCEPT allows traffic through the port. To open a port for outgoing connections, use the OUTPUT chain instead: iptables -A OUTPUT -p tcp --dport 8182 -j ACCEPT To open a range of ports, use the --match multiport option: iptables -A INPUT -p tcp --match multiport --dports 1024:2000 -j ACCEPT Closing Ports in iptables To close a port, use the -D option and set the action to DROP. For example, to close port 8182 for incoming connections: iptables -A INPUT -p tcp --dport 8182 -j DROP To close a range of ports, use the same syntax as for opening a range, but replace ACCEPT with DROP: iptables -A INPUT -p tcp --match multiport --dports 1024:2000 -j DROP Saving iptables Rules By default, iptables rules are only effective until you restart the server. To save the rules permanently, install the iptables-persistent utility. For APT-based distributions: apt update && apt -y install iptables-persistent For DNF-based distributions: dnf -y install iptables-persistent To save the current rules, run: iptables-save After the next server reboot, the rules will be automatically reloaded. Viewing Open Ports in iptables To list all current rules and opened ports on the Linux machine, use: iptables -L -v -n To list rules specifically for IPv4, use: iptables -S To list rules for IPv6, use: ip6tables -S Conclusion In this guide, we demonstrated how to open and close network ports in Linux and check currently open ports using three different utilities: ufw, firewalld, and iptables. Proper port management reduces the risk of potential network attacks and helps obscure information about the services using those ports.
14 February 2025 · 6 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support