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