Print more descriptive error messages
[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         ldap_errno = ldap_count_entries(conn->ld, *result);
850         if (ldap_errno != 1) {
851                 if (ldap_errno == 0) {
852                         DEBUG("rlm_ldap: object not found");
853                 } else {
854                         DEBUG("rlm_ldap: got ambiguous search result (%d results)", ldap_errno);
855                 }
856                 res = RLM_MODULE_NOTFOUND;
857                 ldap_msgfree(*result);
858         }
859         return res;
860 }
861
862
863 /*
864  *      Translate the LDAP queries.
865  */
866 static size_t ldap_escape_func(char *out, size_t outlen, const char *in)
867 {
868         size_t len = 0;
869
870         while (in[0]) {
871                 /*
872                  *      Encode unsafe characters.
873                  */
874                 if (((len == 0) &&
875                     ((in[0] == ' ') || (in[0] == '#'))) ||
876                     (strchr(",+\"\\<>;*=()", *in))) {
877                         static const char hex[] = "0123456789abcdef";
878
879                         /*
880                          *      Only 3 or less bytes available.
881                          */
882                         if (outlen <= 3) {
883                                 break;
884                         }
885
886                         *(out++) = '\\';
887                         *(out++) = hex[((*in) >> 4) & 0x0f];
888                         *(out++) = hex[(*in) & 0x0f];
889                         outlen -= 3;
890                         len += 3;
891                         in++;
892                         continue;
893                 }
894
895                 /*
896                  *      Only one byte left.
897                  */
898                 if (outlen <= 1) {
899                         break;
900                 }
901
902                 /*
903                  *      Allowed character.
904                  */
905                 *(out++) = *(in++);
906                 outlen--;
907                 len++;
908         }
909         *out = '\0';
910         return len;
911 }
912
913 /*
914  *      ldap_groupcmp(). Implement the Ldap-Group == "group" filter
915  */
916 static int ldap_groupcmp(void *instance, REQUEST *req,
917                          UNUSED VALUE_PAIR *request, VALUE_PAIR *check,
918                          UNUSED VALUE_PAIR *check_pairs,
919                          UNUSED VALUE_PAIR **reply_pairs)
920 {
921         char            filter[MAX_FILTER_STR_LEN];
922         char            gr_filter[MAX_FILTER_STR_LEN];
923         int             res;
924         LDAPMessage     *result = NULL;
925         LDAPMessage     *msg = NULL;
926         char            basedn[MAX_FILTER_STR_LEN];
927         char            *attrs[] = {"dn",NULL};
928         char            **vals;
929         ldap_instance   *inst = instance;
930         char            *group_attrs[] = {inst->groupmemb_attr,NULL};
931         LDAP_CONN       *conn;
932         int             conn_id = -1;
933         VALUE_PAIR      *vp_user_dn;
934         VALUE_PAIR      **request_pairs;
935
936         request_pairs = &req->config_items;
937
938         DEBUG("rlm_ldap: Entering ldap_groupcmp()");
939
940         if (check->vp_strvalue == NULL || check->length == 0){
941                 DEBUG("rlm_ldap::ldap_groupcmp: Illegal group name");
942                 return 1;
943         }
944
945         if (req == NULL){
946                 DEBUG("rlm_ldap::ldap_groupcmp: NULL request");
947                 return 1;
948         }
949
950         if (!radius_xlat(basedn, sizeof(basedn), inst->basedn, req, ldap_escape_func)) {
951                 DEBUG("rlm_ldap::ldap_groupcmp: unable to create basedn.");
952                 return 1;
953         }
954
955         while((vp_user_dn = pairfind(*request_pairs, PW_LDAP_USERDN)) == NULL){
956                 char            *user_dn = NULL;
957
958                 if (!radius_xlat(filter, sizeof(filter), inst->filter,
959                                         req, ldap_escape_func)){
960                         DEBUG("rlm_ldap::ldap_groupcmp: unable to create filter");
961                         return 1;
962                 }
963                 if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
964                         radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
965                         return 1;
966                 }
967                 if ((res = perform_search(inst, conn, basedn, LDAP_SCOPE_SUBTREE,
968                                         filter, attrs, &result)) != RLM_MODULE_OK){
969                         DEBUG("rlm_ldap::ldap_groupcmp: search failed");
970                         ldap_release_conn(conn_id,inst->conns);
971                         return 1;
972                 }
973                 if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
974                         DEBUG("rlm_ldap::ldap_groupcmp: ldap_first_entry() failed");
975                         ldap_release_conn(conn_id,inst->conns);
976                         ldap_msgfree(result);
977                         return 1;
978                 }
979                 if ((user_dn = ldap_get_dn(conn->ld, msg)) == NULL) {
980                         DEBUG("rlm_ldap:ldap_groupcmp:: ldap_get_dn() failed");
981                         ldap_release_conn(conn_id,inst->conns);
982                         ldap_msgfree(result);
983                         return 1;
984                 }
985                 ldap_release_conn(conn_id,inst->conns);
986
987                 /*
988                  *      Adding new attribute containing DN for LDAP
989                  *      object associated with given username
990                  */
991                 pairadd(request_pairs, pairmake("Ldap-UserDn", user_dn,
992                                                 T_OP_EQ));
993                 ldap_memfree(user_dn);
994                 ldap_msgfree(result);
995         }
996
997         if(!radius_xlat(gr_filter, sizeof(gr_filter),
998                         inst->groupmemb_filt, req, ldap_escape_func)) {
999                 DEBUG("rlm_ldap::ldap_groupcmp: unable to create filter.");
1000                 return 1;
1001         }
1002
1003         if (strchr((char *)check->vp_strvalue,',') != NULL) {
1004                 /* This looks like a DN */
1005                 snprintf(filter,sizeof(filter), "%s",gr_filter);
1006                 snprintf(basedn,sizeof(basedn), "%s",(char *)check->vp_strvalue);
1007         } else
1008                 snprintf(filter,sizeof(filter), "(&(%s=%s)%s)",
1009                          inst->groupname_attr,
1010                          (char *)check->vp_strvalue,gr_filter);
1011
1012         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1) {
1013                 radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
1014                 return 1;
1015         }
1016
1017         if ((res = perform_search(inst, conn, basedn, LDAP_SCOPE_SUBTREE,
1018                                 filter, attrs, &result)) == RLM_MODULE_OK) {
1019                 DEBUG("rlm_ldap::ldap_groupcmp: User found in group %s",
1020                                 (char *)check->vp_strvalue);
1021                 ldap_msgfree(result);
1022                 ldap_release_conn(conn_id,inst->conns);
1023                 return 0;
1024         }
1025
1026         ldap_release_conn(conn_id,inst->conns);
1027
1028         if (res != RLM_MODULE_NOTFOUND ) {
1029                 DEBUG("rlm_ldap::ldap_groupcmp: Search returned error");
1030                 return 1;
1031         }
1032
1033         if (inst->groupmemb_attr == NULL){
1034                 /*
1035                  *      Search returned NOTFOUND and searching for
1036                  *      membership using user object attributes is not
1037                  *      specified in config file
1038                  */
1039                 DEBUG("rlm_ldap::ldap_groupcmp: Group %s not found or user is not a member.",(char *)check->vp_strvalue);
1040                 return 1;
1041         }
1042
1043         snprintf(filter,sizeof(filter), "(objectclass=*)");
1044         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
1045                 radlog(L_ERR, "rlm_ldap: Add ldap connections are in use");
1046                 return 1;
1047         }
1048         if ((res = perform_search(inst, conn, vp_user_dn->vp_strvalue,
1049                                   LDAP_SCOPE_BASE, filter, group_attrs,
1050                                   &result)) != RLM_MODULE_OK) {
1051                 DEBUG("rlm_ldap::ldap_groupcmp: Search returned error");
1052                 ldap_release_conn(conn_id, inst->conns);
1053                 return 1;
1054         }
1055
1056         if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
1057                 DEBUG("rlm_ldap::ldap_groupcmp: ldap_first_entry() failed");
1058                 ldap_release_conn(conn_id,inst->conns);
1059                 ldap_msgfree(result);
1060                 return 1;
1061         }
1062         if ((vals = ldap_get_values(conn->ld, msg,
1063                                     inst->groupmemb_attr)) != NULL) {
1064                 int i = 0;
1065                 char found = 0;
1066
1067                 for (;i < ldap_count_values(vals);i++){
1068                         if (strchr(vals[i],',') != NULL){
1069                                 /* This looks like a DN */
1070                                 LDAPMessage *gr_result = NULL;
1071                                 snprintf(filter,sizeof(filter), "(%s=%s)",
1072                                         inst->groupname_attr,
1073                                         (char *)check->vp_strvalue);
1074                                 if ((res = perform_search(inst, conn, vals[i],
1075                                                 LDAP_SCOPE_BASE, filter,
1076                                                 attrs, &gr_result)) != RLM_MODULE_OK){
1077                                         if (res != RLM_MODULE_NOTFOUND) {
1078                                                 DEBUG("rlm_ldap::ldap_groupcmp: Search returned error");
1079                                                 ldap_value_free(vals);
1080                                                 ldap_msgfree(result);
1081                                                 ldap_release_conn(conn_id,inst->conns);
1082                                                 return 1;
1083                                         }
1084                                 } else {
1085                                         ldap_msgfree(gr_result);
1086                                         found = 1;
1087                                         break;
1088                                 }
1089                         } else {
1090                                 if (strcmp(vals[i],(char *)check->vp_strvalue) == 0){
1091                                         found = 1;
1092                                         break;
1093                                 }
1094                         }
1095                 }
1096                 ldap_value_free(vals);
1097                 ldap_msgfree(result);
1098                 if (found == 0){
1099                         DEBUG("rlm_ldap::groupcmp: Group %s not found or user not a member",
1100                                 (char *)check->vp_strvalue);
1101                         ldap_release_conn(conn_id,inst->conns);
1102                         return 1;
1103                 }
1104         } else {
1105                         DEBUG("rlm_ldap::ldap_groupcmp: ldap_get_values() failed");
1106                         ldap_msgfree(result);
1107                         ldap_release_conn(conn_id,inst->conns);
1108                         return 1;
1109         }
1110
1111         DEBUG("rlm_ldap::ldap_groupcmp: User found in group %s",(char *)check->vp_strvalue);
1112         ldap_release_conn(conn_id,inst->conns);
1113
1114         return 0;
1115 }
1116
1117 /*
1118  * ldap_xlat()
1119  * Do an xlat on an LDAP URL
1120  */
1121 static size_t ldap_xlat(void *instance, REQUEST *request, char *fmt,
1122                      char *out, size_t freespace, RADIUS_ESCAPE_STRING func)
1123 {
1124         char url[MAX_FILTER_STR_LEN];
1125         int res;
1126         size_t ret = 0;
1127         ldap_instance *inst = instance;
1128         LDAPURLDesc *ldap_url;
1129         LDAPMessage *result = NULL;
1130         LDAPMessage *msg = NULL;
1131         char **vals;
1132         int conn_id = -1;
1133         LDAP_CONN *conn;
1134
1135         DEBUG("rlm_ldap: - ldap_xlat");
1136         if (!radius_xlat(url, sizeof(url), fmt, request, func)) {
1137                 radlog (L_ERR, "rlm_ldap: Unable to create LDAP URL.\n");
1138                 return 0;
1139         }
1140         if (!ldap_is_ldap_url(url)){
1141                 radlog (L_ERR, "rlm_ldap: String passed does not look like an LDAP URL.\n");
1142                 return 0;
1143         }
1144         if (ldap_url_parse(url,&ldap_url)){
1145                 radlog (L_ERR, "rlm_ldap: LDAP URL parse failed.\n");
1146                 return 0;
1147         }
1148         if (ldap_url->lud_attrs == NULL || ldap_url->lud_attrs[0] == NULL ||
1149             ( ldap_url->lud_attrs[1] != NULL ||
1150               ( ! strlen(ldap_url->lud_attrs[0]) ||
1151                 ! strcmp(ldap_url->lud_attrs[0],"*") ) ) ){
1152                 radlog (L_ERR, "rlm_ldap: Invalid Attribute(s) request.\n");
1153                 ldap_free_urldesc(ldap_url);
1154                 return 0;
1155         }
1156         if (ldap_url->lud_host){
1157                 if (strncmp(inst->server,ldap_url->lud_host,
1158                             strlen(inst->server)) != 0 ||
1159                     ldap_url->lud_port != inst->port) {
1160                         DEBUG("rlm_ldap: Requested server/port is not known to this module instance.");
1161                         ldap_free_urldesc(ldap_url);
1162                         return 0;
1163                 }
1164         }
1165         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
1166                 radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
1167                 ldap_free_urldesc(ldap_url);
1168                 return 0;
1169         }
1170         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){
1171                 if (res == RLM_MODULE_NOTFOUND){
1172                         DEBUG("rlm_ldap: Search returned not found");
1173                         ldap_free_urldesc(ldap_url);
1174                         ldap_release_conn(conn_id,inst->conns);
1175                         return 0;
1176                 }
1177                 DEBUG("rlm_ldap: Search returned error");
1178                 ldap_free_urldesc(ldap_url);
1179                 ldap_release_conn(conn_id,inst->conns);
1180                 return 0;
1181         }
1182         if ((msg = ldap_first_entry(conn->ld, result)) == NULL){
1183                 DEBUG("rlm_ldap: ldap_first_entry() failed");
1184                 ldap_msgfree(result);
1185                 ldap_free_urldesc(ldap_url);
1186                 ldap_release_conn(conn_id,inst->conns);
1187                 return 0;
1188         }
1189         if ((vals = ldap_get_values(conn->ld, msg, ldap_url->lud_attrs[0])) != NULL) {
1190                 ret = strlen(vals[0]);
1191                 if (ret >= freespace){
1192                         DEBUG("rlm_ldap: Insufficient string space");
1193                         ldap_free_urldesc(ldap_url);
1194                         ldap_value_free(vals);
1195                         ldap_msgfree(result);
1196                         ldap_release_conn(conn_id,inst->conns);
1197                         return 0;
1198                 }
1199                 DEBUG("rlm_ldap: Adding attribute %s, value: %s",ldap_url->lud_attrs[0],vals[0]);
1200                 strlcpy(out,vals[0],freespace);
1201                 ldap_value_free(vals);
1202         }
1203         else
1204                 ret = 0;
1205
1206         ldap_msgfree(result);
1207         ldap_free_urldesc(ldap_url);
1208         ldap_release_conn(conn_id,inst->conns);
1209
1210         DEBUG("rlm_ldap: - ldap_xlat end");
1211
1212         return ret;
1213 }
1214
1215
1216 /*
1217  *      For auto-header discovery.
1218  */
1219 static const FR_NAME_NUMBER header_names[] = {
1220         { "{clear}",    PW_CLEARTEXT_PASSWORD },
1221         { "{cleartext}", PW_CLEARTEXT_PASSWORD },
1222         { "{md5}",      PW_MD5_PASSWORD },
1223         { "{smd5}",     PW_SMD5_PASSWORD },
1224         { "{crypt}",    PW_CRYPT_PASSWORD },
1225         { "{sha}",      PW_SHA_PASSWORD },
1226         { "{ssha}",     PW_SSHA_PASSWORD },
1227         { "{nt}",       PW_NT_PASSWORD },
1228         { "{ns-mta-md5}", PW_NS_MTA_MD5_PASSWORD },
1229         { NULL, 0 }
1230 };
1231
1232
1233 /******************************************************************************
1234  *
1235  *      Function: rlm_ldap_authorize
1236  *
1237  *      Purpose: Check if user is authorized for remote access
1238  *
1239  ******************************************************************************/
1240 static int ldap_authorize(void *instance, REQUEST * request)
1241 {
1242         LDAPMessage     *result = NULL;
1243         LDAPMessage     *msg = NULL;
1244         LDAPMessage     *def_msg = NULL;
1245         LDAPMessage     *def_attr_msg = NULL;
1246         LDAPMessage     *def_result = NULL;
1247         LDAPMessage     *def_attr_result = NULL;
1248         ldap_instance   *inst = instance;
1249         char            *user_dn = NULL;
1250         char            filter[MAX_FILTER_STR_LEN];
1251         char            basedn[MAX_FILTER_STR_LEN];
1252         VALUE_PAIR      *check_tmp;
1253         VALUE_PAIR      *reply_tmp;
1254         int             res;
1255         VALUE_PAIR      **check_pairs, **reply_pairs;
1256         char            **vals;
1257         VALUE_PAIR      *module_fmsg_vp;
1258         VALUE_PAIR      *user_profile;
1259         char            module_fmsg[MAX_STRING_LEN];
1260         LDAP_CONN       *conn;
1261         int             conn_id = -1;
1262         int             added_known_password = 0;
1263
1264         if (!request->username){
1265                 RDEBUG2("Attribute \"User-Name\" is required for authorization.\n");
1266                 return RLM_MODULE_NOOP;
1267         }
1268
1269         check_pairs = &request->config_items;
1270         reply_pairs = &request->reply->vps;
1271
1272         /*
1273          * Check for valid input, zero length names not permitted
1274          */
1275         if (request->username->vp_strvalue == 0) {
1276                 DEBUG2("zero length username not permitted\n");
1277                 return RLM_MODULE_INVALID;
1278         }
1279         RDEBUG("performing user authorization for %s",
1280                request->username->vp_strvalue);
1281
1282         if (!radius_xlat(filter, sizeof(filter), inst->filter,
1283                          request, ldap_escape_func)) {
1284                 radlog(L_ERR, "rlm_ldap: unable to create filter.\n");
1285                 return RLM_MODULE_INVALID;
1286         }
1287
1288         if (!radius_xlat(basedn, sizeof(basedn), inst->basedn,
1289                          request, ldap_escape_func)) {
1290                 radlog(L_ERR, "rlm_ldap: unable to create basedn.\n");
1291                 return RLM_MODULE_INVALID;
1292         }
1293
1294         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
1295                 radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
1296                 return RLM_MODULE_FAIL;
1297         }
1298         if ((res = perform_search(instance, conn, basedn, LDAP_SCOPE_SUBTREE, filter, inst->atts, &result)) != RLM_MODULE_OK) {
1299                 RDEBUG("search failed");
1300                 if (res == RLM_MODULE_NOTFOUND){
1301                         snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: User not found");
1302                         module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1303                         pairadd(&request->packet->vps, module_fmsg_vp);
1304                 }
1305                 ldap_release_conn(conn_id,inst->conns);
1306                 return (res);
1307         }
1308         if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
1309                 RDEBUG("ldap_first_entry() failed");
1310                 ldap_msgfree(result);
1311                 ldap_release_conn(conn_id,inst->conns);
1312                 return RLM_MODULE_FAIL;
1313         }
1314         if ((user_dn = ldap_get_dn(conn->ld, msg)) == NULL) {
1315                 RDEBUG("ldap_get_dn() failed");
1316                 ldap_msgfree(result);
1317                 ldap_release_conn(conn_id,inst->conns);
1318                 return RLM_MODULE_FAIL;
1319         }
1320         /*
1321          * Adding new attribute containing DN for LDAP object associated with
1322          * given username
1323          */
1324         pairadd(check_pairs, pairmake("Ldap-UserDn", user_dn, T_OP_EQ));
1325         ldap_memfree(user_dn);
1326
1327
1328         /* Remote access is controled by attribute of the user object */
1329         if (inst->access_attr) {
1330                 if ((vals = ldap_get_values(conn->ld, msg, inst->access_attr)) != NULL) {
1331                         if (inst->default_allow){
1332                                 RDEBUG("checking if remote access for %s is allowed by %s", request->username->vp_strvalue, inst->access_attr);
1333                                 if (!strncmp(vals[0], "FALSE", 5)) {
1334                                         RDEBUG("dialup access disabled");
1335                                         snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Access Attribute denies access");
1336                                         module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1337                                         pairadd(&request->packet->vps, module_fmsg_vp);
1338                                         ldap_msgfree(result);
1339                                         ldap_value_free(vals);
1340                                         ldap_release_conn(conn_id,inst->conns);
1341                                         return RLM_MODULE_USERLOCK;
1342                                 }
1343                                 ldap_value_free(vals);
1344                         }
1345                         else{
1346                                 RDEBUG("%s attribute exists - access denied by default", inst->access_attr);
1347                                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Access Attribute denies access");
1348                                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1349                                 pairadd(&request->packet->vps, module_fmsg_vp);
1350                                 ldap_msgfree(result);
1351                                 ldap_value_free(vals);
1352                                 ldap_release_conn(conn_id,inst->conns);
1353                                 return RLM_MODULE_USERLOCK;
1354                         }
1355                 } else {
1356                         if (inst->default_allow){
1357                                 RDEBUG("no %s attribute - access denied by default", inst->access_attr);
1358                                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Access Attribute denies access");
1359                                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1360                                 pairadd(&request->packet->vps, module_fmsg_vp);
1361                                 ldap_msgfree(result);
1362                                 ldap_release_conn(conn_id,inst->conns);
1363                                 return RLM_MODULE_USERLOCK;
1364                         }
1365                 }
1366         }
1367
1368         /*
1369          * Check for the default profile entry. If it exists then add the
1370          * attributes it contains in the check and reply pairs
1371          */
1372
1373         user_profile = pairfind(request->config_items, PW_USER_PROFILE);
1374         if (inst->default_profile || user_profile){
1375                 char *profile = inst->default_profile;
1376
1377                 strlcpy(filter,inst->base_filter,sizeof(filter));
1378                 if (user_profile)
1379                         profile = user_profile->vp_strvalue;
1380                 if (profile && strlen(profile)){
1381                         if ((res = perform_search(instance, conn,
1382                                 profile, LDAP_SCOPE_BASE,
1383                                 filter, inst->atts, &def_result)) == RLM_MODULE_OK){
1384                                 if ((def_msg = ldap_first_entry(conn->ld,def_result))){
1385                                         if ((check_tmp = ldap_pairget(conn->ld,def_msg,inst->check_item_map,check_pairs,1))) {
1386                                                 if (inst->do_xlat){
1387                                                         pairxlatmove(request, check_pairs, &check_tmp);
1388                                                         pairfree(&check_tmp);
1389                                                 }
1390                                                 else
1391                                                         pairadd(check_pairs,check_tmp);
1392                                         }
1393                                         if ((reply_tmp = ldap_pairget(conn->ld,def_msg,inst->reply_item_map,reply_pairs,0))) {
1394                                                 if (inst->do_xlat){
1395                                                         pairxlatmove(request, reply_pairs, &reply_tmp);
1396                                                         pairfree(&reply_tmp);
1397                                                 }
1398                                                 else
1399                                                         pairadd(reply_pairs,reply_tmp);
1400                                         }
1401                                 }
1402                                 ldap_msgfree(def_result);
1403                         } else
1404                                 RDEBUG("default_profile/user-profile search failed");
1405                 }
1406         }
1407
1408         /*
1409          * Check for the profile attribute. If it exists, we assume that it
1410          * contains the DN of an entry containg a profile for the user. That
1411          * way we can have different general profiles for various user groups
1412          * (students,faculty,staff etc)
1413          */
1414
1415         if (inst->profile_attr){
1416                 if ((vals = ldap_get_values(conn->ld, msg, inst->profile_attr)) != NULL) {
1417                         unsigned int i=0;
1418                         strlcpy(filter,inst->base_filter,sizeof(filter));
1419                         while(vals[i] != NULL && strlen(vals[i])){
1420                                 if ((res = perform_search(instance, conn,
1421                                         vals[i], LDAP_SCOPE_BASE,
1422                                         filter, inst->atts, &def_attr_result)) == RLM_MODULE_OK){
1423                                         if ((def_attr_msg = ldap_first_entry(conn->ld,def_attr_result))){
1424                                                 if ((check_tmp = ldap_pairget(conn->ld,def_attr_msg,inst->check_item_map,check_pairs,1))) {
1425                                                         if (inst->do_xlat){
1426                                                                 pairxlatmove(request, check_pairs, &check_tmp);
1427                                                                 pairfree(&check_tmp);
1428                                                         }
1429                                                         else
1430                                                                 pairadd(check_pairs,check_tmp);
1431                                                 }
1432                                                 if ((reply_tmp = ldap_pairget(conn->ld,def_attr_msg,inst->reply_item_map,reply_pairs,0))) {
1433                                                         if (inst->do_xlat){
1434                                                                 pairxlatmove(request, reply_pairs, &reply_tmp);
1435                                                                 pairfree(&reply_tmp);
1436                                                         }
1437                                                         else
1438                                                                 pairadd(reply_pairs,reply_tmp);
1439                                                 }
1440                                         }
1441                                         ldap_msgfree(def_attr_result);
1442                                 } else
1443                                         RDEBUG("profile_attribute search failed");
1444                                 i++;
1445                         }
1446                         ldap_value_free(vals);
1447                 }
1448         }
1449         if (inst->passwd_attr && strlen(inst->passwd_attr)) {
1450 #ifdef NOVELL_UNIVERSAL_PASSWORD
1451                 if (strcasecmp(inst->passwd_attr,"nspmPassword") != 0) {
1452 #endif
1453                         VALUE_PAIR *passwd_item;
1454                         char **passwd_vals;
1455                         char *value = NULL;
1456                         int i;
1457
1458                         /*
1459                          *      Read the password from the DB, and
1460                          *      add it to the request.
1461                          */
1462                         passwd_vals = ldap_get_values(conn->ld,msg,
1463                                                       inst->passwd_attr);
1464
1465                         /*
1466                          *      Loop over what we received, and parse it.
1467                          */
1468                         if (passwd_vals) for (i = 0;
1469                                               passwd_vals[i] != NULL;
1470                                               i++) {
1471                                 int attr = PW_USER_PASSWORD;
1472
1473                                 if (strlen(passwd_vals[i]) == 0)
1474                                         continue;
1475
1476                                 value = passwd_vals[i];
1477
1478                                 if (inst->auto_header) {
1479                                         char *p;
1480                                         char autobuf[16];
1481
1482                                         p = strchr(value, '}');
1483                                         if (!p) continue;
1484                                         if ((size_t)(p - value + 1) >= sizeof(autobuf))
1485                                                 continue; /* paranoia */
1486                                         memcpy(autobuf, value, p - value + 1);
1487                                         autobuf[p - value + 1] = '\0';
1488
1489                                         attr = fr_str2int(header_names,
1490                                                             autobuf, 0);
1491                                         if (!attr) continue;
1492                                         value = p + 1;
1493                                         goto create_attr;
1494
1495                                 } else if (inst->passwd_hdr &&
1496                                            strlen(inst->passwd_hdr)) {
1497                                         if (strncasecmp(value,
1498                                                         inst->passwd_hdr,
1499                                                         strlen(inst->passwd_hdr)) == 0) {
1500                                                 value += strlen(inst->passwd_hdr);
1501                                         } else {
1502                                                 RDEBUG("Password header not found in password %s for user %s", passwd_vals[0], request->username->vp_strvalue);
1503                                         }
1504                                 }
1505                                 if (!value) continue;
1506
1507                         create_attr:
1508                                 passwd_item = radius_paircreate(request,
1509                                                                 &request->config_items,
1510                                                                 attr,
1511                                                                 PW_TYPE_STRING);
1512                                 strlcpy(passwd_item->vp_strvalue, value,
1513                                         sizeof(passwd_item->vp_strvalue));
1514                                 passwd_item->length = strlen(passwd_item->vp_strvalue);
1515                                 RDEBUG("Added %s = %s in check items",
1516                                       passwd_item->name,
1517                                       passwd_item->vp_strvalue);
1518                                 added_known_password = 1;
1519                         }
1520                         ldap_value_free(passwd_vals);
1521 #ifdef NOVELL_UNIVERSAL_PASSWORD
1522                 }
1523                 else{
1524                 /*
1525                 * Read Universal Password from eDirectory
1526                 */
1527                         VALUE_PAIR      *passwd_item;
1528                         VALUE_PAIR      *vp_user_dn;
1529                         char            *universal_password = NULL;
1530                         size_t          universal_password_len = UNIVERSAL_PASS_LEN;
1531                         char            *passwd_val = NULL;
1532
1533                         res = 0;
1534
1535                         if ((passwd_item = pairfind(request->config_items, PW_CLEARTEXT_PASSWORD)) == NULL){
1536
1537                                 universal_password = rad_malloc(universal_password_len);
1538                                 memset(universal_password, 0, universal_password_len);
1539
1540                                 vp_user_dn = pairfind(request->config_items,PW_LDAP_USERDN);
1541                                 res = nmasldap_get_password(conn->ld,vp_user_dn->vp_strvalue,&universal_password_len,universal_password);
1542
1543                                 if (res == 0){
1544                                         passwd_val = universal_password;
1545
1546                                         if (inst->passwd_hdr && strlen(inst->passwd_hdr)){
1547                                                 passwd_val = strstr(passwd_val,inst->passwd_hdr);
1548
1549                                                 if (passwd_val != NULL)
1550                                                         passwd_val += strlen((char*)inst->passwd_hdr);
1551                                                 else
1552                                                         RDEBUG("Password header not found in password %s for user %s ",passwd_val,request->username->vp_strvalue);
1553                                         }
1554
1555                                         if (passwd_val){
1556                                                 passwd_item = radius_paircreate(request, &request->config_items, PW_CLEARTEXT_PASSWORD, PW_TYPE_STRING);
1557                                                 strlcpy(passwd_item->vp_strvalue,passwd_val,sizeof(passwd_item->vp_strvalue));
1558                                                 passwd_item->length = strlen(passwd_item->vp_strvalue);
1559                                                 added_known_password = 1;
1560
1561 #ifdef NOVELL
1562                                                 {
1563                                                         DICT_ATTR *dattr;
1564                                                         VALUE_PAIR      *vp_inst, *vp_apc;
1565                                                         int inst_attr, apc_attr;
1566
1567                                                         dattr = dict_attrbyname("LDAP-Instance");
1568                                                         inst_attr = dattr->attr;
1569                                                         dattr = dict_attrbyname("eDir-APC");
1570                                                         apc_attr = dattr->attr;
1571
1572                                                         vp_inst = pairfind(request->config_items, inst_attr);
1573                                                         if(vp_inst == NULL){
1574                                                                 /*
1575                                                                  * The authorize method of no other LDAP module instance has
1576                                                                  * processed this request.
1577                                                                  */
1578                                                                 vp_inst = radius_paircreate(request, &request->config_items, inst_attr, PW_TYPE_STRING);
1579                                                                 strlcpy(vp_inst->vp_strvalue, inst->xlat_name, sizeof(vp_inst->vp_strvalue));
1580                                                                 vp_inst->length = strlen(vp_inst->vp_strvalue);
1581
1582                                                                 /*
1583                                                                  * Inform the authenticate / post-auth method about the presence
1584                                                                  * of UP in the config items list and whether eDirectory account
1585                                                                  * policy check is to be performed or not.
1586                                                                  */
1587                                                                 vp_apc = radius_paircreate(request, &request->config_items, apc_attr, PW_TYPE_STRING);
1588                                                                 if(!inst->edir_account_policy_check){
1589                                                                         /* Do nothing */
1590                                                                         strcpy(vp_apc->vp_strvalue, "1");
1591                                                                 }else{
1592                                                                         /* Perform eDirectory account-policy check */
1593                                                                         strcpy(vp_apc->vp_strvalue, "2");
1594                                                                 }
1595                                                                 vp_apc->length = 1;
1596                                                         }
1597                                                 }
1598 #endif
1599
1600                                                 RDEBUG("Added the eDirectory password %s in check items as %s",passwd_item->vp_strvalue,passwd_item->name);
1601                                         }
1602                                 }
1603                                 else {
1604                                         RDEBUG("Error reading Universal Password.Return Code = %d",res);
1605                                 }
1606
1607                                 memset(universal_password, 0, universal_password_len);
1608                                 free(universal_password);
1609                         }
1610                 }
1611 #endif
1612         }
1613
1614 #ifdef NOVELL
1615         {
1616                 VALUE_PAIR      *vp_auth_opt;
1617                 DICT_ATTR       *dattr;
1618                 char            **auth_option;
1619                 int             auth_opt_attr;
1620
1621                 dattr = dict_attrbyname("eDir-Auth-Option");
1622                 auth_opt_attr = dattr->attr;
1623                 if(pairfind(*check_pairs, auth_opt_attr) == NULL){
1624                         if ((auth_option = ldap_get_values(conn->ld, msg, "sasDefaultLoginSequence")) != NULL) {
1625                                 if ((vp_auth_opt = paircreate(auth_opt_attr, PW_TYPE_STRING)) == NULL){
1626                                         radlog(L_ERR, "rlm_ldap: Could not allocate memory. Aborting.");
1627                                         ldap_msgfree(result);
1628                                         ldap_release_conn(conn_id, inst->conns);
1629                                 }
1630                                 strcpy(vp_auth_opt->vp_strvalue, auth_option[0]);
1631                                 vp_auth_opt->length = strlen(auth_option[0]);
1632                                 pairadd(&request->config_items, vp_auth_opt);
1633                         }else{
1634                                 RDEBUG("No default NMAS login sequence");
1635                         }
1636                 }
1637         }
1638 #endif
1639
1640         RDEBUG("looking for check items in directory...");
1641
1642         if ((check_tmp = ldap_pairget(conn->ld, msg, inst->check_item_map,check_pairs,1)) != NULL) {
1643                 if (inst->do_xlat){
1644                         pairxlatmove(request, check_pairs, &check_tmp);
1645                         pairfree(&check_tmp);
1646                 }
1647                 else
1648                         pairadd(check_pairs,check_tmp);
1649         }
1650
1651
1652         RDEBUG("looking for reply items in directory...");
1653
1654
1655         if ((reply_tmp = ldap_pairget(conn->ld, msg, inst->reply_item_map,reply_pairs,0)) != NULL) {
1656                 if (inst->do_xlat){
1657                         pairxlatmove(request, reply_pairs, &reply_tmp);
1658                         pairfree(&reply_tmp);
1659                 }
1660                 else
1661                         pairadd(reply_pairs,reply_tmp);
1662         }
1663
1664        if (inst->do_comp && paircompare(request,request->packet->vps,*check_pairs,reply_pairs) != 0){
1665 #ifdef NOVELL
1666                 /* Don't perform eDirectory APC if RADIUS authorize fails */
1667                 int apc_attr;
1668                 VALUE_PAIR *vp_apc;
1669                 DICT_ATTR *dattr;
1670
1671                 dattr = dict_attrbyname("eDir-APC");
1672                 apc_attr = dattr->attr;
1673
1674                 vp_apc = pairfind(request->config_items, apc_attr);
1675                 if(vp_apc)
1676                         vp_apc->vp_strvalue[0] = '1';
1677 #endif
1678
1679                 RDEBUG("Pairs do not match. Rejecting user.");
1680                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Pairs do not match");
1681                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1682                 pairadd(&request->packet->vps, module_fmsg_vp);
1683                 ldap_msgfree(result);
1684                 ldap_release_conn(conn_id,inst->conns);
1685
1686                 return RLM_MODULE_REJECT;
1687         }
1688        
1689        /*
1690         *       More warning messages for people who can't be bothered
1691         *       to read the documentation.
1692         */
1693        if (debug_flag > 1) {
1694                if (!pairfind(request->config_items, PW_CLEARTEXT_PASSWORD) &&
1695                    !pairfind(request->config_items, PW_USER_PASSWORD)) {
1696                        DEBUG("WARNING: No \"known good\" password was found in LDAP.  Are you sure that the user is configured correctly?");
1697                }
1698        }
1699
1700         /*
1701          * Module should default to LDAP authentication if no Auth-Type
1702          * specified.  Note that we do this ONLY if configured, AND we
1703          * set the Auth-Type to our module name, which allows multiple
1704          * ldap instances to work.
1705          */
1706         if (inst->set_auth_type &&
1707             (pairfind(*check_pairs, PW_AUTH_TYPE) == NULL) &&
1708             request->password &&
1709             (request->password->attribute == PW_USER_PASSWORD) &&
1710             !added_known_password) {
1711                 pairadd(check_pairs, pairmake("Auth-Type", inst->auth_type, T_OP_EQ));
1712                 RDEBUG("Setting Auth-Type = %s", inst->auth_type);
1713         }
1714
1715         RDEBUG("user %s authorized to use remote access",
1716               request->username->vp_strvalue);
1717         ldap_msgfree(result);
1718         ldap_release_conn(conn_id,inst->conns);
1719
1720         return RLM_MODULE_OK;
1721 }
1722
1723 /*****************************************************************************
1724  *
1725  *      Function: rlm_ldap_authenticate
1726  *
1727  *      Purpose: Check the user's password against ldap database
1728  *
1729  *****************************************************************************/
1730 static int ldap_authenticate(void *instance, REQUEST * request)
1731 {
1732         LDAP           *ld_user;
1733         LDAPMessage    *result, *msg;
1734         ldap_instance  *inst = instance;
1735         char           *user_dn, *attrs[] = {"uid", NULL};
1736         char            filter[MAX_FILTER_STR_LEN];
1737         char            basedn[MAX_FILTER_STR_LEN];
1738         int             res;
1739         VALUE_PAIR     *vp_user_dn;
1740         VALUE_PAIR      *module_fmsg_vp;
1741         char            module_fmsg[MAX_STRING_LEN];
1742         LDAP_CONN       *conn;
1743         int             conn_id = -1;
1744 #ifdef NOVELL
1745         char            *err = NULL;
1746 #endif
1747
1748         /*
1749          * Ensure that we're being passed a plain-text password, and not
1750          * anything else.
1751          */
1752
1753         if (!request->username) {
1754                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Name\" is required for authentication.\n");
1755                 return RLM_MODULE_INVALID;
1756         }
1757
1758         if (!request->password){
1759                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Password\" is required for authentication.");
1760                 DEBUG2("  You seem to have set \"Auth-Type := LDAP\" somewhere.");
1761                 DEBUG2("  THAT CONFIGURATION IS WRONG.  DELETE IT.");
1762                 DEBUG2("  YOU ARE PREVENTING THE SERVER FROM WORKING PROPERLY.");
1763                 return RLM_MODULE_INVALID;
1764         }
1765
1766         if(request->password->attribute != PW_USER_PASSWORD) {
1767                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Password\" is required for authentication. Cannot use \"%s\".", request->password->name);
1768                 return RLM_MODULE_INVALID;
1769         }
1770
1771         if (request->password->length == 0) {
1772                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: empty password supplied");
1773                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1774                 pairadd(&request->packet->vps, module_fmsg_vp);
1775                 return RLM_MODULE_INVALID;
1776         }
1777
1778         /*
1779          * Check that we don't have any failed connections. If we do there's no real need
1780          * of runing. Also give it another chance if we have a lot of failed connections.
1781          */
1782         if (inst->failed_conns > MAX_FAILED_CONNS_END)
1783                 inst->failed_conns = 0;
1784         if (inst->failed_conns > MAX_FAILED_CONNS_START){
1785                 inst->failed_conns++;
1786                 return RLM_MODULE_FAIL;
1787         }
1788
1789
1790         RDEBUG("login attempt by \"%s\" with password \"%s\"",
1791                request->username->vp_strvalue, request->password->vp_strvalue);
1792
1793         while ((vp_user_dn = pairfind(request->config_items,
1794                                       PW_LDAP_USERDN)) == NULL) {
1795                 if (!radius_xlat(filter, sizeof(filter), inst->filter,
1796                                 request, ldap_escape_func)) {
1797                         radlog(L_ERR, "rlm_ldap: unable to create filter.\n");
1798                         return RLM_MODULE_INVALID;
1799                 }
1800
1801                 if (!radius_xlat(basedn, sizeof(basedn), inst->basedn,
1802                                 request, ldap_escape_func)) {
1803                         radlog(L_ERR, "rlm_ldap: unable to create basedn.\n");
1804                         return RLM_MODULE_INVALID;
1805                 }
1806
1807                 if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
1808                         radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
1809                         return RLM_MODULE_FAIL;
1810                 }
1811                 if ((res = perform_search(instance, conn, basedn, LDAP_SCOPE_SUBTREE, filter, attrs, &result)) != RLM_MODULE_OK) {
1812                         if (res == RLM_MODULE_NOTFOUND){
1813                                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: User not found");
1814                                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1815                                 pairadd(&request->packet->vps, module_fmsg_vp);
1816                         }
1817                         ldap_release_conn(conn_id,inst->conns);
1818                         return (res);
1819                 }
1820                 if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
1821                         ldap_msgfree(result);
1822                         ldap_release_conn(conn_id,inst->conns);
1823                         return RLM_MODULE_FAIL;
1824                 }
1825                 if ((user_dn = ldap_get_dn(conn->ld, msg)) == NULL) {
1826                         RDEBUG("ldap_get_dn() failed");
1827                         ldap_msgfree(result);
1828                         ldap_release_conn(conn_id,inst->conns);
1829                         return RLM_MODULE_FAIL;
1830                 }
1831                 ldap_release_conn(conn_id,inst->conns);
1832                 pairadd(&request->config_items, pairmake("Ldap-UserDn", user_dn, T_OP_EQ));
1833                 ldap_memfree(user_dn);
1834                 ldap_msgfree(result);
1835         }
1836
1837         user_dn = vp_user_dn->vp_strvalue;
1838
1839         RDEBUG("user DN: %s", user_dn);
1840
1841 #ifndef NOVELL
1842         ld_user = ldap_connect(instance, user_dn, request->password->vp_strvalue,
1843                                1, &res, NULL);
1844 #else
1845         /* Don't perform eDirectory APC again after attempting to bind here. */
1846         {
1847                 int apc_attr;
1848                 DICT_ATTR *dattr;
1849                 VALUE_PAIR *vp_apc;
1850                 VALUE_PAIR      *vp_auth_opt, *vp_state;
1851                 int auth_opt_attr;
1852                 char seq[256];
1853                 char host_ipaddr[32];
1854                 LDAP_CONN       *conn1;
1855                 int auth_state = -1;
1856                 char            *challenge = NULL;
1857                 int             challenge_len = MAX_CHALLENGE_LEN;
1858                 char            *state = NULL;
1859
1860                 dattr = dict_attrbyname("eDir-APC");
1861                 apc_attr = dattr->attr;
1862                 vp_apc = pairfind(request->config_items, apc_attr);
1863                 if(vp_apc && vp_apc->vp_strvalue[0] == '2')
1864                         vp_apc->vp_strvalue[0] = '3';
1865
1866                 res = 0;
1867
1868                 dattr = dict_attrbyname("eDir-Auth-Option");
1869                 auth_opt_attr = dattr->attr;
1870
1871                 vp_auth_opt = pairfind(request->config_items, auth_opt_attr);
1872
1873                 if(vp_auth_opt )
1874                 {
1875                         RDEBUG("ldap auth option = %s", vp_auth_opt->vp_strvalue);
1876                         strncpy(seq, vp_auth_opt->vp_strvalue, vp_auth_opt->length);
1877                         seq[vp_auth_opt->length] = '\0';
1878                         if( strcmp(seq, "<No Default>") ){
1879
1880                                 /* Get the client IP address to check for packet validity */
1881                                 inet_ntop(AF_INET, &request->packet->src_ipaddr, host_ipaddr, sizeof(host_ipaddr));
1882
1883                                 /* challenge variable is used to receive the challenge from the
1884                                  * Token method (if any) and also to send the state attribute
1885                                  * in case the request packet is a reply to a challenge
1886                                  */
1887                                 challenge = rad_malloc(MAX_CHALLENGE_LEN);
1888
1889                                 /*  If state attribute present in request it is a reply to challenge. */
1890                                 if((vp_state = pairfind(request->packet->vps, PW_STATE))!= NULL ){
1891                                         RDEBUG("Response to Access-Challenge");
1892                                         strncpy(challenge, vp_state->vp_strvalue, sizeof(challenge));
1893                                         challenge_len = vp_state->length;
1894                                         challenge[challenge_len] = 0;
1895                                         auth_state = -2;
1896                                 }
1897
1898                                 if ((conn_id = ldap_get_conn(inst->conns, &conn1, inst)) == -1){
1899                                         radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
1900                                         res =  RLM_MODULE_FAIL;
1901                                 }
1902
1903                                 if(!conn1){
1904                                         radlog(L_ERR, "rlm_ldap: NULL connection handle passed");
1905                                         return RLM_MODULE_FAIL;
1906                                 }
1907
1908                                 if (conn1->failed_conns > MAX_FAILED_CONNS_START){
1909                                         conn1->failed_conns++;
1910                                         if (conn1->failed_conns >= MAX_FAILED_CONNS_END){
1911                                                 conn1->failed_conns = MAX_FAILED_CONNS_RESTART;
1912                                                 conn1->bound = 0;
1913                                         }
1914                                 }
1915 retry:
1916                                 if (!conn1->bound || conn1->ld == NULL) {
1917                                         DEBUG2("rlm_ldap: attempting LDAP reconnection");
1918                                         if (conn1->ld){
1919                                                 DEBUG2("rlm_ldap: closing existing LDAP connection");
1920                                                 ldap_unbind_s(conn1->ld);
1921                                         }
1922                                         if ((conn1->ld = ldap_connect(instance, inst->login,inst->password, 0, &res, NULL)) == NULL) {
1923                                                 radlog(L_ERR, "rlm_ldap: (re)connection attempt failed");
1924                                                 conn1->failed_conns++;
1925                                                 return (RLM_MODULE_FAIL);
1926                                         }
1927                                         conn1->bound = 1;
1928                                         conn1->failed_conns = 0;
1929                                 }
1930                                 RDEBUG("Performing NMAS Authentication for user: %s, seq: %s \n", user_dn,seq);
1931
1932                                 res = radLdapXtnNMASAuth(conn1->ld, user_dn, request->password->vp_strvalue, seq, host_ipaddr, &challenge_len, challenge, &auth_state );
1933
1934                                 switch(res){
1935                                         case LDAP_SUCCESS:
1936                                                 ldap_release_conn(conn_id,inst->conns);
1937                                                 if ( auth_state == -1)
1938                                                         res = RLM_MODULE_FAIL;
1939                                                 if ( auth_state != REQUEST_CHALLENGED){
1940                                                         if (auth_state == REQUEST_ACCEPTED){
1941                                                                 RDEBUG("user %s authenticated succesfully",request->username->vp_strvalue);
1942                                                                 res = RLM_MODULE_OK;
1943                                                         }else if(auth_state == REQUEST_REJECTED){
1944                                                                 RDEBUG("user %s authentication failed",request->username->vp_strvalue);
1945                                                                 res = RLM_MODULE_REJECT;
1946                                                         }
1947                                                 }else{
1948                                                         /* Request challenged. Generate Reply-Message attribute with challenge data */
1949                                                         pairadd(&request->reply->vps,pairmake("Reply-Message", challenge, T_OP_EQ));
1950                                                         /* Generate state attribute */
1951                                                         state = rad_malloc(MAX_CHALLENGE_LEN);
1952                                                         (void) sprintf(state, "%s%s", challenge, challenge);
1953                                                         vp_state = paircreate(PW_STATE, PW_TYPE_OCTETS);
1954                                                         memcpy(vp_state->vp_strvalue, state, strlen(state));
1955                                                         vp_state->length = strlen(state);
1956                                                         pairadd(&request->reply->vps, vp_state);
1957                                                         free(state);
1958                                                         /* Mark the packet as a Acceess-Challenge Packet */
1959                                                         request->reply->code = PW_ACCESS_CHALLENGE;
1960                                                         RDEBUG("Sending Access-Challenge.");
1961                                                         res = RLM_MODULE_HANDLED;
1962                                                 }
1963                                                 if(challenge)
1964                                                         free(challenge);
1965                                                 return res;
1966                                         case LDAP_SERVER_DOWN:
1967                                                 radlog(L_ERR, "rlm_ldap: nmas authentication failed: LDAP connection lost.");                                                conn->failed_conns++;
1968                                                 if (conn->failed_conns <= MAX_FAILED_CONNS_START){
1969                                                         radlog(L_INFO, "rlm_ldap: Attempting reconnect");
1970                                                         conn->bound = 0;
1971                                                         goto retry;
1972                                                 }
1973                                                 if(challenge)
1974                                                         free(challenge);
1975                                                 return RLM_MODULE_FAIL;
1976                                         default:
1977                                                 ldap_release_conn(conn_id,inst->conns);
1978                                                 if(challenge)
1979                                                         free(challenge);
1980                                                 return RLM_MODULE_FAIL;
1981                                 }
1982                         }
1983                 }
1984         }
1985
1986         ld_user = ldap_connect(instance, user_dn, request->password->vp_strvalue,
1987                         1, &res, &err);
1988
1989         if(err != NULL){
1990                 /* 'err' contains the LDAP connection error description */
1991                 RDEBUG("%s", err);
1992                 pairadd(&request->reply->vps, pairmake("Reply-Message", err, T_OP_EQ));
1993                 ldap_memfree((void *)err);
1994         }
1995 #endif
1996
1997         if (ld_user == NULL){
1998                 if (res == RLM_MODULE_REJECT){
1999                         inst->failed_conns = 0;
2000                         snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Bind as user failed");
2001                         module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
2002                         pairadd(&request->packet->vps, module_fmsg_vp);
2003                 }
2004                 if (res == RLM_MODULE_FAIL){
2005                         RDEBUG("ldap_connect() failed");
2006                         inst->failed_conns++;
2007                 }
2008                 return (res);
2009         }
2010
2011         RDEBUG("user %s authenticated succesfully",
2012               request->username->vp_strvalue);
2013         ldap_unbind_s(ld_user);
2014         inst->failed_conns = 0;
2015
2016         return RLM_MODULE_OK;
2017 }
2018
2019 #ifdef NOVELL
2020 /*****************************************************************************
2021  *
2022  *      Function: rlm_ldap_postauth
2023  *
2024  *      Purpose: Perform eDirectory account policy check and failed-login reporting
2025  *      to eDirectory.
2026  *
2027  *****************************************************************************/
2028 static int ldap_postauth(void *instance, REQUEST * request)
2029 {
2030         int res = RLM_MODULE_FAIL;
2031         int inst_attr, apc_attr;
2032         char password[UNIVERSAL_PASS_LEN];
2033         ldap_instance  *inst = instance;
2034         LDAP_CONN       *conn;
2035         VALUE_PAIR *vp_inst, *vp_apc;
2036         DICT_ATTR *dattr;
2037
2038         dattr = dict_attrbyname("LDAP-Instance");
2039         inst_attr = dattr->attr;
2040         dattr = dict_attrbyname("eDir-APC");
2041         apc_attr = dattr->attr;
2042
2043         vp_inst = pairfind(request->config_items, inst_attr);
2044
2045         /*
2046          * Check if the password in the config items list is the user's UP which has
2047          * been read in the authorize method of this instance of the LDAP module.
2048          */
2049         if((vp_inst == NULL) || strcmp(vp_inst->vp_strvalue, inst->xlat_name))
2050                 return RLM_MODULE_NOOP;
2051
2052         vp_apc = pairfind(request->config_items, apc_attr);
2053
2054         switch(vp_apc->vp_strvalue[0]){
2055                 case '1':
2056                         /* Account policy check not enabled */
2057                 case '3':
2058                         /* Account policy check has been completed */
2059                         res = RLM_MODULE_NOOP;
2060                         break;
2061                 case '2':
2062                         {
2063                                 int err, conn_id = -1;
2064                                 char *error_msg = NULL;
2065                                 VALUE_PAIR *vp_fdn, *vp_pwd;
2066                                 DICT_ATTR *da;
2067
2068                                 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
2069                                   /* Bind to eDirectory as the RADIUS user with a wrong password. */
2070                                   vp_pwd = pairfind(request->config_items, PW_CLEARTEXT_PASSWORD);
2071                                   strcpy(password, vp_pwd->vp_strvalue);
2072                                   if (strlen(password) > 0) {
2073                                           if (password[0] != 'a') {
2074                                                   password[0] = 'a';
2075                                           } else {
2076                                                   password[0] = 'b';
2077                                           }
2078                                   } else {
2079                                           strcpy(password, "dummy_password");
2080                                   }
2081                                   res = RLM_MODULE_REJECT;
2082                                 } else {
2083                                         /* Bind to eDirectory as the RADIUS user using the user's UP */
2084                                         vp_pwd = pairfind(request->config_items, PW_CLEARTEXT_PASSWORD);
2085                                         if (vp_pwd == NULL) {
2086                                                 RDEBUG("User's Universal Password not in config items list.");
2087                                                 return RLM_MODULE_FAIL;
2088                                         }
2089                                         strcpy(password, vp_pwd->vp_strvalue);
2090                                 }
2091
2092                                 if ((da = dict_attrbyname("Ldap-UserDn")) == NULL) {
2093                                         RDEBUG("Attribute for user FDN not found in dictionary. Unable to proceed");
2094                                         return RLM_MODULE_FAIL;
2095                                 }
2096
2097                                 vp_fdn = pairfind(request->config_items, da->attr);
2098                                 if (vp_fdn == NULL) {
2099                                         RDEBUG("User's FQDN not in config items list.");
2100                                         return RLM_MODULE_FAIL;
2101                                 }
2102
2103                                 if ((conn_id = ldap_get_conn(inst->apc_conns, &conn, inst)) == -1){
2104                                         radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
2105                                         return RLM_MODULE_FAIL;
2106                                 }
2107
2108                                 /*
2109                                  *      If there is an existing LDAP
2110                                  *      connection to the directory,
2111                                  *      bind over it. Otherwise,
2112                                  *      establish a new connection.
2113                                  */
2114                         postauth_reconnect:
2115                                 if (!conn->bound || conn->ld == NULL) {
2116                                         DEBUG2("rlm_ldap: attempting LDAP reconnection");
2117                                         if (conn->ld){
2118                                                 DEBUG2("rlm_ldap: closing existing LDAP connection");
2119                                                 ldap_unbind_s(conn->ld);
2120                                         }
2121                                         if ((conn->ld = ldap_connect(instance, (char *)vp_fdn->vp_strvalue, password, 0, &res, &error_msg)) == NULL) {
2122                                                 radlog(L_ERR, "rlm_ldap: eDirectory account policy check failed.");
2123
2124                                                 if (error_msg != NULL) {
2125                                                         RDEBUG("%s", error_msg);
2126                                                         pairadd(&request->reply->vps, pairmake("Reply-Message", error_msg, T_OP_EQ));
2127                                                         ldap_memfree((void *)error_msg);
2128                                                 }
2129
2130                                                 vp_apc->vp_strvalue[0] = '3';
2131                                                 ldap_release_conn(conn_id, inst->apc_conns);
2132                                                 return RLM_MODULE_REJECT;
2133                                         }
2134                                         conn->bound = 1;
2135                                 } else if((err = ldap_simple_bind_s(conn->ld, (char *)vp_fdn->vp_strvalue, password)) != LDAP_SUCCESS) {
2136                                         if (err == LDAP_SERVER_DOWN) {
2137                                                 conn->bound = 0;
2138                                                 goto postauth_reconnect;
2139                                         }
2140                                         RDEBUG("eDirectory account policy check failed.");
2141                                         ldap_get_option(conn->ld, LDAP_OPT_ERROR_STRING, &error_msg);
2142                                         if (error_msg != NULL) {
2143                                                 RDEBUG("%s", error_msg);
2144                                                 pairadd(&request->reply->vps, pairmake("Reply-Message", error_msg, T_OP_EQ));
2145                                                 ldap_memfree((void *)error_msg);
2146                                         }
2147                                         vp_apc->vp_strvalue[0] = '3';
2148                                         ldap_release_conn(conn_id, inst->apc_conns);
2149                                         return RLM_MODULE_REJECT;
2150                                 }
2151                                 vp_apc->vp_strvalue[0] = '3';
2152                                 ldap_release_conn(conn_id, inst->apc_conns);
2153                                 return RLM_MODULE_OK;
2154                         }
2155         }
2156         return res;
2157 }
2158 #endif
2159
2160 static LDAP *ldap_connect(void *instance, const char *dn, const char *password,
2161                           int auth, int *result, char **err)
2162 {
2163         ldap_instance  *inst = instance;
2164         LDAP           *ld = NULL;
2165         int             msgid, rc, ldap_version;
2166         int             ldap_errno = 0;
2167         LDAPMessage    *res;
2168         struct timeval tv;
2169
2170         if (inst->is_url){
2171 #ifdef HAVE_LDAP_INITIALIZE
2172                 DEBUG("rlm_ldap: (re)connect to %s, authentication %d", inst->server, auth);
2173                 if (ldap_initialize(&ld, inst->server) != LDAP_SUCCESS) {
2174                         radlog(L_ERR, "rlm_ldap: ldap_initialize() failed");
2175                         *result = RLM_MODULE_FAIL;
2176                         return (NULL);
2177                 }
2178 #endif
2179         } else {
2180                 DEBUG("rlm_ldap: (re)connect to %s:%d, authentication %d", inst->server, inst->port, auth);
2181                 if ((ld = ldap_init(inst->server, inst->port)) == NULL) {
2182                         radlog(L_ERR, "rlm_ldap: ldap_init() failed");
2183                         *result = RLM_MODULE_FAIL;
2184                         return (NULL);
2185                 }
2186         }
2187         tv.tv_sec = inst->net_timeout;
2188         tv.tv_usec = 0;
2189         if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT,
2190                             (void *) &tv) != LDAP_OPT_SUCCESS) {
2191                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2192                 radlog(L_ERR, "rlm_ldap: Could not set LDAP_OPT_NETWORK_TIMEOUT %d: %s", inst->net_timeout, ldap_err2string(ldap_errno));
2193         }
2194
2195         if (ldap_set_option(ld, LDAP_OPT_TIMELIMIT,
2196                             (void *) &(inst->timelimit)) != LDAP_OPT_SUCCESS) {
2197                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2198                 radlog(L_ERR, "rlm_ldap: Could not set LDAP_OPT_TIMELIMIT %d: %s", inst->timelimit, ldap_err2string(ldap_errno));
2199         }
2200
2201         if (inst->ldap_debug && ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &(inst->ldap_debug)) != LDAP_OPT_SUCCESS) {
2202                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2203                 radlog(L_ERR, "rlm_ldap: Could not set LDAP_OPT_DEBUG_LEVEL %d: %s", inst->ldap_debug, ldap_err2string(ldap_errno));
2204         }
2205
2206         ldap_version = LDAP_VERSION3;
2207         if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION,
2208                             &ldap_version) != LDAP_OPT_SUCCESS) {
2209                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2210                 radlog(L_ERR, "rlm_ldap: Could not set LDAP version to V3: %s", ldap_err2string(ldap_errno));
2211         }
2212
2213 #ifdef HAVE_LDAP_START_TLS
2214         if (inst->tls_mode) {
2215                 DEBUG("rlm_ldap: setting TLS mode to %d", inst->tls_mode);
2216                 if (ldap_set_option(ld, LDAP_OPT_X_TLS,
2217                                     (void *) &(inst->tls_mode)) != LDAP_OPT_SUCCESS) {
2218                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2219                         radlog(L_ERR, "rlm_ldap: could not set LDAP_OPT_X_TLS option %s:", ldap_err2string(ldap_errno));
2220                 }
2221         }
2222
2223         if (inst->tls_cacertfile != NULL) {
2224                 DEBUG("rlm_ldap: setting TLS CACert File to %s", inst->tls_cacertfile);
2225
2226                 if ( ldap_set_option( NULL, LDAP_OPT_X_TLS_CACERTFILE,
2227                                       (void *) inst->tls_cacertfile )
2228                      != LDAP_OPT_SUCCESS) {
2229                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2230                         radlog(L_ERR, "rlm_ldap: could not set "
2231                                "LDAP_OPT_X_TLS_CACERTFILE option to %s: %s",
2232                                inst->tls_cacertfile,
2233                                ldap_err2string(ldap_errno));
2234                 }
2235         }
2236
2237         if (inst->tls_cacertdir != NULL) {
2238                 DEBUG("rlm_ldap: setting TLS CACert Directory to %s", inst->tls_cacertdir);
2239
2240                 if ( ldap_set_option( NULL, LDAP_OPT_X_TLS_CACERTDIR,
2241                                       (void *) inst->tls_cacertdir )
2242                      != LDAP_OPT_SUCCESS) {
2243                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2244                         radlog(L_ERR, "rlm_ldap: could not set "
2245                                "LDAP_OPT_X_TLS_CACERTDIR option to %s: %s",
2246                                inst->tls_cacertdir,
2247                                ldap_err2string(ldap_errno));
2248                 }
2249         }
2250
2251         if (strcmp(TLS_DEFAULT_VERIFY, inst->tls_require_cert ) != 0 ) {
2252                 DEBUG("rlm_ldap: setting TLS Require Cert to %s",
2253                       inst->tls_require_cert);
2254         }
2255
2256
2257 #ifdef HAVE_LDAP_INT_TLS_CONFIG
2258         if (ldap_int_tls_config(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT,
2259                                 (inst->tls_require_cert)) != LDAP_OPT_SUCCESS) {
2260                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2261                 radlog(L_ERR, "rlm_ldap: could not set "
2262                        "LDAP_OPT_X_TLS_REQUIRE_CERT option to %s: %s",
2263                        inst->tls_require_cert,
2264                        ldap_err2string(ldap_errno));
2265         }
2266 #endif
2267
2268         if (inst->tls_certfile != NULL) {
2269                 DEBUG("rlm_ldap: setting TLS Cert File to %s", inst->tls_certfile);
2270
2271                 if (ldap_set_option(NULL, LDAP_OPT_X_TLS_CERTFILE,
2272                                     (void *) inst->tls_certfile)
2273                     != LDAP_OPT_SUCCESS) {
2274                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2275                         radlog(L_ERR, "rlm_ldap: could not set "
2276                                "LDAP_OPT_X_TLS_CERTFILE option to %s: %s",
2277                                inst->tls_certfile,
2278                                ldap_err2string(ldap_errno));
2279                 }
2280         }
2281
2282         if (inst->tls_keyfile != NULL) {
2283                 DEBUG("rlm_ldap: setting TLS Key File to %s",
2284                       inst->tls_keyfile);
2285
2286                 if ( ldap_set_option( NULL, LDAP_OPT_X_TLS_KEYFILE,
2287                                       (void *) inst->tls_keyfile )
2288                      != LDAP_OPT_SUCCESS) {
2289                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2290                         radlog(L_ERR, "rlm_ldap: could not set "
2291                                "LDAP_OPT_X_TLS_KEYFILE option to %s: %s",
2292                                inst->tls_keyfile, ldap_err2string(ldap_errno));
2293                 }
2294         }
2295
2296         if (inst->tls_randfile != NULL) {
2297                 DEBUG("rlm_ldap: setting TLS Key File to %s",
2298                       inst->tls_randfile);
2299
2300                 if (ldap_set_option(NULL, LDAP_OPT_X_TLS_RANDOM_FILE,
2301                                     (void *) inst->tls_randfile)
2302                     != LDAP_OPT_SUCCESS) {
2303                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2304                         radlog(L_ERR, "rlm_ldap: could not set "
2305                                "LDAP_OPT_X_TLS_RANDOM_FILE option to %s: %s",
2306                                inst->tls_randfile, ldap_err2string(ldap_errno));
2307                 }
2308         }
2309
2310         if (inst->start_tls) {
2311                 DEBUG("rlm_ldap: starting TLS");
2312                 rc = ldap_start_tls_s(ld, NULL, NULL);
2313                 if (rc != LDAP_SUCCESS) {
2314                         DEBUG("rlm_ldap: ldap_start_tls_s()");
2315                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER,
2316                                         &ldap_errno);
2317                         radlog(L_ERR, "rlm_ldap: could not start TLS %s",
2318                                ldap_err2string(ldap_errno));
2319                         *result = RLM_MODULE_FAIL;
2320                         ldap_unbind_s(ld);
2321                         return (NULL);
2322                 }
2323         }
2324 #endif /* HAVE_LDAP_START_TLS */
2325
2326         if (inst->is_url){
2327                 DEBUG("rlm_ldap: bind as %s/%s to %s",
2328                       dn, password, inst->server);
2329         } else {
2330                 DEBUG("rlm_ldap: bind as %s/%s to %s:%d",
2331                       dn, password, inst->server, inst->port);
2332         }
2333
2334         msgid = ldap_bind(ld, dn, password,LDAP_AUTH_SIMPLE);
2335         if (msgid == -1) {
2336                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2337                 if(err != NULL){
2338                         ldap_get_option(ld, LDAP_OPT_ERROR_STRING, err);
2339                 }
2340                 if (inst->is_url) {
2341                         radlog(L_ERR, "rlm_ldap: %s bind to %s failed: %s",
2342                                 dn, inst->server, ldap_err2string(ldap_errno));
2343                 } else {
2344                         radlog(L_ERR, "rlm_ldap: %s bind to %s:%d failed: %s",
2345                                 dn, inst->server, inst->port,
2346                                 ldap_err2string(ldap_errno));
2347                 }
2348                 *result = RLM_MODULE_FAIL;
2349                 ldap_unbind_s(ld);
2350                 return (NULL);
2351         }
2352         DEBUG("rlm_ldap: waiting for bind result ...");
2353
2354         tv.tv_sec = inst->timeout;
2355         tv.tv_usec = 0;
2356         rc = ldap_result(ld, msgid, 1, &tv, &res);
2357
2358         if (rc < 1) {
2359                 DEBUG("rlm_ldap: ldap_result()");
2360                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2361                 if(err != NULL){
2362                         ldap_get_option(ld, LDAP_OPT_ERROR_STRING, err);
2363                 }
2364                 if (inst->is_url) {
2365                         radlog(L_ERR, "rlm_ldap: %s bind to %s failed: %s",
2366                                 dn, inst->server, (rc == 0) ? "timeout" : ldap_err2string(ldap_errno));
2367                 } else {
2368                         radlog(L_ERR, "rlm_ldap: %s bind to %s:%d failed: %s",
2369                                dn, inst->server, inst->port,
2370                                 (rc == 0) ? "timeout" : ldap_err2string(ldap_errno));
2371                 }
2372                 *result = RLM_MODULE_FAIL;
2373                 ldap_unbind_s(ld);
2374                 return (NULL);
2375         }
2376
2377         ldap_errno = ldap_result2error(ld, res, 1);
2378         switch (ldap_errno) {
2379         case LDAP_SUCCESS:
2380                 DEBUG("rlm_ldap: Bind was successful");
2381                 *result = RLM_MODULE_OK;
2382                 break;
2383
2384         case LDAP_INVALID_CREDENTIALS:
2385                 if (auth){
2386                         DEBUG("rlm_ldap: Bind failed with invalid credentials");
2387                         *result = RLM_MODULE_REJECT;
2388                 } else {
2389                         radlog(L_ERR, "rlm_ldap: LDAP login failed: check identity, password settings in ldap section of radiusd.conf");
2390                         *result = RLM_MODULE_FAIL;
2391                 }
2392                 if(err != NULL){
2393                         ldap_get_option(ld, LDAP_OPT_ERROR_STRING, err);
2394                 }
2395                 break;
2396
2397         default:
2398                 if (inst->is_url) {
2399                         radlog(L_ERR,"rlm_ldap: %s bind to %s failed %s",
2400                                 dn, inst->server, ldap_err2string(ldap_errno));
2401                 } else {
2402                         radlog(L_ERR,"rlm_ldap: %s bind to %s:%d failed %s",
2403                                 dn, inst->server, inst->port,
2404                                 ldap_err2string(ldap_errno));
2405                 }
2406                 *result = RLM_MODULE_FAIL;
2407                 if(err != NULL){
2408                         ldap_get_option(ld, LDAP_OPT_ERROR_STRING, err);
2409                 }
2410         }
2411
2412         if (*result != RLM_MODULE_OK) {
2413                 ldap_unbind_s(ld);
2414                 ld = NULL;
2415         }
2416         return ld;
2417 }
2418
2419 /*****************************************************************************
2420  *
2421  *      Detach from the LDAP server and cleanup internal state.
2422  *
2423  *****************************************************************************/
2424 static int
2425 ldap_detach(void *instance)
2426 {
2427         ldap_instance  *inst = instance;
2428         TLDAP_RADIUS *pair, *nextpair;
2429
2430         if (inst->conns) {
2431                 int i;
2432
2433                 for (i = 0;i < inst->num_conns; i++) {
2434                         if (inst->conns[i].ld){
2435                                 ldap_unbind_s(inst->conns[i].ld);
2436                         }
2437                         pthread_mutex_destroy(&inst->conns[i].mutex);
2438                 }
2439                 free(inst->conns);
2440         }
2441
2442 #ifdef NOVELL
2443         if (inst->apc_conns){
2444                 int i;
2445
2446                 for (i = 0; i < inst->num_conns; i++) {
2447                         if (inst->apc_conns[i].ld){
2448                                 ldap_unbind_s(inst->apc_conns[i].ld);
2449                         }
2450                         pthread_mutex_destroy(&inst->apc_conns[i].mutex);
2451                 }
2452                 free(inst->apc_conns);
2453         }
2454 #endif
2455
2456         pair = inst->check_item_map;
2457
2458         while (pair != NULL) {
2459                 nextpair = pair->next;
2460                 free(pair->attr);
2461                 free(pair->radius_attr);
2462                 free(pair);
2463                 pair = nextpair;
2464         }
2465
2466         pair = inst->reply_item_map;
2467
2468         while (pair != NULL) {
2469                 nextpair = pair->next;
2470                 free(pair->attr);
2471                 free(pair->radius_attr);
2472                 free(pair);
2473                 pair = nextpair;
2474         }
2475
2476         if (inst->atts)
2477                 free(inst->atts);
2478
2479         paircompare_unregister(PW_LDAP_GROUP, ldap_groupcmp);
2480         xlat_unregister(inst->xlat_name,ldap_xlat);
2481         free(inst->xlat_name);
2482
2483         free(inst);
2484
2485         return 0;
2486 }
2487
2488
2489 #ifdef FIELDCPY
2490 static void
2491 fieldcpy(char *string, char **uptr)
2492 {
2493         char           *ptr;
2494
2495         ptr = *uptr;
2496         while (*ptr == ' ' || *ptr == '\t') {
2497                 ptr++;
2498         }
2499         if (*ptr == '"') {
2500                 ptr++;
2501                 while (*ptr != '"' && *ptr != '\0' && *ptr != '\n') {
2502                         *string++ = *ptr++;
2503                 }
2504                 *string = '\0';
2505                 if (*ptr == '"') {
2506                         ptr++;
2507                 }
2508                 *uptr = ptr;
2509                 return;
2510         }
2511         while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0' && *ptr != '\n' &&
2512                *ptr != '=' && *ptr != ',') {
2513                 *string++ = *ptr++;
2514         }
2515         *string = '\0';
2516         *uptr = ptr;
2517         return;
2518 }
2519 #endif
2520
2521 /*
2522  *      Copied from src/lib/token.c
2523  */
2524 static const FR_NAME_NUMBER tokens[] = {
2525         { "=~", T_OP_REG_EQ,    }, /* order is important! */
2526         { "!~", T_OP_REG_NE,    },
2527         { "{",  T_LCBRACE,      },
2528         { "}",  T_RCBRACE,      },
2529         { "(",  T_LBRACE,       },
2530         { ")",  T_RBRACE,       },
2531         { ",",  T_COMMA,        },
2532         { "+=", T_OP_ADD,       },
2533         { "-=", T_OP_SUB,       },
2534         { ":=", T_OP_SET,       },
2535         { "=*", T_OP_CMP_TRUE,  },
2536         { "!*", T_OP_CMP_FALSE, },
2537         { "==", T_OP_CMP_EQ,    },
2538         { "=",  T_OP_EQ,        },
2539         { "!=", T_OP_NE,        },
2540         { ">=", T_OP_GE,        },
2541         { ">",  T_OP_GT,        },
2542         { "<=", T_OP_LE,        },
2543         { "<",  T_OP_LT,        },
2544         { NULL, 0}
2545 };
2546
2547 /*****************************************************************************
2548  *      Get RADIUS attributes from LDAP object
2549  *      ( according to draft-adoba-radius-05.txt
2550  *        <http://www.ietf.org/internet-drafts/draft-adoba-radius-05.txt> )
2551  *
2552  *****************************************************************************/
2553 static VALUE_PAIR *ldap_pairget(LDAP *ld, LDAPMessage *entry,
2554                                 TLDAP_RADIUS *item_map,
2555                                 VALUE_PAIR **pairs, int is_check)
2556 {
2557         char          **vals;
2558         int             vals_count;
2559         int             vals_idx;
2560         const char      *ptr;
2561         const char     *value;
2562         TLDAP_RADIUS   *element;
2563         FR_TOKEN      token, operator;
2564         int             is_generic_attribute;
2565         char            buf[MAX_STRING_LEN];
2566         VALUE_PAIR     *pairlist = NULL;
2567         VALUE_PAIR     *newpair = NULL;
2568         char            do_xlat = FALSE;
2569         char            print_buffer[2048];
2570
2571         /*
2572          *      check if there is a mapping from this LDAP attribute
2573          *      to a RADIUS attribute
2574          */
2575         for (element = item_map; element != NULL; element = element->next) {
2576                 /*
2577                  *      No mapping, skip it.
2578                  */
2579                 if ((vals = ldap_get_values(ld,entry,element->attr)) == NULL)
2580                         continue;
2581
2582                 /*
2583                  *      Check whether this is a one-to-one-mapped ldap
2584                  *      attribute or a generic attribute and set flag
2585                  *      accordingly.
2586                  */
2587                 if (strcasecmp(element->radius_attr, GENERIC_ATTRIBUTE_ID)==0)
2588                         is_generic_attribute = 1;
2589                 else
2590                         is_generic_attribute = 0;
2591
2592                 /*
2593                  *      Find out how many values there are for the
2594                  *      attribute and extract all of them.
2595                  */
2596                 vals_count = ldap_count_values(vals);
2597
2598                 for (vals_idx = 0; vals_idx < vals_count; vals_idx++) {
2599                         value = vals[vals_idx];
2600
2601                         if (is_generic_attribute) {
2602                                 /*
2603                                  *      This is a generic attribute.
2604                                  */
2605                                 FR_TOKEN dummy; /* makes pairread happy */
2606
2607                                 /* not sure if using pairread here is ok ... */
2608                                 if ( (newpair = pairread(&value, &dummy)) != NULL) {
2609                                         DEBUG("rlm_ldap: extracted attribute %s from generic item %s",
2610                                               newpair->name, vals[vals_idx]);
2611                                         pairadd(&pairlist, newpair);
2612                                 } else {
2613                                         radlog(L_ERR, "rlm_ldap: parsing %s failed: %s",
2614                                                element->attr, vals[vals_idx]);
2615                                 }
2616                         } else {
2617                                 /*
2618                                  *      This is a one-to-one-mapped attribute
2619                                  */
2620                                 ptr = value;
2621                                 operator = gettoken(&ptr, buf, sizeof(buf));
2622                                 if (operator < T_EQSTART || operator > T_EQEND) {
2623                                         /* no leading operator found */
2624                                         if (element->operator != T_OP_INVALID)
2625                                                 operator = element->operator;
2626                                         else if (is_check)
2627                                                 operator = T_OP_CMP_EQ;
2628                                         else
2629                                                 operator = T_OP_EQ;
2630                                 } else {
2631                                         /* the value is after the operator */
2632                                         value = ptr;
2633                                 }
2634
2635                                 /*
2636                                  *      Do xlat if the *entire* string
2637                                  *      is quoted.
2638                                  */
2639                                 if ((value[0] == '\'' || value[0] == '"' ||
2640                                      value[0] == '`') &&
2641                                     (value[0] == value[strlen(value)-1])) {
2642                                         ptr = value;
2643                                         token = gettoken(&ptr, buf, sizeof(buf));
2644                                         switch (token) {
2645                                         /* take the unquoted string */
2646                                         case T_SINGLE_QUOTED_STRING:
2647                                         case T_DOUBLE_QUOTED_STRING:
2648                                                 value = buf;
2649                                                 break;
2650
2651                                         /* the value will be xlat'ed later */
2652                                         case T_BACK_QUOTED_STRING:
2653                                                 value = buf;
2654                                                 do_xlat = TRUE;
2655                                                 break;
2656
2657                                         /* keep the original string */
2658                                         default:
2659                                                 break;
2660                                         }
2661                                 }
2662                                 if (value[0] == '\0') {
2663                                         DEBUG("rlm_ldap: Attribute %s has no value", element->attr);
2664                                         continue;
2665                                 }
2666
2667                                 /*
2668                                  *      Create the pair.
2669                                  */
2670                                 newpair = pairmake(element->radius_attr,
2671                                                    do_xlat ? NULL : value,
2672                                                    operator);
2673                                 if (newpair == NULL) {
2674                                         radlog(L_ERR, "rlm_ldap: Failed to create the pair: %s", fr_strerror());
2675                                         continue;
2676                                 }
2677
2678                                 if (do_xlat) {
2679                                         newpair->flags.do_xlat = 1;
2680                                         strlcpy(newpair->vp_strvalue, buf,
2681                                                 sizeof(newpair->vp_strvalue));
2682                                         newpair->length = 0;
2683                                 }
2684                                 vp_prints(print_buffer, sizeof(print_buffer),
2685                                           newpair);
2686                                 DEBUG("rlm_ldap: %s -> %s",
2687                                       element->attr, print_buffer);
2688
2689
2690                                 /*
2691                                  *      Add the pair into the packet.
2692                                  */
2693                                 if (!vals_idx){
2694                                         pairdelete(pairs, newpair->attribute);
2695                                 }
2696                                 pairadd(&pairlist, newpair);
2697                         }
2698                 }
2699                 ldap_value_free(vals);
2700         }
2701
2702         return (pairlist);
2703 }
2704
2705 /* globally exported name */
2706 module_t rlm_ldap = {
2707         RLM_MODULE_INIT,
2708         "LDAP",
2709         RLM_TYPE_THREAD_SAFE,   /* type: reserved        */
2710         ldap_instantiate,       /* instantiation         */
2711         ldap_detach,            /* detach                */
2712         {
2713                 ldap_authenticate,      /* authentication        */
2714                 ldap_authorize,         /* authorization         */
2715                 NULL,                   /* preaccounting         */
2716                 NULL,                   /* accounting            */
2717                 NULL,                   /* checksimul            */
2718                 NULL,                   /* pre-proxy             */
2719                 NULL,                   /* post-proxy            */
2720 #ifdef NOVELL
2721                 ldap_postauth           /* post-auth             */
2722 #else
2723                 NULL
2724 #endif
2725         },
2726 };