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