Small tweak to ldap debug output
[freeradius.git] / src / modules / rlm_ldap / rlm_ldap.c
1 /*
2  *   This program is is free software; you can redistribute it and/or modify
3  *   it under the terms of the GNU General Public License, version 2 if the
4  *   License as published by the Free Software Foundation.
5  *
6  *   This program is distributed in the hope that it will be useful,
7  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
8  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9  *   GNU General Public License for more details.
10  *
11  *   You should have received a copy of the GNU General Public License
12  *   along with this program; if not, write to the Free Software
13  *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
14  */
15
16 /**
17  * $Id$
18  * @file rlm_ldap.c
19  * @brief LDAP authorization and authentication module.
20  *
21  * @author Arran Cudbard-Bell <a.cudbardb@freeradius.org>
22  * @author Alan DeKok <aland@freeradius.org>
23  *
24  * @copyright 2013 Network RADIUS SARL <info@networkradius.com>
25  * @copyright 2012-2013 Arran Cudbard-Bell <a.cudbardb@freeradius.org>
26  * @copyright 2012 Alan DeKok <aland@freeradius.org>
27  * @copyright 1999-2013 The FreeRADIUS Server Project.
28  */
29 RCSID("$Id$")
30
31 #include        <freeradius-devel/rad_assert.h>
32
33 #include        <stdarg.h>
34 #include        <ctype.h>
35
36 #include        "ldap.h"
37
38 /*
39  *      Scopes
40  */
41 const FR_NAME_NUMBER ldap_scope[] = {
42         { "sub",        LDAP_SCOPE_SUB  },
43         { "one",        LDAP_SCOPE_ONE  },
44         { "base",       LDAP_SCOPE_BASE },
45         { "children",   LDAP_SCOPE_CHILDREN },
46
47         {  NULL , -1 }
48 };
49
50 #ifdef LDAP_OPT_X_TLS_NEVER
51 const FR_NAME_NUMBER ldap_tls_require_cert[] = {
52         { "never",      LDAP_OPT_X_TLS_NEVER    },
53         { "demand",     LDAP_OPT_X_TLS_DEMAND   },
54         { "allow",      LDAP_OPT_X_TLS_ALLOW    },
55         { "try",        LDAP_OPT_X_TLS_TRY      },
56         { "hard",       LDAP_OPT_X_TLS_HARD     },      /* oh yes, just like that */
57
58         {  NULL , -1 }
59 };
60 #endif
61
62 /*
63  *      TLS Configuration
64  */
65 static CONF_PARSER tls_config[] = {
66         /*
67          *      Deprecated attributes
68          */
69         {"cacertfile", PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, offsetof(ldap_instance_t, tls_ca_file), NULL, NULL},
70         {"ca_file", PW_TYPE_FILE_INPUT, offsetof(ldap_instance_t, tls_ca_file), NULL, NULL},
71
72         {"cacertdir", PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, offsetof(ldap_instance_t, tls_ca_path), NULL, NULL},
73         {"ca_path", PW_TYPE_FILE_INPUT, offsetof(ldap_instance_t, tls_ca_path), NULL, NULL},
74
75         {"certfile", PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, offsetof(ldap_instance_t, tls_certificate_file), NULL, NULL},
76         {"certificate_file", PW_TYPE_FILE_INPUT, offsetof(ldap_instance_t, tls_certificate_file), NULL, NULL},
77
78         {"keyfile", PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, offsetof(ldap_instance_t, tls_private_key_file), NULL, NULL}, // OK if it changes on HUP
79         {"private_key_file", PW_TYPE_FILE_INPUT, offsetof(ldap_instance_t, tls_private_key_file), NULL, NULL}, // OK if it changes on HUP
80
81         {"randfile", PW_TYPE_FILE_INPUT | PW_TYPE_DEPRECATED, offsetof(ldap_instance_t, tls_random_file), NULL, NULL},
82         {"random_file", PW_TYPE_FILE_INPUT, offsetof(ldap_instance_t, tls_random_file), NULL, NULL},
83
84         /*
85          *      LDAP Specific TLS attributes
86          */
87         {"start_tls", PW_TYPE_BOOLEAN, offsetof(ldap_instance_t, start_tls), NULL, "no"},
88         {"require_cert", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, tls_require_cert_str), NULL, NULL},
89
90         { NULL, -1, 0, NULL, NULL }
91 };
92
93
94 static CONF_PARSER profile_config[] = {
95         {"filter", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, profile_filter), NULL, "(&)"}, //!< Correct filter for
96                                                                                                 //!< when the DN is
97                                                                                                 //!< known.
98         {"attribute", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, profile_attr), NULL, NULL},
99         {"default", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, default_profile), NULL, NULL},
100
101         { NULL, -1, 0, NULL, NULL }
102 };
103
104 /*
105  *      User configuration
106  */
107 static CONF_PARSER user_config[] = {
108         {"filter", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, userobj_filter), NULL, "(uid=%u)"},
109         {"scope", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, userobj_scope_str), NULL, "sub"},
110         {"base_dn", PW_TYPE_STRING_PTR | PW_TYPE_REQUIRED, offsetof(ldap_instance_t,userobj_base_dn), NULL, NULL},
111
112         {"access_attribute", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, userobj_access_attr), NULL, NULL},
113         {"access_positive", PW_TYPE_BOOLEAN, offsetof(ldap_instance_t, access_positive), NULL, "yes"},
114
115         { NULL, -1, 0, NULL, NULL }
116 };
117
118 /*
119  *      Group configuration
120  */
121 static CONF_PARSER group_config[] = {
122         {"filter", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, groupobj_filter), NULL, NULL},
123         {"scope", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, groupobj_scope_str), NULL, "sub"},
124         {"base_dn", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, groupobj_base_dn), NULL, NULL},
125
126         {"name_attribute", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, groupobj_name_attr), NULL, "cn"},
127         {"membership_attribute", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, userobj_membership_attr), NULL, NULL},
128         {"membership_filter", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, groupobj_membership_filter), NULL, NULL},
129         {"cacheable_name", PW_TYPE_BOOLEAN, offsetof(ldap_instance_t, cacheable_group_name), NULL, "no"},
130         {"cacheable_dn", PW_TYPE_BOOLEAN, offsetof(ldap_instance_t, cacheable_group_dn), NULL, "no"},
131
132         { NULL, -1, 0, NULL, NULL }
133 };
134
135 /*
136  *      Client configuration
137  */
138 static CONF_PARSER client_attribute[] = {
139         {"identifier", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, clientobj_identifier), NULL, "host"},
140         {"shortname", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, clientobj_shortname), NULL, "cn"},
141         {"nas_type", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, clientobj_type), NULL, NULL},
142         {"secret", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, clientobj_secret), NULL, NULL},
143         {"virtual_server", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, clientobj_server), NULL, NULL},
144         {"require_message_authenticator", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, clientobj_require_ma),
145          NULL, NULL},
146
147         { NULL, -1, 0, NULL, NULL }
148 };
149
150 static CONF_PARSER client_config[] = {
151         {"filter", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, clientobj_filter), NULL, NULL},
152         {"scope", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, clientobj_scope_str), NULL, "sub"},
153         {"base_dn", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, clientobj_base_dn), NULL, NULL},
154         {"attribute", PW_TYPE_SUBSECTION, 0, NULL, (void const *) client_attribute},
155
156         { NULL, -1, 0, NULL, NULL }
157 };
158
159 /*
160  *      Reference for accounting updates
161  */
162 static const CONF_PARSER acct_section_config[] = {
163         {"reference", PW_TYPE_STRING_PTR, offsetof(ldap_acct_section_t, reference), NULL, "."},
164
165         {NULL, -1, 0, NULL, NULL}
166 };
167
168 /*
169  *      Various options that don't belong in the main configuration.
170  *
171  *      Note that these overlap a bit with the connection pool code!
172  */
173 static CONF_PARSER option_config[] = {
174         /*
175          *      Debugging flags to the server
176          */
177         {"ldap_debug", PW_TYPE_INTEGER, offsetof(ldap_instance_t,ldap_debug), NULL, "0x0000"},
178
179         {"chase_referrals", PW_TYPE_BOOLEAN, offsetof(ldap_instance_t,chase_referrals), NULL, NULL},
180
181         {"rebind", PW_TYPE_BOOLEAN, offsetof(ldap_instance_t,rebind), NULL, NULL},
182
183         /* timeout on network activity */
184         {"net_timeout", PW_TYPE_INTEGER, offsetof(ldap_instance_t,net_timeout), NULL, "10"},
185
186         /* timeout for search results */
187         {"res_timeout", PW_TYPE_INTEGER, offsetof(ldap_instance_t,res_timeout), NULL, "20"},
188
189         /* allow server unlimited time for search (server-side limit) */
190         {"srv_timelimit", PW_TYPE_INTEGER, offsetof(ldap_instance_t,srv_timelimit), NULL, "20"},
191
192 #ifdef LDAP_OPT_X_KEEPALIVE_IDLE
193         {"idle", PW_TYPE_INTEGER, offsetof(ldap_instance_t,keepalive_idle), NULL, "60"},
194 #endif
195 #ifdef LDAP_OPT_X_KEEPALIVE_PROBES
196         {"probes", PW_TYPE_INTEGER, offsetof(ldap_instance_t,keepalive_probes), NULL, "3"},
197 #endif
198 #ifdef LDAP_OPT_X_KEEPALIVE_INTERVAL
199         {"interval", PW_TYPE_INTEGER,  offsetof(ldap_instance_t,keepalive_interval), NULL, "30"},
200 #endif
201
202         { NULL, -1, 0, NULL, NULL }
203 };
204
205
206 static const CONF_PARSER module_config[] = {
207         {"server", PW_TYPE_STRING_PTR | PW_TYPE_REQUIRED, offsetof(ldap_instance_t,server), NULL, "localhost"},
208         {"port", PW_TYPE_INTEGER, offsetof(ldap_instance_t,port), NULL, "389"},
209
210         {"password", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t,password), NULL, ""},
211         {"identity", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t,admin_dn), NULL, ""},
212
213         {"valuepair_attribute", PW_TYPE_STRING_PTR, offsetof(ldap_instance_t, valuepair_attr), NULL, NULL},
214
215 #ifdef WITH_EDIR
216         /* support for eDirectory Universal Password */
217         {"edir", PW_TYPE_BOOLEAN, offsetof(ldap_instance_t,edir), NULL, NULL}, /* NULL defaults to "no" */
218
219         /*
220          *      Attempt to bind with the Cleartext password we got from eDirectory
221          *      Universal password for additional authorization checks.
222          */
223         {"edir_autz", PW_TYPE_BOOLEAN, offsetof(ldap_instance_t,edir_autz), NULL, NULL}, /* NULL defaults to "no" */
224 #endif
225
226         {"read_clients", PW_TYPE_BOOLEAN, offsetof(ldap_instance_t,do_clients), NULL, NULL}, /* NULL defaults to "no" */
227
228         { "user", PW_TYPE_SUBSECTION, 0, NULL, (void const *) user_config },
229
230         { "group", PW_TYPE_SUBSECTION, 0, NULL, (void const *) group_config },
231
232         { "client", PW_TYPE_SUBSECTION, 0, NULL, (void const *) client_config },
233
234         { "profile", PW_TYPE_SUBSECTION, 0, NULL, (void const *) profile_config },
235
236         { "options", PW_TYPE_SUBSECTION, 0, NULL, (void const *) option_config },
237
238         { "tls", PW_TYPE_SUBSECTION, 0, NULL, (void const *) tls_config },
239
240         {NULL, -1, 0, NULL, NULL}
241 };
242
243 /** Expand an LDAP URL into a query, and return a string result from that query.
244  *
245  */
246 static ssize_t ldap_xlat(void *instance, REQUEST *request, char const *fmt, char *out, size_t freespace)
247 {
248         ldap_rcode_t status;
249         size_t len = 0;
250         ldap_instance_t *inst = instance;
251         LDAPURLDesc *ldap_url;
252         LDAPMessage *result = NULL;
253         LDAPMessage *entry = NULL;
254         char **vals;
255         ldap_handle_t *conn;
256         int ldap_errno;
257         char const *url;
258         char const **attrs;
259
260         url = fmt;
261
262         if (!ldap_is_ldap_url(url)) {
263                 REDEBUG("String passed does not look like an LDAP URL");
264                 return -1;
265         }
266
267         if (ldap_url_parse(url, &ldap_url)){
268                 REDEBUG("Parsing LDAP URL failed");
269                 return -1;
270         }
271
272         /*
273          *      Nothing, empty string, "*" string, or got 2 things, die.
274          */
275         if (!ldap_url->lud_attrs || !ldap_url->lud_attrs[0] ||
276             !*ldap_url->lud_attrs[0] ||
277             (strcmp(ldap_url->lud_attrs[0], "*") == 0) ||
278             ldap_url->lud_attrs[1]) {
279                 REDEBUG("Bad attributes list in LDAP URL. URL must specify exactly one attribute to retrieve");
280
281                 goto free_urldesc;
282         }
283
284         if (ldap_url->lud_host &&
285             ((strncmp(inst->server, ldap_url->lud_host, strlen(inst->server)) != 0) ||
286              (ldap_url->lud_port != inst->port))) {
287                 RDEBUG("Requested server/port is \"%s:%i\"", ldap_url->lud_host, inst->port);
288
289                 goto free_urldesc;
290         }
291
292         conn = rlm_ldap_get_socket(inst, request);
293         if (!conn) goto free_urldesc;
294
295         memcpy(&attrs, &ldap_url->lud_attrs, sizeof(attrs));
296
297         status = rlm_ldap_search(inst, request, &conn, ldap_url->lud_dn, ldap_url->lud_scope, ldap_url->lud_filter,
298                                  attrs, &result);
299         switch (status) {
300                 case LDAP_PROC_SUCCESS:
301                         break;
302                 case LDAP_PROC_NO_RESULT:
303                         RDEBUG("Search returned not found");
304                 default:
305                         goto free_socket;
306         }
307
308         rad_assert(conn);
309         rad_assert(result);
310
311         entry = ldap_first_entry(conn->handle, result);
312         if (!entry) {
313                 ldap_get_option(conn->handle, LDAP_OPT_RESULT_CODE, &ldap_errno);
314                 REDEBUG("Failed retrieving entry: %s", ldap_err2string(ldap_errno));
315                 len = -1;
316                 goto free_result;
317         }
318
319         vals = ldap_get_values(conn->handle, entry, ldap_url->lud_attrs[0]);
320         if (!vals) {
321                 RDEBUG("No \"%s\" attributes found in specified object", ldap_url->lud_attrs[0]);
322                 goto free_result;
323         }
324
325         len = strlen(vals[0]);
326         if (len >= freespace){
327                 goto free_vals;
328         }
329
330         strlcpy(out, vals[0], freespace);
331
332 free_vals:
333         ldap_value_free(vals);
334 free_result:
335         ldap_msgfree(result);
336 free_socket:
337         rlm_ldap_release_socket(inst, conn);
338 free_urldesc:
339         ldap_free_urldesc(ldap_url);
340
341         return len;
342 }
343
344 /** Perform LDAP-Group comparison checking
345  *
346  * Attempts to match users to groups using a variety of methods.
347  *
348  * @param instance of the rlm_ldap module.
349  * @param request Current request.
350  * @param thing Unknown.
351  * @param check Which group to check for user membership.
352  * @param check_pairs Unknown.
353  * @param reply_pairs Unknown.
354  * @return 1 on failure (or if the user is not a member), else 0.
355  */
356 static int rlm_ldap_groupcmp(void *instance, REQUEST *request, UNUSED VALUE_PAIR *thing, VALUE_PAIR *check,
357                              UNUSED VALUE_PAIR *check_pairs, UNUSED VALUE_PAIR **reply_pairs)
358 {
359         ldap_instance_t *inst = instance;
360         rlm_rcode_t     rcode;
361
362         int             found = false;
363         int             check_is_dn;
364
365         ldap_handle_t   *conn = NULL;
366         char const      *user_dn;
367
368         if (!inst->groupobj_base_dn) {
369                 REDEBUG("Directive 'group.base_dn' must be set'");
370
371                 return 1;
372         }
373
374         RDEBUG("Searching for user in group \"%s\"", check->vp_strvalue);
375
376         if (check->length == 0) {
377                 RDEBUG("Cannot do comparison (group name is empty)");
378                 return 1;
379         }
380
381         /*
382          *      Check if we can do cached membership verification
383          */
384         check_is_dn = rlm_ldap_is_dn(check->vp_strvalue);
385         if ((check_is_dn && inst->cacheable_group_dn) || (!check_is_dn && inst->cacheable_group_name)) {
386                 switch(rlm_ldap_check_cached(inst, request, check)) {
387                         case RLM_MODULE_NOTFOUND:
388                                 found = false;
389                                 goto finish;
390                         case RLM_MODULE_OK:
391                                 found = true;
392                                 goto finish;
393                         /*
394                          *      Fallback to dynamic search on failure
395                          */
396                         case RLM_MODULE_FAIL:
397                         case RLM_MODULE_INVALID:
398                         default:
399                                 break;
400                 }
401         }
402
403         conn = rlm_ldap_get_socket(inst, request);
404         if (!conn) return 1;
405
406         /*
407          *      This is used in the default membership filter.
408          */
409         user_dn = rlm_ldap_find_user(inst, request, &conn, NULL, false, NULL, &rcode);
410         if (!user_dn) {
411                 rlm_ldap_release_socket(inst, conn);
412                 return 1;
413         }
414
415         rad_assert(conn);
416
417         /*
418          *      Check groupobj user membership
419          */
420         if (inst->groupobj_membership_filter) {
421                 switch(rlm_ldap_check_groupobj_dynamic(inst, request, &conn, check)) {
422                         case RLM_MODULE_NOTFOUND:
423                                 break;
424                         case RLM_MODULE_OK:
425                                 found = true;
426                         default:
427                                 goto finish;
428                 }
429         }
430
431         rad_assert(conn);
432
433         /*
434          *      Check userobj group membership
435          */
436         if (inst->userobj_membership_attr) {
437                 switch(rlm_ldap_check_userobj_dynamic(inst, request, &conn, user_dn, check)) {
438                         case RLM_MODULE_NOTFOUND:
439                                 break;
440                         case RLM_MODULE_OK:
441                                 found = true;
442                         default:
443                                 goto finish;
444                 }
445         }
446
447         rad_assert(conn);
448
449         finish:
450         if (conn) {
451                 rlm_ldap_release_socket(inst, conn);
452         }
453
454         if (!found) {
455                 RDEBUG("User is not a member of specified group");
456
457                 return 1;
458         }
459
460         return 0;
461 }
462
463 /** Detach from the LDAP server and cleanup internal state.
464  *
465  */
466 static int mod_detach(void *instance)
467 {
468         ldap_instance_t *inst = instance;
469
470         fr_connection_pool_delete(inst->pool);
471
472         if (inst->user_map) {
473                 talloc_free(inst->user_map);
474         }
475
476         return 0;
477 }
478
479 /** Parse an accounting sub section.
480  *
481  * Allocate a new ldap_acct_section_t and write the config data into it.
482  *
483  * @param[in] inst rlm_ldap configuration.
484  * @param[in] parent of the config section.
485  * @param[out] config to write the sub section parameters to.
486  * @param[in] comp The section name were parsing the config for.
487  * @return 0 on success, else < 0 on failure.
488  */
489 static int parse_sub_section(ldap_instance_t *inst, CONF_SECTION *parent, ldap_acct_section_t **config,
490                              rlm_components_t comp)
491 {
492         CONF_SECTION *cs;
493
494         char const *name = section_type_value[comp].section;
495
496         cs = cf_section_sub_find(parent, name);
497         if (!cs) {
498                 INFO("rlm_ldap (%s): Couldn't find configuration for %s, will return NOOP for calls "
499                        "from this section", inst->xlat_name, name);
500
501                 return 0;
502         }
503
504         *config = talloc_zero(inst, ldap_acct_section_t);
505         if (cf_section_parse(cs, *config, acct_section_config) < 0) {
506                 LDAP_ERR("Failed parsing configuration for section %s", name);
507
508                 return -1;
509         }
510
511         (*config)->cs = cs;
512
513         return 0;
514 }
515
516 /** Instantiate the module
517  *
518  * Creates a new instance of the module reading parameters from a configuration section.
519  *
520  * @param conf to parse.
521  * @param instance Where to write pointer to configuration data.
522  * @return 0 on success < 0 on failure.
523  */
524 static int mod_instantiate(CONF_SECTION *conf, void *instance)
525 {
526         CONF_SECTION *options;
527         ldap_instance_t *inst = instance;
528
529         inst->cs = conf;
530
531         options = cf_section_sub_find(conf, "options");
532         if (!options || !cf_pair_find(options, "chase_referrals")) {
533                 inst->chase_referrals_unset = true;      /* use OpenLDAP defaults */
534         }
535
536         inst->xlat_name = cf_section_name2(conf);
537         if (!inst->xlat_name) {
538                 inst->xlat_name = cf_section_name1(conf);
539         }
540
541         /*
542          *      If the configuration parameters can't be parsed, then fail.
543          */
544         if ((parse_sub_section(inst, conf, &inst->accounting, RLM_COMPONENT_ACCT) < 0) ||
545             (parse_sub_section(inst, conf, &inst->postauth, RLM_COMPONENT_POST_AUTH) < 0)) {
546                 LDAP_ERR("Failed parsing configuration");
547
548                 goto error;
549         }
550
551         /*
552          *      Sanity checks for cacheable groups code.
553          */
554         if (inst->cacheable_group_name && inst->groupobj_membership_filter) {
555                 if (!inst->groupobj_name_attr) {
556                         LDAP_ERR("Directive 'group.name_attribute' must be set if cacheable group names are enabled");
557
558                         goto error;
559                 }
560         }
561
562         if (inst->cacheable_group_name || inst->cacheable_group_dn) {
563                 if (!inst->groupobj_base_dn) {
564                         LDAP_ERR("Directive 'group.base_dn' must be set if cacheable group names are enabled");
565
566                         goto error;
567                 }
568         }
569
570         /*
571          *      Check for URLs.  If they're used and the library doesn't support them, then complain.
572          */
573         inst->is_url = 0;
574         if (ldap_is_ldap_url(inst->server)) {
575 #ifdef HAVE_LDAP_INITIALIZE
576                 inst->is_url = 1;
577                 inst->port = 0;
578 #else
579                 LDAP_ERR("Directive 'server' is in URL form but ldap_initialize() is not available");
580                 goto error;
581 #endif
582         }
583
584         /*
585          *      Workaround for servers which support LDAPS but not START TLS
586          */
587         if (inst->port == LDAPS_PORT || inst->tls_mode) {
588                 inst->tls_mode = LDAP_OPT_X_TLS_HARD;
589         } else {
590                 inst->tls_mode = 0;
591         }
592
593 #if LDAP_SET_REBIND_PROC_ARGS != 3
594         /*
595          *      The 2-argument rebind doesn't take an instance variable.  Our rebind function needs the instance
596          *      variable for the username, password, etc.
597          */
598         if (inst->rebind == true) {
599                 LDAP_ERR("Cannot use 'rebind' directive as this version of libldap does not support the API "
600                          "that we need");
601
602                 goto error;
603         }
604 #endif
605
606         /*
607          *      Convert scope strings to enumerated constants
608          */
609         inst->userobj_scope = fr_str2int(ldap_scope, inst->userobj_scope_str, -1);
610         if (inst->userobj_scope < 0) {
611                 LDAP_ERR("Invalid 'user.scope' value \"%s\", expected 'sub', 'one', 'base' or 'children'",
612                          inst->userobj_scope_str);
613                 goto error;
614         }
615
616         inst->groupobj_scope = fr_str2int(ldap_scope, inst->groupobj_scope_str, -1);
617         if (inst->groupobj_scope < 0) {
618                 LDAP_ERR("Invalid 'group.scope' value \"%s\", expected 'sub', 'one', 'base' or 'children'",
619                          inst->groupobj_scope_str);
620                 goto error;
621         }
622
623         inst->clientobj_scope = fr_str2int(ldap_scope, inst->clientobj_scope_str, -1);
624         if (inst->clientobj_scope < 0) {
625                 LDAP_ERR("Invalid 'client.scope' value \"%s\", expected 'sub', 'one', 'base' or 'children'",
626                          inst->clientobj_scope_str);
627                 goto error;
628         }
629
630         if (inst->tls_require_cert_str) {
631 #ifdef LDAP_OPT_X_TLS_NEVER
632                 /*
633                  *      Convert cert strictness to enumerated constants
634                  */
635                 inst->tls_require_cert = fr_str2int(ldap_tls_require_cert, inst->tls_require_cert_str, -1);
636                 if (inst->tls_require_cert < 0) {
637                         LDAP_ERR("Invalid 'tls.require_cert' value \"%s\", expected 'never', 'demand', 'allow', "
638                                  "'try' or 'hard'", inst->tls_require_cert_str);
639                         goto error;
640                 }
641 #else
642                 LDAP_ERR("Modifying 'tls.require_cert' is not supported by current version of libldap. "
643                          "Please upgrade libldap and rebuild this module");
644
645                 goto error;
646 #endif
647         }
648         /*
649          *      Build the attribute map
650          */
651         if (rlm_ldap_map_verify(inst, &(inst->user_map)) < 0) {
652                 goto error;
653         }
654
655         /*
656          *      Group comparison checks.
657          */
658         if (cf_section_name2(conf)) {
659                 ATTR_FLAGS flags;
660                 char buffer[256];
661
662                 snprintf(buffer, sizeof(buffer), "%s-Ldap-Group",
663                          inst->xlat_name);
664                 memset(&flags, 0, sizeof(flags));
665
666                 dict_addattr(buffer, -1, 0, PW_TYPE_STRING, flags);
667                 inst->group_da = dict_attrbyname(buffer);
668                 if (!inst->group_da) {
669                         LDAP_ERR("Failed creating attribute %s", buffer);
670
671                         goto error;
672                 }
673
674                 paircompare_register(inst->group_da, dict_attrbyvalue(PW_USER_NAME, 0), false, rlm_ldap_groupcmp, inst);
675         /*
676          *      Were the default instance
677          */
678         } else {
679                 inst->group_da = dict_attrbyvalue(PW_LDAP_GROUP, 0);
680                 paircompare_register(dict_attrbyvalue(PW_LDAP_GROUP, 0), dict_attrbyvalue(PW_USER_NAME, 0),
681                                 false, rlm_ldap_groupcmp, inst);
682         }
683
684         xlat_register(inst->xlat_name, ldap_xlat, rlm_ldap_escape_func, inst);
685
686         /*
687          *      Initialize the socket pool.
688          */
689         inst->pool = fr_connection_pool_init(inst->cs, inst, mod_conn_create, NULL, mod_conn_delete, NULL);
690         if (!inst->pool) {
691                 return -1;
692         }
693
694         /*
695          *      Bulk load dynamic clients.
696          */
697         if (inst->do_clients) {
698                 if (rlm_ldap_load_clients(inst) < 0) {
699                         LDAP_ERR("Error loading clients");
700
701                         return -1;
702                 }
703         }
704
705         return 0;
706
707 error:
708         return -1;
709 }
710
711 /** Check the user's password against ldap directory
712  *
713  * @param instance rlm_ldap configuration.
714  * @param request Current request.
715  * @return one of the RLM_MODULE_* values.
716  */
717 static rlm_rcode_t mod_authenticate(void *instance, REQUEST *request)
718 {
719         rlm_rcode_t     rcode;
720         ldap_rcode_t    status;
721         char const      *dn;
722         ldap_instance_t *inst = instance;
723         ldap_handle_t   *conn;
724
725         /*
726          * Ensure that we're being passed a plain-text password, and not
727          * anything else.
728          */
729
730         if (!request->username) {
731                 REDEBUG("Attribute \"User-Name\" is required for authentication");
732
733                 return RLM_MODULE_INVALID;
734         }
735
736         if (!request->password ||
737             (request->password->da->attr != PW_USER_PASSWORD)) {
738                 RWDEBUG("You have set \"Auth-Type := LDAP\" somewhere.");
739                 RWDEBUG("*********************************************");
740                 RWDEBUG("* THAT CONFIGURATION IS WRONG.  DELETE IT.   ");
741                 RWDEBUG("* YOU ARE PREVENTING THE SERVER FROM WORKING.");
742                 RWDEBUG("*********************************************");
743
744                 REDEBUG("Attribute \"User-Password\" is required for authentication.");
745
746                 return RLM_MODULE_INVALID;
747         }
748
749         if (request->password->length == 0) {
750                 REDEBUG("Empty password supplied");
751
752                 return RLM_MODULE_INVALID;
753         }
754
755         RDEBUG("Login attempt by \"%s\"", request->username->vp_strvalue);
756
757         conn = rlm_ldap_get_socket(inst, request);
758         if (!conn) return RLM_MODULE_FAIL;
759
760         /*
761          *      Get the DN by doing a search.
762          */
763         dn = rlm_ldap_find_user(inst, request, &conn, NULL, false, NULL, &rcode);
764         if (!dn) {
765                 rlm_ldap_release_socket(inst, conn);
766
767                 return rcode;
768         }
769
770         /*
771          *      Bind as the user
772          */
773         conn->rebound = true;
774         status = rlm_ldap_bind(inst, request, &conn, dn, request->password->vp_strvalue, true);
775         switch (status) {
776         case LDAP_PROC_SUCCESS:
777                 rcode = RLM_MODULE_OK;
778                 RDEBUG("Bind as user \"%s\" was successful", dn);
779                 break;
780
781         case LDAP_PROC_NOT_PERMITTED:
782                 rcode = RLM_MODULE_USERLOCK;
783                 break;
784
785         case LDAP_PROC_REJECT:
786                 rcode = RLM_MODULE_REJECT;
787                 break;
788
789         case LDAP_PROC_BAD_DN:
790                 rcode = RLM_MODULE_INVALID;
791                 break;
792
793         case LDAP_PROC_NO_RESULT:
794                 rcode = RLM_MODULE_NOTFOUND;
795                 break;
796
797         default:
798                 rcode = RLM_MODULE_FAIL;
799                 break;
800         };
801
802         rlm_ldap_release_socket(inst, conn);
803
804         return rcode;
805 }
806
807 /** Check if user is authorized for remote access
808  *
809  */
810 static rlm_rcode_t mod_authorize(void *instance, REQUEST *request)
811 {
812         rlm_rcode_t     rcode = RLM_MODULE_OK;
813         ldap_rcode_t    status;
814         int             ldap_errno;
815         int             i;
816         ldap_instance_t *inst = instance;
817         char            **vals;
818         VALUE_PAIR      *vp;
819         ldap_handle_t   *conn;
820         LDAPMessage     *result, *entry;
821         char const      *dn = NULL;
822         rlm_ldap_map_xlat_t     expanded; /* faster than mallocing every time */
823
824         if (!request->username) {
825                 RDEBUG2("Attribute \"User-Name\" is required for authorization.");
826
827                 return RLM_MODULE_NOOP;
828         }
829
830         /*
831          *      Check for valid input, zero length names not permitted
832          */
833         if (request->username->length == 0) {
834                 RDEBUG2("Zero length username not permitted");
835
836                 return RLM_MODULE_INVALID;
837         }
838
839         if (rlm_ldap_map_xlat(request, inst->user_map, &expanded) < 0) {
840                 return RLM_MODULE_FAIL;
841         }
842
843         conn = rlm_ldap_get_socket(inst, request);
844         if (!conn) return RLM_MODULE_FAIL;
845
846         /*
847          *      Add any additional attributes we need for checking access, memberships, and profiles
848          */
849         if (inst->userobj_access_attr) {
850                 expanded.attrs[expanded.count++] = inst->userobj_access_attr;
851         }
852
853         if (inst->userobj_membership_attr && (inst->cacheable_group_dn || inst->cacheable_group_name)) {
854                 expanded.attrs[expanded.count++] = inst->userobj_membership_attr;
855         }
856
857         if (inst->profile_attr) {
858                 expanded.attrs[expanded.count++] = inst->profile_attr;
859         }
860
861         if (inst->valuepair_attr) {
862                 expanded.attrs[expanded.count++] = inst->valuepair_attr;
863         }
864
865         expanded.attrs[expanded.count] = NULL;
866
867         dn = rlm_ldap_find_user(inst, request, &conn, expanded.attrs, true, &result, &rcode);
868         if (!dn) {
869                 goto finish;
870         }
871
872         entry = ldap_first_entry(conn->handle, result);
873         if (!entry) {
874                 ldap_get_option(conn->handle, LDAP_OPT_RESULT_CODE, &ldap_errno);
875                 REDEBUG("Failed retrieving entry: %s", ldap_err2string(ldap_errno));
876
877                 goto finish;
878         }
879
880         /*
881          *      Check for access.
882          */
883         if (inst->userobj_access_attr) {
884                 rcode = rlm_ldap_check_access(inst, request, conn, entry);
885                 if (rcode != RLM_MODULE_OK) {
886                         goto finish;
887                 }
888         }
889
890         /*
891          *      Check if we need to cache group memberships
892          */
893         if (inst->cacheable_group_dn || inst->cacheable_group_name) {
894                 if (inst->userobj_membership_attr) {
895                         rcode = rlm_ldap_cacheable_userobj(inst, request, &conn, entry, inst->userobj_membership_attr);
896                         if (rcode != RLM_MODULE_OK) {
897                                 goto finish;
898                         }
899                 }
900
901                 rcode = rlm_ldap_cacheable_groupobj(inst, request, &conn);
902                 if (rcode != RLM_MODULE_OK) {
903                         goto finish;
904                 }
905         }
906
907 #ifdef WITH_EDIR
908         /*
909          *      We already have a Cleartext-Password.  Skip edir.
910          */
911         if (pairfind(request->config_items, PW_CLEARTEXT_PASSWORD, 0, TAG_ANY)) {
912                 goto skip_edir;
913         }
914
915         /*
916          *      Retrieve Universal Password if we use eDirectory
917          */
918         if (inst->edir) {
919                 int res = 0;
920                 char password[256];
921                 size_t pass_size = sizeof(password);
922
923                 /*
924                  *      Retrive universal password
925                  */
926                 res = nmasldap_get_password(conn->handle, dn, password, &pass_size);
927                 if (res != 0) {
928                         RWDEBUG("Failed to retrieve eDirectory password");
929                         rcode = RLM_MODULE_NOOP;
930
931                         goto finish;
932                 }
933
934                 /*
935                  *      Add Cleartext-Password attribute to the request
936                  */
937                 vp = radius_paircreate(request, &request->config_items, PW_CLEARTEXT_PASSWORD, 0);
938                 pairstrcpy(vp, password);
939                 vp->length = pass_size;
940
941                 RDEBUG2("Added eDirectory password in check items as %s = %s", vp->da->name, vp->vp_strvalue);
942
943                 if (inst->edir_autz) {
944                         RDEBUG2("Binding as user for eDirectory authorization checks");
945                         /*
946                          *      Bind as the user
947                          */
948                         conn->rebound = true;
949                         status = rlm_ldap_bind(inst, request, &conn, dn, vp->vp_strvalue, true);
950                         switch (status) {
951                         case LDAP_PROC_SUCCESS:
952                                 rcode = RLM_MODULE_OK;
953                                 RDEBUG("Bind as user \"%s\" was successful", dn);
954
955                                 break;
956                         case LDAP_PROC_NOT_PERMITTED:
957                                 rcode = RLM_MODULE_USERLOCK;
958
959                                 goto finish;
960                         case LDAP_PROC_REJECT:
961                                 rcode = RLM_MODULE_REJECT;
962
963                                 goto finish;
964                         case LDAP_PROC_BAD_DN:
965                                 rcode = RLM_MODULE_INVALID;
966
967                                 goto finish;
968                         case LDAP_PROC_NO_RESULT:
969                                 rcode = RLM_MODULE_NOTFOUND;
970
971                                 goto finish;
972                         default:
973                                 rcode = RLM_MODULE_FAIL;
974
975                                 goto finish;
976                         };
977                 }
978         }
979
980 skip_edir:
981 #endif
982
983         /*
984          *      Apply ONE user profile, or a default user profile.
985          */
986         if (inst->default_profile) {
987                 char profile[1024];
988
989                 if (radius_xlat(profile, sizeof(profile), request, inst->default_profile, NULL, NULL) < 0) {
990                         REDEBUG("Failed creating default profile string");
991
992                         rcode = RLM_MODULE_INVALID;
993                         goto finish;
994                 }
995
996                 rlm_ldap_map_profile(inst, request, &conn, profile, &expanded);
997         }
998
999         /*
1000          *      Apply a SET of user profiles.
1001          */
1002         if (inst->profile_attr) {
1003                 vals = ldap_get_values(conn->handle, entry, inst->profile_attr);
1004                 if (vals != NULL) {
1005                         for (i = 0; vals[i] != NULL; i++) {
1006                                 rlm_ldap_map_profile(inst, request, &conn, vals[i], &expanded);
1007                         }
1008
1009                         ldap_value_free(vals);
1010                 }
1011         }
1012
1013         if (inst->user_map || inst->valuepair_attr) {
1014                 RDEBUG("Processing user attributes");
1015                 rlm_ldap_map_do(inst, request, conn->handle, &expanded, entry);
1016                 rlm_ldap_check_reply(inst, request);
1017         }
1018
1019 finish:
1020         rlm_ldap_map_xlat_free(&expanded);
1021         if (result) {
1022                 ldap_msgfree(result);
1023         }
1024         rlm_ldap_release_socket(inst, conn);
1025
1026         return rcode;
1027 }
1028
1029 /** Modify user's object in LDAP
1030  *
1031  * Process a modifcation map to update a user object in the LDAP directory.
1032  *
1033  * @param inst rlm_ldap instance.
1034  * @param request Current request.
1035  * @param section that holds the map to process.
1036  * @return one of the RLM_MODULE_* values.
1037  */
1038 static rlm_rcode_t user_modify(ldap_instance_t *inst, REQUEST *request, ldap_acct_section_t *section)
1039 {
1040         rlm_rcode_t     rcode = RLM_MODULE_OK;
1041
1042         ldap_handle_t   *conn = NULL;
1043
1044         LDAPMod         *mod_p[LDAP_MAX_ATTRMAP + 1], mod_s[LDAP_MAX_ATTRMAP];
1045         LDAPMod         **modify = mod_p;
1046
1047         char            *passed[LDAP_MAX_ATTRMAP * 2];
1048         int             i, total = 0, last_pass = 0;
1049
1050         char            *expanded[LDAP_MAX_ATTRMAP];
1051         int             last_exp = 0;
1052
1053         char const      *attr;
1054         char const      *value;
1055
1056         char const      *dn;
1057         /*
1058          *      Build our set of modifications using the update sections in
1059          *      the config.
1060          */
1061         CONF_ITEM       *ci;
1062         CONF_PAIR       *cp;
1063         CONF_SECTION    *cs;
1064         FR_TOKEN        op;
1065         char            path[MAX_STRING_LEN];
1066
1067         char            *p = path;
1068
1069         rad_assert(section);
1070
1071         /*
1072          *      Locate the update section were going to be using
1073          */
1074         if (section->reference[0] != '.') {
1075                 *p++ = '.';
1076         }
1077
1078         if (radius_xlat(p, (sizeof(path) - (p - path)) - 1, request, section->reference, NULL, NULL) < 0) {
1079                 goto error;
1080         }
1081
1082         ci = cf_reference_item(NULL, section->cs, path);
1083         if (!ci) {
1084                 goto error;
1085         }
1086
1087         if (!cf_item_is_section(ci)){
1088                 REDEBUG("Reference must resolve to a section");
1089
1090                 goto error;
1091         }
1092
1093         cs = cf_section_sub_find(cf_itemtosection(ci), "update");
1094         if (!cs) {
1095                 REDEBUG("Section must contain 'update' subsection");
1096
1097                 goto error;
1098         }
1099
1100         /*
1101          *      Iterate over all the pairs, building our mods array
1102          */
1103         for (ci = cf_item_find_next(cs, NULL); ci != NULL; ci = cf_item_find_next(cs, ci)) {
1104                 int do_xlat = false;
1105
1106                 if (total == LDAP_MAX_ATTRMAP) {
1107                         REDEBUG("Modify map size exceeded");
1108
1109                         goto error;
1110                 }
1111
1112                 if (!cf_item_is_pair(ci)) {
1113                         REDEBUG("Entry is not in \"ldap-attribute = value\" format");
1114
1115                         goto error;
1116                 }
1117
1118                 /*
1119                  *      Retrieve all the information we need about the pair
1120                  */
1121                 cp = cf_itemtopair(ci);
1122                 value = cf_pair_value(cp);
1123                 attr = cf_pair_attr(cp);
1124                 op = cf_pair_operator(cp);
1125
1126                 if (!value || (*value == '\0')) {
1127                         RDEBUG("Empty value string, skipping attribute \"%s\"", attr);
1128
1129                         continue;
1130                 }
1131
1132                 switch (cf_pair_value_type(cp))
1133                 {
1134                         case T_BARE_WORD:
1135                         case T_SINGLE_QUOTED_STRING:
1136                         break;
1137                         case T_BACK_QUOTED_STRING:
1138                         case T_DOUBLE_QUOTED_STRING:
1139                                 do_xlat = true;
1140                         break;
1141                         default:
1142                                 rad_assert(0);
1143                                 goto error;
1144                 }
1145
1146                 if (op == T_OP_CMP_FALSE) {
1147                         passed[last_pass] = NULL;
1148                 } else if (do_xlat) {
1149                         char *exp = NULL;
1150
1151                         if (radius_xlat(exp, 0, request, value, NULL, NULL) <= 0) {
1152                                 RDEBUG("Skipping attribute \"%s\"", attr);
1153
1154                                 talloc_free(exp);
1155
1156                                 continue;
1157                         }
1158
1159                         expanded[last_exp++] = exp;
1160                         passed[last_pass] = exp;
1161                 /*
1162                  *      Static strings
1163                  */
1164                 } else {
1165                         memcpy(&(passed[last_pass]), &value, sizeof(passed[last_pass]));
1166                 }
1167
1168                 passed[last_pass + 1] = NULL;
1169
1170                 mod_s[total].mod_values = &(passed[last_pass]);
1171
1172                 last_pass += 2;
1173
1174                 switch (op)
1175                 {
1176                 /*
1177                  *  T_OP_EQ is *NOT* supported, it is impossible to
1178                  *  support because of the lack of transactions in LDAP
1179                  */
1180                 case T_OP_ADD:
1181                         mod_s[total].mod_op = LDAP_MOD_ADD;
1182                         break;
1183
1184                 case T_OP_SET:
1185                         mod_s[total].mod_op = LDAP_MOD_REPLACE;
1186                         break;
1187
1188                 case T_OP_SUB:
1189                 case T_OP_CMP_FALSE:
1190                         mod_s[total].mod_op = LDAP_MOD_DELETE;
1191                         break;
1192
1193 #ifdef LDAP_MOD_INCREMENT
1194                 case T_OP_INCRM:
1195                         mod_s[total].mod_op = LDAP_MOD_INCREMENT;
1196                         break;
1197 #endif
1198                 default:
1199                         REDEBUG("Operator '%s' is not supported for LDAP modify operations",
1200                                 fr_int2str(fr_tokens, op, "<INVALID>"));
1201
1202                         goto error;
1203                 }
1204
1205                 /*
1206                  *      Now we know the value is ok, copy the pointers into
1207                  *      the ldapmod struct.
1208                  */
1209                 memcpy(&(mod_s[total].mod_type), &(attr), sizeof(mod_s[total].mod_type));
1210
1211                 mod_p[total] = &(mod_s[total]);
1212                 total++;
1213         }
1214
1215         if (total == 0) {
1216                 rcode = RLM_MODULE_NOOP;
1217                 goto release;
1218         }
1219
1220         mod_p[total] = NULL;
1221
1222         conn = rlm_ldap_get_socket(inst, request);
1223         if (!conn) return RLM_MODULE_FAIL;
1224
1225
1226         dn = rlm_ldap_find_user(inst, request, &conn, NULL, false, NULL, &rcode);
1227         if (!dn || (rcode != RLM_MODULE_OK)) {
1228                 goto error;
1229         }
1230
1231         rcode = rlm_ldap_modify(inst, request, &conn, dn, modify);
1232
1233         release:
1234         error:
1235         /*
1236          *      Free up any buffers we allocated for xlat expansion
1237          */
1238         for (i = 0; i < last_exp; i++) {
1239                 talloc_free(expanded[i]);
1240         }
1241
1242         rlm_ldap_release_socket(inst, conn);
1243
1244         return rcode;
1245 }
1246
1247 static rlm_rcode_t mod_accounting(void *instance, REQUEST * request) {
1248         ldap_instance_t *inst = instance;
1249
1250         if (inst->accounting) {
1251                 return user_modify(inst, request, inst->accounting);
1252         }
1253
1254         return RLM_MODULE_NOOP;
1255 }
1256
1257 static rlm_rcode_t mod_post_auth(void *instance, REQUEST * request)
1258 {
1259         ldap_instance_t *inst = instance;
1260
1261         if (inst->postauth) {
1262                 return user_modify(inst, request, inst->postauth);
1263         }
1264
1265         return RLM_MODULE_NOOP;
1266 }
1267
1268
1269 /* globally exported name */
1270 module_t rlm_ldap = {
1271         RLM_MODULE_INIT,
1272         "ldap",
1273         RLM_TYPE_THREAD_SAFE,   /* type: reserved        */
1274         sizeof(ldap_instance_t),
1275         module_config,
1276         mod_instantiate,        /* instantiation         */
1277         mod_detach,             /* detach                */
1278         {
1279                 mod_authenticate,       /* authentication        */
1280                 mod_authorize,          /* authorization         */
1281                 NULL,                   /* preaccounting         */
1282                 mod_accounting,         /* accounting            */
1283                 NULL,                   /* checksimul            */
1284                 NULL,                   /* pre-proxy             */
1285                 NULL,                   /* post-proxy            */
1286                 mod_post_auth           /* post-auth */
1287         },
1288 };