One place for hosting & domains

      October 2021

      How To Install Suricata on Debian 11


      Not using Debian 11?

      Choose a different version or distribution.


      [**]Suricata is a Network Security Monitoring (NSM) tool that uses sets of community created and user defined signatures (also referred to as rules) to examine and process network traffic. Suricata can generate log events, trigger alerts, and drop traffic when it detects suspicious packets or requests to any number of different services running on a server.

      [**]By default Suricata works as a passive Intrusion Detection System (IDS) to scan for suspicious traffic on a server or network. It will generate and log alerts for further investigation. It can also be configured as an active Intrusion Prevention System (IPS) to log, alert, and completely block network traffic that matches specific rules.

      [**]You can deploy Suricata on a gateway host in a network to scan all incoming and outgoing network traffic from other systems, or you can run it locally on individual machines in either mode.

      [**]In this tutorial you will learn how to install Suricata, and how to customize some of its default settings on Debian 11 to suit your needs. You will also learn how to download existing sets of signatures (usually referred to as rulesets) that Suricata uses to scan network traffic. Finally you’ll learn how to test whether Suricata is working correctly when it detects suspicious requests and data in a response.


      [**]Depending on your network configuration and how you intend to use Suricata, you may need more or less CPU and RAM for your server. Generally, the more traffic you plan to inspect the more resources you should allocate to Suricata. In a production environment plan to use at least 2 CPUs and 4 or 8GB of RAM to start with. From there you can scale up resources according to Suricata’s performance and the amount of traffic that you need to process.

      [**]If you plan to use Suricata to protect the server that it is running on, you will need:

      [**]Otherwise, if you plan to use Suricata on a gateway host to monitor and protect multiple servers, you will need to ensure that the host’s networking is configured correctly.

      [**]If you are using DigitalOcean you can follow this guide on How to Configure a Droplet as a VPC Gateway. Those instructions should work for most Debian and Ubuntu servers as well.

      Step 1 — Installing Suricata

      [**]To get started installing Suricata, you will need to update the list of available packages on your Debian system. You can use the apt update command to do this:

      [**]Now you can install the suricata package using the apt command:

      • sudo apt install suricata

      [**]Now that the package is installed, enable the suricata.service so that it will run when your system restarts. Use the systemctl command to enable it:

      • sudo systemctl enable suricata.service

      [**]You should receive output like the following indicating the service is enabled:


      Synchronizing state of suricata.service with SysV service script with /lib/systemd/systemd-sysv-install. Executing: /lib/systemd/systemd-sysv-install enable suricata . . .

      [**]Before moving on to the next section of this tutorial, which explains how to configure Suricata, stop the service using systemctl:

      • sudo systemctl stop suricata.service

      [**]Stopping Suricata ensures that when you edit and test the configuration file, any changes that you make will be validated and loaded when Suricata starts up again.

      Step 2 — Configuring Suricata For The First Time

      [**]The Suricata package from the OISF repositories ships with a configuration file that covers a wide variety of use cases. The default mode for Suricata is IDS mode, so no traffic will be dropped, only logged. Leaving this mode set to the default is a good idea as you learn Suricata. Once you have Suricata configured and integrated into your environment, and have a good idea of the kinds of traffic that it will alert you about, you can opt to turn on IPS mode.

      [**]However, the default configuration still has a few settings that you may need to change depending on your environment and needs.

      [**]Suricata can include a Community ID field in its JSON output to make it easier to match individual event records to records in datasets generated by other tools.

      [**]If you plan to use Suricata with other tools like Zeek or Elasticsearch, adding the Community ID now is a good idea.

      [**]To enable the option, open /etc/suricata/suricata.yaml using nano or your preferred editor:

      • sudo nano /etc/suricata/suricata.yaml

      [**]Find line 120 which reads # Community Flow ID. If you are using nano type CTRL+_ and then 120 when prompted to enter a line number. Below that line is the community-id key. Set it to true to enable the setting:


      . . .
            # Community Flow ID
            # Adds a 'community_id' field to EVE records. These are meant to give
            # records a predictable flow ID that can be used to match records to
            # output of other tools such as Zeek (Bro).
            # Takes a 'seed' that needs to be same across sensors and tools
            # to make the id less predictable.
            # enable/disable the community id feature.
            community-id: true
      . . .

      [**]Now when you examine events, they will have an ID like 1:S+3BA2UmrHK0Pk+u3XH78GAFTtQ= that you can use to correlate records across different NMS tools.

      [**]Save and close the /etc/suricata/suricata.yaml file. If you are using nano, you can do so with CTRL+X, then Y and ENTER to confirm.

      Determining Which Network Interface(s) To Use

      [**]You may need to override the default network interface or interfaces that you would like Suricata to inspect traffic on. The configuration file that comes with the OISF Suricata package defaults to inspecting traffic on a device called eth0. If your system uses a different default network interface, or if you would like to inspect traffic on more than one interface, then you will need to change this value.

      [**]To determine the device name of your default network interface, you can use the ip command as follows:

      • ip -p -j route show default

      [**]The -p flag formats the output to be more readable, and the -j flag prints the output as JSON.

      [**]You should receive output like the following:


      [ { "dst": "default", "gateway": "", "dev": "eth0", "flags": [ "onlink" ] } ]

      [**]The dev line indicates the default device. In this example output, the device is the highlighted eth0 interface. Your output may show a device name like ens... or eno.... Whatever the name is, make a note of it.

      [**]Now you can edit Suricata’s configuration and verify or change the interface name. Open the /etc/suricata/suricata.yaml configuration file using nano or your preferred editor:

      • sudo nano /etc/suricata/suricata.yaml

      [**]Scroll through the file until you come to a line that reads af-packet: around line 580. If you are using nano you can also go to the line directly by entering CTRL+_ and typing the line number. Below that line is the default interface that Suricata will use to inspect traffic. Edit the line to match your interface like the highlighted example that follows:


      # Linux high speed capture support
        - interface: eth0
          # Number of receive threads. "auto" uses the number of cores
          #threads: auto
          # Default clusterid. AF_PACKET will load balance packets based on flow.
          cluster-id: 99
      . . .

      [**]If you want to inspect traffic on additional interfaces, you can add more - interface: eth... YAML objects. For example, to add a device named enp0s1, scroll down to the bottom of the af-packet section to around line 650. To add a new interface, insert it before the -interface: default section like the following highlighted example:


          #  For eBPF and XDP setup including bypass, filter and load balancing, please
          #  see doc/userguide/capture-hardware/ebpf-xdp.rst for more info.
        - interface: enp0s1
          cluster-id: 98
        - interface: default
          #threads: auto
          #use-mmap: no
          #tpacket-v3: yes

      [**]Be sure to choose a unique cluster-id value for each - interface object.

      [**]Keep your editor open and proceed to the next section where you will configure live rule reloading. If you do not want to enable that setting then you can save and close the /etc/suricata/suricata.yaml file. If you are using nano, you can do so with CTRL+X, then Y and ENTER to confirm.

      Configuring Live Rule Reloading

      [**]Suricata supports live rule reloading, which means you can add, remove, and edit rules without needing to restart the running Suricata process. To enable the live reload option, scroll to the bottom of the configuration file and add the following lines:


      . . .
        - rule-reload: true

      [**]With this setting in place, you will be able to send the SIGUSR2 system signal to the running process, and Suricata will reload any changed rules into memory.

      [**]A command like the following will notify the Suricata process to reload its rulesets, without restarting the process:

      • sudo kill -usr2 $(pidof suricata)

      [**]The $(pidof suricata) portion of the command invokes a subshell, and finds the process ID of the running Suricata daemon. The beginning sudo kill -usr2 part of the command uses the kill utility to send the SIGUSR2 signal to the process ID that is reported back by the subshell.

      [**]You can use this command any time you run suricata-update or when you add or edit your own custom rules.

      [**]Save and close the /etc/suricata/suricata.yaml file. If you are using nano, you can do so with CTRL+X, then Y and ENTER to confirm.

      Step 3 — Updating Suricata Rulesets

      [**]At this point in the tutorial, if you were to start Suricata, you would receive a warning message like the following in the logs that there are no loaded rules:


      <Warning> - [ERRCODE: SC_ERR_NO_RULES(42)] - No rule files match the pattern /var/lib/suricata/rules/suricata.rules

      [**]By default the Suricata package includes a limited set of detection rules (in the /etc/suricata/rules directory), so turning Suricata on at this point would only detect a limited amount of bad traffic.

      [**]Suricata includes a tool called suricata-update that can fetch rulesets from external providers. Run it as follows to download an up to date ruleset for your Suricata server:

      • sudo suricata-update -o /etc/suricata/rules

      [**]The -o /etc/suricata/rules portion of the command instructs the update tool to save the rules to a different directory than its default /var/lib/suricata/rules location. You should receive output like the following:


      19/10/2021 -- 19:31:03 - <Info> -- Using data-directory /var/lib/suricata. 19/10/2021 -- 19:31:03 - <Info> -- Using Suricata configuration /etc/suricata/suricata.yaml 19/10/2021 -- 19:31:03 - <Info> -- Using /etc/suricata/rules for Suricata provided rules. . . . 19/10/2021 -- 19:31:03 - <Info> -- No sources configured, will use Emerging Threats Open 19/10/2021 -- 19:31:03 - <Info> -- Fetching 100% - 3052046/3052046 . . . 19/10/2021 -- 19:31:06 - <Info> -- Writing rules to /etc/suricata/rules/suricata.rules: total: 31063; enabled: 23700; added: 31063; removed 0; modified: 0 19/10/2021 -- 19:31:07 - <Info> -- Writing /etc/suricata/rules/classification.config 19/10/2021 -- 19:31:07 - <Info> -- Testing with suricata -T. 19/10/2021 -- 19:31:32 - <Info> -- Done.

      [**]The highlighted lines indicate suricata-update has fetched the free Emerging Threats ET Open Rules, and saved them to Suricata’s /var/lib/suricata/rules/suricata.rules file. It also indicates the number of rules that were processed, in this example, 31011 were added and of those 23649 were enabled.

      Adding Ruleset Providers

      [**]The suricata-update tool can fetch rules from a variety of free and commercial ruleset providers. Some rulesets like the ET Open set that you already added are available for free, while others require a paid subscription.

      [**]You can list the default set of rule providers using the list-sources flag to suricata-update like this:

      • sudo suricata-update list-sources

      [**]You will receive a list of sources like the following:


      . . . 19/10/2021 -- 19:27:34 - <Info> -- Adding all sources 19/10/2021 -- 19:27:34 - <Info> -- Saved /var/lib/suricata/update/cache/index.yaml Name: et/open Vendor: Proofpoint Summary: Emerging Threats Open Ruleset License: MIT . . .

      [**]For example, if you wanted to include the tgreen/hunting ruleset, you could enable it using the following command:

      • sudo suricata-update enable-source tgreen/hunting -o /etc/suricata/rules

      [**]Then run the suricata-update command with the -o /etc/suricata/rules flag again and the new set of rules will be added, in addition to the existing ET Open rules and any others that you have downloaded.

      Step 4 — Validating Suricata’s Configuration

      [**]Now that you have edited Suricata’s configuration file to include the optional Community ID, specify the default network interface, and enabled live rule reloading, it is a good idea to test the configuration.

      [**]Suricata has a built-in test mode that will check the configuration file and any included rules for validity. Validate your changes from the previous section using the -T flag to run Suricata in test mode. The -v flag will print some additional information, and the -c flag tells Suricata where to find its configuration file:

      • sudo suricata -T -c /etc/suricata/suricata.yaml -v

      [**]The test can take some time depending on the amount of CPU you have allocated to Suricata and the number of rules that you have added, so be prepared to wait for a minute or two for it to complete.

      [**]With the default ET Open ruleset you should receive output like the following:


      21/10/2021 -- 15:00:40 - <Info> - Running suricata under test mode 21/10/2021 -- 15:00:40 - <Notice> - This is Suricata version 6.0.1 RELEASE running in SYSTEM mode 21/10/2021 -- 15:00:40 - <Info> - CPUs/cores online: 2 21/10/2021 -- 15:00:40 - <Info> - fast output device (regular) initialized: fast.log 21/10/2021 -- 15:00:40 - <Info> - eve-log output device (regular) initialized: eve.json 21/10/2021 -- 15:00:40 - <Info> - stats output device (regular) initialized: stats.log 21/10/2021 -- 15:00:46 - <Info> - 1 rule files processed. 23700 rules successfully loaded, 0 rules failed 21/10/2021 -- 15:00:46 - <Info> - Threshold config parsed: 0 rule(s) found 21/10/2021 -- 15:00:47 - <Info> - 23703 signatures processed. 1175 are IP-only rules, 3974 are inspecting packet payload, 18355 inspect application layer, 104 are decoder event only 21/10/2021 -- 15:01:13 - <Notice> - Configuration provided was successfully loaded. Exiting. 21/10/2021 -- 15:01:13 - <Info> - cleaning up signature grouping structure... complete

      [**]If there is an error in your configuration file, then the test mode will generate a specific error code and message that you can use to help troubleshoot. For example, including a rules file that does not exist called test.rules would generate an error like the following:


      21/10/2021 -- 15:10:15 - <Info> - Running suricata under test mode 21/10/2021 -- 15:10:15 - <Notice> - This is Suricata version 6.0.3 RELEASE running in SYSTEM mode 21/10/2021 -- 15:10:15 - <Info> - CPUs/cores online: 2 21/10/2021 -- 15:10:15 - <Info> - eve-log output device (regular) initialized: eve.json 21/10/2021 -- 15:10:15 - <Info> - stats output device (regular) initialized: stats.log 21/10/2021 -- 15:10:21 - <Warning> - [ERRCODE: SC_ERR_NO_RULES(42)] - No rule files match the pattern /etc/suricata/rules/test.rules

      [**]With that error you could then edit your configuration file to include the correct path, or fix invalid variables and configuration options.

      [**]Once your Suricata test mode run completes successfully you can move to the next step, which is starting Suricata in daemon mode.

      Step 5 — Running Suricata

      [**]Now that you have a valid Suricata configuration and ruleset, you can start the Suricata server. Run the following systemctl command:

      • sudo systemctl start suricata.service

      [**]You can examine the status of the service using the systemctl status command:

      • sudo systemctl status suricata.service

      [**]You should receive output like the following:


      ● suricata.service - Suricata IDS/IDP daemon Loaded: loaded (/lib/systemd/system/suricata.service; enabled; vendor preset: enabled) Active: active (running) since Fri 2021-10-29 19:46:02 UTC; 6s ago Docs: man:suricata(8) man:suricatasc(8) Process: 4278 ExecStart=/usr/bin/suricata -D --af-packet -c /etc/suricata/suricata.yaml --pidfile /run/ (code=exited, status=0/SUCCESS) Main PID: 4279 (Suricata-Main) Tasks: 1 (limit: 4678) Memory: 206.0M CPU: 6.273s CGroup: /system.slice/suricata.service └─4279 /usr/bin/suricata -D --af-packet -c /etc/suricata/suricata.yaml --pidfile /run/ Oct 29 19:46:02 suricata systemd[1]: Starting Suricata IDS/IDP daemon... Oct 29 19:46:02 suricata suricata[4278]: 29/10/2021 -- 19:46:02 - <Notice> - This is Suricata version 6.0.1 RELEASE running in SYSTEM mode Oct 29 19:46:02 suricata systemd[1]: Started Suricata IDS/IDP daemon.

      [**]As with the test mode command, it will take Suricata a minute or two to load and parse all of the rules. You can use the tail command to watch for a specific message in Suricata’s logs that indicates it has finished starting:

      • sudo tail -f /var/log/suricata/suricata.log

      [**]You will receive a number of lines of output, and the terminal may appear to be stuck while Suricata loads. Continue waiting for output until you receive a line like the following:


      29/10/2021 -- 19:46:34 - <Info> - All AFP capture threads are running.

      [**]This line indicates Suricata is running and ready to inspect traffic. You can exit the tail command using CTRL+C.

      [**]Now that you have verified that Suricata is running, the next step in this tutorial is to check whether Suricata detects a request to a test URL that is designed to generate an alert.

      Step 6 — Testing Suricata Rules

      [**]The ET Open ruleset that you downloaded contains over 30000 rules. A full explanation of how Suricata rules work, and how to construct them is beyond the scope of this introductory tutorial. A subsequent tutorial in this series will explain how rules work and how to build your own.

      [**]For the purposes of this tutorial, testing whether Suricata is detecting suspicious traffic with the configuration that you generated is sufficient. The Suricata Quickstart recommends testing the ET Open rule with number 2100498 using the curl command.

      [**]Run the following to generate an HTTP request, which will return a response that matches Suricata’s alert rule:

      • curl

      [**]The curl command will output a response like the following:


      uid=0(root) gid=0(root) groups=0(root)

      [**]This example response data is designed to trigger an alert, by pretending to return the output of a command like id that might run on a compromised remote system via a web shell.

      [**]Now you can check Suricata’s logs for a corresponding alert. There are two logs that are enabled with the default Suricata configuration. The first is in /var/log/suricata/fast.log and the second is a machine readable log in /var/log/suricata/eve.log.

      Examining /var/log/suricata/fast.log

      [**]To check for a log entry in /var/log/suricata/fast.log that corresponds to your curl request use the grep command. Using the 2100498 rule identifier from the Quickstart documentation, search for entries that match it using the following command:

      • grep 2100498 /var/log/suricata/fast.log

      [**]If your request used IPv6, then you should receive output like the following, where 2001:DB8::1 is your system’s public IPv6 address:

      [secondary_label] Output
      10/29/2021-19:47:33.631122  [**] [1:2100498:7] GPL ATTACK_RESPONSE id check returned root [**] [Classification: Potentially Bad Traffic] [Priority: 2] {TCP} 2600:9000:2000:4400:0018:30b3:e400:93a1:80 -> 2001:DB8::1:34628

      [**]If your request used IPv4, then your log should have a message like this, where is your system’s public IPv4 address:

      [secondary_label] Output
      10/29/2021-19:48:05.832461  [**] [1:2100498:7] GPL ATTACK_RESPONSE id check returned root [**] [Classification: Potentially Bad Traffic] [Priority: 2] {TCP} ->

      [**]Note the highlighted 2100498 value in the output, which is the Signature ID (sid) that Suricata uses to identify a rule.

      Examining /var/log/suricata/eve.log

      [**]Suricata also logs events to /var/log/suricata/eve.log (nicknamed the EVE log) using JSON to format entries.

      [**]The Suricata documentation recommends using the jq utility to read and filter the entries in this file. Install jq if you do not have it on your system using the following apt command:

      [**]Once you have jq installed, you can filter the events in the EVE log by searching for the 2100498 signature with the following command:

      • jq 'select(.alert .signature_id==2100498)' /var/log/suricata/eve.json

      [**]The command examines each JSON entry and prints any that have an alert object, with a signature_id key that matches the 2100498 value that you are searching for. The output will resemble the following:


      { "timestamp": "2021-10-29T19:48:05.832461+0000", "flow_id": 666167948976574, "in_iface": "eth0", "event_type": "alert", "src_ip": "", "src_port": 80, "dest_ip": "", "dest_port": 38920, "proto": "TCP", "community_id": "1:orJE+IStTM2bjccd9RzqMmjYceE=", "alert": { "action": "allowed", "gid": 1, "signature_id": 2100498, "rev": 7, "signature": "GPL ATTACK_RESPONSE id check returned root", "category": "Potentially Bad Traffic", . . . }

      [**]Note the highlighted "signature_id": 2100498, line, which is the key that jq is searching for. Also note the highlighted "community_id": "1:orJE+IStTM2bjccd9RzqMmjYceE=", line in the JSON output. This key is the generated Community Flow Identifier that you enabled in Suricata’s configuration file.

      [**]Each alert will generate a unique Community Flow Identifier. Other NMS tools can also generate the same identifier to enable cross-referencing a Suricata alert with output from other tools.

      [**]A matching log entry in either log file means that Suricata successfully inspected the network traffic, matched it against a detection rule, and generated an alert for subsequent analysis or logging. A future tutorial in this series will explore how to send Suricata alerts to a Security Incident Event Management (SIEM) system for further processing.

      Step 7 — Handling Suricata Alerts

      [**]Once you have alerts set up and tested, you can choose how you want to handle them. For some use cases, logging alerts for auditing purposes may be sufficient; or you may prefer to take a more active approach to blocking traffic from systems that generate repeated alerts.

      [**]If you would like to block traffic based on the alerts that Suricata generates, one approach is to use entries from the EVE log and then add firewall rules to restrict access to your system or systems. You can use the jq tool to extract specific fields from an alert, and then add UFW or IPtables rules to block requests.

      [**]Again, this example is a hypothetical scenario using deliberately crafted request and response data. Your knowledge of the systems and protocols that your environment should be able to access is essential in order to determine which traffic is legitimate and which can be blocked.


      [**]In this tutorial you installed Suricata from the OISF software repositories. Installing Suricata this way ensures that you can receive updates whenever a new version of Suricata is released. After installing Suricata you edited the default configuration to add a Community Flow ID for use with other security tools. You also enabled live rule reloading, and downloaded an initial set of rules.

      [**]Once you validated Suricata’s configuration, you started the process and generated some test HTTP traffic. You verified that Suricata could detect suspicious traffic by examining both of the default logs to make sure they contained an alert corresponding to the rule you were testing.

      [**]For more information about Suricata, visit the official Suricata Site. For more details on any of the configuration options that you configured in this tutorial, refer to the Suricata User Guide.

      [**]Now that you have Suricata installed and configured, you can continue to the next tutorial in this series (forthcoming) where you’ll explore how to write your own custom Suricata rules. You’ll learn about different ways to create alerts, or even how to drop traffic entirely, based on criteria like invalid TCP/IP packets, the contents of DNS queries, HTTP requests and responses, and even TLS handshakes.

      Source link

      Initial Server Setup with Debian 11

      Not using Debian 11?

      Choose a different version or distribution.


      When you first create a new Debian 11 server, there are a few configuration steps that you should take early on as part of the basic setup. This will increase the security and usability of your server and will give you a solid foundation for subsequent actions.

      In this tutorial, we will learn how to log into our server as the root user, create a new user with admin privileges, and set up a basic firewall.

      Step 1 — Logging in as Root

      To log into your server, you will need to know your server’s public IP address. You will also need the password or, if you installed an SSH key for authentication, the private key for the root user’s account. If you have not already logged into your server, you may want to follow our guide on how to connect to your Droplet with SSH, which covers this process in detail.

      If you are not already connected to your server, go ahead and log in as the root user using the following command (substitute the highlighted portion of the command with your server’s public IP address):

      Accept the warning about host authenticity if it appears. If you are using password authentication, provide your root password to log in. If you are using an SSH key that is passphrase protected, you may be prompted to enter the passphrase the first time you use the key each session. If this is your first time logging into the server with a password, you may also be prompted to change the root password.

      About Root

      The root user is the administrative user in a Linux environment that has very broad privileges. Because of the heightened privileges of the root account, you are discouraged from using it on a regular basis. This is because part of the power inherent with the root account is the ability to make very destructive changes, even by accident.

      The next step is to set up an alternative user account with a reduced scope of influence for day-to-day work. Later, we’ll explain how to gain increased privileges for those times when you need them.

      Step 2 — Creating a New User

      Once you are logged in as root, we’re prepared to add the new user account that we will use to log in from now on.

      This example creates a new user called sammy, but you should replace it with a username that you like:

      You will be asked a few questions, starting with the account password.

      Enter a strong password and, optionally, fill in any of the additional information you would like. This is not required and you can just hit ENTER in any field you wish to skip.

      Next, we’ll set up this new user with admin privileges.

      Step 3 — Granting Administrative Privileges

      Now, we have created a new user account with regular account privileges. However, we may sometimes need to do administrative tasks with it.

      To avoid having to log out of our normal user and log back in as the root account, we can set up what is known as superuser or root privileges for our normal account. This will allow our normal user to run commands with administrative privileges by putting the word sudo before the command.

      To add these privileges to our new user, we need to add the new user to the sudo group. By default, on Debian 11, users who belong to the sudo group are allowed to use the sudo command.

      As root, run this command to add your new user to the sudo group (substitute the highlighted word with your new user):

      Now, when logged in as your regular user, you can type sudo before commands to run the command with superuser privileges.

      Step 4 — Setting Up a Basic Firewall

      Debian servers can use firewalls to make sure only certain connections to specific services are allowed. In this guide, we will install and use the UFW firewall to help set firewall policies and manage exceptions.

      We can use the apt package manager to install UFW. Update the local index to retrieve the latest information about available packages and then install the UFW firewall software by typing:

      • apt update
      • apt install ufw

      Note: If your servers are running on DigitalOcean, you can optionally use DigitalOcean Cloud Firewalls instead of the UFW firewall. We recommend using only one firewall at a time to avoid conflicting rules that may be difficult to debug.

      Firewall profiles allow UFW to manage named sets of firewall rules for installed applications. Profiles for some common software are bundled with UFW by default and packages can register additional profiles with UFW during the installation process. OpenSSH, the service allowing us to connect to our server now, has a firewall profile that we can use.

      You list all available application profiles by typing:


      Available applications: . . . OpenSSH . . .

      We need to make sure that the firewall allows SSH connections so that we can log back in next time. We can allow these connections by typing:

      Afterwards, we can enable the firewall by typing:

      Type y and press ENTER to proceed. You can see that SSH connections are still allowed by typing:


      Status: active To Action From -- ------ ---- OpenSSH ALLOW Anywhere OpenSSH (v6) ALLOW Anywhere (v6)

      As the firewall is currently blocking all connections except for SSH, if you install and configure additional services, you will need to adjust the firewall settings to allow acceptable traffic in. You can learn some common UFW operations in our UFW essentials guide.

      Step 5 — Enabling External Access for Your Regular User

      Now that we have a regular user for daily use, we need to make sure we can SSH into the account directly.

      Note: Until verifying that you can log in and use sudo with your new user, we recommend staying logged in as root. This way, if you have problems, you can troubleshoot and make any necessary changes as root. If you are using a DigitalOcean Droplet and experience problems with your root SSH connection, you can also log into the Droplet using the DigitalOcean Console.

      The process for configuring SSH access for your new user depends on whether your server’s root account uses a password or SSH keys for authentication.

      If the Root Account Uses Password Authentication

      If you logged in to your root account using a password, then password authentication is enabled for SSH. You can SSH to your new user account by opening up a new terminal session and using SSH with your new username:

      After entering your regular user’s password, you will be logged in. Remember, if you need to run a command with administrative privileges, type sudo before it like this:

      You will be prompted for your regular user password when using sudo for the first time each session (and periodically afterwards).

      To enhance your server’s security, we strongly recommend setting up SSH keys instead of using password authentication. Follow our guide on setting up SSH keys on Debian 11 to learn how to configure key-based authentication.

      If the Root Account Uses SSH Key Authentication

      If you logged in to your root account using SSH keys, then password authentication is disabled for SSH. You will need to add a copy of your local public key to the new user’s ~/.ssh/authorized_keys file to log in successfully.

      Since your public key is already in the root account’s ~/.ssh/authorized_keys file on the server, we can copy that file and directory structure to our new user account in our existing session with the cp command. Afterwards, we can adjust ownership of the files using the chown command.

      Make sure to change the highlighted portions of the command below to match your regular user’s name:

      • cp -r ~/.ssh /home/sammy
      • chown -R sammy:sammy /home/sammy/.ssh

      The cp -r command copies the entire directory to the new user’s home directory, and the chown -R command changes the owner of that directory (and everything inside it) to the specified username:groupname (Debian creates a group with the same name as your username by default).

      Now, open up a new terminal session and log in via SSH with your new username:

      You should be logged in to the new user account without using a password. Remember, if you need to run a command with administrative privileges, type sudo before it like this:

      You will be prompted for your regular user password when using sudo for the first time each session (and periodically afterwards).

      Where To Go From Here?

      At this point, you have a solid foundation for your server. You can install any of the software you need on your server now.

      Source link

      How to Set Up SSH Keys on Debian 11

      Not using Debian 11?

      Choose a different version or distribution.


      SSH, or secure shell, is an encrypted protocol used to administer and communicate with servers. When working with a Debian server, chances are you will spend most of your time in a terminal session connected to your server through SSH.

      In this guide, we’ll focus on setting up SSH keys for a vanilla Debian 11 installation. SSH keys provide an easy, secure way of logging into your server and are recommended for all users.

      Step 1 — Create the RSA Key Pair

      The first step is to create a key pair on the client machine (usually your computer):

      By default ssh-keygen will create a 3072-bit RSA key pair, which is secure enough for most use cases (you may optionally pass in the -b 4096 flag to create a larger 4096-bit key).

      After entering the command, you should see the following output:


      Generating public/private rsa key pair. Enter file in which to save the key (/your_home/.ssh/id_rsa):

      Press enter to save the key pair into the .ssh/ subdirectory in your home directory, or specify an alternate path.

      If you had previously generated an SSH key pair, you may see the following prompt:


      /home/your_home/.ssh/id_rsa already exists. Overwrite (y/n)?

      Warning: If you choose to overwrite the key on disk, you will not be able to authenticate using the previous key anymore. Be very careful when selecting yes, as this is a destructive process that cannot be reversed.

      You should then see the following prompt:


      Enter passphrase (empty for no passphrase):

      Here you optionally may enter a secure passphrase, which is highly recommended. A passphrase adds an additional layer of security to prevent unauthorized users from logging in. To learn more about security, consult our tutorial on How To Configure SSH Key-Based Authentication on a Linux Server.

      You should then see the following output:


      Your identification has been saved in /your_home/.ssh/id_rsa. Your public key has been saved in /your_home/.ssh/ The key fingerprint is: SHA256:5E2BtTN9FHPBNoRXAB/EdjtHNYOHzTBzG5qUv7S3hyM root@debian-suricata The key's randomart image is: +---[RSA 3072]----+ | oo .O^XB| | . +.BO%B| | . = .+B+o| | o o o . =.| | S . . =| | o.| | .o| | E o..| | . ..| +----[SHA256]-----+

      You now have a public and private key that you can use to authenticate. The next step is to place the public key on your server so that you can use SSH-key-based authentication to log in.

      Step 2 — Copy the Public Key to Debian Server

      The quickest way to copy your public key to the Debian host is to use a utility called ssh-copy-id. Due to its simplicity, this method is highly recommended if available. If you do not have ssh-copy-id available to you on your client machine, you may use one of the two alternate methods provided in this section (copying via password-based SSH, or manually copying the key).

      Copying Public Key Using ssh-copy-id

      The ssh-copy-id tool is included by default in many operating systems, so you may have it available on your local system. For this method to work, you must already have password-based SSH access to your server.

      To use the utility, you simply need to specify the remote host that you would like to connect to and the user account that you have password SSH access to. This is the account to which your public SSH key will be copied.

      The syntax is:

      • ssh-copy-id username@remote_host

      You may see the following message:


      The authenticity of host ' (' can't be established. ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe. Are you sure you want to continue connecting (yes/no)? yes

      This means that your local computer does not recognize the remote host. This will happen the first time you connect to a new host. Type “yes” and press ENTER to continue.

      Next, the utility will scan your local account for the key that we created earlier. When it finds the key, it will prompt you for the password of the remote user’s account:


      /usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed /usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys username@'s password:

      Type in the password (your typing will not be displayed for security purposes) and press ENTER. The utility will connect to the account on the remote host using the password you provided. It will then copy the contents of your ~/.ssh/ key into a file in the remote account’s home ~/.ssh directory called authorized_keys.

      You should see the following output:


      Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'username@'" and check to make sure that only the key(s) you wanted were added.

      At this point, your key has been uploaded to the remote account. You can continue on to Step 3.

      Copying Public Key Using SSH

      If you do not have ssh-copy-id available, but you have password-based SSH access to an account on your server, you can upload your keys using a conventional SSH method.

      We can do this by using the cat command to read the contents of the public SSH key on our local computer and piping that through an SSH connection to the remote server.

      On the other side, we can make sure that the ~/.ssh directory exists and has the correct permissions under the account we’re using.

      We can then output the content we piped over into a file called authorized_keys within this directory. We’ll use the >> redirect symbol to append the content instead of overwriting it. This will let us add keys without destroying previously added keys.

      The full command looks like this:

      • cat ~/.ssh/ | ssh username@remote_host "mkdir -p ~/.ssh && touch ~/.ssh/authorized_keys && chmod -R go= ~/.ssh && cat >> ~/.ssh/authorized_keys"

      You may see the following message:


      The authenticity of host ' (' can't be established. ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe. Are you sure you want to continue connecting (yes/no)? yes

      This means that your local computer does not recognize the remote host. This will happen the first time you connect to a new host. Type “yes” and press ENTER to continue.

      Afterwards, you should be prompted to enter the remote user account password:


      username@'s password:

      After entering your password, the content of your key will be copied to the end of the authorized_keys file of the remote user’s account. Continue on to Step 3 if this was successful.

      Copying Public Key Manually

      If you do not have password-based SSH access to your server available, you will have to complete the above process manually.

      We will manually append the content of your file to the ~/.ssh/authorized_keys file on your remote machine.

      To display the content of your key, type this into your local computer:

      You will see the key’s content, which should look something like this:


      ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDgkLJ8d2gGEJCN7xdyVaDqk8qgeZqQ0MlfoPK3TzWI5dkG0WiZ16jrkiW/h6lhO9K1w89VDMnmNN9ULOWHrZMNs//Qyv/oN+FLIgK2CkKXRxTmbh/ZGnqOm3Zo2eU+QAmjb8hSsstQ3DiuGu8tbiWmsa3k3jKbWNWpXqY3Q88t+bM1DZrHwYzaIZ1BSA1ghqHCvIZqeP9IUL2l2DUfSCT9LXJEgMQhgjakJnzEGPgd5VHMR32rVrbIbbDzlyyoZ7SpCe5y0vYvbV2JKWI/8SEOmwehEHJ9RBZmciwc+1sdEcAJVMDujb9p5rX4hyvFpG0KGhZesB+/s7PdOa8zlIg4TZhXUHl4t1jpPC83Y9KEwS/Ni4dhaxlnr3T6l5hUX2cD+eWl1vVpogBqKNGBMrVR4dWs3Z4BVUf9exqTRRYOfgo0UckULqW5pmLW07JUuGo1kpFAxpDBPFWoPsg08CGRdEUS7ScRnMK1KdcH54kUZr0O88SZOsv9Zily/A5GyNM= demo@test

      Access your remote host using whichever method you have available.

      Once you have access to your account on the remote server, you should make sure the ~/.ssh directory exists. This command will create the directory if necessary, or do nothing if it already exists:

      Now, you can create or modify the authorized_keys file within this directory. You can add the contents of your file to the end of the authorized_keys file, creating it if necessary, using this command:

      • echo public_key_string >> ~/.ssh/authorized_keys

      In the above command, substitute the public_key_string with the output from the cat ~/.ssh/ command that you executed on your local system. It should start with ssh-rsa AAAA....

      Finally, we’ll ensure that the ~/.ssh directory and authorized_keys file have the appropriate permissions set:

      This recursively removes all “group” and “other” permissions for the ~/.ssh/ directory.

      If you’re using the root account to set up keys for a user account, it’s also important that the ~/.ssh directory belongs to the user and not to root:

      • chown -R sammy:sammy ~/.ssh

      In this tutorial our user is named sammy but you should substitute the appropriate username into the above command.

      You can now attempt passwordless authentication with your Debian server.

      Step 3 — Authenticate to Debian Server Using SSH Keys

      If you have successfully completed one of the procedures above, you should be able to log into the remote host without the remote account’s password.

      The general process is the same:

      If this is your first time connecting to this host (if you used the last method above), you may see something like this:


      The authenticity of host ' (' can't be established. ECDSA key fingerprint is fd:fd:d4:f9:77:fe:73:84:e1:55:00:ad:d6:6d:22:fe. Are you sure you want to continue connecting (yes/no)? yes

      This means that your local computer does not recognize the remote host. Type “yes” and then press ENTER to continue.

      If you did not supply a passphrase for your private key, you will be logged in immediately. If you supplied a passphrase for the private key when you created the key, you will be prompted to enter it now (note that your keystrokes will not display in the terminal session for security). After authenticating, a new shell session should open for you with the configured account on the Debian server.

      If key-based authentication was successful, continue on to learn how to further secure your system by disabling password authentication.

      Step 4 — Disable Password Authentication on your Server

      If you were able to log into your account using SSH without a password, you have successfully configured SSH-key-based authentication to your account. However, your password-based authentication mechanism is still active, meaning that your server is still exposed to brute-force attacks.

      Before completing the steps in this section, make sure that you either have SSH-key-based authentication configured for the root account on this server, or preferably, that you have SSH-key-based authentication configured for a non-root account on this server with sudo privileges. This step will lock down password-based logins, so ensuring that you will still be able to get administrative access is crucial.

      Once you’ve confirmed that your remote account has administrative privileges, log into your remote server with SSH keys, either as root or with an account with sudo privileges. Then, open up the SSH daemon’s configuration file:

      • sudo nano /etc/ssh/sshd_config

      Inside the file, search for a directive called PasswordAuthentication. This may be commented out. Uncomment the line and set the value to “no”. This will disable your ability to log in via SSH using account passwords:


      PasswordAuthentication no

      Save and close the file when you are finished by pressing CTRL + X, then Y to confirm saving the file, and finally ENTER to exit nano. To actually implement these changes, we need to restart the sshd service:

      • sudo systemctl restart ssh

      As a precaution, open up a new terminal window and test that the SSH service is functioning correctly before closing this session:

      Once you have verified your SSH service, you can safely close all current server sessions.

      The SSH daemon on your Debian server now only responds to SSH keys. Password-based authentication has successfully been disabled.


      You should now have SSH-key-based authentication configured on your server, allowing you to sign in without providing an account password.

      If you’d like to learn more about working with SSH, take a look at our SSH Essentials Guide.

      Source link