check & memset
[freeradius.git] / src / modules / rlm_ldap / rlm_ldap.c
1 /*
2  * rlm_ldap.c LDAP authorization and authentication module.
3  * 
4  * 
5  * This module is based on LDAP patch to Cistron radiusd by James Golovich 
6  * <james@wwnet.net>, which in turn was based mostly on a Mysql+Cistron patch 
7  * from <oyarzun@wilmington.net>
8  * 
9  * 17 Jan 2000, Adrian Pavlykevych <pam@polynet.lviv.ua>
10  *      - OpenLDAP SDK porting, basic TLS support, LDAP authorization,
11  *        fault tolerance with multiple LDAP server support 
12  * 24 May 2000, Adrian Pavlykevych <pam@polynet.lviv.ua> 
13  *      - Converting to new configuration file format, futher improvements
14  *        in fault tolerance, threaded operation
15  * 12 Dec 2000, Adrian Pavlykevych <pam@polynet.lviv.ua> 
16  *      - Added preliminary support for multiple instances
17  *      - moved all instance configuration into dynamicly allocated structure
18  *      - Removed connection maintenance thread and all attempts for multihreading
19  *        the module itself. OpenLDAP SDK is not thread safe when used with shared
20  *        LDAP connection.
21  *      - Added configuration option for defining LDAP attribute of user object,
22  *        which controls remote access.
23  * 16 Feb 2001, Hannu Laurila <hannu.laurila@japo.fi>
24  *      - LDAP<->RADIUS attribute mappings are now read from a file
25  *      - Support for generic RADIUS check and reply attribute.
26  * Jun 2001, Kostas Kalevras <kkalev@noc.ntua.gr>
27  *      - Fix: check and reply attributes from LDAP _replace_ existing ones
28  *      - Added "default_profile" directive, which points to radiusProfile 
29  *        object, which contains default values for RADIUS users
30  *      - Added "profile_attribute" directive, which specifies user object 
31  *        attribute pointing to radiusProfile object.
32  * Nov 2001, Kostas Kalevras <kkalev@noc.ntua.gr>
33  *      - Added support for adding the user password to the check. Based on
34  *        the password_header directive rlm_ldap will strip the
35  *        password header if needed. This will make support for CHAP much easier.
36  *      - Added module messages when we reject a user.
37  *      - Added ldap_groupcmp to allow searching for user group membership.
38  *      - Added ldap_xlat to allow ldap urls in xlat strings. Something like:
39  *        %{ldap:ldap:///dc=company,dc=com?cn?sub?uid=user}
40  * Nov 2001, Gordon Tetlow <gordont@gnf.org>
41  *      - Do an xlat on the access_group attribute.
42  * Dec 2001, Kostas Kalevras <kkalev@noc.ntua.gr>
43  *      - Added ldap caching for the default/regular profiles and group entries.
44  *      - Fixed a memory leak in ldap_xlat.
45  *      - Removed dict_attrbyname from ldap_pairget. They are not needed.
46  *      - Moved the radius_xlat's for filter and basedn in ldap_authenticate() to
47  *        the right place.
48  *      - Made the module thread safe. We create a connection pool and each thread
49  *        will call ldap_get_conn to lock one of the ldap connections and release with
50  *        a call to ldap_release_conn when it has finished.
51  *      - Request only the user attributes that interest us (radius attributes,regular
52  *        profile,user password and access attribute).
53  * Mar 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
54  *      - Fixed a bug where the ldap server will kill the idle connections from the ldap
55  *        connection pool. We now check if ldap_search returns LDAP_SERVER_DOWN and try to
56  *        reconnect if it does. Bug noted by Dan Perik <dan_perik-work@ntm.org.pg>
57  * May 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
58  *      - Instead of the Group attribute we now have the Ldap-Group attribute, to avoid
59  *        collisions with other modules
60  *      - If perform_search fails check the ld != NULL before using it. Based on a bug report
61  *        by John <jhogenmiller@pennswoods.net>
62  * Jun 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
63  *      - Add the ability to do a paircmp on the check items. Add a compare_check_items boolean
64  *        configuration directive which defaults to no. If it is set then we will do a compare
65  *      - Add another configuration directive. access_attr_used_for_allow. If it is set to yes
66  *        then the access_attr will be used to allow user access. If it is set to no then it will
67  *        be used to deny user access.
68  *      - Remember to free inst->atts in ldap_detach()
69  *      - Add a forgotten ldap_free_urldesc in ldap_xlat()
70  *      - Add a variable locked in the LDAP_CONN structure. We use this to avoid deadlocks. The mutex
71  *        we are using is of type fast and can deadlock if the same thread tries to relock it. That
72  *        could happen in case of calls to xlat.
73  *      - When ldap_search returns NO_SUCH_OBJECT don't return fail but notfound
74  * Jul 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
75  *      - Fix the logic when we get an LDAP_SERVER_DOWN or we have conn->ld == NULL in perform_search
76  *      - Try to minimize the penalty of having the ldap server go down. The comments before
77  *        MAX_FAILED_CONNS_* definitions should explain things.
78  *      - Check for a number of error codes from ldap_search and log corresponding error messages
79  *        We should only reconnect when that can help things.
80  *      - In ldap_groupcmp instead of first searching for the group object and then checking user
81  *        group membership combine them in one ldap search operation. That should make group
82  *        membership checks a lot faster.
83  *      - Remember to do ldap_release_conn and ldap_msgfree when we do paircmp and the result is reject
84  * Aug 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
85  *      - Add support for group membership attribute inside the user entry in ldap_groupcmp. The attribute
86  *        can either contain the name or the DN of the group. Added the groupmembership_attribute
87  *        configuration directive
88  *      - Move the ldap_{get,release}_conn in ldap_groupcmp so that we hold a connection for the minimum time.
89  *      - Now that ldap_groupcmp is complete we really don't need access_group. Removed it.
90  *      - Remember to free groupmembership_attribute in ldap_detach
91  *      - Don't delete existing generic attributes in ldap_pairget when adding new ones. Since generic attributes
92  *        have operators we don't need to try to be cleaver.
93  * Sep 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
94  *      - Fix a crash in ldap_pairget when the attribute value is larger than the buffer size
95  *        Bug report by Stefan Radovanovici <sra@rtsffm.com>
96  *      - If we add a check item then use the == operator. Based on an idea by Allister Maguire <amaguire@gnc.net.nz>
97  *      - Only add a failure message for bind as user failed in ldap_authenticate if the result of ldap_connect was
98  *        RLM_MODULE_REJECT
99  *      - Make tls_mode a configurable option. Patch from John <jhogenmiller@pennswoods.net>
100  *      - Allow multiple regular profiles for an entry
101  * Oct 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
102  *      - Disable cache after searching for the default profile
103  *      - Use the MAX_FAILED_CONNS_* in ldap_authenticate() when calling ldap_connect()
104  * Nov 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
105  *      - Set LDAP version to V3 before binding. Now freeradius should work with openldap21
106  * Dec 2002, Kostas Kalevras <kkalev@noc.ntua.gr>
107  *      - Set default values for the server and basedn parameters
108  * Feb 2003, Kostas Kalevras <kkalev@noc.ntua.gr>
109  *      - Add support for ldap_initialize. That way we can specify the server as an ldap url.
110  *        Based on ideas from Derrik Pates <dpates@dsdk12.net>
111  * Mar 2003, Kostas Kalevras <kkalev@noc.ntua.gr>
112  *      - Add an ldap_escape_func. Escape the * character from the filter so that we can avoid
113  *        the trivial DoS of username=*
114  *      - Remove the caching code. It does not exist in openldap21.
115  *        Based on a report from Mike Denka <mdenk@whidbey.net>
116  * May 2003, Kostas Kalevras <kkalev@noc.ntua.gr>
117  *      - Don't do a double free on the attribute maps. Bug noted by Derrik Pates <dpates@dsdk12.net>
118  *      - Apply a patch from Alexander M. Pravking <fduch@antar.bryansk.ru> to do an xlat on the
119  *        retrieved attributes.
120  */
121 static const char rcsid[] = "$Id$";
122
123 #include "autoconf.h"
124
125 #include        <sys/types.h>
126 #include        <sys/socket.h>
127 #include        <sys/time.h>
128 #include        <netinet/in.h>
129
130 #include        <stdio.h>
131 #include        <stdlib.h>
132 #include        <netdb.h>
133 #include        <pwd.h>
134 #include        <time.h>
135 #include        <ctype.h>
136 #include        <string.h>
137
138 #include        <lber.h>
139 #include        <ldap.h>
140
141 #include        <errno.h>
142 #include        <unistd.h>
143 #include        <pthread.h>
144
145 #include        "libradius.h"
146 #include        "radiusd.h"
147 #include        "conffile.h"
148 #include        "modules.h"
149 #include        "rad_assert.h"
150
151 #define MAX_FILTER_STR_LEN      1024
152 #define TIMELIMIT 5
153
154 /*
155  * These are used in case ldap_search returns LDAP_SERVER_DOWN
156  * In that case we do conn->failed_conns++ and then check it:
157  * If conn->failed_conns <= MAX_FAILED_CONNS_START then we try
158  * to reconnect
159  * conn->failed_conns is also checked on entrance in perform_search:
160  * If conn->failed_conns > MAX_FAILED_CONNS_START then we don't
161  * try to do anything and we just do conn->failed_conns++ and
162  * return RLM_MODULE_FAIL
163  * if conn->failed_conns >= MAX_FAILED_CONNS_END then we give it
164  * another chance and we set it to MAX_FAILED_CONNS_RESTART and
165  * try to reconnect.
166  *
167  *
168  * We are assuming that the majority of the LDAP_SERVER_DOWN cases
169  * will either be an ldap connection timeout or a temporary ldap
170  * server problem.
171  * As a result we make a few attempts to reconnect hoping that the problem
172  * will soon go away. If it does not go away then we just return
173  * RLM_MODULE_FAIL on entrance in perform_search until conn->failed_conns
174  * gets to MAX_FAILED_CONNS_END. After that we give it one more chance by
175  * going back to MAX_FAILED_CONNS_RESTART
176  *
177  */
178
179 #define MAX_FAILED_CONNS_END            20
180 #define MAX_FAILED_CONNS_RESTART        4
181 #define MAX_FAILED_CONNS_START          5
182
183 /* linked list of mappings between RADIUS attributes and LDAP attributes */
184 struct TLDAP_RADIUS {
185         char*                 attr;
186         char*                 radius_attr;
187         struct TLDAP_RADIUS*  next;
188 };
189 typedef struct TLDAP_RADIUS TLDAP_RADIUS;
190
191 typedef struct ldap_conn {
192         LDAP            *ld;
193         char            bound;
194         char            locked;
195         int             failed_conns;
196         pthread_mutex_t mutex;
197 } LDAP_CONN;
198
199 typedef struct {
200         char           *server;
201         int             port;
202         int             timelimit;
203         struct timeval  net_timeout;
204         struct timeval  timeout;
205         int             debug;
206         int             tls_mode;
207         int             start_tls;
208         int             num_conns;
209         int             do_comp;
210         int             default_allow;
211         int             failed_conns;
212         int             is_url;
213         char           *login;
214         char           *password;
215         char           *filter;
216         char           *basedn;
217         char           *default_profile;
218         char           *profile_attr;
219         char           *access_attr;
220         char           *passwd_hdr;
221         char           *passwd_attr;
222         char           *dictionary_mapping;
223         char           *groupname_attr;
224         char           *groupmemb_filt;
225         char           *groupmemb_attr;
226         char            **atts;
227         TLDAP_RADIUS   *check_item_map;
228         TLDAP_RADIUS   *reply_item_map;
229         LDAP_CONN       *conns;
230         int             ldap_debug; /* Debug flag for LDAP SDK */
231         char            *xlat_name; /* name used to xlat */
232 }               ldap_instance;
233
234 static CONF_PARSER module_config[] = {
235         {"server", PW_TYPE_STRING_PTR, offsetof(ldap_instance,server), NULL, "localhost"},
236         {"port", PW_TYPE_INTEGER, offsetof(ldap_instance,port), NULL, "389"},
237         /* wait forever on network activity */
238         {"net_timeout", PW_TYPE_INTEGER, offsetof(ldap_instance,net_timeout.tv_sec), NULL, "10"},
239         /* wait forever for search results */
240         {"timeout", PW_TYPE_INTEGER, offsetof(ldap_instance,timeout.tv_sec), NULL, "20"},
241         /* allow server unlimited time for search (server-side limit) */
242         {"timelimit", PW_TYPE_INTEGER, offsetof(ldap_instance,timelimit), NULL, "20"},
243         {"identity", PW_TYPE_STRING_PTR, offsetof(ldap_instance,login), NULL, ""},
244         {"start_tls", PW_TYPE_BOOLEAN, offsetof(ldap_instance,start_tls), NULL, "no"},
245         {"password", PW_TYPE_STRING_PTR, offsetof(ldap_instance,password), NULL, ""},
246         {"basedn", PW_TYPE_STRING_PTR, offsetof(ldap_instance,basedn), NULL, "o=notexist"},
247         {"filter", PW_TYPE_STRING_PTR, offsetof(ldap_instance,filter), NULL, "(uid=%u)"},
248         {"default_profile", PW_TYPE_STRING_PTR, offsetof(ldap_instance,default_profile), NULL, NULL},
249         {"profile_attribute", PW_TYPE_STRING_PTR, offsetof(ldap_instance,profile_attr), NULL, NULL},
250         {"password_header", PW_TYPE_STRING_PTR, offsetof(ldap_instance,passwd_hdr), NULL, NULL},
251         {"password_attribute", PW_TYPE_STRING_PTR, offsetof(ldap_instance,passwd_attr), NULL, NULL},
252         /* LDAP attribute name that controls remote access */
253         {"access_attr", PW_TYPE_STRING_PTR, offsetof(ldap_instance,access_attr), NULL, NULL},
254         /* file with mapping between LDAP and RADIUS attributes */
255         {"groupname_attribute", PW_TYPE_STRING_PTR, offsetof(ldap_instance,groupname_attr), NULL, "cn"},
256         {"groupmembership_filter", PW_TYPE_STRING_PTR, offsetof(ldap_instance,groupmemb_filt), NULL, "(|(&(objectClass=GroupOfNames)(member=%{Ldap-UserDn}))(&(objectClass=GroupOfUniqueNames)(uniquemember=%{Ldap-UserDn})))"},
257         {"groupmembership_attribute", PW_TYPE_STRING_PTR, offsetof(ldap_instance,groupmemb_attr), NULL, NULL},
258         {"dictionary_mapping", PW_TYPE_STRING_PTR, offsetof(ldap_instance,dictionary_mapping), NULL, "${confdir}/ldap.attrmap"},
259         {"ldap_debug", PW_TYPE_INTEGER, offsetof(ldap_instance,ldap_debug), NULL, "0x0000"},
260         {"ldap_connections_number", PW_TYPE_INTEGER, offsetof(ldap_instance,num_conns), NULL, "5"},
261         {"compare_check_items", PW_TYPE_BOOLEAN, offsetof(ldap_instance,do_comp), NULL, "no"},
262         {"access_attr_used_for_allow", PW_TYPE_BOOLEAN, offsetof(ldap_instance,default_allow), NULL, "yes"},
263
264         {NULL, -1, 0, NULL, NULL}
265 };
266
267 #define ld_valid                ld_options.ldo_valid
268 #define LDAP_VALID_SESSION      0x2
269 #define LDAP_VALID(ld)  ( (ld)->ld_valid == LDAP_VALID_SESSION )
270
271 #ifdef FIELDCPY
272 static void     fieldcpy(char *, char **);
273 #endif
274 static VALUE_PAIR *ldap_pairget(LDAP *, LDAPMessage *, TLDAP_RADIUS *,VALUE_PAIR **,char);
275 static int ldap_groupcmp(void *, REQUEST *, VALUE_PAIR *, VALUE_PAIR *, VALUE_PAIR *, VALUE_PAIR **);
276 static int ldap_xlat(void *,REQUEST *, char *, char *,int, RADIUS_ESCAPE_STRING);
277 static LDAP    *ldap_connect(void *instance, const char *, const char *, int, int *);
278 static int     read_mappings(ldap_instance* inst);
279
280 static inline int ldap_get_conn(LDAP_CONN *conns,LDAP_CONN **ret,void *instance)
281 {
282         ldap_instance *inst = instance;
283         register int i = 0;
284
285         for(;i<inst->num_conns;i++){
286                 if (conns[i].locked == 0 && pthread_mutex_trylock(&(conns[i].mutex)) == 0){
287                         *ret = &conns[i];
288                         conns[i].locked = 1;
289                         DEBUG("ldap_get_conn: Got Id: %d",i);
290                         return i;
291                 }
292         }
293
294         return -1;
295 }
296         
297 static inline void ldap_release_conn(int i, LDAP_CONN *conns)
298 {
299         DEBUG("ldap_release_conn: Release Id: %d",i);
300         conns[i].locked = 0;
301         pthread_mutex_unlock(&(conns[i].mutex));
302 }
303
304 /*************************************************************************
305  *
306  *      Function: rlm_ldap_instantiate
307  *
308  *      Purpose: Uses section of radiusd config file passed as parameter
309  *               to create an instance of the module.
310  *
311  *************************************************************************/
312 static int 
313 ldap_instantiate(CONF_SECTION * conf, void **instance)
314 {
315         ldap_instance  *inst;
316         int i = 0;
317         int atts_num = 0;
318         int reply_map_num = 0;
319         int check_map_num = 0;
320         int att_map[3] = {0,0,0};
321         TLDAP_RADIUS *pair;
322         char *xlat_name;
323
324         inst = rad_malloc(sizeof *inst);
325         if (!inst) {
326                 return -1;
327         }
328         memset(inst, 0, sizeof(*inst));
329
330         if (cf_section_parse(conf, inst, module_config) < 0) {
331                 free(inst);
332                 return -1;
333         }
334
335         if (inst->server == NULL) {
336                 radlog(L_ERR, "rlm_ldap: missing 'server' directive.");
337                 free(inst);
338                 return -1;
339         }
340         inst->is_url = 0;
341 #ifdef HAVE_LDAP_INITIALIZE
342         if (ldap_is_ldap_url(inst->server)){
343                 inst->is_url = 1;
344                 inst->port = 0;
345         }
346 #endif
347  
348         inst->timeout.tv_usec = 0;
349         inst->net_timeout.tv_usec = 0;
350         /* workaround for servers which support LDAPS but not START TLS */
351         if(inst->port == LDAPS_PORT)
352                 inst->tls_mode = LDAP_OPT_X_TLS_HARD;
353         else
354                 inst->tls_mode = 0;
355         inst->reply_item_map = NULL;
356         inst->check_item_map = NULL;
357         inst->conns = NULL;
358         inst->failed_conns = 0;
359
360         paircompare_register(PW_LDAP_GROUP, PW_USER_NAME, ldap_groupcmp, inst);
361         DEBUG("conns: %p",inst->conns);
362
363         xlat_name = cf_section_name2(conf);
364         if (xlat_name == NULL) {
365                 xlat_name = cf_section_name1(conf);
366                 rad_assert(xlat_name != NULL); /* or all hell breaks loose */
367         }
368         inst->xlat_name = strdup(xlat_name);
369         xlat_register(xlat_name,ldap_xlat,inst);
370
371         if (inst->num_conns <= 0){
372                 radlog(L_ERR, "rlm_ldap: Invalid ldap connections number passed.");
373                 free(inst);
374                 return -1;
375         }
376         inst->conns = (LDAP_CONN *)malloc(sizeof(LDAP_CONN)*inst->num_conns);
377         if (inst->conns == NULL){
378                 radlog(L_ERR, "rlm_ldap: Could not allocate memory. Aborting.");
379                 free(inst);
380                 return -1;
381         }
382         for(;i<inst->num_conns;i++){
383                 inst->conns[i].bound = 0;
384                 inst->conns[i].locked = 0;
385                 inst->conns[i].failed_conns = 0;
386                 inst->conns[i].ld = NULL;
387                 pthread_mutex_init(&inst->conns[i].mutex, NULL);
388         }       
389
390         if (read_mappings(inst) != 0) {
391                 radlog(L_ERR, "rlm_ldap: Reading dictionary mappings from file %s failed",
392                        inst->dictionary_mapping);
393                 radlog(L_ERR, "rlm_ldap: Proceeding with no mappings");
394         }
395         
396         pair = inst->check_item_map;
397         while(pair != NULL){
398                 atts_num++;
399                 pair = pair->next;
400         }
401         check_map_num = (atts_num - 1);
402         pair = inst->reply_item_map;
403         while(pair != NULL){
404                 atts_num++;
405                 pair = pair->next;
406         }
407         reply_map_num = (atts_num - 1);
408         if (inst->profile_attr)
409                 atts_num++;
410         if (inst->passwd_attr)
411                 atts_num++;
412         if (inst->access_attr)
413                 atts_num++;
414         inst->atts = (char **)malloc(sizeof(char *)*(atts_num + 1));
415         if (inst->atts == NULL){
416                 radlog(L_ERR, "rlm_ldap: Could not allocate memory. Aborting.");
417                 free(inst);
418                 return -1;
419         }
420         pair = inst->check_item_map;
421         for(i=0;i<atts_num;i++){
422                 if (i <= check_map_num ){
423                         inst->atts[i] = pair->attr;
424                         if (i == check_map_num)
425                                 pair = inst->reply_item_map;
426                         else
427                                 pair = pair->next;
428                 }
429                 else if (i <= reply_map_num){
430                         inst->atts[i] = pair->attr;
431                         pair = pair->next;
432                 }
433                 else{
434                         if (inst->profile_attr && !att_map[0]){
435                                 inst->atts[i] = inst->profile_attr;
436                                 att_map[0] = 1;
437                         }
438                         else if (inst->passwd_attr && !att_map[1]){
439                                 inst->atts[i] = inst->passwd_attr;
440                                 att_map[1] = 1;
441                         }
442                         else if (inst->access_attr && !att_map[2]){
443                                 inst->atts[i] = inst->access_attr;
444                                 att_map[2] = 1;
445                         }
446                 }
447         }
448         inst->atts[atts_num] = NULL;            
449
450         DEBUG("conns: %p",inst->conns);
451
452         *instance = inst;
453
454
455         return 0;
456 }
457
458
459 /*
460  * read_mappings(...) reads a ldap<->radius mappings file to inst->reply_item_map and inst->check_item_map
461  */
462
463 #define MAX_LINE_LEN 160
464 #define GENERIC_ATTRIBUTE_ID "$GENERIC$"
465
466 static int
467 read_mappings(ldap_instance* inst)
468 {
469         FILE* mapfile;
470         char *filename;
471         /* all buffers are of MAX_LINE_LEN so we can use sscanf without being afraid of buffer overflows */
472         char buf[MAX_LINE_LEN], itemType[MAX_LINE_LEN], radiusAttribute[MAX_LINE_LEN], ldapAttribute[MAX_LINE_LEN];
473         int linenumber;
474
475         /* open the mappings file for reading */
476
477         filename = inst->dictionary_mapping;
478         DEBUG("rlm_ldap: reading ldap<->radius mappings from file %s", filename);
479         mapfile = fopen(filename, "r");
480
481         if (mapfile == NULL) {
482                 radlog(L_ERR, "rlm_ldap: Opening file %s failed", filename);
483                 return -1; /* error */
484         }
485
486         /* read file line by line. Note that if line length exceed MAX_LINE_LEN, line numbers will be mixed up */
487
488         linenumber = 0;
489
490         while (fgets(buf, sizeof buf, mapfile)!=NULL) {
491                 char* ptr;
492                 int token_count;
493                 TLDAP_RADIUS* pair;
494
495                 linenumber++;
496
497                 /* strip comments */
498                 ptr = strchr(buf, '#');
499                 if (ptr) *ptr = 0;
500                 
501                 /* empty line */
502                 if (buf[0] == 0) continue;
503                 
504                 /* extract tokens from the string */            
505                 token_count = sscanf(buf, "%s %s %s", itemType, radiusAttribute, ldapAttribute);
506
507                 if (token_count <= 0) /* no tokens */                   
508                         continue;
509
510                 if (token_count != 3) {
511                         radlog(L_ERR, "rlm_ldap: Skipping %s line %i: %s", filename, linenumber, buf);
512                         radlog(L_ERR, "rlm_ldap: Expected 3 tokens "
513                                "(Item type, RADIUS Attribute and LDAP Attribute) but found only %i", token_count);
514                         continue;
515                 }
516
517                 /* create new TLDAP_RADIUS list node */
518                 pair = rad_malloc(sizeof(TLDAP_RADIUS));
519
520                 pair->attr = strdup(ldapAttribute);
521                 pair->radius_attr = strdup(radiusAttribute);
522
523                 if ( (pair->attr == NULL) || (pair->radius_attr == NULL) ) {
524                         radlog(L_ERR, "rlm_ldap: Out of memory");
525                         if (pair->attr) free(pair->attr);
526                         if (pair->radius_attr) free(pair->radius_attr);
527                         free(pair);
528                         fclose(mapfile);
529                         return -1;
530                 }
531                         
532                 /* push node to correct list */
533                 if (strcasecmp(itemType, "checkItem") == 0) {
534                         pair->next = inst->check_item_map;
535                         inst->check_item_map = pair;
536                 } else if (strcasecmp(itemType, "replyItem") == 0) {
537                         pair->next = inst->reply_item_map;
538                         inst->reply_item_map = pair;
539                 } else {
540                         radlog(L_ERR, "rlm_ldap: file %s: skipping line %i: unknown itemType %s", 
541                                filename, linenumber, itemType);
542                         free(pair->attr);
543                         free(pair->radius_attr);
544                         free(pair);
545                         continue;
546                 }
547
548                 DEBUG("rlm_ldap: LDAP %s mapped to RADIUS %s",
549                       pair->attr, pair->radius_attr);
550         }
551         
552         fclose(mapfile);
553
554         return 0; /* success */
555 }
556
557 static int 
558 perform_search(void *instance, LDAP_CONN *conn, char *search_basedn, int scope, char *filter, 
559                 char **attrs, LDAPMessage ** result)
560 {
561         int             res = RLM_MODULE_OK;
562         int             ldap_errno = 0;
563         ldap_instance  *inst = instance;
564         int             search_retry = 0;
565
566         *result = NULL;
567
568         if (!conn){
569                 radlog(L_ERR, "rlm_ldap: NULL connection handle passed");
570                 return RLM_MODULE_FAIL;
571         }
572         if (conn->failed_conns > MAX_FAILED_CONNS_START){
573                 conn->failed_conns++;
574                 if (conn->failed_conns >= MAX_FAILED_CONNS_END){
575                         conn->failed_conns = MAX_FAILED_CONNS_RESTART;
576                         conn->bound = 0;
577                 }
578         }
579 retry:
580         if (!conn->bound || conn->ld == NULL) {
581                 DEBUG2("rlm_ldap: attempting LDAP reconnection");
582                 if (conn->ld){
583                         DEBUG2("rlm_ldap: closing existing LDAP connection");
584                         ldap_unbind_s(conn->ld);
585                 }
586                 if ((conn->ld = ldap_connect(instance, inst->login, inst->password, 0, &res)) == NULL) {
587                         radlog(L_ERR, "rlm_ldap: (re)connection attempt failed");
588                         if (search_retry == 0)
589                                 conn->failed_conns++;
590                         return (RLM_MODULE_FAIL);
591                 }
592                 conn->bound = 1;
593                 conn->failed_conns = 0;
594         }
595         DEBUG2("rlm_ldap: performing search in %s, with filter %s", search_basedn ? search_basedn : "(null)" , filter);
596         switch (ldap_search_st(conn->ld, search_basedn, scope, filter, attrs, 0, &(inst->timeout), result)) {
597         case LDAP_SUCCESS:
598         case LDAP_NO_SUCH_OBJECT:
599                 break;
600         case LDAP_SERVER_DOWN:
601                 radlog(L_ERR, "rlm_ldap: ldap_search() failed: LDAP connection lost.");
602                 conn->failed_conns++;
603                 if (search_retry == 0){
604                         if (conn->failed_conns <= MAX_FAILED_CONNS_START){
605                                 radlog(L_INFO, "rlm_ldap: Attempting reconnect");
606                                 search_retry = 1;
607                                 conn->bound = 0;
608                                 ldap_msgfree(*result);  
609                                 goto retry;
610                         }
611                 }
612                 ldap_msgfree(*result);
613                 return RLM_MODULE_FAIL;
614         case LDAP_INSUFFICIENT_ACCESS:
615                 radlog(L_ERR, "rlm_ldap: ldap_search() failed: Insufficient access. Check the identity and password configuration directives.");
616                 ldap_msgfree(*result);
617                 return RLM_MODULE_FAIL;
618         case LDAP_TIMEOUT:
619                 radlog(L_ERR, "rlm_ldap: ldap_search() failed: Timed out while waiting for server to respond. Please increase the timeout.");
620                 ldap_msgfree(*result);
621                 return RLM_MODULE_FAIL;
622         case LDAP_TIMELIMIT_EXCEEDED:
623         case LDAP_BUSY:
624         case LDAP_UNAVAILABLE:
625                 /* We don't need to reconnect in these cases so we don't set conn->bound */
626                 ldap_get_option(conn->ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
627                 radlog(L_ERR, "rlm_ldap: ldap_search() failed: %s", ldap_err2string(ldap_errno));
628                 ldap_msgfree(*result);  
629                 return (RLM_MODULE_FAIL);
630         default:
631                 ldap_get_option(conn->ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
632                 radlog(L_ERR, "rlm_ldap: ldap_search() failed: %s", ldap_err2string(ldap_errno));
633                 conn->bound = 0;
634                 ldap_msgfree(*result);  
635                 return (RLM_MODULE_FAIL);
636         }
637
638         if ((ldap_count_entries(conn->ld, *result)) != 1) {
639                 DEBUG("rlm_ldap: object not found or got ambiguous search result");
640                 res = RLM_MODULE_NOTFOUND;
641                 ldap_msgfree(*result);  
642         }
643         return res;
644 }
645
646
647 /*
648  *      Translate the LDAP queries.
649  */
650 static int ldap_escape_func(char *out, int outlen, const char *in)
651 {
652         int len = 0;
653         
654         while (in[0]) {
655                 /*
656                  *  Only one byte left.
657                  */
658                 if (outlen <= 1) {
659                         break;
660                 }
661                 
662                 if (strchr("*", *in)) {
663                         in++;
664                         outlen--;
665                         continue;
666                 }
667                 
668                 /*
669                  *      Else it's a nice character.
670                  */
671                 *out = *in;
672                 out++;
673                 in++;
674                 outlen--;
675                 len++;
676         }
677         *out = '\0';
678         return len;
679 }
680
681 /*
682  * ldap_groupcmp(). Implement the Ldap-Group == "group" filter
683  */
684
685 static int ldap_groupcmp(void *instance, REQUEST *req, VALUE_PAIR *request, VALUE_PAIR *check,
686                 VALUE_PAIR *check_pairs, VALUE_PAIR **reply_pairs)
687 {
688         char            filter[MAX_FILTER_STR_LEN];
689         char            gr_filter[MAX_FILTER_STR_LEN];
690         int             res;
691         LDAPMessage     *result = NULL;
692         LDAPMessage     *msg = NULL;
693         char            basedn[MAX_FILTER_STR_LEN];
694         char            *attrs[] = {"dn",NULL};
695         char            **vals;
696         ldap_instance   *inst = instance;
697         char            *group_attrs[] = {inst->groupmemb_attr,NULL};
698         LDAP_CONN       *conn;
699         int             conn_id = -1;
700         VALUE_PAIR      *vp_user_dn;
701         VALUE_PAIR      **request_pairs;
702
703         request_pairs = &req->packet->vps;
704
705         DEBUG("rlm_ldap: Entering ldap_groupcmp()");
706
707         if (check->strvalue == NULL || check->length == 0){
708                 DEBUG("rlm_ldap::ldap_groupcmp: Illegal group name");
709                 return 1;
710         }
711
712         if (req == NULL){
713                 DEBUG("rlm_ldap::ldap_groupcmp: NULL request");
714                 return 1;
715         }
716
717         if (!radius_xlat(basedn, sizeof(basedn), inst->basedn, req, NULL)) {
718                 DEBUG("rlm_ldap::ldap_groupcmp: unable to create basedn.");
719                 return 1;
720         }
721
722         while((vp_user_dn = pairfind(*request_pairs, PW_LDAP_USERDN)) == NULL){
723                 char            *user_dn = NULL;
724
725                 if (!radius_xlat(filter, sizeof(filter), inst->filter,
726                                         req, ldap_escape_func)){
727                         DEBUG("rlm_ldap::ldap_groupcmp: unable to create filter");
728                         return 1;
729                 }
730                 if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
731                         radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
732                         return 1;
733                 }
734                 if ((res = perform_search(inst, conn, basedn, LDAP_SCOPE_SUBTREE,
735                                         filter, attrs, &result)) != RLM_MODULE_OK){
736                         DEBUG("rlm_ldap::ldap_groupcmp: search failed");
737                         ldap_release_conn(conn_id,inst->conns);
738                         return 1;
739                 }
740                 if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
741                         DEBUG("rlm_ldap::ldap_groupcmp: ldap_first_entry() failed");
742                         ldap_release_conn(conn_id,inst->conns);
743                         ldap_msgfree(result);
744                         return 1;
745                 }
746                 if ((user_dn = ldap_get_dn(conn->ld, msg)) == NULL) {
747                         DEBUG("rlm_ldap:ldap_groupcmp:: ldap_get_dn() failed");
748                         ldap_release_conn(conn_id,inst->conns);
749                         ldap_msgfree(result);
750                         return 1;
751                 }
752                 ldap_release_conn(conn_id,inst->conns);
753                 /*
754                 * Adding new attribute containing DN for LDAP object associated with
755                 * given username
756                 */
757                 pairadd(request_pairs, pairmake("Ldap-UserDn", user_dn, T_OP_EQ));
758                 ldap_memfree(user_dn);
759                 ldap_msgfree(result);
760         }
761
762         if(!radius_xlat(gr_filter, sizeof(gr_filter), inst->groupmemb_filt, req, NULL)){
763                 DEBUG("rlm_ldap::ldap_groupcmp: unable to create filter.");
764                 return 1;
765         }
766
767         if (strchr((char *)check->strvalue,',') != NULL) {
768                 /* This looks like a DN */
769                 snprintf(filter,sizeof(filter), "%s",gr_filter);
770                 snprintf(basedn,sizeof(basedn), "%s",(char *)check->strvalue);
771         } else 
772                 snprintf(filter,sizeof(filter), "(&(%s=%s)%s)",inst->groupname_attr,(char *)check->strvalue,gr_filter);
773
774         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
775                 radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
776                 return 1;
777         }
778         
779         if ((res = perform_search(inst, conn, basedn, LDAP_SCOPE_SUBTREE,
780                                 filter, attrs, &result)) == RLM_MODULE_OK){
781                 DEBUG("rlm_ldap::ldap_groupcmp: User found in group %s",
782                                 (char *)check->strvalue);
783                 ldap_msgfree(result);
784                 ldap_release_conn(conn_id,inst->conns);
785                 return 0;
786         }
787         
788         ldap_release_conn(conn_id,inst->conns);
789
790         if (res != RLM_MODULE_NOTFOUND ) {
791                 DEBUG("rlm_ldap::ldap_groupcmp: Search returned error");
792                 return 1;
793         }
794
795         if (inst->groupmemb_attr == NULL){
796                 /* search returned NOTFOUND and searching for membership 
797                  * using user object attributes is not specified in config
798                  * file
799                  */
800                 DEBUG("rlm_ldap::ldap_groupcmp: Group %s not found or user is not a member.",(char *)check->strvalue);
801                 return 1;
802         }
803
804         snprintf(filter,sizeof(filter), "(objectclass=*)");
805         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
806                 radlog(L_ERR, "rlm_ldap: Add ldap connections are in use");
807                 return 1;
808         }
809         if ((res = perform_search(inst, conn, vp_user_dn->strvalue, LDAP_SCOPE_BASE,
810                                         filter, group_attrs,&result)) != RLM_MODULE_OK){
811                 DEBUG("rlm_ldap::ldap_groupcmp: Search returned error");
812                 ldap_release_conn(conn_id, inst->conns);
813                 return 1;
814         }               
815
816         if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
817                 DEBUG("rlm_ldap::ldap_groupcmp: ldap_first_entry() failed");
818                 ldap_release_conn(conn_id,inst->conns);
819                 ldap_msgfree(result);
820                 return 1;
821         }
822         if ((vals = ldap_get_values(conn->ld, msg, inst->groupmemb_attr)) != NULL) {
823                 unsigned int i = 0;
824                 char found = 0;
825                 for (;i < ldap_count_values(vals);i++){
826                         if (strchr(vals[i],',') != NULL){ 
827                                 /* This looks like a DN */
828                                 LDAPMessage *gr_result = NULL;
829                                 snprintf(filter,sizeof(filter), "(%s=%s)",
830                                         inst->groupname_attr,
831                                         (char *)check->strvalue);
832                                 if ((res = perform_search(inst, conn, vals[i],
833                                                 LDAP_SCOPE_BASE, filter,
834                                                 attrs, &gr_result)) != RLM_MODULE_OK){
835                                         if (res != RLM_MODULE_NOTFOUND){
836                                                 DEBUG("rlm_ldap::ldap_groupcmp: \
837                                                         Search returned error");
838                                                 ldap_value_free(vals);
839                                                 ldap_msgfree(result);
840                                                 ldap_release_conn(conn_id,inst->conns);
841                                                 return 1;
842                                         }
843                                 } else {
844                                         ldap_msgfree(gr_result);
845                                         found = 1;
846                                         break;
847                                 }
848                         } else {
849                                 if (strcmp(vals[i],(char *)check->strvalue) == 0){
850                                         found = 1;
851                                         break;
852                                 }
853                         }
854                 }
855                 ldap_value_free(vals);
856                 ldap_msgfree(result);
857                 if (found == 0){
858                         DEBUG("rlm_ldap::groupcmp: Group %s not found \
859                                 or user not a member",
860                                 (char *)check->strvalue);
861                         ldap_release_conn(conn_id,inst->conns);
862                         return 1;
863                 }
864         } else {
865                         DEBUG("rlm_ldap::ldap_groupcmp: ldap_get_values() failed");
866                         ldap_msgfree(result);
867                         ldap_release_conn(conn_id,inst->conns);
868                         return 1;
869         }
870
871         DEBUG("rlm_ldap::ldap_groupcmp: User found in group %s",(char *)check->strvalue);
872         ldap_release_conn(conn_id,inst->conns);
873
874         return 0;
875 }
876
877 /*
878  * ldap_xlat()
879  * Do an xlat on an LDAP URL
880  */
881
882 static int ldap_xlat(void *instance, REQUEST *request, char *fmt, char *out, int freespace,
883                                 RADIUS_ESCAPE_STRING func)
884 {
885         char url[MAX_FILTER_STR_LEN];
886         int res;
887         int ret = 0;
888         ldap_instance *inst = instance;
889         LDAPURLDesc *ldap_url;
890         LDAPMessage *result = NULL;
891         LDAPMessage *msg = NULL;
892         char **vals;
893         int conn_id = -1;
894         LDAP_CONN *conn;
895
896         DEBUG("rlm_ldap: - ldap_xlat");
897         if (!radius_xlat(url, sizeof(url), fmt, request, func)) {
898                 radlog (L_ERR, "rlm_ldap: Unable to create LDAP URL.\n");
899                 return 0;
900         }
901         if (!ldap_is_ldap_url(url)){
902                 radlog (L_ERR, "rlm_ldap: String passed does not look like an LDAP URL.\n");
903                 return 0;
904         }
905         if (ldap_url_parse(url,&ldap_url)){
906                 radlog (L_ERR, "rlm_ldap: LDAP URL parse failed.\n");
907                 return 0;
908         }
909         if (ldap_url->lud_attrs == NULL || ldap_url->lud_attrs[0] == NULL || \
910                 ( ldap_url->lud_attrs[1] != NULL || ( ! strlen(ldap_url->lud_attrs[0]) || \
911                 ! strcmp(ldap_url->lud_attrs[0],"*") ) ) ){
912                 radlog (L_ERR, "rlm_ldap: Invalid Attribute(s) request.\n");
913                 ldap_free_urldesc(ldap_url);
914                 return 0;
915         }
916         if (ldap_url->lud_host){
917                 if (strncmp(inst->server,ldap_url->lud_host,strlen(inst->server)) != 0 || \
918                                 ldap_url->lud_port != inst->port){
919                         DEBUG("rlm_ldap: Requested server/port is not known to this module instance.");
920                         ldap_free_urldesc(ldap_url);
921                         return 0;
922                 }
923         }
924         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
925                 radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
926                 ldap_free_urldesc(ldap_url);
927                 return 0;
928         }
929         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){
930                 if (res == RLM_MODULE_NOTFOUND){
931                         DEBUG("rlm_ldap: Search returned not found");
932                         ldap_free_urldesc(ldap_url);
933                         ldap_release_conn(conn_id,inst->conns);
934                         return 0;
935                 }
936                 DEBUG("rlm_ldap: Search returned error");
937                 ldap_free_urldesc(ldap_url);
938                 ldap_release_conn(conn_id,inst->conns);
939                 return 0;
940         }
941         if ((msg = ldap_first_entry(conn->ld, result)) == NULL){
942                 DEBUG("rlm_ldap: ldap_first_entry() failed");
943                 ldap_msgfree(result);
944                 ldap_free_urldesc(ldap_url);
945                 ldap_release_conn(conn_id,inst->conns);
946                 return 0;
947         }
948         if ((vals = ldap_get_values(conn->ld, msg, ldap_url->lud_attrs[0])) != NULL) {
949                 ret = strlen(vals[0]);
950                 if (ret > freespace){
951                         DEBUG("rlm_ldap: Insufficient string space");
952                         ldap_free_urldesc(ldap_url);
953                         ldap_value_free(vals);
954                         ldap_msgfree(result);
955                         ldap_release_conn(conn_id,inst->conns);
956                         return 0;
957                 }
958                 DEBUG("rlm_ldap: Adding attribute %s, value: %s",ldap_url->lud_attrs[0],vals[0]);
959                 strncpy(out,vals[0],ret);
960                 ldap_value_free(vals);
961         }
962         else
963                 ret = 0;
964
965         ldap_msgfree(result);
966         ldap_free_urldesc(ldap_url);
967         ldap_release_conn(conn_id,inst->conns);
968
969         DEBUG("rlm_ldap: - ldap_xlat end");
970
971         return ret;
972 }
973
974
975 /******************************************************************************
976  *
977  *      Function: rlm_ldap_authorize
978  *
979  *      Purpose: Check if user is authorized for remote access
980  *
981  ******************************************************************************/
982 static int 
983 ldap_authorize(void *instance, REQUEST * request)
984 {
985         LDAPMessage     *result = NULL;
986         LDAPMessage     *msg = NULL;
987         LDAPMessage     *def_msg = NULL;
988         LDAPMessage     *def_attr_msg = NULL;
989         LDAPMessage     *def_result = NULL;
990         LDAPMessage     *def_attr_result = NULL;
991         ldap_instance   *inst = instance;
992         char            *user_dn = NULL;
993         char            filter[MAX_FILTER_STR_LEN];
994         char            basedn[MAX_FILTER_STR_LEN];
995         VALUE_PAIR      *check_tmp;
996         VALUE_PAIR      *reply_tmp;
997         int             res;
998         VALUE_PAIR      **check_pairs, **reply_pairs;
999         char            **vals;
1000         VALUE_PAIR      *module_fmsg_vp;
1001         VALUE_PAIR      *user_profile;
1002         char            module_fmsg[MAX_STRING_LEN];
1003         LDAP_CONN       *conn;
1004         int             conn_id = -1;
1005
1006         DEBUG("rlm_ldap: - authorize");
1007
1008         if (!request->username){
1009                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Name\" is required for authentication.\n");
1010                 return RLM_MODULE_INVALID;
1011         }
1012
1013         check_pairs = &request->config_items;
1014         reply_pairs = &request->reply->vps;
1015
1016         /*
1017          * Check for valid input, zero length names not permitted
1018          */
1019         if (request->username->strvalue == 0) {
1020                 radlog(L_ERR, "rlm_ldap: zero length username not permitted\n");
1021                 return RLM_MODULE_INVALID;
1022         }
1023         DEBUG("rlm_ldap: performing user authorization for %s",
1024                request->username->strvalue);
1025
1026         if (!radius_xlat(filter, sizeof(filter), inst->filter,
1027                          request, ldap_escape_func)) {
1028                 radlog (L_ERR, "rlm_ldap: unable to create filter.\n");
1029                 return RLM_MODULE_INVALID;
1030         }
1031
1032         if (!radius_xlat(basedn, sizeof(basedn), inst->basedn,
1033                          request, NULL)) {
1034                 radlog (L_ERR, "rlm_ldap: unable to create basedn.\n");
1035                 return RLM_MODULE_INVALID;
1036         }
1037
1038         if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
1039                 radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
1040                 return RLM_MODULE_FAIL;
1041         }
1042         if ((res = perform_search(instance, conn, basedn, LDAP_SCOPE_SUBTREE, filter, inst->atts, &result)) != RLM_MODULE_OK) {
1043                 DEBUG("rlm_ldap: search failed");
1044                 if (res == RLM_MODULE_NOTFOUND){
1045                         snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: User not found");
1046                         module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1047                         pairadd(&request->packet->vps, module_fmsg_vp);
1048                 }
1049                 ldap_release_conn(conn_id,inst->conns);
1050                 return (res);
1051         }
1052         if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
1053                 DEBUG("rlm_ldap: ldap_first_entry() failed");
1054                 ldap_msgfree(result);
1055                 ldap_release_conn(conn_id,inst->conns);
1056                 return RLM_MODULE_FAIL;
1057         }
1058         if ((user_dn = ldap_get_dn(conn->ld, msg)) == NULL) {
1059                 DEBUG("rlm_ldap: ldap_get_dn() failed");
1060                 ldap_msgfree(result);
1061                 ldap_release_conn(conn_id,inst->conns);
1062                 return RLM_MODULE_FAIL;
1063         }
1064         /*
1065          * Adding new attribute containing DN for LDAP object associated with
1066          * given username
1067          */
1068         pairadd(&request->packet->vps, pairmake("Ldap-UserDn", user_dn, T_OP_EQ));
1069         ldap_memfree(user_dn);
1070
1071
1072         /* Remote access is controled by attribute of the user object */
1073         if (inst->access_attr) {
1074                 if ((vals = ldap_get_values(conn->ld, msg, inst->access_attr)) != NULL) {
1075                         if (inst->default_allow){
1076                                 DEBUG("rlm_ldap: checking if remote access for %s is allowed by %s", request->username->strvalue, inst->access_attr);
1077                                 if (!strncmp(vals[0], "FALSE", 5)) {
1078                                         DEBUG("rlm_ldap: dialup access disabled");
1079                                         snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Access Attribute denies access");
1080                                         module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1081                                         pairadd(&request->packet->vps, module_fmsg_vp);
1082                                         ldap_msgfree(result);
1083                                         ldap_value_free(vals);
1084                                         ldap_release_conn(conn_id,inst->conns);
1085                                         return RLM_MODULE_USERLOCK;
1086                                 }
1087                                 ldap_value_free(vals);
1088                         }
1089                         else{
1090                                 DEBUG("rlm_ldap: %s attribute exists - access denied by default", inst->access_attr);
1091                                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Access Attribute denies access");
1092                                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1093                                 pairadd(&request->packet->vps, module_fmsg_vp);
1094                                 ldap_msgfree(result);
1095                                 ldap_value_free(vals);
1096                                 ldap_release_conn(conn_id,inst->conns);
1097                                 return RLM_MODULE_USERLOCK;
1098                         }
1099                 } else {
1100                         if (inst->default_allow){
1101                                 DEBUG("rlm_ldap: no %s attribute - access denied by default", inst->access_attr);
1102                                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Access Attribute denies access");
1103                                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1104                                 pairadd(&request->packet->vps, module_fmsg_vp);
1105                                 ldap_msgfree(result);
1106                                 ldap_release_conn(conn_id,inst->conns);
1107                                 return RLM_MODULE_USERLOCK;
1108                         }
1109                 }
1110         }
1111
1112         /*
1113          * Check for the default profile entry. If it exists then add the 
1114          * attributes it contains in the check and reply pairs
1115          */
1116
1117         user_profile = pairfind(request->config_items, PW_USER_PROFILE);
1118         if (inst->default_profile || user_profile){
1119                 char *profile = inst->default_profile;
1120
1121                 strNcpy(filter,"(objectclass=radiusprofile)",sizeof(filter));
1122                 if (user_profile)
1123                         profile = user_profile->strvalue;
1124                 if (profile && strlen(profile)){
1125                         if ((res = perform_search(instance, conn,
1126                                 profile, LDAP_SCOPE_BASE, 
1127                                 filter, inst->atts, &def_result)) == RLM_MODULE_OK){
1128                                 if ((def_msg = ldap_first_entry(conn->ld,def_result))){
1129                                         if ((check_tmp = ldap_pairget(conn->ld,def_msg,inst->check_item_map,check_pairs,1))) {
1130                                                 /*pairadd(check_pairs,check_tmp);*/
1131                                                 pairxlatmove(request, check_pairs, &check_tmp);
1132                                                 pairfree(&check_tmp);
1133                                         }
1134                                         if ((reply_tmp = ldap_pairget(conn->ld,def_msg,inst->reply_item_map,reply_pairs,0))) {
1135                                                 /*pairadd(reply_pairs,reply_tmp);*/
1136                                                 pairxlatmove(request, reply_pairs, &reply_tmp);
1137                                                 pairfree(&reply_tmp);
1138                                         }
1139                                 }
1140                                 ldap_msgfree(def_result);
1141                         } else 
1142                                 DEBUG("rlm_ldap: default_profile/user-profile search failed");
1143                 }
1144         }
1145
1146         /*
1147          * Check for the profile attribute. If it exists, we assume that it 
1148          * contains the DN of an entry containg a profile for the user. That
1149          * way we can have different general profiles for various user groups
1150          * (students,faculty,staff etc)
1151          */
1152
1153         if (inst->profile_attr){
1154                 if ((vals = ldap_get_values(conn->ld, msg, inst->profile_attr)) != NULL) {
1155                         unsigned int i=0;
1156                         strNcpy(filter,"(objectclass=radiusprofile)",sizeof(filter));
1157                         while(vals[i] != NULL && strlen(vals[i])){
1158                                 if ((res = perform_search(instance, conn,
1159                                         vals[i], LDAP_SCOPE_BASE, 
1160                                         filter, inst->atts, &def_attr_result)) == RLM_MODULE_OK){
1161                                         if ((def_attr_msg = ldap_first_entry(conn->ld,def_attr_result))){
1162                                                 if ((check_tmp = ldap_pairget(conn->ld,def_attr_msg,inst->check_item_map,check_pairs,1))) {
1163                                                         /*pairadd(check_pairs,check_tmp);*/
1164                                                         pairxlatmove(request, check_pairs, &check_tmp);
1165                                                         pairfree(&check_tmp);
1166                                                 }
1167                                                 if ((reply_tmp = ldap_pairget(conn->ld,def_attr_msg,inst->reply_item_map,reply_pairs,0))) {
1168                                                         /*pairadd(reply_pairs,reply_tmp);*/
1169                                                         pairxlatmove(request, reply_pairs, &reply_tmp);
1170                                                         pairfree(&reply_tmp);
1171                                                 }
1172                                         }
1173                                         ldap_msgfree(def_attr_result);
1174                                 } else 
1175                                         DEBUG("rlm_ldap: profile_attribute search failed");
1176                                 i++;
1177                         }
1178                         ldap_value_free(vals);
1179                 }
1180         }
1181         if (inst->passwd_attr && strlen(inst->passwd_attr)){
1182                 VALUE_PAIR *passwd_item;
1183
1184                 if ((passwd_item = pairfind(request->config_items, PW_PASSWORD)) == NULL){
1185                         char **passwd_vals;
1186                         char *passwd_val = NULL;
1187                         int passwd_len;
1188
1189                         if ((passwd_vals = ldap_get_values(conn->ld,msg,inst->passwd_attr)) != NULL){
1190                                 unsigned int i=0;
1191                                 while(passwd_vals[i] != NULL){
1192                                         if (strlen(passwd_vals[i])){
1193                                                 passwd_val = passwd_vals[i];
1194
1195                                                 if (inst->passwd_hdr && strlen(inst->passwd_hdr)){
1196                                                         passwd_val = strstr(passwd_val,inst->passwd_hdr);
1197                                                         if (passwd_val != NULL)
1198                                                                 passwd_val += strlen(inst->passwd_hdr);
1199                                                         else
1200                                                                 DEBUG("rlm_ldap: Password header not found in password %s for user %s", passwd_vals[0],request->username->strvalue);
1201                                                 }
1202                                                 if (passwd_val){
1203                                                         if ((passwd_item = paircreate(PW_PASSWORD,PW_TYPE_STRING)) == NULL){
1204                                                                 radlog(L_ERR|L_CONS, "no memory");
1205                                                                 ldap_value_free(passwd_vals);
1206                                                                 ldap_msgfree(result);
1207                                                                 ldap_release_conn(conn_id,inst->conns);
1208                                                                 return RLM_MODULE_FAIL;
1209                                                         }
1210                                                         passwd_len = strlen(passwd_val);
1211                                                         strncpy(passwd_item->strvalue,passwd_val,MAX_STRING_LEN - 1);
1212                                                         passwd_item->length = (passwd_len > (MAX_STRING_LEN - 1)) ? (MAX_STRING_LEN - 1) : passwd_len;
1213                                                         pairadd(&request->config_items,passwd_item);
1214                                                         DEBUG("rlm_ldap: Added password %s in check items",passwd_item->strvalue);
1215                                                 }
1216                                         }
1217                                         i++;
1218                                 }
1219                                 ldap_value_free(passwd_vals);
1220                         }
1221                 }
1222         }
1223
1224
1225
1226         DEBUG("rlm_ldap: looking for check items in directory...");
1227
1228         if ((check_tmp = ldap_pairget(conn->ld, msg, inst->check_item_map,check_pairs,1)) != NULL) {
1229                 /*pairadd(check_pairs,check_tmp);*/
1230                 pairxlatmove(request, check_pairs, &check_tmp);
1231                 pairfree(&check_tmp);
1232         }
1233
1234
1235         DEBUG("rlm_ldap: looking for reply items in directory...");
1236
1237
1238         if ((reply_tmp = ldap_pairget(conn->ld, msg, inst->reply_item_map,reply_pairs,0)) != NULL) {
1239                 /*pairadd(reply_pairs,reply_tmp);*/
1240                 pairxlatmove(request, reply_pairs, &reply_tmp);
1241                 pairfree(&reply_tmp);
1242         }
1243
1244        if (inst->do_comp && paircmp(request,request->packet->vps,*check_pairs,reply_pairs) != 0){
1245                 DEBUG("rlm_ldap: Pairs do not match. Rejecting user.");
1246                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Pairs do not match");
1247                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1248                 pairadd(&request->packet->vps, module_fmsg_vp);
1249                 ldap_msgfree(result);
1250                 ldap_release_conn(conn_id,inst->conns);
1251
1252                 return RLM_MODULE_REJECT;
1253         }
1254
1255         /*
1256          * Module should default to LDAP authentication if no Auth-Type
1257          * specified
1258          */
1259         if (pairfind(*check_pairs, PW_AUTHTYPE) == NULL)
1260                 pairadd(check_pairs, pairmake("Auth-Type", "LDAP", T_OP_EQ));
1261
1262
1263         DEBUG("rlm_ldap: user %s authorized to use remote access",
1264               request->username->strvalue);
1265         ldap_msgfree(result);
1266         ldap_release_conn(conn_id,inst->conns);
1267
1268         return RLM_MODULE_OK;
1269 }
1270
1271 /*****************************************************************************
1272  *
1273  *      Function: rlm_ldap_authenticate
1274  *
1275  *      Purpose: Check the user's password against ldap database
1276  *
1277  *****************************************************************************/
1278 static int 
1279 ldap_authenticate(void *instance, REQUEST * request)
1280 {
1281         LDAP           *ld_user;
1282         LDAPMessage    *result, *msg;
1283         ldap_instance  *inst = instance;
1284         char           *user_dn, *attrs[] = {"uid", NULL};
1285         char            filter[MAX_FILTER_STR_LEN];
1286         char            basedn[MAX_FILTER_STR_LEN];
1287         int             res;
1288         VALUE_PAIR     *vp_user_dn;
1289         VALUE_PAIR      *module_fmsg_vp;
1290         char            module_fmsg[MAX_STRING_LEN];
1291         LDAP_CONN       *conn;
1292         int             conn_id = -1;
1293
1294         DEBUG("rlm_ldap: - authenticate");
1295
1296         /*
1297          * Ensure that we're being passed a plain-text password, and not
1298          * anything else.
1299          */
1300
1301         if (!request->username) {
1302                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Name\" is required for authentication.\n");
1303                 return RLM_MODULE_INVALID;
1304         }
1305
1306         if (!request->password){
1307                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Password\" is required for authentication.");
1308                 return RLM_MODULE_INVALID;
1309         }
1310
1311         if(request->password->attribute != PW_PASSWORD) {
1312                 radlog(L_AUTH, "rlm_ldap: Attribute \"User-Password\" is required for authentication. Cannot use \"%s\".", request->password->name);
1313                 return RLM_MODULE_INVALID;
1314         }
1315
1316         if (request->password->length == 0) {
1317                 radlog(L_ERR, "rlm_ldap: empty password supplied");
1318                 return RLM_MODULE_INVALID;
1319         }
1320
1321         /*
1322          * Check that we don't have any failed connections. If we do there's no real need
1323          * of runing. Also give it another chance if we have a lot of failed connections.
1324          */
1325         if (inst->failed_conns > MAX_FAILED_CONNS_END)
1326                 inst->failed_conns = 0;
1327         if (inst->failed_conns > MAX_FAILED_CONNS_START){
1328                 inst->failed_conns++;
1329                 return RLM_MODULE_FAIL;
1330         }
1331
1332
1333         DEBUG("rlm_ldap: login attempt by \"%s\" with password \"%s\"", 
1334                request->username->strvalue, request->password->strvalue);
1335
1336         while((vp_user_dn = pairfind(request->packet->vps, PW_LDAP_USERDN)) == NULL) {
1337                 if (!radius_xlat(filter, sizeof(filter), inst->filter,
1338                                 request, NULL)) {
1339                         radlog (L_ERR, "rlm_ldap: unable to create filter.\n"); 
1340                         return RLM_MODULE_INVALID;
1341                 }
1342
1343                 if (!radius_xlat(basedn, sizeof(basedn), inst->basedn,
1344                                 request, NULL)) {
1345                         radlog (L_ERR, "rlm_ldap: unable to create basedn.\n");
1346                         return RLM_MODULE_INVALID;
1347                 }
1348
1349                 if ((conn_id = ldap_get_conn(inst->conns,&conn,inst)) == -1){
1350                         radlog(L_ERR, "rlm_ldap: All ldap connections are in use");
1351                         return RLM_MODULE_FAIL;
1352                 }
1353                 if ((res = perform_search(instance, conn, basedn, LDAP_SCOPE_SUBTREE, filter, attrs, &result)) != RLM_MODULE_OK) {
1354                         if (res == RLM_MODULE_NOTFOUND){
1355                                 snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: User not found");
1356                                 module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1357                                 pairadd(&request->packet->vps, module_fmsg_vp);
1358                         }
1359                         ldap_release_conn(conn_id,inst->conns);
1360                         return (res);
1361                 }
1362                 if ((msg = ldap_first_entry(conn->ld, result)) == NULL) {
1363                         ldap_msgfree(result);
1364                         ldap_release_conn(conn_id,inst->conns);
1365                         return RLM_MODULE_FAIL;
1366                 }
1367                 if ((user_dn = ldap_get_dn(conn->ld, msg)) == NULL) {
1368                         DEBUG("rlm_ldap: ldap_get_dn() failed");
1369                         ldap_msgfree(result);
1370                         ldap_release_conn(conn_id,inst->conns);
1371                         return RLM_MODULE_FAIL;
1372                 }
1373                 ldap_release_conn(conn_id,inst->conns);
1374                 pairadd(&request->packet->vps, pairmake("Ldap-UserDn", user_dn, T_OP_EQ));
1375                 ldap_memfree(user_dn);
1376                 ldap_msgfree(result);
1377         }
1378
1379         user_dn = vp_user_dn->strvalue;
1380
1381         DEBUG("rlm_ldap: user DN: %s", user_dn);
1382
1383         ld_user = ldap_connect(instance, user_dn, request->password->strvalue,
1384                                1, &res);
1385         if (ld_user == NULL){
1386                 if (res == RLM_MODULE_REJECT){
1387                         inst->failed_conns = 0;
1388                         snprintf(module_fmsg,sizeof(module_fmsg),"rlm_ldap: Bind as user failed");
1389                         module_fmsg_vp = pairmake("Module-Failure-Message", module_fmsg, T_OP_EQ);
1390                         pairadd(&request->packet->vps, module_fmsg_vp);
1391                 }
1392                 if (res == RLM_MODULE_FAIL){
1393                         DEBUG("rlm_ldap: ldap_connect() failed");
1394                         inst->failed_conns++;
1395                 }
1396                 return (res);
1397         }
1398
1399         DEBUG("rlm_ldap: user %s authenticated succesfully",
1400               request->username->strvalue);
1401         ldap_unbind_s(ld_user);
1402         inst->failed_conns = 0;
1403
1404         return RLM_MODULE_OK;
1405 }
1406
1407 static LDAP    *
1408 ldap_connect(void *instance, const char *dn, const char *password, int auth, int *result)
1409 {
1410         ldap_instance  *inst = instance;
1411         LDAP           *ld = NULL;
1412         int             msgid, rc, ldap_version;
1413         int             ldap_errno = 0;
1414         LDAPMessage    *res;
1415
1416         if (inst->is_url){
1417 #ifdef HAVE_LDAP_INITIALIZE
1418                 DEBUG("rlm_ldap: (re)connect to %s, authentication %d", inst->server, auth);
1419                 if (ldap_initialize(&ld, inst->server) != LDAP_SUCCESS) {
1420                         radlog(L_ERR, "rlm_ldap: ldap_initialize() failed");
1421                         *result = RLM_MODULE_FAIL;
1422                         return (NULL);
1423                 }
1424 #endif
1425         }
1426         else{
1427                 DEBUG("rlm_ldap: (re)connect to %s:%d, authentication %d", inst->server, inst->port, auth);
1428                 if ((ld = ldap_init(inst->server, inst->port)) == NULL) {
1429                         radlog(L_ERR, "rlm_ldap: ldap_init() failed");
1430                         *result = RLM_MODULE_FAIL;
1431                         return (NULL);
1432                 }
1433         }
1434         if (ldap_set_option(ld, LDAP_OPT_NETWORK_TIMEOUT, (void *) &(inst->net_timeout)) != LDAP_OPT_SUCCESS) {
1435                 radlog(L_ERR, "rlm_ldap: Could not set LDAP_OPT_NETWORK_TIMEOUT %ld.%ld", inst->net_timeout.tv_sec, inst->net_timeout.tv_usec);
1436         }
1437         if (ldap_set_option(ld, LDAP_OPT_TIMELIMIT, (void *) &(inst->timelimit)) != LDAP_OPT_SUCCESS) {
1438                 radlog(L_ERR, "rlm_ldap: Could not set LDAP_OPT_TIMELIMIT %d", inst->timelimit);
1439         }
1440         if (inst->ldap_debug && ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, &(inst->ldap_debug)) != LDAP_OPT_SUCCESS) {
1441                 radlog(L_ERR, "rlm_ldap: Could not set LDAP_OPT_DEBUG_LEVEL %d", inst->ldap_debug);
1442         }
1443         ldap_version = LDAP_VERSION3;
1444         if (ldap_set_option(ld, LDAP_OPT_PROTOCOL_VERSION, &ldap_version) != LDAP_OPT_SUCCESS) {
1445                 radlog(L_ERR, "rlm_ldap: Could not set LDAP version to V3");
1446         }
1447 #ifdef HAVE_LDAP_START_TLS
1448         if(inst->tls_mode) {
1449                 DEBUG("rlm_ldap: setting TLS mode to %d", inst->tls_mode);
1450                 if(ldap_set_option(ld, LDAP_OPT_X_TLS,
1451                            (void *) &(inst->tls_mode)) != LDAP_OPT_SUCCESS) {
1452                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
1453                         radlog(L_ERR, "rlm_ldap: could not set LDAP_OPT_X_TLS option %s", ldap_err2string(ldap_errno));
1454                 }
1455         }
1456         if (inst->start_tls) {
1457                 DEBUG("rlm_ldap: starting TLS");
1458                 rc = ldap_start_tls_s(ld, NULL, NULL);
1459                 if (rc != LDAP_SUCCESS) {
1460                         DEBUG("rlm_ldap: ldap_start_tls_s()");
1461                         ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
1462                         radlog(L_ERR, "rlm_ldap: could not start TLS %s", ldap_err2string(ldap_errno));
1463                         *result = RLM_MODULE_FAIL;
1464                         ldap_unbind_s(ld);
1465                         return (NULL);
1466                 }
1467         }
1468 #endif /* HAVE_LDAP_START_TLS */
1469
1470         if (inst->is_url){
1471                 DEBUG("rlm_ldap: bind as %s/%s to %s", dn, password, inst->server);
1472         }
1473         else{
1474                 DEBUG("rlm_ldap: bind as %s/%s to %s:%d", dn, password, inst->server, inst->port);
1475         }
1476         msgid = ldap_bind(ld, dn, password,LDAP_AUTH_SIMPLE);
1477         if (msgid == -1) {
1478                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
1479                 if (inst->is_url)
1480                         radlog(L_ERR, "rlm_ldap: %s bind to %s failed: %s",
1481                                 dn, inst->server, ldap_err2string(ldap_errno));
1482                 else
1483                         radlog(L_ERR, "rlm_ldap: %s bind to %s:%d failed: %s",
1484                                 dn, inst->server, inst->port,
1485                                 ldap_err2string(ldap_errno));
1486                 *result = RLM_MODULE_FAIL;
1487                 ldap_unbind_s(ld);
1488                 return (NULL);
1489         }
1490         DEBUG("rlm_ldap: waiting for bind result ...");
1491
1492         rc = ldap_result(ld, msgid, 1, &(inst->timeout), &res);
1493
1494         if(rc < 1) {
1495                 DEBUG("rlm_ldap: ldap_result()");
1496                 ldap_get_option(ld, LDAP_OPT_ERROR_NUMBER, &ldap_errno);
1497                 if (inst->is_url)
1498                         radlog(L_ERR, "rlm_ldap: %s bind to %s failed: %s",
1499                                 dn, inst->server, (rc == 0) ? "timeout" : ldap_err2string(ldap_errno));
1500                 else
1501                         radlog(L_ERR, "rlm_ldap: %s bind to %s:%d failed: %s",
1502                                 dn, inst->server, inst->port,
1503                                 (rc == 0) ? "timeout" : ldap_err2string(ldap_errno));
1504                 *result = RLM_MODULE_FAIL;
1505                 ldap_unbind_s(ld);
1506                 return (NULL);
1507         }
1508         ldap_errno = ldap_result2error(ld, res, 1);
1509         switch (ldap_errno) {
1510         case LDAP_SUCCESS:
1511                 *result = RLM_MODULE_OK;
1512                 break;
1513
1514         case LDAP_INVALID_CREDENTIALS:
1515                 if (auth) 
1516                         *result = RLM_MODULE_REJECT;
1517                 else {
1518                         radlog(L_ERR, "rlm_ldap: LDAP login failed: check login, password settings in ldap section of radiusd.conf");
1519                         *result = RLM_MODULE_FAIL;
1520                 }               
1521                 break;
1522                 
1523         default:
1524                 if (inst->is_url)
1525                         radlog(L_ERR,"rlm_ldap: %s bind to %s failed %s",
1526                                 dn, inst->server, ldap_err2string(ldap_errno));
1527                 else
1528                         radlog(L_ERR,"rlm_ldap: %s bind to %s:%d failed %s",
1529                                 dn, inst->server, inst->port,
1530                                 ldap_err2string(ldap_errno));
1531                 *result = RLM_MODULE_FAIL;
1532         }
1533
1534         if (*result != RLM_MODULE_OK) {
1535                 ldap_unbind_s(ld);
1536                 ld = NULL;
1537         }
1538         return ld;
1539 }
1540
1541 /*****************************************************************************
1542  *
1543  *      Detach from the LDAP server and cleanup internal state.
1544  *
1545  *****************************************************************************/
1546 static int 
1547 ldap_detach(void *instance)
1548 {
1549         ldap_instance  *inst = instance;
1550         TLDAP_RADIUS *pair, *nextpair;
1551
1552         if (inst->server)
1553                 free((char *) inst->server);
1554         if (inst->login)
1555                 free((char *) inst->login);
1556         if (inst->password)
1557                 free((char *) inst->password);
1558         if (inst->basedn)
1559                 free((char *) inst->basedn);
1560         if (inst->dictionary_mapping)
1561                 free(inst->dictionary_mapping);
1562         if (inst->filter)
1563                 free((char *) inst->filter);
1564         if (inst->passwd_hdr)
1565                 free((char *) inst->passwd_hdr);
1566         if (inst->passwd_attr)
1567                 free((char *) inst->passwd_attr);
1568         if (inst->groupname_attr)
1569                 free((char *) inst->groupname_attr);
1570         if (inst->groupmemb_filt)
1571                 free((char *) inst->groupmemb_filt);
1572         if (inst->groupmemb_attr)
1573                 free((char *) inst->groupmemb_attr);
1574         if (inst->access_attr)
1575                 free((char *) inst->access_attr);
1576         if (inst->profile_attr)
1577                 free((char *) inst->profile_attr);
1578         if (inst->conns){
1579                 int i=0;
1580
1581                 for(;i<inst->num_conns;i++){
1582                         if (inst->conns[i].ld){
1583                                 ldap_unbind_s(inst->conns[i].ld);
1584                         }
1585                         pthread_mutex_destroy(&inst->conns[i].mutex);
1586                 }
1587                 free(inst->conns);
1588         }
1589
1590         pair = inst->check_item_map;
1591         
1592         while (pair != NULL) {
1593                 nextpair = pair->next;
1594                 free(pair->attr);
1595                 free(pair->radius_attr);
1596                 free(pair);
1597                 pair = nextpair;
1598         }
1599
1600         pair = inst->reply_item_map;
1601
1602         while (pair != NULL) {
1603                 nextpair = pair->next;
1604                 free(pair->attr);
1605                 free(pair->radius_attr);
1606                 free(pair);
1607                 pair = nextpair;
1608         }
1609
1610         if (inst->atts)
1611                 free(inst->atts);
1612
1613         paircompare_unregister(PW_LDAP_GROUP, ldap_groupcmp);
1614         xlat_unregister(inst->xlat_name,ldap_xlat);
1615         free(inst->xlat_name);
1616
1617         free(inst);
1618
1619         return 0;
1620 }
1621
1622 #ifdef FIELDCPY
1623 static void 
1624 fieldcpy(char *string, char **uptr)
1625 {
1626         char           *ptr;
1627
1628         ptr = *uptr;
1629         while (*ptr == ' ' || *ptr == '\t') {
1630                 ptr++;
1631         }
1632         if (*ptr == '"') {
1633                 ptr++;
1634                 while (*ptr != '"' && *ptr != '\0' && *ptr != '\n') {
1635                         *string++ = *ptr++;
1636                 }
1637                 *string = '\0';
1638                 if (*ptr == '"') {
1639                         ptr++;
1640                 }
1641                 *uptr = ptr;
1642                 return;
1643         }
1644         while (*ptr != ' ' && *ptr != '\t' && *ptr != '\0' && *ptr != '\n' &&
1645                *ptr != '=' && *ptr != ',') {
1646                 *string++ = *ptr++;
1647         }
1648         *string = '\0';
1649         *uptr = ptr;
1650         return;
1651 }
1652 #endif
1653 /*****************************************************************************
1654  *      Get RADIUS attributes from LDAP object
1655  *      ( according to draft-adoba-radius-05.txt
1656  *        <http://www.ietf.org/internet-drafts/draft-adoba-radius-05.txt> )
1657  *
1658  *****************************************************************************/
1659
1660 static VALUE_PAIR *
1661 ldap_pairget(LDAP * ld, LDAPMessage * entry,
1662              TLDAP_RADIUS * item_map, VALUE_PAIR **pairs,char is_check)
1663 {
1664         char          **vals;
1665         int             vals_count;
1666         int             vals_idx;
1667         char           *ptr;
1668         TLDAP_RADIUS   *element;
1669         LRAD_TOKEN      token;
1670         int             is_generic_attribute;
1671         char            value[256];
1672         VALUE_PAIR     *pairlist = NULL;
1673         VALUE_PAIR     *newpair = NULL;
1674
1675         /* check if there is a mapping from this LDAP attribute to a RADIUS attribute */
1676         for (element = item_map; element != NULL; element = element->next) {
1677         if ((vals = ldap_get_values(ld,entry,element->attr)) != NULL){
1678                         /* check whether this is a one-to-one-mapped ldap attribute or a generic
1679                            attribute and set flag accordingly */
1680
1681                         if (strcasecmp(element->radius_attr, GENERIC_ATTRIBUTE_ID)==0)
1682                                 is_generic_attribute = 1;
1683                         else
1684                                 is_generic_attribute = 0;
1685
1686                         /* find out how many values there are for the attribute and extract all of them */
1687
1688                         vals_count = ldap_count_values(vals);
1689
1690                         for (vals_idx = 0; vals_idx < vals_count; vals_idx++) {
1691                                 ptr = vals[vals_idx];
1692
1693                                 if (is_generic_attribute) {
1694                                         /* this is a generic attribute */
1695                                         LRAD_TOKEN dummy; /* makes pairread happy */
1696                                         
1697                                         /* not sure if using pairread here is ok ... */
1698                                         if ( (newpair = pairread(&ptr, &dummy)) != NULL) {
1699                                                 DEBUG("rlm_ldap: extracted attribute %s from generic item %s", 
1700                                                       newpair->name, vals[vals_idx]);
1701                                                 pairadd(&pairlist, newpair);
1702                                         } else {
1703                                                 radlog(L_ERR, "rlm_ldap: parsing %s failed: %s", 
1704                                                        element->attr, vals[vals_idx]);
1705                                         }
1706                                 } else {
1707                                         /* this is a one-to-one-mapped attribute */
1708                                         token = gettoken(&ptr, value, sizeof(value) - 1);
1709                                         if (token < T_EQSTART || token > T_EQEND) {
1710                                                 token = (is_check) ? T_OP_CMP_EQ : T_OP_EQ;
1711                                         } else {
1712                                                 gettoken(&ptr, value, sizeof(value) - 1);
1713                                         }
1714                                         if (value[0] == 0) {
1715                                                 DEBUG("rlm_ldap: Attribute %s has no value", element->attr);
1716                                                 break;
1717                                         }
1718                                         DEBUG("rlm_ldap: Adding %s as %s, value %s & op=%d", element->attr, element->radius_attr, value, token);
1719                                                 if ((newpair = pairmake(element->radius_attr, value, token)) == NULL)
1720                                                 continue;
1721                                         if (! vals_idx){
1722                                                 pairdelete(pairs,newpair->attribute);
1723                                         }
1724                                         pairadd(&pairlist, newpair);
1725                                 }
1726                         }
1727                         ldap_value_free(vals);
1728                 }
1729         }
1730
1731         return (pairlist);
1732 }
1733
1734 /* globally exported name */
1735 module_t        rlm_ldap = {
1736         "LDAP",
1737         RLM_TYPE_THREAD_SAFE,   /* type: reserved        */
1738         NULL,                   /* initialization        */
1739         ldap_instantiate,       /* instantiation         */
1740         {
1741                 ldap_authenticate,      /* authentication        */
1742                 ldap_authorize,         /* authorization         */
1743                 NULL,                   /* preaccounting         */
1744                 NULL,                   /* accounting            */
1745                 NULL,                   /* checksimul            */
1746                 NULL,                   /* pre-proxy             */
1747                 NULL,                   /* post-proxy            */
1748                 NULL                    /* post-auth             */
1749         },
1750         ldap_detach,            /* detach                */
1751         NULL,                   /* destroy               */
1752 };