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