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