#!/bin/sh

SOCKETDIR="/tmp"
SOCKET="${SOCKETDIR}/${PAM_USER}-${PAM_XDISPLAY}"
export DISPLAY=${PAM_XDISPLAY}
export SSH_ASKPASS="/usr/bin/shm_askpass"

test -x /usr/bin/daemon || exit 1

print_env () {
    logger "PAM_USER=${PAM_USER}"
    logger "PAM_SSHAUTH_HOST=${PAM_SSHAUTH_HOST}"
    logger "SOCKET=${SOCKET}"
    logger "DISPLAY=${DISPLAY}"
    W=$(whoami)
    logger "whoami: ${W}"
}

open_socket () {

    if [ -n "${DISPLAY}" ]; then
        #
        # We have a $DISPLAY variable set.  Spawn an ssh session.
        # Note, you must install the "daemon" package to obtain the "daemon"
        # utility.  This nice little program easily backgrounds any script or
        # command, and has the added advantage (for us) of disassociating from
        # the controlling terminal.  With no controlling terminal, and $DISPLAY
        # set, ssh will use the program specified in SSH_ASKPASS to obtain the
        # passowrd.  Since this was stored in the "auth" phase above,
        # shm_askpass will pass it to ssh for it to authenticate with.
        #

        daemon -i -- ssh -q -N -X -M -S "${SOCKET}" -l ${PAM_USER} ${PAM_SSHAUTH_HOST}
    fi
}

close_socket () {
    ssh -q -S "${SOCKET}" -O exit ${PAM_SSHAUTH_HOST}
}

#
# This is an example session helper script to be used in conjunction with
# pam_exec and libpam_sshauth.
#

case ${PAM_TYPE} in

auth)

    logger "___ Begin Auth ___"
    print_env

    #
    # We're authenticating, so we'll store the auth token using shm_askpass
    # shm_askpass --write will read a password from stdin, and store it in
    # POSIX shared memory.
    #

    shm_askpass --write

    logger "___ End Auth ___"

    ;;

open_session)

    logger "___ Begin Open_Session ___"
    print_env

    #
    # opening a session as user.  Spawn our ssh socket, this time as the
    # user.
    #

    open_socket

    logger "___ End Open_Session ___"

    ;;

close_session)

    #
    # We're closing the session down, so cause the socket to exit.
    #

    logger "___ Begin Close_Session ___"
    print_env
    close_socket
    logger "___ End Close_Session ___"

    ;;

esac

exit 0
