In this lesson, you will learn how to monitor user session lifecycles by configuring PAM to trigger logging events exactly when a user logs in and logs out.
The Role of the session Stack
While the auth and account groups handle the initial entry into the system, the session group in PAM is responsible for actions that must occur immediately before and after a user session is active. By leveraging the pam_exec.so module, we can execute custom scripts or binary commands triggered by these lifecycle events.
Implementation Logic
To track sessions, we modify /etc/pam.d/common-session (or a specific service like sshd). The pam_exec module allows us to define commands that run with the user's context. Because PAM tracks both the opening and closing of a session, we can use environment variables provided by PAM to determine the current state.
When a session opens, the PAM_TYPE environment variable is set to open_session. When it closes, it is set to close_session. Here is how you might configure a tracking entry:
# Add to /etc/pam.d/common-session
session optional pam_exec.so /usr/local/bin/session_logger.sh
Within your /usr/local/bin/session_logger.sh script, you would implement logic like this:
#!/bin/bash
if [ "$PAM_TYPE" = "open_session" ]; then
echo "$(date): User $PAM_USER logged in from $PAM_RHOST" >> /var/log/user_sessions.log
elif [ "$PAM_TYPE" = "close_session" ]; then
echo "$(date): User $PAM_USER logged out" >> /var/log/user_sessions.log
fi
Why Use PAM for Tracking?
Unlike standard system logs that may rely on the application (like sshd) to report a logout, PAM provides a centralized gatekeeper approach. Since every session must pass through the session stack to be established or terminated, this method ensures that even if a user switches shells or uses different authentication methods, their session lifecycle is consistently recorded. This is invaluable for auditing compliance and detecting unauthorized session persistence.
Key Takeaway: By utilizing the pam_exec.so module within the session stack, you can create a reliable, centralized audit trail that automatically captures user login and logout timestamps based on the PAM_TYPE event variable.