More

    Linux Tutorials: How To Open Or Close Ports

    Linux system administrators and personal Linux PC users need to open or close ports on their machines for various reasons. If you are a Linux PC user, you may want to close all ports to prevent inbound connections. A Linux system administrator will need to open specific ports to allow SSH connections so they can remotely connect to servers or to allow server apps to listen for inbound connections.

    Linux comes with the Uncomplicated Firewall (UFW) tool preinstalled so that you can quickly open or close ports on your Linux machine. UFW is the tool we will use in this tutorial. Before proceeding, you will need to check if UFW is already installed using the following command. Also enable UFW. There is a GUI utility that can do all this called ‘GUFW’. However, if you are using a server without a GUI then you’ll need the commands below.

    ufw version
    ufw enable
    

    If you get a ‘command not found’ error then install it with Aptitude: sudo apt install ufw.

    How To Open A Port With UFW

    To open a port with Uncomplicated Firewall, use the ‘ufw allow’ command followed by the port you want to open as shown below. You may need to type ‘sudo’ before the following commands, as this requires administrator privileges.

    ufw allow 13000

    How To Close A Port With UFW

    You can close a port with the firewall by using the ‘ufw deny’ command as shown in the example below.

    ufw deny 40

    Example Use Case Of UFW: Blocking Common SSH Ports To Deter Attacks

    Port 22 is the default SSH port for Linux servers and is therefore one of the first ports that hackers will try to connect to. In this example, we will change the SSH port from 22 to 13000. Run the follow command to open the SSH configuration file in the Nano text editor.

    nano /etc/ssh/sshd_config

    Search for ‘Port 22‘ in that file and comment it out by typing a hashtag ‘#’ before it. Add this new line below it: ‘Port 13000‘.

    Now restart the SSH server.

    systemctl restart ssh.service

    The next step is to configure UFW to allow connections to your new SSH port (see the example above allowing connections to port 13000). Afterwards, block connections to port 22:

    ufw deny 22

    Finally, apply the changes with the following two commands:

    ufw disable
    ufw enable

    How To Change Ownership Of A File In Linux

    RedHat Linux Cheat Sheet: Common RedHat Commands

    Linux Mint Commands: A Cheatsheet For Linux Mint With Examples

    Comments

    Leave a Reply

    Share article

    Newsletter

    Subscribe to stay updated.