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