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