id: home-env-permission

info:
  name: User Home Directory and Shell Environment File Ownership & Permission
  author: songyaeji
  severity: medium
  description: |
    Shell startup and environment files (e.g., .bashrc, .bash_profile, .bash_logout) were not owned by the user or root and had insecure write permissions.Malicious users could manipulate environment variables or inject commands.
  reference:
    - https://isms.kisa.or.kr
  tags: linux,local,audit,compliance,kisa

self-contained: true

code:
  - engine:
      - sh
      - bash
    source: |
      for user in $(awk -F: '$6 ~ /^\/home/ {print $1}' /etc/passwd); do
        HOME_DIR=$(eval echo ~$user)
        find "$HOME_DIR" -maxdepth 1 -type f \
          \( -name ".bashrc" -o -name ".bash_profile" -o -name ".bash_logout" \) \
          -exec ls -l {} \; | awk -v usr="$user" '{print $0, "EXPECTED_USER="usr}'
      done

    matchers:
      - type: regex
        name: insecure-perms
        part: response
        regex:
          - "^-.{5}w"   # group writable
          - "^-.{8}w"   # other/world writable

      - type: regex
        name: invalid-owner
        part: response
        regex:
          - "^\\S+\\s+\\S+\\s+(?!root|.*EXPECTED_USER=)"
# digest: 490a0046304402200d1c1eb3e56074bf3daf7445e93706d95501decf32ee59f9d155f9d07f56d988022070e34135003e30cdd8a2aea1d25fef4df3cb8b9e354d0511a38a1dace28b16b0:922c64590222798bb761d5b6d8e72950