BLOG POSTS
How to Secure Your Redis Installation on Ubuntu 24

How to Secure Your Redis Installation on Ubuntu 24

Redis is a powerful in-memory data structure store widely used for caching, session management, and real-time applications. However, out-of-the-box Redis installations are notoriously insecure and can expose your server to various attacks including data breaches, unauthorized access, and even complete system compromise. This guide will walk you through essential security configurations for Redis on Ubuntu 24, covering everything from basic authentication to advanced network isolation techniques that will help you deploy Redis safely in production environments.

Understanding Redis Security Fundamentals

Redis was originally designed for trusted environments where security wasn’t the primary concern. By default, Redis listens on all network interfaces without authentication, making it accessible to anyone who can reach your server. The official Redis security documentation emphasizes that Redis should be considered a “trusted environment” component, meaning it requires proper network isolation and access controls.

Common Redis security vulnerabilities include:

  • Unprotected instances exposed to the internet
  • Default configuration allowing anonymous access
  • Lack of encryption for data in transit
  • Insufficient user access controls
  • Missing command filtering and restrictions

Initial Redis Installation and Basic Setup

First, let’s install Redis on Ubuntu 24 and verify the installation:

sudo apt update
sudo apt install redis-server -y

# Check Redis version and status
redis-server --version
sudo systemctl status redis-server

# Test basic connectivity
redis-cli ping

The default Redis configuration file is located at /etc/redis/redis.conf. Before making changes, create a backup:

sudo cp /etc/redis/redis.conf /etc/redis/redis.conf.backup

Network Security Configuration

The most critical security step is restricting network access. By default, Redis binds to all interfaces (0.0.0.0), which is dangerous in production.

Binding to Specific Interfaces

Edit the Redis configuration to bind only to localhost and specific internal IPs:

sudo nano /etc/redis/redis.conf

# Find the bind directive and modify it
bind 127.0.0.1 10.0.0.100

# Alternatively, for local access only
bind 127.0.0.1 -::1

Changing the Default Port

Moving Redis from the default port 6379 adds security through obscurity:

# In /etc/redis/redis.conf
port 6380

# Or disable TCP entirely and use Unix sockets only
port 0
unixsocket /var/run/redis/redis-server.sock
unixsocketperm 700

Firewall Configuration

Configure UFW to restrict Redis access:

# Allow Redis only from specific IP ranges
sudo ufw allow from 10.0.0.0/24 to any port 6380

# For Unix socket setup, no firewall rules needed
sudo ufw status verbose

Authentication and Authorization

Setting Up Password Authentication

Configure a strong password for Redis access:

# Generate a strong password
openssl rand -base64 32

# Add to redis.conf
requirepass your_super_strong_password_here

# Restart Redis
sudo systemctl restart redis-server

# Test authentication
redis-cli -p 6380
AUTH your_super_strong_password_here

Redis 6+ ACL System

Redis 6 introduced a comprehensive ACL system. Create specific users with limited permissions:

# Connect as admin
redis-cli -p 6380
AUTH your_super_strong_password_here

# Create a read-only user
ACL SETUSER readonly on >readonly_password ~cached:* &read

# Create an application user with specific command access
ACL SETUSER appuser on >app_password ~app:* +@read +@write -@dangerous

# Save ACL configuration
ACL SAVE

# List all users
ACL LIST

# Test the new user
redis-cli -p 6380 --user appuser --pass app_password
ACL Pattern Description Use Case
~cached:* Access only keys starting with “cached:” Cache-only applications
+@read Allow all read commands Analytics and monitoring
-@dangerous Deny dangerous commands (FLUSHALL, CONFIG, etc.) Production applications
+@write -del Allow write operations except DELETE Append-only applications

Command Security and Restrictions

Disable or rename dangerous commands that could compromise your system:

# In /etc/redis/redis.conf

# Completely disable dangerous commands
rename-command FLUSHDB ""
rename-command FLUSHALL ""
rename-command KEYS ""
rename-command CONFIG ""
rename-command SHUTDOWN ""
rename-command DEBUG ""
rename-command EVAL ""

# Rename critical commands to obscure names
rename-command FLUSHDB 83eab5f4cc89a2623b2fa0640bd6b6e6
rename-command CONFIG 8c0f0b0a71a5b4b77b0a5f7b8c0e0d0a

For production environments, here’s a recommended command restriction table:

Command Risk Level Recommended Action Reason
FLUSHALL/FLUSHDB Critical Disable or rename Can delete all data
CONFIG High Rename Can modify server configuration
EVAL/EVALSHA High Disable if not needed Can execute arbitrary Lua scripts
KEYS Medium Disable Performance impact, information disclosure
DEBUG Medium Disable Can expose sensitive information

Encryption and TLS Configuration

Redis 6+ supports TLS encryption for data in transit. Here’s how to set it up:

# Generate SSL certificates
sudo mkdir -p /etc/redis/ssl
cd /etc/redis/ssl

# Create a private key
sudo openssl genrsa -out redis.key 2048

# Create a certificate signing request
sudo openssl req -new -key redis.key -out redis.csr

# Generate self-signed certificate (for testing)
sudo openssl x509 -req -days 365 -in redis.csr -signkey redis.key -out redis.crt

# Set proper permissions
sudo chown redis:redis /etc/redis/ssl/*
sudo chmod 600 /etc/redis/ssl/redis.key
sudo chmod 644 /etc/redis/ssl/redis.crt

Configure TLS in Redis:

# In /etc/redis/redis.conf

# Enable TLS port
port 0
tls-port 6380

# Certificate configuration
tls-cert-file /etc/redis/ssl/redis.crt
tls-key-file /etc/redis/ssl/redis.key
tls-ca-cert-file /etc/redis/ssl/ca.crt

# TLS security settings
tls-protocols "TLSv1.2 TLSv1.3"
tls-cipher-suites TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256
tls-prefer-server-ciphers yes

Connect using TLS:

# Connect with TLS
redis-cli --tls --cert /etc/redis/ssl/redis.crt --key /etc/redis/ssl/redis.key --cacert /etc/redis/ssl/ca.crt -p 6380

# Test the connection
AUTH your_password
PING

File System Security

Secure Redis data directories and log files:

# Create a dedicated Redis user (if not exists)
sudo useradd --system --home /var/lib/redis --shell /bin/false redis

# Set proper permissions for Redis directories
sudo chown -R redis:redis /var/lib/redis
sudo chmod 750 /var/lib/redis

# Secure log files
sudo chown redis:redis /var/log/redis/redis-server.log
sudo chmod 640 /var/log/redis/redis-server.log

# Secure configuration file
sudo chown root:redis /etc/redis/redis.conf
sudo chmod 640 /etc/redis/redis.conf

Enable Memory Protection

Configure memory overcommit and disable transparent huge pages:

# Add to /etc/sysctl.conf
echo 'vm.overcommit_memory = 1' | sudo tee -a /etc/sysctl.conf

# Disable transparent huge pages
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
echo never | sudo tee /sys/kernel/mm/transparent_hugepage/defrag

# Make persistent
echo 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' | sudo tee -a /etc/rc.local
echo 'echo never > /sys/kernel/mm/transparent_hugepage/defrag' | sudo tee -a /etc/rc.local

# Apply changes
sudo sysctl -p

Advanced Security Configurations

Setting Up Redis Sentinel for High Availability

Redis Sentinel provides high availability while maintaining security:

# Create sentinel configuration
sudo nano /etc/redis/sentinel.conf

# Basic sentinel configuration
port 26379
bind 127.0.0.1
sentinel monitor mymaster 127.0.0.1 6380 2
sentinel auth-pass mymaster your_redis_password
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 10000
sentinel parallel-syncs mymaster 1

# Security settings for sentinel
requirepass sentinel_password
sentinel auth-user mymaster appuser

Implementing Rate Limiting

Protect against brute force attacks with client connection limits:

# In /etc/redis/redis.conf

# Limit maximum clients
maxclients 128

# Client timeout (in seconds)
timeout 300

# TCP keepalive
tcp-keepalive 300

# Client buffer limits
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit replica 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60

Monitoring and Logging

Set up comprehensive logging for security monitoring:

# Configure logging in redis.conf
loglevel notice
logfile /var/log/redis/redis-server.log
syslog-enabled yes
syslog-ident redis-server

# Enable slow query logging
slowlog-log-slower-than 10000
slowlog-max-len 128

Create a monitoring script to track suspicious activities:

#!/bin/bash
# Save as /usr/local/bin/redis-security-monitor.sh

LOG_FILE="/var/log/redis/redis-server.log"
ALERT_EMAIL="admin@yourdomain.com"

# Monitor for failed authentication attempts
tail -f $LOG_FILE | while read line; do
    if echo "$line" | grep -q "WRONGPASS"; then
        echo "$(date): Failed Redis authentication attempt: $line" | mail -s "Redis Security Alert" $ALERT_EMAIL
    fi
    
    if echo "$line" | grep -q "Connection refused"; then
        echo "$(date): Redis connection refused: $line" | mail -s "Redis Connection Alert" $ALERT_EMAIL
    fi
done

Performance Impact of Security Measures

Security configurations can impact Redis performance. Here’s a comparison of different security measures:

Security Feature Performance Impact Memory Overhead CPU Overhead
Password Authentication Minimal (<1%) Negligible Low
ACL System Low (2-3%) Small Low
TLS Encryption Moderate (10-15%) Medium High
Unix Sockets Improvement (+5%) Lower Lower
Command Renaming Negligible Negligible Negligible

Real-World Security Scenarios

E-commerce Application Setup

For an e-commerce platform handling sensitive session data:

# redis.conf for e-commerce
bind 127.0.0.1
port 0
unixsocket /var/run/redis/redis.sock
unixsocketperm 700

requirepass ultra_secure_ecommerce_password

# Disable dangerous commands
rename-command FLUSHDB ""
rename-command FLUSHALL ""
rename-command CONFIG "CONFIG_8f7a2b1c9d0e3f4g5h6i7j8k9l0m1n2o"

# Memory and performance settings
maxmemory 2gb
maxmemory-policy allkeys-lru
save 900 1
save 300 10
save 60 10000

Multi-Tenant SaaS Environment

For a SaaS application with multiple tenants:

# Create tenant-specific users
redis-cli
AUTH master_password

# Tenant A - can only access keys prefixed with "tenant_a:"
ACL SETUSER tenant_a on >tenant_a_password ~tenant_a:* +@all -@setup -@admin -@dangerous

# Tenant B - read-only access to shared cache
ACL SETUSER tenant_b on >tenant_b_password ~shared:* ~tenant_b:* +@read

# Analytics user - read-only access to all tenant data
ACL SETUSER analytics on >analytics_password ~* +@read -@admin

ACL SAVE

Common Security Pitfalls and Troubleshooting

Here are frequent security issues and their solutions:

  • Redis not starting after configuration changes: Check syntax errors in redis.conf using redis-server /etc/redis/redis.conf --test-memory 1
  • Applications can’t connect after ACL setup: Verify user permissions with ACL WHOAMI and ACL CAT
  • TLS connection failures: Ensure certificate paths are correct and files have proper permissions
  • Performance degradation: Monitor with redis-cli --latency and adjust buffer sizes
  • Memory issues after security changes: Use INFO memory to check memory usage patterns

Debug ACL issues with detailed logging:

# Enable ACL logging
CONFIG SET acl-log-max-len 128

# Check ACL log
ACL LOG

# Reset ACL log
ACL LOG RESET

Backup and Recovery Security

Secure your Redis backups and recovery procedures:

#!/bin/bash
# Secure backup script
BACKUP_DIR="/secure/redis/backups"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="redis_backup_$DATE.rdb"

# Create encrypted backup
redis-cli --rdb /tmp/dump.rdb
gpg --cipher-algo AES256 --compress-algo 1 --symmetric --output $BACKUP_DIR/$BACKUP_FILE.gpg /tmp/dump.rdb
rm /tmp/dump.rdb

# Set secure permissions
chmod 600 $BACKUP_DIR/$BACKUP_FILE.gpg
chown redis:redis $BACKUP_DIR/$BACKUP_FILE.gpg

Best Practices Summary

Follow these essential security practices for production Redis deployments:

  • Never expose Redis directly to the internet
  • Always use authentication, preferably with ACL users
  • Implement network isolation using firewalls or VPNs
  • Regularly update Redis to the latest stable version
  • Monitor logs for suspicious activities
  • Use Unix sockets when possible for better performance and security
  • Implement proper backup encryption and retention policies
  • Test security configurations in staging environments first
  • Document all security measures for team knowledge sharing

For enhanced security in enterprise environments, consider deploying Redis on a secure VPS or dedicated server with additional network isolation and monitoring capabilities. Regular security audits and penetration testing will help identify potential vulnerabilities before they can be exploited.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

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