Merge pull request #59 from sionescu/master
[freeradius.git] / src / modules / rlm_ldap / rlm_ldap.c
1 /*
2  * rlm_ldap.c   LDAP authorization and authentication module.
3  *
4  *   This program is free software; you can redistribute it and/or modify
5  *   it under the terms of the GNU General Public License as published by
6  *   the Free Software Foundation; either version 2 of the License, or
7  *   (at your option) any later version.
8  *
9  *   This program is distributed in the hope that it will be useful,
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *   GNU General Public License for more details.
13  *
14  *   You should have received a copy of the GNU General Public License
15  *   along with this program; if not, write to the Free Software
16  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  *
18  *   Copyright 2004,2006 The FreeRADIUS Server Project.
19  */
20
21 #include <freeradius-devel/ident.h>
22 RCSID("$Id$")
23
24 #include <freeradius-devel/radiusd.h>
25 #include <freeradius-devel/modules.h>
26 #include        <freeradius-devel/rad_assert.h>
27
28 #include        <pwd.h>
29 #include        <ctype.h>
30
31 #include        <lber.h>
32 #include        <ldap.h>
33
34 #ifndef HAVE_PTHREAD_H
35 /*
36  *      This is a lot simpler than putting ifdef's around
37  *      every use of the pthread functions.
38  */
39 #define pthread_mutex_lock(a)
40 #define pthread_mutex_trylock(a) (0)
41 #define pthread_mutex_unlock(a)
42 #define pthread_mutex_init(a,b)
43 #define pthread_mutex_destroy(a)
44 #else
45 #include        <pthread.h>
46 #endif
47
48
49 #define MAX_FILTER_STR_LEN      1024
50 #define TIMELIMIT 5
51
52 /*
53  * These are used in case ldap_search returns LDAP_SERVER_DOWN
54  * In that case we do conn->failed_conns++ and then check it:
55  * If conn->failed_conns <= MAX_FAILED_CONNS_START then we try
56  * to reconnect
57  * conn->failed_conns is also checked on entrance in perform_search:
58  * If conn->failed_conns > MAX_FAILED_CONNS_START then we don't
59  * try to do anything and we just do conn->failed_conns++ and
60  * return RLM_MODULE_FAIL
61  * if conn->failed_conns >= MAX_FAILED_CONNS_END then we give it
62  * another chance and we set it to MAX_FAILED_CONNS_RESTART and
63  * try to reconnect.
64  *
65  *
66  * We are assuming that the majority of the LDAP_SERVER_DOWN cases
67  * will either be an ldap connection timeout or a temporary ldap
68  * server problem.
69  * As a result we make a few attempts to reconnect hoping that the problem
70  * will soon go away. If it does not go away then we just return
71  * RLM_MODULE_FAIL on entrance in perform_search until conn->failed_conns
72  * gets to MAX_FAILED_CONNS_END. After that we give it one more chance by
73  * going back to MAX_FAILED_CONNS_RESTART
74  *
75  */
76
77 #define MAX_FAILED_CONNS_END            20
78 #define MAX_FAILED_CONNS_RESTART        4
79 #define MAX_FAILED_CONNS_START          5
80
81 #ifdef NOVELL_UNIVERSAL_PASSWORD
82
83 /* Universal Password Length */
84 #define UNIVERSAL_PASS_LEN 256
85
86 int nmasldap_get_password(
87         LDAP     *ld,
88         char     *objectDN,
89         size_t   *pwdSize,      /* in bytes */
90         char     *pwd );
91
92 #endif
93
94 #ifdef NOVELL
95
96 #define REQUEST_ACCEPTED   0
97 #define REQUEST_CHALLENGED 1
98 #define REQUEST_REJECTED   2
99 #define MAX_CHALLENGE_LEN  128
100
101 int radLdapXtnNMASAuth( LDAP *, char *, char *, char *, char *, size_t *, char *, int * );
102
103 #endif
104
105 /* linked list of mappings between RADIUS attributes and LDAP attributes */
106 struct TLDAP_RADIUS {
107         char*                 attr;
108         char*                 radius_attr;
109         FR_TOKEN              operator;
110         struct TLDAP_RADIUS*  next;
111 };
112 typedef struct TLDAP_RADIUS TLDAP_RADIUS;
113
114 typedef struct ldap_conn {
115         LDAP            *ld;
116         char            bound;
117         char            locked;
118         int             failed_conns;
119 #ifdef HAVE_PTHREAD_H
120         pthread_mutex_t mutex;
121 #endif
122 } LDAP_CONN;
123
124 typedef struct {
125         CONF_SECTION   *cs;
126         char           *server;
127         int             port;
128         int             timelimit;
129         int             net_timeout;
130         int             timeout;
131         int             debug;
132         int             tls_mode;
133         int             start_tls;
134         int             num_conns;
135         int             do_comp;
136         int             do_xlat;
137         int             default_allow;
138         int             failed_conns;
139         int             is_url;
140         int             chase_referrals;
141         int             rebind;
142         char           *login;
143         char           *password;
144         char           *filter;
145         char           *base_filter;
146         char           *basedn;
147         char           *default_profile;
148         char           *profile_attr;
149         char           *access_attr;
150         char           *passwd_attr;
151         char           *dictionary_mapping;
152         char           *groupname_attr;
153         char           *groupmemb_filt;
154         char           *groupmemb_attr;
155         char            **atts;
156         TLDAP_RADIUS   *check_item_map;
157         TLDAP_RADIUS   *reply_item_map;
158         LDAP_CONN       *conns;
159 #ifdef NOVELL
160         LDAP_CONN *apc_conns;
161 #endif
162         int             ldap_debug; /* Debug flag for LDAP SDK */
163         char            *xlat_name; /* name used to xlat */
164         char            *auth_type;
165         char            *tls_cacertfile;
166         char            *tls_cacertdir;
167         char            *tls_certfile;
168         char            *tls_keyfile;
169         char            *tls_randfile;
170         char            *tls_require_cert;
171 #ifdef NOVELL
172         int              edir_account_policy_check;
173 #endif
174         int              set_auth_type;
175
176         /*
177          *      For keep-alives.
178          */
179 #ifdef LDAP_OPT_X_KEEPALIVE_IDLE
180         int             keepalive_idle;
181 #endif
182 #ifdef LDAP_OPT_X_KEEPALIVE_PROBES
183         int             keepalive_probes;
184 #endif
185 #ifdef LDAP_OPT_ERROR_NUMBER
186         int             keepalive_interval;
187 #endif
188
189 }  ldap_instance;
190
191 /* The default setting for TLS Certificate Verification */
192 #define TLS_DEFAULT_VERIFY "allow"
193
194 #if defined(LDAP_OPT_X_KEEPALIVE_IDLE) || defined(LDAP_OPT_X_KEEPALIVE_PROBES) || defined (LDAP_OPT_ERROR_NUMBER)
195 static CONF_PARSER keepalive_config[] = {
196 #ifdef LDAP_OPT_X_KEEPALIVE_IDLE
197         {"idle", PW_TYPE_INTEGER, offsetof(ldap_instance,keepalive_idle), NULL, "60"},
198 #endif
199 #ifdef LDAP_OPT_X_KEEPALIVE_PROBES
200         {"probes", PW_TYPE_INTEGER, offsetof(ldap_instance,keepalive_probes), NULL, "3"},
201 #endif
202 #ifdef LDAP_OPT_ERROR_NUMBER
203         {"interval", PW_TYPE_INTEGER, offsetof(ldap_instance,keepalive_interval), NULL, "30"},
204 #endif
205
206         { NULL, -1, 0, NULL, NULL }
207 };
208 #endif                          /* KEEPALIVE */
209
210 static CONF_PARSER tls_config[] = {
211         {"start_tls", PW_TYPE_BOOLEAN,
212          offsetof(ldap_instance,start_tls), NULL, "no"},
213         {"cacertfile", PW_TYPE_FILENAME,
214          offsetof(ldap_instance,tls_cacertfile), NULL, NULL},
215         {"cacertdir", PW_TYPE_FILENAME,
216          offsetof(ldap_instance,tls_cacertdir), NULL, NULL},
217         {"certfile", PW_TYPE_FILENAME,
218          offsetof(ldap_instance,tls_certfile), NULL, NULL},
219         {"keyfile", PW_TYPE_FILENAME,
220          offsetof(ldap_instance,tls_keyfile), NULL, NULL},
221         {"randfile", PW_TYPE_STRING_PTR, /* OK if it changes on HUP */
222          offsetof(ldap_instance,tls_randfile), NULL, NULL},
223         {"require_cert", PW_TYPE_STRING_PTR,
224          offsetof(ldap_instance,tls_require_cert), NULL, TLS_DEFAULT_VERIFY},
225         { NULL, -1, 0, NULL, NULL }
226 };
227
228 static const CONF_PARSER module_config[] = {
229         {"server", PW_TYPE_STRING_PTR,
230          offsetof(ldap_instance,server), NULL, "localhost"},
231         {"port", PW_TYPE_INTEGER,
232          offsetof(ldap_instance,port), NULL, "389"},
233         {"password", PW_TYPE_STRING_PTR,
234          offsetof(ldap_instance,password), NULL, ""},
235         {"identity", PW_TYPE_STRING_PTR,
236          offsetof(ldap_instance,login), NULL, ""},
237
238         /*
239          *      Timeouts & stuff.
240          */
241         /* wait forever on network activity */
242         {"net_timeout", PW_TYPE_INTEGER,
243          offsetof(ldap_instance,net_timeout), NULL, "10"},
244         /* wait forever for search results */
245         {"timeout", PW_TYPE_INTEGER,
246          offsetof(ldap_instance,timeout), NULL, "20"},
247         /* allow server unlimited time for search (server-side limit) */
248         {"timelimit", PW_TYPE_INTEGER,
249          offsetof(ldap_instance,timelimit), NULL, "20"},
250
251         /*
252          *      TLS configuration  The first few are here for backwards
253          *      compatibility.  The last is the new subsection.
254          */
255         {"tls_mode", PW_TYPE_BOOLEAN | PW_TYPE_DEPRECATED,
256          offsetof(ldap_instance,tls_mode), NULL, "no"},
257
258         {"start_tls", PW_TYPE_BOOLEAN | PW_TYPE_DEPRECATED,
259          offsetof(ldap_instance,start_tls), NULL, "no"},
260         {"tls_cacertfile", PW_TYPE_FILENAME | PW_TYPE_DEPRECATED,
261          offsetof(ldap_instance,tls_cacertfile), NULL, NULL},
262         {"tls_cacertdir", PW_TYPE_FILENAME | PW_TYPE_DEPRECATED,
263          offsetof(ldap_instance,tls_cacertdir), NULL, NULL},
264         {"tls_certfile", PW_TYPE_FILENAME | PW_TYPE_DEPRECATED,
265          offsetof(ldap_instance,tls_certfile), NULL, NULL},
266         {"tls_keyfile", PW_TYPE_FILENAME | PW_TYPE_DEPRECATED,
267          offsetof(ldap_instance,tls_keyfile), NULL, NULL},
268         {"tls_randfile", PW_TYPE_STRING_PTR | PW_TYPE_DEPRECATED, /* OK if it changes on HUP */
269          offsetof(ldap_instance,tls_randfile), NULL, NULL},
270         {"tls_require_cert", PW_TYPE_STRING_PTR | PW_TYPE_DEPRECATED,
271          offsetof(ldap_instance,tls_require_cert), NULL, TLS_DEFAULT_VERIFY},
272         { "tls", PW_TYPE_SUBSECTION, 0, NULL, (const void *) tls_config },
273
274         /*
275          *      DN's and filters.
276          */
277         {"basedn", PW_TYPE_STRING_PTR,
278          offsetof(ldap_instance,basedn), NULL, "o=notexist"},
279         {"filter", PW_TYPE_STRING_PTR,
280          offsetof(ldap_instance,filter), NULL, "(uid=%u)"},
281         {"base_filter", PW_TYPE_STRING_PTR,
282          offsetof(ldap_instance,base_filter), NULL, "(objectclass=radiusprofile)"},
283         {"default_profile", PW_TYPE_STRING_PTR,
284          offsetof(ldap_instance,default_profile), NULL, NULL},
285         {"profile_attribute", PW_TYPE_STRING_PTR,
286          offsetof(ldap_instance,profile_attr), NULL, NULL},
287
288         /*
289          *      Getting passwords from the database
290          */
291         {"password_attribute", PW_TYPE_STRING_PTR,
292          offsetof(ldap_instance,passwd_attr), NULL, NULL},
293
294         /*
295          *      Access limitations
296          */
297         /* LDAP attribute name that controls remote access */
298         {"access_attr", PW_TYPE_STRING_PTR,
299          offsetof(ldap_instance,access_attr), NULL, NULL},
300         {"access_attr_used_for_allow", PW_TYPE_BOOLEAN,
301          offsetof(ldap_instance,default_allow), NULL, "yes"},
302         {"chase_referrals", PW_TYPE_BOOLEAN,
303          offsetof(ldap_instance,chase_referrals), NULL, NULL},
304         {"rebind", PW_TYPE_BOOLEAN,
305          offsetof(ldap_instance,rebind), NULL, NULL},
306
307         /*
308          *      Group checks.  These could probably be done
309          *      via dynamic xlat's.
310          */
311         {"groupname_attribute", PW_TYPE_STRING_PTR,
312          offsetof(ldap_instance,groupname_attr), NULL, "cn"},
313         {"groupmembership_filter", PW_TYPE_STRING_PTR,
314          offsetof(ldap_instance,groupmemb_filt), NULL, "(|(&(objectClass=GroupOfNames)(member=%{Ldap-UserDn}))(&(objectClass=GroupOfUniqueNames)(uniquemember=%{Ldap-UserDn})))"},
315         {"groupmembership_attribute", PW_TYPE_STRING_PTR,
316          offsetof(ldap_instance,groupmemb_attr), NULL, NULL},
317
318         /* file with mapping between LDAP and RADIUS attributes */
319         {"dictionary_mapping", PW_TYPE_FILENAME,
320          offsetof(ldap_instance,dictionary_mapping), NULL, "${confdir}/ldap.attrmap"},
321
322         /*
323          *      Debugging flags to the server
324          */
325         {"ldap_debug", PW_TYPE_INTEGER,
326          offsetof(ldap_instance,ldap_debug), NULL, "0x0000"},
327         {"ldap_connections_number", PW_TYPE_INTEGER,
328          offsetof(ldap_instance,num_conns), NULL, "5"},
329         {"compare_check_items", PW_TYPE_BOOLEAN,
330          offsetof(ldap_instance,do_comp), NULL, "no"},
331         {"do_xlat", PW_TYPE_BOOLEAN,
332          offsetof(ldap_instance,do_xlat), NULL, "yes"},
333
334 #ifdef NOVELL
335         /*
336          *      Novell magic.
337          */
338         {"edir_account_policy_check", PW_TYPE_BOOLEAN,
339          offsetof(ldap_instance,edir_account_policy_check), NULL, "yes"},
340 #endif
341
342         {"set_auth_type", PW_TYPE_BOOLEAN, offsetof(ldap_instance,set_auth_type), NULL, "yes"},
343
344 #if defined(LDAP_OPT_X_KEEPALIVE_IDLE) || defined(LDAP_OPT_X_KEEPALIVE_PROBES) || defined (LDAP_OPT_ERROR_NUMBER)
345         { "keepalive", PW_TYPE_SUBSECTION, 0, NULL, (const void *) keepalive_config },
346 #endif
347
348         {NULL, -1, 0, NULL, NULL}
349 };
350
351 #define ld_valid                ld_options.ldo_valid
352 #define LDAP_VALID_SESSION      0x2
353 #define LDAP_VALID(ld)  ( (ld)->ld_valid == LDAP_VALID_SESSION )
354
355 #ifdef FIELDCPY
356 static void     fieldcpy(char *, char **);
357 #endif
358 static VALUE_PAIR *ldap_pairget(LDAP *, LDAPMessage *, TLDAP_RADIUS *,VALUE_PAIR **,int, ldap_instance *);
359 static int ldap_groupcmp(void *, REQUEST *, VALUE_PAIR *, VALUE_PAIR *, VALUE_PAIR *, VALUE_PAIR **);
360 static size_t ldap_xlat(void *, REQUEST *, const char *, char *, size_t, RADIUS_ESCAPE_STRING);
361 static LDAP    *ldap_connect(void *instance, const char *, const char *, int, int *, char **);
362 static int     read_mappings(ldap_instance* inst);
363
364 static inline int ldap_get_conn(LDAP_CONN *conns,LDAP_CONN **ret,
365                                 ldap_instance *inst)
366 {
367         register int i = 0;
368
369         for(i=0;i<inst->num_conns;i++){
370                 DEBUG("  [%s] ldap_get_conn: Checking Id: %d",
371                       inst->xlat_name, i);
372                 if ((pthread_mutex_trylock(&conns[i].mutex) == 0)) {
373                         if (conns[i].locked == 1) {
374                                 /* connection is already being used */
375                                 pthread_mutex_unlock(&(conns[i].mutex));
376                                 continue;
377                         }
378                         /* found an unused connection */
379                         *ret = &conns[i];
380                         conns[i].locked = 1;
381                         DEBUG("  [%s] ldap_get_conn: Got Id: %d",
382                               inst->xlat_name, i);
383                         return i;
384                 }
385         }
386
387         return -1;
388 }
389
390 static inline void ldap_release_conn(int i, ldap_instance *inst)
391                                      
392 {
393         LDAP_CONN *conns = inst->conns;
394
395         DEBUG("  [%s] ldap_release_conn: Release Id: %d", inst->xlat_name, i);
396         conns[i].locked = 0;
397         pthread_mutex_unlock(&(conns[i].mutex));
398 }
399
400 #ifdef NOVELL
401 static inline void ldap_release_apc_conn(int i, ldap_instance *inst)
402                                      
403 {
404         LDAP_CONN *conns = inst->apc_conns;
405
406         DEBUG("  [%s] ldap_release_conn: Release Id: %d", inst->xlat_name, i);
407         conns[i].locked = 0;
408         pthread_mutex_unlock(&(conns[i].mutex));
409 }
410 #endif
411
412 /*************************************************************************
413  *
414  *      Function: rlm_ldap_instantiate
415  *
416  *      Purpose: Uses section of radiusd config file passed as parameter
417  *               to create an instance of the module.
418  *
419  *************************************************************************/
420 static int
421 ldap_instantiate(CONF_SECTION * conf, void **instance)
422 {
423         ldap_instance  *inst;
424         int i = 0;
425         int atts_num = 0;
426         int reply_map_num = 0;
427         int check_map_num = 0;
428         int att_map[3] = {0,0,0};
429         TLDAP_RADIUS *pair;
430         ATTR_FLAGS flags;
431         const char *xlat_name;
432
433         inst = rad_malloc(sizeof *inst);
434         if (!inst) {
435                 return -1;
436         }
437         memset(inst, 0, sizeof(*inst));
438         inst->chase_referrals = 2; /* use OpenLDAP defaults */
439         inst->rebind = 2;
440         inst->cs = conf;
441
442         if (cf_section_parse(conf, inst, module_config) < 0) {
443                 free(inst);
444                 return -1;
445         }
446
447         if (inst->server == NULL) {
448                 radlog(L_ERR, "rlm_ldap: missing 'server' directive.");
449                 free(inst);     /* FIXME: detach */
450                 return -1;
451         }
452         inst->is_url = 0;
453         if (ldap_is_ldap_url(inst->server)){
454 #ifdef HAVE_LDAP_INITIALIZE
455                 inst->is_url = 1;
456                 inst->port = 0;
457 #else
458                 radlog(L_ERR, "rlm_ldap: 'server' directive is in URL form but ldap_initialize() is not available.");
459                 free(inst);     /* FIXME: detach */
460                 return -1;
461 #endif
462         }
463
464         /* workaround for servers which support LDAPS but not START TLS */
465         if(inst->port == LDAPS_PORT || inst->tls_mode)
466                 inst->tls_mode = LDAP_OPT_X_TLS_HARD;
467         else
468                 inst->tls_mode = 0;
469         inst->reply_item_map = NULL;
470         inst->check_item_map = NULL;
471         inst->conns = NULL;
472         inst->failed_conns = 0;
473
474 #if LDAP_SET_REBIND_PROC_ARGS != 3
475         /*
476          *      The 2-argument rebind doesn't take an instance
477          *      variable.  Our rebind function needs the instance
478          *      variable for the username, password, etc.
479          */
480         if (inst->rebind == 1) {
481                 radlog(L_ERR, "rlm_ldap: Cannot use 'rebind' directive as this version of libldap does not support the API that we need.");
482                 free(inst);
483                 return -1;
484         }
485 #endif
486
487         DEBUG("rlm_ldap: Registering ldap_groupcmp for Ldap-Group");
488         paircompare_register(PW_LDAP_GROUP, PW_USER_NAME, ldap_groupcmp, inst);
489         memset(&flags, 0, sizeof(flags));
490
491         xlat_name = cf_section_name2(conf);
492         if (xlat_name != NULL){
493                 char *group_name;
494                 DICT_ATTR *dattr;
495
496                 /*
497                  * Allocate room for <instance>-Ldap-Group
498                  */
499                 group_name = rad_malloc((strlen(xlat_name) + 1 + 11) * sizeof(char));
500                 sprintf(group_name,"%s-Ldap-Group",xlat_name);
501                 DEBUG("rlm_ldap: Creating new attribute %s",group_name);
502                 dict_addattr(group_name, -1, 0, PW_TYPE_STRING, flags);
503                 dattr = dict_attrbyname(group_name);
504                 if (dattr == NULL){
505                         radlog(L_ERR, "rlm_ldap: Failed to create attribute %s",group_name);
506                         free(group_name);
507                         free(inst);     /* FIXME: detach */
508                         return -1;
509                 }
510                 DEBUG("rlm_ldap: Registering ldap_groupcmp for %s",group_name);
511                 paircompare_register(dattr->attr, PW_USER_NAME, ldap_groupcmp, inst);
512                 free(group_name);
513         }
514         else {
515                 xlat_name = cf_section_name1(conf);
516                 rad_assert(xlat_name != NULL); /* or all hell breaks loose */
517         }
518         inst->xlat_name = strdup(xlat_name);
519         DEBUG("rlm_ldap: Registering ldap_xlat with xlat_name %s",xlat_name);
520         xlat_register(xlat_name,ldap_xlat,inst);
521
522         /*
523          *      Over-ride set_auth_type if there's no Auth-Type of our name.
524          *      This automagically catches the case where LDAP is listed
525          *      in "authorize", but not "authenticate".
526          */
527         if (inst->set_auth_type) {
528           DICT_VALUE *dv = dict_valbyname(PW_AUTH_TYPE, 0, xlat_name);
529
530                 /*
531                  *      No section of *my* name, but maybe there's an
532                  *      LDAP section...
533                  */
534                 if (!dv) dv = dict_valbyname(PW_AUTH_TYPE, 0, "LDAP");
535                 if (!dv) {
536                         DEBUG2("rlm_ldap: Over-riding set_auth_type, as there is no module %s listed in the \"authenticate\" section.", xlat_name);
537                         inst->set_auth_type = 0;
538                 } else {
539                         inst->auth_type = dv->name; /* doesn't change on HUP */
540                 }
541         } /* else no need to look up the value */
542
543 #ifdef NOVELL
544         /*
545          *      (LDAP_Instance, V1) attribute-value pair in the config
546          *      items list means that the 'authorize' method of the
547          *      instance 'V1' of the LDAP module has processed this
548          *      request.
549          */
550         dict_addattr("LDAP-Instance", -1, 0, PW_TYPE_STRING, flags);
551
552         /*
553          *      ('eDir-APC', '1') in config items list
554          *      Do not perform eDirectory account policy check (APC)
555          *
556          *      ('eDir-APC', '2') in config items list
557          *      Perform eDirectory APC
558          *
559          *      ('eDir-APC', '3') in config items list
560          *      eDirectory APC has been completed
561          */
562         dict_addattr("eDir-APC", -1, 0, PW_TYPE_STRING, flags);
563         /*
564          *      eDir-Auth-Option allows for a different NMAS Authentication method to be used instead of password
565          */
566         dict_addattr("eDir-Auth-Option", -1, 0, PW_TYPE_STRING, flags);
567 #endif
568
569         if (inst->num_conns <= 0){
570                 radlog(L_ERR, "rlm_ldap: Invalid ldap connections number passed.");
571                 free(inst);     /* FIXME: detach */
572                 return -1;
573         }
574         inst->conns = malloc(sizeof(*(inst->conns))*inst->num_conns);
575         if (inst->conns == NULL){
576                 radlog(L_ERR, "rlm_ldap: Could not allocate memory. Aborting.");
577                 free(inst);     /* FIXME: detach */
578                 return -1;
579         }
580         for(i = 0; i < inst->num_conns; i++){
581                 inst->conns[i].bound = 0;
582                 inst->conns[i].locked = 0;
583                 inst->conns[i].failed_conns = 0;
584                 inst->conns[i].ld = NULL;
585                 pthread_mutex_init(&inst->conns[i].mutex, NULL);
586         }
587
588 #ifdef NOVELL
589         /*
590          *      'inst->apc_conns' is a separate connection pool to be
591          *      used for performing eDirectory account policy check in
592          *      the 'postauth' method. This avoids changing the
593          *      (RADIUS server) credentials associated with the
594          *      'inst->conns' connection pool.
595          */
596         inst->apc_conns = malloc(sizeof(*(inst->apc_conns))*inst->num_conns);
597         if (inst->apc_conns == NULL){
598                 radlog(L_ERR, "rlm_ldap: Could not allocate memory. Aborting.");
599                 free(inst);     /* FIXME: detach */
600                 return -1;
601         }
602         for(i = 0; i < inst->num_conns; i++){
603                 inst->apc_conns[i].bound = 0;
604                 inst->apc_conns[i].locked = 0;
605                 inst->apc_conns[i].failed_conns = 0;
606                 inst->apc_conns[i].ld = NULL;
607                 pthread_mutex_init(&inst->apc_conns[i].mutex, NULL);
608         }
609 #endif
610
611         if (read_mappings(inst) != 0) {
612                 radlog(L_ERR, "rlm_ldap: Reading dictionary mappings from file %s failed",
613                        inst->dictionary_mapping);
614                 free(inst);     /* FIXME: detach */
615                 return -1;
616         }
617         if ((inst->check_item_map == NULL) &&
618             (inst->reply_item_map == NULL)) {
619                 radlog(L_ERR, "rlm_ldap: dictionary mappings file %s did not contain any mappings",
620                         inst->dictionary_mapping);
621                 free(inst);     /* FIXME: detach */
622                 return -1;
623         }
624
625         pair = inst->check_item_map;
626         while(pair != NULL){
627                 atts_num++;
628                 pair = pair->next;
629         }
630         check_map_num = (atts_num - 1);
631         pair = inst->reply_item_map;
632         while(pair != NULL){
633                 atts_num++;
634                 pair = pair->next;
635         }
636         reply_map_num = (atts_num - 1);
637         if (inst->profile_attr)
638                 atts_num++;
639         if (inst->passwd_attr)
640                 atts_num++;
641         if (inst->access_attr)
642                 atts_num++;
643 #ifdef NOVELL
644                 atts_num++;     /* eDirectory Authentication Option attribute */
645 #endif
646         inst->atts = (char **)malloc(sizeof(char *)*(atts_num + 1));
647         if (inst->atts == NULL){
648                 radlog(L_ERR, "rlm_ldap: Could not allocate memory. Aborting.");
649                 free(inst);     /* FIXME: detach */
650                 return -1;
651         }
652         pair = inst->check_item_map;
653         if (pair == NULL)
654                 pair = inst->reply_item_map;
655 #ifdef NOVELL
656         for(i=0;i<atts_num - 1;i++){
657 #else
658         for(i=0;i<atts_num;i++){
659 #endif
660                 if (i <= check_map_num ){
661                         inst->atts[i] = pair->attr;
662                         if (i == check_map_num)
663                                 pair = inst->reply_item_map;
664                         else
665                                 pair = pair->next;
666                 }
667                 else if (i <= reply_map_num){
668                         inst->atts[i] = pair->attr;
669                         pair = pair->next;
670                 }
671                 else{
672                         if (inst->profile_attr && !att_map[0]){
673                                 inst->atts[i] = inst->profile_attr;
674                                 att_map[0] = 1;
675                         }
676                         else if (inst->passwd_attr && !att_map[1]){
677                                 inst->atts[i] = inst->passwd_attr;
678                                 att_map[1] = 1;
679                         }
680                         else if (inst->access_attr && !att_map[2]){
681                                 inst->atts[i] = inst->access_attr;
682                                 att_map[2] = 1;
683                         }
684                 }
685         }
686 #ifdef NOVELL
687         {
688                 static char ts[] = "sasdefaultloginsequence";
689                 inst->atts[atts_num - 1] = ts;
690         }
691 #endif
692         inst->atts[atts_num] = NULL;
693
694         DEBUG("conns: %p",inst->conns);
695
696         *instance = inst;
697
698
699         return 0;
700 }
701
702
703 /*
704  *      read_mappings(...) reads a ldap<->radius mappings file to
705  *      inst->reply_item_map and inst->check_item_map
706  */
707 #define MAX_LINE_LEN 160
708 #define GENERIC_ATTRIBUTE_ID "$GENERIC$"
709
710 static int
711 read_mappings(ldap_instance* inst)
712 {
713         FILE* mapfile;
714         char *filename;
715
716         /*
717          *      All buffers are of MAX_LINE_LEN so we can use sscanf
718          *      without being afraid of buffer overflows
719          */
720         char buf[MAX_LINE_LEN], itemType[MAX_LINE_LEN];
721         char radiusAttribute[MAX_LINE_LEN], ldapAttribute[MAX_LINE_LEN];
722         int linenumber;
723         FR_TOKEN operator;
724         char opstring[MAX_LINE_LEN];
725
726         /* open the mappings file for reading */
727
728         filename = inst->dictionary_mapping;
729         DEBUG("rlm_ldap: reading ldap<->radius mappings from file %s", filename);
730         mapfile = fopen(filename, "r");
731
732         if (mapfile == NULL) {
733                 radlog(L_ERR, "rlm_ldap: Opening file %s failed: %s",
734                        filename, strerror(errno));
735                 return -1; /* error */
736         }
737
738         /*
739          *      read file line by line. Note that if line length
740          *      exceeds MAX_LINE_LEN, line numbers will be mixed up
741          */
742         linenumber = 0;
743
744         while (fgets(buf, sizeof buf, mapfile)!=NULL) {
745                 char* ptr;
746                 int token_count;
747                 TLDAP_RADIUS* pair;
748
749                 linenumber++;
750
751                 /* strip comments */
752                 ptr = strchr(buf, '#');
753                 if (ptr) *ptr = 0;
754
755                 /* empty line */
756                 if (buf[0] == 0) continue;
757
758                 /* extract tokens from the string */
759                 token_count = sscanf(buf, "%s %s %s %s",
760                                      itemType, radiusAttribute,
761                                      ldapAttribute, opstring);
762
763                 if (token_count <= 0) /* no tokens */
764                         continue;
765
766                 if ((token_count < 3) || (token_count > 4)) {
767                         radlog(L_ERR, "rlm_ldap: Skipping %s line %i: %s",
768                                filename, linenumber, buf);
769                         radlog(L_ERR, "rlm_ldap: Expected 3 to 4 tokens "
770                                "(Item type, RADIUS Attribute and LDAP Attribute) but found only %i", token_count);
771                         continue;
772                 }
773
774                 if (token_count == 3) {
775                         operator = T_OP_INVALID; /* use defaults */
776                 } else {
777                         ptr = opstring;
778                         operator = gettoken((void*)&ptr, buf, sizeof(buf));
779                         if ((operator < T_OP_ADD) || (operator > T_OP_CMP_EQ)) {
780                                 radlog(L_ERR, "rlm_ldap: file %s: skipping line %i: unknown or invalid operator %s",
781                                        filename, linenumber, opstring);
782                                 continue;
783                         }
784                 }
785
786                 /* create new TLDAP_RADIUS list node */
787                 pair = rad_malloc(sizeof(*pair));
788
789                 pair->attr = strdup(ldapAttribute);
790                 pair->radius_attr = strdup(radiusAttribute);
791                 pair->operator = operator;
792
793                 if ( (pair->attr == NULL) || (pair->radius_attr == NULL) ) {
794                         radlog(L_ERR, "rlm_ldap: Out of memory");
795                         if (pair->attr) free(pair->attr);
796                         if (pair->radius_attr) free(pair->radius_attr);
797                         free(pair);
798                         fclose(mapfile);
799                         return -1;
800                 }
801
802                 /* push node to correct list */
803                 if (strcasecmp(itemType, "checkItem") == 0) {
804                         pair->next = inst->check_item_map;
805                         inst->check_item_map = pair;
806                 } else if (strcasecmp(itemType, "replyItem") == 0) {
807                         pair->next = inst->reply_item_map;
808                         inst->reply_item_map = pair;
809                 } else {
810                         radlog(L_ERR, "rlm_ldap: file %s: skipping line %i: unknown itemType %s",
811                                filename, linenumber, itemType);
812                         free(pair->attr);
813                         free(pair->radius_attr);
814                         free(pair);
815                         continue;
816                 }
817
818                 DEBUG("rlm_ldap: LDAP %s mapped to RADIUS %s",
819                       pair->attr, pair->radius_attr);
820         }
821
822         fclose(mapfile);
823
824         return 0; /* success */
825 }
826
827 static int perform_search(void *instance, LDAP_CONN *conn,
828                           char *search_basedn, int scope, char *filter,
829                           char **attrs, LDAPMessage ** result)
830 {
831         int             res = RLM_MODULE_OK;
832         int             ldap_errno = 0;
833         ldap_instance  *inst = instance;
834         int             search_retry = 0;
835         struct timeval  tv;
836
837         *result = NULL;
838
839         if (!conn){
840                 radlog(L_ERR, "  [%s] NULL connection handle passed",
841                         inst->xlat_name);
842                 return RLM_MODULE_FAIL;
843         }
844         if (conn->failed_conns > MAX_FAILED_CONNS_START){
845                 conn->failed_conns++;
846                 if (conn->failed_conns >= MAX_FAILED_CONNS_END){
847                         conn->failed_conns = MAX_FAILED_CONNS_RESTART;
848                         conn->bound = 0;
849                 }
850         }
851 retry:
852         if (!conn->bound || conn->ld == NULL) {
853                 DEBUG2("  [%s] attempting LDAP reconnection", inst->xlat_name);
854                 if (conn->ld){
855                         DEBUG2("  [%s] closing existing LDAP connection",
856                                 inst->xlat_name);
857                         ldap_unbind_s(conn->ld);
858                 }
859                 if ((conn->ld = ldap_connect(instance, inst->login,
860                                              inst->password, 0, &res, NULL)) == NULL) {
861                         radlog(L_ERR, "  [%s] (re)connection attempt failed",
862                                 inst->xlat_name);
863                         if (search_retry == 0)
864                                 conn->failed_conns++;
865                         return (RLM_MODULE_FAIL);
866                 }
867                 conn->bound = 1;
868                 conn->failed_conns = 0;
869         }
870
871         tv.tv_sec = inst->timeout;
872         tv.tv_usec = 0;
873         DEBUG2("  [%s] performing search in %s, with filter %s", inst->xlat_name, 
874                search_basedn ? search_basedn : "(null)" , filter);
875         switch (ldap_search_st(conn->ld, search_basedn, scope, filter,
876                                attrs, 0, &tv, result)) {
877         case LDAP_SUCCESS:
878         case LDAP_NO_SUCH_OBJECT:
879                 break;
880         case LDAP_SERVER_DOWN:
881                 radlog(L_ERR, "  [%s] ldap_search() failed: LDAP connection lost.", inst->xlat_name);
882                 conn->failed_conns++;
883                 if (search_retry == 0){
884                         if (conn->failed_conns <= MAX_FAILED_CONNS_START){
885                                 radlog(L_INFO, "  [%s] Attempting reconnect", inst->xlat_name);
886                                 search_retry = 1;
887                                 conn->bound = 0;
888                                 ldap_msgfree(*result);
889                                 goto retry;
890                         }
891                 }
892                 ldap_msgfree(*result);
893                 return RLM_MODULE_FAIL;
894         case LDAP_INSUFFICIENT_ACCESS:
895                 radlog(L_ERR, "  [%s] ldap_search() failed: Insufficient access. Check the identity and password configuration directives.", inst->xlat_name);
896                 ldap_msgfree(*result);
897                 return RLM_MODULE_FAIL;
898         case LDAP_TIMEOUT:
899                 exec_trigger(NULL, inst->cs, "modules.ldap.timeout", TRUE);
900                 radlog(L_ERR, "  [%s] ldap_search() failed: Timed out while waiting for server to respond. Please increase the timeout.", inst->xlat_name);
901                 ldap_msgfree(*result);
902                 return RLM_MODULE_FAIL;
903         case LDAP_FILTER_ERROR:
904                 radlog(L_ERR, "  [%s] ldap_search() failed: Bad search filter: %s", inst->xlat_name,filter);
905                 ldap_msgfree(*result);
906                 return RLM_MODULE_FAIL;
907         case LDAP_TIMELIMIT_EXCEEDED:
908                 exec_trigger(NULL, inst->cs, "modules.ldap.timeout", TRUE);
909
910         case LDAP_BUSY:
911         case LDAP_UNAVAILABLE:
912                 /* We don't need to reconnect in these cases so we don't set conn->bound */
913                 ldap_get_option(conn->ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
914                 radlog(L_ERR, "  [%s] ldap_search() failed: %s", inst->xlat_name,
915                        ldap_err2string(ldap_errno));
916                 ldap_msgfree(*result);
917                 return (RLM_MODULE_FAIL);
918         default:
919                 ldap_get_option(conn->ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
920                 radlog(L_ERR, "  [%s] ldap_search() failed: %s", inst->xlat_name,
921                        ldap_err2string(ldap_errno));
922                 conn->bound = 0;
923                 ldap_msgfree(*result);
924                 return (RLM_MODULE_FAIL);
925         }
926
927         ldap_errno = ldap_count_entries(conn->ld, *result);
928         if (ldap_errno != 1) {
929                 if (ldap_errno == 0) {
930                         DEBUG("  [%s] object not found", inst->xlat_name);
931                 } else {
932                         DEBUG("  [%s] got ambiguous search result (%d results)", inst->xlat_name, ldap_errno);
933                 }
934                 res = RLM_MODULE_NOTFOUND;
935                 ldap_msgfree(*result);
936         }
937         return res;
938 }
939
940
941 /*
942  *      Translate the LDAP queries.
943  */
944 static size_t ldap_escape_func(char *out, size_t outlen, const char *in)
945 {
946         size_t len = 0;
947
948         while (in[0]) {
949                 /*
950                  *      Encode unsafe characters.
951                  */
952                 if (((len == 0) &&
953                     ((in[0] == ' ') || (in[0] == '#'))) ||
954                     (strchr(",+\"\\<>;*=()", *in))) {
955                         static const char hex[] = "0123456789abcdef";
956
957                         /*
958                          *      Only 3 or less bytes available.
959                          */
960                         if (outlen <= 3) {
961                                 break;
962                         }
963
964                         *(out++) = '\\';
965                         *(out++) = hex[((*in) >> 4) & 0x0f];
966                         *(out++) = hex[(*in) & 0x0f];
967                         outlen -= 3;
968                         len += 3;
969                         in++;
970                         continue;
971                 }
972
973                 /*
974                  *      Only one byte left.
975                  */
976                 if (outlen <= 1) {
977                         break;
978                 }
979
980                 /*
981                  *      Allowed character.
982                  */
983                 *(out++) = *(in++);
984                 outlen--;
985                 len++;
986         }
987         *out = '\0';
988         return len;
989 }
990
991 /*
992  *      ldap_groupcmp(). Implement the Ldap-Group == "group" filter
993  */
994 static int ldap_groupcmp(void *instance, REQUEST *req,
995                          UNUSED VALUE_PAIR *request, VALUE_PAIR *check,
996                          UNUSED VALUE_PAIR *check_pairs,
997                          UNUSED VALUE_PAIR **reply_pairs)
998 {
999         char            filter[MAX_FILTER_STR_LEN];
1000         char            gr_filter[MAX_FILTER_STR_LEN];
1001         int             res;
1002         LDAPMessage     *result = NULL;
1003         LDAPMessage     *msg = NULL;
1004         char            basedn[MAX_FILTER_STR_LEN];
1005         static char     firstattr[] = "dn";
1006         char            *attrs[] = {firstattr,NULL};
1007         char            **vals;
1008         ldap_instance   *inst = instance;
1009         char            *group_attrs[] = {inst->groupmemb_attr,NULL};
1010         LDAP_CONN       *conn;
1011         int             conn_id = -1;
1012         VALUE_PAIR      *vp_user_dn;
1013         VALUE_PAIR      **request_pairs;
1014
1015         request_pairs = &req->config_items;
1016
1017         DEBUG("  [%s] Entering ldap_groupcmp()", inst->xlat_name);
1018
1019         if (check->vp_strvalue == NULL || check->length == 0){
1020                 DEBUG("rlm_ldap::ldap_groupcmp: Illegal group name");
1021                 return 1;
1022         }
1023
1024         if (req == NULL){
1025                 DEBUG("rlm_ldap::ldap_groupcmp: NULL request");
1026                 return 1;
1027         }
1028
1029         if (!radius_xlat(basedn, sizeof(basedn), inst->basedn, req, ldap_escape_func)) {
1030                 DEBUG("rlm_ldap::ldap_groupcmp: unable to create basedn.");
1031                 return 1;
1032         }
1033
1034         while((vp_user_dn = pairfind(*request_pairs, PW_LDAP_USERDN, 0)) == NULL){
1035                 char            *user_dn = NULL;
1036
1037                 if (!radius_xlat(filter, sizeof(filter), inst->filter,
1038                                         req, ldap_escape_func)){
1039                         DEBUG("rlm_ldap::ldap_groupcmp: unable to create filter");
1040                         return 1;
1041                 }
1042                 if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
1043                         radlog(L_ERR, "  [%s] All ldap connections are in use", inst->xlat_name);
1044                         return 1;
1045                 }
1046                 if ((res = perform_search(inst, conn, basedn, LDAP_SCOPE_SUBTREE,
1047                                         filter, attrs, &result)) != RLM_MODULE_OK){
1048                         DEBUG("rlm_ldap::ldap_groupcmp: search failed");
1049                         ldap_release_conn(conn_id,inst);
1050                         return 1;
1051                 }
1052                 if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
1053                         DEBUG("rlm_ldap::ldap_groupcmp: ldap_first_entry() failed");
1054                         ldap_release_conn(conn_id,inst);
1055                         ldap_msgfree(result);
1056                         return 1;
1057                 }
1058                 if ((user_dn = ldap_get_dn(conn->ld, msg)) == NULL) {
1059                         DEBUG("rlm_ldap:ldap_groupcmp:: ldap_get_dn() failed");
1060                         ldap_release_conn(conn_id,inst);
1061                         ldap_msgfree(result);
1062                         return 1;
1063                 }
1064                 ldap_release_conn(conn_id,inst);
1065
1066                 /*
1067                  *      Adding new attribute containing DN for LDAP
1068                  *      object associated with given username
1069                  */
1070                 pairadd(request_pairs, pairmake("Ldap-UserDn", user_dn,
1071                                                 T_OP_EQ));
1072                 ldap_memfree(user_dn);
1073                 ldap_msgfree(result);
1074         }
1075
1076         if(!radius_xlat(gr_filter, sizeof(gr_filter),
1077                         inst->groupmemb_filt, req, ldap_escape_func)) {
1078                 DEBUG("rlm_ldap::ldap_groupcmp: unable to create filter.");
1079                 return 1;
1080         }
1081
1082         if (strchr((char *)check->vp_strvalue,',') != NULL) {
1083                 /* This looks like a DN */
1084                 strlcpy(filter, gr_filter, sizeof(filter));
1085                 strlcpy(basedn, check->vp_strvalue, sizeof(basedn));
1086         } else
1087                 snprintf(filter,sizeof(filter), "(&(%s=%s)%s)",
1088                          inst->groupname_attr,
1089                          (char *)check->vp_strvalue,gr_filter);
1090
1091         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1) {
1092                 radlog(L_ERR, "  [%s] All ldap connections are in use", inst->xlat_name);
1093                 return 1;
1094         }
1095
1096         if ((res = perform_search(inst, conn, basedn, LDAP_SCOPE_SUBTREE,
1097                                 filter, attrs, &result)) == RLM_MODULE_OK) {
1098                 DEBUG("rlm_ldap::ldap_groupcmp: User found in group %s",
1099                                 (char *)check->vp_strvalue);
1100                 ldap_msgfree(result);
1101                 ldap_release_conn(conn_id,inst);
1102                 return 0;
1103         }
1104
1105         ldap_release_conn(conn_id,inst);
1106
1107         if (res != RLM_MODULE_NOTFOUND ) {
1108                 DEBUG("rlm_ldap::ldap_groupcmp: Search returned error");
1109                 return 1;
1110         }
1111
1112         if (inst->groupmemb_attr == NULL){
1113                 /*
1114                  *      Search returned NOTFOUND and searching for
1115                  *      membership using user object attributes is not
1116                  *      specified in config file
1117                  */
1118                 DEBUG("rlm_ldap::ldap_groupcmp: Group %s not found or user is not a member.",(char *)check->vp_strvalue);
1119                 return 1;
1120         }
1121
1122         snprintf(filter,sizeof(filter), "(objectclass=*)");
1123         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
1124                 radlog(L_ERR, "  [%s] Add ldap connections are in use", inst->xlat_name);
1125                 return 1;
1126         }
1127         if ((res = perform_search(inst, conn, vp_user_dn->vp_strvalue,
1128                                   LDAP_SCOPE_BASE, filter, group_attrs,
1129                                   &result)) != RLM_MODULE_OK) {
1130                 DEBUG("rlm_ldap::ldap_groupcmp: Search returned error");
1131                 ldap_release_conn(conn_id, inst);
1132                 return 1;
1133         }
1134
1135         if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
1136                 DEBUG("rlm_ldap::ldap_groupcmp: ldap_first_entry() failed");
1137                 ldap_release_conn(conn_id,inst);
1138                 ldap_msgfree(result);
1139                 return 1;
1140         }
1141         if ((vals = ldap_get_values(conn->ld, msg,
1142                                     inst->groupmemb_attr)) != NULL) {
1143                 int i = 0;
1144                 char found = 0;
1145
1146                 for (;i < ldap_count_values(vals);i++){
1147                         if (strchr(vals[i],',') != NULL){
1148                                 /* This looks like a DN */
1149                                 LDAPMessage *gr_result = NULL;
1150                                 snprintf(filter,sizeof(filter), "(%s=%s)",
1151                                         inst->groupname_attr,
1152                                         (char *)check->vp_strvalue);
1153                                 if ((res = perform_search(inst, conn, vals[i],
1154                                                 LDAP_SCOPE_BASE, filter,
1155                                                 attrs, &gr_result)) != RLM_MODULE_OK){
1156                                         if (res != RLM_MODULE_NOTFOUND) {
1157                                                 DEBUG("rlm_ldap::ldap_groupcmp: Search returned error");
1158                                                 ldap_value_free(vals);
1159                                                 ldap_msgfree(result);
1160                                                 ldap_release_conn(conn_id,inst);
1161                                                 return 1;
1162                                         }
1163                                 } else {
1164                                         ldap_msgfree(gr_result);
1165                                         found = 1;
1166                                         break;
1167                                 }
1168                         } else {
1169                                 if (strcmp(vals[i],(char *)check->vp_strvalue) == 0){
1170                                         found = 1;
1171                                         break;
1172                                 }
1173                         }
1174                 }
1175                 ldap_value_free(vals);
1176                 ldap_msgfree(result);
1177                 if (found == 0){
1178                         DEBUG("rlm_ldap::groupcmp: Group %s not found or user not a member",
1179                                 (char *)check->vp_strvalue);
1180                         ldap_release_conn(conn_id,inst);
1181                         return 1;
1182                 }
1183         } else {
1184                         DEBUG("rlm_ldap::ldap_groupcmp: ldap_get_values() failed");
1185                         ldap_msgfree(result);
1186                         ldap_release_conn(conn_id,inst);
1187                         return 1;
1188         }
1189
1190         DEBUG("rlm_ldap::ldap_groupcmp: User found in group %s",(char *)check->vp_strvalue);
1191         ldap_release_conn(conn_id,inst);
1192
1193         return 0;
1194 }
1195
1196 /*
1197  * ldap_xlat()
1198  * Do an xlat on an LDAP URL
1199  */
1200 static size_t ldap_xlat(void *instance, REQUEST *request, const char *fmt,
1201                      char *out, size_t freespace, RADIUS_ESCAPE_STRING func)
1202 {
1203         char url[MAX_FILTER_STR_LEN];
1204         int res;
1205         size_t ret = 0;
1206         ldap_instance *inst = instance;
1207         LDAPURLDesc *ldap_url;
1208         LDAPMessage *result = NULL;
1209         LDAPMessage *msg = NULL;
1210         char **vals;
1211         int conn_id = -1;
1212         LDAP_CONN *conn;
1213
1214         DEBUG("  [%s] - ldap_xlat", inst->xlat_name);
1215         if (!radius_xlat(url, sizeof(url), fmt, request, func)) {
1216                 radlog (L_ERR, "  [%s] Unable to create LDAP URL.\n", inst->xlat_name);
1217                 return 0;
1218         }
1219         if (!ldap_is_ldap_url(url)){
1220                 radlog (L_ERR, "  [%s] String passed does not look like an LDAP URL.\n", inst->xlat_name);
1221                 return 0;
1222         }
1223         if (ldap_url_parse(url,&ldap_url)){
1224                 radlog (L_ERR, "  [%s] LDAP URL parse failed.\n", inst->xlat_name);
1225                 return 0;
1226         }
1227         if (ldap_url->lud_attrs == NULL || ldap_url->lud_attrs[0] == NULL ||
1228             ( ldap_url->lud_attrs[1] != NULL ||
1229               ( !*ldap_url->lud_attrs[0] ||
1230                 ! strcmp(ldap_url->lud_attrs[0],"*") ) ) ){
1231                 radlog (L_ERR, "  [%s] Invalid Attribute(s) request.\n", inst->xlat_name);
1232                 ldap_free_urldesc(ldap_url);
1233                 return 0;
1234         }
1235         if (ldap_url->lud_host){
1236                 if (strncmp(inst->server,ldap_url->lud_host,
1237                             strlen(inst->server)) != 0 ||
1238                     ldap_url->lud_port != inst->port) {
1239                         DEBUG("  [%s] Requested server/port is not known to this module instance.", inst->xlat_name);
1240                         ldap_free_urldesc(ldap_url);
1241                         return 0;
1242                 }
1243         }
1244         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
1245                 radlog(L_ERR, "  [%s] All ldap connections are in use", inst->xlat_name);
1246                 ldap_free_urldesc(ldap_url);
1247                 return 0;
1248         }
1249         if ((res = perform_search(inst, conn, ldap_url->lud_dn, ldap_url->lud_scope, ldap_url->lud_filter, ldap_url->lud_attrs, &result)) != RLM_MODULE_OK){
1250                 if (res == RLM_MODULE_NOTFOUND){
1251                         DEBUG("  [%s] Search returned not found", inst->xlat_name);
1252                         ldap_free_urldesc(ldap_url);
1253                         ldap_release_conn(conn_id,inst);
1254                         return 0;
1255                 }
1256                 DEBUG("  [%s] Search returned error", inst->xlat_name);
1257                 ldap_free_urldesc(ldap_url);
1258                 ldap_release_conn(conn_id,inst);
1259                 return 0;
1260         }
1261         if ((msg = ldap_first_entry(conn->ld, result)) == NULL){
1262                 DEBUG("  [%s] ldap_first_entry() failed", inst->xlat_name);
1263                 ldap_msgfree(result);
1264                 ldap_free_urldesc(ldap_url);
1265                 ldap_release_conn(conn_id,inst);
1266                 return 0;
1267         }
1268         if ((vals = ldap_get_values(conn->ld, msg, ldap_url->lud_attrs[0])) != NULL) {
1269                 ret = strlen(vals[0]);
1270                 if (ret >= freespace){
1271                         DEBUG("  [%s] Insufficient string space", inst->xlat_name);
1272                         ldap_free_urldesc(ldap_url);
1273                         ldap_value_free(vals);
1274                         ldap_msgfree(result);
1275                         ldap_release_conn(conn_id,inst);
1276                         return 0;
1277                 }
1278                 DEBUG("  [%s] Adding attribute %s, value: %s", inst->xlat_name,ldap_url->lud_attrs[0],vals[0]);
1279                 strlcpy(out,vals[0],freespace);
1280                 ldap_value_free(vals);
1281         }
1282         else
1283                 ret = 0;
1284
1285         ldap_msgfree(result);
1286         ldap_free_urldesc(ldap_url);
1287         ldap_release_conn(conn_id,inst);
1288
1289         DEBUG("  [%s] - ldap_xlat end", inst->xlat_name);
1290
1291         return ret;
1292 }
1293
1294
1295 /*
1296  *      For auto-header discovery.
1297  */
1298 static const FR_NAME_NUMBER header_names[] = {
1299         { "{clear}",    PW_CLEARTEXT_PASSWORD },
1300         { "{cleartext}", PW_CLEARTEXT_PASSWORD },
1301         { "{md5}",      PW_MD5_PASSWORD },
1302         { "{BASE64_MD5}",       PW_MD5_PASSWORD },
1303         { "{smd5}",     PW_SMD5_PASSWORD },
1304         { "{crypt}",    PW_CRYPT_PASSWORD },
1305         { "{sha}",      PW_SHA_PASSWORD },
1306         { "{ssha}",     PW_SSHA_PASSWORD },
1307         { "{nt}",       PW_NT_PASSWORD },
1308         { "{ns-mta-md5}", PW_NS_MTA_MD5_PASSWORD },
1309         { NULL, 0 }
1310 };
1311
1312
1313 /******************************************************************************
1314  *
1315  *      Function: rlm_ldap_authorize
1316  *
1317  *      Purpose: Check if user is authorized for remote access
1318  *
1319  ******************************************************************************/
1320 static int ldap_authorize(void *instance, REQUEST * request)
1321 {
1322         LDAPMessage     *result = NULL;
1323         LDAPMessage     *msg = NULL;
1324         LDAPMessage     *def_msg = NULL;
1325         LDAPMessage     *def_attr_msg = NULL;
1326         LDAPMessage     *def_result = NULL;
1327         LDAPMessage     *def_attr_result = NULL;
1328         ldap_instance   *inst = instance;
1329         char            *user_dn = NULL;
1330         char            filter[MAX_FILTER_STR_LEN];
1331         char            basedn[MAX_FILTER_STR_LEN];
1332         VALUE_PAIR      *check_tmp;
1333         VALUE_PAIR      *reply_tmp;
1334         int             res;
1335         VALUE_PAIR      **check_pairs, **reply_pairs;
1336         char            **vals;
1337         VALUE_PAIR      *module_fmsg_vp;
1338         VALUE_PAIR      *user_profile;
1339         char            module_fmsg[MAX_STRING_LEN];
1340         LDAP_CONN       *conn;
1341         int             conn_id = -1;
1342         int             added_known_password = 0;
1343
1344         if (!request->username){
1345                 RDEBUG2("Attribute \"User-Name\" is required for authorization.\n");
1346                 return RLM_MODULE_NOOP;
1347         }
1348
1349         check_pairs = &request->config_items;
1350         reply_pairs = &request->reply->vps;
1351
1352         /*
1353          * Check for valid input, zero length names not permitted
1354          */
1355         if (request->username->vp_strvalue == 0) {
1356                 DEBUG2("zero length username not permitted\n");
1357                 return RLM_MODULE_INVALID;
1358         }
1359         RDEBUG("performing user authorization for %s",
1360                request->username->vp_strvalue);
1361
1362         if (!radius_xlat(filter, sizeof(filter), inst->filter,
1363                          request, ldap_escape_func)) {
1364                 radlog(L_ERR, "  [%s] unable to create filter.\n", inst->xlat_name);
1365                 return RLM_MODULE_INVALID;
1366         }
1367
1368         if (!radius_xlat(basedn, sizeof(basedn), inst->basedn,
1369                          request, ldap_escape_func)) {
1370                 radlog(L_ERR, "  [%s] unable to create basedn.\n", inst->xlat_name);
1371                 return RLM_MODULE_INVALID;
1372         }
1373
1374         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
1375                 radlog(L_ERR, "  [%s] All ldap connections are in use", inst->xlat_name);
1376                 return RLM_MODULE_FAIL;
1377         }
1378         if ((res = perform_search(instance, conn, basedn, LDAP_SCOPE_SUBTREE, filter, inst->atts, &result)) != RLM_MODULE_OK) {
1379                 RDEBUG("search failed");
1380                 if (res == RLM_MODULE_NOTFOUND){
1381                         snprintf(module_fmsg,sizeof(module_fmsg),"  [%s] User not found", inst->xlat_name);
1382                         module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1383                         pairadd(&request->packet->vps, module_fmsg_vp);
1384                 }
1385                 ldap_release_conn(conn_id,inst);
1386                 return (res);
1387         }
1388         if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
1389                 RDEBUG("ldap_first_entry() failed");
1390                 ldap_msgfree(result);
1391                 ldap_release_conn(conn_id,inst);
1392                 return RLM_MODULE_FAIL;
1393         }
1394         if ((user_dn = ldap_get_dn(conn->ld, msg)) == NULL) {
1395                 RDEBUG("ldap_get_dn() failed");
1396                 ldap_msgfree(result);
1397                 ldap_release_conn(conn_id,inst);
1398                 return RLM_MODULE_FAIL;
1399         }
1400         /*
1401          * Adding new attribute containing DN for LDAP object associated with
1402          * given username
1403          */
1404         pairadd(check_pairs, pairmake("Ldap-UserDn", user_dn, T_OP_EQ));
1405         ldap_memfree(user_dn);
1406
1407
1408         /* Remote access is controled by attribute of the user object */
1409         if (inst->access_attr) {
1410                 if ((vals = ldap_get_values(conn->ld, msg, inst->access_attr)) != NULL) {
1411                         if (inst->default_allow){
1412                                 RDEBUG("checking if remote access for %s is allowed by %s", request->username->vp_strvalue, inst->access_attr);
1413                                 if (!strncmp(vals[0], "FALSE", 5)) {
1414                                         RDEBUG("dialup access disabled");
1415                                         snprintf(module_fmsg,sizeof(module_fmsg),"  [%s] Access Attribute denies access", inst->xlat_name);
1416                                         module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1417                                         pairadd(&request->packet->vps, module_fmsg_vp);
1418                                         ldap_msgfree(result);
1419                                         ldap_value_free(vals);
1420                                         ldap_release_conn(conn_id,inst);
1421                                         return RLM_MODULE_USERLOCK;
1422                                 }
1423                                 ldap_value_free(vals);
1424                         }
1425                         else{
1426                                 RDEBUG("%s attribute exists - access denied by default", inst->access_attr);
1427                                 snprintf(module_fmsg,sizeof(module_fmsg),"  [%s] Access Attribute denies access", inst->xlat_name);
1428                                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1429                                 pairadd(&request->packet->vps, module_fmsg_vp);
1430                                 ldap_msgfree(result);
1431                                 ldap_value_free(vals);
1432                                 ldap_release_conn(conn_id,inst);
1433                                 return RLM_MODULE_USERLOCK;
1434                         }
1435                 } else {
1436                         if (inst->default_allow){
1437                                 RDEBUG("no %s attribute - access denied by default", inst->access_attr);
1438                                 snprintf(module_fmsg,sizeof(module_fmsg),"  [%s] Access Attribute denies access", inst->xlat_name);
1439                                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1440                                 pairadd(&request->packet->vps, module_fmsg_vp);
1441                                 ldap_msgfree(result);
1442                                 ldap_release_conn(conn_id,inst);
1443                                 return RLM_MODULE_USERLOCK;
1444                         }
1445                 }
1446         }
1447
1448         /*
1449          * Check for the default profile entry. If it exists then add the
1450          * attributes it contains in the check and reply pairs
1451          */
1452
1453         user_profile = pairfind(request->config_items, PW_USER_PROFILE, 0);
1454         if (inst->default_profile || user_profile){
1455                 char *profile = inst->default_profile;
1456
1457                 strlcpy(filter,inst->base_filter,sizeof(filter));
1458                 if (user_profile)
1459                         profile = user_profile->vp_strvalue;
1460                 if (profile && *profile){
1461                         if ((res = perform_search(instance, conn,
1462                                 profile, LDAP_SCOPE_BASE,
1463                                 filter, inst->atts, &def_result)) == RLM_MODULE_OK){
1464                                 if ((def_msg = ldap_first_entry(conn->ld,def_result))){
1465                                         if ((check_tmp = ldap_pairget(conn->ld,def_msg,inst->check_item_map,check_pairs,1, inst))) {
1466                                                 if (inst->do_xlat){
1467                                                         pairxlatmove(request, check_pairs, &check_tmp);
1468                                                         pairfree(&check_tmp);
1469                                                 }
1470                                                 else
1471                                                         pairadd(check_pairs,check_tmp);
1472                                         }
1473                                         if ((reply_tmp = ldap_pairget(conn->ld,def_msg,inst->reply_item_map,reply_pairs,0, inst))) {
1474                                                 if (inst->do_xlat){
1475                                                         pairxlatmove(request, reply_pairs, &reply_tmp);
1476                                                         pairfree(&reply_tmp);
1477                                                 }
1478                                                 else
1479                                                         pairadd(reply_pairs,reply_tmp);
1480                                         }
1481                                 }
1482                                 ldap_msgfree(def_result);
1483                         } else
1484                                 RDEBUG("default_profile/user-profile search failed");
1485                 }
1486         }
1487
1488         /*
1489          * Check for the profile attribute. If it exists, we assume that it
1490          * contains the DN of an entry containg a profile for the user. That
1491          * way we can have different general profiles for various user groups
1492          * (students,faculty,staff etc)
1493          */
1494
1495         if (inst->profile_attr){
1496                 if ((vals = ldap_get_values(conn->ld, msg, inst->profile_attr)) != NULL) {
1497                         unsigned int i=0;
1498                         strlcpy(filter,inst->base_filter,sizeof(filter));
1499                         while(vals[i] && *vals[i]){
1500                                 if ((res = perform_search(instance, conn,
1501                                         vals[i], LDAP_SCOPE_BASE,
1502                                         filter, inst->atts, &def_attr_result)) == RLM_MODULE_OK){
1503                                         if ((def_attr_msg = ldap_first_entry(conn->ld,def_attr_result))){
1504                                                 if ((check_tmp = ldap_pairget(conn->ld,def_attr_msg,inst->check_item_map,check_pairs,1, inst))) {
1505                                                         if (inst->do_xlat){
1506                                                                 pairxlatmove(request, check_pairs, &check_tmp);
1507                                                                 pairfree(&check_tmp);
1508                                                         }
1509                                                         else
1510                                                                 pairadd(check_pairs,check_tmp);
1511                                                 }
1512                                                 if ((reply_tmp = ldap_pairget(conn->ld,def_attr_msg,inst->reply_item_map,reply_pairs,0, inst))) {
1513                                                         if (inst->do_xlat){
1514                                                                 pairxlatmove(request, reply_pairs, &reply_tmp);
1515                                                                 pairfree(&reply_tmp);
1516                                                         }
1517                                                         else
1518                                                                 pairadd(reply_pairs,reply_tmp);
1519                                                 }
1520                                         }
1521                                         ldap_msgfree(def_attr_result);
1522                                 } else
1523                                         RDEBUG("profile_attribute search failed");
1524                                 i++;
1525                         }
1526                         ldap_value_free(vals);
1527                 }
1528         }
1529         if (inst->passwd_attr && *inst->passwd_attr) {
1530 #ifdef NOVELL_UNIVERSAL_PASSWORD
1531                 if (strcasecmp(inst->passwd_attr,"nspmPassword") != 0) {
1532 #endif
1533                         VALUE_PAIR *passwd_item;
1534                         char **passwd_vals;
1535                         char *value = NULL;
1536                         int i;
1537
1538                         /*
1539                          *      Read the password from the DB, and
1540                          *      add it to the request.
1541                          */
1542                         passwd_vals = ldap_get_values(conn->ld,msg,
1543                                                       inst->passwd_attr);
1544
1545                         /*
1546                          *      Loop over what we received, and parse it.
1547                          */
1548                         if (passwd_vals) for (i = 0;
1549                                               passwd_vals[i] != NULL;
1550                                               i++) {
1551                                 int attr = PW_USER_PASSWORD;
1552
1553                                 if (!*passwd_vals[i])
1554                                         continue;
1555
1556                                 value = passwd_vals[i];
1557                                 if (!value) continue;
1558
1559                                 passwd_item = radius_paircreate(request,
1560                                                                 &request->config_items,
1561                                                                 attr, 0,
1562                                                                 PW_TYPE_STRING);
1563                                 strlcpy(passwd_item->vp_strvalue, value,
1564                                         sizeof(passwd_item->vp_strvalue));
1565                                 passwd_item->length = strlen(passwd_item->vp_strvalue);
1566                                 RDEBUG("Added %s = %s in check items",
1567                                       passwd_item->name,
1568                                       passwd_item->vp_strvalue);
1569                                 added_known_password = 1;
1570                         }
1571                         ldap_value_free(passwd_vals);
1572 #ifdef NOVELL_UNIVERSAL_PASSWORD
1573                 }
1574                 else{
1575                 /*
1576                 * Read Universal Password from eDirectory
1577                 */
1578                         VALUE_PAIR      *passwd_item;
1579                         VALUE_PAIR      *vp_user_dn;
1580                         char            *universal_password = NULL;
1581                         size_t          universal_password_len = UNIVERSAL_PASS_LEN;
1582                         char            *passwd_val = NULL;
1583
1584                         res = 0;
1585
1586                         if ((passwd_item = pairfind(request->config_items, PW_CLEARTEXT_PASSWORD, 0)) == NULL){
1587
1588                                 universal_password = rad_malloc(universal_password_len);
1589                                 memset(universal_password, 0, universal_password_len);
1590
1591                                 vp_user_dn = pairfind(request->config_items,PW_LDAP_USERDN, 0);
1592                                 res = nmasldap_get_password(conn->ld,vp_user_dn->vp_strvalue,&universal_password_len,universal_password);
1593
1594                                 if (res == 0){
1595                                         passwd_val = universal_password;
1596                                         if (passwd_val){
1597                                                 passwd_item = radius_paircreate(request, &request->config_items, PW_CLEARTEXT_PASSWORD, 0, PW_TYPE_STRING);
1598                                                 strlcpy(passwd_item->vp_strvalue,passwd_val,sizeof(passwd_item->vp_strvalue));
1599                                                 passwd_item->length = strlen(passwd_item->vp_strvalue);
1600                                                 added_known_password = 1;
1601
1602 #ifdef NOVELL
1603                                                 {
1604                                                         DICT_ATTR *dattr;
1605                                                         VALUE_PAIR      *vp_inst, *vp_apc;
1606                                                         int inst_attr, apc_attr;
1607
1608                                                         dattr = dict_attrbyname("LDAP-Instance");
1609                                                         inst_attr = dattr->attr;
1610                                                         dattr = dict_attrbyname("eDir-APC");
1611                                                         apc_attr = dattr->attr;
1612
1613                                                         vp_inst = pairfind(request->config_items, inst_attr, 0);
1614                                                         if(vp_inst == NULL){
1615                                                                 /*
1616                                                                  * The authorize method of no other LDAP module instance has
1617                                                                  * processed this request.
1618                                                                  */
1619                                                                 vp_inst = radius_paircreate(request, &request->config_items, inst_attr, 0, PW_TYPE_STRING);
1620                                                                 strlcpy(vp_inst->vp_strvalue, inst->xlat_name, sizeof(vp_inst->vp_strvalue));
1621                                                                 vp_inst->length = strlen(vp_inst->vp_strvalue);
1622
1623                                                                 /*
1624                                                                  * Inform the authenticate / post-auth method about the presence
1625                                                                  * of UP in the config items list and whether eDirectory account
1626                                                                  * policy check is to be performed or not.
1627                                                                  */
1628                                                                 vp_apc = radius_paircreate(request, &request->config_items, apc_attr, 0, PW_TYPE_STRING);
1629                                                                 if(!inst->edir_account_policy_check){
1630                                                                         /* Do nothing */
1631                                                                         strcpy(vp_apc->vp_strvalue, "1");
1632                                                                 }else{
1633                                                                         /* Perform eDirectory account-policy check */
1634                                                                         strcpy(vp_apc->vp_strvalue, "2");
1635                                                                 }
1636                                                                 vp_apc->length = 1;
1637                                                         }
1638                                                 }
1639 #endif
1640
1641                                                 RDEBUG("Added the eDirectory password %s in check items as %s",passwd_item->vp_strvalue,passwd_item->name);
1642                                         }
1643                                 }
1644                                 else {
1645                                         RDEBUG("Error reading Universal Password.Return Code = %d",res);
1646                                 }
1647
1648                                 memset(universal_password, 0, universal_password_len);
1649                                 free(universal_password);
1650                         }
1651                 }
1652 #endif
1653         }
1654
1655 #ifdef NOVELL
1656         {
1657                 VALUE_PAIR      *vp_auth_opt;
1658                 DICT_ATTR       *dattr;
1659                 char            **auth_option;
1660                 int             auth_opt_attr;
1661
1662                 dattr = dict_attrbyname("eDir-Auth-Option");
1663                 auth_opt_attr = dattr->attr;
1664                 if(pairfind(*check_pairs, auth_opt_attr, 0) == NULL){
1665                         if ((auth_option = ldap_get_values(conn->ld, msg, "sasDefaultLoginSequence")) != NULL) {
1666                                 if ((vp_auth_opt = paircreate(auth_opt_attr, 0, PW_TYPE_STRING)) == NULL){
1667                                         radlog(L_ERR, "  [%s] Could not allocate memory. Aborting.", inst->xlat_name);
1668                                         ldap_msgfree(result);
1669                                         ldap_release_conn(conn_id, inst);
1670                                 }
1671                                 strcpy(vp_auth_opt->vp_strvalue, auth_option[0]);
1672                                 vp_auth_opt->length = strlen(auth_option[0]);
1673                                 pairadd(&request->config_items, vp_auth_opt);
1674                         }else{
1675                                 RDEBUG("No default NMAS login sequence");
1676                         }
1677                 }
1678         }
1679 #endif
1680
1681         RDEBUG("looking for check items in directory...");
1682
1683         if ((check_tmp = ldap_pairget(conn->ld, msg, inst->check_item_map,check_pairs,1, inst)) != NULL) {
1684                 if (inst->do_xlat){
1685                         pairxlatmove(request, check_pairs, &check_tmp);
1686                         pairfree(&check_tmp);
1687                 }
1688                 else
1689                         pairadd(check_pairs,check_tmp);
1690         }
1691
1692
1693         RDEBUG("looking for reply items in directory...");
1694
1695
1696         if ((reply_tmp = ldap_pairget(conn->ld, msg, inst->reply_item_map,reply_pairs,0, inst)) != NULL) {
1697                 if (inst->do_xlat){
1698                         pairxlatmove(request, reply_pairs, &reply_tmp);
1699                         pairfree(&reply_tmp);
1700                 }
1701                 else
1702                         pairadd(reply_pairs,reply_tmp);
1703         }
1704
1705        if (inst->do_comp && paircompare(request,request->packet->vps,*check_pairs,reply_pairs) != 0){
1706 #ifdef NOVELL
1707                 /* Don't perform eDirectory APC if RADIUS authorize fails */
1708                 int apc_attr;
1709                 VALUE_PAIR *vp_apc;
1710                 DICT_ATTR *dattr;
1711
1712                 dattr = dict_attrbyname("eDir-APC");
1713                 apc_attr = dattr->attr;
1714
1715                 vp_apc = pairfind(request->config_items, apc_attr, 0);
1716                 if(vp_apc)
1717                         vp_apc->vp_strvalue[0] = '1';
1718 #endif
1719
1720                 RDEBUG("Pairs do not match. Rejecting user.");
1721                 snprintf(module_fmsg,sizeof(module_fmsg),"  [%s] Pairs do not match", inst->xlat_name);
1722                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1723                 pairadd(&request->packet->vps, module_fmsg_vp);
1724                 ldap_msgfree(result);
1725                 ldap_release_conn(conn_id,inst);
1726
1727                 return RLM_MODULE_REJECT;
1728         }
1729        
1730        /*
1731         *       More warning messages for people who can't be bothered
1732         *       to read the documentation.
1733         */
1734        if (debug_flag > 1) {
1735                if (!pairfind(request->config_items, PW_CLEARTEXT_PASSWORD, 0) &&
1736                    !pairfind(request->config_items, PW_NT_PASSWORD, 0) &&
1737                    !pairfind(request->config_items, PW_USER_PASSWORD, 0) &&
1738                    !pairfind(request->config_items, PW_PASSWORD_WITH_HEADER, 0) &&
1739                    !pairfind(request->config_items, PW_CRYPT_PASSWORD, 0)) {
1740                        DEBUG("WARNING: No \"known good\" password was found in LDAP.  Are you sure that the user is configured correctly?");
1741                }
1742        }
1743
1744         /*
1745          * Module should default to LDAP authentication if no Auth-Type
1746          * specified.  Note that we do this ONLY if configured, AND we
1747          * set the Auth-Type to our module name, which allows multiple
1748          * ldap instances to work.
1749          */
1750         if (inst->set_auth_type &&
1751             (pairfind(*check_pairs, PW_AUTH_TYPE, 0) == NULL) &&
1752             request->password &&
1753             (request->password->attribute == PW_USER_PASSWORD) &&
1754             !added_known_password) {
1755                 pairadd(check_pairs, pairmake("Auth-Type", inst->auth_type, T_OP_EQ));
1756                 RDEBUG("Setting Auth-Type = %s", inst->auth_type);
1757         }
1758
1759         RDEBUG("user %s authorized to use remote access",
1760               request->username->vp_strvalue);
1761         ldap_msgfree(result);
1762         ldap_release_conn(conn_id,inst);
1763
1764         return RLM_MODULE_OK;
1765 }
1766
1767 /*****************************************************************************
1768  *
1769  *      Function: rlm_ldap_authenticate
1770  *
1771  *      Purpose: Check the user's password against ldap database
1772  *
1773  *****************************************************************************/
1774 static int ldap_authenticate(void *instance, REQUEST * request)
1775 {
1776         LDAP           *ld_user;
1777         LDAPMessage    *result, *msg;
1778         ldap_instance  *inst = instance;
1779         static char     firstattr[] = "uid";
1780         char           *user_dn, *attrs[] = {firstattr, NULL};
1781         char            filter[MAX_FILTER_STR_LEN];
1782         char            basedn[MAX_FILTER_STR_LEN];
1783         int             res;
1784         VALUE_PAIR     *vp_user_dn;
1785         VALUE_PAIR      *module_fmsg_vp;
1786         char            module_fmsg[MAX_STRING_LEN];
1787         LDAP_CONN       *conn;
1788         int             conn_id = -1;
1789 #ifdef NOVELL
1790         char            *err = NULL;
1791 #endif
1792
1793         /*
1794          * Ensure that we're being passed a plain-text password, and not
1795          * anything else.
1796          */
1797
1798         if (!request->username) {
1799                 radlog(L_AUTH, "  [%s] Attribute \"User-Name\" is required for authentication.\n", inst->xlat_name);
1800                 return RLM_MODULE_INVALID;
1801         }
1802
1803         if (!request->password){
1804                 radlog(L_AUTH, "  [%s] Attribute \"User-Password\" is required for authentication.", inst->xlat_name);
1805                 DEBUG2("  You seem to have set \"Auth-Type := LDAP\" somewhere.");
1806                 DEBUG2("  THAT CONFIGURATION IS WRONG.  DELETE IT.");
1807                 DEBUG2("  YOU ARE PREVENTING THE SERVER FROM WORKING PROPERLY.");
1808                 return RLM_MODULE_INVALID;
1809         }
1810
1811         if(request->password->attribute != PW_USER_PASSWORD) {
1812                 radlog(L_AUTH, "  [%s] Attribute \"User-Password\" is required for authentication. Cannot use \"%s\".", inst->xlat_name, request->password->name);
1813                 return RLM_MODULE_INVALID;
1814         }
1815
1816         if (request->password->length == 0) {
1817                 snprintf(module_fmsg,sizeof(module_fmsg),"  [%s] empty password supplied", inst->xlat_name);
1818                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1819                 pairadd(&request->packet->vps, module_fmsg_vp);
1820                 return RLM_MODULE_INVALID;
1821         }
1822
1823         /*
1824          * Check that we don't have any failed connections. If we do there's no real need
1825          * of runing. Also give it another chance if we have a lot of failed connections.
1826          */
1827         if (inst->failed_conns > MAX_FAILED_CONNS_END)
1828                 inst->failed_conns = 0;
1829         if (inst->failed_conns > MAX_FAILED_CONNS_START){
1830                 inst->failed_conns++;
1831                 return RLM_MODULE_FAIL;
1832         }
1833
1834
1835         RDEBUG("login attempt by \"%s\" with password \"%s\"",
1836                request->username->vp_strvalue, request->password->vp_strvalue);
1837
1838         while ((vp_user_dn = pairfind(request->config_items,
1839                                       PW_LDAP_USERDN, 0)) == NULL) {
1840                 if (!radius_xlat(filter, sizeof(filter), inst->filter,
1841                                 request, ldap_escape_func)) {
1842                         radlog(L_ERR, "  [%s] unable to create filter.\n", inst->xlat_name);
1843                         return RLM_MODULE_INVALID;
1844                 }
1845
1846                 if (!radius_xlat(basedn, sizeof(basedn), inst->basedn,
1847                                 request, ldap_escape_func)) {
1848                         radlog(L_ERR, "  [%s] unable to create basedn.\n", inst->xlat_name);
1849                         return RLM_MODULE_INVALID;
1850                 }
1851
1852                 if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
1853                         radlog(L_ERR, "  [%s] All ldap connections are in use", inst->xlat_name);
1854                         return RLM_MODULE_FAIL;
1855                 }
1856                 if ((res = perform_search(instance, conn, basedn, LDAP_SCOPE_SUBTREE, filter, attrs, &result)) != RLM_MODULE_OK) {
1857                         if (res == RLM_MODULE_NOTFOUND){
1858                                 snprintf(module_fmsg,sizeof(module_fmsg),"  [%s] User not found", inst->xlat_name);
1859                                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1860                                 pairadd(&request->packet->vps, module_fmsg_vp);
1861                         }
1862                         ldap_release_conn(conn_id,inst);
1863                         return (res);
1864                 }
1865                 if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
1866                         ldap_msgfree(result);
1867                         ldap_release_conn(conn_id,inst);
1868                         return RLM_MODULE_FAIL;
1869                 }
1870                 if ((user_dn = ldap_get_dn(conn->ld, msg)) == NULL) {
1871                         RDEBUG("ldap_get_dn() failed");
1872                         ldap_msgfree(result);
1873                         ldap_release_conn(conn_id,inst);
1874                         return RLM_MODULE_FAIL;
1875                 }
1876                 ldap_release_conn(conn_id,inst);
1877                 pairadd(&request->config_items, pairmake("Ldap-UserDn", user_dn, T_OP_EQ));
1878                 ldap_memfree(user_dn);
1879                 ldap_msgfree(result);
1880         }
1881
1882         user_dn = vp_user_dn->vp_strvalue;
1883
1884         RDEBUG("user DN: %s", user_dn);
1885
1886 #ifndef NOVELL
1887         ld_user = ldap_connect(instance, user_dn, request->password->vp_strvalue,
1888                                1, &res, NULL);
1889 #else
1890         /* Don't perform eDirectory APC again after attempting to bind here. */
1891         {
1892                 int apc_attr;
1893                 DICT_ATTR *dattr;
1894                 VALUE_PAIR *vp_apc;
1895                 VALUE_PAIR      *vp_auth_opt, *vp_state;
1896                 int auth_opt_attr;
1897                 char seq[256];
1898                 char host_ipaddr[32];
1899                 LDAP_CONN       *conn1;
1900                 int auth_state = -1;
1901                 char            *challenge = NULL;
1902                 size_t          challenge_len = MAX_CHALLENGE_LEN;
1903                 char            *state = NULL;
1904
1905                 dattr = dict_attrbyname("eDir-APC");
1906                 apc_attr = dattr->attr;
1907                 vp_apc = pairfind(request->config_items, apc_attr, 0);
1908                 if(vp_apc && vp_apc->vp_strvalue[0] == '2')
1909                         vp_apc->vp_strvalue[0] = '3';
1910
1911                 res = 0;
1912
1913                 dattr = dict_attrbyname("eDir-Auth-Option");
1914                 auth_opt_attr = dattr->attr;
1915
1916                 vp_auth_opt = pairfind(request->config_items, auth_opt_attr, 0);
1917
1918                 if(vp_auth_opt )
1919                 {
1920                         RDEBUG("ldap auth option = %s", vp_auth_opt->vp_strvalue);
1921                         strncpy(seq, vp_auth_opt->vp_strvalue, vp_auth_opt->length);
1922                         seq[vp_auth_opt->length] = '\0';
1923                         if( strcasecmp(seq, "<No Default>") ){
1924
1925                                 /* Get the client IP address to check for packet validity */
1926                                 inet_ntop(AF_INET, &request->packet->src_ipaddr, host_ipaddr, sizeof(host_ipaddr));
1927
1928                                 /* challenge variable is used to receive the challenge from the
1929                                  * Token method (if any) and also to send the state attribute
1930                                  * in case the request packet is a reply to a challenge
1931                                  */
1932                                 challenge = rad_malloc(MAX_CHALLENGE_LEN);
1933
1934                                 /*  If state attribute present in request it is a reply to challenge. */
1935                                 if((vp_state = pairfind(request->packet->vps, PW_STATE, 0))!= NULL ){
1936                                         RDEBUG("Response to Access-Challenge");
1937                                         strncpy(challenge, vp_state->vp_strvalue, sizeof(challenge));
1938                                         challenge_len = vp_state->length;
1939                                         challenge[challenge_len] = 0;
1940                                         auth_state = -2;
1941                                 }
1942
1943                                 if ((conn_id = ldap_get_conn(inst->conns, &conn1, inst)) == -1){
1944                                         radlog(L_ERR, "  [%s] All ldap connections are in use", inst->xlat_name);
1945                                         res =  RLM_MODULE_FAIL;
1946                                 }
1947
1948                                 if(!conn1){
1949                                         radlog(L_ERR, "  [%s] NULL connection handle passed", inst->xlat_name);
1950                                         return RLM_MODULE_FAIL;
1951                                 }
1952
1953                                 if (conn1->failed_conns > MAX_FAILED_CONNS_START){
1954                                         conn1->failed_conns++;
1955                                         if (conn1->failed_conns >= MAX_FAILED_CONNS_END){
1956                                                 conn1->failed_conns = MAX_FAILED_CONNS_RESTART;
1957                                                 conn1->bound = 0;
1958                                         }
1959                                 }
1960 retry:
1961                                 if (!conn1->bound || conn1->ld == NULL) {
1962                                         DEBUG2("  [%s] attempting LDAP reconnection", inst->xlat_name);
1963                                         if (conn1->ld){
1964                                                 DEBUG2("  [%s] closing existing LDAP connection", inst->xlat_name);
1965                                                 ldap_unbind_s(conn1->ld);
1966                                         }
1967                                         if ((conn1->ld = ldap_connect(instance, inst->login,inst->password, 0, &res, NULL)) == NULL) {
1968                                                 radlog(L_ERR, "  [%s] (re)connection attempt failed", inst->xlat_name);
1969                                                 conn1->failed_conns++;
1970                                                 return (RLM_MODULE_FAIL);
1971                                         }
1972                                         conn1->bound = 1;
1973                                         conn1->failed_conns = 0;
1974                                 }
1975                                 RDEBUG("Performing NMAS Authentication for user: %s, seq: %s \n", user_dn,seq);
1976
1977                                 res = radLdapXtnNMASAuth(conn1->ld, user_dn, request->password->vp_strvalue, seq, host_ipaddr, &challenge_len, challenge, &auth_state );
1978
1979                                 switch(res){
1980                                         case LDAP_SUCCESS:
1981                                                 ldap_release_conn(conn_id,inst);
1982                                                 if ( auth_state == -1)
1983                                                         res = RLM_MODULE_FAIL;
1984                                                 if ( auth_state != REQUEST_CHALLENGED){
1985                                                         if (auth_state == REQUEST_ACCEPTED){
1986                                                                 RDEBUG("user %s authenticated succesfully",request->username->vp_strvalue);
1987                                                                 res = RLM_MODULE_OK;
1988                                                         }else if(auth_state == REQUEST_REJECTED){
1989                                                                 RDEBUG("user %s authentication failed",request->username->vp_strvalue);
1990                                                                 res = RLM_MODULE_REJECT;
1991                                                         }
1992                                                 }else{
1993                                                         /* Request challenged. Generate Reply-Message attribute with challenge data */
1994                                                         pairadd(&request->reply->vps,pairmake("Reply-Message", challenge, T_OP_EQ));
1995                                                         /* Generate state attribute */
1996                                                         state = rad_malloc(MAX_CHALLENGE_LEN);
1997                                                         (void) sprintf(state, "%s%s", challenge, challenge);
1998                                                         vp_state = paircreate(PW_STATE, 0, PW_TYPE_OCTETS);
1999                                                         memcpy(vp_state->vp_strvalue, state, strlen(state));
2000                                                         vp_state->length = strlen(state);
2001                                                         pairadd(&request->reply->vps, vp_state);
2002                                                         free(state);
2003                                                         /* Mark the packet as a Acceess-Challenge Packet */
2004                                                         request->reply->code = PW_ACCESS_CHALLENGE;
2005                                                         RDEBUG("Sending Access-Challenge.");
2006                                                         res = RLM_MODULE_HANDLED;
2007                                                 }
2008                                                 if(challenge)
2009                                                         free(challenge);
2010                                                 return res;
2011                                         case LDAP_SERVER_DOWN:
2012                                                 radlog(L_ERR, "  [%s] nmas authentication failed: LDAP connection lost.", inst->xlat_name);                                                conn->failed_conns++;
2013                                                 if (conn->failed_conns <= MAX_FAILED_CONNS_START){
2014                                                         radlog(L_INFO, "  [%s] Attempting reconnect", inst->xlat_name);
2015                                                         conn->bound = 0;
2016                                                         goto retry;
2017                                                 }
2018                                                 if(challenge)
2019                                                         free(challenge);
2020                                                 return RLM_MODULE_FAIL;
2021                                         default:
2022                                                 ldap_release_conn(conn_id,inst);
2023                                                 if(challenge)
2024                                                         free(challenge);
2025                                                 return RLM_MODULE_FAIL;
2026                                 }
2027                         }
2028                 }
2029         }
2030
2031         ld_user = ldap_connect(instance, user_dn, request->password->vp_strvalue,
2032                         1, &res, &err);
2033
2034         if(err != NULL){
2035                 /* 'err' contains the LDAP connection error description */
2036                 RDEBUG("%s", err);
2037                 pairadd(&request->reply->vps, pairmake("Reply-Message", err, T_OP_EQ));
2038                 ldap_memfree((void *)err);
2039         }
2040 #endif
2041
2042         if (ld_user == NULL){
2043                 if (res == RLM_MODULE_REJECT){
2044                         inst->failed_conns = 0;
2045                         snprintf(module_fmsg,sizeof(module_fmsg),"  [%s] Bind as user failed", inst->xlat_name);
2046                         module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
2047                         pairadd(&request->packet->vps, module_fmsg_vp);
2048                 }
2049                 if (res == RLM_MODULE_FAIL){
2050                         RDEBUG("ldap_connect() failed");
2051                         inst->failed_conns++;
2052                 }
2053                 return (res);
2054         }
2055
2056         RDEBUG("user %s authenticated succesfully",
2057               request->username->vp_strvalue);
2058         ldap_unbind_s(ld_user);
2059         inst->failed_conns = 0;
2060
2061         return RLM_MODULE_OK;
2062 }
2063
2064 #ifdef NOVELL
2065 /*****************************************************************************
2066  *
2067  *      Function: rlm_ldap_postauth
2068  *
2069  *      Purpose: Perform eDirectory account policy check and failed-login reporting
2070  *      to eDirectory.
2071  *
2072  *****************************************************************************/
2073 static int ldap_postauth(void *instance, REQUEST * request)
2074 {
2075         int res = RLM_MODULE_FAIL;
2076         int inst_attr, apc_attr;
2077         char password[UNIVERSAL_PASS_LEN];
2078         ldap_instance  *inst = instance;
2079         LDAP_CONN       *conn;
2080         VALUE_PAIR *vp_inst, *vp_apc;
2081         DICT_ATTR *dattr;
2082
2083         dattr = dict_attrbyname("LDAP-Instance");
2084         inst_attr = dattr->attr;
2085         dattr = dict_attrbyname("eDir-APC");
2086         apc_attr = dattr->attr;
2087
2088         vp_inst = pairfind(request->config_items, inst_attr, 0);
2089
2090         /*
2091          * Check if the password in the config items list is the user's UP which has
2092          * been read in the authorize method of this instance of the LDAP module.
2093          */
2094         if((vp_inst == NULL) || strcmp(vp_inst->vp_strvalue, inst->xlat_name))
2095                 return RLM_MODULE_NOOP;
2096
2097         vp_apc = pairfind(request->config_items, apc_attr, 0);
2098
2099         switch(vp_apc->vp_strvalue[0]){
2100                 case '1':
2101                         /* Account policy check not enabled */
2102                 case '3':
2103                         /* Account policy check has been completed */
2104                         res = RLM_MODULE_NOOP;
2105                         break;
2106                 case '2':
2107                         {
2108                                 int err, conn_id = -1;
2109                                 char *error_msg = NULL;
2110                                 VALUE_PAIR *vp_fdn, *vp_pwd;
2111                                 DICT_ATTR *da;
2112
2113                                 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
2114                                   /* Bind to eDirectory as the RADIUS user with a wrong password. */
2115                                   vp_pwd = pairfind(request->config_items, PW_CLEARTEXT_PASSWORD, 0);
2116                                   if (vp_pwd && *vp_pwd->vp_strvalue) {
2117                                           strcpy(password, vp_pwd->vp_strvalue);
2118                                           if (password[0] != 'a') {
2119                                                   password[0] = 'a';
2120                                           } else {
2121                                                   password[0] = 'b';
2122                                           }
2123                                   } else {
2124                                           strcpy(password, "dummy_password");
2125                                   }
2126                                   res = RLM_MODULE_REJECT;
2127                                 } else {
2128                                         /* Bind to eDirectory as the RADIUS user using the user's UP */
2129                                         vp_pwd = pairfind(request->config_items, PW_CLEARTEXT_PASSWORD, 0);
2130                                         if (vp_pwd == NULL) {
2131                                                 RDEBUG("User's Universal Password not in config items list.");
2132                                                 return RLM_MODULE_FAIL;
2133                                         }
2134                                         strcpy(password, vp_pwd->vp_strvalue);
2135                                 }
2136
2137                                 if ((da = dict_attrbyname("Ldap-UserDn")) == NULL) {
2138                                         RDEBUG("Attribute for user FDN not found in dictionary. Unable to proceed");
2139                                         return RLM_MODULE_FAIL;
2140                                 }
2141
2142                                 vp_fdn = pairfind(request->config_items, da->attr, 0);
2143                                 if (vp_fdn == NULL) {
2144                                         RDEBUG("User's FQDN not in config items list.");
2145                                         return RLM_MODULE_FAIL;
2146                                 }
2147
2148                                 if ((conn_id = ldap_get_conn(inst->apc_conns, &conn, inst)) == -1){
2149                                         radlog(L_ERR, "  [%s] All ldap connections are in use", inst->xlat_name);
2150                                         return RLM_MODULE_FAIL;
2151                                 }
2152
2153                                 /*
2154                                  *      If there is an existing LDAP
2155                                  *      connection to the directory,
2156                                  *      bind over it. Otherwise,
2157                                  *      establish a new connection.
2158                                  */
2159                         postauth_reconnect:
2160                                 if (!conn->bound || conn->ld == NULL) {
2161                                         DEBUG2("  [%s] attempting LDAP reconnection", inst->xlat_name);
2162                                         if (conn->ld){
2163                                                 DEBUG2("  [%s] closing existing LDAP connection", inst->xlat_name);
2164                                                 ldap_unbind_s(conn->ld);
2165                                         }
2166                                         if ((conn->ld = ldap_connect(instance, (char *)vp_fdn->vp_strvalue, password, 0, &res, &error_msg)) == NULL) {
2167                                                 radlog(L_ERR, "  [%s] eDirectory account policy check failed.", inst->xlat_name);
2168
2169                                                 if (error_msg != NULL) {
2170                                                         RDEBUG("%s", error_msg);
2171                                                         pairadd(&request->reply->vps, pairmake("Reply-Message", error_msg, T_OP_EQ));
2172                                                         ldap_memfree((void *)error_msg);
2173                                                 }
2174
2175                                                 vp_apc->vp_strvalue[0] = '3';
2176                                                 ldap_release_apc_conn(conn_id, inst);
2177                                                 return RLM_MODULE_REJECT;
2178                                         }
2179                                         conn->bound = 1;
2180                                 } else if((err = ldap_simple_bind_s(conn->ld, (char *)vp_fdn->vp_strvalue, password)) != LDAP_SUCCESS) {
2181                                         if (err == LDAP_SERVER_DOWN) {
2182                                                 conn->bound = 0;
2183                                                 goto postauth_reconnect;
2184                                         }
2185                                         RDEBUG("eDirectory account policy check failed.");
2186                                         ldap_get_option(conn->ld, LDAP_OPT_ERROR_STRING, &error_msg);
2187                                         if (error_msg != NULL) {
2188                                                 RDEBUG("%s", error_msg);
2189                                                 pairadd(&request->reply->vps, pairmake("Reply-Message", error_msg, T_OP_EQ));
2190                                                 ldap_memfree((void *)error_msg);
2191                                         }
2192                                         vp_apc->vp_strvalue[0] = '3';
2193                                         ldap_release_apc_conn(conn_id, inst);
2194                                         return RLM_MODULE_REJECT;
2195                                 }
2196                                 vp_apc->vp_strvalue[0] = '3';
2197                                 ldap_release_apc_conn(conn_id, inst);
2198                                 return RLM_MODULE_OK;
2199                         }
2200         }
2201         return res;
2202 }
2203 #endif
2204
2205 #if LDAP_SET_REBIND_PROC_ARGS == 3
2206 static int ldap_rebind(LDAP *ld, LDAP_CONST char *url,
2207                        UNUSED ber_tag_t request, UNUSED ber_int_t msgid,
2208                        void *params )
2209 {
2210         ldap_instance   *inst = params;
2211
2212         DEBUG("  [%s] rebind to URL %s", inst->xlat_name,url);
2213         return ldap_bind_s(ld, inst->login, inst->password, LDAP_AUTH_SIMPLE);
2214 }
2215 #endif
2216
2217 static LDAP *ldap_connect(void *instance, const char *dn, const char *password,
2218                           int auth, int *result, char **err)
2219 {
2220         ldap_instance  *inst = instance;
2221         LDAP           *ld = NULL;
2222         int             msgid, rc, ldap_version;
2223         int             ldap_errno = 0;
2224         LDAPMessage    *res;
2225         struct timeval tv;
2226
2227         if (inst->is_url){
2228 #ifdef HAVE_LDAP_INITIALIZE
2229                 DEBUG("  [%s] (re)connect to %s, authentication %d", inst->xlat_name, inst->server, auth);
2230                 if (ldap_initialize(&ld, inst->server) != LDAP_SUCCESS) {
2231                         exec_trigger(NULL, inst->cs, "modules.ldap.fail", FALSE);
2232                         radlog(L_ERR, "  [%s] ldap_initialize() failed", inst->xlat_name);
2233                         *result = RLM_MODULE_FAIL;
2234                         return (NULL);
2235                 }
2236 #endif
2237         } else {
2238                 DEBUG("  [%s] (re)connect to %s:%d, authentication %d", inst->xlat_name, inst->server, inst->port, auth);
2239                 if ((ld = ldap_init(inst->server, inst->port)) == NULL) {
2240                         exec_trigger(NULL, inst->cs, "modules.ldap.fail", FALSE);
2241                         radlog(L_ERR, "  [%s] ldap_init() failed", inst->xlat_name);
2242                         *result = RLM_MODULE_FAIL;
2243                         return (NULL);
2244                 }
2245         }
2246
2247         tv.tv_sec = inst->net_timeout;
2248         tv.tv_usec = 0;
2249         if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT,
2250                             (void *) &tv) != LDAP_OPT_SUCCESS) {
2251                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2252                 radlog(L_ERR, "  [%s] Could not set LDAP_OPT_NETWORK_TIMEOUT %d: %s", inst->xlat_name, inst->net_timeout, ldap_err2string(ldap_errno));
2253         }
2254
2255         /*
2256          *      Leave "chase_referrals" unset to use the OpenLDAP
2257          *      default.
2258          */
2259         if (inst->chase_referrals != 2) {
2260                 if (inst->chase_referrals) {
2261                         rc=ldap_set_option(ld, LDAP_OPT_REFERRALS,
2262                                            LDAP_OPT_ON);
2263                         
2264 #if LDAP_SET_REBIND_PROC_ARGS == 3
2265                         if (inst->rebind == 1) {
2266                                 ldap_set_rebind_proc(ld, ldap_rebind,
2267                                                      inst);
2268                         }
2269 #endif
2270                 } else {
2271                         rc=ldap_set_option(ld, LDAP_OPT_REFERRALS,
2272                                            LDAP_OPT_OFF);
2273                 }
2274                 if (rc != LDAP_OPT_SUCCESS) {
2275                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2276                         radlog(L_ERR, "  [%s] Could not set LDAP_OPT_REFERRALS=%d  %s", inst->xlat_name, inst->chase_referrals, ldap_err2string(ldap_errno));
2277                 }
2278         }
2279
2280         if (ldap_set_option(ld, LDAP_OPT_TIMELIMIT,
2281                             (void *) &(inst->timelimit)) != LDAP_OPT_SUCCESS) {
2282                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2283                 radlog(L_ERR, "  [%s] Could not set LDAP_OPT_TIMELIMIT %d: %s", inst->xlat_name, inst->timelimit, ldap_err2string(ldap_errno));
2284         }
2285
2286         if (inst->ldap_debug && ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &(inst->ldap_debug)) != LDAP_OPT_SUCCESS) {
2287                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2288                 radlog(L_ERR, "  [%s] Could not set LDAP_OPT_DEBUG_LEVEL %d: %s", inst->xlat_name, inst->ldap_debug, ldap_err2string(ldap_errno));
2289         }
2290
2291         ldap_version = LDAP_VERSION3;
2292         if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION,
2293                             &ldap_version) != LDAP_OPT_SUCCESS) {
2294                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2295                 radlog(L_ERR, "  [%s] Could not set LDAP version to V3: %s", inst->xlat_name, ldap_err2string(ldap_errno));
2296         }
2297
2298 #ifdef LDAP_OPT_X_KEEPALIVE_IDLE
2299         if (ldap_set_option(ld, LDAP_OPT_X_KEEPALIVE_IDLE,
2300                             (void *) &(inst->keepalive_idle)) != LDAP_OPT_SUCCESS) {
2301                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2302                 radlog(L_ERR, "  [%s] Could not set LDAP_OPT_X_KEEPALIVE_IDLE %d: %s", inst->xlat_name, inst->keepalive_idle, ldap_err2string(ldap_errno));
2303         }
2304 #endif
2305
2306 #ifdef LDAP_OPT_X_KEEPALIVE_PROBES
2307         if (ldap_set_option(ld, LDAP_OPT_X_KEEPALIVE_PROBES,
2308                             (void *) &(inst->keepalive_probes)) != LDAP_OPT_SUCCESS) {
2309                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2310                 radlog(L_ERR, "  [%s] Could not set LDAP_OPT_X_KEEPALIVE_PROBES %d: %s", inst->xlat_name, inst->keepalive_probes, ldap_err2string(ldap_errno));
2311         }
2312 #endif
2313
2314 #ifdef LDAP_OPT_X_KEEPALIVE_INTERVAL
2315         if (ldap_set_option(ld, LDAP_OPT_X_KEEPALIVE_INTERVAL,
2316                             (void *) &(inst->keepalive_interval)) != LDAP_OPT_SUCCESS) {
2317                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2318                 radlog(L_ERR, "  [%s] Could not set LDAP_OPT_X_KEEPALIVE_INTERVAL %d: %s", inst->xlat_name, inst->keepalive_interval, ldap_err2string(ldap_errno));
2319         }
2320 #endif
2321
2322 #ifdef HAVE_LDAP_START_TLS
2323         if (inst->tls_mode) {
2324                 DEBUG("  [%s] setting TLS mode to %d", inst->xlat_name, inst->tls_mode);
2325                 if (ldap_set_option(ld, LDAP_OPT_X_TLS,
2326                                     (void *) &(inst->tls_mode)) != LDAP_OPT_SUCCESS) {
2327                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2328                         radlog(L_ERR, "  [%s] could not set LDAP_OPT_X_TLS option %s:", inst->xlat_name, ldap_err2string(ldap_errno));
2329                 }
2330         }
2331
2332         if (inst->tls_cacertfile != NULL) {
2333                 DEBUG("  [%s] setting TLS CACert File to %s", inst->xlat_name, inst->tls_cacertfile);
2334
2335                 if ( ldap_set_option( NULL, LDAP_OPT_X_TLS_CACERTFILE,
2336                                       (void *) inst->tls_cacertfile )
2337                      != LDAP_OPT_SUCCESS) {
2338                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2339                         radlog(L_ERR, "  [%s] could not set "
2340                                "LDAP_OPT_X_TLS_CACERTFILE option to %s: %s",
2341                                inst->xlat_name, 
2342                                inst->tls_cacertfile,
2343                                ldap_err2string(ldap_errno));
2344                 }
2345         }
2346
2347         if (inst->tls_cacertdir != NULL) {
2348                 DEBUG("  [%s] setting TLS CACert Directory to %s", inst->xlat_name, inst->tls_cacertdir);
2349
2350                 if ( ldap_set_option( NULL, LDAP_OPT_X_TLS_CACERTDIR,
2351                                       (void *) inst->tls_cacertdir )
2352                      != LDAP_OPT_SUCCESS) {
2353                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2354                         radlog(L_ERR, "  [%s] could not set "
2355                                "LDAP_OPT_X_TLS_CACERTDIR option to %s: %s",
2356                                inst->xlat_name, 
2357                                inst->tls_cacertdir,
2358                                ldap_err2string(ldap_errno));
2359                 }
2360         }
2361
2362         if (strcmp(TLS_DEFAULT_VERIFY, inst->tls_require_cert ) != 0 ) {
2363                 DEBUG("  [%s] setting TLS Require Cert to %s", inst->xlat_name,
2364                       inst->tls_require_cert);
2365         }
2366
2367
2368 #ifdef HAVE_LDAP_INT_TLS_CONFIG
2369         if (ldap_int_tls_config(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT,
2370                                 (inst->tls_require_cert)) != LDAP_OPT_SUCCESS) {
2371                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2372                 radlog(L_ERR, "  [%s] could not set ", 
2373                        "LDAP_OPT_X_TLS_REQUIRE_CERT option to %s: %s",
2374                        inst->xlat_name, 
2375                        inst->tls_require_cert,
2376                        ldap_err2string(ldap_errno));
2377         }
2378 #endif
2379
2380         if (inst->tls_certfile != NULL) {
2381                 DEBUG("  [%s] setting TLS Cert File to %s", inst->xlat_name, inst->tls_certfile);
2382
2383                 if (ldap_set_option(NULL, LDAP_OPT_X_TLS_CERTFILE,
2384                                     (void *) inst->tls_certfile)
2385                     != LDAP_OPT_SUCCESS) {
2386                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2387                         radlog(L_ERR, "  [%s] could not set "
2388                                "LDAP_OPT_X_TLS_CERTFILE option to %s: %s",
2389                                inst->xlat_name, 
2390                                inst->tls_certfile,
2391                                ldap_err2string(ldap_errno));
2392                 }
2393         }
2394
2395         if (inst->tls_keyfile != NULL) {
2396                 DEBUG("  [%s] setting TLS Key File to %s", inst->xlat_name,
2397                       inst->tls_keyfile);
2398
2399                 if ( ldap_set_option( NULL, LDAP_OPT_X_TLS_KEYFILE,
2400                                       (void *) inst->tls_keyfile )
2401                      != LDAP_OPT_SUCCESS) {
2402                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2403                         radlog(L_ERR, "  [%s] could not set "
2404                                "LDAP_OPT_X_TLS_KEYFILE option to %s: %s",
2405                                inst->xlat_name, 
2406                                inst->tls_keyfile, ldap_err2string(ldap_errno));
2407                 }
2408         }
2409
2410         if (inst->tls_randfile != NULL) {
2411                 DEBUG("  [%s] setting TLS Key File to %s", inst->xlat_name,
2412                       inst->tls_randfile);
2413
2414                 if (ldap_set_option(NULL, LDAP_OPT_X_TLS_RANDOM_FILE,
2415                                     (void *) inst->tls_randfile)
2416                     != LDAP_OPT_SUCCESS) {
2417                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2418                         radlog(L_ERR, "  [%s] could not set "
2419                                "LDAP_OPT_X_TLS_RANDOM_FILE option to %s: %s",
2420                                inst->xlat_name,
2421                                inst->tls_randfile, ldap_err2string(ldap_errno));
2422                 }
2423         }
2424
2425         if (inst->start_tls) {
2426                 DEBUG("  [%s] starting TLS", inst->xlat_name);
2427                 rc = ldap_start_tls_s(ld, NULL, NULL);
2428                 if (rc != LDAP_SUCCESS) {
2429                         DEBUG("  [%s] ldap_start_tls_s()", inst->xlat_name);
2430                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER,
2431                                         &ldap_errno);
2432                         radlog(L_ERR, "  [%s] could not start TLS %s", inst->xlat_name,
2433                                ldap_err2string(ldap_errno));
2434                         *result = RLM_MODULE_FAIL;
2435                         ldap_unbind_s(ld);
2436                         exec_trigger(NULL, inst->cs, "modules.ldap.fail", FALSE);
2437                         return (NULL);
2438                 }
2439         }
2440 #endif /* HAVE_LDAP_START_TLS */
2441
2442         if (inst->is_url){
2443                 DEBUG("  [%s] bind as %s/%s to %s", inst->xlat_name,
2444                       dn, password, inst->server);
2445         } else {
2446                 DEBUG("  [%s] bind as %s/%s to %s:%d", inst->xlat_name,
2447                       dn, password, inst->server, inst->port);
2448         }
2449
2450         msgid = ldap_bind(ld, dn, password,LDAP_AUTH_SIMPLE);
2451         if (msgid == -1) {
2452                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2453                 if(err != NULL){
2454                         ldap_get_option(ld, LDAP_OPT_ERROR_STRING, err);
2455                 }
2456                 if (inst->is_url) {
2457                         radlog(L_ERR, "  [%s] %s bind to %s failed: %s", inst->xlat_name,
2458                                 dn, inst->server, ldap_err2string(ldap_errno));
2459                 } else {
2460                         radlog(L_ERR, "  [%s] %s bind to %s:%d failed: %s", inst->xlat_name,
2461                                 dn, inst->server, inst->port,
2462                                 ldap_err2string(ldap_errno));
2463                 }
2464                 *result = RLM_MODULE_FAIL;
2465                 ldap_unbind_s(ld);
2466                 return (NULL);
2467         }
2468         DEBUG("  [%s] waiting for bind result ...", inst->xlat_name);
2469
2470         tv.tv_sec = inst->timeout;
2471         tv.tv_usec = 0;
2472         rc = ldap_result(ld, msgid, 1, &tv, &res);
2473
2474         if (rc < 1) {
2475                 DEBUG("  [%s] ldap_result()", inst->xlat_name);
2476                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2477                 if(err != NULL){
2478                         ldap_get_option(ld, LDAP_OPT_ERROR_STRING, err);
2479                 }
2480                 if (inst->is_url) {
2481                         radlog(L_ERR, "  [%s] %s bind to %s failed: %s", inst->xlat_name,
2482                                 dn, inst->server, (rc == 0) ? "timeout" : ldap_err2string(ldap_errno));
2483                 } else {
2484                         radlog(L_ERR, "  [%s] %s bind to %s:%d failed: %s", inst->xlat_name,
2485                                dn, inst->server, inst->port,
2486                                 (rc == 0) ? "timeout" : ldap_err2string(ldap_errno));
2487                 }
2488                 *result = RLM_MODULE_FAIL;
2489                 ldap_unbind_s(ld);
2490                 return (NULL);
2491         }
2492
2493         ldap_errno = ldap_result2error(ld, res, 1);
2494         switch (ldap_errno) {
2495         case LDAP_SUCCESS:
2496                 DEBUG("  [%s] Bind was successful", inst->xlat_name);
2497                 *result = RLM_MODULE_OK;
2498                 break;
2499
2500         case LDAP_INVALID_CREDENTIALS:
2501                 if (auth){
2502                         DEBUG("  [%s] Bind failed with invalid credentials", inst->xlat_name);
2503                         *result = RLM_MODULE_REJECT;
2504                 } else {
2505                         radlog(L_ERR, "  [%s] LDAP login failed: check identity, password settings in ldap section of radiusd.conf", inst->xlat_name);
2506                         *result = RLM_MODULE_FAIL;
2507                 }
2508                 if(err != NULL){
2509                         ldap_get_option(ld, LDAP_OPT_ERROR_STRING, err);
2510                 }
2511                 break;
2512
2513         case LDAP_CONSTRAINT_VIOLATION:
2514                 DEBUG("rlm_ldap: Bind failed with constraint violation");
2515                 *result = RLM_MODULE_REJECT;
2516                 if(err != NULL){
2517                         ldap_get_option(ld, LDAP_OPT_ERROR_STRING, err);
2518                 }
2519                 break;
2520
2521         default:
2522                 if (inst->is_url) {
2523                         radlog(L_ERR,"  [%s] %s bind to %s failed %s", inst->xlat_name,
2524                                 dn, inst->server, ldap_err2string(ldap_errno));
2525                 } else {
2526                         radlog(L_ERR,"  [%s] %s bind to %s:%d failed %s", inst->xlat_name,
2527                                 dn, inst->server, inst->port,
2528                                 ldap_err2string(ldap_errno));
2529                 }
2530                 *result = RLM_MODULE_FAIL;
2531                 if(err != NULL){
2532                         ldap_get_option(ld, LDAP_OPT_ERROR_STRING, err);
2533                 }
2534         }
2535
2536         if (*result != RLM_MODULE_OK) {
2537                 ldap_unbind_s(ld);
2538                 ld = NULL;
2539         }
2540         return ld;
2541 }
2542
2543 /*****************************************************************************
2544  *
2545  *      Detach from the LDAP server and cleanup internal state.
2546  *
2547  *****************************************************************************/
2548 static int
2549 ldap_detach(void *instance)
2550 {
2551         ldap_instance  *inst = instance;
2552         TLDAP_RADIUS *pair, *nextpair;
2553
2554         if (inst->conns) {
2555                 int i;
2556
2557                 for (i = 0;i < inst->num_conns; i++) {
2558                         if (inst->conns[i].locked) return -1;
2559
2560                         if (inst->conns[i].ld){
2561                                 ldap_unbind_s(inst->conns[i].ld);
2562                         }
2563                         pthread_mutex_destroy(&inst->conns[i].mutex);
2564                 }
2565                 free(inst->conns);
2566         }
2567
2568 #ifdef NOVELL
2569         if (inst->apc_conns){
2570                 int i;
2571
2572                 for (i = 0; i < inst->num_conns; i++) {
2573                         if (inst->apc_conns[i].locked) return -1;
2574
2575                         if (inst->apc_conns[i].ld){
2576                                 ldap_unbind_s(inst->apc_conns[i].ld);
2577                         }
2578                         pthread_mutex_destroy(&inst->apc_conns[i].mutex);
2579                 }
2580                 free(inst->apc_conns);
2581         }
2582 #endif
2583
2584         pair = inst->check_item_map;
2585
2586         while (pair != NULL) {
2587                 nextpair = pair->next;
2588                 free(pair->attr);
2589                 free(pair->radius_attr);
2590                 free(pair);
2591                 pair = nextpair;
2592         }
2593
2594         pair = inst->reply_item_map;
2595
2596         while (pair != NULL) {
2597                 nextpair = pair->next;
2598                 free(pair->attr);
2599                 free(pair->radius_attr);
2600                 free(pair);
2601                 pair = nextpair;
2602         }
2603
2604         if (inst->atts)
2605                 free(inst->atts);
2606
2607         paircompare_unregister(PW_LDAP_GROUP, ldap_groupcmp);
2608         xlat_unregister(inst->xlat_name,ldap_xlat, instance);
2609         free(inst->xlat_name);
2610
2611         free(inst);
2612
2613         return 0;
2614 }
2615
2616
2617 #ifdef FIELDCPY
2618 static void
2619 fieldcpy(char *string, char **uptr)
2620 {
2621         char           *ptr;
2622
2623         ptr = *uptr;
2624         while (*ptr == ' ' || *ptr == '\t') {
2625                 ptr++;
2626         }
2627         if (*ptr == '"') {
2628                 ptr++;
2629                 while (*ptr != '"' && *ptr != '\0' && *ptr != '\n') {
2630                         *string++ = *ptr++;
2631                 }
2632                 *string = '\0';
2633                 if (*ptr == '"') {
2634                         ptr++;
2635                 }
2636                 *uptr = ptr;
2637                 return;
2638         }
2639         while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0' && *ptr != '\n' &&
2640                *ptr != '=' && *ptr != ',') {
2641                 *string++ = *ptr++;
2642         }
2643         *string = '\0';
2644         *uptr = ptr;
2645         return;
2646 }
2647 #endif
2648
2649 /*
2650  *      Copied from src/lib/token.c
2651  */
2652 static const FR_NAME_NUMBER tokens[] = {
2653         { "=~", T_OP_REG_EQ,    }, /* order is important! */
2654         { "!~", T_OP_REG_NE,    },
2655         { "{",  T_LCBRACE,      },
2656         { "}",  T_RCBRACE,      },
2657         { "(",  T_LBRACE,       },
2658         { ")",  T_RBRACE,       },
2659         { ",",  T_COMMA,        },
2660         { "+=", T_OP_ADD,       },
2661         { "-=", T_OP_SUB,       },
2662         { ":=", T_OP_SET,       },
2663         { "=*", T_OP_CMP_TRUE,  },
2664         { "!*", T_OP_CMP_FALSE, },
2665         { "==", T_OP_CMP_EQ,    },
2666         { "=",  T_OP_EQ,        },
2667         { "!=", T_OP_NE,        },
2668         { ">=", T_OP_GE,        },
2669         { ">",  T_OP_GT,        },
2670         { "<=", T_OP_LE,        },
2671         { "<",  T_OP_LT,        },
2672         { NULL, 0}
2673 };
2674
2675 /*****************************************************************************
2676  *      Get RADIUS attributes from LDAP object
2677  *      ( according to draft-adoba-radius-05.txt
2678  *        <http://www.ietf.org/internet-drafts/draft-adoba-radius-05.txt> )
2679  *
2680  *****************************************************************************/
2681 static VALUE_PAIR *ldap_pairget(LDAP *ld, LDAPMessage *entry,
2682                                 TLDAP_RADIUS *item_map,
2683                                 VALUE_PAIR **pairs, int is_check,
2684                                 ldap_instance *inst)
2685 {
2686         char          **vals;
2687         int             vals_count;
2688         int             vals_idx;
2689         const char      *ptr;
2690         const char     *value;
2691         TLDAP_RADIUS   *element;
2692         FR_TOKEN      token, operator;
2693         int             is_generic_attribute;
2694         char            buf[MAX_STRING_LEN];
2695         VALUE_PAIR     *pairlist = NULL;
2696         VALUE_PAIR     *newpair = NULL;
2697         char            do_xlat = FALSE;
2698         char            print_buffer[2048];
2699
2700         /*
2701          *      check if there is a mapping from this LDAP attribute
2702          *      to a RADIUS attribute
2703          */
2704         for (element = item_map; element != NULL; element = element->next) {
2705                 /*
2706                  *      No mapping, skip it.
2707                  */
2708                 if ((vals = ldap_get_values(ld,entry,element->attr)) == NULL)
2709                         continue;
2710
2711                 /*
2712                  *      Check whether this is a one-to-one-mapped ldap
2713                  *      attribute or a generic attribute and set flag
2714                  *      accordingly.
2715                  */
2716                 if (strcasecmp(element->radius_attr, GENERIC_ATTRIBUTE_ID)==0)
2717                         is_generic_attribute = 1;
2718                 else
2719                         is_generic_attribute = 0;
2720
2721                 /*
2722                  *      Find out how many values there are for the
2723                  *      attribute and extract all of them.
2724                  */
2725                 vals_count = ldap_count_values(vals);
2726
2727                 for (vals_idx = 0; vals_idx < vals_count; vals_idx++) {
2728                         value = vals[vals_idx];
2729
2730                         if (is_generic_attribute) {
2731                                 /*
2732                                  *      This is a generic attribute.
2733                                  */
2734                                 FR_TOKEN dummy; /* makes pairread happy */
2735
2736                                 /* not sure if using pairread here is ok ... */
2737                                 if ( (newpair = pairread(&value, &dummy)) != NULL) {
2738                                         DEBUG("  [%s] extracted attribute %s from generic item %s", inst->xlat_name,
2739                                               newpair->name, vals[vals_idx]);
2740                                         pairadd(&pairlist, newpair);
2741                                 } else {
2742                                         radlog(L_ERR, "  [%s] parsing %s failed: %s", inst->xlat_name,
2743                                                element->attr, vals[vals_idx]);
2744                                 }
2745                         } else {
2746                                 /*
2747                                  *      This is a one-to-one-mapped attribute
2748                                  */
2749                                 ptr = value;
2750                                 operator = gettoken(&ptr, buf, sizeof(buf));
2751                                 if (operator < T_EQSTART || operator > T_EQEND) {
2752                                         /* no leading operator found */
2753                                         if (element->operator != T_OP_INVALID)
2754                                                 operator = element->operator;
2755                                         else if (is_check)
2756                                                 operator = T_OP_CMP_EQ;
2757                                         else
2758                                                 operator = T_OP_EQ;
2759                                 } else {
2760                                         /* the value is after the operator */
2761                                         value = ptr;
2762                                 }
2763
2764                                 /*
2765                                  *      Do xlat if the *entire* string
2766                                  *      is quoted.
2767                                  */
2768                                 if ((value[0] == '\'' || value[0] == '"' ||
2769                                      value[0] == '`') &&
2770                                     (value[0] == value[strlen(value)-1])) {
2771                                         ptr = value;
2772                                         token = gettoken(&ptr, buf, sizeof(buf));
2773                                         switch (token) {
2774                                         /* take the unquoted string */
2775                                         case T_SINGLE_QUOTED_STRING:
2776                                         case T_DOUBLE_QUOTED_STRING:
2777                                                 value = buf;
2778                                                 break;
2779
2780                                         /* the value will be xlat'ed later */
2781                                         case T_BACK_QUOTED_STRING:
2782                                                 value = buf;
2783                                                 do_xlat = TRUE;
2784                                                 break;
2785
2786                                         /* keep the original string */
2787                                         default:
2788                                                 break;
2789                                         }
2790                                 }
2791                                 if (value[0] == '\0') {
2792                                         DEBUG("  [%s] Attribute %s has no value", inst->xlat_name, element->attr);
2793                                         continue;
2794                                 }
2795
2796                                 /*
2797                                  *      Create the pair.
2798                                  */
2799                                 if (do_xlat) {
2800                                         newpair = pairmake_xlat(element->radius_attr,
2801                                                                 value,
2802                                                                 operator);
2803                                 } else {
2804                                         newpair = pairmake(element->radius_attr,
2805                                                            value,
2806                                                            operator);
2807                                 }
2808                                 if (newpair == NULL) {
2809                                         radlog(L_ERR, "  [%s] Failed to create the pair: %s", inst->xlat_name, fr_strerror());
2810                                         continue;
2811                                 }
2812
2813                                 vp_prints(print_buffer, sizeof(print_buffer),
2814                                           newpair);
2815                                 DEBUG("  [%s] %s -> %s", inst->xlat_name,
2816                                       element->attr, print_buffer);
2817
2818
2819                                 /*
2820                                  *      Add the pair into the packet.
2821                                  */
2822                                 if (!vals_idx){
2823                                   pairdelete(pairs, newpair->attribute, newpair->vendor);
2824                                 }
2825                                 pairadd(&pairlist, newpair);
2826                         }
2827                 }
2828                 ldap_value_free(vals);
2829         }
2830
2831         return (pairlist);
2832 }
2833
2834 /* globally exported name */
2835 module_t rlm_ldap = {
2836         RLM_MODULE_INIT,
2837         "LDAP",
2838         RLM_TYPE_THREAD_SAFE,   /* type: reserved        */
2839         ldap_instantiate,       /* instantiation         */
2840         ldap_detach,            /* detach                */
2841         {
2842                 ldap_authenticate,      /* authentication        */
2843                 ldap_authorize,         /* authorization         */
2844                 NULL,                   /* preaccounting         */
2845                 NULL,                   /* accounting            */
2846                 NULL,                   /* checksimul            */
2847                 NULL,                   /* pre-proxy             */
2848                 NULL,                   /* post-proxy            */
2849 #ifdef NOVELL
2850                 ldap_postauth           /* post-auth             */
2851 #else
2852                 NULL
2853 #endif
2854         },
2855 };