How To Install and Secure Redis 7.0 on Ubuntu 23.04 / Debian – In-memory Caching System

By | October 12, 2023

Redis (Remote Dictionary Server) is an open-source software used to store structured data, which can be used as a database, cache, or message broker. It is known for its speed and versatility. In this article, you will be guided through the process of installing and securing Redis on an Ubuntu machine.

Installation

1. Prerequisites

There are some prerequisites to running the installation.

  • An account with sudo privileges
  • Ensuring that your server's package list is up-to-date and all installed packages are upgraded to the latest versions

The following command helps you update and upgrade the package:

sudo apt update
sudo apt upgrade

2. Installing Redis

The default repositories of Ubuntu include a package for Redis, which makes installation straightforward. To install Redis, run the following command:

$ sudo apt install redis-server
…
Selecting previously unselected package redis-tools.
Preparing to unpack .../4-redis-tools_5%3a6.0.16-1ubuntu1_amd64.deb ...
Unpacking redis-tools (5:6.0.16-1ubuntu1) ...
Selecting previously unselected package redis-server.
Preparing to unpack .../5-redis-server_5%3a6.0.16-1ubuntu1_amd64.deb ...
Unpacking redis-server (5:6.0.16-1ubuntu1) ...
Setting up libjemalloc2:amd64 (5.2.1-4ubuntu1) ...
Setting up lua-cjson:amd64 (2.1.0+dfsg-2.1) ...
Setting up lua-bitop:amd64 (1.0.2-5) ...
Setting up liblua5.1-0:amd64 (5.1.5-8.1build4) ...
Setting up redis-tools (5:6.0.16-1ubuntu1) ...
Setting up redis-server (5:6.0.16-1ubuntu1) ...
Created symlink /etc/systemd/system/redis.service → /lib/systemd/system/redis-server.service.
Created symlink /etc/systemd/system/multi-user.target.wants/redis-server.service → /lib/systemd/system/redis-server.service.
Processing triggers for man-db (2.10.2-1) ...
Processing triggers for libc-bin (2.35-0ubuntu3.1) ...
…

After the installation is complete, you can check its status by running the below command.

$ sudo systemctl status redis
● redis-server.service - Advanced key-value store
     Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2023-09-10 15:10:03 +07; 21s ago
       Docs: http://redis.io/documentation,
             man:redis-server(1)
   Main PID: 2558 (redis-server)
     Status: "Ready to accept connections"
      Tasks: 5 (limit: 4542)
     Memory: 2.7M
        CPU: 107ms
     CGroup: /system.slice/redis-server.service
             └─2558 "/usr/bin/redis-server 127.0.0.1:6379" "" "" "" "" "" "" "" "" "" "" "" "" "" "" >

Sep 10 15:10:03 Ubuntu-01 systemd[1]: Starting Advanced key-value store...
Sep 10 15:10:03 Ubuntu-01 systemd[1]: Started Advanced key-value store.

Check version: You can check the version of the installed redis package with the redis-cli command line utility

$ redis-cli --version
redis-cli 7.0.8
$

To learn more about the cli utility run the help option:

redis-cli --help

Configuring and Securing Redis from potential threats

Redis comes with a default configuration that is reasonably secure for most use cases. However, it's always better to make a few adjustments to enhance security.

1. Bind to Specific IP Address

By default, Redis binds to all available network interfaces. To make Redis more secure, consider binding it to a specific IP address, especially if your server has multiple network interfaces.

First, locate the Redis configuration file and modify it (sudo privileges) with any editor (GNU Emacs, vim, nano, etc.) with the following file path:

/etc/redis/redis.conf

Then, find the following line and change it to bind to a specific IP address (e.g., your server's private IP):

bind 127.0.0.1

Replace 127.0.0.1 with your server's private IP address within the "Network" part of the configuration. For example:

…
################################## MODULES #####################################

# Load modules at startup. If the server is not able to load modules
# it will abort. It is possible to use multiple loadmodule directives.
#
# loadmodule /path/to/my_module.so
# loadmodule /path/to/other_module.so

################################## NETWORK #####################################

# By default, if no "bind" configuration directive is specified, Redis listens
# for connections from all available network interfaces on the host machine.
# It is possible to listen to just one or multiple selected interfaces using
# the "bind" configuration directive, followed by one or more IP addresses.
#
# Examples:
#
# bind 192.168.1.100 10.0.0.1
# bind 127.0.0.1 ::1
bind 192.168.200.3
#
# ~~~ WARNING ~~~ If the computer running Redis is directly exposed to the
# internet, binding to all the interfaces is dangerous and will expose the
# instance to everybody on the internet. So by default we uncomment the
# following bind directive, that will force Redis to listen only on the
# IPv4 loopback interface address (this means Redis will only be able to
# accept client connections from the same host that it is running on).
#
# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES
# JUST COMMENT OUT THE FOLLOWING LINE.
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# bind 127.0.0.1 ::1

# Protected mode is a layer of security protection, in order to avoid that
# Redis instances left open on the internet are accessed and exploited.
#
# When protected mode is on and if:
#
# 1) The server is not binding explicitly to a set of addresses using the
#    "bind" directive.
# 2) No password is configured.
#
# The server only accepts connections from clients connecting from the
# IPv4 and IPv6 loopback addresses 127.0.0.1 and ::1, and from Unix domain
# sockets.
#
# By default protected mode is enabled. You should disable it only if
# you are sure you want clients from other hosts to connect to Redis
# even if no authentication is configured, nor a specific set of interfaces
# are explicitly listed using the "bind" directive.
protected-mode no

# Accept connections on the specified port, default is 6379 (IANA #815344).
# If port 0 is specified Redis will not listen on a TCP socket.
port 6379

# TCP listen() backlog.
#
# In high requests-per-second environments you need a high backlog in order
# to avoid slow clients connection issues. Note that the Linux kernel
# will silently truncate it to the value of /proc/sys/net/core/somaxconn so
# make sure to raise both the value of somaxconn and tcp_max_syn_backlog
# in order to get the desired effect.
tcp-backlog 511

# Unix socket.
#
# Specify the path for the Unix socket that will be used to listen for
# incoming connections. There is no default, so Redis will not listen
# on a unix socket when not specified.
#
# unixsocket /var/run/redis/redis-server.sock
# unixsocketperm 700

# Close the connection after a client is idle for N seconds (0 to disable)
timeout 0

# TCP keepalive.
#
# If non-zero, use SO_KEEPALIVE to send TCP ACKs to clients in absence
# of communication. This is useful for two reasons:
#
# 1) Detect dead peers.
# 2) Force network equipment in the middle to consider the connection to be
#    alive.
#
# On Linux, the specified value (in seconds) is the period used to send ACKs.
# Note that to close the connection the double of the time is needed.
# On other kernels the period depends on the kernel configuration.
#
# A reasonable value for this option is 300 seconds, which is the new
# Redis default starting with Redis 3.2.1.
tcp-keepalive 300
…

After making configuration changes, remember to save the file. You will need to restart the Redis service to apply any changes.

$ sudo systemctl restart redis

2. Set a strong authentication password

By default, Redis does not require authentication. You can enhance security by mandating a strong password, which is located in the line "requirepass foobared" in the Redis configuration file (/etc/redis/redis.conf).

# requirepass foobared
requirepass MyN3wp4s5

Replace the string "foobared" with a strong password. The new password in the above example is "MyN3wp4s5". Also, you will need to restart the Redis service to apply any changes.

3. Disable Remote Access

In case you don't want remote access to your Redis server, you can enable the protected mode in the Redis configuration file (/etc/redis/redis.conf) by running the following command:

protected-mode yes

4. Test the Installation

To ensure that Redis is running correctly, try connecting to it using the 'redis-cli' tool. By default, the command will connect to the server at the IP address 127.0.0.1 with port 6379.

As you have changed the binding setting above, you will need to use it with option '-h' to specify a different host name or an IP address. For example:

$ redis-cli -h 192.168.200.3
192.168.200.3:6379>
192.168.200.3:6379> AUTH MyN3wp4s5
OK
192.168.200.3:6379> ping
PONG

If you set a password in the configuration file, use it to authenticate with the 'AUTH' command unless you will receive an error like below:

192.168.200.3:6379> CONFIG get requirepass
(error) NOAUTH Authentication required.

5. Change the Redis Default Port

By default, Redis listens on port 6379. You should change the default port to add an extra layer of security, as attackers often target well-known ports. To change the port, edit the Redis configuration file (/etc/redis/redis.conf) and modify the port directive as follows:

# port 6379
port 63001

Replace 63001 with your desired port number. Afterward, restart Redis to apply the changes and use 'redis-cli' with option '-p' to connect to specific port:

$ sudo systemctl restart redis
$ systemctl status redis
● redis-server.service - Advanced key-value store
     Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)
     Active: active (running) since Mon 2023-09-10 17:34:42 +07; 4s ago
       Docs: http://redis.io/documentation,
             man:redis-server(1)
   Main PID: 2777 (redis-server)
     Status: "Ready to accept connections"
      Tasks: 5 (limit: 4551)
     Memory: 2.7M
        CPU: 90ms
     CGroup: /system.slice/redis-server.service
             └─2777 "/usr/bin/redis-server 192.168.200.3:63001" "" "" "" "" "" "" "" "" "" "" "" "" ">

៩ 10 17:34:42 Ubuntu-01 systemd[1]: Starting Advanced key-value store...
៩ 10 17:34:42 Ubuntu-01 systemd[1]: Started Advanced key-value store.

$ redis-cli -h 192.168.200.3 -p 63001
192.168.200.3:63001>

6. Restrict access to Redis with firewall rules

Method 1: Restriction using 'firewalld'

Define new Redis zone to firewalld policy.

$ sudo firewall-cmd --permanent --new-zone=redis
success

Then, specify which port you'd like to open. Redis uses port 6379 by default; you can replace it with your Redis port number. For example, in this case, we use 63001.

$ sudo firewall-cmd --permanent --zone=redis --add-port=63001/tcp
success

Next, specify any source. This example will use IP address '192.168.200.1' as source, which should be allowed to pass through the firewalld and access Redis.

$ sudo firewall-cmd --permanent --zone=redis --add-source=192.168.200.1
success

Remember to reload the firewall to implement the new rules.

$ sudo firewall-cmd --reload
success

You can check the active zone of 'firewalld' by executing the following command:

$ sudo firewall-cmd --get-active-zones
public
   interfaces: ens33
redis
   source: 192.168.200.1

And list detailed information on the Redis zone.

$ sudo firewall-cmd --list-all --zones=redis
redis (active)
  target: default
  icmp-block-inversion: no
  interfaces:
  sources: 192.168.200.1
  services: 
  ports: 63001/tcp
  protocols:
  forward: no
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

To explain this configuration, when the firewall encounters a packet from an IP address (192.168.200.1), it will apply the rules in the Redis zone to that connection. The other connections will be processed by the default public zone.

Method 2: Restrict access by using UFW (Uncomplicated Firewall)

You can try other firewall methods by using UFW to only allow trusted IP addresses or networks to connect to the Redis port. For example, to allow access only from a specific IP address, '192.168.200.1', use the following command:

$ sudo ufw allow from 192.168.200.1 to any port 63001
Rule added

Replace 63001 with your Redis port number. Then, check if the firewall rule is set correctly with the following command:

$ sudo ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), deny (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
22/tcp                     ALLOW IN    Anywhere
8080/tcp                   ALLOW IN    Anywhere
8081/tcp                   ALLOW IN    Anywhere
443                        ALLOW IN    Anywhere
80/tcp                     ALLOW IN    Anywhere
6069/tcp                   ALLOW IN    Anywhere
6069/udp                   ALLOW IN    Anywhere
63001                      ALLOW IN    192.168.200.1
22/tcp (v6)                ALLOW IN    Anywhere (v6)
8080/tcp (v6)              ALLOW IN    Anywhere (v6)
8081/tcp (v6)              ALLOW IN    Anywhere (v6)
443 (v6)                   ALLOW IN    Anywhere (v6)
80/tcp (v6)                ALLOW IN    Anywhere (v6)
6069/tcp (v6)              ALLOW IN    Anywhere (v6)
6069/udp (v6)              ALLOW IN    Anywhere (v6)

7. Monitor Redis Logs

Redis logs are located in the path "/var/log/redis/redis-server.log". You should regularly review for suspicious activities or unauthorized access attempts.

You can review this file by using 'cat' command:

$ cat /var/log/redis/redis-server.log
[term]

or monitoring it in real-time with <strong>'tail'</strong> command (and option <strong>'-f'</strong> or <strong>'--follow'</strong>) by following:

[term]
$ tail -f /var/log/redis/redis-server.log
[term]

Configure log rotation to manage log files efficiently and ensure they don't consume excessive disk space. You can use 'Logrotate', which is installed on Ubuntu by default for the Redis log rotation. It is defined in the file /etc/logrotate.d/redis-server. 
 
[term]
$ sudo nano /etc/logrotate.d/redis-server
/var/log/redis/redis-server*.log {
        weekly
        missingok
        rotate 12
        compress
        notifempty
}
[term]

The lines in the curly brackets define how to rotate the log in the directory. 

<ul>
	<li><strong>weekly:</strong> Logs are rotated every week. Alternatively, you can specify another time interval (hourly, daily, weekly, monthly, or yearly).</li>
	<li><strong>missingok:</strong> Daemon does not report any error if the log file is missing.</li>
	<li><strong>rotate 12:</strong> Log files are rotated 12 times before being removed. If this value is set to 'rotate 0', then old versions will be removed rather than rotated.</li>
	<li><strong>compress:</strong> Old versions of log files are compressed with 'gzip' by default.</li>
	<li><strong>notifempty:</strong> Do not rotate the log if it is empty.</li>
</ul>

<h4>8. Keep Redis and your Ubuntu machine up-to-date</h4>

Security vulnerabilities can be discovered anytime. To keep both your Redis installation and Ubuntu system up-to-date, you should apply security updates and patches regularly to be protected against known vulnerabilities. The latest Redis version is public on <a href="https://redis.io/download/">Download | Redis</a>.

To check your current version of Redis, run the below command:

[term]
$ redis-cli --version

9. Backup and Restore

The other way to enhance the security and resilience of your Redis data is implementing regular backup data and ensuring that you can restore it in case of data loss or security incidents.

Redis data are located at path "/var/lib/redis/dump.rdb". You can back up or copy the database file while the Redis server is running using the following steps:

Access Redis by 'redis-cli' tool and save current data.

$ redis-cli -h 192.168.200.3 -p 63001
192.168.200.3:63001>
192.168.200.3:63001> AUTH MyN3wp4s5
OK
192.168.200.3:63001>save
OK

Then, copy the current data file, dump.rdp, to the backup directory you want to store.

$ sudo cp /var/lib/redis/dump.rdb /home/jayce/redis/backup/14Sep2023/dump.rdp

You can use any automated backup tools available for your Ubuntu machine to schedule backup Redis data as per your plan.

To restore Redis data from a backup file, follow the example below:

Stop Redis services. This also stops the running instance.

$ service redis-server stop
$ service redis-server status
○ redis-server.service - Advanced key-value store
     Loaded: loaded (/lib/systemd/system/redis-server.service; enabled; vendor preset: enabled)
     Active: inactive (dead) since Thu 2023-09-15 23:11:08 +07; 3s ago
       Docs: http://redis.io/documentation,
             man:redis-server(1)
    Process: 844 ExecStart=/usr/bin/redis-server /etc/redis/redis.conf --supervised systemd --daemoni>
   Main PID: 844 (code=exited, status=0/SUCCESS)
     Status: "Saving the final RDB snapshot"
        CPU: 2.148s

៩ 15 22:39:43 Ubuntu-01 systemd[1]: Starting Advanced key-value store...
៩ 15 22:39:44 Ubuntu-01 systemd[1]: Started Advanced key-value store.
៩ 15 23:11:08 Ubuntu-01 systemd[1]: Stopping Advanced key-value store...
៩ 15 23:11:08 Ubuntu-01 systemd[1]: redis-server.service: Deactivated successfully.
៩ 15 23:11:08 Ubuntu-01 systemd[1]: Stopped Advanced key-value store.
៩ 15 23:11:08 Ubuntu-01 systemd[1]: redis-server.service: Consumed 2.148s CPU time.

Rename the current data file.

$ sudo mv /var/lib/redis/dump.rdb /var/lib/redis/dump.rdb.corrupted

Make sure AOF (Append-only file) is disabled on the Redis configuration file (/etc/redis/redis.conf).

appendonly no

Copy the file from the backup directory created in the previous example by using 'cp' command with option '-p'.

$ sudo cp -p /home/jayce/redis/backup/14Sep2023/dump.rdp /var/lib/redis/dump.rdb

Make sure the permission of the new restore file is the same as the old data file.

ls -lha /var/lib/redis/
total 12K
drwxr-x---  2 redis redis 4.0K ៩  28 23:23 .
drwxr-xr-x 72 root  root  4.0K ៩  28 22:06 ..
-rw-rw----  1 redis redis   93 ៩  28 23:11 dump.rdb
-rw-rw----  1 root  root     97 ៩  28 23:21 dump.rdb.corrupted

Start the Redis services to bring it back.

$ service redis-server start

Conclusion

Keep learning about the best security practices by following Redis security guidelines on Security | Redis Documentation Center. It will help you keep yourself up-to-date with the latest security recommendations. Hopefully, you enjoyed and will have more knowledge in setting up and securing your Redis server by going through the examples explained in this article.

About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].

Leave a Reply

Your email address will not be published. Required fields are marked *