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