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