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