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