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