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