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