Store the LDAP-UserDN attribute in the check item list not in the incoming request
[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  * Jul 2004, Kostas Kalevras <kkalev@noc.ntua.gr>
160  *      - Don't core dump when ldap.attrmap contains only one reply item
161  * Sep 2004, Kostas Kalevras <kkalev@noc.ntua.gr>
162  *      - Store the LDAP-UserDN attribute in the check item list not in the incoming request
163  */
164 static const char rcsid[] = "$Id$";
165
166 #include "autoconf.h"
167
168 #include        <sys/types.h>
169 #include        <sys/socket.h>
170 #include        <sys/time.h>
171 #include        <netinet/in.h>
172
173 #include        <stdio.h>
174 #include        <stdlib.h>
175 #include        <netdb.h>
176 #include        <pwd.h>
177 #include        <time.h>
178 #include        <ctype.h>
179 #include        <string.h>
180
181 #include        <lber.h>
182 #include        <ldap.h>
183
184 #include        <errno.h>
185 #include        <unistd.h>
186 #include        <pthread.h>
187
188 #include        "libradius.h"
189 #include        "radiusd.h"
190 #include        "conffile.h"
191 #include        "modules.h"
192 #include        "rad_assert.h"
193
194 #ifndef HAVE_PTHREAD_H
195 /*
196  *      This is a lot simpler than putting ifdef's around
197  *      every use of the pthread functions.
198  */
199 #define pthread_mutex_lock(a)
200 #define pthread_mutex_unlock(a)
201 #define pthread_mutex_init(a,b)
202 #define pthread_mutex_destroy(a)
203 #endif
204
205
206 #define MAX_FILTER_STR_LEN      1024
207 #define TIMELIMIT 5
208
209 /*
210  * These are used in case ldap_search returns LDAP_SERVER_DOWN
211  * In that case we do conn->failed_conns++ and then check it:
212  * If conn->failed_conns <= MAX_FAILED_CONNS_START then we try
213  * to reconnect
214  * conn->failed_conns is also checked on entrance in perform_search:
215  * If conn->failed_conns > MAX_FAILED_CONNS_START then we don't
216  * try to do anything and we just do conn->failed_conns++ and
217  * return RLM_MODULE_FAIL
218  * if conn->failed_conns >= MAX_FAILED_CONNS_END then we give it
219  * another chance and we set it to MAX_FAILED_CONNS_RESTART and
220  * try to reconnect.
221  *
222  *
223  * We are assuming that the majority of the LDAP_SERVER_DOWN cases
224  * will either be an ldap connection timeout or a temporary ldap
225  * server problem.
226  * As a result we make a few attempts to reconnect hoping that the problem
227  * will soon go away. If it does not go away then we just return
228  * RLM_MODULE_FAIL on entrance in perform_search until conn->failed_conns
229  * gets to MAX_FAILED_CONNS_END. After that we give it one more chance by
230  * going back to MAX_FAILED_CONNS_RESTART
231  *
232  */
233
234 #define MAX_FAILED_CONNS_END            20
235 #define MAX_FAILED_CONNS_RESTART        4
236 #define MAX_FAILED_CONNS_START          5
237
238 /* linked list of mappings between RADIUS attributes and LDAP attributes */
239 struct TLDAP_RADIUS {
240         char*                 attr;
241         char*                 radius_attr;
242         struct TLDAP_RADIUS*  next;
243 };
244 typedef struct TLDAP_RADIUS TLDAP_RADIUS;
245
246 typedef struct ldap_conn {
247         LDAP            *ld;
248         char            bound;
249         char            locked;
250         int             failed_conns;
251         pthread_mutex_t mutex;
252 } LDAP_CONN;
253
254 typedef struct {
255         char           *server;
256         int             port;
257         int             timelimit;
258         struct timeval  net_timeout;
259         struct timeval  timeout;
260         int             debug;
261         int             tls_mode;
262         int             start_tls;
263         int             num_conns;
264         int             do_comp;
265         int             do_xlat;
266         int             default_allow;
267         int             failed_conns;
268         int             is_url;
269         char           *login;
270         char           *password;
271         char           *filter;
272         char           *base_filter;
273         char           *basedn;
274         char           *default_profile;
275         char           *profile_attr;
276         char           *access_attr;
277         char           *passwd_hdr;
278         char           *passwd_attr;
279         char           *dictionary_mapping;
280         char           *groupname_attr;
281         char           *groupmemb_filt;
282         char           *groupmemb_attr;
283         char            **atts;
284         TLDAP_RADIUS   *check_item_map;
285         TLDAP_RADIUS   *reply_item_map;
286         LDAP_CONN       *conns;
287         int             ldap_debug; /* Debug flag for LDAP SDK */
288         char            *xlat_name; /* name used to xlat */
289         char            *tls_cacertfile;
290         char            *tls_cacertdir;
291         char            *tls_certfile;
292         char            *tls_keyfile;
293         char            *tls_randfile;
294         char            *tls_require_cert;
295 }               ldap_instance;
296
297 /* The default setting for TLS Certificate Verification */
298 #define TLS_DEFAULT_VERIFY "allow"
299
300 static CONF_PARSER module_config[] = {
301         {"server", PW_TYPE_STRING_PTR, offsetof(ldap_instance,server), NULL, "localhost"},
302         {"port", PW_TYPE_INTEGER, offsetof(ldap_instance,port), NULL, "389"},
303         /* wait forever on network activity */
304         {"net_timeout", PW_TYPE_INTEGER, offsetof(ldap_instance,net_timeout.tv_sec), NULL, "10"},
305         /* wait forever for search results */
306         {"timeout", PW_TYPE_INTEGER, offsetof(ldap_instance,timeout.tv_sec), NULL, "20"},
307         /* allow server unlimited time for search (server-side limit) */
308         {"timelimit", PW_TYPE_INTEGER, offsetof(ldap_instance,timelimit), NULL, "20"},
309         {"identity", PW_TYPE_STRING_PTR, offsetof(ldap_instance,login), NULL, ""},
310         {"tls_mode", PW_TYPE_BOOLEAN, offsetof(ldap_instance,tls_mode), NULL, "no"},
311         {"start_tls", PW_TYPE_BOOLEAN, offsetof(ldap_instance,start_tls), NULL, "no"},
312         {"tls_cacertfile", PW_TYPE_STRING_PTR, offsetof(ldap_instance,tls_cacertfile), NULL, NULL},
313         {"tls_cacertdir", PW_TYPE_STRING_PTR, offsetof(ldap_instance,tls_cacertdir), NULL, NULL},
314         {"tls_certfile", PW_TYPE_STRING_PTR, offsetof(ldap_instance,tls_certfile), NULL, NULL},
315         {"tls_keyfile", PW_TYPE_STRING_PTR, offsetof(ldap_instance,tls_keyfile), NULL, NULL},
316         {"tls_randfile", PW_TYPE_STRING_PTR, offsetof(ldap_instance,tls_randfile), NULL, NULL},
317         {"tls_require_cert", PW_TYPE_STRING_PTR, offsetof(ldap_instance,tls_require_cert), NULL, TLS_DEFAULT_VERIFY},
318         {"password", PW_TYPE_STRING_PTR, offsetof(ldap_instance,password), NULL, ""},
319         {"basedn", PW_TYPE_STRING_PTR, offsetof(ldap_instance,basedn), NULL, "o=notexist"},
320         {"filter", PW_TYPE_STRING_PTR, offsetof(ldap_instance,filter), NULL, "(uid=%u)"},
321         {"base_filter", PW_TYPE_STRING_PTR, offsetof(ldap_instance,base_filter), NULL, "(objectclass=radiusprofile)"},
322         {"default_profile", PW_TYPE_STRING_PTR, offsetof(ldap_instance,default_profile), NULL, NULL},
323         {"profile_attribute", PW_TYPE_STRING_PTR, offsetof(ldap_instance,profile_attr), NULL, NULL},
324         {"password_header", PW_TYPE_STRING_PTR, offsetof(ldap_instance,passwd_hdr), NULL, NULL},
325         {"password_attribute", PW_TYPE_STRING_PTR, offsetof(ldap_instance,passwd_attr), NULL, NULL},
326         /* LDAP attribute name that controls remote access */
327         {"access_attr", PW_TYPE_STRING_PTR, offsetof(ldap_instance,access_attr), NULL, NULL},
328         /* file with mapping between LDAP and RADIUS attributes */
329         {"groupname_attribute", PW_TYPE_STRING_PTR, offsetof(ldap_instance,groupname_attr), NULL, "cn"},
330         {"groupmembership_filter", PW_TYPE_STRING_PTR, offsetof(ldap_instance,groupmemb_filt), NULL, "(|(&(objectClass=GroupOfNames)(member=%{Ldap-UserDn}))(&(objectClass=GroupOfUniqueNames)(uniquemember=%{Ldap-UserDn})))"},
331         {"groupmembership_attribute", PW_TYPE_STRING_PTR, offsetof(ldap_instance,groupmemb_attr), NULL, NULL},
332         {"dictionary_mapping", PW_TYPE_STRING_PTR, offsetof(ldap_instance,dictionary_mapping), NULL, "${confdir}/ldap.attrmap"},
333         {"ldap_debug", PW_TYPE_INTEGER, offsetof(ldap_instance,ldap_debug), NULL, "0x0000"},
334         {"ldap_connections_number", PW_TYPE_INTEGER, offsetof(ldap_instance,num_conns), NULL, "5"},
335         {"compare_check_items", PW_TYPE_BOOLEAN, offsetof(ldap_instance,do_comp), NULL, "no"},
336         {"access_attr_used_for_allow", PW_TYPE_BOOLEAN, offsetof(ldap_instance,default_allow), NULL, "yes"},
337         {"do_xlat", PW_TYPE_BOOLEAN, offsetof(ldap_instance,do_xlat), NULL, "yes"},
338
339         {NULL, -1, 0, NULL, NULL}
340 };
341
342 #define ld_valid                ld_options.ldo_valid
343 #define LDAP_VALID_SESSION      0x2
344 #define LDAP_VALID(ld)  ( (ld)->ld_valid == LDAP_VALID_SESSION )
345
346 #ifdef FIELDCPY
347 static void     fieldcpy(char *, char **);
348 #endif
349 static VALUE_PAIR *ldap_pairget(LDAP *, LDAPMessage *, TLDAP_RADIUS *,VALUE_PAIR **,char);
350 static int ldap_groupcmp(void *, REQUEST *, VALUE_PAIR *, VALUE_PAIR *, VALUE_PAIR *, VALUE_PAIR **);
351 static int ldap_xlat(void *,REQUEST *, char *, char *,int, RADIUS_ESCAPE_STRING);
352 static LDAP    *ldap_connect(void *instance, const char *, const char *, int, int *);
353 static int     read_mappings(ldap_instance* inst);
354
355 static inline int ldap_get_conn(LDAP_CONN *conns,LDAP_CONN **ret,void *instance)
356 {
357         ldap_instance *inst = instance;
358         register int i = 0;
359
360         for(i=0;i<inst->num_conns;i++){
361                 DEBUG("rlm_ldap: ldap_get_conn: Checking Id: %d",i);
362                 if (conns[i].locked == 0 && pthread_mutex_trylock(&(conns[i].mutex)) == 0){
363                         *ret = &conns[i];
364                         conns[i].locked = 1;
365                         DEBUG("rlm_ldap: ldap_get_conn: Got Id: %d",i);
366                         return i;
367                 }
368         }
369
370         return -1;
371 }
372
373 static inline void ldap_release_conn(int i, LDAP_CONN *conns)
374 {
375         DEBUG("rlm_ldap: ldap_release_conn: Release Id: %d",i);
376         conns[i].locked = 0;
377         pthread_mutex_unlock(&(conns[i].mutex));
378 }
379
380 /*************************************************************************
381  *
382  *      Function: rlm_ldap_instantiate
383  *
384  *      Purpose: Uses section of radiusd config file passed as parameter
385  *               to create an instance of the module.
386  *
387  *************************************************************************/
388 static int
389 ldap_instantiate(CONF_SECTION * conf, void **instance)
390 {
391         ldap_instance  *inst;
392         int i = 0;
393         int atts_num = 0;
394         int reply_map_num = 0;
395         int check_map_num = 0;
396         int att_map[3] = {0,0,0};
397         TLDAP_RADIUS *pair;
398         ATTR_FLAGS flags;
399         char *xlat_name;
400
401         inst = rad_malloc(sizeof *inst);
402         if (!inst) {
403                 return -1;
404         }
405         memset(inst, 0, sizeof(*inst));
406
407         if (cf_section_parse(conf, inst, module_config) < 0) {
408                 free(inst);
409                 return -1;
410         }
411
412         if (inst->server == NULL) {
413                 radlog(L_ERR, "rlm_ldap: missing 'server' directive.");
414                 free(inst);
415                 return -1;
416         }
417         inst->is_url = 0;
418         if (ldap_is_ldap_url(inst->server)){
419 #ifdef HAVE_LDAP_INITIALIZE
420                 inst->is_url = 1;
421                 inst->port = 0;
422 #else
423                 radlog(L_ERR, "rlm_ldap: 'server' directive is in URL form but ldap_initialize() is not available.");
424                 free(inst);
425                 return -1;
426 #endif
427         }
428
429         inst->timeout.tv_usec = 0;
430         inst->net_timeout.tv_usec = 0;
431         /* workaround for servers which support LDAPS but not START TLS */
432         if(inst->port == LDAPS_PORT || inst->tls_mode)
433                 inst->tls_mode = LDAP_OPT_X_TLS_HARD;
434         else
435                 inst->tls_mode = 0;
436         inst->reply_item_map = NULL;
437         inst->check_item_map = NULL;
438         inst->conns = NULL;
439         inst->failed_conns = 0;
440
441         DEBUG("rlm_ldap: Registering ldap_groupcmp for Ldap-Group");
442         paircompare_register(PW_LDAP_GROUP, PW_USER_NAME, ldap_groupcmp, inst);
443
444         xlat_name = cf_section_name2(conf);
445         if (xlat_name != NULL){
446                 char *group_name;
447                 DICT_ATTR *dattr;
448
449                 /*
450                  * Allocate room for <instance>-Ldap-Group
451                  */
452                 group_name = malloc((strlen(xlat_name) + 1 + 11) * sizeof(char));
453                 rad_assert(group_name != NULL);
454                 sprintf(group_name,"%s-Ldap-Group",xlat_name);
455                 DEBUG("rlm_ldap: Creating new attribute %s",group_name);
456                 dict_addattr(group_name, 0, PW_TYPE_STRING, -1, flags);
457                 dattr = dict_attrbyname(group_name);
458                 if (dattr == NULL){
459                         radlog(L_ERR, "rlm_ldap: Failed to create attribute %s",group_name);
460                         free(inst);
461                         return -1;
462                 }
463                 DEBUG("rlm_ldap: Registering ldap_groupcmp for %s",group_name);
464                 paircompare_register(dattr->attr, PW_USER_NAME, ldap_groupcmp, inst);
465         }
466         else {
467                 xlat_name = cf_section_name1(conf);
468                 rad_assert(xlat_name != NULL); /* or all hell breaks loose */
469         }
470         inst->xlat_name = strdup(xlat_name);
471         DEBUG("rlm_ldap: Registering ldap_xlat with xlat_name %s",xlat_name);
472         xlat_register(xlat_name,ldap_xlat,inst);
473
474         if (inst->num_conns <= 0){
475                 radlog(L_ERR, "rlm_ldap: Invalid ldap connections number passed.");
476                 free(inst);
477                 return -1;
478         }
479         inst->conns = (LDAP_CONN *)malloc(sizeof(LDAP_CONN)*inst->num_conns);
480         if (inst->conns == NULL){
481                 radlog(L_ERR, "rlm_ldap: Could not allocate memory. Aborting.");
482                 free(inst);
483                 return -1;
484         }
485         for(;i<inst->num_conns;i++){
486                 inst->conns[i].bound = 0;
487                 inst->conns[i].locked = 0;
488                 inst->conns[i].failed_conns = 0;
489                 inst->conns[i].ld = NULL;
490                 pthread_mutex_init(&inst->conns[i].mutex, NULL);
491         }
492
493         if (read_mappings(inst) != 0) {
494                 radlog(L_ERR, "rlm_ldap: Reading dictionary mappings from file %s failed",
495                        inst->dictionary_mapping);
496                 free(inst);
497                 return -1;
498         }
499         if (inst->check_item_map == NULL && inst->reply_item_map == NULL){
500                 radlog(L_ERR, "rlm_ldap: dictionary mappings file %s did not contain any mappings",
501                         inst->dictionary_mapping);
502                 free(inst);
503                 return -1;
504         }
505
506         pair = inst->check_item_map;
507         while(pair != NULL){
508                 atts_num++;
509                 pair = pair->next;
510         }
511         check_map_num = (atts_num - 1);
512         pair = inst->reply_item_map;
513         while(pair != NULL){
514                 atts_num++;
515                 pair = pair->next;
516         }
517         reply_map_num = (atts_num - 1);
518         if (inst->profile_attr)
519                 atts_num++;
520         if (inst->passwd_attr)
521                 atts_num++;
522         if (inst->access_attr)
523                 atts_num++;
524         inst->atts = (char **)malloc(sizeof(char *)*(atts_num + 1));
525         if (inst->atts == NULL){
526                 radlog(L_ERR, "rlm_ldap: Could not allocate memory. Aborting.");
527                 free(inst);
528                 return -1;
529         }
530         pair = inst->check_item_map;
531         if (pair == NULL)
532                 pair = inst->reply_item_map;
533         for(i=0;i<atts_num;i++){
534                 if (i <= check_map_num ){
535                         inst->atts[i] = pair->attr;
536                         if (i == check_map_num)
537                                 pair = inst->reply_item_map;
538                         else
539                                 pair = pair->next;
540                 }
541                 else if (i <= reply_map_num){
542                         inst->atts[i] = pair->attr;
543                         pair = pair->next;
544                 }
545                 else{
546                         if (inst->profile_attr && !att_map[0]){
547                                 inst->atts[i] = inst->profile_attr;
548                                 att_map[0] = 1;
549                         }
550                         else if (inst->passwd_attr && !att_map[1]){
551                                 inst->atts[i] = inst->passwd_attr;
552                                 att_map[1] = 1;
553                         }
554                         else if (inst->access_attr && !att_map[2]){
555                                 inst->atts[i] = inst->access_attr;
556                                 att_map[2] = 1;
557                         }
558                 }
559         }
560         inst->atts[atts_num] = NULL;
561
562         DEBUG("conns: %p",inst->conns);
563
564         *instance = inst;
565
566
567         return 0;
568 }
569
570
571 /*
572  * read_mappings(...) reads a ldap<->radius mappings file to inst->reply_item_map and inst->check_item_map
573  */
574
575 #define MAX_LINE_LEN 160
576 #define GENERIC_ATTRIBUTE_ID "$GENERIC$"
577
578 static int
579 read_mappings(ldap_instance* inst)
580 {
581         FILE* mapfile;
582         char *filename;
583         /* all buffers are of MAX_LINE_LEN so we can use sscanf without being afraid of buffer overflows */
584         char buf[MAX_LINE_LEN], itemType[MAX_LINE_LEN], radiusAttribute[MAX_LINE_LEN], ldapAttribute[MAX_LINE_LEN];
585         int linenumber;
586
587         /* open the mappings file for reading */
588
589         filename = inst->dictionary_mapping;
590         DEBUG("rlm_ldap: reading ldap<->radius mappings from file %s", filename);
591         mapfile = fopen(filename, "r");
592
593         if (mapfile == NULL) {
594                 radlog(L_ERR, "rlm_ldap: Opening file %s failed", filename);
595                 return -1; /* error */
596         }
597
598         /* read file line by line. Note that if line length exceed MAX_LINE_LEN, line numbers will be mixed up */
599
600         linenumber = 0;
601
602         while (fgets(buf, sizeof buf, mapfile)!=NULL) {
603                 char* ptr;
604                 int token_count;
605                 TLDAP_RADIUS* pair;
606
607                 linenumber++;
608
609                 /* strip comments */
610                 ptr = strchr(buf, '#');
611                 if (ptr) *ptr = 0;
612
613                 /* empty line */
614                 if (buf[0] == 0) continue;
615
616                 /* extract tokens from the string */
617                 token_count = sscanf(buf, "%s %s %s", itemType, radiusAttribute, ldapAttribute);
618
619                 if (token_count <= 0) /* no tokens */
620                         continue;
621
622                 if (token_count != 3) {
623                         radlog(L_ERR, "rlm_ldap: Skipping %s line %i: %s", filename, linenumber, buf);
624                         radlog(L_ERR, "rlm_ldap: Expected 3 tokens "
625                                "(Item type, RADIUS Attribute and LDAP Attribute) but found only %i", token_count);
626                         continue;
627                 }
628
629                 /* create new TLDAP_RADIUS list node */
630                 pair = rad_malloc(sizeof(TLDAP_RADIUS));
631
632                 pair->attr = strdup(ldapAttribute);
633                 pair->radius_attr = strdup(radiusAttribute);
634
635                 if ( (pair->attr == NULL) || (pair->radius_attr == NULL) ) {
636                         radlog(L_ERR, "rlm_ldap: Out of memory");
637                         if (pair->attr) free(pair->attr);
638                         if (pair->radius_attr) free(pair->radius_attr);
639                         free(pair);
640                         fclose(mapfile);
641                         return -1;
642                 }
643
644                 /* push node to correct list */
645                 if (strcasecmp(itemType, "checkItem") == 0) {
646                         pair->next = inst->check_item_map;
647                         inst->check_item_map = pair;
648                 } else if (strcasecmp(itemType, "replyItem") == 0) {
649                         pair->next = inst->reply_item_map;
650                         inst->reply_item_map = pair;
651                 } else {
652                         radlog(L_ERR, "rlm_ldap: file %s: skipping line %i: unknown itemType %s",
653                                filename, linenumber, itemType);
654                         free(pair->attr);
655                         free(pair->radius_attr);
656                         free(pair);
657                         continue;
658                 }
659
660                 DEBUG("rlm_ldap: LDAP %s mapped to RADIUS %s",
661                       pair->attr, pair->radius_attr);
662         }
663
664         fclose(mapfile);
665
666         return 0; /* success */
667 }
668
669 static int
670 perform_search(void *instance, LDAP_CONN *conn, char *search_basedn, int scope, char *filter,
671                 char **attrs, LDAPMessage ** result)
672 {
673         int             res = RLM_MODULE_OK;
674         int             ldap_errno = 0;
675         ldap_instance  *inst = instance;
676         int             search_retry = 0;
677
678         *result = NULL;
679
680         if (!conn){
681                 radlog(L_ERR, "rlm_ldap: NULL connection handle passed");
682                 return RLM_MODULE_FAIL;
683         }
684         if (conn->failed_conns > MAX_FAILED_CONNS_START){
685                 conn->failed_conns++;
686                 if (conn->failed_conns >= MAX_FAILED_CONNS_END){
687                         conn->failed_conns = MAX_FAILED_CONNS_RESTART;
688                         conn->bound = 0;
689                 }
690         }
691 retry:
692         if (!conn->bound || conn->ld == NULL) {
693                 DEBUG2("rlm_ldap: attempting LDAP reconnection");
694                 if (conn->ld){
695                         DEBUG2("rlm_ldap: closing existing LDAP connection");
696                         ldap_unbind_s(conn->ld);
697                 }
698                 if ((conn->ld = ldap_connect(instance, inst->login, inst->password, 0, &res)) == NULL) {
699                         radlog(L_ERR, "rlm_ldap: (re)connection attempt failed");
700                         if (search_retry == 0)
701                                 conn->failed_conns++;
702                         return (RLM_MODULE_FAIL);
703                 }
704                 conn->bound = 1;
705                 conn->failed_conns = 0;
706         }
707         DEBUG2("rlm_ldap: performing search in %s, with filter %s", search_basedn ? search_basedn : "(null)" , filter);
708         switch (ldap_search_st(conn->ld, search_basedn, scope, filter, attrs, 0, &(inst->timeout), result)) {
709         case LDAP_SUCCESS:
710         case LDAP_NO_SUCH_OBJECT:
711                 break;
712         case LDAP_SERVER_DOWN:
713                 radlog(L_ERR, "rlm_ldap: ldap_search() failed: LDAP connection lost.");
714                 conn->failed_conns++;
715                 if (search_retry == 0){
716                         if (conn->failed_conns <= MAX_FAILED_CONNS_START){
717                                 radlog(L_INFO, "rlm_ldap: Attempting reconnect");
718                                 search_retry = 1;
719                                 conn->bound = 0;
720                                 ldap_msgfree(*result);
721                                 goto retry;
722                         }
723                 }
724                 ldap_msgfree(*result);
725                 return RLM_MODULE_FAIL;
726         case LDAP_INSUFFICIENT_ACCESS:
727                 radlog(L_ERR, "rlm_ldap: ldap_search() failed: Insufficient access. Check the identity and password configuration directives.");
728                 ldap_msgfree(*result);
729                 return RLM_MODULE_FAIL;
730         case LDAP_TIMEOUT:
731                 radlog(L_ERR, "rlm_ldap: ldap_search() failed: Timed out while waiting for server to respond. Please increase the timeout.");
732                 ldap_msgfree(*result);
733                 return RLM_MODULE_FAIL;
734         case LDAP_FILTER_ERROR:
735                 radlog(L_ERR, "rlm_ldap: ldap_search() failed: Bad search filter: %s",filter);
736                 ldap_msgfree(*result);
737                 return RLM_MODULE_FAIL;
738         case LDAP_TIMELIMIT_EXCEEDED:
739         case LDAP_BUSY:
740         case LDAP_UNAVAILABLE:
741                 /* We don't need to reconnect in these cases so we don't set conn->bound */
742                 ldap_get_option(conn->ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
743                 radlog(L_ERR, "rlm_ldap: ldap_search() failed: %s", ldap_err2string(ldap_errno));
744                 ldap_msgfree(*result);
745                 return (RLM_MODULE_FAIL);
746         default:
747                 ldap_get_option(conn->ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
748                 radlog(L_ERR, "rlm_ldap: ldap_search() failed: %s", ldap_err2string(ldap_errno));
749                 conn->bound = 0;
750                 ldap_msgfree(*result);
751                 return (RLM_MODULE_FAIL);
752         }
753
754         if ((ldap_count_entries(conn->ld, *result)) != 1) {
755                 DEBUG("rlm_ldap: object not found or got ambiguous search result");
756                 res = RLM_MODULE_NOTFOUND;
757                 ldap_msgfree(*result);
758         }
759         return res;
760 }
761
762
763 /*
764  *      Translate the LDAP queries.
765  */
766 static int ldap_escape_func(char *out, int outlen, const char *in)
767 {
768         int len = 0;
769
770         while (in[0]) {
771                 /*
772                  *  Only one byte left.
773                  */
774                 if (outlen <= 1) {
775                         break;
776                 }
777
778                 if (strchr("*", *in)) {
779                         in++;
780                         outlen--;
781                         continue;
782                 }
783
784                 /*
785                  *      Else it's a nice character.
786                  */
787                 *out = *in;
788                 out++;
789                 in++;
790                 outlen--;
791                 len++;
792         }
793         *out = '\0';
794         return len;
795 }
796
797 /*
798  * ldap_groupcmp(). Implement the Ldap-Group == "group" filter
799  */
800
801 static int ldap_groupcmp(void *instance, REQUEST *req, VALUE_PAIR *request, VALUE_PAIR *check,
802                 VALUE_PAIR *check_pairs, VALUE_PAIR **reply_pairs)
803 {
804         char            filter[MAX_FILTER_STR_LEN];
805         char            gr_filter[MAX_FILTER_STR_LEN];
806         int             res;
807         LDAPMessage     *result = NULL;
808         LDAPMessage     *msg = NULL;
809         char            basedn[MAX_FILTER_STR_LEN];
810         char            *attrs[] = {"dn",NULL};
811         char            **vals;
812         ldap_instance   *inst = instance;
813         char            *group_attrs[] = {inst->groupmemb_attr,NULL};
814         LDAP_CONN       *conn;
815         int             conn_id = -1;
816         VALUE_PAIR      *vp_user_dn;
817         VALUE_PAIR      **request_pairs;
818
819         request_pairs = &req->config_items;
820
821         DEBUG("rlm_ldap: Entering ldap_groupcmp()");
822
823         if (check->strvalue == NULL || check->length == 0){
824                 DEBUG("rlm_ldap::ldap_groupcmp: Illegal group name");
825                 return 1;
826         }
827
828         if (req == NULL){
829                 DEBUG("rlm_ldap::ldap_groupcmp: NULL request");
830                 return 1;
831         }
832
833         if (!radius_xlat(basedn, sizeof(basedn), inst->basedn, req, NULL)) {
834                 DEBUG("rlm_ldap::ldap_groupcmp: unable to create basedn.");
835                 return 1;
836         }
837
838         while((vp_user_dn = pairfind(*request_pairs, PW_LDAP_USERDN)) == NULL){
839                 char            *user_dn = NULL;
840
841                 if (!radius_xlat(filter, sizeof(filter), inst->filter,
842                                         req, ldap_escape_func)){
843                         DEBUG("rlm_ldap::ldap_groupcmp: unable to create filter");
844                         return 1;
845                 }
846                 if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
847                         radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
848                         return 1;
849                 }
850                 if ((res = perform_search(inst, conn, basedn, LDAP_SCOPE_SUBTREE,
851                                         filter, attrs, &result)) != RLM_MODULE_OK){
852                         DEBUG("rlm_ldap::ldap_groupcmp: search failed");
853                         ldap_release_conn(conn_id,inst->conns);
854                         return 1;
855                 }
856                 if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
857                         DEBUG("rlm_ldap::ldap_groupcmp: ldap_first_entry() failed");
858                         ldap_release_conn(conn_id,inst->conns);
859                         ldap_msgfree(result);
860                         return 1;
861                 }
862                 if ((user_dn = ldap_get_dn(conn->ld, msg)) == NULL) {
863                         DEBUG("rlm_ldap:ldap_groupcmp:: ldap_get_dn() failed");
864                         ldap_release_conn(conn_id,inst->conns);
865                         ldap_msgfree(result);
866                         return 1;
867                 }
868                 ldap_release_conn(conn_id,inst->conns);
869                 /*
870                 * Adding new attribute containing DN for LDAP object associated with
871                 * given username
872                 */
873                 pairadd(request_pairs, pairmake("Ldap-UserDn", user_dn, T_OP_EQ));
874                 ldap_memfree(user_dn);
875                 ldap_msgfree(result);
876         }
877
878         if(!radius_xlat(gr_filter, sizeof(gr_filter), inst->groupmemb_filt, req, NULL)){
879                 DEBUG("rlm_ldap::ldap_groupcmp: unable to create filter.");
880                 return 1;
881         }
882
883         if (strchr((char *)check->strvalue,',') != NULL) {
884                 /* This looks like a DN */
885                 snprintf(filter,sizeof(filter), "%s",gr_filter);
886                 snprintf(basedn,sizeof(basedn), "%s",(char *)check->strvalue);
887         } else
888                 snprintf(filter,sizeof(filter), "(&(%s=%s)%s)",inst->groupname_attr,(char *)check->strvalue,gr_filter);
889
890         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
891                 radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
892                 return 1;
893         }
894
895         if ((res = perform_search(inst, conn, basedn, LDAP_SCOPE_SUBTREE,
896                                 filter, attrs, &result)) == RLM_MODULE_OK){
897                 DEBUG("rlm_ldap::ldap_groupcmp: User found in group %s",
898                                 (char *)check->strvalue);
899                 ldap_msgfree(result);
900                 ldap_release_conn(conn_id,inst->conns);
901                 return 0;
902         }
903
904         ldap_release_conn(conn_id,inst->conns);
905
906         if (res != RLM_MODULE_NOTFOUND ) {
907                 DEBUG("rlm_ldap::ldap_groupcmp: Search returned error");
908                 return 1;
909         }
910
911         if (inst->groupmemb_attr == NULL){
912                 /* search returned NOTFOUND and searching for membership
913                  * using user object attributes is not specified in config
914                  * file
915                  */
916                 DEBUG("rlm_ldap::ldap_groupcmp: Group %s not found or user is not a member.",(char *)check->strvalue);
917                 return 1;
918         }
919
920         snprintf(filter,sizeof(filter), "(objectclass=*)");
921         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
922                 radlog(L_ERR, "rlm_ldap: Add ldap connections are in use");
923                 return 1;
924         }
925         if ((res = perform_search(inst, conn, vp_user_dn->strvalue, LDAP_SCOPE_BASE,
926                                         filter, group_attrs,&result)) != RLM_MODULE_OK){
927                 DEBUG("rlm_ldap::ldap_groupcmp: Search returned error");
928                 ldap_release_conn(conn_id, inst->conns);
929                 return 1;
930         }
931
932         if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
933                 DEBUG("rlm_ldap::ldap_groupcmp: ldap_first_entry() failed");
934                 ldap_release_conn(conn_id,inst->conns);
935                 ldap_msgfree(result);
936                 return 1;
937         }
938         if ((vals = ldap_get_values(conn->ld, msg, inst->groupmemb_attr)) != NULL) {
939                 unsigned int i = 0;
940                 char found = 0;
941                 for (;i < ldap_count_values(vals);i++){
942                         if (strchr(vals[i],',') != NULL){
943                                 /* This looks like a DN */
944                                 LDAPMessage *gr_result = NULL;
945                                 snprintf(filter,sizeof(filter), "(%s=%s)",
946                                         inst->groupname_attr,
947                                         (char *)check->strvalue);
948                                 if ((res = perform_search(inst, conn, vals[i],
949                                                 LDAP_SCOPE_BASE, filter,
950                                                 attrs, &gr_result)) != RLM_MODULE_OK){
951                                         if (res != RLM_MODULE_NOTFOUND){
952                                                 DEBUG("rlm_ldap::ldap_groupcmp: \
953                                                         Search returned error");
954                                                 ldap_value_free(vals);
955                                                 ldap_msgfree(result);
956                                                 ldap_release_conn(conn_id,inst->conns);
957                                                 return 1;
958                                         }
959                                 } else {
960                                         ldap_msgfree(gr_result);
961                                         found = 1;
962                                         break;
963                                 }
964                         } else {
965                                 if (strcmp(vals[i],(char *)check->strvalue) == 0){
966                                         found = 1;
967                                         break;
968                                 }
969                         }
970                 }
971                 ldap_value_free(vals);
972                 ldap_msgfree(result);
973                 if (found == 0){
974                         DEBUG("rlm_ldap::groupcmp: Group %s not found \
975                                 or user not a member",
976                                 (char *)check->strvalue);
977                         ldap_release_conn(conn_id,inst->conns);
978                         return 1;
979                 }
980         } else {
981                         DEBUG("rlm_ldap::ldap_groupcmp: ldap_get_values() failed");
982                         ldap_msgfree(result);
983                         ldap_release_conn(conn_id,inst->conns);
984                         return 1;
985         }
986
987         DEBUG("rlm_ldap::ldap_groupcmp: User found in group %s",(char *)check->strvalue);
988         ldap_release_conn(conn_id,inst->conns);
989
990         return 0;
991 }
992
993 /*
994  * ldap_xlat()
995  * Do an xlat on an LDAP URL
996  */
997
998 static int ldap_xlat(void *instance, REQUEST *request, char *fmt, char *out, int freespace,
999                                 RADIUS_ESCAPE_STRING func)
1000 {
1001         char url[MAX_FILTER_STR_LEN];
1002         int res;
1003         int ret = 0;
1004         ldap_instance *inst = instance;
1005         LDAPURLDesc *ldap_url;
1006         LDAPMessage *result = NULL;
1007         LDAPMessage *msg = NULL;
1008         char **vals;
1009         int conn_id = -1;
1010         LDAP_CONN *conn;
1011
1012         DEBUG("rlm_ldap: - ldap_xlat");
1013         if (!radius_xlat(url, sizeof(url), fmt, request, func)) {
1014                 radlog (L_ERR, "rlm_ldap: Unable to create LDAP URL.\n");
1015                 return 0;
1016         }
1017         if (!ldap_is_ldap_url(url)){
1018                 radlog (L_ERR, "rlm_ldap: String passed does not look like an LDAP URL.\n");
1019                 return 0;
1020         }
1021         if (ldap_url_parse(url,&ldap_url)){
1022                 radlog (L_ERR, "rlm_ldap: LDAP URL parse failed.\n");
1023                 return 0;
1024         }
1025         if (ldap_url->lud_attrs == NULL || ldap_url->lud_attrs[0] == NULL || \
1026                 ( ldap_url->lud_attrs[1] != NULL || ( ! strlen(ldap_url->lud_attrs[0]) || \
1027                 ! strcmp(ldap_url->lud_attrs[0],"*") ) ) ){
1028                 radlog (L_ERR, "rlm_ldap: Invalid Attribute(s) request.\n");
1029                 ldap_free_urldesc(ldap_url);
1030                 return 0;
1031         }
1032         if (ldap_url->lud_host){
1033                 if (strncmp(inst->server,ldap_url->lud_host,strlen(inst->server)) != 0 || \
1034                                 ldap_url->lud_port != inst->port){
1035                         DEBUG("rlm_ldap: Requested server/port is not known to this module instance.");
1036                         ldap_free_urldesc(ldap_url);
1037                         return 0;
1038                 }
1039         }
1040         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
1041                 radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
1042                 ldap_free_urldesc(ldap_url);
1043                 return 0;
1044         }
1045         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){
1046                 if (res == RLM_MODULE_NOTFOUND){
1047                         DEBUG("rlm_ldap: Search returned not found");
1048                         ldap_free_urldesc(ldap_url);
1049                         ldap_release_conn(conn_id,inst->conns);
1050                         return 0;
1051                 }
1052                 DEBUG("rlm_ldap: Search returned error");
1053                 ldap_free_urldesc(ldap_url);
1054                 ldap_release_conn(conn_id,inst->conns);
1055                 return 0;
1056         }
1057         if ((msg = ldap_first_entry(conn->ld, result)) == NULL){
1058                 DEBUG("rlm_ldap: ldap_first_entry() failed");
1059                 ldap_msgfree(result);
1060                 ldap_free_urldesc(ldap_url);
1061                 ldap_release_conn(conn_id,inst->conns);
1062                 return 0;
1063         }
1064         if ((vals = ldap_get_values(conn->ld, msg, ldap_url->lud_attrs[0])) != NULL) {
1065                 ret = strlen(vals[0]);
1066                 if (ret > freespace){
1067                         DEBUG("rlm_ldap: Insufficient string space");
1068                         ldap_free_urldesc(ldap_url);
1069                         ldap_value_free(vals);
1070                         ldap_msgfree(result);
1071                         ldap_release_conn(conn_id,inst->conns);
1072                         return 0;
1073                 }
1074                 DEBUG("rlm_ldap: Adding attribute %s, value: %s",ldap_url->lud_attrs[0],vals[0]);
1075                 strncpy(out,vals[0],ret);
1076                 ldap_value_free(vals);
1077         }
1078         else
1079                 ret = 0;
1080
1081         ldap_msgfree(result);
1082         ldap_free_urldesc(ldap_url);
1083         ldap_release_conn(conn_id,inst->conns);
1084
1085         DEBUG("rlm_ldap: - ldap_xlat end");
1086
1087         return ret;
1088 }
1089
1090
1091 /******************************************************************************
1092  *
1093  *      Function: rlm_ldap_authorize
1094  *
1095  *      Purpose: Check if user is authorized for remote access
1096  *
1097  ******************************************************************************/
1098 static int
1099 ldap_authorize(void *instance, REQUEST * request)
1100 {
1101         LDAPMessage     *result = NULL;
1102         LDAPMessage     *msg = NULL;
1103         LDAPMessage     *def_msg = NULL;
1104         LDAPMessage     *def_attr_msg = NULL;
1105         LDAPMessage     *def_result = NULL;
1106         LDAPMessage     *def_attr_result = NULL;
1107         ldap_instance   *inst = instance;
1108         char            *user_dn = NULL;
1109         char            filter[MAX_FILTER_STR_LEN];
1110         char            basedn[MAX_FILTER_STR_LEN];
1111         VALUE_PAIR      *check_tmp;
1112         VALUE_PAIR      *reply_tmp;
1113         int             res;
1114         VALUE_PAIR      **check_pairs, **reply_pairs;
1115         char            **vals;
1116         VALUE_PAIR      *module_fmsg_vp;
1117         VALUE_PAIR      *user_profile;
1118         char            module_fmsg[MAX_STRING_LEN];
1119         LDAP_CONN       *conn;
1120         int             conn_id = -1;
1121
1122         DEBUG("rlm_ldap: - authorize");
1123
1124         if (!request->username){
1125                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Name\" is required for authentication.\n");
1126                 return RLM_MODULE_INVALID;
1127         }
1128
1129         check_pairs = &request->config_items;
1130         reply_pairs = &request->reply->vps;
1131
1132         /*
1133          * Check for valid input, zero length names not permitted
1134          */
1135         if (request->username->strvalue == 0) {
1136                 radlog(L_ERR, "rlm_ldap: zero length username not permitted\n");
1137                 return RLM_MODULE_INVALID;
1138         }
1139         DEBUG("rlm_ldap: performing user authorization for %s",
1140                request->username->strvalue);
1141
1142         if (!radius_xlat(filter, sizeof(filter), inst->filter,
1143                          request, ldap_escape_func)) {
1144                 radlog (L_ERR, "rlm_ldap: unable to create filter.\n");
1145                 return RLM_MODULE_INVALID;
1146         }
1147
1148         if (!radius_xlat(basedn, sizeof(basedn), inst->basedn,
1149                          request, NULL)) {
1150                 radlog (L_ERR, "rlm_ldap: unable to create basedn.\n");
1151                 return RLM_MODULE_INVALID;
1152         }
1153
1154         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
1155                 radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
1156                 return RLM_MODULE_FAIL;
1157         }
1158         if ((res = perform_search(instance, conn, basedn, LDAP_SCOPE_SUBTREE, filter, inst->atts, &result)) != RLM_MODULE_OK) {
1159                 DEBUG("rlm_ldap: search failed");
1160                 if (res == RLM_MODULE_NOTFOUND){
1161                         snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: User not found");
1162                         module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1163                         pairadd(&request->packet->vps, module_fmsg_vp);
1164                 }
1165                 ldap_release_conn(conn_id,inst->conns);
1166                 return (res);
1167         }
1168         if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
1169                 DEBUG("rlm_ldap: ldap_first_entry() failed");
1170                 ldap_msgfree(result);
1171                 ldap_release_conn(conn_id,inst->conns);
1172                 return RLM_MODULE_FAIL;
1173         }
1174         if ((user_dn = ldap_get_dn(conn->ld, msg)) == NULL) {
1175                 DEBUG("rlm_ldap: ldap_get_dn() failed");
1176                 ldap_msgfree(result);
1177                 ldap_release_conn(conn_id,inst->conns);
1178                 return RLM_MODULE_FAIL;
1179         }
1180         /*
1181          * Adding new attribute containing DN for LDAP object associated with
1182          * given username
1183          */
1184         pairadd(check_pairs, pairmake("Ldap-UserDn", user_dn, T_OP_EQ));
1185         ldap_memfree(user_dn);
1186
1187
1188         /* Remote access is controled by attribute of the user object */
1189         if (inst->access_attr) {
1190                 if ((vals = ldap_get_values(conn->ld, msg, inst->access_attr)) != NULL) {
1191                         if (inst->default_allow){
1192                                 DEBUG("rlm_ldap: checking if remote access for %s is allowed by %s", request->username->strvalue, inst->access_attr);
1193                                 if (!strncmp(vals[0], "FALSE", 5)) {
1194                                         DEBUG("rlm_ldap: dialup access disabled");
1195                                         snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Access Attribute denies access");
1196                                         module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1197                                         pairadd(&request->packet->vps, module_fmsg_vp);
1198                                         ldap_msgfree(result);
1199                                         ldap_value_free(vals);
1200                                         ldap_release_conn(conn_id,inst->conns);
1201                                         return RLM_MODULE_USERLOCK;
1202                                 }
1203                                 ldap_value_free(vals);
1204                         }
1205                         else{
1206                                 DEBUG("rlm_ldap: %s attribute exists - access denied by default", inst->access_attr);
1207                                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Access Attribute denies access");
1208                                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1209                                 pairadd(&request->packet->vps, module_fmsg_vp);
1210                                 ldap_msgfree(result);
1211                                 ldap_value_free(vals);
1212                                 ldap_release_conn(conn_id,inst->conns);
1213                                 return RLM_MODULE_USERLOCK;
1214                         }
1215                 } else {
1216                         if (inst->default_allow){
1217                                 DEBUG("rlm_ldap: no %s attribute - access denied by default", inst->access_attr);
1218                                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Access Attribute denies access");
1219                                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1220                                 pairadd(&request->packet->vps, module_fmsg_vp);
1221                                 ldap_msgfree(result);
1222                                 ldap_release_conn(conn_id,inst->conns);
1223                                 return RLM_MODULE_USERLOCK;
1224                         }
1225                 }
1226         }
1227
1228         /*
1229          * Check for the default profile entry. If it exists then add the
1230          * attributes it contains in the check and reply pairs
1231          */
1232
1233         user_profile = pairfind(request->config_items, PW_USER_PROFILE);
1234         if (inst->default_profile || user_profile){
1235                 char *profile = inst->default_profile;
1236
1237                 strNcpy(filter,inst->base_filter,sizeof(filter));
1238                 if (user_profile)
1239                         profile = user_profile->strvalue;
1240                 if (profile && strlen(profile)){
1241                         if ((res = perform_search(instance, conn,
1242                                 profile, LDAP_SCOPE_BASE,
1243                                 filter, inst->atts, &def_result)) == RLM_MODULE_OK){
1244                                 if ((def_msg = ldap_first_entry(conn->ld,def_result))){
1245                                         if ((check_tmp = ldap_pairget(conn->ld,def_msg,inst->check_item_map,check_pairs,1))) {
1246                                                 if (inst->do_xlat){
1247                                                         pairxlatmove(request, check_pairs, &check_tmp);
1248                                                         pairfree(&check_tmp);
1249                                                 }
1250                                                 else
1251                                                         pairadd(check_pairs,check_tmp);
1252                                         }
1253                                         if ((reply_tmp = ldap_pairget(conn->ld,def_msg,inst->reply_item_map,reply_pairs,0))) {
1254                                                 if (inst->do_xlat){
1255                                                         pairxlatmove(request, reply_pairs, &reply_tmp);
1256                                                         pairfree(&reply_tmp);
1257                                                 }
1258                                                 else
1259                                                         pairadd(reply_pairs,reply_tmp);
1260                                         }
1261                                 }
1262                                 ldap_msgfree(def_result);
1263                         } else
1264                                 DEBUG("rlm_ldap: default_profile/user-profile search failed");
1265                 }
1266         }
1267
1268         /*
1269          * Check for the profile attribute. If it exists, we assume that it
1270          * contains the DN of an entry containg a profile for the user. That
1271          * way we can have different general profiles for various user groups
1272          * (students,faculty,staff etc)
1273          */
1274
1275         if (inst->profile_attr){
1276                 if ((vals = ldap_get_values(conn->ld, msg, inst->profile_attr)) != NULL) {
1277                         unsigned int i=0;
1278                         strNcpy(filter,inst->base_filter,sizeof(filter));
1279                         while(vals[i] != NULL && strlen(vals[i])){
1280                                 if ((res = perform_search(instance, conn,
1281                                         vals[i], LDAP_SCOPE_BASE,
1282                                         filter, inst->atts, &def_attr_result)) == RLM_MODULE_OK){
1283                                         if ((def_attr_msg = ldap_first_entry(conn->ld,def_attr_result))){
1284                                                 if ((check_tmp = ldap_pairget(conn->ld,def_attr_msg,inst->check_item_map,check_pairs,1))) {
1285                                                         if (inst->do_xlat){
1286                                                                 pairxlatmove(request, check_pairs, &check_tmp);
1287                                                                 pairfree(&check_tmp);
1288                                                         }
1289                                                         else
1290                                                                 pairadd(check_pairs,check_tmp);
1291                                                 }
1292                                                 if ((reply_tmp = ldap_pairget(conn->ld,def_attr_msg,inst->reply_item_map,reply_pairs,0))) {
1293                                                         if (inst->do_xlat){
1294                                                                 pairxlatmove(request, reply_pairs, &reply_tmp);
1295                                                                 pairfree(&reply_tmp);
1296                                                         }
1297                                                         else
1298                                                                 pairadd(reply_pairs,reply_tmp);
1299                                                 }
1300                                         }
1301                                         ldap_msgfree(def_attr_result);
1302                                 } else
1303                                         DEBUG("rlm_ldap: profile_attribute search failed");
1304                                 i++;
1305                         }
1306                         ldap_value_free(vals);
1307                 }
1308         }
1309         if (inst->passwd_attr && strlen(inst->passwd_attr)){
1310                 VALUE_PAIR *passwd_item;
1311
1312                 if ((passwd_item = pairfind(request->config_items, PW_PASSWORD)) == NULL){
1313                         char **passwd_vals;
1314                         char *passwd_val = NULL;
1315                         int passwd_len;
1316
1317                         if ((passwd_vals = ldap_get_values(conn->ld,msg,inst->passwd_attr)) != NULL){
1318                                 unsigned int i=0;
1319                                 while(passwd_vals[i] != NULL){
1320                                         if (strlen(passwd_vals[i])){
1321                                                 passwd_val = passwd_vals[i];
1322
1323                                                 if (inst->passwd_hdr && strlen(inst->passwd_hdr)){
1324                                                         passwd_val = strstr(passwd_val,inst->passwd_hdr);
1325                                                         if (passwd_val != NULL)
1326                                                                 passwd_val += strlen(inst->passwd_hdr);
1327                                                         else
1328                                                                 DEBUG("rlm_ldap: Password header not found in password %s for user %s", passwd_vals[0],request->username->strvalue);
1329                                                 }
1330                                                 if (passwd_val){
1331                                                         if ((passwd_item = paircreate(PW_PASSWORD,PW_TYPE_STRING)) == NULL){
1332                                                                 radlog(L_ERR|L_CONS, "no memory");
1333                                                                 ldap_value_free(passwd_vals);
1334                                                                 ldap_msgfree(result);
1335                                                                 ldap_release_conn(conn_id,inst->conns);
1336                                                                 return RLM_MODULE_FAIL;
1337                                                         }
1338                                                         passwd_len = strlen(passwd_val);
1339                                                         strncpy(passwd_item->strvalue,passwd_val,MAX_STRING_LEN - 1);
1340                                                         passwd_item->length = (passwd_len > (MAX_STRING_LEN - 1)) ? (MAX_STRING_LEN - 1) : passwd_len;
1341                                                         pairadd(&request->config_items,passwd_item);
1342                                                         DEBUG("rlm_ldap: Added password %s in check items",passwd_item->strvalue);
1343                                                 }
1344                                         }
1345                                         i++;
1346                                 }
1347                                 ldap_value_free(passwd_vals);
1348                         }
1349                 }
1350         }
1351
1352
1353
1354         DEBUG("rlm_ldap: looking for check items in directory...");
1355
1356         if ((check_tmp = ldap_pairget(conn->ld, msg, inst->check_item_map,check_pairs,1)) != NULL) {
1357                 if (inst->do_xlat){
1358                         pairxlatmove(request, check_pairs, &check_tmp);
1359                         pairfree(&check_tmp);
1360                 }
1361                 else
1362                         pairadd(check_pairs,check_tmp);
1363         }
1364
1365
1366         DEBUG("rlm_ldap: looking for reply items in directory...");
1367
1368
1369         if ((reply_tmp = ldap_pairget(conn->ld, msg, inst->reply_item_map,reply_pairs,0)) != NULL) {
1370                 if (inst->do_xlat){
1371                         pairxlatmove(request, reply_pairs, &reply_tmp);
1372                         pairfree(&reply_tmp);
1373                 }
1374                 else
1375                         pairadd(reply_pairs,reply_tmp);
1376         }
1377
1378        if (inst->do_comp && paircmp(request,request->packet->vps,*check_pairs,reply_pairs) != 0){
1379                 DEBUG("rlm_ldap: Pairs do not match. Rejecting user.");
1380                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Pairs do not match");
1381                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1382                 pairadd(&request->packet->vps, module_fmsg_vp);
1383                 ldap_msgfree(result);
1384                 ldap_release_conn(conn_id,inst->conns);
1385
1386                 return RLM_MODULE_REJECT;
1387         }
1388
1389         /*
1390          * Module should default to LDAP authentication if no Auth-Type
1391          * specified
1392          */
1393         if (pairfind(*check_pairs, PW_AUTHTYPE) == NULL)
1394                 pairadd(check_pairs, pairmake("Auth-Type", "LDAP", T_OP_EQ));
1395
1396
1397         DEBUG("rlm_ldap: user %s authorized to use remote access",
1398               request->username->strvalue);
1399         ldap_msgfree(result);
1400         ldap_release_conn(conn_id,inst->conns);
1401
1402         return RLM_MODULE_OK;
1403 }
1404
1405 /*****************************************************************************
1406  *
1407  *      Function: rlm_ldap_authenticate
1408  *
1409  *      Purpose: Check the user's password against ldap database
1410  *
1411  *****************************************************************************/
1412 static int
1413 ldap_authenticate(void *instance, REQUEST * request)
1414 {
1415         LDAP           *ld_user;
1416         LDAPMessage    *result, *msg;
1417         ldap_instance  *inst = instance;
1418         char           *user_dn, *attrs[] = {"uid", NULL};
1419         char            filter[MAX_FILTER_STR_LEN];
1420         char            basedn[MAX_FILTER_STR_LEN];
1421         int             res;
1422         VALUE_PAIR     *vp_user_dn;
1423         VALUE_PAIR      *module_fmsg_vp;
1424         char            module_fmsg[MAX_STRING_LEN];
1425         LDAP_CONN       *conn;
1426         int             conn_id = -1;
1427
1428         DEBUG("rlm_ldap: - authenticate");
1429
1430         /*
1431          * Ensure that we're being passed a plain-text password, and not
1432          * anything else.
1433          */
1434
1435         if (!request->username) {
1436                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Name\" is required for authentication.\n");
1437                 return RLM_MODULE_INVALID;
1438         }
1439
1440         if (!request->password){
1441                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Password\" is required for authentication.");
1442                 return RLM_MODULE_INVALID;
1443         }
1444
1445         if(request->password->attribute != PW_PASSWORD) {
1446                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Password\" is required for authentication. Cannot use \"%s\".", request->password->name);
1447                 return RLM_MODULE_INVALID;
1448         }
1449
1450         if (request->password->length == 0) {
1451                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: empty password supplied");
1452                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1453                 pairadd(&request->packet->vps, module_fmsg_vp);
1454                 return RLM_MODULE_INVALID;
1455         }
1456
1457         /*
1458          * Check that we don't have any failed connections. If we do there's no real need
1459          * of runing. Also give it another chance if we have a lot of failed connections.
1460          */
1461         if (inst->failed_conns > MAX_FAILED_CONNS_END)
1462                 inst->failed_conns = 0;
1463         if (inst->failed_conns > MAX_FAILED_CONNS_START){
1464                 inst->failed_conns++;
1465                 return RLM_MODULE_FAIL;
1466         }
1467
1468
1469         DEBUG("rlm_ldap: login attempt by \"%s\" with password \"%s\"",
1470                request->username->strvalue, request->password->strvalue);
1471
1472         while((vp_user_dn = pairfind(request->config_items, PW_LDAP_USERDN)) == NULL) {
1473                 if (!radius_xlat(filter, sizeof(filter), inst->filter,
1474                                 request, NULL)) {
1475                         radlog (L_ERR, "rlm_ldap: unable to create filter.\n");
1476                         return RLM_MODULE_INVALID;
1477                 }
1478
1479                 if (!radius_xlat(basedn, sizeof(basedn), inst->basedn,
1480                                 request, NULL)) {
1481                         radlog (L_ERR, "rlm_ldap: unable to create basedn.\n");
1482                         return RLM_MODULE_INVALID;
1483                 }
1484
1485                 if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
1486                         radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
1487                         return RLM_MODULE_FAIL;
1488                 }
1489                 if ((res = perform_search(instance, conn, basedn, LDAP_SCOPE_SUBTREE, filter, attrs, &result)) != RLM_MODULE_OK) {
1490                         if (res == RLM_MODULE_NOTFOUND){
1491                                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: User not found");
1492                                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1493                                 pairadd(&request->packet->vps, module_fmsg_vp);
1494                         }
1495                         ldap_release_conn(conn_id,inst->conns);
1496                         return (res);
1497                 }
1498                 if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
1499                         ldap_msgfree(result);
1500                         ldap_release_conn(conn_id,inst->conns);
1501                         return RLM_MODULE_FAIL;
1502                 }
1503                 if ((user_dn = ldap_get_dn(conn->ld, msg)) == NULL) {
1504                         DEBUG("rlm_ldap: ldap_get_dn() failed");
1505                         ldap_msgfree(result);
1506                         ldap_release_conn(conn_id,inst->conns);
1507                         return RLM_MODULE_FAIL;
1508                 }
1509                 ldap_release_conn(conn_id,inst->conns);
1510                 pairadd(&request->config_items, pairmake("Ldap-UserDn", user_dn, T_OP_EQ));
1511                 ldap_memfree(user_dn);
1512                 ldap_msgfree(result);
1513         }
1514
1515         user_dn = vp_user_dn->strvalue;
1516
1517         DEBUG("rlm_ldap: user DN: %s", user_dn);
1518
1519         ld_user = ldap_connect(instance, user_dn, request->password->strvalue,
1520                                1, &res);
1521         if (ld_user == NULL){
1522                 if (res == RLM_MODULE_REJECT){
1523                         inst->failed_conns = 0;
1524                         snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Bind as user failed");
1525                         module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1526                         pairadd(&request->packet->vps, module_fmsg_vp);
1527                 }
1528                 if (res == RLM_MODULE_FAIL){
1529                         DEBUG("rlm_ldap: ldap_connect() failed");
1530                         inst->failed_conns++;
1531                 }
1532                 return (res);
1533         }
1534
1535         DEBUG("rlm_ldap: user %s authenticated succesfully",
1536               request->username->strvalue);
1537         ldap_unbind_s(ld_user);
1538         inst->failed_conns = 0;
1539
1540         return RLM_MODULE_OK;
1541 }
1542
1543 static LDAP    *
1544 ldap_connect(void *instance, const char *dn, const char *password, int auth, int *result)
1545 {
1546         ldap_instance  *inst = instance;
1547         LDAP           *ld = NULL;
1548         int             msgid, rc, ldap_version;
1549         int             ldap_errno = 0;
1550         LDAPMessage    *res;
1551
1552         if (inst->is_url){
1553 #ifdef HAVE_LDAP_INITIALIZE
1554                 DEBUG("rlm_ldap: (re)connect to %s, authentication %d", inst->server, auth);
1555                 if (ldap_initialize(&ld, inst->server) != LDAP_SUCCESS) {
1556                         radlog(L_ERR, "rlm_ldap: ldap_initialize() failed");
1557                         *result = RLM_MODULE_FAIL;
1558                         return (NULL);
1559                 }
1560 #endif
1561         }
1562         else{
1563                 DEBUG("rlm_ldap: (re)connect to %s:%d, authentication %d", inst->server, inst->port, auth);
1564                 if ((ld = ldap_init(inst->server, inst->port)) == NULL) {
1565                         radlog(L_ERR, "rlm_ldap: ldap_init() failed");
1566                         *result = RLM_MODULE_FAIL;
1567                         return (NULL);
1568                 }
1569         }
1570         if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, (void *) &(inst->net_timeout)) != LDAP_OPT_SUCCESS) {
1571                 radlog(L_ERR, "rlm_ldap: Could not set LDAP_OPT_NETWORK_TIMEOUT %ld.%ld", inst->net_timeout.tv_sec, inst->net_timeout.tv_usec);
1572         }
1573         if (ldap_set_option(ld, LDAP_OPT_TIMELIMIT, (void *) &(inst->timelimit)) != LDAP_OPT_SUCCESS) {
1574                 radlog(L_ERR, "rlm_ldap: Could not set LDAP_OPT_TIMELIMIT %d", inst->timelimit);
1575         }
1576         if (inst->ldap_debug && ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &(inst->ldap_debug)) != LDAP_OPT_SUCCESS) {
1577                 radlog(L_ERR, "rlm_ldap: Could not set LDAP_OPT_DEBUG_LEVEL %d", inst->ldap_debug);
1578         }
1579         ldap_version = LDAP_VERSION3;
1580         if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &ldap_version) != LDAP_OPT_SUCCESS) {
1581                 radlog(L_ERR, "rlm_ldap: Could not set LDAP version to V3");
1582         }
1583 #ifdef HAVE_LDAP_START_TLS
1584         if(inst->tls_mode) {
1585                 DEBUG("rlm_ldap: setting TLS mode to %d", inst->tls_mode);
1586                 if(ldap_set_option(ld, LDAP_OPT_X_TLS,
1587                            (void *) &(inst->tls_mode)) != LDAP_OPT_SUCCESS) {
1588                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
1589                         radlog(L_ERR, "rlm_ldap: could not set LDAP_OPT_X_TLS option %s", ldap_err2string(ldap_errno));
1590                 }
1591         }
1592
1593         if(inst->tls_cacertfile != NULL) {
1594                 DEBUG("rlm_ldap: setting TLS CACert File to %s", inst->tls_cacertfile);
1595
1596                 if ( ldap_set_option( NULL, LDAP_OPT_X_TLS_CACERTFILE,
1597                                                           (void *) inst->tls_cacertfile )
1598                          != LDAP_OPT_SUCCESS) {
1599                         radlog(L_ERR, "rlm_ldap: could not set "
1600                                    "LDAP_OPT_X_TLS_CACERTFILE option to %s", inst->tls_cacertfile);
1601                 }
1602         }
1603
1604         if(inst->tls_cacertdir != NULL) {
1605                 DEBUG("rlm_ldap: setting TLS CACert File to %s", inst->tls_cacertdir);
1606
1607                 if ( ldap_set_option( NULL, LDAP_OPT_X_TLS_CACERTDIR,
1608                                                           (void *) inst->tls_cacertdir )
1609                          != LDAP_OPT_SUCCESS) {
1610                         radlog(L_ERR, "rlm_ldap: could not set "
1611                                    "LDAP_OPT_X_TLS_CACERTDIR option to %s", inst->tls_cacertdir);
1612                 }
1613         }
1614
1615         if( strcmp( TLS_DEFAULT_VERIFY, inst->tls_require_cert ) != 0 ) {
1616                 DEBUG("rlm_ldap: setting TLS Require Cert to %s",
1617                           inst->tls_require_cert);
1618         }
1619
1620
1621 #ifdef HAVE_INT_TLS_CONFIG
1622
1623         if ( ldap_int_tls_config( NULL, LDAP_OPT_X_TLS_REQUIRE_CERT,
1624                                                           (inst->tls_require_cert) )
1625                  != LDAP_OPT_SUCCESS) {
1626                 radlog(L_ERR, "rlm_ldap: could not set "
1627                            "LDAP_OPT_X_TLS_REQUIRE_CERT option to %s",
1628                            inst->tls_require_cert);
1629         }
1630
1631 #endif
1632
1633         if(inst->tls_certfile != NULL) {
1634                 DEBUG("rlm_ldap: setting TLS Cert File to %s", inst->tls_certfile);
1635
1636                 if ( ldap_set_option( NULL, LDAP_OPT_X_TLS_CERTFILE,
1637                                                           (void *) inst->tls_certfile )
1638                          != LDAP_OPT_SUCCESS) {
1639                         radlog(L_ERR, "rlm_ldap: could not set "
1640                                    "LDAP_OPT_X_TLS_CERTFILE option to %s",
1641                                    inst->tls_certfile);
1642                 }
1643         }
1644
1645         if(inst->tls_keyfile != NULL) {
1646                 DEBUG("rlm_ldap: setting TLS Key File to %s", inst->tls_keyfile);
1647
1648                 if ( ldap_set_option( NULL, LDAP_OPT_X_TLS_KEYFILE,
1649                                                           (void *) inst->tls_keyfile )
1650                          != LDAP_OPT_SUCCESS) {
1651                         radlog(L_ERR, "rlm_ldap: could not set "
1652                                    "LDAP_OPT_X_TLS_KEYFILE option to %s",
1653                                    inst->tls_keyfile);
1654                 }
1655         }
1656
1657         if(inst->tls_randfile != NULL) {
1658                 DEBUG("rlm_ldap: setting TLS Key File to %s", inst->tls_randfile);
1659
1660                 if ( ldap_set_option( NULL, LDAP_OPT_X_TLS_RANDOM_FILE,
1661                                                           (void *) inst->tls_randfile )
1662                          != LDAP_OPT_SUCCESS) {
1663                         radlog(L_ERR, "rlm_ldap: could not set "
1664                                    "LDAP_OPT_X_TLS_RANDOM_FILE option to %s",
1665                                    inst->tls_randfile);
1666                 }
1667         }
1668         if (inst->start_tls) {
1669                 DEBUG("rlm_ldap: starting TLS");
1670                 rc = ldap_start_tls_s(ld, NULL, NULL);
1671                 if (rc != LDAP_SUCCESS) {
1672                         DEBUG("rlm_ldap: ldap_start_tls_s()");
1673                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
1674                         radlog(L_ERR, "rlm_ldap: could not start TLS %s", ldap_err2string(ldap_errno));
1675                         *result = RLM_MODULE_FAIL;
1676                         ldap_unbind_s(ld);
1677                         return (NULL);
1678                 }
1679         }
1680 #endif /* HAVE_LDAP_START_TLS */
1681
1682         if (inst->is_url){
1683                 DEBUG("rlm_ldap: bind as %s/%s to %s", dn, password, inst->server);
1684         }
1685         else{
1686                 DEBUG("rlm_ldap: bind as %s/%s to %s:%d", dn, password, inst->server, inst->port);
1687         }
1688         msgid = ldap_bind(ld, dn, password,LDAP_AUTH_SIMPLE);
1689         if (msgid == -1) {
1690                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
1691                 if (inst->is_url)
1692                         radlog(L_ERR, "rlm_ldap: %s bind to %s failed: %s",
1693                                 dn, inst->server, ldap_err2string(ldap_errno));
1694                 else
1695                         radlog(L_ERR, "rlm_ldap: %s bind to %s:%d failed: %s",
1696                                 dn, inst->server, inst->port,
1697                                 ldap_err2string(ldap_errno));
1698                 *result = RLM_MODULE_FAIL;
1699                 ldap_unbind_s(ld);
1700                 return (NULL);
1701         }
1702         DEBUG("rlm_ldap: waiting for bind result ...");
1703
1704         rc = ldap_result(ld, msgid, 1, &(inst->timeout), &res);
1705
1706         if(rc < 1) {
1707                 DEBUG("rlm_ldap: ldap_result()");
1708                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
1709                 if (inst->is_url)
1710                         radlog(L_ERR, "rlm_ldap: %s bind to %s failed: %s",
1711                                 dn, inst->server, (rc == 0) ? "timeout" : ldap_err2string(ldap_errno));
1712                 else
1713                         radlog(L_ERR, "rlm_ldap: %s bind to %s:%d failed: %s",
1714                                 dn, inst->server, inst->port,
1715                                 (rc == 0) ? "timeout" : ldap_err2string(ldap_errno));
1716                 *result = RLM_MODULE_FAIL;
1717                 ldap_unbind_s(ld);
1718                 return (NULL);
1719         }
1720         ldap_errno = ldap_result2error(ld, res, 1);
1721         switch (ldap_errno) {
1722         case LDAP_SUCCESS:
1723                 DEBUG("rlm_ldap: Bind was successful");
1724                 *result = RLM_MODULE_OK;
1725                 break;
1726
1727         case LDAP_INVALID_CREDENTIALS:
1728                 if (auth){
1729                         DEBUG("rlm_ldap: Bind failed with invalid credentials");
1730                         *result = RLM_MODULE_REJECT;
1731                 }
1732                 else {
1733                         radlog(L_ERR, "rlm_ldap: LDAP login failed: check identity, password settings in ldap section of radiusd.conf");
1734                         *result = RLM_MODULE_FAIL;
1735                 }
1736                 break;
1737
1738         default:
1739                 if (inst->is_url)
1740                         radlog(L_ERR,"rlm_ldap: %s bind to %s failed %s",
1741                                 dn, inst->server, ldap_err2string(ldap_errno));
1742                 else
1743                         radlog(L_ERR,"rlm_ldap: %s bind to %s:%d failed %s",
1744                                 dn, inst->server, inst->port,
1745                                 ldap_err2string(ldap_errno));
1746                 *result = RLM_MODULE_FAIL;
1747         }
1748
1749         if (*result != RLM_MODULE_OK) {
1750                 ldap_unbind_s(ld);
1751                 ld = NULL;
1752         }
1753         return ld;
1754 }
1755
1756 /*****************************************************************************
1757  *
1758  *      Detach from the LDAP server and cleanup internal state.
1759  *
1760  *****************************************************************************/
1761 static int
1762 ldap_detach(void *instance)
1763 {
1764         ldap_instance  *inst = instance;
1765         TLDAP_RADIUS *pair, *nextpair;
1766
1767         if (inst->server)
1768                 free((char *) inst->server);
1769         if (inst->login)
1770                 free((char *) inst->login);
1771         if (inst->password)
1772                 free((char *) inst->password);
1773         if (inst->basedn)
1774                 free((char *) inst->basedn);
1775         if (inst->dictionary_mapping)
1776                 free(inst->dictionary_mapping);
1777         if (inst->filter)
1778                 free((char *) inst->filter);
1779         if (inst->base_filter)
1780                 free((char *) inst->base_filter);
1781         if (inst->passwd_hdr)
1782                 free((char *) inst->passwd_hdr);
1783         if (inst->passwd_attr)
1784                 free((char *) inst->passwd_attr);
1785         if (inst->groupname_attr)
1786                 free((char *) inst->groupname_attr);
1787         if (inst->groupmemb_filt)
1788                 free((char *) inst->groupmemb_filt);
1789         if (inst->groupmemb_attr)
1790                 free((char *) inst->groupmemb_attr);
1791         if (inst->access_attr)
1792                 free((char *) inst->access_attr);
1793         if (inst->profile_attr)
1794                 free((char *) inst->profile_attr);
1795         if (inst->conns){
1796                 int i=0;
1797
1798                 for(;i<inst->num_conns;i++){
1799                         if (inst->conns[i].ld){
1800                                 ldap_unbind_s(inst->conns[i].ld);
1801                         }
1802                         pthread_mutex_destroy(&inst->conns[i].mutex);
1803                 }
1804                 free(inst->conns);
1805         }
1806
1807         pair = inst->check_item_map;
1808
1809         while (pair != NULL) {
1810                 nextpair = pair->next;
1811                 free(pair->attr);
1812                 free(pair->radius_attr);
1813                 free(pair);
1814                 pair = nextpair;
1815         }
1816
1817         pair = inst->reply_item_map;
1818
1819         while (pair != NULL) {
1820                 nextpair = pair->next;
1821                 free(pair->attr);
1822                 free(pair->radius_attr);
1823                 free(pair);
1824                 pair = nextpair;
1825         }
1826
1827         if (inst->atts)
1828                 free(inst->atts);
1829
1830         paircompare_unregister(PW_LDAP_GROUP, ldap_groupcmp);
1831         xlat_unregister(inst->xlat_name,ldap_xlat);
1832         free(inst->xlat_name);
1833
1834         free(inst);
1835
1836         return 0;
1837 }
1838
1839 #ifdef FIELDCPY
1840 static void
1841 fieldcpy(char *string, char **uptr)
1842 {
1843         char           *ptr;
1844
1845         ptr = *uptr;
1846         while (*ptr == ' ' || *ptr == '\t') {
1847                 ptr++;
1848         }
1849         if (*ptr == '"') {
1850                 ptr++;
1851                 while (*ptr != '"' && *ptr != '\0' && *ptr != '\n') {
1852                         *string++ = *ptr++;
1853                 }
1854                 *string = '\0';
1855                 if (*ptr == '"') {
1856                         ptr++;
1857                 }
1858                 *uptr = ptr;
1859                 return;
1860         }
1861         while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0' && *ptr != '\n' &&
1862                *ptr != '=' && *ptr != ',') {
1863                 *string++ = *ptr++;
1864         }
1865         *string = '\0';
1866         *uptr = ptr;
1867         return;
1868 }
1869 #endif
1870 /*****************************************************************************
1871  *      Get RADIUS attributes from LDAP object
1872  *      ( according to draft-adoba-radius-05.txt
1873  *        <http://www.ietf.org/internet-drafts/draft-adoba-radius-05.txt> )
1874  *
1875  *****************************************************************************/
1876
1877 static VALUE_PAIR *
1878 ldap_pairget(LDAP * ld, LDAPMessage * entry,
1879              TLDAP_RADIUS * item_map, VALUE_PAIR **pairs,char is_check)
1880 {
1881         char          **vals;
1882         int             vals_count;
1883         int             vals_idx;
1884         char           *ptr;
1885         TLDAP_RADIUS   *element;
1886         LRAD_TOKEN      token;
1887         int             is_generic_attribute;
1888         char            value[256];
1889         VALUE_PAIR     *pairlist = NULL;
1890         VALUE_PAIR     *newpair = NULL;
1891
1892         /* check if there is a mapping from this LDAP attribute to a RADIUS attribute */
1893         for (element = item_map; element != NULL; element = element->next) {
1894         if ((vals = ldap_get_values(ld,entry,element->attr)) != NULL){
1895                         /* check whether this is a one-to-one-mapped ldap attribute or a generic
1896                            attribute and set flag accordingly */
1897
1898                         if (strcasecmp(element->radius_attr, GENERIC_ATTRIBUTE_ID)==0)
1899                                 is_generic_attribute = 1;
1900                         else
1901                                 is_generic_attribute = 0;
1902
1903                         /* find out how many values there are for the attribute and extract all of them */
1904
1905                         vals_count = ldap_count_values(vals);
1906
1907                         for (vals_idx = 0; vals_idx < vals_count; vals_idx++) {
1908                                 ptr = vals[vals_idx];
1909
1910                                 if (is_generic_attribute) {
1911                                         /* this is a generic attribute */
1912                                         LRAD_TOKEN dummy; /* makes pairread happy */
1913
1914                                         /* not sure if using pairread here is ok ... */
1915                                         if ( (newpair = pairread(&ptr, &dummy)) != NULL) {
1916                                                 DEBUG("rlm_ldap: extracted attribute %s from generic item %s",
1917                                                       newpair->name, vals[vals_idx]);
1918                                                 pairadd(&pairlist, newpair);
1919                                         } else {
1920                                                 radlog(L_ERR, "rlm_ldap: parsing %s failed: %s",
1921                                                        element->attr, vals[vals_idx]);
1922                                         }
1923                                 } else {
1924                                         /* this is a one-to-one-mapped attribute */
1925                                         token = gettoken(&ptr, value, sizeof(value) - 1);
1926                                         if (token < T_EQSTART || token > T_EQEND) {
1927                                                 token = (is_check) ? T_OP_CMP_EQ : T_OP_EQ;
1928                                         } else {
1929                                                 gettoken(&ptr, value, sizeof(value) - 1);
1930                                         }
1931                                         if (value[0] == 0) {
1932                                                 DEBUG("rlm_ldap: Attribute %s has no value", element->attr);
1933                                                 break;
1934                                         }
1935                                         DEBUG("rlm_ldap: Adding %s as %s, value %s & op=%d", element->attr, element->radius_attr, value, token);
1936                                                 if ((newpair = pairmake(element->radius_attr, value, token)) == NULL)
1937                                                 continue;
1938                                         if (! vals_idx){
1939                                                 pairdelete(pairs,newpair->attribute);
1940                                         }
1941                                         pairadd(&pairlist, newpair);
1942                                 }
1943                         }
1944                         ldap_value_free(vals);
1945                 }
1946         }
1947
1948         return (pairlist);
1949 }
1950
1951 /* globally exported name */
1952 module_t        rlm_ldap = {
1953         "LDAP",
1954         RLM_TYPE_THREAD_SAFE,   /* type: reserved        */
1955         NULL,                   /* initialization        */
1956         ldap_instantiate,       /* instantiation         */
1957         {
1958                 ldap_authenticate,      /* authentication        */
1959                 ldap_authorize,         /* authorization         */
1960                 NULL,                   /* preaccounting         */
1961                 NULL,                   /* accounting            */
1962                 NULL,                   /* checksimul            */
1963                 NULL,                   /* pre-proxy             */
1964                 NULL,                   /* post-proxy            */
1965                 NULL                    /* post-auth             */
1966         },
1967         ldap_detach,            /* detach                */
1968         NULL,                   /* destroy               */
1969 };