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" '{
            if ($3 != "root" && $3 != usr) print "INVALID_OWNER", $0
            else print $0
          }'
      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:
          - "^INVALID_OWNER"
# digest: 4b0a004830460221008f1026cc0254988a320127f54f6632957306601d6961aea2ac9a446cd5f6b9ab02210086b126c50bbc20138ad7477bb88eeaf1b605461def18dd415775fd23651b9758:922c64590222798bb761d5b6d8e72950