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