⚠️ For learning/practice only β€” DO NOT use direct in Dev/SIT/UAT/Prod environments

1. πŸ”’ Protect /data/script.sh β€” Read + Execute Only, No Edit/Delete

# Set permissions: read + execute for owner, group, others (no write)
chmod 555 /data/script.sh

# Make the file IMMUTABLE (even root can't edit/delete it)
sudo chattr +i /data/script.sh

# Verify immutable flag is set
lsattr /data/script.sh
# Output: ----i--------e-- /data/script.sh

βœ… What this does:

  • chmod 555 β†’ No write access
  • chattr +i β†’ is the strongest protection β€” it prevents modification, deletion, and renaming even by root. (even for root)

πŸ”„ To Undo immutability later:

sudo chattr -i /data/script.sh

2. πŸ‘» Hide Commands from CLI History

Option A β€” Hide a single command (prefix with space):


# Add a space before the command
sudo ./script.sh 

βœ”Requires HISTCONTROL=ignorespace or ignoreboth in your shell config.

export HISTCONTROL=ignoreboth

Option B β€” Disable history temporarily for a session :

# Turn off history for current session
unset HISTFILE

# Or set file to /dev/null
export HISTFILE=/dev/null

Option C β€”Permanently configure in ~/.bashrc or ~/.zshrc:


# Ignore commands starting with space, and ignore duplicates
echo 'export HISTCONTROL=ignoreboth' >> ~/.bashrc

# Reload config
source ~/.bashrc

Option D β€” Delete a specific command after running:

# Open history, find the line number, then delete it
history
history -d <LINE_NUMBER>

3. πŸ›‘οΈ Secure the /data/ Folder β€” No Add/Delete Files

# Set sticky bit + restrict permissions on the folder
chmod 555 /data          # No write permission (can't add/delete files)

# Make the directory itself immutable
sudo chattr +i /data

# Verify
lsattr -d /data

πŸ“Œ Behavior Summary


Command               Effect                         
chmod 555 /data       = Removes write permission β€” no one can add or delete files          
chattr +i /data       = Immutable flag - Directory locked completely      
Sticky bit (chmod +t) = Only file owner can delete their own files (useful for shared dirs)

πŸ” Quick Verification Commands

ls -la /data/script.sh     # Check permissions
lsattr /data/script.sh     # Check immutable flag
lsattr -d /data            # Check folder flag
stat /data/script.sh       # Full file details

πŸ†• 4. πŸ‘€ Monitor Changes Using -w (Audit Example)

Use auditd to watch files/directories for changes.

Install & start auditd

sudo apt install auditd -y   # Ubuntu/Debian
sudo systemctl enable auditd
sudo systemctl start auditd

Add watch on file

sudo auditctl -w /data/script.sh -p rwxa -k script_monitor

Add watch on directory

sudo auditctl -w /data/ -p wa -k data_monitor

πŸ” Meaning of flags

| ---- | ------------------------ |
| Flag | Meaning                  |
| ---- | ------------------------ |
| `-w` | Watch file/directory     |
| `-p` | Permissions to monitor   |
| `r`  | Read                     |
| `w`  | Write                    |
| `x`  | Execute                  |
| `a`  | Attribute change         |
| `-k` | Key (for searching logs) |
| ---- | ------------------------ |

πŸ”Ž Check logs

sudo ausearch -k script_monitor
sudo ausearch -k data_monitor

❌ Remove watch

sudo auditctl -W /data/script.sh
sudo auditctl -W /data/

⚠️ Important Notes

  • chattr +i is very powerful β€” use carefully β€” requires root/sudo to set and unset
  • Root cannot override immutable without removing flag
  • Hiding from history only works if you run the command β€” system logs (like auditd) may still record it
  • Always test in lab environment only

πŸš€ Real-World Use Cases (VERY IMPORTANT)

βœ… Use Case 1: Protect Production Deployment Script

Problem: Dev accidentally modifies deploy.sh

Solution:

chmod 555 /prod/deploy.sh
chattr +i /prod/deploy.sh
auditctl -w /prod/deploy.sh -p wa -k deploy_watch

βœ” Prevents:

  • Accidental edits
  • Malicious tampering

βœ… Use Case 2: Detect Unauthorized Changes

Problem: Someone modifies critical config silently

Solution:

auditctl -w /etc/nginx/nginx.conf -p wa -k nginx_change
ausearch -k nginx_change

βœ” Result:

  • Full audit trail

βœ… Use Case 3: Restrict Production Access

Problem: Too many users have root access

Solution:

  • Remove direct SSH root login
  • Use sudo with logging

βœ” Result:

  • Traceable actions
  • Reduced blast radius

πŸ§ͺ DevOps Security Lab: Attack vs Defense (Step-by-Step)

🎯 Lab Goal

Simulate:

  • Unauthorized file modification
  • Secret exposure

Then implement:

  • File protection
  • Audit monitoring
  • Access restriction

πŸ—οΈ Lab Setup

1. Create Test Environment

sudo mkdir -p /lab/data
cd /lab/data

2. Create a "critical script"

cat <<EOF > deploy.sh
#!/bin/bash
echo "Deploying application..."
EOF
chmod +x deploy.sh

πŸ”΄ Phase 1: Simulate Attack

πŸ‘¨β€πŸ’» Attack 1 β€” Modify Critical Script

echo 'echo "HACKED by attacker"' >> deploy.sh

Run it:

./deploy.sh

πŸ‘‰ Output:

Deploying application...
HACKED by attacker

βœ” Impact: Production script tampered

πŸ” Attack 2 β€” Read Secret File

echo "DB_PASSWORD=SuperSecret123" > /lab/data/.env
cat /lab/data/.env

βœ” Impact: Sensitive data exposed

🟒 Phase 2: Apply Defense

πŸ›‘οΈ Defense 1 β€” Protect Script

chmod 555 deploy.sh
sudo chattr +i deploy.sh

Try attack again:

echo "malicious code" >> deploy.sh

πŸ‘‰ Output:

Operation not permitted

βœ” Attack blocked

πŸ›‘οΈ Defense 2 β€” Monitor File Changes (-w)

sudo apt install auditd -y
sudo systemctl start auditd
sudo auditctl -w /lab/data/deploy.sh -p wa -k deploy_watch

Try modifying:

sudo chattr -i deploy.sh
echo "test change" >> deploy.sh

Check logs:

sudo ausearch -k deploy_watch

βœ” You'll see who changed it + when

πŸ›‘οΈ Defense 3 β€” Secure Secrets

chmod 400 /lab/data/.env

Try access as another user:

sudo useradd attacker
sudo su - attacker
cat /lab/data/.env

πŸ‘‰ Output:

Permission denied

βœ” Secret protected

πŸ›‘οΈ Defense 4 β€” Lock Directory

sudo chattr +i /lab/data

Try:

touch test.txt

πŸ‘‰ Output:

Operation not permitted

βœ” Directory protected

πŸ” Phase 3: Detection & Analysis

Check file attributes

lsattr deploy.sh

Check permissions

ls -l deploy.sh

Audit logs

ausearch -k deploy_watch

🧠 What You Learned (Real DevOps Mapping)

| ---------------------- | --------------- | ------------------ |
| Attack                 | Real Scenario   | Defense            |
| ---------------------- | --------------- | ------------------ |
| Script modified        | CI/CD tampering | `chattr +i`        |
| Secret exposed         | Git leak        | `chmod 400`, Vault |
| Unauthorized access    | Insider threat  | auditd             |
| File creation/deletion | Malware         | immutable dir      |
| ---------------------- | --------------- | ------------------ |

πŸš€ Advanced Challenge

Try these:

1. Break your own security

sudo chattr -i deploy.sh

πŸ‘‰ Learn: root control limitations

2. Add real-time monitoring

Use:

  • Falco
  • Wazuh

3. Simulate CI/CD attack

  • Add secret in script
  • Push to Git
  • Scan with: - Trivy

⚠️ Key Takeaways

  • chmod = basic protection
  • chattr +i = strong protection
  • auditd -w = visibility
  • Secrets must NEVER be open
  • Security = Prevent + Detect

🧩 Real Interview Insight

If asked:

πŸ‘‰ "How do you secure production scripts?"

Answer:

"I use immutable flags (chattr +i), restrict permissions (chmod 555), monitor via auditd (-w), and ensure secrets are managed via vault instead of files."

🏁 Conclusion

DevOps without security is a risk multiplier.

By combining:

  • Strong access control
  • Secure pipelines
  • File-level protection
  • Continuous monitoring

You can transform your infrastructure into a resilient, production-ready system

πŸ™Œ Thank You..! πŸ˜ŠπŸ‘

If you found this article helpful: πŸ‘‰ Click the clap button πŸ‘‰ Drop a comment with your questions πŸ‘‰ Follow for more DevOps, Linux & Cloud tutorials