Failed to open PAM security session

If one day you notice that your super-duper script doesn’t work when executed from cron and crond itself is whining about:

CRON (username) ERROR: failed to open PAM security session: Success
CRON (username) ERROR: cannot set security context

Then the most obvious step from here is to take a look at /etc/pam.d/crond and /var/log/secure (if you’re running Redhat based Linux distro):

#
# The PAM configuration file for the cron daemon
#
#
auth       sufficient pam_rootok.so
auth       required   pam_env.so
auth       include    system-auth
account    required   pam_access.so
account    include    system-auth
session    required   pam_loginuid.so
session    include    system-auth

In case if /var/log/secure has similar lines check your /etc/security/access.conf and make sure that cron is allowed for everyone or at least for the user experiencing the problem:

pam_access(crond:account): access denied for user `username’ from `cron’

Otherwise, a word “session” should give you a hint on a possible issue with system-auth section. Lets check it:

cat /etc/pam.d/system-auth
#%PAM-1.0
# This file is auto-generated.
# User changes will be destroyed the next time authconfig is run.
auth        required      pam_env.so
auth        sufficient    pam_unix.so nullok try_first_pass
auth        requisite     pam_succeed_if.so uid >= 500 quiet
auth        required      pam_deny.so

account     required      pam_unix.so
account     sufficient    pam_succeed_if.so uid < 500 quiet
account     required      pam_permit.so

password    requisite     pam_cracklib.so try_first_pass retry=3
password    sufficient    pam_unix.so md5 shadow nullok try_first_pass use_authtok
password    required      pam_deny.so

session     optional      pam_keyinit.so revoke
session     required      pam_limits.so
session     [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session     required      pam_unix.so

The most critical module here is pam_unix.so which retrieves account information from /etc/passwd and /etc/shadow. Check them for the consistency because in my case /etc/shadow was a culprit missing a record for a username. Once it was fixed the errors had stopped popping up.