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