LinuxMedium
Fix: Linux Permission Denied Errors
Command fails with 'Permission denied'
!Symptoms
- Command fails with 'Permission denied'
- Cannot read, write, or execute a file despite it existing
- SSH connection refused with 'Permission denied (publickey)'
- Scripts fail with permission errors when run by a service account
?Root Causes
- File ownership does not match the running user
- File permissions (chmod) are too restrictive
- SELinux or AppArmor blocking the action
- SSH key permissions too open (must be 600)
- Trying to bind to a privileged port (< 1024) without root
- sudo not configured for the user
#Diagnosis Steps
- 1Check file permissions: `ls -la <file>`
- 2Check current user: `whoami` and `id`
- 3Check SELinux status: `getenforce` and `ls -laZ <file>`
- 4For SSH: check key permissions `ls -la ~/.ssh/` (should be 700 for .ssh, 600 for keys)
- 5Check sudo access: `sudo -l`
>Fix
- 1Fix ownership: `chown <user>:<group> <file>`
- 2Fix permissions: `chmod 644 <file>` for files, `chmod 755 <dir>` for directories
- 3For SSH keys: `chmod 600 ~/.ssh/id_rsa && chmod 644 ~/.ssh/id_rsa.pub`
- 4Fix SELinux context: `restorecon -Rv <path>`
- 5For port binding: use a port > 1024 or grant capability: `setcap 'cap_net_bind_service=+ep' <binary>`
*Prevention
- Follow the principle of least privilege for file permissions
- Use groups to manage access instead of changing ownership frequently
- Document required permissions in deployment runbooks
- Use ansible/chef/puppet to enforce consistent permissions
- Set umask appropriately for service accounts
Related Error Messages
Permission deniedOperation not permittedPermission denied (publickey)EACCES: permission deniedcannot open shared object file