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