Skip to main content

Incorrect Permission Assignment for Critical Resource using os Module

PY036
incorrect_permission
CWE-732
⚠️ Warning or ⛔️ Error

This rule identifies instances in code where potentially risky file or directory permission modes are being set using functions like chmod, fchmod, mknod, open, lchmod, and similar system calls. Setting inappropriate permission modes can lead to security vulnerabilities, including unauthorized access, data leakage, or privilege escalation.

Setting overly permissive modes (e.g., 0777, 0666) can expose files or directories to unauthorized access or modification. The rule flags instances where the mode may pose a security risk, particularly when:

  • Write permissions are granted to others (group or world): Modes like 0666 (read/write for everyone) or 0777 (read/write/execute for everyone) are inherently dangerous.
  • Inappropriate permissions for sensitive files: Configuration files, credential files, and other sensitive files should not be globally readable or writable.

Example

import os
import stat


# 0o755 for rwxr-xr-x
os.chmod(
"example.txt",
stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IXGRP |
stat.S_IROTH | stat.S_IXOTH,
)

Remediation

  • Restrict file permissions: Use more restrictive permission modes that limit access to only the necessary users.
  • Review file sensitivity: Ensure that sensitive files are protected with the appropriate permissions.
  • Apply the principle of least privilege: Only grant the minimum required permissions for the intended functionality.

Safer Permissions Examples:

  • For general files: 0644 (read/write for owner, read-only for group and others)
  • For sensitive files: 0600 (read/write for owner only)
  • For executable scripts: 0755 (read/write/execute for owner, read/execute for group and others)
import os
import stat


# 0o644 for rw-r--r--
os.chmod(
"example.txt",
stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH,
)

False Positives

In the case of a false positive the rule can be suppressed. Simply add a trailing or preceding comment line with either the rule ID (PY036) or rule category name (incorrect_permission).

Fix Iconfix
import os
import stat


# 0o755 for rwxr-xr-x
# suppress: PY036
os.chmod(
"example.txt",
stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IXGRP |
stat.S_IROTH | stat.S_IXOTH,
)

See also