Description
Unnecessary read or write permissions may let other users read sensitive files or alter data. If the application trusts or executes altered content, the effect can extend to other resources accessible to its account.
Potential impact
- Data exposure: Unauthorized users may read sensitive files.
- Data tampering: Other users may modify file contents and undermine integrity.
- System damage: Modifying or deleting important files may disrupt the system.
Remediation
- Set permissions when creating a file or directory. On POSIX systems, use
0o600for a sensitive file that only the owner should read and write, or0o700for an owner-only directory that must also allow traversal. - If an existing path must not be overwritten, use
O_CREAT | O_EXCLwithos.opento reject an existing file or symbolic link. - Review existing files and directories periodically and remove access that is no longer needed.
Examples
File permissions
Before
python
# Unsafe file permissions
import os
file_path = 'sensitive_data.txt'
with open(file_path, 'w') as f:
f.write('Sensitive information')
# Excessive permissions let other users overwrite the file; execution risks depend on how it is used.
os.chmod(file_path, 0o777)
After
python
# Safe file permissions
import os
file_path = 'sensitive_data.txt'
# Atomically create a new file with mode 0o600; fail if a file or symbolic link already exists.
fd = os.open(file_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, 'w') as f:
f.write('Sensitive information')
Explanation
- Before: Excessive permissions let other users overwrite the file. Code execution depends on how the application uses the modified content.
- After:
O_CREAT | O_EXCLand0o600create the file with restricted permissions from the start. An existing file or symbolic link at the same path causes failure instead of being overwritten.
Directory permissions
Before
python
# Unsafe directory permissions
import os
dir_path = 'sensitive_dir'
os.mkdir(dir_path)
# Explicitly grant every user read, write and search permissions.
os.chmod(dir_path, 0o777)
After
python
# Safe directory permissions
import os
dir_path = 'sensitive_dir'
# Restrict access to the owner from the moment of creation.
os.mkdir(dir_path, mode=0o700)
Explanation
Passing 0o700 to os.mkdir restricts access to the owner from creation. The original 0o777 allowed other users to traverse the directory and change its contents.