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