Sign In
Sign In

How to Add a New Sudo User in Ubuntu

How to Add a New Sudo User in Ubuntu
Hostman Team
Technical writer
Ubuntu
12.02.2025
Reading time: 10 min

The acronym sudo stands for "substitute user and do." The sudo program allows regular users in the system to perform tasks that would typically require the superuser (root), who has full privileges and access rights.

This approach enables system management under a user with limited privileges, reducing the risk of errors or unauthorized access to critical system functions.

Thus, you can create a separate user with access to the sudo utility but without access to many system functions, the misuse of which could harm the system.

The key difference between sudo and su (substitute user) is that sudo switches users temporarily, without asking for the user's password.

In this guide, we'll go over how to create a new user in Ubuntu 22.04 and add them to the sudo group, thus providing extended privileges for system management.

Creating a New User for Sudo

Before creating a new user with special privileges, you need to log into the system as the superuser.

If you're using a server running Ubuntu, connect to it via SSH as the root user:

ssh root@IP_ADDRESS

For example, the connection command might look like this:

ssh [email protected]

After that, the terminal will prompt you to enter the root password.  For security reasons, the terminal won't display the password characters as you type them.

Next, create a new user by assigning them a chosen name:

adduser hostman

The terminal will show a few messages indicating the creation of the new user, a new group to which they are automatically added, and a directory associated with the user:

Adding user `hostman' ...
Adding new group `hostman' (1001) ...
Adding new user `hostman' (1000) with group `hostman' ...
Creating home directory `/home/hostman' ...
Copying files from `/etc/skel' ...

Next, the terminal will ask you to set a password for the new user and provide additional information about them:

Changing the user information for hostman
Enter the new value, or press ENTER for the default
    Full Name []:
    Room Number []:
    Work Phone []:
    Home Phone []:
    Other []:
Is the information correct? [Y/n]

After filling out the information, press y to confirm. You have created a new user.

Adding a User to the Sudo Group

Now, you need to add the new user to the special sudo group, which will grant them extended privileges:

usermod -aG sudo hostman

The -a flag is necessary to ensure that the specified group does not replace other groups the user is already a part of. In this case, the user hostman is at least part of the previously created hostman group.

The -G flag is used to specify additional groups we want to add the user to. It is different from the -g flag, which sets the user's primary group. In this case, the primary group for the user hostman is the hostman group.

Now, you can switch to the new user:

su - hostman

Immediately after switching, the terminal will display a message stating that commands can now be executed as the administrator (root) using sudo:

To run a command as administrator (user "root"), use "sudo <command>".
See "man sudo_root" for details.

By the way, you can always check which user is currently executing commands:

whoami

The terminal will display the active user's name:

hostman

Running Commands with Sudo

Sudo As root

To test the new user's privileges, try listing the contents of the system directory /root:

sudo ls -la /root

The -la flag is a combination of two flags:

  • -l specifies a detailed (long) format for listing the contents of the filesystem.

  • -a includes directories whose names start with a dot.

Thus, the ls command will show all the contents of the /root directory in detail.

When running this command for the first time, the terminal will ask for the password set for the user hostman:

[sudo] password for hostman:

After entering the password, you will see the contents of the /root directory:

total 48
drwx------  7 root root 4096 Nov 20 05:30 .
drwxr-xr-x 20 root root 4096 Nov 20 12:09 ..
drwx------  3 root root 4096 Nov 11 12:17 .ansible
-rw-r--r--  1 root root 4078 Nov 20 10:12 .bash_history
-rw-r--r--  1 root root 3106 Oct 15  2021 .bashrc
drwx------  2 root root 4096 Nov 11 12:17 .cache
drwxr-xr-x  3 root root 4096 Nov 19 05:36 .local
-rw-------  1 root root  214 Nov 18 04:26 .mysql_history
-rw-r--r--  1 root root  161 Jul  9  2019 .profile
-rw-r--r--  1 root root 1372 Nov 18 04:16 resize.log
drwx------  3 root root 4096 Nov 11 12:17 snap
drwx------  2 root root 4096 Nov 18 04:16 .ssh

Note that using sudo does not require wrapping the command in quotes or anything else. The target command is written naturally right after sudo.

If you enter the above command without using sudo:

ls -la /root

You will see an access denied message:

ls: cannot open directory '/root': Permission denied

Another basic command that is run with sudo is updating the list of available repositories:

sudo apt update

Similarly, if you try to update repositories without sudo, you'll get an access restriction message:

Reading package lists... Done
E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)
E: Unable to lock directory /var/lib/apt/lists/
W: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied)
W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied)

Thus, any attempt to use a command requiring administrator privileges will result in an access denied message in the terminal.

Sudo As Another User

With sudo, you can execute commands not only as root but also as any other user.

First, let's switch back to the root user:

su - root

The terminal will prompt for the root user's password.

Now, let's try executing a command that requires administrative privileges as the user hostman, using the -u flag:

sudo -u hostman ls -la /root

The terminal will display the familiar access denied message:

ls: cannot open directory '/root': Permission denied

Next, let's switch back to the hostman user:

su - hostman

For clarity, we can perform the same action under the hostman user:

sudo -u root ls -la /root

First, the terminal asks for the hostman user's password and then displays the contents of the specified directory:

total 52
drwx------  7 root root 4096 Nov 20 15:39 .
drwxr-xr-x 20 root root 4096 Nov 20 12:09 ..
drwx------  3 root root 4096 Nov 11 12:17 .ansible
-rw-r--r--  1 root root 4171 Nov 20 15:21 .bash_history
-rw-r--r--  1 root root 3106 Oct 15  2021 .bashrc
drwx------  2 root root 4096 Nov 11 12:17 .cache
drwxr-xr-x  3 root root 4096 Nov 19 05:36 .local
-rw-------  1 root root  214 Nov 18 04:26 .mysql_history
-rw-r--r--  1 root root  161 Jul  9  2019 .profile
-rw-r--r--  1 root root 1372 Nov 18 04:16 resize.log
drwx------  3 root root 4096 Nov 11 12:17 snap
drwx------  2 root root 4096 Nov 18 04:16 .ssh
-rw-r--r--  1 root root    0 Nov 20 15:39 .sudo_as_admin_successful

Configuring Sudo Access Permissions

You can restrict the permissions of a particular user in the sudo group to only executing specific allowed commands.

To check this, let's first switch back to the root user:

su - root

Setting Access Permissions

To configure unique access permissions for each sudo user, we need to open the /etc/sudoers file:

sudo nano /etc/sudoers

Then, we can add the description of allowed commands using the following format:

USER HOST=(AVATAR:GROUP) COMMANDS

Where:

  • USER: The user that will initiate the sudo command.
  • HOST: The hostname where the sudo command will be executed. This is relevant when using multiple machines.
  • AVATAR: The user under whose name the allowed commands will be executed via sudo.
  • GROUP: The group the user belongs to.
  • COMMANDS: The set of commands (which may consist of just one command) that the user can execute via sudo.

In the simplest case, you can allow to execute all commands under any user:

hostman ALL=(ALL:ALL) ALL

In a more complex case, only specific commands can be allowed from a limited set of users:

hostman ALL=(root:ALL) /usr/bin/apt,/usr/bin/rm,/bin/nano

Note that command sets are listed comma-separated without spaces.

To find the full paths to the binaries of necessary commands, you can use the whereis utility:

whereis apt rm nano

The terminal will display information about the specified commands:

apt: /usr/bin/apt /usr/lib/apt /etc/apt /usr/share/man/man8/apt.8.gz
rm: /usr/bin/rm /usr/share/man/man1/rm.1.gz
nano: /usr/bin/nano /usr/share/nano /usr/share/man/man1/nano.1.gz /usr/share/info/nano.info.gz

The first path listed after the command name is the actual address of the binary file.

To activate the specified restrictions, you need to replace the line that allows sudo group users to execute any root commands:

%sudo ALL=(ALL:ALL) ALL

With a similar one but with a comment symbol at the beginning, to disable the setting:

#%sudo ALL=(ALL:ALL) ALL

Now you can switch back to the hostman user:

su - hostman

And let's try running the familiar command to list the contents of the /root directory:

sudo ls -la /root

The terminal will display a message indicating that the specified command is prohibited on this host:

Sorry, user hostman is not allowed to execute '/usr/bin/ls /root' as root on <hostname>.

However, the command to update repositories will still work:

sudo apt update

Checking Access Rights

Of course, you can find out the details of a user's privileges by simply viewing the contents of the /etc/sudoers file. However, there's an easier way, by using the sudo command itself:

sudo -l -U hostman
  • The -l flag lists all commands the user is allowed to use.

  • The -U flag specifies the target username. If omitted, the terminal will display access rights for the root user.

In the terminal, you will see a message detailing the access rights for the specified user:

Matching Defaults entries for hostman on <hostname>:
    env_reset, mail_badpass, secure_path=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin,
    use_pty

User hostman may run the following commands on <hostname>:
    (root : ALL) /usr/bin/apt, /usr/bin/rm, /bin/nano

The key part of the output is:

User hostman may run the following commands on <hostname>:
   (root : ALL) /usr/bin/apt, /usr/bin/rm, /bin/nano

This indicates that the user hostman can run the following commands as root:

  • /usr/bin/apt
  • /usr/bin/rm
  • /bin/nano

These are exactly the commands specified in the /etc/sudoers configuration file. This way, you can quickly review the privileges of a specific user without the need to search through the /etc/sudoers file manually.

Additionally, you can simplify the process of obtaining user privilege information by checking the permission for executing a specific command:

sudo -l -U hostman ls

If the command is not allowed, there will be no output in the terminal. However, if it is allowed:

sudo -l -U hostman apt

The terminal will display the full path to the command's binary:

/usr/bin/apt

This way, you can check whether the current user can execute a specific command when unsure about their access rights.

Disabling Password Prompt

The sudo utility allows running commands without explicitly entering a password. However, disabling the password prompt is not considered secure, so perform this configuration at your own risk.

To disable the password prompt, you need to open the /etc/sudoers file:

sudo nano /etc/sudoers

Then, add a new line containing the NOPASSWD keyword and a list of commands for which the password is not required:

hostman ALL=(root:ALL) NOPASSWD: /usr/bin/apt

You should also separate commands that require a password from those that don't. For example, the allowed commands with a password prompt should be listed separately from the ones without:

hostman ALL=(root:ALL) /usr/bin/rm,/bin/nano
hostman ALL=(root:ALL) NOPASSWD: /usr/bin/apt

This way, you'll have two sections for allowed commands: one requiring a password and one that doesn't.

Conclusion

Although the sudo command resembles the su command, there is a key difference between them:

  • su stands for "substitute user".
  • sudo stands for "substitute user and do".

Thus, su performs a full user switch, requiring an explicit password input, while sudo only simulates executing a command as another user, without switching the user entirely.

For this reason, sudo is much safer when granting extended privileges to another user. The user won't need the root password, as they can execute administrator commands under their own user account.

Additionally, unique permissions (access rights) for each individual user in the sudo group can be configured in a special configuration file. In this file, you can also specify whether a password is necessary to run certain commands.

Ubuntu
12.02.2025
Reading time: 10 min

Similar

Ubuntu

How to Install Caddy Web Server on Ubuntu 22.04

Caddy is a cross-platform web server built in the Go and uses HTTPS by default. It stands out for its ease of use and simple configuration. It is known for being easy to configure, especially for users who do not have much experience with web server administration.  Unlike other web servers, Caddy is designed to work with HTTPS out of the box and has integration with Let's Encrypt, allowing you to automatically receive and renew certificates. Below, we will explain how to install Caddy on Ubuntu 22.04 and how to configure it. Why Use Caddy? Why do you need Caddy and what does it offer compared to Apache or Nginx? As we said above: simplicity and security. You do not need to configure encryption parameters and protocol usage, Caddy will do everything out of the box, and in the best possible way, using the most modern technologies. It has the latest features such as HTTP/2, IPv6, Markdown, WebSockets, CreateCGI, templates, and other standard features. The configuration itself is extremely simple, you need to set a minimum of options to get a working server, but at the same time you can manage it quite flexibly, redefining the necessary parameters. The only downside is compatibility with old systems, as Caddy automatically disables outdated protocols and ciphers. Installing the Caddy Web Server via Cloudsmith  There are four different methods to install Caddy. We can do it by simply downloading the executable binary, by compiling the source code, using docker image, or installing it from the repository. In this article, we will do the latter. Before we start installing the Caddy web server, it is recommended that we first update the Ubuntu host system and at the same time update the package sources. We always want to benefit from the most recent releases and prefer to avoid outdated software packages. Perform updates and upgrades: sudo apt update && sudo apt upgrade -y Installing Caddy requires appropriate sudo permissions on the host system. To install Caddy on Linux Ubuntu 22.04, we first start by setting up the necessary dependencies: apt install gnupg curl apt-transport-https debian-keyring debian-archive-keyring -y Once the installation of all dependencies for the web server has been successfully completed, we need to add the GPG key using the following command: curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg Next we have to add the Caddy repository to the APT sources list, allowing Caddy to be installed from this repository: curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list Update the package sources: sudo apt update -y Finally, the Caddy can be installed via the command line. At this point, all prerequisites, and preparations for the installation have been successfully completed. Run the command below to install. sudo apt install caddy -y Now that the web server has been installed on the Linux host system, the service just needs to be activated. We do this with the following command. sudo systemctl enable --now caddy The version you just installed can be validated with the following command: caddy version Is a version number displayed? Then Caddy has been successfully installed on the system. Caddy Configuration The internal format of the caddy configuration is stored in JSON format and can be managed online via REST API, a more classic format of setting via a configuration file is also available, for this purpose the configuration file /etc/caddy/Caddyfile is used.  It already contains an example of the configuration, and we only need to correct it. Please note that the indents in the file are formed strictly using tabulation and two, four, six, etc. indents should be used, otherwise you will receive a warning about incorrect formatting of the configuration file. Set up a Static Site If we want to set a website with Caddy over the local network or over the Internet, we have to save the files and subdirectories associated with the website in the www directory. To do this, we first create a new directory for the output of a web page: sudo mkdir -p /var/www/htmlcd /var/www/html Create a website index with the editor: sudo nano index.html Copy the following content and paste this example page into the index.html: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello, I'm Caddy, your reliable web server!</title> </head> <body> <p>Great projects can be created here! All that is needed is HTML and CSS knowledge, rounded off with a little JavaScript.</p> </body> </html> Now we need to edit the Caddy configuration file so that the web page can be displayed. To do this, execute the following commands from your system. sudo nano /etc/caddy/Caddyfile  Edit: :80 { # Path of the website root * /var/www/html/ The website should now be accessible via the IP address from the local network. If you want to make the website accessible via the Internet, the web ports (80/443) must be released for the server IP address within the NAT settings in the router/firewall. Set up a Domain To set up a domain, you first need to specify the domain's A/AAAA DNS records on this server in the DNS control panel. Then create a document root directory for the website in the /var/www/html folder: mkdir /var/www/html/example.com Replace example.com with your domain. When using SELinux, we will change the file security context for web content: # chcon -t httpd_sys_content_t /var/www/html/example.com -R# chcon -t httpd_sys_rw_content_t /var/www/html/example.com -R To configure a domain in this configuration, we will only have to replace <name> :80 with our domain. Also, if we want to change the path of our website, we will have to modify the parameter root. example.com { root * /var/www/html/example file_server } To reload the configuration, we have to restart the service: systemctl reload caddy Also, if we want, we can configure the logs for access: example.com { root * /var/www/html/example file_server log { output file /var/log/caddy/access.log format console } } Configure a Dynamic Site  To work with dynamic content, we will need support for PHP, the scripting language in which most CMS are written. Caddy does not have its own process manager, so we will use PHP-FPM for this purpose: sudo apt install php-fpm Then we go to /etc/php/8.3/fpm/php.ini and adjust some parameters. First, we find, uncomment and change the option to the following: cgi.fix_pathinfo=0 Then we set the maximum size of the request being sent: post_max_size = 32M And the maximum size of the uploaded file, it must be less than or equal to the size of the request sent: upload_max_filesize = 30M Save the changes and restart the fpm service: sudo systemctl restart php8.3-fpm Now, after adding the fpm directive, configuration will look like this: example.com { root * /var/www/html/example file_server encode zstd gzip php_fastcgi unix//run/php/php8.3-fpm.sock # Uses PHP-FPM to serve PHP files (through a Unix socket) log { output file /var/log/caddy/access.log format console } } Set up Caddy as Reverse Proxy To set up a reverse proxy, add a new site block with the following structure: example.com { encode zstd gzip handle_path /static/* { root * /var/www/html/example file_server } reverse_proxy localhost:3000 log { output file /var/log/caddy/access.log format console } } This Caddyfile sets up a reverse proxy where requests to hostman.com are forwarded to localhost:3000, except for requests starting with /static/, which are served directly from /var/www/html/example. The reverse_proxy directive ensures all non-static requests are proxied to the backend server at localhost:3000. Wrapping Up If you are a beginner and want to set up a web server without the hassle of long configuration, Caddy is perfect for you. Even if you are an experienced user who needs an instant and simple web server, then you should pay attention to Caddy.  If you require a more sophisticated server with advanced features, then with minimal configurations you can set folder permissions, manage authentication, error pages, archiving, HTTP request redirection, and other settings.
07 February 2025 · 7 min to read
PostgreSQL

How to Install PostgreSQL on Ubuntu

PostgreSQL is a well-known relational database management system that provides high-availability features. These are renowned for their functionalities, such as support for complex statements, views, triggers, and foreign keys. PostgreSQL is installed on Ubuntu to provide a secure as well as flexible DB infrastructure. By installing it on the Linux distribution, you can enable and deal with the vast data in an efficient and secure manner. This infrastructure is designed to deal with different workloads, from single-machine apps to large internet-facing apps with multiple concurrent users. In this tutorial, we will walk through installing and setting up PostgreSQL on Ubuntu. Installing PostgreSQL on Ubuntu Ubuntu comes with the PostgreSQL package in its default repositories. You can install it on a Linux system following the given steps. It downloads the stable package. This is important for DB analysts, administrators, and industries that require a dependable DB solution for managing a large volume of data.  Let’s move forward into each step of installing PostgreSQL with detailed explanations on Ubuntu. Step 1: Refresh Ubuntu Repository First, refresh the Ubuntu package indexes. It is useful for maintaining system stability and security: sudo apt update Step 2: PostgreSQL Installation  PostgreSQL is included in Ubuntu's default repositories, making installation straightforward. To install it with some additional tools, execute the below command: sudo apt install -y postgresql postgresql-contrib Here: postgresql: The core PostgreSQL DB server. postgresql-contrib: Additional utilities and extensions useful for DB. Step 3: Start and Enable Services It is essential to enable the PostgreSQL service after installation and ensure it starts automatically upon bootup. The installed package utilizes the systemd daemon, which deals with the DB server runtime operations.  Run the commands below to make sure the DB server automatically initializes when the server boots up. Let’s initialize the service: sudo systemctl start postgresql And enable it so that it launches automatically when the machine boots up: sudo systemctl enable postgresql Step 4: Verify Installation To verify if the installed package is operating properly, check out its status through the below: sudo systemctl status postgresql In the figure, you can see an active status. It represents the services that are correctly running. Step 5: Access Shell Finally, switch to the PostgreSQL user account and launch the CLI to interact with database operations. Here, the -i flag provides an interactive login shell: sudo -i -u postgres The above display gives access to a user account. Once you're in the user environment, launch the CLI through the given command: psql As you can see in the above screenshot, this command launchs the CLI, where users can perform multiple operations by executing commands. Step 6: Basic Database Commands The creation of a database and a new user for any application is a good practice rather than using the root. In this way, a particular user can access the shell interface and run basic statements on the particular database. Here are general commands with thorough explanations and examples: Creation of the New Database To prevent conflicts, ensure data integrity and control access privileges for different applications or users, you need to create a new database. For creation, use the given command within the shell: CREATE DATABASE hostmandb; The screenshot shows that a database has been created. Creation of the New User Create a customized user and set a strong password: CREATE USER hostman_user WITH ENCRYPTED PASSWORD 'Qwer1234'; We have created a hostman_user with the password Qwer1234. Give Privileges to the Created User You can grant hostman_user complete privileges to the hostmandb through the given command. This allows controlled accessibility to database objects, enhancing data integrity as well as security: GRANT ALL PRIVILEGES ON DATABASE hostmandb TO hostman_user; Exit Shell For closing the shell, you can utilize the \q option as below: \q The figure shows that the shell has been exited. Finally, you can exit the user environment by executing the given command: exit The output confirms that you have returned to the main system user account. Access a Database as the Particular User You can connect to the particular database from the specific user account through the -U flag: psql -U hostman_user -d hostmandb -h 127.0.0.1 -p 5432 Here: -U hostman_user: Indicates the user. -d hostmandb: Indicates the database name. -h 127.0.0.1: Indicates the host (local machine). -p 5432: Indicates the PostgreSQL default port. In the given output, you can see that the user hostman_user has accessed the hostmandb console. Listing of All Databases View all databases and check whether the hostmandb database is available or not: \l In the figure, you can see that the database hostmandb is listed. Switch/Connect to the Particular Database To switch to a specific database, such as hostmandb, within PostgreSQL, use the \c command: \c hostmandb The above output confirms that the postgres user has successfully connected to the hostmandb database. Creation of the Particular Table To create a customized table, use the below statement. In our example, we create a hostmantb table: CREATE TABLE hostmantb(    id SERIAL PRIMARY KEY,    name VARCHAR(100),    age INTEGER,    department_id INTEGER); Here: id SERIAL PRIMARY KEY: It creates an auto-incrementing primary key column with the name id. name VARCHAR(100): It creates a name column that can store up to 100 characters. age INTEGER: It creates an age column that stores integer values. department_id INTEGER: This line creates a department_id column that stores integer values. The outcome of the above screenshot confirms that the table hostmantb is successfully created with specific attributes. List All Tables in the Particular Database For listing all tables in the hostmandb database, use the \dt command: \dt It displays all tables as well as confirms that the hostmantb is listed above. Overview a Table's Structure You can view the structure of the created table through the \d command. Let’s display the structure of hostmantb table: \d hostmantb In the above figure, you can see the complete structure of hostmantb table with id, name, age, and department_id having specific types. Input Entries into a Particular Table To input entries into a hostmantb table, use the below statement. This way, we input the values Peter, 35, and 1 to the columns name, age, and department_id, respectively: INSERT INTO hostmantb(name, age, department_id) VALUES ('Peter', 35, 1); The output confirms that we have successfully input data into the hostmantb table. Select All Data from a Particular Table You can select all data from the hostmantb table through the below statement: SELECT * FROM hostmantb; Modify Data in Particular Table For modifying data in hostmantb, you can utilize the below statement. For example, set the age column to 40 for the row where the name column equals Peter: UPDATE hostmantb SET age = 40 WHERE name = 'Peter'; The output confirms that the age column is updated. Remove Data from the Particular Table In this section, you can remove data from the specific table through the DELETE statement. It deletes all entries from the hostmantb table where the value in the name column is Peter: DELETE FROM hostmantb WHERE name = 'Peter'; In the screenshot, one entry from the hostmantb table is removed. Exit CLI You can easily exit the CLI via the \q utility: \q This tutorial has given you thorough guidelines for every step involved in installing as well as setting PostgreSQL on Ubuntu.  Conclusion By installing PostgreSQL on Ubuntu, you can optimize the DB infrastructure. PostgreSQL is often chosen for its freely available nature, which allows for customization, the system's stability and security features. In addition, PostgreSQL's supporters' help and comprehensive guide make it simpler to enhance operations and troubleshoot problems.  This combination makes sure that the DB system is both powerful as well as adaptable to several needs. In this tutorial, there are a lot of fundamental DB commands to get you started with database administration. Therefore, you will be able to create databases, and users and perform basic tasks.
24 January 2025 · 7 min to read
Firewall

How to Install CSF (ConfigServer Security & Firewall) on Ubuntu 22.04

ConfigServer Security & Firewall (CSF) is a highly regarded tool for securing Linux servers against varying cyberattacks. Its robust functionality and simple interface proves that it is the best choice for system administrators. Whether you're managing a small server or large network, this tool provides an effective defense mechanism which is easy to deploy and manage. The below manual discusses the installation process and configuration of this tool on Ubuntu 22.04 LTS to maximize protection and performance of the server. Advantages of Usage of CSF Firewall on Ubuntu 22.04 LTS This versatile security solution has a variety of benefits tailored for servers using Linux as an operating system. User-Friendly Management With an easy-to-edit configuration file and simple command-line utilities, it ensures even novice administrators can quickly implement server security measures. Powerful Security Features Port Restrictions: Secure sensitive services like MySQL (port 3306) and SSH (port 22) by allowing or denying specific traffic. DDoS Attack Mitigation: Safety against high-traffic denial-of-service attempts. False Login Notifications: Automatically blocks IPs after repeated false login attempts to protect from brute force attacks. GeoIP Filtering: Restriction ofentry from certain geographic regions which gives enhanced security Effortless Update Integrated with the system's package manager, CSF updates seamlessly, making sure that firewall contains the latest security patches. Low Resource Consumption Optimized for performance, this tool works without placing unnecessary strain on system resources. Custom Alerts and Logs Receive real-time notifications for security events and go through detailed logs to monitor server activity. Step-by-Step Guide to Install CSF on Ubuntu 22.04 LTS Below is a detailed manual which explains installing it on Ubuntu 22.04 LTS. Step 1: Updating the System First, update the system’s package repository to make sure you have the latest software. To update the system’s package repository, use the following command: sudo apt update && sudo apt upgrade -y Step 2: Installation of Dependencies CSF relies on some dependencies to function appropriately. To install dependencies, use command below: sudo apt install -y perl libwww-perl liblwp-protocol-https-perl iptables nano Essential Dependencies: Perl: It is a programming language. Many of the CSF scripts and configuration tools are written in Perl. Installing perl will ensure that the system will run necessary scripts to manage firewall operations properly. libwww-perl and liblwp-protocol-https-perl: These libraries handle HTTP & HTTPS requests. CSF uses them to fetch updates, download remote blocklists, and securely manage real-time threat data feeds over HTTPS, enhancing firewall’s ability to keep itself updated with the new security information. iptables: Serving as the foundation for the Linux firewall functionality, iptables is integral for operations. It allows to define and implement traffic filtering rules, block specific ports, and restrict connectivity by IP addresses at the kernel level. nano: While optional, it is included to simplify the method of editing the configuration files directly from the terminal. It enables system administrators for doing quick modifications to firewall settings while staying in terminal. Step 3: Download and install CSF The package is available to download through its official website. For downloading, run these commands: cd /usr/srcsudo wget https://download.configserver.com/csf.tgz Extract the files: sudo tar -xvzf csf.tgz For installation, go to the extracted directory:  cd csf And execute the installer by running the following command: sudo sh install.sh When the installation is complete, it will look like the following: To confirm installation, check the CSF version by running: sudo csf -v CSF version will appear on the screen: Step 4: Configure CSF Firewall Settings CSF needs to be configured according to the user’s needs. There are two ways to configure it, through GUI and through terminal. By Terminal For this, we will perform changes in csf.conf located at /etc/csf/csf.conf. Use the following command to open the csf.conf file: sudo nano /etc/csf/csf.conf Output: Do the following changings for basic firewall protection: Testing mode (TESTING = "1") temporarily clears firewall rules to prevent being locked out during configuration. Enable it until you verify all settings, then disable it (TESTING = "0") to activate full protection. TESTING = "0" Allow MySQL Port: If you need to allow using MySQL, update csf.conf as below: TCP_IN = "22,3306" After modifications have been done in configuration, apply them, using: sudo csf -rsudo systemctl restart csf By GUI This tool already has a GUI mode built in. It needs to be configured through the csf.conf and a few commands. Following is the procedure of enabling it. 1. Install prerequisites: To install prerequisites, use the following command: apt-get install libio-socket-ssl-perl libcrypt-ssleay-perl \                    libnet-libidn-perl libio-socket-inet6-perl libsocket6-perl 2. Perform amendments in csf.conf: Perform edits in csf.conf to enable the UI mode and allow endpoints. Also update the username and password for UI. Note that the default username and password have to be updated. So to access the csf.conf, use the following command: sudo nano /etc/csf/csf.conf Now find ui = "0" and convert it to "1". This will enable the UI mode. Then find UI_PORT =  and write an entry of 7171. This will be the specific gateway on which you can interact with the GUI. Be sure that the port number is always bigger than 1024. After these, also edit the UI_USER and UI_PASSWORD. If the default UI_USER and UI_PASSWORD are not updated the UI will not work. Its a MUST to edit these from default values. Place the same port in TCP_IN and TCP_OUT.  Enter this command to add your IP address to ui.allow file: sudo echo "your_IP_adress" >> /etc/csf/ui/ui.allow In this command you have to paste your IP address. If you do not know your IP address, then you can just google "Whats my IP" and it will show you your IP. Just copy and paste in the above command and hit enter. Then in the terminal, type: csf -rsystemctl restart csfsystemctl restart lfd This will properly apply the ammendmets you have performed. Now, your UI has been set up. Now you need to enter your IP address with the endpoint you allowed (7171). Finally, interact with the UI. To connect with the GUI, you need to type the IP of the server along with the port that you set (7171) in your browser. In my case it was the following: 195.133.93.222:7171 195.133.93.222: The public IP address of the server 7171: Gateway number which I set Now you have the GUI. Additional CSF Firewall Commands With the tool now installed, you can make additional commands that can be highly useful for enhancing firewall management. Following is some detail: To block an IP address: sudo csf -d <IP_ADDRESS> To allow an IP address: sudo csf -a <IP_ADDRESS> To view status: sudo csf -l To restart: sudo csf -r Setting Up Alerts in CSF Activating notifications allows the admins of the server to get timely updates on important events, such as IP blocks, failed login attempts, and other security incidents. These are important in quickly detecting, as well as addressing safety risks. Below is the explanation about setting up notifications via email. Updating the Configuration File Use a text editor like Nano to open the tool’s main configuration file by writing: sudo nano /etc/csf/csf.conf Search for the line starting with LF_EMAIL_ALERT. This setting determines whether CSF sends email notifications. LF_EMAIL_ALERT = "0" Change the value from 0 to 1 to enable email notifications. LF_EMAIL_ALERT = "1" Find the LF_ALERT_TO option in the file, which defines the recipient email for alerts. Add the preferred email here: LF_ALERT_TO = "[email protected]" Define email of the sender by utilizing the option LF_ALERT_FROM. The notifications will be sent from this email address: LF_ALERT_FROM = "[email protected]" Press CTRL + O to save changes and CTRL + X to exit Nano. Restart CSF and LFD: sudo csf -rsudo systemctl restart lfd Customizing Alert Types You can customize which types of events would trigger email notifications. A few common options in the config are below: Login Failures: Controlled by LF_ALERT_LOGIN. Blocked IP Alerts: Enabled by LF_EMAIL_ALERT. Excessive Resource Usage: Configured via LF_ALERT_RESOURCE. For example, to enable login failure notifications, set: LF_ALERT_LOGIN = "1" Benefits of Email Notifications Real-Time Monitoring: Immediate awareness of suspicious activities or potential threats. Quick Response: Reduces the time between detecting and mitigating safety issues. Audit Trail: Email warnings provide a record of important safety events. By enabling notifications, it becomes an even more proactive tool in managing server safety. Example: Configuring CSF for WordPress Here's how to configure CSF to meet the requirements for a server hosting WordPress (WP), MySQL, and Redis: 1: Open the CSF configuration file: sudo nano /etc/csf/csf.conf 2: Allow endpoints 80 (HTTP) and 443 (HTTPS). These are required for serving the WordPress site. Find the line that starts with TCP_IN and modify it as follows: TCP_IN = "22,80,443,3306,6379" Explanation: 22: SSH access 80: HTTP for WordPress 443: HTTPS for WordPress 3306: MySQL gateway 6379: Redis gateway 3: Add a custom rule to limit interaction to Redis (port 6379) from the internal network only. Find the csf.allow file and add: 192.168.1.0/24 6379 # Internal network access to Redis Replace 192.168.1.0/24 with your internal network's CIDR notation. 4: Restrict MySQL connectivity. Allow MySQL authorization from internal network. In the csf.allow file, add: 192.168.1.0/24 3306 # Internal network access to MySQL Allow MySQL access from an external developer IP. In the same csf.allow file, add: 203.0.113.5 3306 # Developer IP access to MySQL Replace 203.0.113.5 with the developer's external IP address. 5: Restrict SSH Access. To allow SSH visibility only from a specific subnet, add the subnet to csf.allow: 192.168.1.0/24  # SSH access from the specific subnet Also, explicitly deny SSH visibility from all other IPs in csf.deny: ALL 22 # Block SSH for all except explicitly allowed IPs 6: Apply changes by restarting CSF and LFD: sudo csf -rsudo systemctl restart lfd 7: Verify that the connections points are correctly opened: sudo csf -l Check specific IP connectivity using: csf -g <IP_ADDRESS> Conclusion Using ConfigServer Security & Firewall on Ubuntu 22.04 LTS significantly improves the safety of the server. Along with its advanced functions like managing gateways, DDoS protection, and warnings in real-time, it also provides a comprehensive solution for safeguarding servers of Linux. To find more about different options and settings of this tool, check its official website. By utilizing this guide, you'll establish a robust firewall infrastructure capable of defending against modern cyber threats while maintaining optimal server performance. In addition, you can install Ubuntu on our cloud VPS server.
21 January 2025 · 9 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