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