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