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