Skip to content

Instantly share code, notes, and snippets.

@jirutka
Last active July 17, 2024 10:40
Show Gist options
  • Save jirutka/b15c31b2739a4f3eab63 to your computer and use it in GitHub Desktop.
Save jirutka/b15c31b2739a4f3eab63 to your computer and use it in GitHub Desktop.
Simple script for OpenSSH server to load authorization keys from LDAP. It requires just POSIX shell and ldapsearch utility. To manage keys in LDAP, use https://github.com/jirutka/ssh-ldap-pubkey.
# /etc/ssh/ldap.conf
# See ldap.conf(5) for details
# This file should be world readable but not world writable.
BASE ou=People,dc=example,dc=org
URI ldap://localhost
#!/bin/sh
# vim: set ts=4:
#
# This script finds and prints authorized SSH public keys in LDAP for the
# username specified as the first argument.
#
# The program must be owned by root and not writable by group or others.
# It expects configuration file /etc/ssh/ldap.conf in format of ldap.conf(5).
#
# sshd_config for OpenSSH 6.2+:
#
# AuthorizedKeysCommand /usr/local/bin/ssh-keyldap
# AuthorizedKeysCommandUser nobody
#
set -eu
LDAPCONF='/etc/ssh/ldap.conf'
log() {
logger -s -t sshd -p "auth.$1" "$2"
}
uid="$1"
export LDAPCONF
if [ ! -r "$LDAPCONF" ]; then
log err "file $LDAPCONF does not exist or not readable"
exit 1
fi
if ! expr "$uid" : '[a-zA-Z0-9._-]*$' 1>/dev/null; then
log err "bad characters in username: $uid"
exit 2
fi
keys=$(ldapsearch -x -LLL -o ldif-wrap=no "(&(uid=$uid)(sshPublicKey=*))" \
'sshPublicKey' | sed -n 's/^sshPublicKey:\s*\(.*\)$/\1/p')
keys_count=$(echo "$keys" | grep '^ssh' | wc -l)
log info "Loaded $keys_count SSH public key(s) from LDAP for user: $uid"
echo "$keys"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment