Skip to main content

Linux Security & Permissions for DevOps

 Linux Security & Permissions: The Complete Security Guide

Master Linux security fundamentals, permissions, and hardening techniques essential for every system administrator.

📅 Published: Feb 2026
⏱️ Estimated Reading Time: 20 minutes
🏷️ Tags: Linux Security, Permissions, SSH Hardening, Firewall, SELinux, AppArmor


🔐 File & Directory Permissions Deep Dive

Understanding the Permission System

Think of Linux permissions as a security system for your files and folders. Every file and directory has a set of permissions that control who can do what. It's like having different types of keys for different rooms in a building.

The Permission Structure

Linux permissions work with three types of people and three types of access:

Three Types of People:

  1. Owner (u) - The user who created the file

  2. Group (g) - A group of users

  3. Others (o) - Everyone else on the system

Three Types of Access:

  1. Read (r) - Can view/open the file

  2. Write (w) - Can modify/delete the file

  3. Execute (x) - Can run the file as a program

Viewing Permissions

bash
# View permissions with ls -l
ls -l important_file.txt
# Output: -rw-r--r-- 1 alice developers 1024 Feb 10 10:30 important_file.txt
# │          │       │       │        │
# │          │       │       │        └── Filename
# │          │       │       └── Group
# │          │       └── Owner
# │          └── Permissions (rw-r--r--)
# └── File type (- = regular file, d = directory, l = link)

Understanding Permission Notation

Permissions are shown as 10 characters:

text
-rwxr-xr-x
│└─┬──┴─┬──┘
│  │    └── Others: r-x (read & execute)
│  └─── Group: r-x (read & execute)
└────── Owner: rwx (read, write, execute)

The first character shows file type:

  • - = Regular file

  • d = Directory

  • l = Symbolic link

  • c = Character device

  • b = Block device

  • s = Socket

Changing Permissions with chmod

Numeric Method (Octal Notation)

Each permission has a numeric value:

  • r (read) = 4

  • w (write) = 2

  • x (execute) = 1

Add them up for each category:

  • rwx = 4+2+1 = 7

  • r-x = 4+0+1 = 5

  • r-- = 4+0+0 = 4

bash
# Common permission sets:
chmod 755 script.sh      # rwxr-xr-x (Owner: all, Group/Others: read/execute)
chmod 644 config.txt     # rw-r--r-- (Owner: read/write, Others: read only)
chmod 600 secret.txt     # rw------- (Only owner can read/write)
chmod 750 shared_dir/    # rwxr-x--- (Owner: all, Group: read/execute)
chmod 777 dangerous/     # rwxrwxrwx (EVERYONE can do ANYTHING - DON'T use!)

Symbolic Method (More Readable)

bash
# Add execute permission for owner
chmod u+x script.sh

# Remove write permission for group
chmod g-w file.txt

# Add read permission for others
chmod o+r document.txt

# Set specific permissions
chmod u=rwx,g=rx,o= script.sh

# Copy permissions from one set to another
chmod g=u file.txt  # Make group permissions same as owner

# Using letters:
# u = user (owner), g = group, o = others, a = all (ugo)
# + = add permission, - = remove permission, = = set exactly
# r = read, w = write, x = execute

Directory Permissions Explained

Directory permissions work differently than file permissions:

  • Read (r) = Can list directory contents (use ls)

  • Write (w) = Can create/delete files in directory

  • Execute (x) = Can enter/access the directory (use cd)

bash
# Common directory permissions:
chmod 755 /home/user/    # Owner: rwx, Others: r-x (can list but not create)
chmod 700 /home/user/    # Only owner can access
chmod 775 /shared/       # Owner and group can write, others can only read

Changing Ownership with chown

bash
# Change file owner
sudo chown alice file.txt

# Change file group
sudo chown :developers file.txt

# Change both owner and group
sudo chown alice:developers file.txt

# Change recursively (directory and all contents)
sudo chown -R alice:developers /home/alice/

# Change only files (not directories) in current directory
find . -type f -exec chown alice {} \;

Default Permissions with umask

The umask sets default permissions for new files and directories. It's like a template.

bash
# Check current umask
umask
# Output: 0022

# Common umask values:
# 0022 = Files: 644, Directories: 755
# 0002 = Files: 664, Directories: 775
# 0077 = Files: 600, Directories: 700 (very restrictive)

# Set new umask
umask 0027
# Files: 640 (rw-r-----), Directories: 750 (rwxr-x---)

# Make permanent (add to ~/.bashrc or /etc/profile)
echo "umask 0027" >> ~/.bashrc

How umask works: It subtracts from the maximum permissions:

  • Maximum file permissions: 666 (rw-rw-rw-)

  • Maximum directory permissions: 777 (rwxrwxrwx)

  • Example: umask 022 → Files: 666-022=644, Directories: 777-022=755


⚡ Special Permission Bits: Sticky Bit, SUID, SGID

The Sticky Bit: Protecting Shared Directories

The sticky bit is like a "no stealing" rule in a shared locker room. In a directory with sticky bit, users can only delete their own files.

bash
# Set sticky bit on a directory
chmod +t /tmp
# Or numerically: chmod 1777 /tmp

# Check if sticky bit is set
ls -ld /tmp
# Output: drwxrwxrwt ... /tmp
# The 't' at the end indicates sticky bit

# Remove sticky bit
chmod -t /shared/

# Common use cases:
sudo chmod +t /var/tmp/      # Temporary files directory
sudo chmod +t /home/shared/  # Shared user directory

Why it matters: Without sticky bit in /tmp, any user could delete other users' temporary files!

SUID (Set User ID): Running as Owner

SUID makes an executable run with the permissions of the file's owner, not the user running it. It's like giving someone your ID card to enter a restricted area.

bash
# Set SUID bit
chmod u+s /usr/bin/passwd
# Or numerically: chmod 4755 /usr/bin/passwd

# Check SUID
ls -l /usr/bin/passwd
# Output: -rwsr-xr-x ... /usr/bin/passwd
# The 's' in owner execute position indicates SUID

# Common SUID programs:
# /usr/bin/passwd (needs to write to /etc/shadow)
# /usr/bin/sudo (needs root privileges)
# /bin/ping (needs raw socket access)

Security warning: SUID programs are dangerous if they have security holes. Always minimize SUID programs on your system.

SGID (Set Group ID): Running as Group

SGID has two functions:

  1. For executables: Run with group permissions

  2. For directories: New files inherit directory's group

bash
# Set SGID on executable
chmod g+s /usr/bin/wall
# Or: chmod 2755 /usr/bin/wall

# Set SGID on directory (files inherit group)
chmod g+s /shared/projects/
# New files created in /shared/projects/ will have group "projects"

# Check SGID
ls -ld /shared/projects/
# Output: drwxr-sr-x ... /shared/projects/
# The 's' in group execute position indicates SGID

Finding Special Permission Files

bash
# Find SUID files
find / -type f -perm /4000 2>/dev/null | head -20

# Find SGID files
find / -type f -perm /2000 2>/dev/null | head -20

# Find sticky bit directories
find / -type d -perm /1000 2>/dev/null | head -20

# Find world-writable files (security risk!)
find / -type f -perm /0002 ! -type l 2>/dev/null | head -20

# Find files with no owner or group (orphaned)
find / -nouser -o -nogroup 2>/dev/null | head -20

Security Best Practices for Permissions

bash
# 1. Regular permission audits
sudo find / -type f -perm /777 2>/dev/null  # Find overly permissive files
sudo find /home -type f -perm /022 2>/dev/null  # World-writable files in /home

# 2. Secure home directories
sudo chmod 750 /home/*  # Only owners can access their homes

# 3. Protect configuration files
sudo chmod 600 /etc/shadow
sudo chmod 644 /etc/passwd

# 4. Secure SSH keys
chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub
chmod 644 ~/.ssh/authorized_keys

# 5. Set secure defaults
echo "umask 027" | sudo tee -a /etc/profile  # System-wide secure umask

🔥 Firewall Setup & SSH Hardening

UFW Firewall Configuration

bash
# Install UFW (if not installed)
sudo apt install ufw

# Enable firewall
sudo ufw enable

# Set default policies (RECOMMENDED)
sudo ufw default deny incoming  # Block all incoming by default
sudo ufw default allow outgoing # Allow all outgoing

# Allow SSH (do this BEFORE enabling if connecting remotely!)
sudo ufw allow ssh
# Or by port: sudo ufw allow 22/tcp

# Allow web services
sudo ufw allow http
sudo ufw allow https

# Allow specific IP range
sudo ufw allow from 192.168.1.0/24 to any port 22

# Allow specific port range
sudo ufw allow 8000:8010/tcp  # For development services

# Deny a specific port
sudo ufw deny 3306  # MySQL (if not needed remotely)

# Check status
sudo ufw status verbose
sudo ufw status numbered  # Shows rules with numbers for deletion

# Delete a rule
sudo ufw delete 2  # Delete rule #2

# Disable firewall (temporarily)
sudo ufw disable

# Reset all rules
sudo ufw reset

SSH Hardening: Making SSH Secure

SSH is often the #1 attack vector. Here's how to harden it:

bash
# Backup original config first
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup

# Edit SSH configuration
sudo nano /etc/ssh/sshd_config

Essential SSH hardening options:

bash
# 1. Change default port (reduces automated attacks)
Port 2222  # Change from 22 to something else

# 2. Disable root login
PermitRootLogin no

# 3. Use only SSH key authentication
PasswordAuthentication no
PubkeyAuthentication yes

# 4. Limit user access
AllowUsers alice bob charlie  # Only these users can SSH
# Or: AllowGroups ssh-users

# 5. Use strong cryptographic algorithms
KexAlgorithms curve25519-sha256@libssh.org
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com

# 6. Limit connection attempts
MaxAuthTries 3
MaxSessions 10

# 7. Set idle timeout
ClientAliveInterval 300
ClientAliveCountMax 2  # Disconnect after 10 minutes idle

# 8. Use login banners
Banner /etc/issue.net

# 9. Restrict SFTP users (if needed)
Subsystem sftp internal-sftp
Match Group sftp-only
    ChrootDirectory /home/%u
    ForceCommand internal-sftp
    AllowTcpForwarding no
    X11Forwarding no

After editing, restart SSH:

bash
# Test config syntax first
sudo sshd -t

# Restart SSH service
sudo systemctl restart ssh

# Keep old SSH session open while testing new one!
# Open new terminal and test before closing current session

SSH Key Management Best Practices

bash
# Generate strong SSH key
ssh-keygen -t ed25519 -a 100 -C "work-laptop"
# -t = type (ed25519 is modern and secure)
# -a = key derivation rounds (higher = more secure but slower)

# Alternative: RSA with 4096 bits
ssh-keygen -t rsa -b 4096 -o -a 100

# Copy key to server
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server -p 2222

# Test connection
ssh -i ~/.ssh/id_ed25519 user@server -p 2222

# Create SSH config for easier connections
cat >> ~/.ssh/config << EOF
Host myserver
    HostName server.example.com
    User myuser
    Port 2222
    IdentityFile ~/.ssh/id_ed25519
    ServerAliveInterval 60
    ServerAliveCountMax 5
EOF

# Now connect with just: ssh myserver

Fail2Ban: Blocking Brute Force Attacks

Fail2Ban monitors logs and bans IPs with too many failed attempts.

bash
# Install Fail2Ban
sudo apt install fail2ban

# Copy default config
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

# Edit configuration
sudo nano /etc/fail2ban/jail.local

Important settings:

ini
[DEFAULT]
bantime = 3600  # Ban for 1 hour
findtime = 600   # Look back 10 minutes
maxretry = 3     # 3 failed attempts = ban

[sshd]
enabled = true
port = ssh  # Or your custom port: 2222
logpath = %(sshd_log)s
backend = %(sshd_backend)s
bash
# Start and enable
sudo systemctl start fail2ban
sudo systemctl enable fail2ban

# Check status
sudo fail2ban-client status
sudo fail2ban-client status sshd

# Manually ban/unban IPs
sudo fail2ban-client set sshd banip 192.168.1.100
sudo fail2ban-client set sshd unbanip 192.168.1.100

📜 Security Logs: Your System's Security Camera

Key Security Log Files

bash
# Authentication logs (Ubuntu/Debian)
sudo tail -f /var/log/auth.log

# Authentication logs (Red Hat/CentOS)
sudo tail -f /var/log/secure

# System logs
sudo tail -f /var/log/syslog  # Ubuntu/Debian
sudo journalctl -f            # Systemd systems

# Failed login attempts
sudo grep "Failed password" /var/log/auth.log
sudo grep "Invalid user" /var/log/secure

# Successful logins
sudo grep "Accepted password" /var/log/auth.log
sudo grep "session opened" /var/log/auth.log

# SSH connection attempts
sudo grep "ssh" /var/log/auth.log | tail -20

# Sudo usage
sudo grep "sudo" /var/log/auth.log

Monitoring Security Logs

bash
# Real-time monitoring of failed SSH attempts
sudo tail -f /var/log/auth.log | grep -i "failed\|invalid"

# Count failed attempts by IP
sudo grep "Failed password" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -rn

# Monitor for brute force attacks
#!/bin/bash
THRESHOLD=10
LOG_FILE="/var/log/auth.log"

echo "Checking for brute force attacks..."
sudo awk '/Failed password/ {print $11}' $LOG_FILE | sort | uniq -c | while read count ip; do
    if [ $count -gt $THRESHOLD ]; then
        echo "ALERT: $ip failed $count times"
        # Optional: auto-block with iptables
        # sudo iptables -A INPUT -s $ip -j DROP
    fi
done

Log Rotation and Retention

bash
# Check logrotate configuration
ls -la /etc/logrotate.d/
cat /etc/logrotate.d/rsyslog

# Force log rotation
sudo logrotate -vf /etc/logrotate.conf

# Check disk space used by logs
sudo du -sh /var/log/
sudo du -ch /var/log/*.log | sort -rh

# Clean old logs (carefully!)
# Keep last 30 days of logs
find /var/log -name "*.log" -type f -mtime +30 -delete

# Compress old logs instead of deleting
find /var/log -name "*.log" -type f -mtime +7 -exec gzip {} \;

🛡️ SELinux & AppArmor: Mandatory Access Control

Understanding MAC (Mandatory Access Control)

Traditional Linux permissions are DAC (Discretionary Access Control) - owners decide permissions. MAC adds an extra layer where the system decides what's allowed, regardless of permissions.

Think of it like:

  • DAC = Building owners decide who enters

  • MAC = Government security rules everyone must follow

SELinux (Security-Enhanced Linux)

Used by Red Hat, CentOS, Fedora.

bash
# Check SELinux status
sestatus
getenforce
# Possible states: Enforcing, Permissive, Disabled

# Temporary change (until reboot)
sudo setenforce 0  # Permissive mode (logs but doesn't block)
sudo setenforce 1  # Enforcing mode

# Permanent change
sudo nano /etc/selinux/config
# Change: SELINUX=enforcing

# Check SELinux context
ls -Z /etc/passwd
# Output: -rw-r--r--. root root system_u:object_r:passwd_file_t:s0 /etc/passwd

# Change context
sudo chcon -t httpd_sys_content_t /var/www/html/index.html

# Restore default context
sudo restorecon -v /var/www/html/index.html

# View SELinux alerts
sudo ausearch -m avc -ts today
sudo sealert -a /var/log/audit/audit.log

# Common troubleshooting: if something works in permissive but not enforcing
sudo setenforce 0  # Switch to permissive
# Test your application
sudo tail -f /var/log/audit/audit.log | grep avc  # See what's being blocked
sudo setenforce 1  # Switch back to enforcing
# Apply suggested fix or create custom policy

AppArmor (Application Armor)

Used by Ubuntu, Debian, SUSE.

bash
# Check AppArmor status
sudo apparmor_status

# List profiles
sudo aa-status

# Disable a profile
sudo apparmor_parser -R /etc/apparmor.d/usr.bin.firefox

# Enable a profile
sudo apparmor_parser -a /etc/apparmor.d/usr.bin.firefox

# Put profile in complain mode (logs but doesn't block)
sudo aa-complain /usr/sbin/nginx

# Put back in enforce mode
sudo aa-enforce /usr/sbin/nginx

# Check logs
sudo dmesg | grep apparmor
sudo journalctl -g apparmor

# Generate new profile (learning mode)
sudo aa-genprof /path/to/application
# Run your application, then in another terminal:
# sudo aa-logprof

When to Use SELinux/AppArmor

Use MAC when:

  • Hosting multiple applications/users

  • Need defense in depth

  • Compliance requirements (HIPAA, PCI-DSS)

  • Public-facing servers

May skip MAC for:

  • Personal desktop

  • Simple single-application servers

  • Development environments


🎯 Real-World Security Scenarios

Scenario 1: Secure Web Server Setup

bash
#!/bin/bash
# secure-webserver.sh

echo "Securing web server..."

# 1. Update system
sudo apt update && sudo apt upgrade -y

# 2. Configure firewall
sudo ufw --force enable
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp comment 'SSH'
sudo ufw allow 80/tcp comment 'HTTP'
sudo ufw allow 443/tcp comment 'HTTPS'
sudo ufw status verbose

# 3. Harden SSH
sudo sed -i 's/#Port 22/Port 2222/' /etc/ssh/sshd_config
sudo sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
sudo sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo sed -i 's/#MaxAuthTries 6/MaxAuthTries 3/' /etc/ssh/sshd_config
sudo systemctl restart ssh

# 4. Secure Nginx
sudo chown -R www-data:www-data /var/www/html
sudo find /var/www/html -type f -exec chmod 644 {} \;
sudo find /var/www/html -type d -exec chmod 755 {} \;

# 5. Install and configure Fail2Ban
sudo apt install fail2ban -y
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo systemctl restart fail2ban

# 6. Set secure umask
echo "umask 027" | sudo tee -a /etc/profile

echo "Web server secured!"

Scenario 2: Permission Audit Script

bash
#!/bin/bash
# security-audit.sh

LOG_FILE="/var/log/security-audit-$(date +%Y%m%d).log"

echo "=== Security Audit: $(date) ===" > $LOG_FILE
echo >> $LOG_FILE

# 1. World-writable files
echo "1. World-writable files:" >> $LOG_FILE
sudo find / -xdev -type f -perm -0002 ! -type l 2>/dev/null | head -50 >> $LOG_FILE

# 2. SUID/SGID files
echo -e "\n2. SUID files:" >> $LOG_FILE
sudo find / -xdev -type f -perm /4000 2>/dev/null >> $LOG_FILE
echo -e "\n3. SGID files:" >> $LOG_FILE
sudo find / -xdev -type f -perm /2000 2>/dev/null >> $LOG_FILE

# 3. Files with no owner
echo -e "\n4. Files with no owner/group:" >> $LOG_FILE
sudo find / -xdev \( -nouser -o -nogroup \) 2>/dev/null | head -20 >> $LOG_FILE

# 4. SSH key permissions
echo -e "\n5. SSH key permissions:" >> $LOG_FILE
ls -la ~/.ssh/ 2>/dev/null >> $LOG_FILE

# 5. Failed login attempts
echo -e "\n6. Recent failed login attempts:" >> $LOG_FILE
sudo tail -100 /var/log/auth.log 2>/dev/null | grep -i "fail\|invalid" | tail -20 >> $LOG_FILE

# 6. Listening ports
echo -e "\n7. Listening ports:" >> $LOG_FILE
sudo ss -tulpn | grep LISTEN >> $LOG_FILE

echo -e "\nAudit saved to: $LOG_FILE" >> $LOG_FILE
echo "Review the log file for security issues: $LOG_FILE"

Scenario 3: User Account Security Check

bash
#!/bin/bash
# user-security-check.sh

echo "=== User Account Security Check ==="

# 1. Users with empty passwords
echo "1. Users with empty passwords:"
sudo awk -F: '($2 == "" || $2 == "!") {print $1}' /etc/shadow

# 2. Password expiration
echo -e "\n2. Password expiration status:"
for user in $(cut -d: -f1 /etc/passwd); do
    expires=$(sudo chage -l $user 2>/dev/null | grep "Account expires" | cut -d: -f2)
    if [ "$expires" != " never" ]; then
        echo "$user expires on: $expires"
    fi
done

# 3. Users with UID 0 (should only be root)
echo -e "\n3. Users with UID 0 (should only be root):"
awk -F: '($3 == 0) {print $1}' /etc/passwd

# 4. Users in sudo group
echo -e "\n4. Users in sudo group:"
getent group sudo | cut -d: -f4 | tr ',' '\n'

# 5. Last login times
echo -e "\n5. Users who haven't logged in for 90 days:"
sudo lastlog -b 90 | grep -v "Never logged in"

Scenario 4: Automated Security Monitoring

bash
#!/bin/bash
# security-monitor.sh

ALERT_EMAIL="admin@example.com"
THRESHOLD_FAILED=10
THRESHOLD_DISK=90

# 1. Check failed SSH attempts
FAILED_COUNT=$(sudo grep "Failed password" /var/log/auth.log 2>/dev/null | wc -l)
if [ $FAILED_COUNT -gt $THRESHOLD_FAILED ]; then
    echo "ALERT: $FAILED_COUNT failed SSH attempts in last check" | mail -s "SSH Alert" $ALERT_EMAIL
fi

# 2. Check disk space
DISK_USAGE=$(df / | awk 'NR==2{print $5}' | sed 's/%//')
if [ $DISK_USAGE -gt $THRESHOLD_DISK ]; then
    echo "ALERT: Disk usage at ${DISK_USAGE}%" | mail -s "Disk Alert" $ALERT_EMAIL
fi

# 3. Check for new SUID files
find / -type f -perm /4000 2>/dev/null > /tmp/suid-new.txt
if [ -f /tmp/suid-old.txt ]; then
    NEW_SUID=$(diff /tmp/suid-old.txt /tmp/suid-new.txt | grep "^>" | wc -l)
    if [ $NEW_SUID -gt 0 ]; then
        echo "ALERT: $NEW_SUID new SUID files found" | mail -s "SUID Alert" $ALERT_EMAIL
    fi
fi
mv /tmp/suid-new.txt /tmp/suid-old.txt

# 4. Check for open ports
OPEN_PORTS=$(sudo ss -tulpn | grep LISTEN | wc -l)
if [ $OPEN_PORTS -gt 20 ]; then
    echo "ALERT: $OPEN_PORTS open ports detected" | mail -s "Port Alert" $ALERT_EMAIL
fi

📋 Quick Reference Cheat Sheet

TaskCommandDescription
View permissionsls -lShow file permissions
Change permissionschmod 755 fileSet rwxr-xr-x
Change ownerchown user:group fileChange ownership
View umaskumaskShow default permissions mask
Check SUID/SGIDls -l /usr/bin/passwdLook for 's' in permissions
Find SUID filesfind / -perm /4000 2>/dev/nullList all SUID files
Set sticky bitchmod +t directoryProtect shared directory
Firewall statussudo ufw statusCheck UFW firewall
Allow SSHsudo ufw allow sshOpen SSH port
Harden SSHEdit /etc/ssh/sshd_configConfigure SSH security
Check auth logssudo tail -f /var/log/auth.logMonitor authentication
SELinux statussestatusCheck SELinux state
AppArmor statussudo apparmor_statusCheck AppArmor
Check failed loginssudo grep "Failed" /var/log/auth.logFind failed attempts
Monitor portssudo ss -tulpnCheck listening ports
World-writable filesfind / -perm -0002 -type fFind security risks
Password policiessudo chage -l usernameCheck password settings

🚀 Practice Exercises

Exercise 1: Secure a Shared Directory

bash
# Create shared directory
sudo mkdir /shared
sudo groupadd project-team
sudo usermod -aG project-team alice
sudo usermod -aG project-team bob

# Set permissions
sudo chown root:project-team /shared
sudo chmod 2775 /shared  # SGID + rwxrwxr-x

# Test
sudo -u alice touch /shared/file1.txt
sudo -u bob touch /shared/file2.txt
ls -la /shared/
# Both files should have group "project-team"

Exercise 2: SSH Hardening Practice

bash
# 1. Backup SSH config
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup

# 2. Create test user
sudo useradd testuser
sudo passwd testuser

# 3. Generate SSH key for test
ssh-keygen -t ed25519 -f ~/.ssh/test_key -N ""

# 4. Configure SSH to only allow key auth for testuser
sudo nano /etc/ssh/sshd_config
# Add at end:
# Match User testuser
#    PasswordAuthentication no
#    PubkeyAuthentication yes

# 5. Copy test key
ssh-copy-id -i ~/.ssh/test_key.pub testuser@localhost

# 6. Test
ssh -i ~/.ssh/test_key testuser@localhost  # Should work
ssh testuser@localhost  # Should fail (no password auth)

# 7. Restore original config
sudo cp /etc/ssh/sshd_config.backup /etc/ssh/sshd_config
sudo systemctl restart ssh

Exercise 3: Permission Analysis

bash
# Create test files
mkdir -p ~/security-test
cd ~/security-test

touch public.txt secret.txt script.sh
mkdir shared-dir

# Set different permissions
chmod 644 public.txt    # rw-r--r--
chmod 600 secret.txt    # rw-------
chmod 755 script.sh     # rwxr-xr-x
chmod 1777 shared-dir   # rwxrwxrwt (with sticky bit)

# Analyze
ls -la
stat public.txt
getfacl shared-dir  # View Access Control Lists

# Test access
echo "test" > public.txt  # Should work
echo "test" > secret.txt  # Should work (you're owner)
./script.sh  # Should work (if it has content)

Exercise 4: Log Monitoring Setup

bash
# Create log monitoring script
cat > ~/monitor-logs.sh << 'EOF'
#!/bin/bash
echo "=== Security Log Monitor ==="
echo "Running: $(date)"
echo

echo "1. Failed SSH attempts (last 10 lines):"
sudo tail -10 /var/log/auth.log 2>/dev/null | grep -i "fail\|invalid" || echo "None found"

echo
echo "2. Successful logins (last hour):"
sudo grep "session opened" /var/log/auth.log 2>/dev/null | grep "$(date '+%b %e %H')" || echo "None found"

echo
echo "3. Sudo commands (last 10):"
sudo grep "sudo:" /var/log/auth.log 2>/dev/null | tail -10 || echo "None found"

echo
echo "4. Current connections:"
ss -tun | grep ESTAB | wc -l
EOF

chmod +x ~/monitor-logs.sh

# Run every 5 minutes
(crontab -l 2>/dev/null; echo "*/5 * * * * /home/$USER/monitor-logs.sh >> /tmp/security-monitor.log") | crontab -

🔗 Master Linux Security with Hands-on Labs

Security is not optional in today's world. Understanding Linux security fundamentals is crucial for protecting systems and data.

👉 Practice Linux security, hardening, and permissions management in our interactive labs at:
https://devops.trainwithsky.com/

Our platform provides:

  • Real security scenarios and challenges

  • Permission management exercises

  • SSH hardening labs

  • Firewall configuration practice

  • Security auditing simulations

  • Guided exercises with security best practices


Frequently Asked Questions

Q: What's the difference between 755 and 750 permissions?
A: 755 allows everyone to read/execute. 750 allows only owner and group members (others get no access).

Q: Should I disable SSH password authentication completely?
A: Yes, for production servers. Use SSH keys only. Keep password auth only for emergency recovery.

Q: What's a safe umask value?
A: 022 for shared systems, 027 for private systems, 077 for maximum security (but may break some applications).

Q: How often should I check security logs?
A: Daily for critical systems, weekly for others. Better: automate monitoring with alerts.

Q: Should I use SELinux or AppArmor?
A: Use what your distribution provides. RHEL/CentOS use SELinux. Ubuntu/Debian use AppArmor.

Q: What's the most common SSH attack?
A: Brute force password guessing. Protect with: 1) Key-only auth 2) Fail2Ban 3) Non-standard port.

Q: How do I recover if I lock myself out with SSH hardening?
A: Have console access (physical or cloud console). Always test changes in new session before closing current one.

Have security questions or run into permission issues? Share your challenge in the comments below! 💬

Comments

Popular posts from this blog

Introduction to Terraform – The Future of Infrastructure as Code

  Introduction to Terraform – The Future of Infrastructure as Code In today’s fast-paced DevOps world, managing infrastructure manually is outdated . This is where Terraform comes in—a powerful Infrastructure as Code (IaC) tool that allows you to define, provision, and manage cloud infrastructure efficiently . Whether you're working with AWS, Azure, Google Cloud, or on-premises servers , Terraform provides a declarative, automation-first approach to infrastructure deployment. Shape Your Future with AI & Infinite Knowledge...!! Read In-Depth Tech & Self-Improvement Blogs http://www.skyinfinitetech.com Watch Life-Changing Videos on YouTube https://www.youtube.com/@SkyInfinite-Learning Transform Your Skills, Business & Productivity – Join Us Today! In today’s digital-first world, agility and automation are no longer optional—they’re essential. Companies across the globe are rapidly shifting their operations to the cloud to keep up with the pace of innovatio...

📊 Monitoring & Logging in Kubernetes – Tools like Prometheus, Grafana, and Fluentd

  Monitoring & Logging in Kubernetes – Tools like Prometheus, Grafana, and Fluentd Monitoring and logging are essential for maintaining a healthy and well-performing Kubernetes cluster. In this guide, we’ll cover why monitoring is important, key monitoring tools like Prometheus and Grafana, and logging tools like Fluentd to help you gain visibility into your cluster’s performance and logs. Shape Your Future with AI & Infinite Knowledge...!! Want to Generate Text-to-Voice, Images & Videos? http://www.ai.skyinfinitetech.com Read In-Depth Tech & Self-Improvement Blogs http://www.skyinfinitetech.com Watch Life-Changing Videos on YouTube https://www.youtube.com/@SkyInfinite-Learning Transform Your Skills, Business & Productivity – Join Us Today! 🚀 Introduction In today’s fast-paced cloud-native environment, Kubernetes has emerged as the de-facto container orchestration platform. But deploying and managing applications in Kubernetes is just half the ba...

🔒 Kubernetes Security – RBAC, Network Policies, and Secrets Management

  Kubernetes Security – RBAC, Network Policies, and Secrets Management Security is a critical aspect of managing Kubernetes clusters. In this guide, we'll cover essential security mechanisms like Role-Based Access Control (RBAC) , Network Policies , and Secrets Management to help you secure your Kubernetes environment effectively. Shape Your Future with AI & Infinite Knowledge...!! Want to Generate Text-to-Voice, Images & Videos? http://www.ai.skyinfinitetech.com Read In-Depth Tech & Self-Improvement Blogs http://www.skyinfinitetech.com Watch Life-Changing Videos on YouTube https://www.youtube.com/@SkyInfinite-Learning Transform Your Skills, Business & Productivity – Join Us Today! 🚀 Introduction: Why Kubernetes Security Is Non-Negotiable As Kubernetes becomes the backbone of modern cloud-native infrastructure, security is no longer optional—it’s mission-critical . With multiple moving parts like containers, pods, services, nodes, and more, Kuberne...