How To Install Samba on Debian 10 Buster

If you are working on a small to medium entreprise network, you probably have dozens of drives and printers that need to be shared.

Besides the NFS protocol, there are plenty of other network protocols that can be used in order to share resources over a network.

The CIFS, short for Common Internet File System, is a network filesystem protocol used to share resources among multiple hosts, sharing the same operating system or not.

The CIFS, also known as the SMB protocol, is implemented by one popular tool : the Samba server.

Started in 1991, Samba was developed in the early days in order to ease the interoperability of Unix and Windows based systems.

In this tutorial, we are going to focus on the Samba installation and configuration for your network.

Prerequisites

In order to install new packages on your system, you will need to be a user with elevated permissions.

To check if you are already a sudo user, you can run the “groups” command and check if “sudo” belongs to the list.

$ groups

user sudo netdev cdrom

If you don’t belong to the sudo group, you can check one of our tutorials in order to gain sudo privileges for Debian instances.

Now that you have sudo privileges, let’s jump right into the Samba server installation.

Installing Samba on Debian

Before installing Samba, you will need to make sure that your packages are up-to-date with the Debian repositories.

$ sudo apt-get update

Now that your system is up-to-date, you can run the “apt-get install” command on the “samba” package.

$ sudo apt-get install samba

When installing Samba, you will be presented with the following screen.

Installing Samba on Debian samba

In short, this window is used in order to configure retrieval of NetBIOS name servers over your network.

Nowadays, your entreprise network is most likely using DNS name servers in order to store static information about hostnames over your network.

As a consequence, you are most likely not using a WINS server, so you can select the “No” option.

When resuming the installation, APT will unpack and install the packages needed for Samba.

Additionnally, a “sambashare” group will be created.

After the installation, you can check the version used on your system by running the “samba” command with the “-v” option.

$ samba -V

Installing Samba on Debian samba-version

You can also verify that the Samba server is running by checking the status of the Samba SMB Daemon with systemctl.

$ systemctl status smbd

Installing Samba on Debian samba-service

Great, Samba is now correctly installed on your Debian server!

Opening Samba Ports on your firewall

This section only applies if you are using UFW or FirewallD on your server.

In order for Samba to be reachable from Windows and Linux hosts, you have to make sure that ports 139 and 445 are open on your firewall.

On Debian and Ubuntu, you are probably using the UFW firewall.

In order to open ports on your UFW firewall, you have to use the “allow” command on ports 139 and 445.

$ sudo ufw allow 139
$ sudo ufw allow 445

$ sufo ufw status

Opening Samba Ports on your firewall ufw-status

If you are working on a CentOS or a RHEL server, you will have to use the “firewall-cmd” in order to open ports on your computer.

$ sudo firewall-cmd --permanent --add-port=139/tcp
success
$ sudo firewall-cmd --permanent --add-port=445/tcp
success
$ sudo firewall-cmd --reload
success

Opening Samba Ports on your firewall-centos

Configuring Samba on Debian

Now that your Samba is correctly installed, it is time to configure it in order to configure it in order to be able to export some shares.

Note : Samba can also be configured in order to act as a domain controller (like Active Directory) but this will be explained in another tutorial.

By default, the Samba configuration files are available in the “/etc/samba” folder.

Configuring Samba on Debian conf-folder

By default, the Samba folder contains the following entries :

  • gdbcommands : a file containing a set of entries for the GDB debugger (won’t be used at all here);
  • smb.conf : the main Samba configuration file;
  • tls : a directory used in order to store TLS and SSL information about your Samba server.

For this section, we are going to focus on the content of the smb.conf file.

The Samba configuration file is composed of different sections :

  • global : as its name indicates, it is used in order to define Samba global parameters such as the workgroup (if you are using Windows), the log location, as well as PAM password synchronization if any;
  • shares definitions : in this section, you will list the different shares exported by the Samba server.

Defining the Windows workgroup

If you plan on including the Samba server into a Windows workgroup, you will need to determine the workgroup your computers belong to.

If you are working on a Unix-only network, you can skip this section and jump right into share definition.

Note : if you are using a domain controller, those settings do not apply to you.

In order to find your current workgroup, head over to the Windows Start Menu, and search for “Show which workgroup this computer is on”.

Defining the Windows workgroup

Select the option provided by the search utility and you should be able to find your workgroup in the next window.

Defining the Windows workgroup-2

In this case, the workgroup name is simply “WORKGROUP“.

However, you will have to make sure that this name is reflected in the Samba configuration file.

Defining the Windows workgroup-3

Now that your workgroup is properly configured, let’s start by defining simple share definitions for your Samba server.

Defining Samba share definitions

On Samba, a share is defined by specifying the following fields :

  • Share name : the name of the share as well as the future address for your share (the share name is to be specified into brackets);
  • Share properties : the path to your share, if it is public, if it can be browsed, if you can read files or create files and so on.

In order to start simply, let’s create a Samba share that will be publicly available to all machines without authentication.

Note : it is recommended to setup Samba authentication if you are exporting shares containing sensitive or personal information.

Creating a public Samba share

First of all, you will need to decide on the folder to be exported on your system, for this tutorial we are going to choose “/example”.

In order for users to be able to write files to the share, they will need to have permissions on the share.

However, we are not going to set full permissions to all users on the folder, we are going to create a system account (that has write permissions) and we are going to force user to use this account when logging to Samba.

In order to create a system account, use the “useradd” command with the “-r” option for system accounts.

$ sudo useradd -rs /bin/false samba-public

$ sudo chown samba-public /example

$ sudo chmod u+rwx /example

In order to create a public Samba share, head over to the bottom of your Samba configuration file and add the following section.

$ nano /etc/samba/smb.conf

[public]
   path = /example
   available = yes
   browsable = yes
   public = yes
   writable = yes
   force user = samba-public

Here is an explanation of all the properties specified in this Samba share definition :

  • path : pretty self-explanatory, the path on your filesystem to be exported with Samba;
  • available : meaning that the share will be exported (you can choose to have shares defined but not exported);
  • browsable : meaning that the share will be public in network views (such as the Windows Network view for example);
  • public : synonym for “guest ok”, this parameter means that everyone can export this share;
  • writable : meaning that all users are able to create files on the share.
  • force user : when logging, users will take the identify of the “samba-public” account.

Before restarting your smbd service, you can use the “testparm” in order to check that your configuration is syntactically correct.

$ testparm

Creating a public Samba share testparm

As you can see, no syntax errors were raised during the configuration verification, so we should be good to go.

Now that your share definition is created, you can restart your smbd service in order for the changes to be applied.

$ sudo systemctl restart smbd

$ sudo systemctl status smbd

Your share should now be accessible : in order to verify it, you can install the “samba-client” package and list the shares exported on your local machine.

$ sudo apt-get install smbclient

$ smbclient -L localhost
Note : you will be asked to provide a password for your workgroup. In most cases, you have no password for your workgroup, you can simply press Enter.

Creating a public Samba share smbclient

Connecting to Samba from Linux

In order to be able to mount CIFS filesystems, you have to install CIFS utilities on your system.

$ sudo apt-get install cifs-utils

Now that CIFS utilities are installed, you will be able to mount your filesystem using the mount command.

$ sudo mount -t cifs //<server_ip>/<share_name> <mountpoint>

Using our previous example, our exported share was named “public” and it was available on the 192.168.178.35 IP address.

Note : you can follow this tutorial if you are not sure how you can find your IP address on Linux.

If we were to mount the filesystem on the “/mnt” mountpoint, this would give

$ sudo mount -t cifs //192.168.178.35/public /mnt -o uid=devconnected

Password for root@//192.168.178.35/public : <no_password>

Now that your drive is mounted, you can access it like any other filesystem and start creating files on it.

Congratulations, you successfully mounted a CIFS drive on Linux!

Connecting to Samba from Windows

If you are using a Windows host, it will be even easier for you to connect to a Samba share.

In the Windows Search menu, look for the “Run” application.

Connecting to Samba from Windows run-app

In the Run windows, connect to the Samba share using the same set of information than the Linux setup.

Be careful : on Windows, you have to use backslashes instead of slashes.

Connecting to Samba from Windows run-app-2

When you are done, simply click on “Ok” in order to navigate your share!

Awesome, you successfully browsed your Samba on Windows!

Securing Samba shares

In the previous sections, we have created a public share.

However, in most cases, you may want to build secure share that are accessible only by a restricted number of users on your network.

By default, Samba authentication is separated from Unix authentication : this statement means that you will have to create separate Samba credentials for your users.

Note : you may choose to have Samba built as an AD/DC but this would be a completely different tutorial.

In order to create a new Samba, you need to use the “smbpasswd” command and specify the name of the user to be created.

$ smbpasswd <user>
Note : the user you are trying to create with Samba needs to have a Unix account already configured on the system.

Now that your user is created, you can edit your Samba configuration file in order to make your share secure.

$ nano /etc/samba/smb.conf

[private]
   path = /private
   available = yes
   browsable = yes
   public = no
   writable = yes
   valid users = <user>

Most of the options were already described in the previous section, except for the “valid users” one which, as its name specifies, authorizes the Samba access to a restricted list of users.

Again, you can test your Samba configuration with the “testparm” command and restart your Samba service if everything is okay.

$ testparm

$ sudo systemctl restart smbd

$ sudo systemctl status smbd

Now that your drive is secured, it is time for you to start accessing it from your remote operating systems.

Connecting to secure Samba using Windows

On Windows, you will have to use the same procedure than the previous step : execute the “Run” application and type the address of your share drive.

Connecting to secure Samba using Windows private

When clicking on “Ok”, you will be presented with a box asking for your credentials : you have to use the credentials you defined in the previous section with smbpasswd.

Connecting to secure Samba using windows-pass-1

If you provided the correct password, you should be redirected to your network drive, congratulations!

Connecting to secure Samba using Linux

In order to connect to a secure Samba share using Linux, you have to use the “mount” command and provide the address of the share as well as the mount point to be used.

$ sudo mount -t cifs //<share_ip>/<share_name> <mount_point> -o username=<user>

Using the example of our “private” share on the 192.168.178.35 IP address, this would result in the following command :

$ sudo mount -t cifs //192.168.178.35/private /mnt -o username=user

Password for user@//192.168.178.35/private: <provide_password>

That’s it!

Your drive should now be correctly mounted.

You can verify that it was correctly mounted with the “findmnt” command that lists mounted filesystems.

$ findmnt /mnt

Connecting to secure Samba using Linux findmnt

Congratulations, you successfully mounted a secure Samba share on your server!

Conclusion

In this tutorial, you learnt how you can easily install and configure a Samba server in order to share your drives.

You also learnt that you can tweak Samba share options in order to make your shares secure, whether you are using Windows or Linux.

Samba is an important tool working on the interoperability of operating systems : if you are interested in the Samba project, you should definitely check their website.

They are also providing a free alternative to Active Directory where Samba can be configured to act as a domain controller.

If you are interested in Linux System Administration, we have a complete section dedicated to it on the website, so make sure to check it out!

Arping Command on Linux Explained

As a network administrator, you are probably already very familiar with the ARP protocol.

ARP is commonly used by layer two devices in order to discover as well as communicating with each other easily.

When you are dealing with a small office network, you might be tempted to ping hosts in order to verify that they are available.

If you are using the ICMP protocol, you might be aware that you are actually performing ARP requests in order to probe devices on your network.

If you are looking for a more straightforward way to create ARP pings, you might be interested in the arping command.

In this tutorial, we are going to focus on the arping command : how to install it and how to use it effectively.

Prerequisites

In order to install the arping command on your system, you will obviously need sudo privileges on your server.

In order to check if you are sudo or not, you can simply execute the following command

$ groups

user sudo

If this is not the case, you can read our guide on getting sudo privileges for Debian or CentOS hosts.

In order to install the arping command on your server, execute the “apt-get install” command and specify the “arping” package.

$ sudo apt-get install arping

Installing arping on Linux arping

Now that the command is installed, you can execute the “arping” command in order to check the current version used.

$ arping -v

ARPing 2.19, by Thomas Habets <thomas@habets.se>

Great!

The arping command is now installed on your server.

By default, the arping command is going to send an ARP (or ICMP) request every second, but it can obviously be configured.

Using arping to discover hosts

First of all, as any device communicating over Ethernet, your device has an internal ARP table used to communicate over the network.

In order to see your current ARP entries, you can simply execute the “arp” command with the “-a” option for all devices.

$ arp -a

When using the ARP command, you are presented with a list of hostnames, followed by IPs and MAC addresses.

Using arping to discover hosts arp-table

In this case, I am presented with the only entry in my ARP table : a router accessible via the 192.168.178.1 IP address.

However, I might be interested in finding other hosts on my local network : to achieve that, you are going to use the arping command.

Pinging hosts using IP addresses

In order to ping hosts over your network, you can simply use the “arping” command and specify the IP address to be pinged.

Additionally, you can specify the number of pings to be sent using the “-c” option for “count”.

$ arping -c 2 <ip_address>
Note : if you are not sure about the way of finding your IP address on Linux, we have a complete guide on the subject.

For example, using the “192.168.178.27” IP address over your local network, you would execute the following command

Pinging hosts using IP addresses arping-example

As you can see, if you are getting response pings, you are presented with the MAC address of the corresponding device.

Note that using the arping command will not automatically update your ARP table : you would have to use a command such as ping in order to update it.

$ arp -a

Pinging hosts using IP addresses arp-update

Awesome, you successfully used the arping command in order to issue ARP requests over the network!

ARP timeouts using arping

If the arping command is not able to resolve the IP address of the target defined, you will get an ARP timeout.

As an example, executing an ARP request on an unknown host would give you the following output

$ arping -c 5 <ip_address>

ARP timeouts using arping-timeout

As you can see, in some cases, you will be presented with a warning if you don’t specify any network interface.

This is quite normal because the arping command expects a network interface to be specified.

If you were to deal with a router, or if you chose to install your Linux server as a router, two network interface cards can be installed in order to route to two different networks.

If this is the case, the arping needs to know the network interface it needs to use in order to send the ARP ping.

As you can see, the arping command will try to “guess” the network interface if it is not provided with one.

Specifying the network interface

If you have multiple network interfaces on your server, the arping won’t be able to “guess” the network interface card to be used.

As a consequence, you might get an error message stating that the arping was not able to guess the correct one.

Specifying the network interface suitable-device-guess

In order to specify the network interface to be used, you will have to use the “-I” option followed by the name of the network interface.

If you need some help on how to enumerate network interfaces, you can use this guide on finding your IP address on Linux.

$ arping -I <interface_name> <ip_address>

If our interface is named “enp0s3”, the command would be the following one :

$ arping -I enp0s3 192.168.178.22

Specifying the network interface arping-network-interface

Awesome, you have pinged your distant server and you have specified the network interface to be used!

Sending ARP pings from Source MAC

In some cases, you may want to specify the source MAC address you are sending packets from.

In order to achieve that, you need to execute the “arping” command with the “-s” option for “source” followed by the MAC address you want to ping.

$ arping -c 2 -s 00:60:70:12:34:56 <ip_address>

In this case, you have two possibilities :

  • You are the owner of the MAC address and you can simply use the “-s” option.
  • You are not the owner of the MAC address and you are trying to spoof the MAC address. In this case, you need to use the promiscuous mode. As a short reminder, the promiscuous mode is set to transmit all frames received by the NIC rather than the ones it was meant to receive.

In order to enable the promiscuous mode with the “arping” command, you need to use the “-p” option.

Using the options we used previously, this would lead us to the following command.

$ arping -c 2 -s 00:60:70:12:34:56 -p <ip_address>

Conclusion

In this tutorial, you learnt how you can easily use the arping in order to ping IP addresses on your local network.

Using arping, you are able to populate your local ARP cache with the matching MAC address.

You also learnt that you are able to “spoof” your MAC address by using the promiscuous mode.

If you are interested in Linux System Administration, we have a complete section dedicated to it on the website, so make sure to check it out!

How To Add a User to Sudoers On Debian 10 Buster

In today’s tutorial, we are going to see how you can add a user to sudoers on Debian distributions.

The sudo command allows authorized users to perform commands as another user, which is by default the root user.

There are two ways to add a user to sudoers : you can add this user to the sudo group or you can add this user to the sudoers file located at etc.

Here are the details of the two methods.

I – Adding an existing user to the sudo group

As a prerequisites, make sure that the sudo command is available by default. If it’s not the case, you can install it by running (with an account with admin rights)

$ apt-get update
$ apt-get install sudo

The first method is to add the user to the sudo group.

To do that, you are going to use the “usermod” command with the capital G flag (for groups)

$ sudo usermod -a -G sudo user

You can also use the gpasswd command to grand sudo rights.

$ sudo gpasswd -a bob sudo
Adding user to the group sudo

Make sure that the user belongs to the sudo group with the groups command.

$ su - user
(password for user)

$ groups
user sudo

You should now be able to perform a sudo request on Debian 10.

Depending on the configuration you chose during your Debian 10 installation process, you may or may not have access to a root account. If you chose a password for your root account, you will be able to connect to it. Otherwise, the default admin account is the one you created during the installation process.

The sudoers file is located at /etc/sudoers.

This file contains a set of rules that are applied to determine who has sudo rights on a system, which commands they can execute with sudo privileges, and if they should be prompted a password or not.

However, you should never modify the sudoers file with a text editor.

Saving a bad sudoers may leave you with the impossibility of getting sudo rights ever again.

Instead, you are going to use visudo, a tool designed to make sure you don’t do any mistakes.

$ sudo visudo

This is what you should see.

II – Adding an existing user to the sudoers file visudo

At the end of the file, add a new line for the user.

john       ALL=(ALL:ALL) ALL

II – Adding an existing user to the sudoers file sudoers-syntax

By default, the account password will be asked every five minutes to perform sudo operations.

However, if you want to remove this password verification, you can set the NOPASSWD option.

john       ALL=(ALL:ALL) NOPASSWD:ALL

If you want the password verification to be skipped for longer periods of time, you can overwrite the timestamp_timeout (in minutes) parameter in your sudoers file.

# /etc/sudoers
#
# This file MUST be edited with the 'visudo' command as root.
#
# See the man page for details on how to write a sudoers file.
#

Defaults        env_reset
Defaults        mail_badpass
Defaults        secure_path = /sbin:/bin:/usr/sbin:/usr/bin
Defaults        timestamp_timeout=30

III – Adding a group to the sudoers file

Via the visudo, you can add an entire group to the sudoers.

This might be handy if you have a group for system administrators for example. In this case, you simply have to add a user to the system administrators group for him/her to be granted sudo privileges.

To add a group to the sudoers file, simply add a percent symbol at the beginning of the file.

%sysadmins       ALL=(ALL:ALL) NOPASSWD:ALL

Make sure that your user is part of the designed group with the groups command.

$ su - user
$ groups
user sysadmins

You can test your new sudo rights by changing your password for example

$ sudo passwd

IV – Most Common Errors

  • user is not in the sudoers file. This incident will be reported.

IV – Most Common Errors not-in-sudoers

This is the standard error message you get when a user does not belong to the sudo group on Debian 10.

By adding this user to the sudoers file on Debian, this error message should not be raised anymore.

How To Add User To Sudoers On Ubuntu 20.04

This tutorial focuses on adding sudoers rights to a user on Ubuntu 20.04 Focal Fossa.

When managing an Ubuntu 20.04 server, it is actually quite important to know how to add sudoers to it.

The sudo command is a very popular command on Linux.

It allows unauthorized users to perform commands as another user, by default being the root user.

On Ubuntu 20.04, we will focus on three different ways to add a user as sudo : add it to the sudo group, to the sudoers file or using the graphical interface.

Here are the details of the three different methods.

Adding an existing user to the sudo group

On most distributions, it is very likely that the sudo command is available by default.

$ which sudo
Note : the “which” command can be used in order to verify the existence of the sudo command on your host.

Adding an existing user to the sudo group which-sudo

If you notice that this is not the case, you can install sudo by running the following commands.

$ apt-get update
$ apt-get install sudo

In order to add a user to sudoers, you have to use the “usermod” command and the capital G (for secondary groups).

$ sudo usermod -a -G sudo <user>

Adding an existing user to the sudo group usermod-sudo

In order to verify that your user was correctly added to the sudo group, you have to use the “groups” command.

If you see “sudo” as a secondary group for your user, congratulations, you successfully added your user to sudoers!

Adding a user to sudoers using gpasswd

A less popular, yet very powerful way to add a user to sudoers is to use the gpasswd command.

$ sudo gpasswd -a <user> sudo

Adding a user to sudoers using gpasswd

As a quick reminder, gpasswd is used in order to administer the “/etc/group” file on your filesystem.

Adding an existing user to the sudoers file

By default, on Ubuntu 20.04, the sudoers file is located at /etc/sudoers.

Adding an existing user to the sudoers file sudoers

This file contains a set of rules that are applied in order to determine who has sudo rights on your system.

Also, the sudoers file can define privileges such as the commands that can be executed with or without sudo, or if you should be prompted with a password.

By default, you should not modify the sudoers file by yourself (the same logic applies to cron jobs for example).

If you were to corrupt this file, you might would not be able to get sudo rights again.

Instead, you are going to use “visudo” : a tool designed to make sure that you don’t make any mistakes.

$ sudo visudo

sudo-visudo

At the end of the file, add a new line for the user.

john       ALL=(ALL:ALL) ALL

Adding an existing user to the sudoers file sudoers-syntax

By saving and exiting the file, the user “john” will be automatically added to the sudo group.

By default, the account password will be asked every five minutes in order to perform sudo operations.

If you want to remove the password verification, you can simply add the “NOPASSWD” option.

john       ALL=(ALL:ALL) NOPASSWD:ALL
Note : if you add a user to the sudoers file, it does not mean that the user will belong to the sudo group on the system. It will be authorized to perform sudo operations, but it won’t be listed if you use the “groups” command.

Tweaking password verification

If you want to tweak the password verification period, or if you want to increase the verification, you have to modify the “timestamp_timeout” parameter.

# /etc/sudoers
#
# This file MUST be edited with the 'visudo' command as root.
#
# See the man page for details on how to write a sudoers file.
#

Defaults        env_reset
Defaults        mail_badpass
Defaults        secure_path = /sbin:/bin:/usr/sbin:/usr/bin
Defaults        timestamp_timeout=30

In this case, the password will be asked every thirty minutes.

Adding a user to sudoers using the graphical interface

On recent Ubuntu distributions, it is possible to add a user to the sudo group very easily.

First, head over to the “Activities” tab located at the top left corner of your screen and type “Users“.

You should see a screen similar to this one.

Adding a user to sudoers using the graphical interface users

Next, you will have to unlock the panel by clicking on “Unlock”.

Adding a user to sudoers using the graphical interface unlock (1)

You will be asked for your password, note that the account has to be a privileged account in order to perform this operation.

Adding a user to sudoers using the graphical interface authentication-required

Now that the panel is unlocked, you can tick the “Administrator” radio button in order for your user to be part of the administrators!
Adding a user to sudoers using the graphical interface john-sudo
You can even verify that your user is part of the sudo group using the “groups” command.

$ groups john

groups-john

Congratulations, your user is now part of the sudo group!

Adding a group to the sudoers file

In the previous section, we added a user to the sudoers file, but what if you wanted to give those rights to an entire group?

To add a group to the sudoers file, add a “percent” symbol at the beginning of the line, just before the name of the group.

%sysadmins       ALL=(ALL:ALL) NOPASSWD:ALL

Next, make sure that you are part of the designed group and execute your command using “sudo”.

$ groups
user sysadmins

$ sudo passwd

Congratulations, you set “sudo” privileges to an entire group!

Conclusion

In this tutorial, you learnt how you can easily add a user to sudoers using three different methods : using the command-line, the visudo command or using the graphical interface.

If you are interested in Ubuntu 20.04, we wrote a guide on installing and enabling a SSH server.

Also, if you are interested in Linux System Administration, we have an entire section dedicated to it on the website, so make sure to check it out!

How To List Services on Linux

As a system administrator, you are probably dealing with a lot of services every day.

On Linux, services are used for many different purposes.

They may be used in order to start a SSH server on your machine or they can perform some operations on a specific hour or day.

Whether you are using a Debian based distribution or a RedHat one, querying services is very similar.

However, given the distribution you are using, and more specifically the initialization system (init or systemd), you may have to use different commands.

In this tutorial, you will learn how you can, given your system manager, list all services on your Linux machine.

Determine the system manager used

As you probably know, recent distributions use the Systemd system manager.

However, it has not always been the case : in the past, most distributions used the SysVinit system manager.

As a consequence, there are really two ways of managing your services on a Linux system.

Before learning the commands to list services, you have to know the system manager that you are currently using.

To determine your current system manager, the easiest way is to use the “pstree” command and to check the first process ever run on your system.

$ pstree | head -n 5

Determine the system manager used pstree

If you see “systemd“, it obviously means that you are currently using systemd. However, if you see “init“, it means that you are using SysVinit.

On Ubuntu 14.04, that is still using the old init system, your “pstree” may look like this.

Determine the system manager used pstree-init

List Services using systemctl

The easiest way to list services on Linux, when you are on a systemd system, is to use the “systemctl” command followed by “list-units”. You can specify the “–type=service” option in order to restrict the results to services only.

$ systemctl list-units --type=service

List Services using systemctl list-services-linux-systemd

By default, this command will show you only the services that are active or the services that have failed on your system. In the screenshot above, most of the services are active but the logrotate one (highlighted in red) is marked as failed.

Awesome, you learnt how you can easily list your services on a Linux server.

However, as you may have noticed, you did not have access to all services : what about inactive services? What about services that were not loaded by systemd on boot?

List All Services on Linux using list-units

In order to list all services, meaning active and inactive, you have to use the “systemctl list-units” command followed by the “–all” option.

Similarly, you can limit the results to services only by using the type filter.

$ systemctl list-units --type=service --all

List All Services on Linux using list-units list-inactive-services

As you can see, inactives services also listed which might be convenient if you just wrote your service and looking after it in the list.

In this case, only loaded services are listed. On boot, systemd loads unit files and it may choose not to load a specific service if it finds that it won’t be used by the system.

As a consequence, there is a real difference between “loaded” and “installed” services. “Installed” services mean that unit files can be found in the corresponding paths.

Disabling Root Login over SSH ssh-root-login

List Services By State

In some cases, you may only be interested in services that have failed. For that, you can specify the state that you are looking for as an option of the systemctl command.

$ systemctl list-units --state=<state>

$ systemctl list-units --state=<state1>,<state2>

Where “state” can be one of the following values : active, inactive, activating, deactivating, failed, not-found or dead.

For example, if we are only interested in “failed” services, we are going to run the following command

$ systemctl list-units --state=failed

List Services By State failed-service

List All Service Files using list-unit-files

Finally, if you are interested in “loaded“, “installed“, “disabled” as well as “enabled” service files, there is a another command that might be pretty handy.

In order to list all service files available, you have to use the “systemctl” command followed by “list-unit-files”. Optionally, you can specify the type by using the “–type=service” option.

$ systemctl list-unit-files --type=service

List All Service Files using list-unit-files list-installed-services

Alternatively, you can use the “grep” command in order to search for specific paths on your system that may contain service files.

$ ls -l /etc/systemd/system /usr/lib/systemd/service | egrep .service$

List All Service Files using list-unit-files list-files-using-grep

Congratulations, you learnt how you can list services if your system is using systemd!

List Services using service

The easiest way to list services on Linux, when you are on a SystemV init system, is to use the “service” command followed by “–status-all” option. This way, you will be presented with a complete list of services on your system.

$ service --status-all

List Services using service list-services-init-system

As you can see, each service is listed preceded by symbols under brackets. Those symbols mean :

  • + : means that the service is running;
  •  : means that the service is not running at all;
  • ? : means that Ubuntu was not able to tell if the service is running or not.

So why are some services to tell if they are running or not, and some are not able to?

It all comes down to the implementation of the init script. In some scripts, such as the udev script for example, you are able to see that the “status” command is implemented.

udev-status

This is not the case for the “dns-clean” script for example which is the reason why you have a question mark when you query this service.

List SysVinit Services in Folders

Another way of listing the current list of services is to use the “ls” command on the folders containing all scripts on a Linux system, namely “/etc/init.d”.

$ ls -l /etc/init.d/*

List SysVinit Services in Folders initd-folder

Conclusion

In this tutorial, you learnt how you can easily list services on a Linux system whether you are using systemd or SysVinit ones.

If you are interested in creating your own services, we recommend that you have a look at the following resources. They might be really useful in order to correctly achieve that.

  • Writing a startup script for init systems;
  • Starting services at boot using systemd;

If you are interested in Linux System Administration, we have a complete section on this subject on the website, so make sure to check it out.

How To Encrypt File on Linux

If you are a conscientious system administrator, you have probably already wondered how you can make your files secure.

Nowadays, as system attacks get more and more frequent, it isn’t probably a bad idea to think about encrypting your files.

On Linux, there are multiple of encrypting files, directories or filesystems : namely using the LUKS disk encryption specification or simple tools such as GnuPG.

In this tutorial, you will learn how you can easily encrypt files and directories on Linux using the GnuPG tool as well as the zip utility.

Encrypt Files using passphase protection

One of the easiest ways of encrypting a file on Linux is to use the “gpg” utility.

“gpg” is a simple utility that is part of the OpenPGP initiative that aims at providing easy methods to securely sign documents.

Files can be decrypted using two different methods : a password or a key file. In this section, we are going to focus on setting up a password protection for your encrypted files.

To encrypt files using a password, use the “gpg” command with the “-c” option specifying that you want to use a symmetric encryption for your file. After that, specify the name of the file that you want to encrypt.

$ gpg -c <file>

The “gpg” command will create a file with a “.gpg” extension which is the encrypted file that you want to store.

Encrypt Files using passphase protection encrypt-file-using-gpg

If you are running a Linux distribution with a graphical environment, you will be prompted with a window in order to specify the passphrase.

passphrase-encrypt-file

Note : make sure not to forget your passphrase. You won’t be able to recover the passphrase in any means.
Special tip : writing down your passphrase and storing it in a physical lock can be a solution.

If you were to inspect the content of the file using a simple “cat “command, you would not be able to see the content.

Encrypt Files using passphase protection encrypted-file

Awesome, you successfully encrypted a file on Linux using “gpg”!

Decrypt Encrypted File on Linux

In order to decrypt an encrypted file on Linux, you have to use the “gpg” command with the “-d” option for “decrypt” and specify the “.gpg” file that you want to decrypt.

$ gpg -d <file>.gpg

Decrypt Encrypted File on Linux decrypt-file-root

Again, you will be probably be prompted with a window (or directly in the terminal) for the passphrase. If you provide the correct one, you will be able to see the content of your file.

Decrypt Encrypted File on Linux decrypt-file-linux

Note : if you were not prompted for the passphrase for the file, it is because the GPG utility will create a set of keys for you in your home directory when you unlock a file (or create it)

Awesome, your file is now decrypted, you can inspect its content easily.

Encrypt Directory using gpg

In some cases, you may be interested in encrypting a whole directory, containing a lot of files.

In order to achieve that, you are going to create an archive first and encrypt it later on.

To create an archive, use the “tar” command along with the “-cvf” options that stand for “create a file in verbose mode”. Now that your archive is created, you can encrypt it using the “gpg” command with the “-c” option.

$ tar -cvf archive.tar <directory>

$ gpg -c archive.tar

Encrypt Directory using gpg encrypt-tar-archive

Again, you might be prompted for a specific passphrase that you will have to remember.

Congratulations, you successfully encrypted a directory using the tar and gpg commands!

Encrypt Directory using zip

In order to encrypt a file using zip, use the “zip” command with the “–encrypt” option and provide the zip name as well as the files to be encrypted.

$ zip -r --encrypt secure.zip <directory>

$ zip --encrypt secure.zip <file>...<file10>

Encrypt Directory using zip secure-zip

Awesome, you have successfully created an encrypted zip archive!

To open your encrypted archive, you can simply use the “unzip” command and provide the password you just used.

Encrypt Directory using zip unzip-encrypted-zip

Encrypt Files using private key

As explained in other tutorials, generating key pairs (a public key and a private key) remain a very efficient way of preventing people from accessing your files.

To encrypt files on Linux using a private key, you have to execute the “gpg” command with the “–full-gen-key” option. You have multiple options for key generation (such as “–quick-generate-key”) but the full one gives you more options.

$ gpg --full-gen-key

Encrypt Files using private key gpg-generate-key

By default, the GPG utility will ask you a couple of questions. First, it wants you to choose an encryption method for your key.

We are going to choose “RSA” as it can be trusted as one of the best encryption methods available.

Encrypt Files using private key rsa-encryption-method

On the next step, you are asked for the size of the key that you want, we are going to remain with the defaults one and press Enter.

Encrypt Files using private key expiration-key

Finally, you are asked if you want to configure an expiration for the key that you are going to create. In this case, we want to use the same key forever, so you can choose the “0” option.

Encrypt Files using private key information-gpg-key

Now that you specified the key parameters, you are going to provide your name, your email address as well as a comment that is describing your key.

If everything is okay, you can press “O” and proceed to choose a passphrase.

passphrase-key-encryption

So why would you need a passphrase? A passphrase is used in order to protect your key from being stolen. Having a key alone is not enough, not that it could be brute-forced, but somebody could steal your key and use it to decrypt your files. A passphrase prevents this operation.

Encrypt Files using private key generated-key-linux

Congratulations, you successfully created your set of keys for encryption, you can now use them in order to encrypt your files.

To encrypt your file using your created key, you have to use the “gpg” command with the “-e” option for “encrypt” and specify the key to be used with the “–recipient” option.

$ gpg -e --recipient <email or name> <file>

In this case, we used the “devconnected” name along with the “devconnected@example.com” email address. To encrypt the file, we are going to execute the following command :

$ gpg -e --recipient devconnected@example.com

encrypt-using-key

Awesome, you have successfully encrypted your file using your key!

Decrypt File using key

In order to decrypt the file you just encrypted using your key, you have to use the “gpg” command with the “-d” option for decrypt.

$ gpg -d <file>.gpg

In this case, you will be prompted with a window that contains many more information, more specifically the key used.

passphrase-2

When providing the correct passphrase, you will be able to decrypt your file, great!

Decrypt File using key decrypt-file-gpg

Encrypt Files using Nautilus GUI

If you are not into using the terminal, you might want to have a beautiful GUI in order to encrypt your files.

To encrypt using a graphical interface, you are going to use the “Nautilus” file manager along with the “seahorse-nautilus” extension. This extension brings GPG features right into your graphical file explorer.

$ sudo apt-get install nautilus

$ sudo apt-get install seahorse-nautilus

Encrypt Files using Nautilus GUI seahorse-nautilus

When you are done, restart Nautilus by using the “nautilus” command with the “-q” option for “quit”.

$ nautilus -q

Open Nautilus again, using the command line or your left vertical bar, and right click on a file to see the “Encrypt” option.
Encrypt Files using Nautilus GUI nautilus-encryption
When clicking on “Encrypt“, you are asked if you want to choose a passphrase or if you want to encrypt the file using a key.
Encrypt Files using Nautilus GUI nautilus-encryption-2-1

In this case, select the key that you created in the steps before, and click on “Ok” when you are done.

That’s it! You now have an encrypted version of your file.

gpg-file

But did you know that you could decrypt your file using a GUI interface also?

Decrypt using GUI Interface

In order to decrypt your file, you can simply double-click or right-click and select the “Open with Decrypt File”.

Decrypt using GUI Interface open-with-decrypt-file

By using this option, you will be asked the name of the file to be created when decrypting the file. In this case we are going to choose file named “custom.txt

custom-file

When clicking on “Save“, you will be asked for the passphrase that you specified when creating your public key. Provide the specified passphrase and your file should be decrypted!

file-decrypted

Conclusion

In this tutorial, you learnt how you can simply encrypt and decrypt a file on Linux using console line commands or GUI tools.

Encryption is a big part of security : if you are storing sensitive information on your computer or server, you should seriously think about encryption for your disks.

If you are interested in disk encryption, maybe you should take a look at the LUKS project that aims at providing a simple API for it.

If you are interested in Linux System Administration, we have a complete section dedicated to it on the website, so make sure to check it out!

How To Flush DNS Cache on Linux

DNS, short for the Domain Name System protocol, is used on Linux systems in order to retrieve IP addresses associated with names.

For example, when you are performing a ping request, it is quite likely that you are using the DNS protocol to retrieve the server IP.

In most cases, the DNS requests that you perform are stored in a local cache on your operating system.

However, in some cases, you may want to flush the DNS cache of your server.

It might be because you changed the IP of a server on your network and you want to changes to be reflected immediately.

In this tutorial, you are going to learn how you can easily flush the DNS cache on Linux, whether you are using systemd or dnsmasq.

Prerequisites

In order to be able to flush your DNS cache, you have to know how DNS resolution works on your Linux system.

Depending on your distribution, you may be facing different Linux services that act as a DNS resolver.

Before you start, it is quite important for you to know how DNS resolution will actually happen on your operating system.

How To Flush DNS Cache on Linux dns-resolution-linux
Inspired by this Wikipedia diagram
If you are reading this article, you are looking to flush the cache of your local DNS resolver. But as you can see, there are many different caches from your local application until the actual Internet DNS servers.

In this tutorial, we are going to focus on the yellow box meaning the local stub resolver implemented on every Linux system.

Finding your local DNS resolver

On most Linux systems, the DNS resolver is either “systemd-resolved” or dnsmasq. In order to know if you are dealing with one or another, you can execute the following command

$ sudo lsof -i :53 -S
Note : so why are we running this command? As DNS runs on port 53, we are looking for the commands associated with the service running on port 53, which is your local DNS resolver or “stub”.

Finding your local DNS resolver lsof-command
As you can see, on a recent Ubuntu 20.04 distribution, the service listening on port 53 is systemd-resolved. However, if you were to execute this command on Ubuntu 14.04, you would get a different output.
lsof-command-old-distribution

In this case, the local DNS used in dnsmasq and commands are obviously different.

local-dns-resolvers

Knowing this information, you can go the chapter you are interested in. If you were to have a different output on your server, make sure to leave a comment for us to update this article.

Flush DNS using systemd-resolved

The easiest way to flush the DNS on Linux, if you are using systemd-resolved, is to use the “systemd-resolve” command followed by “–flush-caches”.

Alternatively, you can use the “resolvectl” command followed by the “flush-caches” option.

$ sudo systemd-resolve --flush-caches

$ sudo resolvectl flush-caches

In order to verify that your Linux DNS cache was actually flushed, you can use the “–statistics” option that will highlight the “Current Cache Size” under the “Cache” section.

$ sudo systemd-resolve --statistics

flush-dns-systemd-resolve

Congratulations, you successfully flushed your DNS cache on Linux!

Flush DNS cache using signals

Another way of flushing the DNS cache can be achieved by sending a “USR2” signal to the “systemd-resolved” service that will instruct it to flush its DNS cache.

$ sudo killall -USR2 systemd-resolved

In order to check that the DNS cache was actually flushed, you can send a “USR1” signal to the systemd-resolved service. This way, it will dump its current state into the systemd journal.

$ sudo killall -USR1 systemd-resolved

$ sudo journalctl -r -u systemd-resolved

Flush DNS cache using signals flush-dns-using-signals

Awesome, your DNS cache was correctly flushed using signals!

Flush DNS using dnsmasq

The easiest way to flush your DNS resolver, when using dnsmasq, is send a “SIGHUP” signal to the “dnsmasq” process with the “killall” command.

$ sudo killall -HUP dnsmasq

Flush DNS using dnsmasq flush-dnsmasq

Similarly to systemd-resolved, you can send a “USR1” to the process in order for it to print its statistics to the “syslog” log file. Using a simple “tail” command, we are able to verify that the DNS cache was actually flushed.

Now what if you were to run dnsmasq as a service?

Dnsmasq running a service

In some cases, you may run “dnsmasq” as a service on your server. In order to check whether this is the case or not, you can run the “systemctl” command or the “service” one if you are on an SysVinit system.

$ sudo systemctl is-active dnsmasq

# On SysVinit systems
$ sudo service dnsmasq status

If you notice that dnsmasq is running as a service, you can restart it using the usual “systemctl” or “service” commands.

$ sudo systemctl restart dnsmasq

# On SysVinit systems
$ sudo service dnsmasq restart

After running those commands, always make sure that your services were correctly restarted.

$ sudo systemctl status dnsmasq

# On SysVinit systems
$ sudo service dnsmasq status

Conclusion

In this tutorial, you learnt how you can quickly and easily flush your DNS cache on Linux.

Using this article, you can easily clear the cache for systemd and dnsmasq local resolvers. However, you should know that there is another common DNS, named bind, that is purposefully omitted in this article.

Another article about setting up a local DNS cache server using BIND should come in the near future.

If you are interested in DNS queries and how they are performed, you can use this very useful article from “zwischenzugs” named the Anatomy of a DNS query. The article is particularly useful if you want to debug DNS queries and you wonder how they are performed.

Also if you are interested in Linux System Administration, we have a complete section about it on the website, so make sure to check it out.

How To Find Last Login on Linux

If you are working in a medium to big-sized company, it is quite likely that you are working with many other system administrators.

As you are performing your sysadmin tasks, some users may try to connect to your server in order to perform their daily tasks.

However, in some cases, you may find that something has changed on your server. As a consequence, you are wondering who performed the change.

Luckily for you, there are many ways to find who last logged in on your server.

In this tutorial, you will learn about the different useful commands that you can use in order to check the last logins on your computer.

Find Last Login using last

The easiest way to find the last login on your Linux computer is to execute the “last” command with no options. Using this command, you will be presented with all the last logins performed on the computer.

$ last

# To check the last ten login attempts, you can pipe it with "head"

$ last | head -n 10

Find Last Login using last-command

As you can see, by default, the output is truncated : the “devconnected” user is only displayed as “devconne” with simply using the last command.

If you find last logins using complete usernames and hostnames, you have to append the “-w” option or “–fullnames“.

$ last -w

$ last --fullnames

Find Last Login using last-complete-output

Last Command Columns

When taking a look at the last command, the output can be a bit confusing. There are many columns but we don’t exactly know what they stand for.

First of all, there is a difference between user login and reboots.

As you can see, user logins start with the name of the user that connected to the computer. On the other hand, “reboot” logs obviously start with the “reboot” keyword.

User Log In Columns

For user logs, the meaning of the different columns is the following :

  • Username : the username who connected to the computer;
  • TTY : the index of the TTY used by the user in order to connect to the computer. “:0” denotes that the connection is local and you may use the “tty” command in order to find the device used by the user;
$ tty

Last Command Columnstty-command
The user is using /dev/pts/0 to interact with the system

  • The name of the display : as X is used as the display server on every machine, it may use a local display (:0, :1 and so on) or a remote display. If you are interested in running graphical applications remotely, you may read our guide about the X protocol;
  • Hour of the login : starting the server is quite different from logging into it. This hour represents the time where the password was actually provided in the interface;
  • Login status : either you are “still logged in” or “down” with the duration of the session.

Last Command Columns last-session-duration

For example, in the following example, the session duration was twelve minutes.

Pseudo reboot columns

On every reboot, your system adds a new line to the current list of reboots performed on your computer.

Those special lines, starting with “reboot“, have the following columns :

  • Reboot : specifying that this is not a log in but rather a system reboot;
  • Details about the reboot : in this case it was actually a “system boot” meaning that the system just started;
  • Kernel version : the kernel version loaded when booting up the system. It might be different if you host different version of the kernel on your boot partition.
  • Hour of the boot : the hour represents the time of the system boot. It is either followed by a “still running” indication or the end hour followed by the session duration in paranthesis.

Now that you have seen how you can list all last logins on your server, let’s see if you are interested in bad login attempts.

Find Last Login By Date

In some cases, you may be interested in login that were made since or until a specific date in the past, or in the last five minutes.

To find the last login by date, execute the “last” command with the “–since” command and specify the date to find the last logins for.

Similarly, you can use the “–until” command in order to find login attempts made until a given date in the past.

$ last --since <date>

$ last --until <date>

So what are the dates that you can use in order to search?

Date formats are specified in the last documentation page.

Find Last Login By Date last-date-formats

As an example, let’s say that you want to find all login attempts were in the past two days, you would execute the following command

$ last --since -2days

Find Last Login By Date last-since-two-days

Similarly, if you want to find all login attempts made five days in the past, you would run the following command

$ last --until -5days

As a diagram often helps more than words, here is a way to understand the “–since” and “–until” options.

Find Last Login By Date linux-last-login-command

Find Last Bad Login Attempts using lastb

In order to find the last bad login attempts on your Linux server, you have to use the “lastb” with administrator rights.

$ sudo lastb

If you are not sure about how to check such rights, make sure to read our dedicated guides.

Find Last Bad Login Attempts using lastb-command-linux

As you can see, the output is quite similar to the one from the “last” command : the username attempted, the device used as well as the time of the attempt.

In this case, the duration “(00:00)” will be fixed as a connection attempt has no duration at all.

Note that the device line can display “ssh:notty” in case that the log in attempt was made from a SSH terminal.

Inspecting the auth.log file

Alternatively, you can inspect the content of the “/var/log/auth.log” file in order to see all failed attempts on your server.

$ tail -f -n 100 /var/log/auth.log | grep -i failed

Inspecting the auth.log file auth-log-failed-attempts

Find Last SSH Logins on Linux

In order to find the last SSH logins performed on your Linux machine, you can simply inspect the content of the “/var/log/auth.log” and pipe it with “grep” to find SSH logs.

$ tail -f -n 100 /var/log/auth.log | grep -i sshd

Find Last SSH Logins on Linux sshd-logs-last

Alternatively, you can inspect the logs of the SSH service by running the “journalctl” command followed by the “-u” option for “unit” and the name of the service.

$ sudo journalctl -r -u ssh | grep -i failed

Find Last SSH Logins on Linux journactl-command

Note : interested in listing services and their statuses on your server? Here is a guide about listing your services on Linux.

If you don’t see any logs related to the SSH service, it might be related to your SSH configuration file, namely to the “PrintLastLog” option.

$ cat /etc/ssh/sshd_config | grep PrintLastLog

Find Last SSH Logins on Linux print-last-log-ssh

If this option is set to “No” on your server and you wish to print last logs, make sure to uncomment the line with the “yes” value. Do not forget to restart your SSH server after that.

$ sudo nano /etc/ssh/sshd_config

PrintLastLog yes

$ sudo systemctl restart ssh

$ sudo systemctl status ssh

Great! You learnt how you can find the last SSH logs on your computer.

List User Last Login on Linux

In order to find last login times for all users on your Linux machine, you can use the “lastlog” command with no options. By default, you will be presented with the list of all users with their last login attempts.

Alternatively, you can use the “-u” option for “user” and specify the user you are looking for.

$ lastlog

$ lastlog -u <user>

List User Last Login on Linux lastlog-command

As you can see, with no options, the command will return the list of all accounts on your machine, even the root one and system ones.

Conclusion

In this tutorial, you learnt how you can easily find the last login attempts made on a Linux computer.

Whether those attempts were made through a login shell or a SSH session, you now know which files to inspect and which tools to use in order to retrieve them.

Remember that you can inspect those files but you can also plot them on a dashboarding solution such as Kibana, here’s a guide on how to achieve that.

If you are interested in Linux System Administration, we have a complete section dedicated to it on the website, so make sure to have a look!

How To Encrypt Partition on Linux

In one of our previous articles, we learnt how you can encrypt your entire root filesystem on Linux easily.

However, in some cases, you may want to encrypt one simple partition that may store some of your important files.

As you already know, encrypting your disks is crucial. If your laptop were to be stolen, you would probably lose all your personal information.

However, there are some ways for you to cope with this problem : by encrypting your disk partitions.

In this tutorial, you will learn about all the steps necessary to encrypt an entire disk partition, secure it with a passphrase or with a keyfile.

For the example, the article will be illustrated on a RHEL 8 operating system, but there should not be any differences if you use another one.

Prerequisites

In order to execute most of the commands provided in this article, you need to have administrator rights.

To check whether this is the case or not, you can execute the “groups” command and verify that you belong to the “sudo” group for Debian-based distributions or “wheel” for RedHat based ones.

$ groups

How To Encrypt Partition on Linux groups

If you don’t have such rights, you can read one of our articles on the subject about getting sudo rights for Ubuntu or CentOS distributions.

Encrypt Partition using cryptsetup

As specified in the previous articles, encrypting a partition involves formatting the entire disk.

As a consequence, if you plan on encrypting a disk with existing data, you should now that your data will be erased in the process. To avoid losing anything, you should make a backup of your data on an external disk or in an online cloud.

Create New Partition on disk

In order to encrypt a partition, we are going first to create a new one using the “fdisk” utility. For the example, we are going to create a new partition named “sdb1” on the “sdb” disk.

$ sudo fdisk /dev/sdb

Create New Partition on disk fdisk-utility

In the fdisk utility, you can create a new partition using the “n” keyword and specify that you want a partition with a size of 5 GBs for example.

Create New Partition on disk create-partition-fdisk

If you are not sure about how to use “fdisk” or how to create partitions, we have a dedicated article about this subject.

At the end of the process, you need to use the “w” keyword in order to write the changes to the disk.

Create New Partition on disk write-changes-disk

Awesome, now that your partition is created, we are going to format it as a LUKS partition.

Format Disk Partition as LUKS

To encrypt the partition, we are going to use a command related to the LUKS project.

The LUKS project, short for Linux Unified Key System, is a specification used in order to encrypt all storage devices using special cryptographic protocols. As described, LUKS is only a specification, you will need a program that implements it.

In this case, we are going to use the “cryptsetup” utility. As explained in the manual section, cryptsetup aims at creating encrypted spaces for dm-crypt.

First of all, make sure that you have the “cryptsetup” command using the “which” command.

$ which cryptsetup

Format Disk Partition as LUKS which-cryptsetup

If the cryptsetup cannot be found on your server, make sure to install it using one of the following commands

$ sudo apt-get install cryptsetup                     (for Debian distributions)

$ sudo yum install cryptsetup                         (for RHEL/CentOS distributions)

To create your LUKS partition, you need to execute the “cryptsetup” followed by “luksFormat” and the name of the partition to be formatted.

$ sudo cryptsetup luksFormat /dev/sdb1

Format Disk Partition as LUKS cryptsetup-luksformat

First of all, you are reminded that encrypting your disk will actually format it in the process.

After typing “YES” in capital letters, you will have to choose a passphrase in order to secure your device.

LUKS supports two ways of protecting your media : using a passphrase (the one that we currently use) and using keys. For now, you can choose a safe password and your partition should be formatted automatically.

Now that your partition is created, you can inspect it using the “lsblk” command : the partition should be marked as “crypto_luks“.

$ lsblk -f

lsblk-command

Awesome! Now that the volume is formatted, we can open it and create a simple ext4 filesystem on it.

Create ext4 Filesystem on Partition

By default, your encrypted volume is closed meaning that you cannot access data that is available on it.

In order to “open”, meaning “unlocking” your volume, you have to use the “cryptsetup” command again followed by “luksOpen” and the name of the volume.

At the end of the command, provide a name for your open volume, in this case we are going to choose “cryptpart“.

$ sudo cryptsetup luksOpen /dev/sdb1 cryptpart

Create ext4 Filesystem on Partition cryptsetup-luksopen

As you can guess, you are asked to provide the passphrase that you chose in the previous section.

Running the “lsblk” command again, you probably noticed that one volume was created under the “sdb1” encrypted volume named “cryptpart“. The “device mapper”, which is one of the frameworks of the Linux Kernel, did that for you.

Now that your volume is unlocked, it is time for you to create a new ext4 filesystem on it.

To create a new filesystem on your partition, use the “mkfs” command followed by the filesystem format, in this case “ext4”.

$ sudo mkfs.ext4 /dev/mapper/cryptpart

mkfs-command

Awesome, the filesystem was created.

You can now mount it and add new files to it. Files created on this volume will automatically be encrypted.

$ mkdir -p /home/devconnected/files 

$ sudo mount /dev/mapper/cryptpart /home/devconnected/files

$ sudo chown devconnected:devconnected /home/devconnected/files

mount-encrypted-partition

Awesome, now that your data is safe on an encrypted partition, let’s see how you can mount the encryption partition on boot.

Modify crypttab and fstab files

Many system administrators know the existence of the fstab file that is used by your init process to mount drives.

However, when dealing with encrypted partitions, there is another file that comes into play : /etc/crypttab.

Similarly to the fstab file, crypttab is read by your init process when booting. Given the information provided in it, it will ask you to unlock the partition or it will read a key file in order to do it automatically.

Note : the /etc/crypttab may not exist on your system. If it is not the case, you may have to create it.

crypttab-columns

The columns of the crypttab are described above :

  • Device name : you can give your decrypted device any name that you want. Furthermore, it will be automatically created by the device mapper under the “/dev/mapper” path. In the previous section, we chose “cryptpart” for this column;
  • Encrypted device UUID : in order to find which partition contains the encrypted data, your system needs to have its UUID meaning its unique identifier;
  • Method of authentication : as explained, you can choose “none” for the passphrase or you can specify a path to the key. The key method will be explained in the last chapter of this article;
  • Mount options : using this column, you can specify the number of tries for a passphrase, the cipher, the encryption method and many other parameters. The complete list of options is available in the “crypttab” manual page.
$ sudo nano /etc/crypttab

# Content of the crypttab file
cryptpart    UUID=<partition_uuid>    none    luks

crypttab-file-2

If you have doubts about the UUID of your encrypted partition, you can use the “blkid” command with a simple “grep” pipe.

$ sudo blkid | grep -i luks

blkid-command

Now that the “/etc/crypttab” file is modified, you will have to modify the “fstab” file to specify the mountpoint.

$ sudo blkid | grep -i ext4

$ sudo nano /etc/fstab

fstab-file

In the fstab columns, you have to specify :

  • The decrypted device UUID : in order to find it, you can use the “blkid” command but make sure that you opened the device before proceeding. If the device is closed, you won’t be able to find your UUID;
  • The mount point : where the decrypted device is going to be mounted. If the path does not exist, it is going to be created automatically;
  • The filesystem type : in this case, we chose to use “ext4” but it may be different on your system;
  • Dump and pass options : we don’t want the filesystem to be checked on boot-time, so we can keep it to the default values.

When you are done, save your file and you should be good to go.

Given the steps you just performed, your device is ready and it should automatically be mounted on boot.

Verify encrypted device mounting on boot

In order to verify that the device is correctly mounted, we can restart our server and wait for the initramfs module to open the encrypted device.

$ sudo reboot

Verify encrypted device mounting on boot encryption-boot

This is the screen that you should see, at least on RHEL8, when starting your server. If you provide the passphrase, your machine should be able to unlock it and mount it for you.

Once you are logged in your server, you can check that the encrypted partition was correctly mounted using the “lsblk” once again.

$ lsblk -f | grep sdb1 -A 2

lsblk-mounted

Congratulations, you successfully encrypted a partition on Linux using LUKS!

Create Keys For Encrypted Partition

As explained before, LUKS handles two authentication methods, namely passphrases and key files.

In the previous section, we used passphrases but it can be quite handy for you to also have a authentication key.

First of all, create a key file and store it somewhere safe (in directories that regular users cannot navigate to, like “/boot” or “/root“).

$ echo "supersecretpass" > volume-key

$ sudo mv volume-key /boot/

create-volume-key

As you can see, by default, the file was created using the user credentials and it has too many permissions.

Using the “chown” and “chmod” commands, we can set “root” as the owner of the file and change its permissions to read-only.

$ sudo chown root:root /boot/volume-key

$ sudo chmod 0400 /boot/volume-key

read-only-file

Now that the file is set to read-only, we can add it as a key in one of the slots of our LUKS volume.

Add Key to LUKS Volume

In order to add a key to your LUKS volume, you need to execute the “cryptsetup” command followed by the “luksAddKey”, the name of the encrypted volume and the path to the key.

$ sudo cryptsetup luksAddKey <encrypted_device> <path_to_key>

$ sudo cryptsetup luksAddKey /dev/sdb1 /boot/volume-key

Add Key to LUKS Volume luks-add-key

In order to perform this operation, you will be prompted for your passphrase. When provided, the key will be automatically added to your keyslots.

To verify that the key was correctly added, you can inspect your keyslots using the “luksDump” command.

$ sudo cryptsetup luksDump /dev/sdb1

Add Key to LUKS Volume luks-dump-command

Now that the key is added, you only need to modify the “/etc/crypttab” in order for your system to find it on boot.

$ sudo nano /etc/crypttab

# Content of the crypttab file
cryptpart    UUID=<partition_uuid>    /boot/volume-key    luks

When rebooting, your encrypted partition will be mounted automatically!

auto-mount-linux

Conclusion

In this article, you learnt how you can easily encrypt your partition on Linux using the LUKS project and its implementation named cryptsetup.

You can saw that you can use a “key file” in order for your partition to be unlocked automatically.

If you are interested in a full system encryption, we recently wrote an article on the subject.

Also, if you want to read more about Linux System Administration, make sure to have a look at our dedicated section on the website.

How To List Disks on Linux

For the system administrator, checking that disks are working properly is a big concern.

In many cases, you will have to list all the disks available on your computer, with their sizes, in order to make sure that they don’t run out of space.

If they were to run out of space, you could essentially have your server down, preventing all your users from accessing it.

In this tutorial, we are going to see how you can easily list disks available on your Linux machine.

Prerequisites

For some of the commands used in this tutorial, you will need administrator rights in order to have the full output of the command.

In order to check that you have sudo rights, you can execute the “sudo” command with the “-l” option.

$ sudo -l

check-sudo-rights

If you see matching entries, it means that you are a privileged account on this machine.

However, if you are notified that you “can’t run sudo on this computer“, have a read at our dedicated tutorials for Ubuntu or CentOS (RHEL equivalent).

List Disks on Linux using lsblk

The easiest way to list disks on Linux is to use the “lsblk” command with no options. The “type” column will mention the “disk” as well as optional partitions and LVM available on it.

$ lsblk

List Disks on Linux using lsblk-command

Optionally, you can use the “-f” option for “filesystems“. This way, your disks will be listed as well as partitions and filesystems formatted on them.

$ lsblk -f

list-disks-lsblk-command

By executing the “lsblk” command, you are presented with multiple different columns :

  • Name : the name of the device. It is quite important for you to know that Linux devices have a specific prefix depending on the nature of the device. “sd” in this case refers to SCSI devices but it is also short for SATA connections as most drives use SATA nowadays;
  • Filesystem type : if your partition contains a filesystem, it should be listed in this column (xfs, swap or encrypted devices);
  • Label : in some cases, in order to avoid using a UUID, you can choose to have a label for your device;
  • UUID : a universal unique identifier. This identifier should be unique worldwide and uniquely identify your device;
  • Mountpoint : if your filesystem is mounted, you should be able to see the actual mountpoint.

Awesome, you successfully listed your disks on Linux using “lsblk”.

However, in some cases, you are interested in listing your disks with the actual hardware information linked to it.

If I want to remove a disk from my Linux machine, knowing the actual physical port or the vendor can be quite useful.

List Disks Information using lshw

In order to list disk information on Linux, you have to use the “lshw” with the “class” option specifying “disk”. Combining “lshw” with the “grep” command, you can retrieve specific information about a disk on your system.

$ sudo lshw -class disk

$ sudo lshw -class disk | grep <disk_name> -A 5 -B

lshw-command-linux-1

As you can see, by running the “lshw” with no grep filters, you are presented with all the disks available on your computer.

If you want to target a specific disk on your computer, you can “pipe” the command with “grep” in order to only list the disks that you want.

list-disks-using-lshw-1

As you can see, using this command, you have way more information about your disks : the description, the product and its vendor as well as the actual bus info (where it might be plugged on your mother board).

Using this information, you can unplug it and replace it with another one very easily.

Awesome, you know how to list your disk information using “lshw” now.

Alternatives to lsblk : fdisk or hwinfo

The “lsblk” command is not the only command that you can use in order to have a listing of your disks on Linux. There are two other commands : fdisk (that is often used for partitioning) and hwinfo.

First, if you use the “fdisk” command with the “-l” option, you will be presented with all the partitions available on your machine as well as disks.

$ sudo fdisk -l

fdisk-command

As you can see there, you have a very detailed description of your main disk. You can even verify the partitions available on it as well as the bootable flag for example.

However, “fdisk” is not the only way for you to list disks, you can also use the “hwinfo” command with the “–disk” option.

$ sudo hwinfo --disk

hwinfo-command-linux

Using the “hwinfo” command without any options is quite hard to read. Luckily for you, there is an option that you can use in order to restrict the output to the disk list.

In order to achieve that, you have to use the “–short” option.

$ sudo hwinfo --disk --short

hwinfo-disk

As you can see, the output is quite concise but it gives you a clear idea on disks available.

Finally, for advanced system administrators, you can have a look at the “/dev/disk” folder.

$ ls -l /dev/disk/

dev-disk-folder

In this folder, you can check the “by-id” folder if you are looking for disks or the “by-uuid” one if you are looking for partitions.

$ ls -l /dev/disk/by-id

dev-disk-by-id

List Disk Using Graphical Interface

To list disks on Linux using the graphical interface, you have to go to the “Activities” and look for a program called “Disks”.

activities-menu-linux

When in the “Activities” menu, you can type “Disks” and look for an output similar to the one depicted below.

disks-activity-linux

When clicking on “Disks”, you will be presented with the list of disks available on your Linux machine.

disks-window

As you can see, in the “Disks” window, you have the “hard disk” as well as “block devices” which are the LVM devices that you may have created during the distribution installation.

When clicking on a specific disk, you can see its disk size, the serial number as well as the partitions and the contents that may be stored on it.

Great! You now have the list of disks that are plugged on your computer.

Conclusion

In this tutorial, you learnt how you can easily list your disks on Linux using the “lsblk” command.

You have learnt that the same result can be achieved using many different commands : hwinfo, fdisk or lshw.

If you read this tutorial in order to learn how you can see your disk usage on Linux, you should read our tutorial on the subject.

If you are interested in Linux System Administration, we have a complete section dedicated to it, make sure to have a look.