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