Skip to content

Instantly share code, notes, and snippets.

@frennkie
Forked from koenpunt/ldap_ssh_key.sh
Last active February 1, 2022 23:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save frennkie/390892c2c58efa2594046e888fe8054c to your computer and use it in GitHub Desktop.
Save frennkie/390892c2c58efa2594046e888fe8054c to your computer and use it in GitHub Desktop.
#!/bin/bash
# https://gist.github.com/koenpunt/40c0b042c453a1add0e8
#
# Check if the user is in the right group
# and afterwards retrieve the SSH public key from LDAP
# Logs directly in Syslog
# requires ldap-utils
#
# sshd_config for OpenSSH 6.2 or higher:
#
# AuthorizedKeysCommand /usr/local/bin/ldap_ssh_keys.sh (chmod 755)
# AuthorizedKeysCommandUser root
#
# Settings
LDAP_SERVER="ldap://dc1.example.com"
BASE_DN="dc=users,dc=example,dc=com"
ALLOWED_GROUP="4711"
ATTR_NAME_UID="sAMAccountName"
ATTR_NAME_SSH_PUBLIC_KEY="sshPublicKey"
# load local configuration if available
if [ -f /etc/example/ldap.cfg ]; then
. /etc/example/ldap.cfg
fi
HOSTNAME=$(echo `hostname`| cut -d"." -f1 | tr /a-z/ /A-Z/)
HOST_PRINCIPAL="${HOSTNAME}$"
SSH_USER=$1
if id "${SSH_USER}" | egrep -q "${ALLOWED_GROUP}";
then
logger -t sshd -p info "User $SSH_USER is a member of the group"
else
logger -t sshd -p warn "User $SSH_USER is not allowed to log in, access denied"
echo
exit 0
fi
KEY=$(kinit ${HOST_PRINCIPAL} -k -t /etc/krb5.keytab; ldapsearch -o ldif-wrap=no -S ${ATTR_NAME_SSH_PUBLIC_KEY} -c -H "${LDAP_SERVER}" -b "${BASE_DN}" -Q -LLL "${ATTR_NAME_UID}=${SSH_USER}" ${ATTR_NAME_SSH_PUBLIC_KEY} | grep -v '^dn:' | perl -pe "s/${ATTR_NAME_SSH_PUBLIC_KEY}: //;")
logger -t sshd -p info "Sent LDAP SSH public key for user $SSH_USER"
echo "${KEY}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment