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