-
Notifications
You must be signed in to change notification settings - Fork 0
/
sshldapauthkey.py
executable file
·197 lines (157 loc) · 6.25 KB
/
sshldapauthkey.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#!/usr/bin/env python
# coding: utf-8
# vim: set ts=4 sts=4 sw=4 si ai et ft=python:
#
# Copyright (c) 2014, ZenRobotics Ltd.
# Author: Paul Tötterman <paul.totterman@zenrobotics.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""OpenSSH AuthorizedKeysCommand + LDAP helper.
To run tests:
python -m doctest sshldapauthkey.py
"""
import errno
import ldap
import ldap.filter
import logging
import logging.handlers
import re
import sys
BINDDN = '...'
BINDPW = ''
DEFAULT_OPTIONS = {'no-agent-forwarding': None,
'no-port-forwarding': None,
'no-pty': None,
'no-user-rc': None,
'no-X11-forwarding': None}
IGNORE_USERS = ['root']
LDAP_CONF = '/etc/ldap/ldap.conf'
PUBKEY_RE = re.compile(r'''^((?P<options>.*) )?'''
r'''(?P<type>ssh-(dss|rsa|ed25519)'''
r'''|ecdsa-sha2-nistp(256|384|521)) '''
r'''(?P<key>[^ ]*)( (?P<comment>.*))?$''')
def parse_ldap_base():
"""Parse LDAP base from ldap.conf(5)."""
# pylint: disable-msg=W0141
ldap_conf = open(LDAP_CONF, 'rb')
pattern = re.compile(r'^\s*[bB][aA][sS][eE]\s+(.+)\s*$')
matches = [pattern.search(x) for x in
ldap_conf.readlines()]
base = filter(None, matches)[0].group(1)
return base
def get_ldap_base(conn, persist={}):
"""Find out LDAP base."""
# pylint: disable-msg=W0102
if 'base' in persist:
return persist['base']
entries = conn.search_s('', ldap.SCOPE_BASE, 'objectClass=*', ('+',))
attrs = entries[0][1]
if len(attrs['namingContexts']) == 1:
base = attrs['namingContexts'][0]
else:
base = parse_ldap_base()
persist['base'] = base
return base
def format_options(options):
"""Format options dict for authorized_keys entry.
>>> format_options({'no-pty': None, 'command': '/bin/sh -i'})
'command="/bin/sh -i",no-pty'
"""
def format_option(option):
"""Format a single option."""
if options[option] is None:
return option
return '%s="%s"' % (option, options[option])
return ','.join([format_option(option) for option in options])
def parse_options(options):
"""Parse authorizes_keys entry options into python dict.
>>> parse_options('command="/bin/sh -i",no-pty,environment="SHELL=/bin/sh"')
{'environment': 'SHELL=/bin/sh', 'command': '/bin/sh -i', 'no-pty': None}
Known bugs:
>>> parse_options('environment="SHELL=bin/sh",environment="HOME=/"')
{'environment': 'HOME=/'}
>>> parse_options('command="/bin/echo \\\\"haha\\\\""')
{'command': '/bin/echo \\\\"haha\\\\'}
"""
result = {}
if options is None:
return result
for option in options.split(','):
if '=' in option:
key, val = option.split('=', 1)
result[key.lower()] = val.strip('"')
else:
result[option] = None
return result
def main(args):
"""Main function."""
# pylint: disable-msg=R0914
logging.getLogger().setLevel(logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler(sys.stderr))
loghandler = logging.handlers.SysLogHandler(address='/dev/log',
facility=logging.handlers.SysLogHandler.LOG_AUTH)
loghandler.setFormatter(logging.Formatter('sshldapauthkey %(levelname)-9s'
'%(message)s'))
logging.getLogger().addHandler(loghandler)
if len(args) != 1:
logging.critical('Usage: sshauthkey <USERNAME>')
sys.exit(1)
uid = args[0]
if uid in IGNORE_USERS:
return
conn = ldap.initialize(ldap.get_option(ldap.OPT_URI))
base = get_ldap_base(conn)
conn.simple_bind_s(BINDDN, BINDPW)
filterstr = ldap.filter.filter_format('(&(uid=%s)'
'(objectClass=posixAccount)'
'(objectClass=shadowAccount)'
'(objectClass=ldapPublicKey))',
(uid,))
results = conn.search_s(base, ldap.SCOPE_SUBTREE, filterstr,
('sshPublicKey',))
if len(results) != 1:
logging.error('too many results for uid=%s', uid)
sys.exit(2)
for result in results:
dname, attrs = result
if 'sshPublicKey' in attrs:
pubkeys = attrs['sshPublicKey']
for pubkey in pubkeys:
match = PUBKEY_RE.match(pubkey)
if not match:
logging.warning('Could not parse ssh key in dn %s: %s',
dname, pubkey)
continue
parts = match.groupdict()
typ = parts['type']
key = parts['key']
comment = parts['comment']
if typ == 'ssh-dss':
logging.error('DSA key type is no longer secure')
continue
options = parse_options(parts['options'])
options.update(DEFAULT_OPTIONS)
if options is None:
line = '%s %s %s' % (typ, key, comment)
else:
line = '%s %s %s %s' % (format_options(options), typ, key,
comment)
try:
print line
except IOError as ioe:
if ioe.errno == errno.EPIPE:
logging.debug('sshd closed pipe')
return
logging.exception('Exception when printing')
if __name__ == '__main__':
main(sys.argv[1:])