auth_server.py 8.53 KB
Newer Older
ale's avatar
ale committed
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
"""ai-webdav-auth-server

Simple authentication daemon for our WebDAV servers, that runs in an
isolated chroot and should not have the credentials to access LDAP
directly.

This server supports two kinds of requests (see dav.fcgi for the
client-side logic):

* given a UID, retrieve the known DAV accounts
* authenticate with UID/realm/username/password

Requests are sent through a UNIX socket, so that the server can know
the user ID of the process that made the request (the WebDAV FastCGI
runner).
"""

import contextlib
import grp
import json
import ldap
import ldap.dn
import logging
import logging.handlers
import optparse
import os
import pam
import pwd
import socket
import struct
import threading
try:
    import SocketServer
except ImportError:
    import socketserver as SocketServer

# Taken from <sys/socket.h>. Python 2 does not have this constant.
SO_PEERCRED = 17

# Default LDAP URI.
LDAP_DEFAULT_URI = 'ldapi:///var/run/ldap/ldapi'

# LDAP base UID.
LDAP_DEFAULT_BASE_UID = 'ou=People, dc=investici, dc=org, o=Anarchy'

# Service used for PAM.
PAM_SERVICE = 'dav'


pamh = pam.pam()


def getpeercred(sock):
    # This is Linux-specific.
    data = sock.getsockopt(socket.SOL_SOCKET, SO_PEERCRED, struct.calcsize('3i'))
    return struct.unpack('3i', data)


def ldap_bind(conn, dn, pw):
    # Separated for easier testing.
    conn.simple_bind_s(dn, pw)


class DavAuthServer(SocketServer.ThreadingMixIn,
                    SocketServer.UnixStreamServer):

    ldap_params = {
        'uri': LDAP_DEFAULT_URI,
        'base_uid': LDAP_DEFAULT_BASE_UID,
        'bind_dn': None,
        'bind_pw': None,
    }

    @contextlib.contextmanager
    def ldapconn(self, bind_dn=None, bind_pw=None):
        logging.info('LDAP connection to %s', self.ldap_params['uri'])
        c = ldap.initialize(self.ldap_params['uri'])
        try:
            if bind_dn:
                ldap_bind(c, bind_dn, bind_pw)
            elif self.ldap_params.get('bind_dn'):
                ldap_bind(c, self.ldap_params['bind_dn'], self.ldap_params['bind_pw'])
            yield c
        finally:
            c.unbind()


class DavAuthHandler(SocketServer.StreamRequestHandler):
    shard_id = None

    def handle(self):
        pid, uid, gid = getpeercred(self.request)
        logging.info('request from uid=%d gid=%d pid=%d', uid, gid, pid)
        try:
            request = json.load(self.rfile)
            if request['type'] == 'auth':
                response = self.authenticate(uid, request['dn'], request['password'])
            elif request['type'] == 'get_accounts':
                response = self.get_accounts(uid)
            else:
                raise ValueError('Unknown request type')
            response_data = json.dumps(response)
            self.wfile.write(response_data.encode('utf-8'))
        except Exception as e:
            logging.exception('request error from uid %d: %s', uid, e)

    def authenticate(self, uid, dn, password):
        # An empty password causes a "server is unwilling to perform"
        # error, so we might just as well handle it now.
        if not password:
            return 'error'
        try:
            # Check the account exists on this host and has the right
            # UID.  This is necessary so you can't log in to other
            # people's repositories!
            with self.server.ldapconn() as l:
                result = l.search_s(dn, ldap.SCOPE_BASE,
                        '(&(host=%s)(uidNumber=%d))' % (self.shard_id, uid))
                if len(result) == 0:
                    logging.error('account for %s uid %d not found on %s', dn,
                            uid, self.shard_id)
                    return 'error'

            # Defer the actual authentication to PAM, so we don't have
            # to actually check the password ourselves. Get the
            # username from the dn (ftpname=).
            username = ldap.dn.explode_dn(dn)[0][len("ftpname="):]
            if pamh.authenticate(username, password, service=PAM_SERVICE):
                return 'ok'
            logging.error('authentication failure for %s (uid=%d)', dn, uid)
            return 'error'
        except ldap.NO_SUCH_OBJECT:
            logging.error('cannot find object for %s (uid=%d)', dn, uid)
            return 'error'
        # Let other errors pass through and get caught (and logged) by the generic
        # exception handler one level up.
        return 'error'

    def get_accounts(self, uid):
        with self.server.ldapconn() as l:
            accounts = {}
            result = l.search_s(
                self.server.ldap_params['base_uid'], ldap.SCOPE_SUBTREE,
                '(&(objectClass=ftpAccount)(status=active)(uidNumber=%d)(host=%s))' % (uid, self.shard_id),
                ['ftpname', 'homeDirectory'])
            for r in result:
                name = r[1]['ftpname'][0].decode('utf-8')
                realm = '/dav/' + name
                accounts[realm] = {'dn': r[0],
                                   'ftpname': name,
                                   'home': r[1]['homeDirectory'][0].decode('utf-8')}
            return accounts


def run_server(socket_path, username, group, shard_id):
    # Set a permissive umask for the (eventual) mkdir.
    old_umask = os.umask(0o022)

    # Create the socket directory if it does not exist.
    socket_dir = os.path.dirname(socket_path)
    if not os.path.exists(socket_dir):
        os.makedirs(socket_dir, 0o755)

    # Delete the socket if it already exists.
    if os.path.exists(socket_path):
        os.unlink(socket_path)

    # Set the umask appropriately so that the socket has mode 777.
    os.umask(0)
    server = DavAuthServer(socket_path, DavAuthHandler)
    os.umask(old_umask)
    if username and group:
        drop_privs(username, group)
    server.serve_forever()


def drop_privs(username, group):
    if os.getuid() != 0:
        return

    userobj = pwd.getpwnam(username)
    grpobj = grp.getgrnam(group)

    os.setgid(grpobj.gr_gid)
    os.initgroups(username, grpobj.gr_gid)
    os.setuid(userobj.pw_uid)


def main():
    parser = optparse.OptionParser()
    parser.add_option('--ldap-uri', dest='ldap_uri', default=LDAP_DEFAULT_URI,
                      metavar='URI', help='LDAP URI connection string')
    parser.add_option('--ldap-bind-dn', dest='ldap_bind_dn',
                      metavar='DN', help='LDAP bind DN')
    parser.add_option('--ldap-bind-pw', dest='ldap_bind_pw',
                      metavar='PASS', help='LDAP bind password')
    parser.add_option('--ldap-bind-pwfile', dest='ldap_bind_pwfile',
                      metavar='FILE', default='/etc/ldap.secret',
                      help='Read LDAP bind password from this file')
    parser.add_option('--ldap-base-uid', dest='ldap_base_uid',
                      metavar='DN', default=LDAP_DEFAULT_BASE_UID,
                      help='Default LDAP base DN')
    parser.add_option('--shard-id', dest='shard_id',
                      metavar='ID', default=None,
                      help='Consider accounts for this shard id')
    parser.add_option('--user',
                      help='Run as a different user')
    parser.add_option('--group',
                      help='Run as a different group')
    parser.add_option('--socket', dest='socket_path',
                      default='/var/run/authdav/auth', metavar='PATH',
                      help='Location of the listening UNIX socket')
    opts, args = parser.parse_args()
    if len(args) != 0:
        parser.error('Too many arguments')

    # Set LDAP params.
    if opts.ldap_uri:
        DavAuthServer.ldap_params['uri'] = opts.ldap_uri
    if opts.ldap_base_uid:
        DavAuthServer.ldap_params['base_uid'] = opts.ldap_base_uid
    if opts.ldap_bind_dn:
        DavAuthServer.ldap_params['bind_dn'] = opts.ldap_bind_dn
        if opts.ldap_bind_pw:
            DavAuthServer.ldap_params['bind_pw'] = opts.ldap_bind_pw
        elif opts.ldap_bind_pwfile:
            with open(opts.ldap_bind_pwfile) as fd:
                DavAuthServer.ldap_params['bind_pw'] = fd.read().strip()
        else:
            parser.error('You must specify a bind password')

    if opts.shard_id:
        DavAuthHandler.shard_id = opts.shard_id

    # Configure syslog logging.
    handler = logging.handlers.SysLogHandler(
        address='/dev/log',
        facility=logging.handlers.SysLogHandler.LOG_DAEMON)
    handler.setFormatter(
        logging.Formatter('auth_server_dav: %(message)s'))
    root_logger = logging.getLogger()
    root_logger.setLevel(logging.INFO)
    root_logger.addHandler(handler)

    run_server(opts.socket_path, opts.user, opts.group, opts.shard_id)


if __name__ == '__main__':
    main()