Added ldap_postauth for edir
[freeradius.git] / src / modules / rlm_ldap / rlm_ldap.c
1 /*
2  * rlm_ldap.c   LDAP authorization and authentication module.
3  *
4  *   This program is free software; you can redistribute it and/or modify
5  *   it under the terms of the GNU General Public License as published by
6  *   the Free Software Foundation; either version 2 of the License, or
7  *   (at your option) any later version.
8  *
9  *   This program is distributed in the hope that it will be useful,
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *   GNU General Public License for more details.
13  *
14  *   You should have received a copy of the GNU General Public License
15  *   along with this program; if not, write to the Free Software
16  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  *
18  *   Copyright 1999,2000,2001,2002,2003,2004,2005,2006,2007,2008,
19  *             2009,2010,2011,1012 The FreeRADIUS Server Project.
20  *
21  *   Copyright 2012 Alan DeKok <aland@freeradius.org>
22  */
23
24 #include <freeradius-devel/ident.h>
25 RCSID("$Id$")
26
27 #include        <freeradius-devel/radiusd.h>
28 #include        <freeradius-devel/modules.h>
29 #include        <freeradius-devel/rad_assert.h>
30
31 #include        <stdarg.h>
32 #include        <ctype.h>
33
34 #include        <lber.h>
35 #include        <ldap.h>
36
37 #define MAX_ATTRMAP             128
38 #define MAX_ATTR_STR_LEN        256
39 #define MAX_FILTER_STR_LEN      1024
40
41 #ifdef WITH_EDIR
42 extern int nmasldap_get_password(LDAP *ld,char *objectDN, char *pwd, size_t *pwdSize);
43
44 #endif
45
46 typedef struct {
47         CONF_SECTION    *cs;
48         fr_connection_pool_t *pool;
49
50         char            *server;
51         int             port;
52
53         char            *login;
54         char            *password;
55
56         char            *filter;
57         char            *basedn;
58
59         int             chase_referrals;
60         int             rebind;
61
62         int             ldap_debug; /* Debug flag for LDAP SDK */
63
64         const char      *xlat_name; /* name used to xlat */
65
66         int             expect_password;
67         
68         /*
69          *      RADIUS attribute to LDAP attribute maps
70          */
71         VALUE_PAIR_MAP  *user_map;      /* Applied to users and profiles */
72         
73         /*
74          *      Access related configuration
75          */
76         char            *access_attr;
77         int             positive_access_attr;
78
79         /*
80          *      Profiles
81          */
82         char            *base_filter;
83         char            *default_profile;
84         char            *profile_attr;
85
86         /*
87          *      Group checking.
88          */
89         char            *groupname_attr;
90         char            *groupmemb_filter;
91         char            *groupmemb_attr;
92
93         /*
94          *      TLS items.  We should really normalize these with the
95          *      TLS code in 3.0.
96          */
97         int             tls_mode;
98         int             start_tls;
99         char            *tls_cacertfile;
100         char            *tls_cacertdir;
101         char            *tls_certfile;
102         char            *tls_keyfile;
103         char            *tls_randfile;
104         char            *tls_require_cert;
105
106         /*
107          *      Options
108          */
109         int             timelimit;
110         int             net_timeout;
111         int             timeout;
112         int             is_url;
113
114 #ifdef WITH_EDIR
115         /*
116          *      eDir support
117          */
118         int             edir;
119 #endif
120         /*
121          *      For keep-alives.
122          */
123 #ifdef LDAP_OPT_X_KEEPALIVE_IDLE
124         int             keepalive_idle;
125 #endif
126 #ifdef LDAP_OPT_X_KEEPALIVE_PROBES
127         int             keepalive_probes;
128 #endif
129 #ifdef LDAP_OPT_ERROR_NUMBER
130         int             keepalive_interval;
131 #endif
132
133 }  ldap_instance;
134
135 /* The default setting for TLS Certificate Verification */
136 #define TLS_DEFAULT_VERIFY "allow"
137
138 /*
139  *      TLS Configuration
140  */
141 static CONF_PARSER tls_config[] = {
142         {"start_tls", PW_TYPE_BOOLEAN,
143          offsetof(ldap_instance,start_tls), NULL, "no"},
144         {"cacertfile", PW_TYPE_FILENAME,
145          offsetof(ldap_instance,tls_cacertfile), NULL, NULL},
146         {"cacertdir", PW_TYPE_FILENAME,
147          offsetof(ldap_instance,tls_cacertdir), NULL, NULL},
148         {"certfile", PW_TYPE_FILENAME,
149          offsetof(ldap_instance,tls_certfile), NULL, NULL},
150         {"keyfile", PW_TYPE_FILENAME,
151          offsetof(ldap_instance,tls_keyfile), NULL, NULL},
152         {"randfile", PW_TYPE_STRING_PTR, /* OK if it changes on HUP */
153          offsetof(ldap_instance,tls_randfile), NULL, NULL},
154         {"require_cert", PW_TYPE_STRING_PTR,
155          offsetof(ldap_instance,tls_require_cert), NULL, TLS_DEFAULT_VERIFY},
156         { NULL, -1, 0, NULL, NULL }
157 };
158
159
160 static CONF_PARSER attr_config[] = {
161         /*
162          *      Access limitations
163          */
164         /* LDAP attribute name that controls remote access */
165         {"access_attr", PW_TYPE_STRING_PTR,
166          offsetof(ldap_instance,access_attr), NULL, NULL},
167         {"positive_access_attr", PW_TYPE_BOOLEAN,
168          offsetof(ldap_instance,positive_access_attr), NULL, "yes"},
169
170         {"base_filter", PW_TYPE_STRING_PTR,
171          offsetof(ldap_instance,base_filter), NULL,
172          "(objectclass=radiusprofile)"},
173         {"default_profile", PW_TYPE_STRING_PTR,
174          offsetof(ldap_instance,default_profile), NULL, NULL},
175         {"profile_attribute", PW_TYPE_STRING_PTR,
176          offsetof(ldap_instance,profile_attr), NULL, NULL},
177
178         { NULL, -1, 0, NULL, NULL }
179 };
180
181
182 /*
183  *      Group configuration
184  */
185 static CONF_PARSER group_config[] = {
186         /*
187          *      Group checks.  These could probably be done
188          *      via dynamic xlat's.
189          */
190         {"name_attribute", PW_TYPE_STRING_PTR,
191          offsetof(ldap_instance,groupname_attr), NULL, "cn"},
192         {"membership_filter", PW_TYPE_STRING_PTR,
193          offsetof(ldap_instance,groupmemb_filter), NULL,
194          "(|(&(objectClass=GroupOfNames)(member=%{Ldap-UserDn}))"
195          "(&(objectClass=GroupOfUniqueNames)(uniquemember=%{Ldap-UserDn})))"},
196         {"membership_attribute", PW_TYPE_STRING_PTR,
197          offsetof(ldap_instance,groupmemb_attr), NULL, NULL},
198
199
200         { NULL, -1, 0, NULL, NULL }
201 };
202
203 /*
204  *      Various options that don't belong in the main configuration.
205  *
206  *      Note that these overlap a bit with the connection pool code!
207  */
208 static CONF_PARSER option_config[] = {
209         /*
210          *      Debugging flags to the server
211          */
212         {"ldap_debug", PW_TYPE_INTEGER,
213          offsetof(ldap_instance,ldap_debug), NULL, "0x0000"},
214
215         {"chase_referrals", PW_TYPE_BOOLEAN,
216          offsetof(ldap_instance,chase_referrals), NULL, NULL},
217
218         {"rebind", PW_TYPE_BOOLEAN,
219          offsetof(ldap_instance,rebind), NULL, NULL},
220
221         /* timeout on network activity */
222         {"net_timeout", PW_TYPE_INTEGER,
223          offsetof(ldap_instance,net_timeout), NULL, "10"},
224
225         /* timeout for search results */
226         {"timeout", PW_TYPE_INTEGER,
227          offsetof(ldap_instance,timeout), NULL, "20"},
228
229         /* allow server unlimited time for search (server-side limit) */
230         {"timelimit", PW_TYPE_INTEGER,
231          offsetof(ldap_instance,timelimit), NULL, "20"},
232
233 #ifdef LDAP_OPT_X_KEEPALIVE_IDLE
234         {"idle", PW_TYPE_INTEGER,
235          offsetof(ldap_instance,keepalive_idle), NULL, "60"},
236 #endif
237 #ifdef LDAP_OPT_X_KEEPALIVE_PROBES
238         {"probes", PW_TYPE_INTEGER,
239          offsetof(ldap_instance,keepalive_probes), NULL, "3"},
240 #endif
241 #ifdef LDAP_OPT_ERROR_NUMBER
242         {"interval", PW_TYPE_INTEGER, 
243          offsetof(ldap_instance,keepalive_interval), NULL, "30"},
244 #endif
245         { NULL, -1, 0, NULL, NULL }
246 };
247
248
249 static const CONF_PARSER module_config[] = {
250         {"server", PW_TYPE_STRING_PTR,
251          offsetof(ldap_instance,server), NULL, "localhost"},
252         {"port", PW_TYPE_INTEGER,
253          offsetof(ldap_instance,port), NULL, "389"},
254
255         {"password", PW_TYPE_STRING_PTR,
256          offsetof(ldap_instance,password), NULL, ""},
257         {"identity", PW_TYPE_STRING_PTR,
258          offsetof(ldap_instance,login), NULL, ""},
259
260         /*
261          *      DN's and filters.
262          */
263         {"basedn", PW_TYPE_STRING_PTR,
264          offsetof(ldap_instance,basedn), NULL, "o=notexist"},
265
266         {"filter", PW_TYPE_STRING_PTR,
267          offsetof(ldap_instance,filter), NULL, "(uid=%u)"},
268
269         /* turn off the annoying warning if we don't expect a password */
270         {"expect_password", PW_TYPE_BOOLEAN,
271          offsetof(ldap_instance,expect_password), NULL, "yes"},
272          
273 #ifdef WITH_EDIR
274         /* support for eDirectory Universal Password */
275         {"edir", PW_TYPE_BOOLEAN,
276          offsetof(ldap_instance,edir), NULL, NULL}, /* NULL defaults to "no" */
277 #endif
278
279         /*
280          *      Terrible things which should be deleted.
281          */
282         { "profiles", PW_TYPE_SUBSECTION, 0, NULL, (const void *) attr_config },
283
284         { "group", PW_TYPE_SUBSECTION, 0, NULL, (const void *) group_config },
285
286         { "options", PW_TYPE_SUBSECTION, 0, NULL,
287          (const void *) option_config },
288
289         { "tls", PW_TYPE_SUBSECTION, 0, NULL, (const void *) tls_config },
290
291         { "profiles", PW_TYPE_SUBSECTION, 0, NULL, (const void *) attr_config },
292
293         {NULL, -1, 0, NULL, NULL}
294 };
295
296 typedef struct ldap_conn {
297         LDAP    *handle;
298         int     rebound;
299         int     referred;
300         ldap_instance *inst;
301 } LDAP_CONN;
302
303 typedef struct xlat_attrs {
304         const VALUE_PAIR_MAP *maps;
305         const char *attrs[MAX_ATTRMAP];
306 } xlat_attrs_t;
307
308 typedef struct rlm_ldap_result {
309         char    **values;
310         int     count;
311 } rlm_ldap_result_t;
312
313
314 #if LDAP_SET_REBIND_PROC_ARGS == 3
315 /*
316  *      Rebind && chase referral stuff
317  */
318 static int ldap_rebind(LDAP *handle, LDAP_CONST char *url,
319                        UNUSED ber_tag_t request, UNUSED ber_int_t msgid,
320                        void *ctx )
321 {
322         LDAP_CONN *conn = ctx;
323
324         conn->referred = TRUE;
325         conn->rebound = TRUE;   /* not really, but oh well... */
326         rad_assert(handle == conn->handle);
327
328         DEBUG("rlm_ldap (%s): Rebinding to URL %s", conn->inst->xlat_name, url);
329         
330         return ldap_bind_s(handle, conn->inst->login, conn->inst->password,
331                            LDAP_AUTH_SIMPLE);
332 }
333 #endif
334
335 static int ldap_bind_wrapper(LDAP_CONN **pconn, const char *user,
336                              const char *password,
337                              const char **perror_str, int do_rebind)
338 {
339         int             rcode, ldap_errno;
340         int             module_rcode = RLM_MODULE_FAIL;
341         int             reconnect = FALSE;
342         const char      *error_string;
343         LDAP_CONN       *conn = *pconn;
344         ldap_instance   *inst = conn->inst;
345         LDAPMessage     *result = NULL;
346         struct timeval tv;
347
348 redo:
349         ldap_errno = ldap_bind(conn->handle, user, password, LDAP_AUTH_SIMPLE);
350         if (ldap_errno < 0) {
351         get_error:
352                 ldap_get_option(conn->handle, LDAP_OPT_ERROR_NUMBER,
353                                 &ldap_errno);
354                 error_string = ldap_err2string(ldap_errno);
355
356                 if (do_rebind && !reconnect) {
357                         conn = fr_connection_reconnect(inst->pool, conn);
358                         *pconn = conn;
359                         if (!conn) return RLM_MODULE_FAIL;
360                         goto redo;
361                 }
362
363         print_error:
364                 if (perror_str) *perror_str = error_string;
365
366 #ifdef HAVE_LDAP_INITIALIZE
367                 if (inst->is_url) {
368                         radlog(L_ERR, "rlm_ldap (%s): %s bind to %s failed: %s",
369                                inst->xlat_name, user,
370                                inst->server, error_string);
371                 } else
372 #endif
373                 {
374                         radlog(L_ERR, "rlm_ldap (%s): %s bind to %s:%d "
375                                       "failed: %s",
376                                inst->xlat_name, user,
377                                inst->server, inst->port,
378                                error_string);
379                 }
380
381                 return module_rcode; /* caller closes the connection */
382         }
383
384         DEBUG3("rlm_ldap (%s): Waiting for bind result...", inst->xlat_name);
385
386         tv.tv_sec = inst->timeout;
387         tv.tv_usec = 0;
388         rcode = ldap_result(conn->handle, ldap_errno, 1, &tv, &result);
389         if (rcode < 0) goto get_error;
390
391         if (rcode == 0) {
392                 error_string = "timeout";
393                 goto print_error;
394         }
395
396         ldap_errno = ldap_result2error(conn->handle, result, 1);
397         switch (ldap_errno) {
398         case LDAP_SUCCESS:
399                 break;
400
401         case LDAP_INVALID_CREDENTIALS:
402         case LDAP_CONSTRAINT_VIOLATION:
403                 rcode = RLM_MODULE_REJECT;
404                 /* FALL-THROUGH */
405
406         default:
407                 goto get_error;
408         }
409
410         return RLM_MODULE_OK;
411 }
412
413 /*************************************************************************
414  *
415  *      Function: ldap_conn_create
416  *
417  *      Purpose: Create and return a new connection
418  *      This function is probably too big.
419  *
420  *************************************************************************/
421 static void *ldap_conn_create(void *ctx)
422 {
423         int module_rcode;
424         int ldap_errno, ldap_version;
425         struct timeval tv;
426         ldap_instance *inst = ctx;
427         LDAP *handle = NULL;
428         LDAP_CONN *conn = NULL;
429         const char *error;
430
431 #ifdef HAVE_LDAP_INITIALIZE
432         if (inst->is_url) {
433                 DEBUG("rlm_ldap (%s): Connect to %s", inst->xlat_name,
434                       inst->server);
435
436                 ldap_errno = ldap_initialize(&handle, inst->server);
437
438                 if (ldap_errno != LDAP_SUCCESS) {
439                         radlog(L_ERR, "rlm_ldap (%s): ldap_initialize() "
440                                "failed: %s",
441                                inst->xlat_name, ldap_err2string(ldap_errno));
442                         goto conn_fail;
443                 }
444         } else
445 #endif
446         {
447                 DEBUG("rlm_ldap (%s): Connect to %s:%d", inst->xlat_name,
448                       inst->server, inst->port);
449
450                 handle = ldap_init(inst->server, inst->port);
451                 if (!handle) {
452                         radlog(L_ERR, "rlm_ldap (%s): ldap_init() failed",
453                                inst->xlat_name);
454                 conn_fail:
455                         if (handle) ldap_unbind_s(handle);
456                         return NULL;
457                 }
458         }
459
460         /*
461          *      We now have a connection structure, but no actual TCP connection.
462          *
463          *      Set a bunch of LDAP options, using common code.
464          */
465 #define do_ldap_option(_option, _name, _value) \
466         if (ldap_set_option(handle, _option, _value) != LDAP_OPT_SUCCESS) { \
467                 ldap_get_option(handle, LDAP_OPT_ERROR_NUMBER, &ldap_errno); \
468                 radlog(L_ERR, "rlm_ldap (%s): Could not set %s: %s", \
469                        inst->xlat_name, _name, ldap_err2string(ldap_errno)); \
470         }
471                 
472         if (inst->ldap_debug) {
473                 do_ldap_option(LDAP_OPT_DEBUG_LEVEL, "ldap_debug",
474                                &(inst->ldap_debug));
475         }
476
477         /*
478          *      Leave "chase_referrals" unset to use the OpenLDAP
479          *      default.
480          */
481         if (inst->chase_referrals != 2) {
482                 if (inst->chase_referrals) {
483                         do_ldap_option(LDAP_OPT_REFERRALS, "chase_referrals",
484                                        LDAP_OPT_ON);
485                         
486 #if LDAP_SET_REBIND_PROC_ARGS == 3
487                         if (inst->rebind == 1) {
488                                 ldap_set_rebind_proc(handle, ldap_rebind, inst);
489                         }
490 #endif
491                 } else {
492                         do_ldap_option(LDAP_OPT_REFERRALS, "chase_referrals",
493                                        LDAP_OPT_OFF);
494                 }
495         }
496
497         tv.tv_sec = inst->net_timeout;
498         tv.tv_usec = 0;
499         do_ldap_option(LDAP_OPT_NETWORK_TIMEOUT, "net_timeout", &tv);
500
501         do_ldap_option(LDAP_OPT_TIMELIMIT, "timelimit",
502                        &(inst->timelimit));
503
504         ldap_version = LDAP_VERSION3;
505         do_ldap_option(LDAP_OPT_PROTOCOL_VERSION, "ldap_version",
506                        &ldap_version);
507
508 #ifdef LDAP_OPT_X_KEEPALIVE_IDLE
509         do_ldap_option(LDAP_OPT_X_KEEPALIVE_IDLE, "keepalive idle",
510                        &(inst->keepalive_idle));
511 #endif
512
513 #ifdef LDAP_OPT_X_KEEPALIVE_PROBES
514         do_ldap_option(LDAP_OPT_X_KEEPALIVE_PROBES, "keepalive probes",
515                        &(inst->keepalive_probes));
516 #endif
517
518 #ifdef LDAP_OPT_X_KEEPALIVE_INTERVAL
519         do_ldap_option(LDAP_OPT_X_KEEPALIVE_INTERVAL, "keepalive interval",
520                        &(inst->keepalive_interval));
521 #endif
522
523 #ifdef HAVE_LDAP_START_TLS
524         /*
525          *      Set all of the TLS options
526          */
527         if (inst->tls_mode) {
528                 do_ldap_option(LDAP_OPT_X_TLS, "tls_mode", &(inst->tls_mode));
529         }
530
531 #define maybe_ldap_option(_option, _name, _value) \
532         if (_value) do_ldap_option(_option, _name, _value)
533
534         maybe_ldap_option(LDAP_OPT_X_TLS_CACERTFILE,
535                           "cacertfile", inst->tls_cacertfile);
536         maybe_ldap_option(LDAP_OPT_X_TLS_CACERTDIR,
537                           "cacertdir", inst->tls_cacertdir);
538
539 #ifdef HAVE_LDAP_INT_TLS_CONFIG
540         if (ldap_int_tls_config(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT,
541                                 (inst->tls_require_cert)) != LDAP_OPT_SUCCESS) {
542                 ldap_get_option(handle, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
543                 radlog(L_ERR, "rlm_ldap (%s): could not set ", 
544                        "LDAP_OPT_X_TLS_REQUIRE_CERT option to %s: %s",
545                        inst->xlat_name, 
546                        inst->tls_require_cert,
547                        ldap_err2string(ldap_errno));
548         }
549 #endif
550
551         maybe_ldap_option(LDAP_OPT_X_TLS_CERTFILE,
552                           "certfile", inst->tls_certfile);
553         maybe_ldap_option(LDAP_OPT_X_TLS_KEYFILE,
554                           "keyfile", inst->tls_keyfile);
555         maybe_ldap_option(LDAP_OPT_X_TLS_RANDOM_FILE,
556                           "randfile", inst->tls_randfile);
557
558         /*
559          *      And finally start the TLS code.
560          */
561         if (inst->start_tls && (inst->port != 636)) {
562                 ldap_errno = ldap_start_tls_s(handle, NULL, NULL);
563                 if (ldap_errno != LDAP_SUCCESS) {
564                         ldap_get_option(handle, LDAP_OPT_ERROR_NUMBER,
565                                         &ldap_errno);
566                         radlog(L_ERR, "rlm_ldap (%s): could not start TLS: %s",
567                                inst->xlat_name,
568                                ldap_err2string(ldap_errno));
569                         goto conn_fail;
570                 }
571         }
572 #endif /* HAVE_LDAP_START_TLS */
573
574         conn = rad_malloc(sizeof(*conn));
575         conn->inst = inst;
576         conn->handle = handle;
577         conn->rebound = FALSE;
578         conn->referred = FALSE;
579
580         module_rcode = ldap_bind_wrapper(&conn, inst->login, inst->password,
581                                          &error, FALSE);
582         if (module_rcode != RLM_MODULE_OK) {
583                 radlog(L_ERR, "rlm_ldap (%s): failed binding to LDAP "
584                        "server: %s",
585                        inst->xlat_name, error);
586
587                 /*
588                  *      FIXME: print "check config, morians!
589                  */
590                 goto conn_fail;
591         }
592
593         return conn;
594 }
595
596
597 /*************************************************************************
598  *
599  *      Function: ldap_conn_delete
600  *
601  *      Purpose: Close and delete a connection
602  *
603  *************************************************************************/
604 static int ldap_conn_delete(UNUSED void *ctx, void *connection)
605 {
606         LDAP_CONN *conn = connection;
607
608         ldap_unbind_s(conn->handle);
609         free(conn);
610
611         return 0;
612 }
613
614
615 /*************************************************************************
616  *
617  *      Function: ldap_get_socket
618  *
619  *      Purpose: Gets an LDAP socket from the connection pool
620  *
621  *************************************************************************/
622 static LDAP_CONN *ldap_get_socket(ldap_instance *inst)
623 {
624         LDAP_CONN *conn;
625
626         conn = fr_connection_get(inst->pool);
627         if (!conn) {
628                 radlog(L_ERR, "rlm_ldap (%s): all ldap connections are in use",
629                        inst->xlat_name);
630                 return NULL;
631         }
632
633         return conn;
634 }
635
636 /*************************************************************************
637  *
638  *      Function: ldap_release_socket
639  *
640  *      Purpose: Frees an LDAP socket back to the connection pool
641  *
642  *************************************************************************/
643 static void ldap_release_socket(ldap_instance *inst, LDAP_CONN *conn)
644 {
645         /*
646          *      Could have already been free'd due to a previous error.
647          */
648         if (!conn) return;
649
650         /*
651          *      We chased a referral to another server.
652          *
653          *      This connection is no longer part of the pool which is
654          *      connected to and bound to the configured server.
655          *      Close it.
656          *
657          *      Note that we do NOT close it if it was bound to
658          *      another user.  Instead, we let the next caller do the
659          *      rebind.
660          */
661         if (conn->referred) {
662                 fr_connection_del(inst->pool, conn);
663                 return;
664         }
665
666         fr_connection_release(inst->pool, conn);
667         return;
668 }
669
670
671 /*************************************************************************
672  *
673  *      Function: ldap_escape_func
674  *
675  *      Purpose: Converts "bad" strings into ones which are safe for LDAP
676  *
677  *************************************************************************/
678 static size_t ldap_escape_func(UNUSED REQUEST *request, char *out,
679                                size_t outlen, const char *in, UNUSED void *arg)
680 {
681         size_t len = 0;
682
683         while (in[0]) {
684                 /*
685                  *      Encode unsafe characters.
686                  */
687                 if (((len == 0) &&
688                     ((in[0] == ' ') || (in[0] == '#'))) ||
689                     (strchr(",+\"\\<>;*=()", *in))) {
690                         static const char hex[] = "0123456789abcdef";
691
692                         /*
693                          *      Only 3 or less bytes available.
694                          */
695                         if (outlen <= 3) {
696                                 break;
697                         }
698
699                         *(out++) = '\\';
700                         *(out++) = hex[((*in) >> 4) & 0x0f];
701                         *(out++) = hex[(*in) & 0x0f];
702                         outlen -= 3;
703                         len += 3;
704                         in++;
705                         continue;
706                 }
707
708                 /*
709                  *      Only one byte left.
710                  */
711                 if (outlen <= 1) {
712                         break;
713                 }
714
715                 /*
716                  *      Allowed character.
717                  */
718                 *(out++) = *(in++);
719                 outlen--;
720                 len++;
721         }
722         *out = '\0';
723         return len;
724 }
725
726 /*************************************************************************
727  *
728  *      Function: perform_search
729  *
730  *      Purpose: Do a search and get a response
731  *
732  *************************************************************************/
733 static int perform_search(ldap_instance *inst, REQUEST *request,
734                           LDAP_CONN **pconn, const char *search_basedn,
735                           int scope, const char *filter, 
736                           const char * const *attrs, LDAPMessage **presult)
737 {
738         int             ldap_errno;
739         int             count = 0;
740         int             reconnect = FALSE;
741         LDAP_CONN       *conn = *pconn;
742         struct timeval  tv;
743
744         /*
745          *      OpenLDAP library doesn't declare attrs array as const, but
746          *      it really should be *sigh*.
747          */
748         char **search_attrs;
749         memcpy(&search_attrs, &attrs, sizeof(attrs));
750
751         *presult = NULL;
752
753         /*
754          *      Do all searches as the default admin user.
755          */
756         if (conn->rebound) {
757                 ldap_errno = ldap_bind_wrapper(pconn,
758                                                inst->login, inst->password,
759                                                NULL, TRUE);
760                 if (ldap_errno != RLM_MODULE_OK) {
761                         return -1;
762                 }
763
764                 rad_assert(*pconn != NULL);
765                 conn = *pconn;
766                 conn->rebound = FALSE;
767         }
768
769         tv.tv_sec = inst->timeout;
770         tv.tv_usec = 0;
771         RDEBUG2("Performing search in '%s' with filter '%s'",
772                 search_basedn ? search_basedn : "(null)" ,
773                 filter);
774
775 retry:
776         ldap_errno = ldap_search_ext_s(conn->handle, search_basedn, scope,
777                                        filter, search_attrs, 0, NULL, NULL,
778                                        &tv, 0, presult);
779         switch (ldap_errno) {
780         case LDAP_SUCCESS:
781         case LDAP_NO_SUCH_OBJECT:
782                 break;
783
784         case LDAP_SERVER_DOWN:
785         do_reconnect:
786                 ldap_msgfree(*presult);
787
788                 if (reconnect) return -1;
789                 reconnect = TRUE;
790
791                 conn = fr_connection_reconnect(inst->pool, conn);
792                 *pconn = conn;  /* tell the caller we have a new connection */
793                 if (!conn) return -1;
794                 goto retry;
795
796         case LDAP_INSUFFICIENT_ACCESS:
797                 radlog(L_ERR, "rlm_ldap (%s): Search failed: "
798                        "Insufficient access. Check the identity and password "
799                        "configuration directives", inst->xlat_name);
800                 ldap_msgfree(*presult);
801                 return -1;
802
803         case LDAP_TIMEOUT:
804                 exec_trigger(NULL, inst->cs, "modules.ldap.timeout", TRUE);
805                 radlog(L_ERR, "rlm_ldap (%s): Search failed: Timed out "
806                        "while waiting for server to respond"
807                        "Please increase the timeout", inst->xlat_name);
808                 ldap_msgfree(*presult);
809                 return -1;
810
811         case LDAP_FILTER_ERROR:
812                 radlog(L_ERR, "rlm_ldap (%s): Search failed: Bad search "
813                        "filter: %s", inst->xlat_name,filter);
814                 ldap_msgfree(*presult);
815                 return -1;
816
817         case LDAP_TIMELIMIT_EXCEEDED:
818                 exec_trigger(NULL, inst->cs, "modules.ldap.timeout", TRUE);
819
820         case LDAP_BUSY:
821         case LDAP_UNAVAILABLE:
822                 /*
823                  *      Reconnect.  There's an issue with the socket
824                  *      or LDAP server.
825                  */
826                 ldap_get_option(conn->handle, LDAP_OPT_ERROR_NUMBER,
827                                 &ldap_errno);
828                 radlog(L_ERR, "rlm_ldap (%s): Search failed: %s",
829                        inst->xlat_name, ldap_err2string(ldap_errno));
830                 goto do_reconnect;
831
832         default:
833                 ldap_get_option(conn->handle, LDAP_OPT_ERROR_NUMBER,
834                                 &ldap_errno);
835                 radlog(L_ERR, "rlm_ldap (%s): Search failed: %s",
836                        inst->xlat_name, ldap_err2string(ldap_errno));
837                 ldap_msgfree(*presult);
838                 return -1;
839         }
840
841         count = ldap_count_entries(conn->handle, *presult);
842         if (count == 0) {
843                 ldap_msgfree(*presult);
844                 RDEBUG("Search returned no results");
845                 
846                 return -2;
847         }
848
849         if (count != 1) {
850                 ldap_msgfree(*presult);
851                 RDEBUG("Got ambiguous search result (%d results)", count);
852                       
853                 return -2;
854         }
855
856         return 0;
857 }
858
859 /*************************************************************************
860  *
861  *      Function: ldap_xlat
862  *
863  *      Purpose: Expand an LDAP URL into a query, and return a string
864  *              result from that query.
865  *
866  *************************************************************************/
867 static size_t ldap_xlat(void *instance, REQUEST *request, const char *fmt,
868                         char *out, size_t freespace)
869 {
870         int rcode;
871         size_t length = 0;
872         ldap_instance *inst = instance;
873         LDAPURLDesc *ldap_url;
874         LDAPMessage *result = NULL;
875         LDAPMessage *entry = NULL;
876         char **vals;
877         LDAP_CONN *conn;
878         int ldap_errno;
879         const char *url;
880         const char **attrs;
881         char buffer[MAX_FILTER_STR_LEN];
882
883         if (strchr(fmt, '%') != NULL) {
884                 if (!radius_xlat(buffer, sizeof(buffer), fmt, request,
885                                  ldap_escape_func, NULL)) {
886                         radlog(L_ERR,
887                                "rlm_ldap (%s): Unable to create LDAP URL", 
888                                inst->xlat_name);
889                         return 0;
890                 }
891                 url = buffer;
892         } else {
893                 url = fmt;
894         }
895
896         if (!ldap_is_ldap_url(url)) {
897                 radlog(L_ERR, "rlm_ldap (%s): String passed does not look "
898                        "like an LDAP URL", inst->xlat_name);
899                 return 0;
900         }
901
902         if (ldap_url_parse(url, &ldap_url)){
903                 radlog(L_ERR, "rlm_ldap (%s): Parsing LDAP URL failed",
904                        inst->xlat_name);
905                 return 0;
906         }
907
908         /*
909          *      Nothing, empty string, "*" string, or got 2 things, die.
910          */
911         if (!ldap_url->lud_attrs || !ldap_url->lud_attrs[0] ||
912             !*ldap_url->lud_attrs[0] ||
913             (strcmp(ldap_url->lud_attrs[0], "*") == 0) ||
914             ldap_url->lud_attrs[1]) {
915                 radlog(L_ERR, "rlm_ldap (%s): Bad attributes list in LDAP "
916                        "URL. URL must specify exactly one attribute to "
917                        "retrieve",
918                        inst->xlat_name);
919                        
920                 goto free_urldesc;
921         }
922
923         if (ldap_url->lud_host &&
924             ((strncmp(inst->server, ldap_url->lud_host,
925                       strlen(inst->server)) != 0) ||
926              (ldap_url->lud_port != inst->port))) {
927                 RDEBUG("Requested server/port is \"%s:%i\"", ldap_url->lud_host,
928                        inst->port);
929                 
930                 goto free_urldesc;
931         }
932
933         conn = ldap_get_socket(inst);
934         if (!conn) goto free_urldesc;
935
936         memcpy(&attrs, &ldap_url->lud_attrs, sizeof(attrs));
937         
938         rcode = perform_search(inst, request, &conn, ldap_url->lud_dn, 
939                                ldap_url->lud_scope, ldap_url->lud_filter, attrs,
940                                &result);
941         if (rcode < 0) {
942                 if (rcode == -2) {
943                         RDEBUG("Search returned not found", inst->xlat_name);
944                         goto free_socket;
945                 }
946
947                 goto free_socket;
948         }
949
950         entry = ldap_first_entry(conn->handle, result);
951         if (!entry) {
952                 ldap_get_option(conn->handle, LDAP_OPT_RESULT_CODE,
953                                 &ldap_errno);
954                 radlog(L_ERR, "rlm_ldap (%s): Failed retrieving entry: %s", 
955                        inst->xlat_name,
956                        ldap_err2string(ldap_errno));
957                 goto free_result;
958         }
959
960         vals = ldap_get_values(conn->handle, entry, ldap_url->lud_attrs[0]);
961         if (!vals) {
962                 RDEBUG("No \"%s\" attributes found in specified object",
963                        inst->xlat_name, ldap_url->lud_attrs[0]);
964                 goto free_result;
965         }
966
967         length = strlen(vals[0]);
968         if (length >= freespace){
969
970                 goto free_vals;
971         }
972
973         strlcpy(out, vals[0], freespace);
974
975 free_vals:
976         ldap_value_free(vals);
977 free_result:
978         ldap_msgfree(result);
979 free_socket:
980         ldap_release_socket(inst, conn);
981 free_urldesc:
982         ldap_free_urldesc(ldap_url);
983
984         return length;
985 }
986
987
988 static char *get_userdn(LDAP_CONN **pconn, REQUEST *request, int *module_rcode)
989 {
990         int             rcode;
991         VALUE_PAIR      *vp;
992         ldap_instance   *inst = (*pconn)->inst;
993         LDAP            *handle = (*pconn)->handle;
994         LDAPMessage     *result, *entry;
995         int             ldap_errno;
996         static char     firstattr[] = "uid";
997         char            *user_dn;
998         const char      *attrs[] = {firstattr, NULL};
999         char            filter[MAX_FILTER_STR_LEN];     
1000         char            basedn[MAX_FILTER_STR_LEN];     
1001
1002         *module_rcode = RLM_MODULE_FAIL;
1003
1004         vp = pairfind(request->config_items, PW_LDAP_USERDN, 0);
1005         if (vp) return vp->vp_strvalue;
1006
1007         if (!radius_xlat(filter, sizeof(filter), inst->filter,
1008                          request, ldap_escape_func, NULL)) {
1009                 radlog(L_ERR, "rlm_ldap (%s): Unable to create filter",
1010                        inst->xlat_name);
1011                 *module_rcode = RLM_MODULE_INVALID;
1012                 return NULL;
1013         }
1014
1015         if (!radius_xlat(basedn, sizeof(basedn), inst->basedn,
1016                          request, ldap_escape_func, NULL)) {
1017                 radlog(L_ERR, "rlm_ldap (%s): Unable to create basedn",
1018                        inst->xlat_name);
1019                 *module_rcode = RLM_MODULE_INVALID;
1020                 return NULL;
1021         }
1022
1023         rcode = perform_search(inst, request, pconn, basedn, LDAP_SCOPE_SUBTREE,
1024                                filter, attrs, &result);
1025         if (rcode < 0) {
1026                 if (rcode == -2) {
1027                         *module_rcode = RLM_MODULE_NOTFOUND;
1028                 }
1029
1030                 return NULL;
1031         }
1032
1033         if ((entry = ldap_first_entry(handle, result)) == NULL) {
1034                 ldap_get_option(handle, LDAP_OPT_RESULT_CODE,
1035                                 &ldap_errno);
1036                 radlog(L_ERR, "rlm_ldap (%s): Failed retrieving entry: %s", 
1037                        inst->xlat_name,
1038                        ldap_err2string(ldap_errno));
1039                 ldap_msgfree(result);
1040                 return NULL;
1041         }
1042
1043         if ((user_dn = ldap_get_dn(handle, entry)) == NULL) {
1044                 ldap_get_option(handle, LDAP_OPT_RESULT_CODE,
1045                                 &ldap_errno);
1046                 radlog(L_ERR, "rlm_ldap (%s): ldap_get_dn() failed: %s",
1047                        inst->xlat_name,
1048                        ldap_err2string(ldap_errno));
1049                        
1050                 ldap_msgfree(result);
1051                 return NULL;
1052         }
1053
1054         vp = pairmake("LDAP-UserDn", user_dn, T_OP_EQ);
1055         if (!vp) {
1056                 ldap_memfree(user_dn);
1057                 ldap_msgfree(result);
1058                 return NULL;
1059         }
1060         
1061         pairadd(&request->config_items, vp);
1062         ldap_memfree(user_dn);
1063         ldap_msgfree(result);
1064
1065         return vp->vp_strvalue;
1066 }
1067
1068
1069 /*****************************************************************************
1070  *
1071  *      Perform LDAP-Group comparison checking
1072  *
1073  *****************************************************************************/
1074 static int ldap_groupcmp(void *instance, REQUEST *request,
1075                          UNUSED VALUE_PAIR *thing, VALUE_PAIR *check,
1076                          UNUSED VALUE_PAIR *check_pairs,
1077                          UNUSED VALUE_PAIR **reply_pairs)
1078 {
1079         ldap_instance   *inst = instance;
1080         int             i, rcode, found, module_rcode;
1081         LDAPMessage     *result = NULL;
1082         LDAPMessage     *entry = NULL;
1083         int             ldap_errno;
1084         int             check_is_dn = FALSE, value_is_dn = FALSE;
1085         static char     firstattr[] = "dn";
1086         const char      *attrs[] = {firstattr, NULL};
1087         char            **vals;
1088         const char      *group_attrs[] = {inst->groupmemb_attr, NULL};
1089         LDAP_CONN       *conn;
1090         char            *user_dn;
1091
1092         char            gr_filter[MAX_FILTER_STR_LEN];
1093         char            filter[MAX_FILTER_STR_LEN];
1094         char            basedn[MAX_FILTER_STR_LEN];
1095
1096         RDEBUG("Searching for user in group \"%s\"", check->vp_strvalue);
1097
1098         if (check->length == 0) {
1099                 RDEBUG("Cannot do comparison (group name is empty)");
1100                 return 1;
1101         }
1102
1103         conn = ldap_get_socket(inst);
1104         if (!conn) return 1;
1105
1106         /*
1107          *      This is used in the default membership filter.
1108          */
1109         user_dn = get_userdn(&conn, request, &module_rcode);
1110         if (!user_dn) {
1111                 ldap_release_socket(inst, conn);
1112                 return 1;
1113         }
1114
1115         if (!inst->groupmemb_filter) goto check_attr;
1116
1117         if (!radius_xlat(gr_filter, sizeof(gr_filter),
1118                          inst->groupmemb_filter, request, ldap_escape_func,
1119                          NULL)) {
1120                 radlog(L_ERR, "rlm_ldap (%s): Failed creating group filter",
1121                        inst->xlat_name);
1122                 return 1;
1123         }
1124
1125         /*
1126          *      If it's a DN, use that.
1127          */
1128         check_is_dn = strchr(check->vp_strvalue,',') == NULL ? FALSE : TRUE;
1129         
1130         if (check_is_dn) {
1131                 strlcpy(filter, gr_filter, sizeof(filter));
1132                 strlcpy(basedn, check->vp_strvalue, sizeof(basedn));    
1133         } else {
1134                 snprintf(filter, sizeof(filter), "(&(%s=%s)%s)",
1135                          inst->groupname_attr,
1136                          check->vp_strvalue, gr_filter);
1137
1138                 /*
1139                  *      get_userdn does this, too.  Oh well.
1140                  */
1141                 if (!radius_xlat(basedn, sizeof(basedn), inst->basedn,
1142                                  request, ldap_escape_func, NULL)) {
1143                         radlog(L_ERR, "rlm_ldap (%s): Failed creating basedn",
1144                                inst->xlat_name);
1145                         return 1;
1146                 }
1147         }
1148
1149         rcode = perform_search(inst, request, &conn, basedn, LDAP_SCOPE_SUBTREE,
1150                                filter, attrs, &result);
1151         if (rcode == 0) {
1152                 ldap_release_socket(inst, conn);
1153                 ldap_msgfree(result);
1154                         
1155                 RDEBUG("User found in group object");
1156                 
1157                 return 0;
1158         }
1159
1160         if (rcode == -1) {
1161                 ldap_release_socket(inst, conn);
1162                 return 1;
1163         }
1164
1165         /* else the search returned -2, for "not found" */
1166
1167         /*
1168          *      Else the search returned NOTFOUND.  See if we're
1169          *      configured to search for group membership using user
1170          *      object attribute.
1171          */
1172         if (!inst->groupmemb_attr) {
1173                 ldap_release_socket(inst, conn);
1174                 RDEBUG("Group object \"%s\" not found, or user is not a member",
1175                        check->vp_strvalue);
1176                 return 1;
1177         }
1178
1179 check_attr:
1180         RDEBUG2("Checking user object membership (%s) attributes",
1181                 inst->groupmemb_attr);
1182
1183         snprintf(filter ,sizeof(filter), "(objectclass=*)");
1184
1185         rcode = perform_search(inst, request, &conn, user_dn, LDAP_SCOPE_BASE,
1186                                filter, group_attrs, &result);
1187         if (rcode < 0) {
1188                 if (rcode == -2) {
1189                         RDEBUG("Can't check membership attributes, user object "
1190                                "not found");
1191                 }
1192                 ldap_release_socket(inst, conn);
1193                 return 1;
1194         }
1195
1196         entry = ldap_first_entry(conn->handle, result);
1197         if (!entry) {
1198                 ldap_get_option(conn->handle, LDAP_OPT_RESULT_CODE,
1199                                 &ldap_errno);
1200                 radlog(L_ERR, "rlm_ldap (%s): Failed retrieving entry: %s", 
1201                        inst->xlat_name,
1202                        ldap_err2string(ldap_errno));
1203                                
1204                 ldap_release_socket(inst, conn);
1205                 ldap_msgfree(result);
1206                 return 1;
1207         }
1208
1209         vals = ldap_get_values(conn->handle, entry, inst->groupmemb_attr);
1210         if (!vals) {
1211                 RDEBUG("No group membership attribute(s) found in user object");
1212                 ldap_release_socket(inst, conn);
1213                 ldap_msgfree(result);
1214                 return 1;
1215         }
1216
1217         /*
1218          *      Loop over the list of groups the user is a member of,
1219          *      looking for a match.
1220          */
1221         found = FALSE;
1222         for (i = 0; i < ldap_count_values(vals); i++) {
1223                 LDAPMessage *gr_result = NULL;
1224                 
1225                 value_is_dn = strchr(vals[i], ',') == NULL ? FALSE : TRUE;
1226                 
1227                 RDEBUG2("Processing group membership value \"%s\"", vals[i]);
1228
1229                 /*
1230                  *      Both literal group names, do case sensitive comparison
1231                  */
1232                 if (!check_is_dn && !value_is_dn) {
1233                         if (strcmp(vals[i], check->vp_strvalue) == 0){
1234                                 RDEBUG("User found (membership value matches "
1235                                        "check value)");
1236                                
1237                                 found = TRUE;
1238                                 break;
1239                         }
1240                         
1241                         continue;
1242                 }
1243
1244                 /*
1245                  *      Both DNs, do case insensitive comparison
1246                  */
1247                 if (check_is_dn && value_is_dn) {
1248                         if (strcasecmp(vals[i], check->vp_strvalue) == 0){
1249                                 RDEBUG("User found (membership DN matches "
1250                                        "check DN)");
1251                                
1252                                 found = TRUE;
1253                                 break;
1254                         }
1255                         
1256                         continue;
1257                 }
1258                 
1259                 /*
1260                  *      If the value is not a DN, or the check item is a DN
1261                  *      there's nothing more we can do.
1262                  */
1263                 if (!value_is_dn && check_is_dn) continue;
1264
1265                 /*
1266                  *      We have a value which is a DN, and a check item which
1267                  *      specifies the name of a group, search using the value
1268                  *      DN for the group, and see if it has a groupname_attr
1269                  *      which matches our check val.
1270                  */
1271                 RDEBUG2("Searching with membership DN and group name");
1272
1273                 snprintf(filter,sizeof(filter), "(%s=%s)",
1274                          inst->groupname_attr, check->vp_strvalue);
1275
1276                 rcode = perform_search(inst, request, &conn, vals[i],
1277                                        LDAP_SCOPE_BASE, filter, attrs,
1278                                        &gr_result);
1279                                        
1280                 ldap_msgfree(gr_result);
1281
1282                 /* Error occurred */
1283                 if (rcode == -1) {
1284                         ldap_value_free(vals);
1285                         ldap_msgfree(result);
1286                         ldap_release_socket(inst, conn);
1287                         return 1;
1288                 }
1289                 
1290                 /*
1291                  *      Either the group DN wasn't found, or it didn't have the
1292                  *      correct name. Continue looping over the attributes.
1293                  */
1294                 if (rcode == -2) {
1295                         ldap_msgfree(gr_result);
1296                         continue;
1297                 }
1298
1299                 found = TRUE;
1300
1301                 RDEBUG("User found (group name in membership DN matches check "
1302                        "value)");
1303
1304                 break;
1305         }
1306
1307         ldap_value_free(vals);
1308         ldap_msgfree(result);
1309         ldap_release_socket(inst, conn);
1310
1311         if (!found){
1312                 RDEBUG("User is not a member of specified group");
1313                 return 1;
1314         }
1315
1316         return 0;
1317 }
1318
1319 /*
1320  *      Verify that the ldap update section makes sense, and add attribute names
1321  *      to array of attributes for efficient querying later.
1322  */
1323 static int build_attrmap(CONF_SECTION *cs, VALUE_PAIR_MAP **head)
1324 {
1325         const char *cs_list, *p;
1326
1327         request_refs_t request_def = REQUEST_CURRENT;
1328         pair_lists_t list_def = PAIR_LIST_REQUEST;
1329
1330         CONF_ITEM *ci = cf_sectiontoitem(cs);
1331         CONF_PAIR *cp;
1332
1333         unsigned int total = 0;
1334         VALUE_PAIR_MAP **tail, *map;
1335         *head = NULL;
1336         tail = head;
1337         
1338         if (!cs) return 0;
1339         
1340         cs_list = p = cf_section_name2(cs);
1341         if (cs_list) {
1342                 request_def = radius_request_name(&p, REQUEST_UNKNOWN);
1343                 if (request_def == REQUEST_UNKNOWN) {
1344                         cf_log_err(ci, "rlm_ldap: Default request specified "
1345                                    "in mapping section is invalid");
1346                         return -1;
1347                 }
1348                 
1349                 list_def = fr_str2int(pair_lists, p, PAIR_LIST_UNKNOWN);
1350                 if (list_def == PAIR_LIST_UNKNOWN) {
1351                         cf_log_err(ci, "rlm_ldap: Default list specified "
1352                                    "in mapping section is invalid");
1353                         return -1;
1354                 }
1355         }
1356
1357         for (ci = cf_item_find_next(cs, NULL);
1358              ci != NULL;
1359              ci = cf_item_find_next(cs, ci)) {
1360                 if (total++ == MAX_ATTRMAP) {
1361                         cf_log_err(ci, "rlm_ldap: Attribute map size exceeded");
1362                         goto error;
1363                 }
1364                 
1365                 if (!cf_item_is_pair(ci)) {
1366                         cf_log_err(ci, "rlm_ldap: Entry is not in \"attribute ="
1367                                        " ldap-attribute\" format");
1368                         goto error;
1369                 }
1370         
1371                 cp = cf_itemtopair(ci);
1372                 map = radius_cp2map(cp, REQUEST_CURRENT, list_def);
1373                 if (!map) {
1374                         goto error;
1375                 }
1376                 
1377                 *tail = map;
1378                 tail = &(map->next);
1379         }
1380
1381         return 0;
1382         
1383         error:
1384                 radius_mapfree(head);
1385                 return -1;
1386 }
1387
1388 /*****************************************************************************
1389  *
1390  *      Detach from the LDAP server and cleanup internal state.
1391  *
1392  *****************************************************************************/
1393 static int ldap_detach(void *instance)
1394 {
1395         ldap_instance *inst = instance;
1396
1397         fr_connection_pool_delete(inst->pool);
1398         
1399         if (inst->user_map) {
1400                 radius_mapfree(&inst->user_map);
1401         }
1402
1403         free(inst);
1404
1405         return 0;
1406 }
1407
1408 /*************************************************************************
1409  *
1410  *      Function: rlm_ldap_instantiate
1411  *
1412  *      Purpose: Uses section of radiusd config file passed as parameter
1413  *               to create an instance of the module.
1414  *
1415  *************************************************************************/
1416 static int ldap_instantiate(CONF_SECTION * conf, void **instance)
1417 {
1418         ldap_instance *inst;
1419         CONF_SECTION *cs;
1420
1421         inst = rad_malloc(sizeof *inst);
1422         if (!inst) {
1423                 return -1;
1424         }
1425         memset(inst, 0, sizeof(*inst));
1426         inst->cs = conf;
1427
1428         inst->chase_referrals = 2; /* use OpenLDAP defaults */
1429         inst->rebind = 2;
1430
1431         if (cf_section_parse(conf, inst, module_config) < 0) {
1432                 free(inst);
1433                 return -1;
1434         }
1435         
1436         inst->xlat_name = cf_section_name2(conf);
1437         if (!inst->xlat_name) inst->xlat_name = cf_section_name1(conf);
1438
1439         if (inst->server == NULL) {
1440                 radlog(L_ERR, "rlm_ldap (%s): missing 'server' directive",
1441                        inst->xlat_name);
1442                 ldap_detach(inst);
1443                 return -1;
1444         }
1445
1446         /*
1447          *      Check for URLs.  If they're used and the library doesn't
1448          *      support them, then complain.
1449          */
1450         inst->is_url = 0;
1451         if (ldap_is_ldap_url(inst->server)) {
1452 #ifdef HAVE_LDAP_INITIALIZE
1453                 inst->is_url = 1;
1454                 inst->port = 0;
1455 #else
1456                 radlog(L_ERR, "rlm_ldap (%s): 'server' directive is in URL "
1457                        "form but ldap_initialize() is not available",
1458                        inst->xlat_name);
1459                 ldap_detach(inst);
1460                 return -1;
1461 #endif
1462         }
1463
1464         /* workaround for servers which support LDAPS but not START TLS */
1465         if (inst->port == LDAPS_PORT || inst->tls_mode) {
1466                 inst->tls_mode = LDAP_OPT_X_TLS_HARD;
1467         } else {
1468                 inst->tls_mode = 0;
1469         }
1470
1471 #if LDAP_SET_REBIND_PROC_ARGS != 3
1472         /*
1473          *      The 2-argument rebind doesn't take an instance
1474          *      variable.  Our rebind function needs the instance
1475          *      variable for the username, password, etc.
1476          */
1477         if (inst->rebind == 1) {
1478                 radlog(L_ERR, "rlm_ldap (%s): Cannot use 'rebind' directive "
1479                        "as this version of libldap does not support the API "
1480                        "that we need", inst->xlat-name);
1481                 ldap_detach(inst);
1482                 return -1;
1483         }
1484 #endif
1485
1486         /*
1487          *      Build the attribute map
1488          */
1489         cs = cf_section_sub_find(conf, "update");
1490         if (cs) {       
1491                 if (build_attrmap(cs, &(inst->user_map)) < 0) {
1492                         ldap_detach(inst);
1493                         return -1;
1494                 }
1495         }
1496
1497         /*
1498          *      Group comparison checks.
1499          */
1500         paircompare_register(PW_LDAP_GROUP, PW_USER_NAME, ldap_groupcmp, inst); 
1501         if (cf_section_name2(conf)) {
1502                 DICT_ATTR *da;
1503                 ATTR_FLAGS flags;
1504                 char buffer[256];
1505
1506                 snprintf(buffer, sizeof(buffer), "%s-Ldap-Group",
1507                          inst->xlat_name);
1508                 memset(&flags, 0, sizeof(flags));
1509
1510                 dict_addattr(buffer, -1, 0, PW_TYPE_STRING, flags);
1511                 da = dict_attrbyname(buffer);
1512                 if (!da) {
1513                         radlog(L_ERR, "rlm_ldap (%s): Failed creating "
1514                                "attribute %s", inst->xlat_name, buffer);
1515                         ldap_detach(inst);
1516                         return -1;
1517                 }
1518
1519                 paircompare_register(da->attr, PW_USER_NAME, ldap_groupcmp,
1520                                      inst);
1521         }
1522
1523         xlat_register(inst->xlat_name, ldap_xlat, inst);
1524
1525         /*
1526          *      Initialize the socket pool.
1527          */
1528         inst->pool = fr_connection_pool_init(inst->cs, inst,
1529                                              ldap_conn_create,
1530                                              NULL,
1531                                              ldap_conn_delete);
1532         if (!inst->pool) {
1533                 ldap_detach(inst);
1534                 return -1;
1535         }
1536         
1537         *instance = inst;
1538         return 0;
1539 }
1540
1541 static int check_access(ldap_instance *inst, REQUEST* request, LDAP_CONN *conn,
1542                         LDAPMessage *entry)
1543 {
1544         int rcode = -1;
1545         char **vals = NULL;
1546
1547         vals = ldap_get_values(conn->handle, entry, inst->access_attr);
1548         if (vals) {
1549                 if (inst->positive_access_attr) {
1550                         if (strncmp(vals[0], "FALSE", 5) == 0) {
1551                                 RDEBUG("Dialup access disabled");
1552
1553                         } else {
1554                                 rcode = 0;
1555                         }
1556
1557                 } else {
1558                         RDEBUG("\"%s\" attribute exists - access denied by"
1559                                " default", inst->access_attr);
1560                 }
1561
1562                 ldap_value_free(vals);
1563
1564         } else if (inst->positive_access_attr) {
1565                 RDEBUG("No %s attribute - access denied by default",
1566                        inst->access_attr);
1567
1568         } else {
1569                 rcode = 0;
1570         }
1571
1572         return rcode;
1573 }
1574
1575
1576 static VALUE_PAIR *ldap_getvalue(REQUEST *request, const VALUE_PAIR_TMPL *dst,
1577                                  void *ctx)
1578 {
1579         rlm_ldap_result_t *self = ctx;
1580         VALUE_PAIR *head, **tail, *vp;
1581         int i;
1582         
1583         request = request;
1584         
1585         head = NULL;
1586         tail = &head;
1587         
1588         /*
1589          *      Iterate over all the retrieved values,
1590          *      don't try and be clever about changing operators
1591          *      just use whatever was set in the attribute map. 
1592          */
1593         for (i = 0; i < self->count; i++) {
1594                 vp = pairalloc(dst->da);
1595                 rad_assert(vp);
1596
1597                 pairparsevalue(vp, self->values[i]);
1598                 
1599                 *tail = vp;
1600                 tail = &(vp->next);
1601         }
1602         
1603         return head;            
1604 }
1605
1606
1607 static void xlat_attrsfree(const xlat_attrs_t *expanded)
1608 {
1609         const VALUE_PAIR_MAP *map;
1610         unsigned int total = 0;
1611         
1612         char *name;
1613         
1614         for (map = expanded->maps; map != NULL; map = map->next)
1615         {
1616                 memcpy(&name, &(expanded->attrs[total++]), sizeof(name));
1617                 
1618                 if (!name) return;
1619                 
1620                 if (map->src->do_xlat) {
1621                         free(name);
1622                 }
1623         }
1624 }
1625
1626
1627 static int xlat_attrs(REQUEST *request, const VALUE_PAIR_MAP *maps,
1628                       xlat_attrs_t *expanded)
1629 {
1630         const VALUE_PAIR_MAP *map;
1631         unsigned int total = 0;
1632         
1633         size_t len;
1634         char *buffer;
1635
1636         for (map = maps; map != NULL; map = map->next)
1637         {
1638                 if (map->src->do_xlat) {
1639                         buffer = rad_malloc(MAX_ATTR_STR_LEN);
1640                         len = radius_xlat(buffer, MAX_ATTR_STR_LEN,
1641                                           map->src->name, request, NULL, NULL);
1642                                           
1643                         if (!len) {
1644                                 RDEBUG("Expansion of LDAP attribute "
1645                                        "\"%s\" failed", map->src->name);
1646                                        
1647                                 expanded->attrs[total] = NULL;
1648                                 
1649                                 xlat_attrsfree(expanded);
1650                                 
1651                                 return -1;
1652                         }
1653                         
1654                         expanded->attrs[total++] = buffer;
1655                 } else {
1656                         expanded->attrs[total++] = map->src->name;
1657                 }
1658         }
1659         
1660         expanded->attrs[total] = NULL;
1661         expanded->maps = maps;
1662         
1663         return 0;
1664 }
1665
1666
1667 /** Convert attribute map into valuepairs
1668  *
1669  * Use the attribute map built earlier to convert LDAP values into valuepairs
1670  * and insert them into whichever list they need to go into.
1671  *
1672  * This is *NOT* atomic, but there's no condition in which we should error
1673  * out...
1674  */
1675 static void do_attrmap(UNUSED ldap_instance *inst, REQUEST *request,
1676                        LDAP *handle, const xlat_attrs_t *expanded,
1677                        LDAPMessage *entry)
1678 {
1679         const VALUE_PAIR_MAP    *map;
1680         unsigned int            total = 0;
1681         
1682         rlm_ldap_result_t       result;
1683         const char              *name;
1684
1685         for (map = expanded->maps; map != NULL; map = map->next)
1686         {
1687                 name = expanded->attrs[total++];
1688                 
1689                 result.values = ldap_get_values(handle, entry, name);
1690                 if (!result.values) {
1691                         RDEBUG2("Attribute \"%s\" not found in LDAP object",
1692                                 name);
1693                                 
1694                         goto next;
1695                 }
1696                 
1697                 /*
1698                  *      Find out how many values there are for the
1699                  *      attribute and extract all of them.
1700                  */
1701                 result.count = ldap_count_values(result.values);
1702                 
1703                 /*
1704                  *      If something bad happened, just skip, this is probably
1705                  *      a case of the dst being incorrect for the current
1706                  *      request context
1707                  */
1708                 if (radius_map2request(request, map, name, ldap_getvalue,
1709                                        &result) < 0) {
1710                         goto next;
1711                 }
1712                 
1713                 next:
1714                 
1715                 ldap_value_free(result.values);
1716         }
1717 }
1718
1719
1720 static void do_check_reply(ldap_instance *inst, REQUEST *request)
1721 {
1722        /*
1723         *       More warning messages for people who can't be bothered
1724         *       to read the documentation.
1725         */
1726         if (inst->expect_password && (debug_flag > 1)) {
1727                 if (!pairfind(request->config_items,PW_CLEARTEXT_PASSWORD, 0) &&
1728                         !pairfind(request->config_items,
1729                                   PW_NT_PASSWORD, 0) &&
1730                         !pairfind(request->config_items,
1731                                   PW_USER_PASSWORD, 0) &&
1732                         !pairfind(request->config_items,
1733                                   PW_PASSWORD_WITH_HEADER, 0) &&
1734                         !pairfind(request->config_items,
1735                                   PW_CRYPT_PASSWORD, 0)) {
1736                                 RDEBUG("WARNING: No \"known good\" password "
1737                                        "was found in LDAP.  Are you sure that "
1738                                        "the user is configured correctly?");
1739                }
1740        }
1741 }
1742
1743
1744 static void apply_profile(ldap_instance *inst, REQUEST *request,
1745                           LDAP_CONN **pconn, const char *profile,
1746                           const xlat_attrs_t *expanded)
1747 {
1748         int rcode;
1749         LDAPMessage     *result, *entry;
1750         int             ldap_errno;
1751         LDAP            *handle = (*pconn)->handle;
1752         char            filter[MAX_FILTER_STR_LEN];
1753
1754         if (!profile || !*profile) return;
1755
1756         strlcpy(filter, inst->base_filter, sizeof(filter));
1757
1758         rcode = perform_search(inst, request, pconn, profile, LDAP_SCOPE_BASE,
1759                                filter, expanded->attrs, &result);
1760                 
1761         if (rcode < 0) {
1762                 if (rcode == -2) {
1763                         RDEBUG("Profile \"%s\" not found", profile);
1764                 }
1765                 goto free_result;
1766         }
1767
1768         entry = ldap_first_entry(handle, result);
1769         if (!entry) {
1770                 ldap_get_option(handle, LDAP_OPT_RESULT_CODE,
1771                                 &ldap_errno);
1772                 radlog(L_ERR, "rlm_ldap (%s): Failed retrieving entry: %s", 
1773                        inst->xlat_name,
1774                        ldap_err2string(ldap_errno));
1775                        
1776                 goto free_result;
1777         }
1778         
1779         do_attrmap(inst, request, handle, expanded, entry);
1780
1781 free_result:
1782         ldap_msgfree(result);
1783 }
1784
1785
1786 /******************************************************************************
1787  *
1788  *      Function: ldap_authorize
1789  *
1790  *      Purpose: Check if user is authorized for remote access
1791  *
1792  ******************************************************************************/
1793 static int ldap_authorize(void *instance, REQUEST * request)
1794 {
1795         int rcode;
1796         int module_rcode = RLM_MODULE_OK;
1797         ldap_instance   *inst = instance;
1798         char            *user_dn;
1799         char            **vals;
1800         VALUE_PAIR      *vp;
1801         LDAP_CONN       *conn;
1802         LDAPMessage     *result, *entry;
1803         int             ldap_errno;
1804         char            filter[MAX_FILTER_STR_LEN];
1805         char            basedn[MAX_FILTER_STR_LEN];
1806         xlat_attrs_t    expanded; /* faster that mallocing every time */
1807         
1808         if (!request->username) {
1809                 RDEBUG2("Attribute \"User-Name\" is required for "
1810                         "authorization.");
1811                 return RLM_MODULE_NOOP;
1812         }
1813
1814         /*
1815          *      Check for valid input, zero length names not permitted
1816          */
1817         if (request->username->length == 0) {
1818                 RDEBUG2("Zero length username not permitted");
1819                 return RLM_MODULE_INVALID;
1820         }
1821
1822         if (!radius_xlat(filter, sizeof(filter), inst->filter,
1823                          request, ldap_escape_func, NULL)) {
1824                 radlog(L_ERR, "rlm_ldap (%s): Failed creating filter",
1825                        inst->xlat_name);
1826                 return RLM_MODULE_INVALID;
1827         }
1828
1829         if (!radius_xlat(basedn, sizeof(basedn), inst->basedn,
1830                          request, ldap_escape_func, NULL)) {
1831                 radlog(L_ERR, "rlm_ldap (%s): Failed creating basedn",
1832                        inst->xlat_name);
1833                 return RLM_MODULE_INVALID;
1834         }
1835
1836         conn = ldap_get_socket(inst);
1837         if (!conn) return RLM_MODULE_FAIL;
1838         
1839         if (xlat_attrs(request, inst->user_map, &expanded) < 0) {
1840                 return RLM_MODULE_FAIL;
1841         }
1842         
1843         rcode = perform_search(inst, request, &conn, basedn,
1844                                LDAP_SCOPE_SUBTREE, filter, expanded.attrs,
1845                                &result);
1846         
1847         if (rcode < 0) {
1848                 if (rcode == -2) {
1849                         module_failure_msg(request,
1850                                            "rlm_ldap (%s): User object not "
1851                                            " found",
1852                                            inst->xlat_name);
1853                                            
1854                         RDEBUG("User object not found", inst->xlat_name);
1855                                
1856                         module_rcode = RLM_MODULE_NOTFOUND;
1857                         goto free_socket;
1858                 }
1859
1860                 goto free_socket;
1861         }
1862
1863         entry = ldap_first_entry(conn->handle, result);
1864         if (!entry) {
1865                 ldap_get_option(conn->handle, LDAP_OPT_RESULT_CODE,
1866                                 &ldap_errno);
1867                 radlog(L_ERR, "rlm_ldap (%s): Failed retrieving entry: %s", 
1868                        inst->xlat_name,
1869                        ldap_err2string(ldap_errno));
1870                        
1871                 goto free_result;
1872         }
1873
1874         user_dn = ldap_get_dn(conn->handle, entry);
1875         if (!user_dn) {
1876                 ldap_get_option(conn->handle, LDAP_OPT_RESULT_CODE,
1877                                 &ldap_errno);
1878                 radlog(L_ERR, "rlm_ldap (%s): ldap_get_dn() failed: %s",
1879                        inst->xlat_name,
1880                        ldap_err2string(ldap_errno));
1881                 goto free_result;
1882         }
1883         
1884         RDEBUG2("User found at DN \"%s\"", user_dn);
1885         /*
1886          *      Adding attribute containing the Users' DN.
1887          */
1888         pairadd(&request->config_items,
1889                 pairmake("Ldap-UserDn", user_dn, T_OP_EQ));
1890
1891 #ifdef WITH_EDIR
1892         /*
1893          *      We already have a Cleartext-Password.  Skip edir.
1894          */
1895         if (inst->edir && pairfind(request->config_items,
1896                                    PW_CLEARTEXT_PASSWORD, 0)) {
1897                 goto skip_edir;
1898         }
1899
1900         /*
1901          *      Retrieve Universal Password if we use eDirectory
1902          */
1903         if (inst->edir) {
1904                 int res = 0;
1905                 size_t bufsize;
1906                 char buffer[256];
1907
1908                 bufsize = sizeof(buffer);
1909
1910                 /* retrive universal password */
1911                 res = nmasldap_get_password(conn->handle, user_dn,
1912                                             buffer, &bufsize);
1913                 if (res != 0) {
1914                         RDEBUG2("Failed to retrieve eDirectory password. Check your configuration !");
1915                         module_rcode = RLM_MODULE_NOOP;
1916                         goto free_result;
1917                 }
1918
1919                 /* add Cleartext-Password attribute to the request */
1920                 vp = radius_paircreate(request, &request->config_items,
1921                                        PW_CLEARTEXT_PASSWORD, 0, PW_TYPE_STRING);
1922                 strlcpy(vp->vp_strvalue, buffer, sizeof(vp->vp_strvalue));
1923                 vp->length = strlen(vp->vp_strvalue);
1924                 
1925                 RDEBUG2("Added eDirectory password in check items as %s = %s",
1926                         vp->name, vp->vp_strvalue);
1927         }
1928
1929 skip_edir:
1930 #endif
1931
1932         ldap_memfree(user_dn);
1933
1934         /*
1935          *      Check for access.
1936          */
1937         if (inst->access_attr) {
1938                 if (check_access(inst, request, conn, entry) < 0) {
1939                         module_rcode = RLM_MODULE_USERLOCK;
1940                         goto free_result;
1941                 }
1942         }
1943
1944         /*
1945          *      Apply ONE user profile, or a default user profile.
1946          */
1947         vp = pairfind(request->config_items, PW_USER_PROFILE, 0);
1948         if (vp || inst->default_profile) {
1949                 char *profile = inst->default_profile;
1950
1951                 if (vp) profile = vp->vp_strvalue;
1952
1953                 apply_profile(inst, request, &conn, profile, &expanded);
1954         }
1955
1956         /*
1957          *      Apply a SET of user profiles.
1958          */
1959         if (inst->profile_attr) {
1960                 vals = ldap_get_values(conn->handle, entry, inst->profile_attr);
1961                 if (vals != NULL) {
1962                         int i;
1963         
1964                         for (i = 0; (vals[i] != NULL) && (*vals[i] != '\0');
1965                              i++) {
1966                                 apply_profile(inst, request, &conn, vals[i],
1967                                               &expanded);
1968                         }
1969         
1970                         ldap_value_free(vals);
1971                 }
1972         }
1973
1974         if (inst->user_map) {
1975                 do_attrmap(inst, request, conn->handle, &expanded, entry);
1976                 do_check_reply(inst, request);
1977         }
1978         
1979 free_result:
1980         xlat_attrsfree(&expanded);
1981         ldap_msgfree(result);
1982 free_socket:
1983         ldap_release_socket(inst, conn);
1984
1985         return module_rcode;
1986 }
1987
1988
1989 /*****************************************************************************
1990  *
1991  *      Function: ldap_authenticate
1992  *
1993  *      Purpose: Check the user's password against ldap database
1994  *
1995  *****************************************************************************/
1996 static int ldap_authenticate(void *instance, REQUEST * request)
1997 {
1998         int             module_rcode;
1999         const char      *user_dn;
2000         ldap_instance   *inst = instance;
2001         LDAP_CONN       *conn;
2002
2003         /*
2004          * Ensure that we're being passed a plain-text password, and not
2005          * anything else.
2006          */
2007
2008         if (!request->username) {
2009                 radlog(L_AUTH, "rlm_ldap (%s): Attribute \"User-Name\" is "
2010                        "required for authentication", inst->xlat_name);
2011                 return RLM_MODULE_INVALID;
2012         }
2013
2014         if (!request->password) {
2015                 radlog(L_AUTH, "rlm_ldap (%s): Attribute \"User-Password\" "
2016                        "is required for authentication.", inst->xlat_name);
2017                 RDEBUG2("  You have set \"Auth-Type := LDAP\" somewhere.");
2018                 RDEBUG2("  *********************************************");
2019                 RDEBUG2("  * THAT CONFIGURATION IS WRONG.  DELETE IT.   ");
2020                 RDEBUG2("  * YOU ARE PREVENTING THE SERVER FROM WORKING.");
2021                 RDEBUG2("  *********************************************");
2022                 return RLM_MODULE_INVALID;
2023         }
2024
2025         if (request->password->attribute != PW_USER_PASSWORD) {
2026                 radlog(L_AUTH, "rlm_ldap (%s): Attribute \"User-Password\" "
2027                        "is required for authentication. Cannot use \"%s\".",
2028                        inst->xlat_name, request->password->name);
2029                 return RLM_MODULE_INVALID;
2030         }
2031
2032         if (request->password->length == 0) {
2033                 module_failure_msg(request,
2034                                    "rlm_ldap (%s): Empty password supplied",
2035                                    inst->xlat_name);
2036                 return RLM_MODULE_INVALID;
2037         }
2038
2039         conn = ldap_get_socket(inst);
2040         if (!conn) return RLM_MODULE_FAIL;
2041
2042         RDEBUG("Login attempt by \"%s\" with password \"%s\"",
2043                request->username->vp_strvalue, request->password->vp_strvalue);
2044
2045         /*
2046          *      Get the DN by doing a search.
2047          */
2048         user_dn = get_userdn(&conn, request, &module_rcode);
2049         if (!user_dn) {
2050                 ldap_release_socket(inst, conn);
2051                 return module_rcode;
2052         }
2053
2054         /*
2055          *      Bind as the user
2056          */
2057         conn->rebound = TRUE;
2058         module_rcode = ldap_bind_wrapper(&conn, user_dn,
2059                                          request->password->vp_strvalue,
2060                                          NULL, TRUE);
2061         if (module_rcode == RLM_MODULE_OK) {
2062                 RDEBUG("Bind as user \"%s\" was successful", user_dn);
2063         }
2064
2065         ldap_release_socket(inst, conn);
2066         return module_rcode;
2067 }
2068
2069
2070 #ifdef WITH_EDIR
2071 /*****************************************************************************
2072  *
2073  *      Function: ldap_postauth
2074  *
2075  *      Purpose: Check the user's password against ldap database
2076  *
2077  *****************************************************************************/
2078 static int ldap_postauth(void *instance, REQUEST * request)
2079 {
2080         int             module_rcode;
2081         const char      *user_dn;
2082         ldap_instance   *inst = instance;
2083         LDAP_CONN       *conn;
2084         VALUE_PAIR      *vp;
2085
2086         /*
2087          *      Ensure that we have a username and a
2088          *      Cleartext-Password in the request
2089          */
2090         if (!request->username) {
2091                 radlog(L_AUTH, "rlm_ldap (%s): Attribute \"User-Name\" is "
2092                        "required for authentication", inst->xlat_name);
2093                 return RLM_MODULE_INVALID;
2094         }
2095
2096         vp = pairfind(request->config_items, PW_CLEARTEXT_PASSWORD, 0);
2097         if (!vp) {
2098                 radlog(L_AUTH, "rlm_ldap (%s): Attribute \"Cleartext-Password\" "
2099                        "is required for authentication.", inst->xlat_name);
2100                 return RLM_MODULE_INVALID;
2101         }
2102
2103         if (!*vp->vp_strvalue) {
2104                 radlog(L_AUTH, "rlm_ldap (%s): Attribute \"Cleartext-Password\" "
2105                        "is empty.", inst->xlat_name);
2106                 return RLM_MODULE_INVALID;
2107         }
2108
2109         conn = ldap_get_socket(inst);
2110         if (!conn) return RLM_MODULE_FAIL;
2111
2112         RDEBUG("Login attempt by \"%s\" with password \"%s\"",
2113                request->username->vp_strvalue, vp->vp_strvalue);
2114
2115         /*
2116          *      Get the DN by doing a search.
2117          */
2118         user_dn = get_userdn(&conn, request, &module_rcode);
2119         if (!user_dn) {
2120                 ldap_release_socket(inst, conn);
2121                 return module_rcode;
2122         }
2123
2124         /*
2125          *      Bind as the user
2126          */
2127         conn->rebound = TRUE;
2128         module_rcode = ldap_bind_wrapper(&conn, user_dn,
2129                                          vp->vp_strvalue,
2130                                          NULL, TRUE);
2131         if (module_rcode == RLM_MODULE_OK) {
2132                 RDEBUG("Bind as user \"%s\" was successful", user_dn);
2133         }
2134
2135         ldap_release_socket(inst, conn);
2136         return module_rcode;
2137 }
2138 #endif
2139
2140 /* globally exported name */
2141 module_t rlm_ldap = {
2142         RLM_MODULE_INIT,
2143         "ldap",
2144         RLM_TYPE_THREAD_SAFE,   /* type: reserved        */
2145         ldap_instantiate,       /* instantiation         */
2146         ldap_detach,            /* detach                */
2147         {
2148                 ldap_authenticate,      /* authentication        */
2149                 ldap_authorize,         /* authorization         */
2150                 NULL,                   /* preaccounting         */
2151                 NULL,                   /* accounting            */
2152                 NULL,                   /* checksimul            */
2153                 NULL,                   /* pre-proxy             */
2154                 NULL,                   /* post-proxy            */
2155 #ifdef WITH_EDIR
2156                 ldap_postauth           /* post-auth */
2157 #else
2158                 NULL                    /* post-auth */
2159 #endif
2160         },
2161 };