Oct 19, 2023 12 min read

How To Install and Secure Redis on Rocky Linux 8

Install and secure Redis on Rocky Linux 8 with our step-by-step tutorial. It is an in-memory data structure store used as a database, cache etc.

Install and Secure Redis on Rocky Linux 8
Table of Contents

Choose a different version or distribution

Introduction

Before we begin talking about how to install and secure redis on rocky Linux 8,let's briefly understand-What is Redis?

Redis is a data structure store that runs in memory and is used as a database, cache, and message broker. It provides fast performance, high availability, and a wide range of data structures, making it useful in various scenarios.

This tutorial will walk you through the steps to install and secure Redis on Rocky Linux 8. We will also address a few FAQs on how to install and secure redis on rocky Linux 8.

Advantages of Redis:

High performance: Redis is known for its exceptional performance, capable of handling millions of operations per second with low latency. Being an in-memory database, it provides fast data retrieval and processing.

Versatile data structures: Redis offers a variety of data structures, including strings, lists, sets, sorted sets, hashes, and more. This allows developers to choose the most suitable structure for specific use cases.

Persistence options: Redis supports persistence mechanisms, allowing data to be saved to disk for durability. It offers two methods: RDB snapshots for periodic snapshots of the dataset and Append-Only Files (AOF) for continuous logs of write operations.

Scalability and high availability: Redis can be scaled horizontally by setting up a Redis Cluster or using sharding techniques. It also provides built-in replication for high availability, ensuring that data remains accessible even in the event of a failure.

Caching capabilities: Redis is widely used as a caching solution due to its fast performance and versatile data structures. It can help reduce the load on the primary database by caching frequently accessed data, thereby improving overall system performance.

Prerequisites

You will need a server running Rocky Linux 8 to successfully complete this tutorial. This server ought to have a firewall set up with firewalld and a non-root user with administrative privileges.

Step 1 — Installing and Starting Redis

Redis may be set up using the DNF package manager. You may install nano, a user-friendly text editor, Redis, and all of its dependencies using DNF. Although Swe'll use nano as an example throughout this guide, you do not need to install it.

sudo dnf install redis nano

You will be requested by this command to confirm that you want to install the chosen packages. To accomplish that, press y and then ENTER:

Output
. . .

Total download size: 1.5 M
Installed size: 5.4 M
Is this ok [y/N]: y

Following that, there is one critical configuration modification to make in the Redis configuration file, which was generated automatically during installation.

Use your chosen text editor to open this file. We'll use nano here:

sudo nano /etc/redis.conf

Locate the supervised directive inside the file. This directive gives you additional control over Redis' functioning by allowing you to create an init system for managing Redis as a service. By default, the supervised directive is set to no. Change this to systemd since you are using Rocky Linux, which employs the systemd init system:

. . .

# If you run Redis from upstart or systemd, Redis can interact with your
# supervision tree. Options:
#   supervised no      - no supervision interaction
#   supervised upstart - signal upstart by putting Redis into SIGSTOP mode
#   supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET
#   supervised auto    - detect upstart or systemd method based on
#                        UPSTART_JOB or NOTIFY_SOCKET environment variables
# Note: these supervision methods only signal "process is ready."
#       They do not enable continuous liveness pings back to your supervisor.
supervised systemd

. . .

There is now only one modification that has to be made to the Redis configuration file, so save it and exit when done. If you edited the file using nano, you would save it, exit, and then press CTRL + X, Y, and Enter.

Start the Redis service after editing the file:

sudo systemctl start redis.service

Redis may be made to start automatically by using the enable command:

sudo systemctl enable redis

Note that the unit file name is not followed by the .service suffix in this command. Since this suffix may be automatically parsed from the service names, you can typically omit it from systemctl instructions.

Run these commands to check on Redis' condition:

sudo systemctl status redis
Output
● redis.service - Redis persistent key-value database
   Loaded: loaded (/usr/lib/systemd/system/redis.service; enabled; vendor preset: disabled)
  Drop-In: /etc/systemd/system/redis.service.d
           └─limit.conf
   Active: active (running) since Tue 2022-09-06 22:11:52 UTC; 40s ago
 Main PID: 14478 (redis-server)
    Tasks: 4 (limit: 11152)
   Memory: 6.6M
   CGroup: /system.slice/redis.service
           └─14478 /usr/bin/redis-server 127.0.0.1:6379

Once Redis is operating, you may use the following command to check its functionality:

redis-cli ping

PONG should appear as the response to this:

Output
PONG

If this is the case, Redis is now operational on your server, and you can start setting it up to improve security.

Step 2 — Setting Up Redis and Securing it with a Firewall

Securing the server that Redis is hosted on is a good technique to protect it. To do this, make sure the server's firewall is activated and that Redis is only bound to localhost or a private IP address.

But if you went with another tutorial to install Redis, you might have changed the configuration file to let connections from everywhere. In comparison to binding to localhost or a private IP, this is less secure.

Open the Redis configuration file once more in your favourite text editor to fix this:

sudo nano /etc/redis.conf

Find the line that starts with bind and remove the # symbol at the start of the line to make sure it isn't disabled or commented out:

. . .
bind 127.0.0.1

Redis should definitely be bound to a private IP address if you need to link it to another IP address (for example, if you plan to access Redis from a different server). Your Redis interface is more vulnerable to outsiders if you bind to a public IP address:

. . .
bind your_private_ip

You can save and close the file after making sure the bind directive is not commented out.

You don't need to add any additional firewall rules for Redis if you followed the necessary Initial Server Setup tutorial, installed firewalld on your server, and do not want to connect to Redis from another host. After all, unless specifically permitted by the firewall rules, all inbound traffic will be discarded by default. There should be no concern about incoming traffic on a solitary Redis server's default port, since it just listens on the loopback interface (127.0.0.1 or localhost).

However, you will need to modify your firewalld configuration using the firewall-cmd command if you do intend to access Redis from another server. Again, to reduce the amount of hosts your service is exposed to, you should only permit connection to your Redis server from your hosts using their private IP addresses.

Add a specific Redis zone to your firewalld policy first:

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

Then, indicate which port you want to be open. Redis by default uses port 6379:

sudo firewall-cmd --permanent --zone=redis --add-port=6379/tcp

Next, indicate any private IP addresses that should be permitted to use Redis and pass past the firewall:

sudo firewall-cmd --permanent --zone=redis --add-source=client_server_private_IP

To apply the new rules, restart the firewall after executing those commands:

sudo firewall-cmd --reload

In this configuration, the firewall will apply the rules in the specific Redis zone to a connection when it detects a packet from your client's IP address. The default public zone will handle all other connections. You don't need to add additional services (like SSH) to the Redis zone because those rules will be automatically applied to that connection since the services in the default zone apply to all connections, not just those that don't expressly match.

Remember that any firewall tool, including firewalld, ufw, and iptables, is going to work. The firewall must be operational in order to prevent unauthorized users from accessing your server. The next step is to set up Redis so that it can only be accessed with a secure password.

Step 3 — Configuring a Redis Password

One of Redis' built-in security features, the auth command, which requires clients to authenticate before being granted access to the database, can be activated by configuring a password. The password is directly set in the /etc/redis.conf configuration file for Redis, just as the bind setting. Open that file again:

sudo nano /etc/redis.conf

Look for a commented directive in the SECURITY section that says:

. . .
# requirepass foobared

Remove the # from it to uncomment it, then replace foobared with an extremely secure password of your choice.

Note: You can generate a password using a program like apg or pwgen rather than coming up with one on your own. However, you can use the command below if you don't want to install an application only to generate a password. This command will echo the value of a string and pipe it to the sha256sum command, which will show the string's SHA256 checksum.

Please note that using this command exactly as given will always provide the same password. Change the string enclosed in quotations to any other word or phrase to generate a unique password:

echo "vegastack" | sha256sum

The resulting password will be incredibly strong and lengthy, even if it won't be memorable—exactly the kind of password required by Redis. It should read as the following, after updating the new value for requirepass with the output of that command you copied and pasted:

. . .
requirepass password_copied_from_output

Alternatively, you might use the result of a different checksum if you'd prefer a shorter password. To avoid generating the same password as this command, once more replace the term inside the quotes:

echo "vegastack" | sha1sum

Save and exit the file after setting the password, then restart Redis:

sudo systemctl restart redis

Open the Redis client to verify that the password is functional.

redis-cli

The commands listed below are used to see if the Redis password is valid. Prior to authentication, the first command tries to set a key to a value:

set key1 10

Because you haven't authenticated, that won't function, and Redis gives an error:

Output
(error) NOAUTH Authentication required.

The password given in the Redis configuration file is used in the following command to authenticate:

auth your_redis_password

Redis will confirm that your authentication was successful:

Output
OK

Following that, rerunning the prior command should succeed:

set key1 10
Output
OK

The get key1 command asks Redis what the new key's value is:

get key1
Output
"10"

redis-cli is shut down by the final command. Alternatively, use exit:

quit

Unauthorized users should now have an extremely tough time accessing your Redis installation. Be careful that you will need to re-authenticate if Redis is restarted while you are currently using the command line client. Be aware that if you're connecting to Redis remotely without SSL or a VPN, this password could still be accessed by third parties.

This section will then discuss renaming Redis instructions to further safeguard Redis against malicious users.

Step 4 — Renaming Dangerous Commands

Redis also includes a security function that lets you rename or totally disable some commands that are deemed risky. These instructions can be used to modify, delete, or otherwise wipe your data if unauthorized users execute them. The following are a few of the commands that are regarded as hazardous:

  • FLUSHDB
  • FLUSHALL
  • KEYS
  • PEXPIRE
  • DEL
  • CONFIG
  • SHUTDOWN
  • BGREWRITEAOF
  • BGSAVE
  • SAVE
  • SPOP
  • SREM
  • RENAME
  • DEBUG

Although this is not a complete list, renaming or turning off each command on it can assist to increase the security of your data store. The needs you have will determine whether you should disable or rename a command. You can disable a command if you are certain that you will never use it. Otherwise, you ought to rename it.

Renaming or deactivating commands is set up in the SECURITY part of the /etc/redis.conf file, just like the authentication password. Open the configuration file once more for modification to enable or disable Redis commands:

sudo nano /etc/redis.conf

Note: These are some instances. If you are positive you won't ever use a command, you can disable it. At redis.io/commands, you can read more about Redis's commands and evaluate how they might be misused.

Rename the command to an empty string, like in the following, to disable or terminate it:

# It is also possible to completely kill a command by renaming it into
# an empty string:
#
rename-command FLUSHDB ""
rename-command FLUSHALL ""
rename-command DEBUG ""

Give a command a new name, like in the examples below, to rename it. Commands that have been renamed should be challenging for others to guess yet simple for you to remember:

# It is also possible to completely kill a command by renaming it into
# an empty string:
#
rename-command FLUSHDB ""
rename-command FLUSHALL ""
rename-command DEBUG ""
rename-command SHUTDOWN SHUTDOWN_MENOT
rename-command CONFIG ASC12_CONFIG

Close the file after saving your modifications. Then restart Redis to apply the changes:

sudo systemctl restart redis.service

Enter the Redis command line to test your new commands:

redis-cli

Use your already created password to verify your identity:

auth your_redis_password
Output
OK

Using the config command will not work if you changed the name of the CONFIG command to ASC12_CONFIG:

config get requirepass
Output
(error) ERR unknown command 'config'

Instead, calling the renamed command will work. Note that Redis commands do not take case into account:

asc12_config get requirepass
Output
1) "requirepass"
2) "your_redis_password"

Last but not least, you can leave redis-cli:

exit

Warning: There is a warning about renaming commands at the conclusion of the SECURITY section in the /etc/redis.conf file. It reads:

. . .

# Please note that changing the name of commands that are logged into the
# AOF file or transmitted to replicas may cause problems.

. . .

This means there should be no issues if the renamed command is not present in the AOF file or if it is present but the AOF file has not been distributed to replicas. As you rename commands, bear that in mind. When you are not using AOF persistence or immediately after installation (i.e., before your Redis-using application has been deployed), is when you should rename a command.

Step 5 — Adjusting Data Directory Ownership and File Permissions

This step will go over a few ownership and permissions adjustments you might need to make to enhance your Redis installation's security profile. Making ensuring that only the user who needs to access Redis has authorization to read its data is necessary for this. That user is the redis user by default.

By grep-ing for the Redis data directory in a lengthy listing of its parent directory, you may confirm this. The following commands and their results:

ls -l /var/lib | grep redis
Output
drwxr-x---. 2 redis          redis            22 Sep 6 22:22 redis

The Redis data directory is owned by the redis user, with secondary access provided to the redis group, according to this output. The folder's permissions, which are set to 750 using octal notation, are secure and match the ownership setting.

By using the chmod command, you may make sure that only the Redis user and group have access to the folder and its contents if your Redis data directory has insecure permissions. The permissions setting for this folder is changed to 770 using the example below:

sudo chmod 770 /var/lib/redis

You might also need to modify the Redis configuration file's permissions. It is held by root by default and has a file permission of 640; the root group has secondary ownership.

ls -l /etc/redis.conf
Output
-rw-r-----. 1 redis root 62192 Sep 6 22:20 /etc/redis.conf

The Redis configuration file can only be accessed by the redis user and the root group thanks to that permission (640). redis.conf should be held by the redis user with secondary ownership going to the redis group because it contains the unencrypted password you configured in Step 4 in the configuration file. Execute the following command to set this:

sudo chown redis:redis /etc/redis.conf

Change the file's permissions so that only the owner has access to read and write to it after that:

sudo chmod 600 /etc/redis.conf

By issuing the prior ls commands once more, you can confirm the new ownership and permissions:

ls -l /var/lib | grep redis
Output
total 40
drwxrwx---. 2 redis          redis            22 Sep 6 22:22 redis
ls -l /etc/redis.conf
Output
total 40
-rw-------. 1 redis redis 62192 Sep 6 22:20 /etc/redis.conf

To apply these modifications, restart Redis:

sudo systemctl restart redis

Your Redis installation has now been secured.

FAQs on Install & Secure Redis on Rocky Linux 8

What programming languages are supported by Redis?

Redis provides official libraries and client support for various programming languages, including Java, Python, Node.js, PHP, Ruby, and many more.

How do I install Redis on my system?

Installation steps vary depending on your operating system and version. It's recommended to consult the official Redis documentation for detailed installation instructions based on your specific setup.

Does Redis support data persistence?

Yes, Redis offers persistence options to save data to disk, ensuring durability. It supports two approaches: RDB snapshots and Append-Only Files (AOF).

Can Redis be used as a primary database?

While Redis can store data persistently, it is primarily designed as an in-memory data store. It is often used as a cache or as a complementary database alongside a traditional primary database.

How does Redis handle high availability?

Redis achieves high availability through data replication using the built-in replication feature. It allows you to set up one or more slave nodes that replicate data from a primary master node.

Does Redis provide support for transactions?

Redis supports transactions, enabling multiple commands to be executed as a single atomic operation. This ensures that all commands are processed sequentially or not at all.

Can Redis be used for caching purposes?

Redis is commonly used as a caching solution due to its fast performance and versatile data structures. It helps improve application performance by storing frequently accessed data in memory.

Conclusion

Installing and securing Redis on Rocky Linux 8 is straightforward and can be done by following a few steps. Redis provides fast in-memory data storage and retrieval capabilities, making it suitable for a range of applications.

Using an SSL proxy is required to safeguard Redis communication across an untrusted network, as advised by the Redis developers in the official Redis security guide.

If you have any queries or doubts, please leave them in the comment below. We'll be happy to address them.

Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to DevOps Tutorials - VegaStack.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.