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