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