Skip to content

Instantly share code, notes, and snippets.

@matsimon
Last active February 26, 2021 20:34
Show Gist options
  • Save matsimon/8539850 to your computer and use it in GitHub Desktop.
Save matsimon/8539850 to your computer and use it in GitHub Desktop.
Script used by 'AuthorizedKeysCommand' to retrieve SSH keys in an Active Directory (OpenSSH >= 6.2)
#!/bin/bash
username=`echo $1`
# AD needs authenticated binds, it's an unprivileged user
# use the UPN to write little less
ldapsearch \
-o ldif-wrap=no \
-D "srv-sshkeylookup@mydomain" \
-w "PlaintextPassword" \
-b "DC=mydomain,DC=example" \
'(&(objectClass=user)(!(lockoutTime>=1))(sAMAccountName='"$username"'))' \
'altSecurityIdentities' \
| sed -n '/^ /{H;d};/altSecurityIdentities: SSHKey:/x;$g;s/\n *//g;s/altSecurityIdentities: SSHKey://gp'
@matsimon
Copy link
Author

First of all, relies on having the (Debian) box joined to AD with Samba3 (not the sssd way) and the using pam_winbind. It does work with multiple keys stored in AD and also quite large ones.

Here are some thoughts on the why and how it works:

  • Line 4: As I rely on "winbind use default domain = no" in smb.conf, usernames are in the format of MYDOMAIN\username for
    AD users. Thus before the LDAP search, we have to cut the domain prefix. Ugly, admitting.
  • Line 9: Omits any kind of linewrapping messing up our sed magic at the very end.
  • Line 13: Attributes & Conditions to retrieve the key
    • objectClass=user: You do only want user to get login by key, not other objects, right?
    • !(lockoutTime>0): A locked (not disabled) account should have either 0 or value (otherwise locked users get a shell)
  • Line 14: On altSecurityIdentities, see prpoposed usage by http://www.sysadmin.org.au/index.php/2012/12/authorizedkeyscommand/ , in short: prefix the public keys with "SSHKey:"
  • Line 14: Another very ugly hack to cut the ssh keys out of the reply

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment