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