Update the GPL boilerplate with the new address of the FSF.
[freeradius.git] / src / modules / rlm_ldap / rlm_ldap.c
1 /*
2  * rlm_ldap.c   LDAP authorization and authentication module.
3  *
4  *   This program is free software; you can redistribute it and/or modify
5  *   it under the terms of the GNU General Public License as published by
6  *   the Free Software Foundation; either version 2 of the License, or
7  *   (at your option) any later version.
8  *
9  *   This program is distributed in the hope that it will be useful,
10  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *   GNU General Public License for more details.
13  *
14  *   You should have received a copy of the GNU General Public License
15  *   along with this program; if not, write to the Free Software
16  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
17  *
18  *   Copyright 2004 The FreeRADIUS Server Project.
19  */
20 static const char rcsid[] = "$Id$";
21
22 #include <freeradius-devel/autoconf.h>
23
24 #include        <sys/types.h>
25 #include        <sys/socket.h>
26 #include        <sys/time.h>
27 #include        <netinet/in.h>
28
29 #include        <stdio.h>
30 #include        <stdlib.h>
31 #include        <netdb.h>
32 #include        <pwd.h>
33 #include        <time.h>
34 #include        <ctype.h>
35 #include        <string.h>
36
37 #include        <lber.h>
38 #include        <ldap.h>
39
40 #include        <errno.h>
41 #include        <unistd.h>
42 #include        <pthread.h>
43
44 #include        <freeradius-devel/radiusd.h>
45 #include        <freeradius-devel/conffile.h>
46 #include        <freeradius-devel/modules.h>
47 #include        <freeradius-devel/rad_assert.h>
48
49 #ifndef HAVE_PTHREAD_H
50 /*
51  *      This is a lot simpler than putting ifdef's around
52  *      every use of the pthread functions.
53  */
54 #define pthread_mutex_lock(a)
55 #define pthread_mutex_trylock(a) (0)
56 #define pthread_mutex_unlock(a)
57 #define pthread_mutex_init(a,b)
58 #define pthread_mutex_destroy(a)
59 #endif
60
61
62 #define MAX_FILTER_STR_LEN      1024
63 #define TIMELIMIT 5
64
65 /*
66  * These are used in case ldap_search returns LDAP_SERVER_DOWN
67  * In that case we do conn->failed_conns++ and then check it:
68  * If conn->failed_conns <= MAX_FAILED_CONNS_START then we try
69  * to reconnect
70  * conn->failed_conns is also checked on entrance in perform_search:
71  * If conn->failed_conns > MAX_FAILED_CONNS_START then we don't
72  * try to do anything and we just do conn->failed_conns++ and
73  * return RLM_MODULE_FAIL
74  * if conn->failed_conns >= MAX_FAILED_CONNS_END then we give it
75  * another chance and we set it to MAX_FAILED_CONNS_RESTART and
76  * try to reconnect.
77  *
78  *
79  * We are assuming that the majority of the LDAP_SERVER_DOWN cases
80  * will either be an ldap connection timeout or a temporary ldap
81  * server problem.
82  * As a result we make a few attempts to reconnect hoping that the problem
83  * will soon go away. If it does not go away then we just return
84  * RLM_MODULE_FAIL on entrance in perform_search until conn->failed_conns
85  * gets to MAX_FAILED_CONNS_END. After that we give it one more chance by
86  * going back to MAX_FAILED_CONNS_RESTART
87  *
88  */
89
90 #define MAX_FAILED_CONNS_END            20
91 #define MAX_FAILED_CONNS_RESTART        4
92 #define MAX_FAILED_CONNS_START          5
93
94 #ifdef NOVELL_UNIVERSAL_PASSWORD
95
96 /* Universal Password Length */
97 #define UNIVERSAL_PASS_LEN 256
98
99 int nmasldap_get_password(
100         LDAP     *ld,
101         char     *objectDN,
102         size_t   *pwdSize,      /* in bytes */
103         char     *pwd );
104
105 #endif
106 /* linked list of mappings between RADIUS attributes and LDAP attributes */
107 struct TLDAP_RADIUS {
108         char*                 attr;
109         char*                 radius_attr;
110         LRAD_TOKEN            operator;
111         struct TLDAP_RADIUS*  next;
112 };
113 typedef struct TLDAP_RADIUS TLDAP_RADIUS;
114
115 typedef struct ldap_conn {
116         LDAP            *ld;
117         char            bound;
118         char            locked;
119         int             failed_conns;
120 #ifdef HAVE_PTHREAD_H
121         pthread_mutex_t mutex;
122 #endif
123 } LDAP_CONN;
124
125 typedef struct {
126         char           *server;
127         int             port;
128         int             timelimit;
129         struct timeval  net_timeout;
130         struct timeval  timeout;
131         int             debug;
132         int             tls_mode;
133         int             start_tls;
134         int             num_conns;
135         int             do_comp;
136         int             do_xlat;
137         int             default_allow;
138         int             failed_conns;
139         int             is_url;
140         char           *login;
141         char           *password;
142         char           *filter;
143         char           *base_filter;
144         char           *basedn;
145         char           *default_profile;
146         char           *profile_attr;
147         char           *access_attr;
148         char           *passwd_hdr;
149         char           *passwd_attr;
150         int             auto_header;
151         char           *dictionary_mapping;
152         char           *groupname_attr;
153         char           *groupmemb_filt;
154         char           *groupmemb_attr;
155         char            **atts;
156         TLDAP_RADIUS   *check_item_map;
157         TLDAP_RADIUS   *reply_item_map;
158         LDAP_CONN       *conns;
159 #ifdef NOVELL
160         LDAP_CONN *apc_conns;
161 #endif
162         int             ldap_debug; /* Debug flag for LDAP SDK */
163         char            *xlat_name; /* name used to xlat */
164         char            *tls_cacertfile;
165         char            *tls_cacertdir;
166         char            *tls_certfile;
167         char            *tls_keyfile;
168         char            *tls_randfile;
169         char            *tls_require_cert;
170 #ifdef NOVELL
171         int              edir_account_policy_check;
172 #endif
173         int              set_auth_type;
174 }  ldap_instance;
175
176 /* The default setting for TLS Certificate Verification */
177 #define TLS_DEFAULT_VERIFY "allow"
178
179 static CONF_PARSER tls_config[] = {
180         {"start_tls", PW_TYPE_BOOLEAN,
181          offsetof(ldap_instance,start_tls), NULL, "no"},
182         {"cacertfile", PW_TYPE_FILENAME,
183          offsetof(ldap_instance,tls_cacertfile), NULL, NULL},
184         {"cacertdir", PW_TYPE_FILENAME,
185          offsetof(ldap_instance,tls_cacertdir), NULL, NULL},
186         {"certfile", PW_TYPE_FILENAME,
187          offsetof(ldap_instance,tls_certfile), NULL, NULL},
188         {"keyfile", PW_TYPE_FILENAME,
189          offsetof(ldap_instance,tls_keyfile), NULL, NULL},
190         {"randfile", PW_TYPE_STRING_PTR, /* OK if it changes on HUP */
191          offsetof(ldap_instance,tls_randfile), NULL, NULL},
192         {"require_cert", PW_TYPE_STRING_PTR,
193          offsetof(ldap_instance,tls_require_cert), NULL, TLS_DEFAULT_VERIFY},
194         { NULL, -1, 0, NULL, NULL }
195 };
196
197 static const CONF_PARSER module_config[] = {
198         {"server", PW_TYPE_STRING_PTR,
199          offsetof(ldap_instance,server), NULL, "localhost"},
200         {"port", PW_TYPE_INTEGER,
201          offsetof(ldap_instance,port), NULL, "389"},
202         {"password", PW_TYPE_STRING_PTR,
203          offsetof(ldap_instance,password), NULL, ""},
204         {"identity", PW_TYPE_STRING_PTR,
205          offsetof(ldap_instance,login), NULL, ""},
206
207         /*
208          *      Timeouts & stuff.
209          */
210         /* wait forever on network activity */
211         {"net_timeout", PW_TYPE_INTEGER,
212          offsetof(ldap_instance,net_timeout.tv_sec), NULL, "10"},
213         /* wait forever for search results */
214         {"timeout", PW_TYPE_INTEGER,
215          offsetof(ldap_instance,timeout.tv_sec), NULL, "20"},
216         /* allow server unlimited time for search (server-side limit) */
217         {"timelimit", PW_TYPE_INTEGER,
218          offsetof(ldap_instance,timelimit), NULL, "20"},
219
220         /*
221          *      TLS configuration  The first few are here for backwards
222          *      compatibility.  The last is the new subsection.
223          */
224         {"tls_mode", PW_TYPE_BOOLEAN,
225          offsetof(ldap_instance,tls_mode), NULL, "no"},
226
227         {"start_tls", PW_TYPE_BOOLEAN,
228          offsetof(ldap_instance,start_tls), NULL, "no"},
229         {"tls_cacertfile", PW_TYPE_FILENAME,
230          offsetof(ldap_instance,tls_cacertfile), NULL, NULL},
231         {"tls_cacertdir", PW_TYPE_FILENAME,
232          offsetof(ldap_instance,tls_cacertdir), NULL, NULL},
233         {"tls_certfile", PW_TYPE_FILENAME,
234          offsetof(ldap_instance,tls_certfile), NULL, NULL},
235         {"tls_keyfile", PW_TYPE_FILENAME,
236          offsetof(ldap_instance,tls_keyfile), NULL, NULL},
237         {"tls_randfile", PW_TYPE_STRING_PTR, /* OK if it changes on HUP */
238          offsetof(ldap_instance,tls_randfile), NULL, NULL},
239         {"tls_require_cert", PW_TYPE_STRING_PTR,
240          offsetof(ldap_instance,tls_require_cert), NULL, TLS_DEFAULT_VERIFY},
241         { "tls", PW_TYPE_SUBSECTION, 0, NULL, (const void *) tls_config },
242
243         /*
244          *      DN's and filters.
245          */
246         {"basedn", PW_TYPE_STRING_PTR,
247          offsetof(ldap_instance,basedn), NULL, "o=notexist"},
248         {"filter", PW_TYPE_STRING_PTR,
249          offsetof(ldap_instance,filter), NULL, "(uid=%u)"},
250         {"base_filter", PW_TYPE_STRING_PTR,
251          offsetof(ldap_instance,base_filter), NULL, "(objectclass=radiusprofile)"},
252         {"default_profile", PW_TYPE_STRING_PTR,
253          offsetof(ldap_instance,default_profile), NULL, NULL},
254         {"profile_attribute", PW_TYPE_STRING_PTR,
255          offsetof(ldap_instance,profile_attr), NULL, NULL},
256
257         /*
258          *      Getting passwords from the database
259          */
260         {"password_header", PW_TYPE_STRING_PTR,
261          offsetof(ldap_instance,passwd_hdr), NULL, NULL},
262         {"password_attribute", PW_TYPE_STRING_PTR,
263          offsetof(ldap_instance,passwd_attr), NULL, NULL},
264         {"auto_header", PW_TYPE_BOOLEAN,
265          offsetof(ldap_instance,auto_header), NULL, "no"},
266
267         /*
268          *      Access limitations
269          */
270         /* LDAP attribute name that controls remote access */
271         {"access_attr", PW_TYPE_STRING_PTR,
272          offsetof(ldap_instance,access_attr), NULL, NULL},
273         {"access_attr_used_for_allow", PW_TYPE_BOOLEAN,
274          offsetof(ldap_instance,default_allow), NULL, "yes"},
275
276         /*
277          *      Group checks.  These could probably be done
278          *      via dynamic xlat's.
279          */
280         {"groupname_attribute", PW_TYPE_STRING_PTR,
281          offsetof(ldap_instance,groupname_attr), NULL, "cn"},
282         {"groupmembership_filter", PW_TYPE_STRING_PTR,
283          offsetof(ldap_instance,groupmemb_filt), NULL, "(|(&(objectClass=GroupOfNames)(member=%{Ldap-UserDn}))(&(objectClass=GroupOfUniqueNames)(uniquemember=%{Ldap-UserDn})))"},
284         {"groupmembership_attribute", PW_TYPE_STRING_PTR,
285          offsetof(ldap_instance,groupmemb_attr), NULL, NULL},
286
287         /* file with mapping between LDAP and RADIUS attributes */
288         {"dictionary_mapping", PW_TYPE_FILENAME,
289          offsetof(ldap_instance,dictionary_mapping), NULL, "${confdir}/ldap.attrmap"},
290
291         /*
292          *      Debugging flags to the server
293          */
294         {"ldap_debug", PW_TYPE_INTEGER,
295          offsetof(ldap_instance,ldap_debug), NULL, "0x0000"},
296         {"ldap_connections_number", PW_TYPE_INTEGER,
297          offsetof(ldap_instance,num_conns), NULL, "5"},
298         {"compare_check_items", PW_TYPE_BOOLEAN,
299          offsetof(ldap_instance,do_comp), NULL, "no"},
300         {"do_xlat", PW_TYPE_BOOLEAN,
301          offsetof(ldap_instance,do_xlat), NULL, "yes"},
302
303 #ifdef NOVELL
304         /*
305          *      Novell magic.
306          */
307         {"edir_account_policy_check", PW_TYPE_BOOLEAN,
308          offsetof(ldap_instance,edir_account_policy_check), NULL, "yes"},
309 #endif
310
311         {"set_auth_type", PW_TYPE_BOOLEAN, offsetof(ldap_instance,set_auth_type), NULL, "yes"},
312         {NULL, -1, 0, NULL, NULL}
313 };
314
315 #define ld_valid                ld_options.ldo_valid
316 #define LDAP_VALID_SESSION      0x2
317 #define LDAP_VALID(ld)  ( (ld)->ld_valid == LDAP_VALID_SESSION )
318
319 #ifdef FIELDCPY
320 static void     fieldcpy(char *, char **);
321 #endif
322 static VALUE_PAIR *ldap_pairget(LDAP *, LDAPMessage *, TLDAP_RADIUS *,VALUE_PAIR **,int);
323 static int ldap_groupcmp(void *, REQUEST *, VALUE_PAIR *, VALUE_PAIR *, VALUE_PAIR *, VALUE_PAIR **);
324 static int ldap_xlat(void *, REQUEST *, char *, char *, size_t, RADIUS_ESCAPE_STRING);
325 static LDAP    *ldap_connect(void *instance, const char *, const char *, int, int *, char **);
326 static int     read_mappings(ldap_instance* inst);
327
328 static inline int ldap_get_conn(LDAP_CONN *conns,LDAP_CONN **ret,void *instance)
329 {
330         ldap_instance *inst = instance;
331         register int i = 0;
332
333         for(i=0;i<inst->num_conns;i++){
334                 DEBUG("rlm_ldap: ldap_get_conn: Checking Id: %d",i);
335                 if ((pthread_mutex_trylock(&conns[i].mutex) == 0)) {
336                         if (conns[i].locked == 1) {
337                                 /* connection is already being used */
338                                 pthread_mutex_unlock(&(conns[i].mutex));
339                                 continue;
340                         }
341                         /* found an unused connection */
342                         *ret = &conns[i];
343                         conns[i].locked = 1;
344                         DEBUG("rlm_ldap: ldap_get_conn: Got Id: %d",i);
345                         return i;
346                 }
347         }
348
349         return -1;
350 }
351
352 static inline void ldap_release_conn(int i, LDAP_CONN *conns)
353 {
354         DEBUG("rlm_ldap: ldap_release_conn: Release Id: %d",i);
355         conns[i].locked = 0;
356         pthread_mutex_unlock(&(conns[i].mutex));
357 }
358
359 /*************************************************************************
360  *
361  *      Function: rlm_ldap_instantiate
362  *
363  *      Purpose: Uses section of radiusd config file passed as parameter
364  *               to create an instance of the module.
365  *
366  *************************************************************************/
367 static int
368 ldap_instantiate(CONF_SECTION * conf, void **instance)
369 {
370         ldap_instance  *inst;
371         int i = 0;
372         int atts_num = 0;
373         int reply_map_num = 0;
374         int check_map_num = 0;
375         int att_map[3] = {0,0,0};
376         TLDAP_RADIUS *pair;
377         ATTR_FLAGS flags;
378         const char *xlat_name;
379
380         inst = rad_malloc(sizeof *inst);
381         if (!inst) {
382                 return -1;
383         }
384         memset(inst, 0, sizeof(*inst));
385
386         if (cf_section_parse(conf, inst, module_config) < 0) {
387                 free(inst);
388                 return -1;
389         }
390
391         if (inst->server == NULL) {
392                 radlog(L_ERR, "rlm_ldap: missing 'server' directive.");
393                 free(inst);     /* FIXME: detach */
394                 return -1;
395         }
396         inst->is_url = 0;
397         if (ldap_is_ldap_url(inst->server)){
398 #ifdef HAVE_LDAP_INITIALIZE
399                 inst->is_url = 1;
400                 inst->port = 0;
401 #else
402                 radlog(L_ERR, "rlm_ldap: 'server' directive is in URL form but ldap_initialize() is not available.");
403                 free(inst);     /* FIXME: detach */
404                 return -1;
405 #endif
406         }
407
408         inst->timeout.tv_usec = 0;
409         inst->net_timeout.tv_usec = 0;
410         /* workaround for servers which support LDAPS but not START TLS */
411         if(inst->port == LDAPS_PORT || inst->tls_mode)
412                 inst->tls_mode = LDAP_OPT_X_TLS_HARD;
413         else
414                 inst->tls_mode = 0;
415         inst->reply_item_map = NULL;
416         inst->check_item_map = NULL;
417         inst->conns = NULL;
418         inst->failed_conns = 0;
419
420         DEBUG("rlm_ldap: Registering ldap_groupcmp for Ldap-Group");
421         paircompare_register(PW_LDAP_GROUP, PW_USER_NAME, ldap_groupcmp, inst);
422
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                 DEBUG("rlm_ldap: Setting Auth-Type = %s", inst->xlat_name);
1678         }
1679
1680         DEBUG("rlm_ldap: user %s authorized to use remote access",
1681               request->username->vp_strvalue);
1682         ldap_msgfree(result);
1683         ldap_release_conn(conn_id,inst->conns);
1684
1685         return RLM_MODULE_OK;
1686 }
1687
1688 /*****************************************************************************
1689  *
1690  *      Function: rlm_ldap_authenticate
1691  *
1692  *      Purpose: Check the user's password against ldap database
1693  *
1694  *****************************************************************************/
1695 static int ldap_authenticate(void *instance, REQUEST * request)
1696 {
1697         LDAP           *ld_user;
1698         LDAPMessage    *result, *msg;
1699         ldap_instance  *inst = instance;
1700         char           *user_dn, *attrs[] = {"uid", NULL};
1701         char            filter[MAX_FILTER_STR_LEN];
1702         char            basedn[MAX_FILTER_STR_LEN];
1703         int             res;
1704         VALUE_PAIR     *vp_user_dn;
1705         VALUE_PAIR      *module_fmsg_vp;
1706         char            module_fmsg[MAX_STRING_LEN];
1707         LDAP_CONN       *conn;
1708         int             conn_id = -1;
1709 #ifdef NOVELL
1710         char            *err = NULL;
1711 #endif
1712
1713         DEBUG("rlm_ldap: - authenticate");
1714
1715         /*
1716          * Ensure that we're being passed a plain-text password, and not
1717          * anything else.
1718          */
1719
1720         if (!request->username) {
1721                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Name\" is required for authentication.\n");
1722                 return RLM_MODULE_INVALID;
1723         }
1724
1725         if (!request->password){
1726                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Password\" is required for authentication.");
1727                 DEBUG2("  You seem to have set \"Auth-Type := LDAP\" somewhere.");
1728                 DEBUG2("  THAT CONFIGURATION IS WRONG.  DELETE IT.");
1729                 DEBUG2("  YOU ARE PREVENTING THE SERVER FROM WORKING PROPERLY.");
1730                 return RLM_MODULE_INVALID;
1731         }
1732
1733         if(request->password->attribute != PW_PASSWORD) {
1734                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Password\" is required for authentication. Cannot use \"%s\".", request->password->name);
1735                 return RLM_MODULE_INVALID;
1736         }
1737
1738         if (request->password->length == 0) {
1739                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: empty password supplied");
1740                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1741                 pairadd(&request->packet->vps, module_fmsg_vp);
1742                 return RLM_MODULE_INVALID;
1743         }
1744
1745         /*
1746          * Check that we don't have any failed connections. If we do there's no real need
1747          * of runing. Also give it another chance if we have a lot of failed connections.
1748          */
1749         if (inst->failed_conns > MAX_FAILED_CONNS_END)
1750                 inst->failed_conns = 0;
1751         if (inst->failed_conns > MAX_FAILED_CONNS_START){
1752                 inst->failed_conns++;
1753                 return RLM_MODULE_FAIL;
1754         }
1755
1756
1757         DEBUG("rlm_ldap: login attempt by \"%s\" with password \"%s\"",
1758                request->username->vp_strvalue, request->password->vp_strvalue);
1759
1760         while ((vp_user_dn = pairfind(request->config_items,
1761                                       PW_LDAP_USERDN)) == NULL) {
1762                 if (!radius_xlat(filter, sizeof(filter), inst->filter,
1763                                 request, NULL)) {
1764                         radlog (L_ERR, "rlm_ldap: unable to create filter.\n");
1765                         return RLM_MODULE_INVALID;
1766                 }
1767
1768                 if (!radius_xlat(basedn, sizeof(basedn), inst->basedn,
1769                                 request, NULL)) {
1770                         radlog (L_ERR, "rlm_ldap: unable to create basedn.\n");
1771                         return RLM_MODULE_INVALID;
1772                 }
1773
1774                 if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
1775                         radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
1776                         return RLM_MODULE_FAIL;
1777                 }
1778                 if ((res = perform_search(instance, conn, basedn, LDAP_SCOPE_SUBTREE, filter, attrs, &result)) != RLM_MODULE_OK) {
1779                         if (res == RLM_MODULE_NOTFOUND){
1780                                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: User not found");
1781                                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1782                                 pairadd(&request->packet->vps, module_fmsg_vp);
1783                         }
1784                         ldap_release_conn(conn_id,inst->conns);
1785                         return (res);
1786                 }
1787                 if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
1788                         ldap_msgfree(result);
1789                         ldap_release_conn(conn_id,inst->conns);
1790                         return RLM_MODULE_FAIL;
1791                 }
1792                 if ((user_dn = ldap_get_dn(conn->ld, msg)) == NULL) {
1793                         DEBUG("rlm_ldap: ldap_get_dn() failed");
1794                         ldap_msgfree(result);
1795                         ldap_release_conn(conn_id,inst->conns);
1796                         return RLM_MODULE_FAIL;
1797                 }
1798                 ldap_release_conn(conn_id,inst->conns);
1799                 pairadd(&request->config_items, pairmake("Ldap-UserDn", user_dn, T_OP_EQ));
1800                 ldap_memfree(user_dn);
1801                 ldap_msgfree(result);
1802         }
1803
1804         user_dn = vp_user_dn->vp_strvalue;
1805
1806         DEBUG("rlm_ldap: user DN: %s", user_dn);
1807
1808 #ifndef NOVELL
1809         ld_user = ldap_connect(instance, user_dn, request->password->vp_strvalue,
1810                                1, &res, NULL);
1811 #else
1812         
1813         ld_user = ldap_connect(instance, user_dn, request->password->vp_strvalue,
1814                         1, &res, &err);
1815
1816         if(err != NULL){
1817                 /* 'err' contains the LDAP connection error description */
1818                 DEBUG("rlm_ldap: %s", err);
1819                 pairadd(&request->reply->vps, pairmake("Reply-Message", err, T_OP_EQ));
1820                 ldap_memfree((void *)err);
1821         }
1822
1823         /* Don't perform eDirectory APC again after attempting to bind here. */
1824         {
1825                 int apc_attr;
1826                 DICT_ATTR *dattr;
1827                 VALUE_PAIR *vp_apc;
1828
1829                 dattr = dict_attrbyname("eDir-APC");
1830                 apc_attr = dattr->attr;
1831                 vp_apc = pairfind(request->config_items, apc_attr);
1832                 if(vp_apc && vp_apc->vp_strvalue[0] == '2')
1833                         vp_apc->vp_strvalue[0] = '3';
1834         }
1835 #endif
1836
1837         if (ld_user == NULL){
1838                 if (res == RLM_MODULE_REJECT){
1839                         inst->failed_conns = 0;
1840                         snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Bind as user failed");
1841                         module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1842                         pairadd(&request->packet->vps, module_fmsg_vp);
1843                 }
1844                 if (res == RLM_MODULE_FAIL){
1845                         DEBUG("rlm_ldap: ldap_connect() failed");
1846                         inst->failed_conns++;
1847                 }
1848                 return (res);
1849         }
1850
1851         DEBUG("rlm_ldap: user %s authenticated succesfully",
1852               request->username->vp_strvalue);
1853         ldap_unbind_s(ld_user);
1854         inst->failed_conns = 0;
1855
1856         return RLM_MODULE_OK;
1857 }
1858
1859 #ifdef NOVELL
1860 /*****************************************************************************
1861  *
1862  *      Function: rlm_ldap_postauth
1863  *
1864  *      Purpose: Perform eDirectory account policy check and failed-login reporting
1865  *      to eDirectory.
1866  *
1867  *****************************************************************************/
1868 static int ldap_postauth(void *instance, REQUEST * request)
1869 {
1870         int res = RLM_MODULE_FAIL;
1871         int inst_attr, apc_attr;
1872         char password[UNIVERSAL_PASS_LEN];
1873         ldap_instance  *inst = instance;
1874         LDAP_CONN       *conn;
1875         VALUE_PAIR *vp_inst, *vp_apc;
1876         DICT_ATTR *dattr;
1877
1878         dattr = dict_attrbyname("LDAP-Instance");
1879         inst_attr = dattr->attr;
1880         dattr = dict_attrbyname("eDir-APC");
1881         apc_attr = dattr->attr;
1882
1883         vp_inst = pairfind(request->config_items, inst_attr);
1884
1885         /*
1886          * Check if the password in the config items list is the user's UP which has
1887          * been read in the authorize method of this instance of the LDAP module.
1888          */
1889         if((vp_inst == NULL) || strcmp(vp_inst->vp_strvalue, inst->xlat_name))
1890                 return RLM_MODULE_NOOP;
1891
1892         vp_apc = pairfind(request->config_items, apc_attr);
1893
1894         switch(vp_apc->vp_strvalue[0]){
1895                 case '1':
1896                         /* Account policy check not enabled */
1897                 case '3':
1898                         /* Account policy check has been completed */
1899                         res = RLM_MODULE_NOOP;
1900                         break;
1901                 case '2':
1902                         {
1903                                 int err, conn_id = -1;
1904                                 char *error_msg = NULL;
1905                                 VALUE_PAIR *vp_fdn, *vp_pwd;
1906                                 DICT_ATTR *da;
1907
1908                                 if (request->reply->code == PW_AUTHENTICATION_REJECT) {
1909                                   /* Bind to eDirectory as the RADIUS user with a wrong password. */
1910                                   vp_pwd = pairfind(request->config_items, PW_PASSWORD);
1911                                   strcpy(password, vp_pwd->vp_strvalue);
1912                                   if (strlen(password) > 0) {
1913                                           if (password[0] != 'a') {
1914                                                   password[0] = 'a';
1915                                           } else {
1916                                                   password[0] = 'b';
1917                                           }
1918                                   } else {
1919                                           strcpy(password, "dummy_password");
1920                                   }
1921                                   res = RLM_MODULE_REJECT;
1922                                 } else {
1923                                         /* Bind to eDirectory as the RADIUS user using the user's UP */
1924                                         vp_pwd = pairfind(request->config_items, PW_PASSWORD);
1925                                         if (vp_pwd == NULL) {
1926                                                 DEBUG("rlm_ldap: User's Universal Password not in config items list.");
1927                                                 return RLM_MODULE_FAIL;
1928                                         }
1929                                         strcpy(password, vp_pwd->vp_strvalue);
1930                                 }
1931
1932                                 if ((da = dict_attrbyname("Ldap-UserDn")) == NULL) {
1933                                         DEBUG("rlm_ldap: Attribute for user FDN not found in dictionary. Unable to proceed");
1934                                         return RLM_MODULE_FAIL;
1935                                 }
1936                                 
1937                                 vp_fdn = pairfind(request->packet->vps, da->attr);
1938                                 if (vp_fdn == NULL) {
1939                                         DEBUG("rlm_ldap: User's FQDN not in config items list.");
1940                                         return RLM_MODULE_FAIL;
1941                                 }
1942                                 
1943                                 if ((conn_id = ldap_get_conn(inst->apc_conns, &conn, inst)) == -1){
1944                                         radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
1945                                         return RLM_MODULE_FAIL;
1946                                 }
1947
1948                                 /*
1949                                  *      If there is an existing LDAP
1950                                  *      connection to the directory,
1951                                  *      bind over it. Otherwise,
1952                                  *      establish a new connection.
1953                                  */
1954                         postauth_reconnect:
1955                                 if (!conn->bound || conn->ld == NULL) {
1956                                         DEBUG2("rlm_ldap: attempting LDAP reconnection");
1957                                         if (conn->ld){
1958                                                 DEBUG2("rlm_ldap: closing existing LDAP connection");
1959                                                 ldap_unbind_s(conn->ld);
1960                                         }
1961                                         if ((conn->ld = ldap_connect(instance, (char *)vp_fdn->vp_strvalue, password, 0, &res, &error_msg)) == NULL) {
1962                                                 radlog(L_ERR, "rlm_ldap: eDirectory account policy check failed.");
1963                                                 
1964                                                 if (error_msg != NULL) {
1965                                                         DEBUG("rlm_ldap: %s", error_msg);
1966                                                         pairadd(&request->reply->vps, pairmake("Reply-Message", error_msg, T_OP_EQ));
1967                                                         ldap_memfree((void *)error_msg);
1968                                                 }
1969                                                 
1970                                                 vp_apc->vp_strvalue[0] = '3';
1971                                                 ldap_release_conn(conn_id, inst->apc_conns);
1972                                                 return RLM_MODULE_REJECT;
1973                                         }
1974                                         conn->bound = 1;
1975                                 } else if((err = ldap_simple_bind_s(conn->ld, (char *)vp_fdn->vp_strvalue, password)) != LDAP_SUCCESS) {
1976                                         if (err == LDAP_SERVER_DOWN) {
1977                                                 conn->bound = 0;
1978                                                 goto postauth_reconnect;
1979                                         }
1980                                         DEBUG("rlm_ldap: eDirectory account policy check failed.");
1981                                         ldap_get_option(conn->ld, LDAP_OPT_ERROR_STRING, &error_msg);
1982                                         if (error_msg != NULL) {
1983                                                 DEBUG("rlm_ldap: %s", error_msg);
1984                                                 pairadd(&request->reply->vps, pairmake("Reply-Message", error_msg, T_OP_EQ));
1985                                                 ldap_memfree((void *)error_msg);
1986                                         }
1987                                         vp_apc->vp_strvalue[0] = '3';
1988                                         ldap_release_conn(conn_id, inst->apc_conns);
1989                                         return RLM_MODULE_REJECT;
1990                                 }
1991                                 vp_apc->vp_strvalue[0] = '3';
1992                                 ldap_release_conn(conn_id, inst->apc_conns);
1993                                 return RLM_MODULE_OK;
1994                         }
1995         }
1996         return res;
1997 }
1998 #endif
1999
2000 static LDAP *ldap_connect(void *instance, const char *dn, const char *password,
2001                           int auth, int *result, char **err)
2002 {
2003         ldap_instance  *inst = instance;
2004         LDAP           *ld = NULL;
2005         int             msgid, rc, ldap_version;
2006         int             ldap_errno = 0;
2007         LDAPMessage    *res;
2008
2009         if (inst->is_url){
2010 #ifdef HAVE_LDAP_INITIALIZE
2011                 DEBUG("rlm_ldap: (re)connect to %s, authentication %d", inst->server, auth);
2012                 if (ldap_initialize(&ld, inst->server) != LDAP_SUCCESS) {
2013                         radlog(L_ERR, "rlm_ldap: ldap_initialize() failed");
2014                         *result = RLM_MODULE_FAIL;
2015                         return (NULL);
2016                 }
2017 #endif
2018         } else {
2019                 DEBUG("rlm_ldap: (re)connect to %s:%d, authentication %d", inst->server, inst->port, auth);
2020                 if ((ld = ldap_init(inst->server, inst->port)) == NULL) {
2021                         radlog(L_ERR, "rlm_ldap: ldap_init() failed");
2022                         *result = RLM_MODULE_FAIL;
2023                         return (NULL);
2024                 }
2025         }
2026         if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT,
2027                             (void *) &(inst->net_timeout)) != LDAP_OPT_SUCCESS) {
2028                 radlog(L_ERR, "rlm_ldap: Could not set LDAP_OPT_NETWORK_TIMEOUT %ld.%ld", inst->net_timeout.tv_sec, inst->net_timeout.tv_usec);
2029         }
2030
2031         if (ldap_set_option(ld, LDAP_OPT_TIMELIMIT,
2032                             (void *) &(inst->timelimit)) != LDAP_OPT_SUCCESS) {
2033                 radlog(L_ERR, "rlm_ldap: Could not set LDAP_OPT_TIMELIMIT %d", inst->timelimit);
2034         }
2035
2036         if (inst->ldap_debug && ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &(inst->ldap_debug)) != LDAP_OPT_SUCCESS) {
2037                 radlog(L_ERR, "rlm_ldap: Could not set LDAP_OPT_DEBUG_LEVEL %d", inst->ldap_debug);
2038         }
2039
2040         ldap_version = LDAP_VERSION3;
2041         if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION,
2042                             &ldap_version) != LDAP_OPT_SUCCESS) {
2043                 radlog(L_ERR, "rlm_ldap: Could not set LDAP version to V3");
2044         }
2045
2046 #ifdef HAVE_LDAP_START_TLS
2047         if (inst->tls_mode) {
2048                 DEBUG("rlm_ldap: setting TLS mode to %d", inst->tls_mode);
2049                 if (ldap_set_option(ld, LDAP_OPT_X_TLS,
2050                                     (void *) &(inst->tls_mode)) != LDAP_OPT_SUCCESS) {
2051                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2052                         radlog(L_ERR, "rlm_ldap: could not set LDAP_OPT_X_TLS option %s", ldap_err2string(ldap_errno));
2053                 }
2054         }
2055
2056         if (inst->tls_cacertfile != NULL) {
2057                 DEBUG("rlm_ldap: setting TLS CACert File to %s", inst->tls_cacertfile);
2058
2059                 if ( ldap_set_option( NULL, LDAP_OPT_X_TLS_CACERTFILE,
2060                                       (void *) inst->tls_cacertfile )
2061                      != LDAP_OPT_SUCCESS) {
2062                         radlog(L_ERR, "rlm_ldap: could not set "
2063                                "LDAP_OPT_X_TLS_CACERTFILE option to %s", inst->tls_cacertfile);
2064                 }
2065         }
2066         
2067         if (inst->tls_cacertdir != NULL) {
2068                 DEBUG("rlm_ldap: setting TLS CACert Directory to %s", inst->tls_cacertdir);
2069                 
2070                 if ( ldap_set_option( NULL, LDAP_OPT_X_TLS_CACERTDIR,
2071                                       (void *) inst->tls_cacertdir )
2072                      != LDAP_OPT_SUCCESS) {
2073                         radlog(L_ERR, "rlm_ldap: could not set "
2074                                "LDAP_OPT_X_TLS_CACERTDIR option to %s", inst->tls_cacertdir);
2075                 }
2076         }
2077
2078         if (strcmp(TLS_DEFAULT_VERIFY, inst->tls_require_cert ) != 0 ) {
2079                 DEBUG("rlm_ldap: setting TLS Require Cert to %s",
2080                       inst->tls_require_cert);
2081         }
2082
2083
2084 #ifdef HAVE_LDAP_INT_TLS_CONFIG
2085         if (ldap_int_tls_config(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT,
2086                                 (inst->tls_require_cert)) != LDAP_OPT_SUCCESS) {
2087                 radlog(L_ERR, "rlm_ldap: could not set "
2088                        "LDAP_OPT_X_TLS_REQUIRE_CERT option to %s",
2089                        inst->tls_require_cert);
2090         }
2091 #endif
2092
2093         if (inst->tls_certfile != NULL) {
2094                 DEBUG("rlm_ldap: setting TLS Cert File to %s", inst->tls_certfile);
2095
2096                 if (ldap_set_option(NULL, LDAP_OPT_X_TLS_CERTFILE,
2097                                     (void *) inst->tls_certfile)
2098                     != LDAP_OPT_SUCCESS) {
2099                         radlog(L_ERR, "rlm_ldap: could not set "
2100                                "LDAP_OPT_X_TLS_CERTFILE option to %s",
2101                                inst->tls_certfile);
2102                 }
2103         }
2104         
2105         if (inst->tls_keyfile != NULL) {
2106                 DEBUG("rlm_ldap: setting TLS Key File to %s",
2107                       inst->tls_keyfile);
2108                 
2109                 if ( ldap_set_option( NULL, LDAP_OPT_X_TLS_KEYFILE,
2110                                       (void *) inst->tls_keyfile )
2111                      != LDAP_OPT_SUCCESS) {
2112                         radlog(L_ERR, "rlm_ldap: could not set "
2113                                "LDAP_OPT_X_TLS_KEYFILE option to %s",
2114                                inst->tls_keyfile);
2115                 }
2116         }
2117         
2118         if (inst->tls_randfile != NULL) {
2119                 DEBUG("rlm_ldap: setting TLS Key File to %s",
2120                       inst->tls_randfile);
2121                 
2122                 if (ldap_set_option(NULL, LDAP_OPT_X_TLS_RANDOM_FILE,
2123                                     (void *) inst->tls_randfile)
2124                     != LDAP_OPT_SUCCESS) {
2125                         radlog(L_ERR, "rlm_ldap: could not set "
2126                                "LDAP_OPT_X_TLS_RANDOM_FILE option to %s",
2127                                inst->tls_randfile);
2128                 }
2129         }
2130
2131         if (inst->start_tls) {
2132                 DEBUG("rlm_ldap: starting TLS");
2133                 rc = ldap_start_tls_s(ld, NULL, NULL);
2134                 if (rc != LDAP_SUCCESS) {
2135                         DEBUG("rlm_ldap: ldap_start_tls_s()");
2136                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER,
2137                                         &ldap_errno);
2138                         radlog(L_ERR, "rlm_ldap: could not start TLS %s",
2139                                ldap_err2string(ldap_errno));
2140                         *result = RLM_MODULE_FAIL;
2141                         ldap_unbind_s(ld);
2142                         return (NULL);
2143                 }
2144         }
2145 #endif /* HAVE_LDAP_START_TLS */
2146
2147         if (inst->is_url){
2148                 DEBUG("rlm_ldap: bind as %s/%s to %s",
2149                       dn, password, inst->server);
2150         } else {
2151                 DEBUG("rlm_ldap: bind as %s/%s to %s:%d",
2152                       dn, password, inst->server, inst->port);
2153         }
2154
2155         msgid = ldap_bind(ld, dn, password,LDAP_AUTH_SIMPLE);
2156         if (msgid == -1) {
2157                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2158                 if(err != NULL){
2159                         ldap_get_option(ld, LDAP_OPT_ERROR_STRING, err);
2160                 }
2161                 if (inst->is_url) {
2162                         radlog(L_ERR, "rlm_ldap: %s bind to %s failed: %s",
2163                                 dn, inst->server, ldap_err2string(ldap_errno));
2164                 } else {
2165                         radlog(L_ERR, "rlm_ldap: %s bind to %s:%d failed: %s",
2166                                 dn, inst->server, inst->port,
2167                                 ldap_err2string(ldap_errno));
2168                 }
2169                 *result = RLM_MODULE_FAIL;
2170                 ldap_unbind_s(ld);
2171                 return (NULL);
2172         }
2173         DEBUG("rlm_ldap: waiting for bind result ...");
2174
2175         rc = ldap_result(ld, msgid, 1, &(inst->timeout), &res);
2176
2177         if (rc < 1) {
2178                 DEBUG("rlm_ldap: ldap_result()");
2179                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
2180                 if(err != NULL){
2181                         ldap_get_option(ld, LDAP_OPT_ERROR_STRING, err);
2182                 }
2183                 if (inst->is_url) {
2184                         radlog(L_ERR, "rlm_ldap: %s bind to %s failed: %s",
2185                                 dn, inst->server, (rc == 0) ? "timeout" : ldap_err2string(ldap_errno));
2186                 } else {
2187                         radlog(L_ERR, "rlm_ldap: %s bind to %s:%d failed: %s",
2188                                dn, inst->server, inst->port,
2189                                 (rc == 0) ? "timeout" : ldap_err2string(ldap_errno));
2190                 }
2191                 *result = RLM_MODULE_FAIL;
2192                 ldap_unbind_s(ld);
2193                 return (NULL);
2194         }
2195
2196         ldap_errno = ldap_result2error(ld, res, 1);
2197         switch (ldap_errno) {
2198         case LDAP_SUCCESS:
2199                 DEBUG("rlm_ldap: Bind was successful");
2200                 *result = RLM_MODULE_OK;
2201                 break;
2202
2203         case LDAP_INVALID_CREDENTIALS:
2204                 if (auth){
2205                         DEBUG("rlm_ldap: Bind failed with invalid credentials");
2206                         *result = RLM_MODULE_REJECT;
2207                 } else {
2208                         radlog(L_ERR, "rlm_ldap: LDAP login failed: check identity, password settings in ldap section of radiusd.conf");
2209                         *result = RLM_MODULE_FAIL;
2210                 }
2211                 if(err != NULL){
2212                         ldap_get_option(ld, LDAP_OPT_ERROR_STRING, err);
2213                 }
2214                 break;
2215
2216         default:
2217                 if (inst->is_url) {
2218                         radlog(L_ERR,"rlm_ldap: %s bind to %s failed %s",
2219                                 dn, inst->server, ldap_err2string(ldap_errno));
2220                 } else {
2221                         radlog(L_ERR,"rlm_ldap: %s bind to %s:%d failed %s",
2222                                 dn, inst->server, inst->port,
2223                                 ldap_err2string(ldap_errno));
2224                 }
2225                 *result = RLM_MODULE_FAIL;
2226                 if(err != NULL){
2227                         ldap_get_option(ld, LDAP_OPT_ERROR_STRING, err);
2228                 }
2229         }
2230
2231         if (*result != RLM_MODULE_OK) {
2232                 ldap_unbind_s(ld);
2233                 ld = NULL;
2234         }
2235         return ld;
2236 }
2237
2238 /*****************************************************************************
2239  *
2240  *      Detach from the LDAP server and cleanup internal state.
2241  *
2242  *****************************************************************************/
2243 static int
2244 ldap_detach(void *instance)
2245 {
2246         ldap_instance  *inst = instance;
2247         TLDAP_RADIUS *pair, *nextpair;
2248
2249         if (inst->server)
2250                 free((char *) inst->server);
2251         if (inst->login)
2252                 free((char *) inst->login);
2253         if (inst->password)
2254                 free((char *) inst->password);
2255         if (inst->basedn)
2256                 free((char *) inst->basedn);
2257         if (inst->dictionary_mapping)
2258                 free(inst->dictionary_mapping);
2259         if (inst->filter)
2260                 free((char *) inst->filter);
2261         if (inst->base_filter)
2262                 free((char *) inst->base_filter);
2263         if (inst->passwd_hdr)
2264                 free((char *) inst->passwd_hdr);
2265         if (inst->passwd_attr)
2266                 free((char *) inst->passwd_attr);
2267         if (inst->groupname_attr)
2268                 free((char *) inst->groupname_attr);
2269         if (inst->groupmemb_filt)
2270                 free((char *) inst->groupmemb_filt);
2271         if (inst->groupmemb_attr)
2272                 free((char *) inst->groupmemb_attr);
2273         if (inst->access_attr)
2274                 free((char *) inst->access_attr);
2275         if (inst->profile_attr)
2276                 free((char *) inst->profile_attr);
2277
2278         if (inst->conns) {
2279                 int i;
2280                 
2281                 for (i = 0;i < inst->num_conns; i++) {
2282                         if (inst->conns[i].ld){
2283                                 ldap_unbind_s(inst->conns[i].ld);
2284                         }
2285                         pthread_mutex_destroy(&inst->conns[i].mutex);
2286                 }
2287                 free(inst->conns);
2288         }
2289
2290 #ifdef NOVELL
2291         if (inst->apc_conns){ 
2292                 int i;
2293
2294                 for (i = 0; i < inst->num_conns; i++) {
2295                         if (inst->apc_conns[i].ld){
2296                                 ldap_unbind_s(inst->apc_conns[i].ld);
2297                         }
2298                         pthread_mutex_destroy(&inst->apc_conns[i].mutex);
2299                 }
2300                 free(inst->apc_conns);
2301         }
2302 #endif
2303
2304         pair = inst->check_item_map;
2305
2306         while (pair != NULL) {
2307                 nextpair = pair->next;
2308                 free(pair->attr);
2309                 free(pair->radius_attr);
2310                 free(pair);
2311                 pair = nextpair;
2312         }
2313
2314         pair = inst->reply_item_map;
2315
2316         while (pair != NULL) {
2317                 nextpair = pair->next;
2318                 free(pair->attr);
2319                 free(pair->radius_attr);
2320                 free(pair);
2321                 pair = nextpair;
2322         }
2323
2324         if (inst->atts)
2325                 free(inst->atts);
2326
2327         paircompare_unregister(PW_LDAP_GROUP, ldap_groupcmp);
2328         xlat_unregister(inst->xlat_name,ldap_xlat);
2329         free(inst->xlat_name);
2330
2331         free(inst);
2332
2333         return 0;
2334 }
2335
2336
2337 #ifdef FIELDCPY
2338 static void
2339 fieldcpy(char *string, char **uptr)
2340 {
2341         char           *ptr;
2342
2343         ptr = *uptr;
2344         while (*ptr == ' ' || *ptr == '\t') {
2345                 ptr++;
2346         }
2347         if (*ptr == '"') {
2348                 ptr++;
2349                 while (*ptr != '"' && *ptr != '\0' && *ptr != '\n') {
2350                         *string++ = *ptr++;
2351                 }
2352                 *string = '\0';
2353                 if (*ptr == '"') {
2354                         ptr++;
2355                 }
2356                 *uptr = ptr;
2357                 return;
2358         }
2359         while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0' && *ptr != '\n' &&
2360                *ptr != '=' && *ptr != ',') {
2361                 *string++ = *ptr++;
2362         }
2363         *string = '\0';
2364         *uptr = ptr;
2365         return;
2366 }
2367 #endif
2368
2369 /*
2370  *      Copied from src/lib/token.c
2371  */
2372 static const LRAD_NAME_NUMBER tokens[] = {
2373         { "=~", T_OP_REG_EQ,    }, /* order is important! */
2374         { "!~", T_OP_REG_NE,    },
2375         { "{",  T_LCBRACE,      },
2376         { "}",  T_RCBRACE,      },
2377         { "(",  T_LBRACE,       },
2378         { ")",  T_RBRACE,       },
2379         { ",",  T_COMMA,        },
2380         { "+=", T_OP_ADD,       },
2381         { "-=", T_OP_SUB,       },
2382         { ":=", T_OP_SET,       },
2383         { "=*", T_OP_CMP_TRUE,  },
2384         { "!*", T_OP_CMP_FALSE, },
2385         { "==", T_OP_CMP_EQ,    },
2386         { "=",  T_OP_EQ,        },
2387         { "!=", T_OP_NE,        },
2388         { ">=", T_OP_GE,        },
2389         { ">",  T_OP_GT,        },
2390         { "<=", T_OP_LE,        },
2391         { "<",  T_OP_LT,        },
2392         { NULL, 0}
2393 };
2394
2395 /*****************************************************************************
2396  *      Get RADIUS attributes from LDAP object
2397  *      ( according to draft-adoba-radius-05.txt
2398  *        <http://www.ietf.org/internet-drafts/draft-adoba-radius-05.txt> )
2399  *
2400  *****************************************************************************/
2401 static VALUE_PAIR *ldap_pairget(LDAP *ld, LDAPMessage *entry,
2402                                 TLDAP_RADIUS *item_map,
2403                                 VALUE_PAIR **pairs, int is_check)
2404 {
2405         char          **vals;
2406         int             vals_count;
2407         int             vals_idx;
2408         char           *ptr;
2409         char           *value;
2410         TLDAP_RADIUS   *element;
2411         LRAD_TOKEN      token, operator;
2412         int             is_generic_attribute;
2413         char            buf[MAX_STRING_LEN];
2414         VALUE_PAIR     *pairlist = NULL;
2415         VALUE_PAIR     *newpair = NULL;
2416         char            do_xlat = FALSE;
2417
2418         /*
2419          *      check if there is a mapping from this LDAP attribute
2420          *      to a RADIUS attribute
2421          */
2422         for (element = item_map; element != NULL; element = element->next) {
2423                 /*
2424                  *      No mapping, skip it.
2425                  */
2426                 if ((vals = ldap_get_values(ld,entry,element->attr)) == NULL)
2427                         continue;
2428
2429                 /*
2430                  *      Check whether this is a one-to-one-mapped ldap
2431                  *      attribute or a generic attribute and set flag
2432                  *      accordingly.
2433                  */
2434                 if (strcasecmp(element->radius_attr, GENERIC_ATTRIBUTE_ID)==0)
2435                         is_generic_attribute = 1;
2436                 else
2437                         is_generic_attribute = 0;
2438
2439                 /*
2440                  *      Find out how many values there are for the
2441                  *      attribute and extract all of them.
2442                  */
2443                 vals_count = ldap_count_values(vals);
2444
2445                 for (vals_idx = 0; vals_idx < vals_count; vals_idx++) {
2446                         value = vals[vals_idx];
2447
2448                         if (is_generic_attribute) {
2449                                 /*
2450                                  *      This is a generic attribute.
2451                                  */
2452                                 LRAD_TOKEN dummy; /* makes pairread happy */
2453
2454                                 /* not sure if using pairread here is ok ... */
2455                                 if ( (newpair = pairread(&value, &dummy)) != NULL) {
2456                                         DEBUG("rlm_ldap: extracted attribute %s from generic item %s",
2457                                               newpair->name, vals[vals_idx]);
2458                                         pairadd(&pairlist, newpair);
2459                                 } else {
2460                                         radlog(L_ERR, "rlm_ldap: parsing %s failed: %s",
2461                                                element->attr, vals[vals_idx]);
2462                                 }
2463                         } else {
2464                                 /*
2465                                  *      This is a one-to-one-mapped attribute
2466                                  */
2467                                 ptr = value;
2468                                 operator = gettoken(&ptr, buf, sizeof(buf));
2469                                 if (operator < T_EQSTART || operator > T_EQEND) {
2470                                         /* no leading operator found */
2471                                         if (element->operator != T_OP_INVALID)
2472                                                 operator = element->operator;
2473                                         else if (is_check)
2474                                                 operator = T_OP_CMP_EQ;
2475                                         else
2476                                                 operator = T_OP_EQ;
2477                                 } else {
2478                                         /* the value is after the operator */
2479                                         value = ptr;
2480                                 }
2481
2482                                 /*
2483                                  *      Do xlat if the *entire* string
2484                                  *      is quoted.
2485                                  */
2486                                 if ((value[0] == '\'' || value[0] == '"' ||
2487                                      value[0] == '`') &&
2488                                     (value[0] == value[strlen(value)-1])) {
2489                                         ptr = value;
2490                                         token = gettoken(&ptr, buf, sizeof(buf));
2491                                         switch (token) {
2492                                         /* take the unquoted string */
2493                                         case T_SINGLE_QUOTED_STRING:
2494                                         case T_DOUBLE_QUOTED_STRING:
2495                                                 value = buf;
2496                                                 break;
2497
2498                                         /* the value will be xlat'ed later */
2499                                         case T_BACK_QUOTED_STRING:
2500                                                 value = buf;
2501                                                 do_xlat = TRUE;
2502                                                 break;
2503
2504                                         /* keep the original string */
2505                                         default:
2506                                                 break;
2507                                         }
2508                                 }
2509                                 if (value[0] == '\0') {
2510                                         DEBUG("rlm_ldap: Attribute %s has no value", element->attr);
2511                                         continue;
2512                                 }
2513
2514                                 DEBUG("rlm_ldap: Adding LDAP attribute %s as RADIUS attribute %s %s %s",
2515                                       element->attr, element->radius_attr,
2516                                       lrad_int2str(tokens, operator, "?"),
2517                                       value);
2518
2519                                 /*
2520                                  *      Create the pair.
2521                                  */
2522                                 newpair = pairmake(element->radius_attr,
2523                                                    do_xlat ? NULL : value,
2524                                                    operator);
2525                                 if (newpair == NULL) {
2526                                         radlog(L_ERR, "rlm_ldap: Failed to create the pair: %s", librad_errstr);
2527                                         continue;
2528                                 }
2529                                 if (do_xlat) {
2530                                         newpair->flags.do_xlat = 1;
2531                                         strNcpy(newpair->vp_strvalue, buf,
2532                                                 sizeof(newpair->vp_strvalue));
2533                                         newpair->length = 0;
2534                                 }
2535
2536                                 /*
2537                                  *      Add the pair into the packet.
2538                                  */
2539                                 if (!vals_idx){
2540                                         pairdelete(pairs, newpair->attribute);
2541                                 }
2542                                 pairadd(&pairlist, newpair);
2543                         }
2544                 }
2545                 ldap_value_free(vals);
2546         }
2547
2548         return (pairlist);
2549 }
2550
2551 /* globally exported name */
2552 module_t rlm_ldap = {
2553         RLM_MODULE_INIT,
2554         "LDAP",
2555         RLM_TYPE_THREAD_SAFE,   /* type: reserved        */
2556         ldap_instantiate,       /* instantiation         */
2557         ldap_detach,            /* detach                */
2558         {
2559                 ldap_authenticate,      /* authentication        */
2560                 ldap_authorize,         /* authorization         */
2561                 NULL,                   /* preaccounting         */
2562                 NULL,                   /* accounting            */
2563                 NULL,                   /* checksimul            */
2564                 NULL,                   /* pre-proxy             */
2565                 NULL,                   /* post-proxy            */
2566 #ifdef NOVELL
2567                 ldap_postauth           /* post-auth             */
2568 #else
2569                 NULL
2570 #endif
2571         },
2572 };