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