1 /* $OpenLDAP$ */
2 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
3  *
4  * Copyright 1998-2021 The OpenLDAP Foundation.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted only as authorized by the OpenLDAP
9  * Public License.
10  *
11  * A copy of this license is available in the file LICENSE in the
12  * top-level directory of the distribution or, alternatively, at
13  * <http://www.OpenLDAP.org/license.html>.
14  */
15 
16 #include "portable.h"
17 
18 #include <stdio.h>
19 #ifdef HAVE_LIMITS_H
20 #include <limits.h>
21 #endif
22 
23 #include <ac/stdlib.h>
24 #include <ac/string.h>
25 
26 #include <lber.h>
27 #include <ldap_log.h>
28 
29 #include "slap.h"
30 
31 #ifdef ENABLE_REWRITE
32 #include <rewrite.h>
33 #endif
34 
35 #ifdef HAVE_CYRUS_SASL
36 # ifdef HAVE_SASL_SASL_H
37 #  include <sasl/sasl.h>
38 #  include <sasl/saslplug.h>
39 # else
40 #  include <sasl.h>
41 #  include <saslplug.h>
42 # endif
43 
44 # define	SASL_CONST const
45 
46 #define SASL_VERSION_FULL	((SASL_VERSION_MAJOR << 16) |\
47 	(SASL_VERSION_MINOR << 8) | SASL_VERSION_STEP)
48 
49 #if SASL_VERSION_FULL >= 0x020119 /* 2.1.25 */
50 typedef sasl_callback_ft slap_sasl_cb_ft;
51 #else
52 typedef int (*slap_sasl_cb_ft)();
53 #endif
54 
55 static sasl_security_properties_t sasl_secprops;
56 #elif defined( SLAP_BUILTIN_SASL )
57 /*
58  * built-in SASL implementation
59  *	only supports EXTERNAL
60  */
61 typedef struct sasl_ctx {
62 	slap_ssf_t sc_external_ssf;
63 	struct berval sc_external_id;
64 } SASL_CTX;
65 
66 #endif
67 
68 #include <lutil.h>
69 
70 static struct berval ext_bv = BER_BVC( "EXTERNAL" );
71 
72 char *slap_sasl_auxprops;
73 
74 #ifdef HAVE_CYRUS_SASL
75 
76 /* Just use our internal auxprop by default */
77 static int
slap_sasl_getopt(void * context,const char * plugin_name,const char * option,const char ** result,unsigned * len)78 slap_sasl_getopt(
79 	void *context,
80 	const char *plugin_name,
81 	const char *option,
82 	const char **result,
83 	unsigned *len)
84 {
85 	if ( strcmp( option, "auxprop_plugin" )) {
86 		return SASL_FAIL;
87 	}
88 	if ( slap_sasl_auxprops )
89 		*result = slap_sasl_auxprops;
90 	else
91 		*result = "slapd";
92 	return SASL_OK;
93 }
94 
95 int
slap_sasl_log(void * context,int priority,const char * message)96 slap_sasl_log(
97 	void *context,
98 	int priority,
99 	const char *message)
100 {
101 	Connection *conn = context;
102 	int level;
103 	const char * label;
104 
105 	if ( message == NULL ) {
106 		return SASL_BADPARAM;
107 	}
108 
109 	switch (priority) {
110 	case SASL_LOG_NONE:
111 		level = LDAP_DEBUG_NONE;
112 		label = "None";
113 		break;
114 	case SASL_LOG_ERR:
115 		level = LDAP_DEBUG_ANY;
116 		label = "Error";
117 		break;
118 	case SASL_LOG_FAIL:
119 		level = LDAP_DEBUG_ANY;
120 		label = "Failure";
121 		break;
122 	case SASL_LOG_WARN:
123 		level = LDAP_DEBUG_TRACE;
124 		label = "Warning";
125 		break;
126 	case SASL_LOG_NOTE:
127 		level = LDAP_DEBUG_TRACE;
128 		label = "Notice";
129 		break;
130 	case SASL_LOG_DEBUG:
131 		level = LDAP_DEBUG_TRACE;
132 		label = "Debug";
133 		break;
134 	case SASL_LOG_TRACE:
135 		level = LDAP_DEBUG_TRACE;
136 		label = "Trace";
137 		break;
138 	case SASL_LOG_PASS:
139 		level = LDAP_DEBUG_TRACE;
140 		label = "Password Trace";
141 		break;
142 	default:
143 		return SASL_BADPARAM;
144 	}
145 
146 	Debug( level, "SASL [conn=%ld] %s: %s\n",
147 		conn ? (long) conn->c_connid: -1L,
148 		label, message );
149 
150 
151 	return SASL_OK;
152 }
153 
154 static const char *slap_propnames[] = {
155 	"*slapConn", "*slapAuthcDNlen", "*slapAuthcDN",
156 	"*slapAuthzDNlen", "*slapAuthzDN", NULL };
157 
158 static Filter generic_filter = { LDAP_FILTER_PRESENT, { 0 }, NULL };
159 static struct berval generic_filterstr = BER_BVC("(objectclass=*)");
160 
161 #define	SLAP_SASL_PROP_CONN	0
162 #define	SLAP_SASL_PROP_AUTHCLEN	1
163 #define	SLAP_SASL_PROP_AUTHC	2
164 #define	SLAP_SASL_PROP_AUTHZLEN	3
165 #define	SLAP_SASL_PROP_AUTHZ	4
166 #define	SLAP_SASL_PROP_COUNT	5	/* Number of properties we used */
167 
168 typedef struct lookup_info {
169 	int flags;
170 	const struct propval *list;
171 	sasl_server_params_t *sparams;
172 } lookup_info;
173 
174 static slap_response sasl_ap_lookup;
175 
176 static struct berval sc_cleartext = BER_BVC("{CLEARTEXT}");
177 
178 static int
sasl_ap_lookup(Operation * op,SlapReply * rs)179 sasl_ap_lookup( Operation *op, SlapReply *rs )
180 {
181 	BerVarray bv;
182 	AttributeDescription *ad;
183 	Attribute *a;
184 	const char *text;
185 	int rc, i;
186 	lookup_info *sl = (lookup_info *)op->o_callback->sc_private;
187 
188 	if (rs->sr_type != REP_SEARCH) return 0;
189 
190 	for( i = 0; sl->list[i].name; i++ ) {
191 		const char *name = sl->list[i].name;
192 
193 		if ( name[0] == '*' ) {
194 			if ( sl->flags & SASL_AUXPROP_AUTHZID ) continue;
195 			/* Skip our private properties */
196 			if ( !strcmp( name, slap_propnames[0] )) {
197 				i += SLAP_SASL_PROP_COUNT - 1;
198 				continue;
199 			}
200 			name++;
201 		} else if ( !(sl->flags & SASL_AUXPROP_AUTHZID ) )
202 			continue;
203 
204 		if ( sl->list[i].values ) {
205 			if ( !(sl->flags & SASL_AUXPROP_OVERRIDE) ) continue;
206 		}
207 		ad = NULL;
208 		rc = slap_str2ad( name, &ad, &text );
209 		if ( rc != LDAP_SUCCESS ) {
210 			Debug( LDAP_DEBUG_TRACE,
211 				"slap_ap_lookup: str2ad(%s): %s\n", name, text, 0 );
212 			continue;
213 		}
214 
215 		/* If it's the rootdn and a rootpw was present, we already set
216 		 * it so don't override it here.
217 		 */
218 		if ( ad == slap_schema.si_ad_userPassword && sl->list[i].values &&
219 			be_isroot_dn( op->o_bd, &op->o_req_ndn ))
220 			continue;
221 
222 		a = attr_find( rs->sr_entry->e_attrs, ad );
223 		if ( !a ) continue;
224 		if ( ! access_allowed( op, rs->sr_entry, ad, NULL, ACL_AUTH, NULL ) ) {
225 			continue;
226 		}
227 		if ( sl->list[i].values && ( sl->flags & SASL_AUXPROP_OVERRIDE ) ) {
228 			sl->sparams->utils->prop_erase( sl->sparams->propctx,
229 			sl->list[i].name );
230 		}
231 		for ( bv = a->a_vals; bv->bv_val; bv++ ) {
232 			/* ITS#3846 don't give hashed passwords to SASL */
233 			if ( ad == slap_schema.si_ad_userPassword &&
234 				bv->bv_val[0] == '{' /*}*/ )
235 			{
236 				if ( lutil_passwd_scheme( bv->bv_val ) ) {
237 					/* If it's not a recognized scheme, just assume it's
238 					 * a cleartext password that happened to include brackets.
239 					 *
240 					 * If it's a recognized scheme, skip this value, unless the
241 					 * scheme is {CLEARTEXT}. In that case, skip over the
242 					 * scheme name and use the remainder. If there is nothing
243 					 * past the scheme name, skip this value.
244 					 */
245 #ifdef SLAPD_CLEARTEXT
246 					if ( !strncasecmp( bv->bv_val, sc_cleartext.bv_val,
247 						sc_cleartext.bv_len )) {
248 						struct berval cbv;
249 						cbv.bv_len = bv->bv_len - sc_cleartext.bv_len;
250 						if ( cbv.bv_len > 0 ) {
251 							cbv.bv_val = bv->bv_val + sc_cleartext.bv_len;
252 							sl->sparams->utils->prop_set( sl->sparams->propctx,
253 								sl->list[i].name, cbv.bv_val, cbv.bv_len );
254 						}
255 					}
256 #endif
257 					continue;
258 				}
259 			}
260 			sl->sparams->utils->prop_set( sl->sparams->propctx,
261 				sl->list[i].name, bv->bv_val, bv->bv_len );
262 		}
263 	}
264 	return LDAP_SUCCESS;
265 }
266 
267 #if SASL_VERSION_FULL >= 0x020118
268 static int
269 #else
270 static void
271 #endif
slap_auxprop_lookup(void * glob_context,sasl_server_params_t * sparams,unsigned flags,const char * user,unsigned ulen)272 slap_auxprop_lookup(
273 	void *glob_context,
274 	sasl_server_params_t *sparams,
275 	unsigned flags,
276 	const char *user,
277 	unsigned ulen)
278 {
279 	OperationBuffer opbuf = {{ NULL }};
280 	Operation *op = (Operation *)&opbuf;
281 	int i, doit = 0;
282 	Connection *conn = NULL;
283 	lookup_info sl;
284 	int rc = LDAP_SUCCESS;
285 
286 	sl.list = sparams->utils->prop_get( sparams->propctx );
287 	sl.sparams = sparams;
288 	sl.flags = flags;
289 
290 	/* Find our DN and conn first */
291 	for( i = 0; sl.list[i].name; i++ ) {
292 		if ( sl.list[i].name[0] == '*' ) {
293 			if ( !strcmp( sl.list[i].name, slap_propnames[SLAP_SASL_PROP_CONN] ) ) {
294 				if ( sl.list[i].values && sl.list[i].values[0] )
295 					AC_MEMCPY( &conn, sl.list[i].values[0], sizeof( conn ) );
296 				continue;
297 			}
298 			if ( flags & SASL_AUXPROP_AUTHZID ) {
299 				if ( !strcmp( sl.list[i].name, slap_propnames[SLAP_SASL_PROP_AUTHZLEN] )) {
300 					if ( sl.list[i].values && sl.list[i].values[0] )
301 						AC_MEMCPY( &op->o_req_ndn.bv_len, sl.list[i].values[0],
302 							sizeof( op->o_req_ndn.bv_len ) );
303 				} else if ( !strcmp( sl.list[i].name, slap_propnames[SLAP_SASL_PROP_AUTHZ] )) {
304 					if ( sl.list[i].values )
305 						op->o_req_ndn.bv_val = (char *)sl.list[i].values[0];
306 					break;
307 				}
308 			}
309 
310 			if ( !strcmp( sl.list[i].name, slap_propnames[SLAP_SASL_PROP_AUTHCLEN] )) {
311 				if ( sl.list[i].values && sl.list[i].values[0] )
312 					AC_MEMCPY( &op->o_req_ndn.bv_len, sl.list[i].values[0],
313 						sizeof( op->o_req_ndn.bv_len ) );
314 			} else if ( !strcmp( sl.list[i].name, slap_propnames[SLAP_SASL_PROP_AUTHC] ) ) {
315 				if ( sl.list[i].values ) {
316 					op->o_req_ndn.bv_val = (char *)sl.list[i].values[0];
317 					if ( !(flags & SASL_AUXPROP_AUTHZID) )
318 						break;
319 				}
320 			}
321 		}
322 	}
323 
324 	/* we don't know anything about this, ignore it */
325 	if ( !conn ) {
326 		rc = LDAP_SUCCESS;
327 		goto done;
328 	}
329 
330 	/* Now see what else needs to be fetched */
331 	for( i = 0; sl.list[i].name; i++ ) {
332 		const char *name = sl.list[i].name;
333 
334 		if ( name[0] == '*' ) {
335 			if ( flags & SASL_AUXPROP_AUTHZID ) continue;
336 			/* Skip our private properties */
337 			if ( !strcmp( name, slap_propnames[0] )) {
338 				i += SLAP_SASL_PROP_COUNT - 1;
339 				continue;
340 			}
341 			name++;
342 		} else if ( !(flags & SASL_AUXPROP_AUTHZID ) )
343 			continue;
344 
345 		if ( sl.list[i].values ) {
346 			if ( !(flags & SASL_AUXPROP_OVERRIDE) ) continue;
347 		}
348 		doit = 1;
349 		break;
350 	}
351 
352 	if (doit) {
353 		slap_callback cb = { NULL, sasl_ap_lookup, NULL, NULL };
354 
355 		cb.sc_private = &sl;
356 
357 		op->o_bd = select_backend( &op->o_req_ndn, 1 );
358 
359 		if ( op->o_bd ) {
360 			/* For rootdn, see if we can use the rootpw */
361 			if ( be_isroot_dn( op->o_bd, &op->o_req_ndn ) &&
362 				!BER_BVISEMPTY( &op->o_bd->be_rootpw )) {
363 				struct berval cbv = BER_BVNULL;
364 
365 				/* If there's a recognized scheme, see if it's CLEARTEXT */
366 				if ( lutil_passwd_scheme( op->o_bd->be_rootpw.bv_val )) {
367 					if ( !strncasecmp( op->o_bd->be_rootpw.bv_val,
368 						sc_cleartext.bv_val, sc_cleartext.bv_len )) {
369 
370 						/* If it's CLEARTEXT, skip past scheme spec */
371 						cbv.bv_len = op->o_bd->be_rootpw.bv_len -
372 							sc_cleartext.bv_len;
373 						if ( cbv.bv_len ) {
374 							cbv.bv_val = op->o_bd->be_rootpw.bv_val +
375 								sc_cleartext.bv_len;
376 						}
377 					}
378 				/* No scheme, use the whole value */
379 				} else {
380 					cbv = op->o_bd->be_rootpw;
381 				}
382 				if ( !BER_BVISEMPTY( &cbv )) {
383 					for( i = 0; sl.list[i].name; i++ ) {
384 						const char *name = sl.list[i].name;
385 
386 						if ( name[0] == '*' ) {
387 							if ( flags & SASL_AUXPROP_AUTHZID ) continue;
388 								name++;
389 						} else if ( !(flags & SASL_AUXPROP_AUTHZID ) )
390 							continue;
391 
392 						if ( !strcasecmp(name,"userPassword") ) {
393 							sl.sparams->utils->prop_set( sl.sparams->propctx,
394 								sl.list[i].name, cbv.bv_val, cbv.bv_len );
395 							break;
396 						}
397 					}
398 				}
399 			}
400 
401 			if ( op->o_bd->be_search ) {
402 				SlapReply rs = {REP_RESULT};
403 				op->o_hdr = conn->c_sasl_bindop->o_hdr;
404 				op->o_controls = opbuf.ob_controls;
405 				op->o_tag = LDAP_REQ_SEARCH;
406 				op->o_dn = conn->c_ndn;
407 				op->o_ndn = conn->c_ndn;
408 				op->o_callback = &cb;
409 				slap_op_time( &op->o_time, &op->o_tincr );
410 				op->o_do_not_cache = 1;
411 				op->o_is_auth_check = 1;
412 				op->o_req_dn = op->o_req_ndn;
413 				op->ors_scope = LDAP_SCOPE_BASE;
414 				op->ors_deref = LDAP_DEREF_NEVER;
415 				op->ors_tlimit = SLAP_NO_LIMIT;
416 				op->ors_slimit = 1;
417 				op->ors_filter = &generic_filter;
418 				op->ors_filterstr = generic_filterstr;
419 				op->o_authz = conn->c_authz;
420 				/* FIXME: we want all attributes, right? */
421 				op->ors_attrs = NULL;
422 
423 				rc = op->o_bd->be_search( op, &rs );
424 			}
425 		}
426 	}
427 done:;
428 #if SASL_VERSION_FULL >= 0x020118
429 	return rc != LDAP_SUCCESS ? SASL_FAIL : SASL_OK;
430 #endif
431 }
432 
433 #if SASL_VERSION_FULL >= 0x020110
434 static int
slap_auxprop_store(void * glob_context,sasl_server_params_t * sparams,struct propctx * prctx,const char * user,unsigned ulen)435 slap_auxprop_store(
436 	void *glob_context,
437 	sasl_server_params_t *sparams,
438 	struct propctx *prctx,
439 	const char *user,
440 	unsigned ulen)
441 {
442 	Operation op = {0};
443 	Opheader oph;
444 	SlapReply rs = {REP_RESULT};
445 	int rc, i;
446 	unsigned j;
447 	Connection *conn = NULL;
448 	const struct propval *pr;
449 	Modifications *modlist = NULL, **modtail = &modlist, *mod;
450 	slap_callback cb = { NULL, slap_null_cb, NULL, NULL };
451 	char textbuf[SLAP_TEXT_BUFLEN];
452 	const char *text;
453 	size_t textlen = sizeof(textbuf);
454 
455 	/* just checking if we are enabled */
456 	if (!prctx) return SASL_OK;
457 
458 	if (!sparams || !user) return SASL_BADPARAM;
459 
460 	pr = sparams->utils->prop_get( sparams->propctx );
461 
462 	/* Find our DN and conn first */
463 	for( i = 0; pr[i].name; i++ ) {
464 		if ( pr[i].name[0] == '*' ) {
465 			if ( !strcmp( pr[i].name, slap_propnames[SLAP_SASL_PROP_CONN] ) ) {
466 				if ( pr[i].values && pr[i].values[0] )
467 					AC_MEMCPY( &conn, pr[i].values[0], sizeof( conn ) );
468 				continue;
469 			}
470 			if ( !strcmp( pr[i].name, slap_propnames[SLAP_SASL_PROP_AUTHCLEN] )) {
471 				if ( pr[i].values && pr[i].values[0] )
472 					AC_MEMCPY( &op.o_req_ndn.bv_len, pr[i].values[0],
473 						sizeof( op.o_req_ndn.bv_len ) );
474 			} else if ( !strcmp( pr[i].name, slap_propnames[SLAP_SASL_PROP_AUTHC] ) ) {
475 				if ( pr[i].values )
476 					op.o_req_ndn.bv_val = (char *)pr[i].values[0];
477 			}
478 		}
479 	}
480 	if (!conn || !op.o_req_ndn.bv_val) return SASL_BADPARAM;
481 
482 	op.o_bd = select_backend( &op.o_req_ndn, 1 );
483 
484 	if ( !op.o_bd || !op.o_bd->be_modify ) return SASL_FAIL;
485 
486 	pr = sparams->utils->prop_get( prctx );
487 	if (!pr) return SASL_BADPARAM;
488 
489 	for (i=0; pr[i].name; i++);
490 	if (!i) return SASL_BADPARAM;
491 
492 	for (i=0; pr[i].name; i++) {
493 		mod = (Modifications *)ch_malloc( sizeof(Modifications) );
494 		mod->sml_op = LDAP_MOD_REPLACE;
495 		mod->sml_flags = 0;
496 		ber_str2bv( pr[i].name, 0, 0, &mod->sml_type );
497 		mod->sml_numvals = pr[i].nvalues;
498 		mod->sml_values = (struct berval *)ch_malloc( (pr[i].nvalues + 1) *
499 			sizeof(struct berval));
500 		for (j=0; j<pr[i].nvalues; j++) {
501 			ber_str2bv( pr[i].values[j], 0, 1, &mod->sml_values[j]);
502 		}
503 		BER_BVZERO( &mod->sml_values[j] );
504 		mod->sml_nvalues = NULL;
505 		mod->sml_desc = NULL;
506 		*modtail = mod;
507 		modtail = &mod->sml_next;
508 	}
509 	*modtail = NULL;
510 
511 	rc = slap_mods_check( &op, modlist, &text, textbuf, textlen, NULL );
512 
513 	if ( rc == LDAP_SUCCESS ) {
514 		rc = slap_mods_no_user_mod_check( &op, modlist,
515 			&text, textbuf, textlen );
516 
517 		if ( rc == LDAP_SUCCESS ) {
518 			if ( conn->c_sasl_bindop ) {
519 				op.o_hdr = conn->c_sasl_bindop->o_hdr;
520 			} else {
521 				op.o_hdr = &oph;
522 				memset( &oph, 0, sizeof(oph) );
523 				operation_fake_init( conn, &op, ldap_pvt_thread_pool_context(), 0 );
524 			}
525 			op.o_tag = LDAP_REQ_MODIFY;
526 			op.o_ndn = op.o_req_ndn;
527 			op.o_callback = &cb;
528 			slap_op_time( &op.o_time, &op.o_tincr );
529 			op.o_do_not_cache = 1;
530 			op.o_is_auth_check = 1;
531 			op.o_req_dn = op.o_req_ndn;
532 			op.orm_modlist = modlist;
533 
534 			rc = op.o_bd->be_modify( &op, &rs );
535 		}
536 	}
537 	slap_mods_free( modlist, 1 );
538 	return rc != LDAP_SUCCESS ? SASL_FAIL : SASL_OK;
539 }
540 #endif /* SASL_VERSION_FULL >= 2.1.16 */
541 
542 static sasl_auxprop_plug_t slap_auxprop_plugin = {
543 	0,	/* Features */
544 	0,	/* spare */
545 	NULL,	/* glob_context */
546 	NULL,	/* auxprop_free */
547 	slap_auxprop_lookup,
548 	"slapd",	/* name */
549 #if SASL_VERSION_FULL >= 0x020110
550 	slap_auxprop_store	/* the declaration of this member changed
551 				 * in cyrus SASL from 2.1.15 to 2.1.16 */
552 #else
553 	NULL
554 #endif
555 };
556 
557 static int
slap_auxprop_init(const sasl_utils_t * utils,int max_version,int * out_version,sasl_auxprop_plug_t ** plug,const char * plugname)558 slap_auxprop_init(
559 	const sasl_utils_t *utils,
560 	int max_version,
561 	int *out_version,
562 	sasl_auxprop_plug_t **plug,
563 	const char *plugname)
564 {
565 	if ( !out_version || !plug ) return SASL_BADPARAM;
566 
567 	if ( max_version < SASL_AUXPROP_PLUG_VERSION ) return SASL_BADVERS;
568 
569 	*out_version = SASL_AUXPROP_PLUG_VERSION;
570 	*plug = &slap_auxprop_plugin;
571 	return SASL_OK;
572 }
573 
574 /* Convert a SASL authcid or authzid into a DN. Store the DN in an
575  * auxiliary property, so that we can refer to it in sasl_authorize
576  * without interfering with anything else. Also, the SASL username
577  * buffer is constrained to 256 characters, and our DNs could be
578  * much longer (SLAP_LDAPDN_MAXLEN, currently set to 8192)
579  */
580 static int
slap_sasl_canonicalize(sasl_conn_t * sconn,void * context,const char * in,unsigned inlen,unsigned flags,const char * user_realm,char * out,unsigned out_max,unsigned * out_len)581 slap_sasl_canonicalize(
582 	sasl_conn_t *sconn,
583 	void *context,
584 	const char *in,
585 	unsigned inlen,
586 	unsigned flags,
587 	const char *user_realm,
588 	char *out,
589 	unsigned out_max,
590 	unsigned *out_len)
591 {
592 	Connection *conn = (Connection *)context;
593 	struct propctx *props = sasl_auxprop_getctx( sconn );
594 	struct propval auxvals[ SLAP_SASL_PROP_COUNT ] = { { 0 } };
595 	struct berval dn;
596 	int rc, which;
597 	const char *names[2];
598 	struct berval	bvin;
599 
600 	*out_len = 0;
601 
602 	Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: %s=\"%s\"\n",
603 		conn ? (long) conn->c_connid : -1L,
604 		(flags & SASL_CU_AUTHID) ? "authcid" : "authzid",
605 		in ? in : "<empty>");
606 
607 	/* If name is too big, just truncate. We don't care, we're
608 	 * using DNs, not the usernames.
609 	 */
610 	if ( inlen > out_max )
611 		inlen = out_max-1;
612 
613 	/* This is a Simple Bind using SPASSWD. That means the in-directory
614 	 * userPassword of the Binding user already points at SASL, so it
615 	 * cannot be used to actually satisfy a password comparison. Just
616 	 * ignore it, some other mech will process it.
617 	 */
618 	if ( !conn->c_sasl_bindop ||
619 		conn->c_sasl_bindop->orb_method != LDAP_AUTH_SASL ) goto done;
620 
621 	/* See if we need to add request, can only do it once */
622 	prop_getnames( props, slap_propnames, auxvals );
623 	if ( !auxvals[0].name )
624 		prop_request( props, slap_propnames );
625 
626 	if ( flags & SASL_CU_AUTHID )
627 		which = SLAP_SASL_PROP_AUTHCLEN;
628 	else
629 		which = SLAP_SASL_PROP_AUTHZLEN;
630 
631 	/* Need to store the Connection for auxprop_lookup */
632 	if ( !auxvals[SLAP_SASL_PROP_CONN].values ) {
633 		names[0] = slap_propnames[SLAP_SASL_PROP_CONN];
634 		names[1] = NULL;
635 		prop_set( props, names[0], (char *)&conn, sizeof( conn ) );
636 	}
637 
638 	/* Already been here? */
639 	if ( auxvals[which].values )
640 		goto done;
641 
642 	/* Normally we require an authzID to have a u: or dn: prefix.
643 	 * However, SASL frequently gives us an authzID that is just
644 	 * an exact copy of the authcID, without a prefix. We need to
645 	 * detect and allow this condition. If SASL calls canonicalize
646 	 * with SASL_CU_AUTHID|SASL_CU_AUTHZID this is a no-brainer.
647 	 * But if it's broken into two calls, we need to remember the
648 	 * authcID so that we can compare the authzID later. We store
649 	 * the authcID temporarily in conn->c_sasl_dn. We necessarily
650 	 * finish Canonicalizing before Authorizing, so there is no
651 	 * conflict with slap_sasl_authorize's use of this temp var.
652 	 *
653 	 * The SASL EXTERNAL mech is backwards from all the other mechs,
654 	 * it does authzID before the authcID. If we see that authzID
655 	 * has already been done, don't do anything special with authcID.
656 	 */
657 	if ( flags == SASL_CU_AUTHID && !auxvals[SLAP_SASL_PROP_AUTHZ].values ) {
658 		conn->c_sasl_dn.bv_val = (char *) in;
659 		conn->c_sasl_dn.bv_len = 0;
660 	} else if ( flags == SASL_CU_AUTHZID && conn->c_sasl_dn.bv_val ) {
661 		rc = strcmp( in, conn->c_sasl_dn.bv_val );
662 		conn->c_sasl_dn.bv_val = NULL;
663 		/* They were equal, no work needed */
664 		if ( !rc ) goto done;
665 	}
666 
667 	bvin.bv_val = (char *)in;
668 	bvin.bv_len = inlen;
669 	rc = slap_sasl_getdn( conn, NULL, &bvin, (char *)user_realm, &dn,
670 		(flags & SASL_CU_AUTHID) ? SLAP_GETDN_AUTHCID : SLAP_GETDN_AUTHZID );
671 	if ( rc != LDAP_SUCCESS ) {
672 		sasl_seterror( sconn, 0, ldap_err2string( rc ) );
673 		return SASL_NOAUTHZ;
674 	}
675 
676 	names[0] = slap_propnames[which];
677 	names[1] = NULL;
678 	prop_set( props, names[0], (char *)&dn.bv_len, sizeof( dn.bv_len ) );
679 
680 	which++;
681 	names[0] = slap_propnames[which];
682 	prop_set( props, names[0], dn.bv_val, dn.bv_len );
683 
684 	Debug( LDAP_DEBUG_ARGS, "SASL Canonicalize [conn=%ld]: %s=\"%s\"\n",
685 		conn ? (long) conn->c_connid : -1L, names[0]+1,
686 		dn.bv_val ? dn.bv_val : "<EMPTY>" );
687 
688 	/* Not needed any more, SASL has copied it */
689 	if ( conn && conn->c_sasl_bindop )
690 		conn->c_sasl_bindop->o_tmpfree( dn.bv_val, conn->c_sasl_bindop->o_tmpmemctx );
691 
692 done:
693 	AC_MEMCPY( out, in, inlen );
694 	out[inlen] = '\0';
695 
696 	*out_len = inlen;
697 
698 	return SASL_OK;
699 }
700 
701 static int
slap_sasl_authorize(sasl_conn_t * sconn,void * context,char * requested_user,unsigned rlen,char * auth_identity,unsigned alen,const char * def_realm,unsigned urlen,struct propctx * props)702 slap_sasl_authorize(
703 	sasl_conn_t *sconn,
704 	void *context,
705 	char *requested_user,
706 	unsigned rlen,
707 	char *auth_identity,
708 	unsigned alen,
709 	const char *def_realm,
710 	unsigned urlen,
711 	struct propctx *props)
712 {
713 	Connection *conn = (Connection *)context;
714 	/* actually:
715 	 *	(SLAP_SASL_PROP_COUNT - 1)	because we skip "conn",
716 	 *	+ 1				for NULL termination?
717 	 */
718 	struct propval auxvals[ SLAP_SASL_PROP_COUNT ] = { { 0 } };
719 	struct berval authcDN, authzDN = BER_BVNULL;
720 	int rc;
721 
722 	/* Simple Binds don't support proxy authorization, ignore it */
723 	if ( !conn->c_sasl_bindop ||
724 		conn->c_sasl_bindop->orb_method != LDAP_AUTH_SASL ) return SASL_OK;
725 
726 	Debug( LDAP_DEBUG_ARGS, "SASL proxy authorize [conn=%ld]: "
727 		"authcid=\"%s\" authzid=\"%s\"\n",
728 		conn ? (long) conn->c_connid : -1L, auth_identity, requested_user );
729 	if ( conn->c_sasl_dn.bv_val ) {
730 		BER_BVZERO( &conn->c_sasl_dn );
731 	}
732 
733 	/* Skip SLAP_SASL_PROP_CONN */
734 	prop_getnames( props, slap_propnames+1, auxvals );
735 
736 	/* Should not happen */
737 	if ( !auxvals[0].values ) {
738 		sasl_seterror( sconn, 0, "invalid authcid" );
739 		return SASL_NOAUTHZ;
740 	}
741 
742 	AC_MEMCPY( &authcDN.bv_len, auxvals[0].values[0], sizeof(authcDN.bv_len) );
743 	authcDN.bv_val = auxvals[1].values ? (char *)auxvals[1].values[0] : NULL;
744 	conn->c_sasl_dn = authcDN;
745 
746 	/* Nothing to do if no authzID was given */
747 	if ( !auxvals[2].name || !auxvals[2].values ) {
748 		goto ok;
749 	}
750 
751 	AC_MEMCPY( &authzDN.bv_len, auxvals[2].values[0], sizeof(authzDN.bv_len) );
752 	authzDN.bv_val = auxvals[3].values ? (char *)auxvals[3].values[0] : NULL;
753 
754 	rc = slap_sasl_authorized( conn->c_sasl_bindop, &authcDN, &authzDN );
755 	if ( rc != LDAP_SUCCESS ) {
756 		Debug( LDAP_DEBUG_TRACE, "SASL Proxy Authorize [conn=%ld]: "
757 			"proxy authorization disallowed (%d)\n",
758 			conn ? (long) conn->c_connid : -1L, rc, 0 );
759 
760 		sasl_seterror( sconn, 0, "not authorized" );
761 		return SASL_NOAUTHZ;
762 	}
763 
764 	/* FIXME: we need yet another dup because slap_sasl_getdn()
765 	 * is using the bind operation slab */
766 	ber_dupbv( &conn->c_sasl_authz_dn, &authzDN );
767 
768 ok:
769 	if (conn->c_sasl_bindop) {
770 		Statslog( LDAP_DEBUG_STATS,
771 			"%s BIND authcid=\"%s\" authzid=\"%s\"\n",
772 			conn->c_sasl_bindop->o_log_prefix,
773 			auth_identity, requested_user, 0, 0 );
774 	}
775 
776 	Debug( LDAP_DEBUG_TRACE, "SASL Authorize [conn=%ld]: "
777 		" proxy authorization allowed authzDN=\"%s\"\n",
778 		conn ? (long) conn->c_connid : -1L,
779 		authzDN.bv_val ? authzDN.bv_val : "", 0 );
780 	return SASL_OK;
781 }
782 
783 static int
slap_sasl_err2ldap(int saslerr)784 slap_sasl_err2ldap( int saslerr )
785 {
786 	int rc;
787 
788 	/* map SASL errors to LDAP resultCode returned by:
789 	 *	sasl_server_new()
790 	 *		SASL_OK, SASL_NOMEM
791 	 *	sasl_server_step()
792 	 *		SASL_OK, SASL_CONTINUE, SASL_TRANS, SASL_BADPARAM, SASL_BADPROT,
793 	 *      ...
794 	 *	sasl_server_start()
795 	 *      + SASL_NOMECH
796 	 *	sasl_setprop()
797 	 *		SASL_OK, SASL_BADPARAM
798 	 */
799 
800 	switch (saslerr) {
801 		case SASL_OK:
802 			rc = LDAP_SUCCESS;
803 			break;
804 		case SASL_CONTINUE:
805 			rc = LDAP_SASL_BIND_IN_PROGRESS;
806 			break;
807 		case SASL_FAIL:
808 		case SASL_NOMEM:
809 			rc = LDAP_OTHER;
810 			break;
811 		case SASL_NOMECH:
812 			rc = LDAP_AUTH_METHOD_NOT_SUPPORTED;
813 			break;
814 		case SASL_BADAUTH:
815 		case SASL_NOUSER:
816 		case SASL_TRANS:
817 		case SASL_EXPIRED:
818 			rc = LDAP_INVALID_CREDENTIALS;
819 			break;
820 		case SASL_NOAUTHZ:
821 			rc = LDAP_INSUFFICIENT_ACCESS;
822 			break;
823 		case SASL_TOOWEAK:
824 		case SASL_ENCRYPT:
825 			rc = LDAP_INAPPROPRIATE_AUTH;
826 			break;
827 		case SASL_UNAVAIL:
828 		case SASL_TRYAGAIN:
829 			rc = LDAP_UNAVAILABLE;
830 			break;
831 		case SASL_DISABLED:
832 			rc = LDAP_UNWILLING_TO_PERFORM;
833 			break;
834 		default:
835 			rc = LDAP_OTHER;
836 			break;
837 	}
838 
839 	return rc;
840 }
841 
842 #ifdef SLAPD_SPASSWD
843 
844 static struct berval sasl_pwscheme = BER_BVC("{SASL}");
845 
chk_sasl(const struct berval * sc,const struct berval * passwd,const struct berval * cred,const char ** text)846 static int chk_sasl(
847 	const struct berval *sc,
848 	const struct berval * passwd,
849 	const struct berval * cred,
850 	const char **text )
851 {
852 	unsigned int i;
853 	int rtn;
854 	void *ctx, *sconn = NULL;
855 
856 	for( i=0; i<cred->bv_len; i++) {
857 		if(cred->bv_val[i] == '\0') {
858 			return LUTIL_PASSWD_ERR;	/* NUL character in password */
859 		}
860 	}
861 
862 	if( cred->bv_val[i] != '\0' ) {
863 		return LUTIL_PASSWD_ERR;	/* cred must behave like a string */
864 	}
865 
866 	for( i=0; i<passwd->bv_len; i++) {
867 		if(passwd->bv_val[i] == '\0') {
868 			return LUTIL_PASSWD_ERR;	/* NUL character in password */
869 		}
870 	}
871 
872 	if( passwd->bv_val[i] != '\0' ) {
873 		return LUTIL_PASSWD_ERR;	/* passwd must behave like a string */
874 	}
875 
876 	rtn = LUTIL_PASSWD_ERR;
877 
878 	ctx = ldap_pvt_thread_pool_context();
879 	ldap_pvt_thread_pool_getkey( ctx, (void *)slap_sasl_bind, &sconn, NULL );
880 
881 	if( sconn != NULL ) {
882 		int sc;
883 		sc = sasl_checkpass( sconn,
884 			passwd->bv_val, passwd->bv_len,
885 			cred->bv_val, cred->bv_len );
886 		rtn = ( sc != SASL_OK ) ? LUTIL_PASSWD_ERR : LUTIL_PASSWD_OK;
887 	}
888 
889 	return rtn;
890 }
891 #endif /* SLAPD_SPASSWD */
892 
893 #endif /* HAVE_CYRUS_SASL */
894 
895 #ifdef ENABLE_REWRITE
896 
897 typedef struct slapd_map_data {
898 	struct berval base;
899 	struct berval filter;
900 	AttributeName attrs[2];
901 	int scope;
902 } slapd_map_data;
903 
904 static void *
slapd_rw_config(const char * fname,int lineno,int argc,char ** argv)905 slapd_rw_config( const char *fname, int lineno, int argc, char **argv )
906 {
907 	slapd_map_data *ret = NULL;
908 	LDAPURLDesc *lud = NULL;
909 	char *uri;
910 	AttributeDescription *ad = NULL;
911 	int rc, flen = 0;
912 	struct berval dn, ndn;
913 
914 	if ( argc != 1 ) {
915 		Debug( LDAP_DEBUG_ANY,
916 			"[%s:%d] slapd map needs URI\n",
917 			fname, lineno, 0 );
918         return NULL;
919 	}
920 
921 	uri = argv[0];
922 	if ( strncasecmp( uri, "uri=", STRLENOF( "uri=" ) ) == 0 ) {
923 		uri += STRLENOF( "uri=" );
924 	}
925 
926 	if ( ldap_url_parse( uri, &lud ) != LDAP_URL_SUCCESS ) {
927 		Debug( LDAP_DEBUG_ANY,
928 			"[%s:%d] illegal URI '%s'\n",
929 			fname, lineno, uri );
930         return NULL;
931 	}
932 
933 	if ( strcasecmp( lud->lud_scheme, "ldap" )) {
934 		Debug( LDAP_DEBUG_ANY,
935 			"[%s:%d] illegal URI scheme '%s'\n",
936 			fname, lineno, lud->lud_scheme );
937 		goto done;
938 	}
939 
940 	if (( lud->lud_host && lud->lud_host[0] ) || lud->lud_exts
941 		|| !lud->lud_dn ) {
942 		Debug( LDAP_DEBUG_ANY,
943 			"[%s:%d] illegal URI '%s'\n",
944 			fname, lineno, uri );
945 		goto done;
946 	}
947 
948 	if ( lud->lud_attrs ) {
949 		if ( lud->lud_attrs[1] ) {
950 			Debug( LDAP_DEBUG_ANY,
951 				"[%s:%d] only one attribute allowed in URI\n",
952 				fname, lineno, 0 );
953 			goto done;
954 		}
955 		if ( strcasecmp( lud->lud_attrs[0], "dn" ) &&
956 			strcasecmp( lud->lud_attrs[0], "entryDN" )) {
957 			const char *text;
958 			rc = slap_str2ad( lud->lud_attrs[0], &ad, &text );
959 			if ( rc )
960 				goto done;
961 		}
962 	}
963 	ber_str2bv( lud->lud_dn, 0, 0, &dn );
964 	if ( dnNormalize( 0, NULL, NULL, &dn, &ndn, NULL ))
965 		goto done;
966 
967 	if ( lud->lud_filter ) {
968 		flen = strlen( lud->lud_filter ) + 1;
969 	}
970 	ret = ch_malloc( sizeof( slapd_map_data ) + flen );
971 	ret->base = ndn;
972 	if ( flen ) {
973 		ret->filter.bv_val = (char *)(ret+1);
974 		ret->filter.bv_len = flen - 1;
975 		strcpy( ret->filter.bv_val, lud->lud_filter );
976 	} else {
977 		BER_BVZERO( &ret->filter );
978 	}
979 	ret->scope = lud->lud_scope;
980 	if ( ad ) {
981 		ret->attrs[0].an_name = ad->ad_cname;
982 	} else {
983 		BER_BVZERO( &ret->attrs[0].an_name );
984 	}
985 	ret->attrs[0].an_desc = ad;
986 	BER_BVZERO( &ret->attrs[1].an_name );
987 done:
988 	ldap_free_urldesc( lud );
989 	return ret;
990 }
991 
992 struct slapd_rw_info {
993 	slapd_map_data *si_data;
994 	struct berval si_val;
995 };
996 
997 static int
slapd_rw_cb(Operation * op,SlapReply * rs)998 slapd_rw_cb( Operation *op, SlapReply *rs )
999 {
1000 	if ( rs->sr_type == REP_SEARCH ) {
1001 		struct slapd_rw_info *si = op->o_callback->sc_private;
1002 
1003 		if ( si->si_data->attrs[0].an_desc ) {
1004 			Attribute *a;
1005 
1006 			a = attr_find( rs->sr_entry->e_attrs,
1007 				si->si_data->attrs[0].an_desc );
1008 			if ( a ) {
1009 				ber_dupbv( &si->si_val, a->a_vals );
1010 			}
1011 		} else {
1012 			ber_dupbv( &si->si_val, &rs->sr_entry->e_name );
1013 		}
1014 	}
1015 	return LDAP_SUCCESS;
1016 }
1017 
1018 static int
slapd_rw_apply(void * private,const char * filter,struct berval * val)1019 slapd_rw_apply( void *private, const char *filter, struct berval *val )
1020 {
1021 	slapd_map_data *sl = private;
1022 	slap_callback cb = { NULL };
1023 	Connection conn = {0};
1024 	OperationBuffer opbuf;
1025 	Operation *op;
1026 	void *thrctx;
1027 	SlapReply rs = {REP_RESULT};
1028 	struct slapd_rw_info si;
1029 	char *ptr;
1030 	int rc;
1031 
1032 	thrctx = ldap_pvt_thread_pool_context();
1033 	connection_fake_init2( &conn, &opbuf, thrctx, 0 );
1034 	op = &opbuf.ob_op;
1035 
1036 	op->o_tag = LDAP_REQ_SEARCH;
1037 	op->o_req_dn = op->o_req_ndn = sl->base;
1038 	op->o_bd = select_backend( &op->o_req_ndn, 1 );
1039 	if ( !op->o_bd ) {
1040 		return REWRITE_ERR;
1041 	}
1042 	si.si_data = sl;
1043 	BER_BVZERO( &si.si_val );
1044 	op->ors_scope = sl->scope;
1045 	op->ors_deref = LDAP_DEREF_NEVER;
1046 	op->ors_slimit = 1;
1047 	op->ors_tlimit = SLAP_NO_LIMIT;
1048 	if ( sl->attrs[0].an_desc ) {
1049 		op->ors_attrs = sl->attrs;
1050 	} else {
1051 		op->ors_attrs = slap_anlist_no_attrs;
1052 	}
1053 	if ( filter ) {
1054 		rc = strlen( filter );
1055 	} else {
1056 		rc = 0;
1057 	}
1058 	rc += sl->filter.bv_len;
1059 	ptr = op->ors_filterstr.bv_val = op->o_tmpalloc( rc + 1, op->o_tmpmemctx );
1060 	if ( sl->filter.bv_len ) {
1061 		ptr = lutil_strcopy( ptr, sl->filter.bv_val );
1062 	} else {
1063 		*ptr = '\0';
1064 	}
1065 	if ( filter ) {
1066 		strcpy( ptr, filter );
1067 	}
1068 	op->ors_filter = str2filter_x( op, op->ors_filterstr.bv_val );
1069 	if ( !op->ors_filter ) {
1070 		op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1071 		return REWRITE_ERR;
1072 	}
1073 
1074 	op->ors_attrsonly = 0;
1075 	op->o_dn = op->o_bd->be_rootdn;
1076 	op->o_ndn = op->o_bd->be_rootndn;
1077 	op->o_do_not_cache = 1;
1078 
1079 	cb.sc_response = slapd_rw_cb;
1080 	cb.sc_private = &si;
1081 	op->o_callback = &cb;
1082 
1083 	rc = op->o_bd->be_search( op, &rs );
1084 	if ( rc == LDAP_SUCCESS && !BER_BVISNULL( &si.si_val )) {
1085 		*val = si.si_val;
1086 		rc = REWRITE_SUCCESS;
1087 	} else {
1088 		if ( !BER_BVISNULL( &si.si_val )) {
1089 			ch_free( si.si_val.bv_val );
1090 		}
1091 		rc = REWRITE_ERR;
1092 	}
1093 	filter_free_x( op, op->ors_filter, 1 );
1094 	op->o_tmpfree( op->ors_filterstr.bv_val, op->o_tmpmemctx );
1095 	return rc;
1096 }
1097 
1098 static int
slapd_rw_destroy(void * private)1099 slapd_rw_destroy( void *private )
1100 {
1101 	slapd_map_data *md = private;
1102 
1103 	assert( private != NULL );
1104 
1105 	ch_free( md->base.bv_val );
1106 	ch_free( md );
1107 
1108 	return 0;
1109 }
1110 
1111 static const rewrite_mapper slapd_mapper = {
1112 	"slapd",
1113 	slapd_rw_config,
1114 	slapd_rw_apply,
1115 	slapd_rw_destroy
1116 };
1117 #endif
1118 
slap_sasl_init(void)1119 int slap_sasl_init( void )
1120 {
1121 #ifdef HAVE_CYRUS_SASL
1122 	int rc;
1123 	static sasl_callback_t server_callbacks[] = {
1124 		{ SASL_CB_LOG, (slap_sasl_cb_ft)&slap_sasl_log, NULL },
1125 		{ SASL_CB_GETOPT, (slap_sasl_cb_ft)&slap_sasl_getopt, NULL },
1126 		{ SASL_CB_LIST_END, NULL, NULL }
1127 	};
1128 #endif
1129 
1130 #ifdef ENABLE_REWRITE
1131 	rewrite_mapper_register( &slapd_mapper );
1132 #endif
1133 
1134 #ifdef HAVE_CYRUS_SASL
1135 #ifdef HAVE_SASL_VERSION
1136 	/* stringify the version number, sasl.h doesn't do it for us */
1137 #define	VSTR0(maj, min, pat)	#maj "." #min "." #pat
1138 #define	VSTR(maj, min, pat)	VSTR0(maj, min, pat)
1139 #define	SASL_VERSION_STRING	VSTR(SASL_VERSION_MAJOR, SASL_VERSION_MINOR, \
1140 				SASL_VERSION_STEP)
1141 
1142 	sasl_version( NULL, &rc );
1143 	if ( ((rc >> 16) != ((SASL_VERSION_MAJOR << 8)|SASL_VERSION_MINOR)) ||
1144 		(rc & 0xffff) < SASL_VERSION_STEP)
1145 	{
1146 		char version[sizeof("xxx.xxx.xxxxx")];
1147 		sprintf( version, "%u.%d.%d", (unsigned)rc >> 24, (rc >> 16) & 0xff,
1148 			rc & 0xffff );
1149 		Debug( LDAP_DEBUG_ANY, "slap_sasl_init: SASL library version mismatch:"
1150 			" expected %s, got %s\n",
1151 			SASL_VERSION_STRING, version, 0 );
1152 		return -1;
1153 	}
1154 #endif
1155 
1156 	sasl_set_mutex(
1157 		ldap_pvt_sasl_mutex_new,
1158 		ldap_pvt_sasl_mutex_lock,
1159 		ldap_pvt_sasl_mutex_unlock,
1160 		ldap_pvt_sasl_mutex_dispose );
1161 
1162 	generic_filter.f_desc = slap_schema.si_ad_objectClass;
1163 
1164 	rc = sasl_auxprop_add_plugin( "slapd", slap_auxprop_init );
1165 	if( rc != SASL_OK ) {
1166 		Debug( LDAP_DEBUG_ANY, "slap_sasl_init: auxprop add plugin failed\n",
1167 			0, 0, 0 );
1168 		return -1;
1169 	}
1170 
1171 	/* should provide callbacks for logging */
1172 	/* server name should be configurable */
1173 	rc = sasl_server_init( server_callbacks, "slapd" );
1174 
1175 	if( rc != SASL_OK ) {
1176 		Debug( LDAP_DEBUG_ANY, "slap_sasl_init: server init failed\n",
1177 			0, 0, 0 );
1178 
1179 		return -1;
1180 	}
1181 
1182 #ifdef SLAPD_SPASSWD
1183 	lutil_passwd_add( &sasl_pwscheme, chk_sasl, NULL );
1184 #endif
1185 
1186 	Debug( LDAP_DEBUG_TRACE, "slap_sasl_init: initialized!\n",
1187 		0, 0, 0 );
1188 
1189 	/* default security properties */
1190 	memset( &sasl_secprops, '\0', sizeof(sasl_secprops) );
1191 	sasl_secprops.max_ssf = INT_MAX;
1192 	sasl_secprops.maxbufsize = 65536;
1193 	sasl_secprops.security_flags = SASL_SEC_NOPLAINTEXT|SASL_SEC_NOANONYMOUS;
1194 #endif
1195 
1196 	return 0;
1197 }
1198 
slap_sasl_destroy(void)1199 int slap_sasl_destroy( void )
1200 {
1201 #ifdef HAVE_CYRUS_SASL
1202 	sasl_done();
1203 #endif
1204 	free( sasl_host );
1205 	sasl_host = NULL;
1206 
1207 	return 0;
1208 }
1209 
1210 static char *
slap_sasl_peer2ipport(struct berval * peer)1211 slap_sasl_peer2ipport( struct berval *peer )
1212 {
1213 	int		isv6 = 0;
1214 	char		*ipport, *p,
1215 			*addr = &peer->bv_val[ STRLENOF( "IP=" ) ];
1216 	ber_len_t	plen = peer->bv_len - STRLENOF( "IP=" );
1217 
1218 	/* IPv6? */
1219 	if ( addr[0] == '[' ) {
1220 		isv6 = 1;
1221 		plen--;
1222 	}
1223 	ipport = ch_strdup( &addr[isv6] );
1224 
1225 	/* Convert IPv6/IPv4 addresses to address;port syntax. */
1226 	p = strrchr( ipport, ':' );
1227 	if ( p != NULL ) {
1228 		*p = ';';
1229 		if ( isv6 ) {
1230 			assert( p[-1] == ']' );
1231 			AC_MEMCPY( &p[-1], p, plen - ( p - ipport ) + 1 );
1232 		}
1233 
1234 	} else if ( isv6 ) {
1235 		/* trim ']' */
1236 		plen--;
1237 		assert( addr[plen] == ']' );
1238 		addr[plen] = '\0';
1239 	}
1240 
1241 	return ipport;
1242 }
1243 
slap_sasl_open(Connection * conn,int reopen)1244 int slap_sasl_open( Connection *conn, int reopen )
1245 {
1246 	int sc = LDAP_SUCCESS;
1247 #ifdef HAVE_CYRUS_SASL
1248 	int cb;
1249 
1250 	sasl_conn_t *ctx = NULL;
1251 	sasl_callback_t *session_callbacks;
1252 	char *ipremoteport = NULL, *iplocalport = NULL;
1253 
1254 	assert( conn->c_sasl_authctx == NULL );
1255 
1256 	if ( !reopen ) {
1257 		assert( conn->c_sasl_extra == NULL );
1258 
1259 		session_callbacks =
1260 			SLAP_CALLOC( 5, sizeof(sasl_callback_t));
1261 		if( session_callbacks == NULL ) {
1262 			Debug( LDAP_DEBUG_ANY,
1263 				"slap_sasl_open: SLAP_MALLOC failed", 0, 0, 0 );
1264 			return -1;
1265 		}
1266 		conn->c_sasl_extra = session_callbacks;
1267 
1268 		session_callbacks[cb=0].id = SASL_CB_LOG;
1269 		session_callbacks[cb].proc = (slap_sasl_cb_ft)&slap_sasl_log;
1270 		session_callbacks[cb++].context = conn;
1271 
1272 		session_callbacks[cb].id = SASL_CB_PROXY_POLICY;
1273 		session_callbacks[cb].proc = (slap_sasl_cb_ft)&slap_sasl_authorize;
1274 		session_callbacks[cb++].context = conn;
1275 
1276 		session_callbacks[cb].id = SASL_CB_CANON_USER;
1277 		session_callbacks[cb].proc = (slap_sasl_cb_ft)&slap_sasl_canonicalize;
1278 		session_callbacks[cb++].context = conn;
1279 
1280 		session_callbacks[cb].id = SASL_CB_LIST_END;
1281 		session_callbacks[cb].proc = NULL;
1282 		session_callbacks[cb++].context = NULL;
1283 	} else {
1284 		session_callbacks = conn->c_sasl_extra;
1285 	}
1286 
1287 	conn->c_sasl_layers = 0;
1288 
1289 	/* create new SASL context */
1290 	if ( conn->c_sock_name.bv_len != 0 &&
1291 		strncmp( conn->c_sock_name.bv_val, "IP=", STRLENOF( "IP=" ) ) == 0 )
1292 	{
1293 		iplocalport = slap_sasl_peer2ipport( &conn->c_sock_name );
1294 	}
1295 
1296 	if ( conn->c_peer_name.bv_len != 0 &&
1297 		strncmp( conn->c_peer_name.bv_val, "IP=", STRLENOF( "IP=" ) ) == 0 )
1298 	{
1299 		ipremoteport = slap_sasl_peer2ipport( &conn->c_peer_name );
1300 	}
1301 
1302 	sc = sasl_server_new( "ldap", sasl_host, global_realm,
1303 		iplocalport, ipremoteport, session_callbacks, SASL_SUCCESS_DATA, &ctx );
1304 	if ( iplocalport != NULL ) {
1305 		ch_free( iplocalport );
1306 	}
1307 	if ( ipremoteport != NULL ) {
1308 		ch_free( ipremoteport );
1309 	}
1310 
1311 	if( sc != SASL_OK ) {
1312 		Debug( LDAP_DEBUG_ANY, "sasl_server_new failed: %d\n",
1313 			sc, 0, 0 );
1314 
1315 		return -1;
1316 	}
1317 
1318 	conn->c_sasl_authctx = ctx;
1319 
1320 	if( sc == SASL_OK ) {
1321 		sc = sasl_setprop( ctx,
1322 			SASL_SEC_PROPS, &sasl_secprops );
1323 
1324 		if( sc != SASL_OK ) {
1325 			Debug( LDAP_DEBUG_ANY, "sasl_setprop failed: %d\n",
1326 				sc, 0, 0 );
1327 
1328 			slap_sasl_close( conn );
1329 			return -1;
1330 		}
1331 	}
1332 
1333 	sc = slap_sasl_err2ldap( sc );
1334 
1335 #elif defined(SLAP_BUILTIN_SASL)
1336 	/* built-in SASL implementation */
1337 	SASL_CTX *ctx = (SASL_CTX *) SLAP_MALLOC(sizeof(SASL_CTX));
1338 	if( ctx == NULL ) return -1;
1339 
1340 	ctx->sc_external_ssf = 0;
1341 	BER_BVZERO( &ctx->sc_external_id );
1342 
1343 	conn->c_sasl_authctx = ctx;
1344 #endif
1345 
1346 	return sc;
1347 }
1348 
slap_sasl_external(Connection * conn,slap_ssf_t ssf,struct berval * auth_id)1349 int slap_sasl_external(
1350 	Connection *conn,
1351 	slap_ssf_t ssf,
1352 	struct berval *auth_id )
1353 {
1354 #ifdef HAVE_CYRUS_SASL
1355 	int sc;
1356 	sasl_conn_t *ctx = conn->c_sasl_authctx;
1357 	sasl_ssf_t sasl_ssf = ssf;
1358 
1359 	if ( ctx == NULL ) {
1360 		return LDAP_UNAVAILABLE;
1361 	}
1362 
1363 	sc = sasl_setprop( ctx, SASL_SSF_EXTERNAL, &sasl_ssf );
1364 
1365 	if ( sc != SASL_OK ) {
1366 		return LDAP_OTHER;
1367 	}
1368 
1369 	sc = sasl_setprop( ctx, SASL_AUTH_EXTERNAL,
1370 		auth_id ? auth_id->bv_val : NULL );
1371 
1372 	if ( sc != SASL_OK ) {
1373 		return LDAP_OTHER;
1374 	}
1375 #elif defined(SLAP_BUILTIN_SASL)
1376 	/* built-in SASL implementation */
1377 	SASL_CTX *ctx = conn->c_sasl_authctx;
1378 	if ( ctx == NULL ) return LDAP_UNAVAILABLE;
1379 
1380 	ctx->sc_external_ssf = ssf;
1381 	if( auth_id ) {
1382 		ctx->sc_external_id = *auth_id;
1383 		BER_BVZERO( auth_id );
1384 	} else {
1385 		BER_BVZERO( &ctx->sc_external_id );
1386 	}
1387 #endif
1388 
1389 	return LDAP_SUCCESS;
1390 }
1391 
slap_sasl_reset(Connection * conn)1392 int slap_sasl_reset( Connection *conn )
1393 {
1394 	return LDAP_SUCCESS;
1395 }
1396 
slap_sasl_mechs(Connection * conn)1397 char ** slap_sasl_mechs( Connection *conn )
1398 {
1399 	char **mechs = NULL;
1400 
1401 #ifdef HAVE_CYRUS_SASL
1402 	sasl_conn_t *ctx = conn->c_sasl_authctx;
1403 
1404 	if( ctx == NULL ) ctx = conn->c_sasl_sockctx;
1405 
1406 	if( ctx != NULL ) {
1407 		int sc;
1408 		SASL_CONST char *mechstr;
1409 
1410 		sc = sasl_listmech( ctx,
1411 			NULL, NULL, ",", NULL,
1412 			&mechstr, NULL, NULL );
1413 
1414 		if( sc != SASL_OK ) {
1415 			Debug( LDAP_DEBUG_ANY, "slap_sasl_listmech failed: %d\n",
1416 				sc, 0, 0 );
1417 
1418 			return NULL;
1419 		}
1420 
1421 		mechs = ldap_str2charray( mechstr, "," );
1422 	}
1423 #elif defined(SLAP_BUILTIN_SASL)
1424 	/* builtin SASL implementation */
1425 	SASL_CTX *ctx = conn->c_sasl_authctx;
1426 	if ( ctx != NULL && ctx->sc_external_id.bv_val ) {
1427 		/* should check ssf */
1428 		mechs = ldap_str2charray( "EXTERNAL", "," );
1429 	}
1430 #endif
1431 
1432 	return mechs;
1433 }
1434 
slap_sasl_close(Connection * conn)1435 int slap_sasl_close( Connection *conn )
1436 {
1437 #ifdef HAVE_CYRUS_SASL
1438 	sasl_conn_t *ctx = conn->c_sasl_authctx;
1439 
1440 	if( ctx != NULL ) {
1441 		sasl_dispose( &ctx );
1442 	}
1443 	if ( conn->c_sasl_sockctx &&
1444 		conn->c_sasl_authctx != conn->c_sasl_sockctx )
1445 	{
1446 		ctx = conn->c_sasl_sockctx;
1447 		sasl_dispose( &ctx );
1448 	}
1449 
1450 	conn->c_sasl_authctx = NULL;
1451 	conn->c_sasl_sockctx = NULL;
1452 	conn->c_sasl_done = 0;
1453 
1454 	free( conn->c_sasl_extra );
1455 	conn->c_sasl_extra = NULL;
1456 
1457 #elif defined(SLAP_BUILTIN_SASL)
1458 	SASL_CTX *ctx = conn->c_sasl_authctx;
1459 	if( ctx ) {
1460 		if( ctx->sc_external_id.bv_val ) {
1461 			free( ctx->sc_external_id.bv_val );
1462 			BER_BVZERO( &ctx->sc_external_id );
1463 		}
1464 		free( ctx );
1465 		conn->c_sasl_authctx = NULL;
1466 	}
1467 #endif
1468 
1469 	return LDAP_SUCCESS;
1470 }
1471 
slap_sasl_bind(Operation * op,SlapReply * rs)1472 int slap_sasl_bind( Operation *op, SlapReply *rs )
1473 {
1474 #ifdef HAVE_CYRUS_SASL
1475 	sasl_conn_t *ctx = op->o_conn->c_sasl_authctx;
1476 	struct berval response;
1477 	unsigned reslen = 0;
1478 	int sc;
1479 
1480 	Debug(LDAP_DEBUG_ARGS,
1481 		"==> sasl_bind: dn=\"%s\" mech=%s datalen=%ld\n",
1482 		op->o_req_dn.bv_len ? op->o_req_dn.bv_val : "",
1483 		op->o_conn->c_sasl_bind_in_progress ? "<continuing>" :
1484 		op->o_conn->c_sasl_bind_mech.bv_val,
1485 		op->orb_cred.bv_len );
1486 
1487 	if( ctx == NULL ) {
1488 		send_ldap_error( op, rs, LDAP_UNAVAILABLE,
1489 			"SASL unavailable on this session" );
1490 		return rs->sr_err;
1491 	}
1492 
1493 #define	START( ctx, mech, cred, clen, resp, rlen, err ) \
1494 	sasl_server_start( ctx, mech, cred, clen, resp, rlen )
1495 #define	STEP( ctx, cred, clen, resp, rlen, err ) \
1496 	sasl_server_step( ctx, cred, clen, resp, rlen )
1497 
1498 	if ( !op->o_conn->c_sasl_bind_in_progress ) {
1499 		/* If we already authenticated once, must use a new context */
1500 		if ( op->o_conn->c_sasl_done ) {
1501 			sasl_ssf_t ssf = 0;
1502 			sasl_ssf_t *ssfp = NULL;
1503 			const char *authid = NULL;
1504 
1505 			sasl_getprop( ctx, SASL_SSF_EXTERNAL, (void *)&ssfp );
1506 			if ( ssfp ) ssf = *ssfp;
1507 
1508 			sasl_getprop( ctx, SASL_AUTH_EXTERNAL, (void *)&authid );
1509 			if ( authid ) authid = ch_strdup( authid );
1510 
1511 			if ( ctx != op->o_conn->c_sasl_sockctx ) {
1512 				sasl_dispose( &ctx );
1513 			}
1514 			op->o_conn->c_sasl_authctx = NULL;
1515 
1516 			slap_sasl_open( op->o_conn, 1 );
1517 			ctx = op->o_conn->c_sasl_authctx;
1518 			sasl_setprop( ctx, SASL_SSF_EXTERNAL, &ssf );
1519 			if ( authid ) {
1520 				sasl_setprop( ctx, SASL_AUTH_EXTERNAL, authid );
1521 				ch_free( (char *)authid );
1522 			}
1523 		}
1524 		sc = START( ctx,
1525 			op->o_conn->c_sasl_bind_mech.bv_val,
1526 			op->orb_cred.bv_val, op->orb_cred.bv_len,
1527 			(SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1528 
1529 	} else {
1530 		sc = STEP( ctx,
1531 			op->orb_cred.bv_val, op->orb_cred.bv_len,
1532 			(SASL_CONST char **)&response.bv_val, &reslen, &rs->sr_text );
1533 	}
1534 
1535 	response.bv_len = reslen;
1536 
1537 	if ( sc == SASL_OK ) {
1538 		sasl_ssf_t *ssf = NULL;
1539 
1540 		ber_dupbv_x( &op->orb_edn, &op->o_conn->c_sasl_dn, op->o_tmpmemctx );
1541 		BER_BVZERO( &op->o_conn->c_sasl_dn );
1542 		op->o_conn->c_sasl_done = 1;
1543 
1544 		rs->sr_err = LDAP_SUCCESS;
1545 
1546 		(void) sasl_getprop( ctx, SASL_SSF, (void *)&ssf );
1547 		op->orb_ssf = ssf ? *ssf : 0;
1548 
1549 		ctx = NULL;
1550 		if( op->orb_ssf ) {
1551 			ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1552 			op->o_conn->c_sasl_layers++;
1553 
1554 			/* If there's an old layer, set sockctx to NULL to
1555 			 * tell connection_read() to wait for us to finish.
1556 			 * Otherwise there is a race condition: we have to
1557 			 * send the Bind response using the old security
1558 			 * context and then remove it before reading any
1559 			 * new messages.
1560 			 */
1561 			if ( op->o_conn->c_sasl_sockctx ) {
1562 				ctx = op->o_conn->c_sasl_sockctx;
1563 				op->o_conn->c_sasl_sockctx = NULL;
1564 			} else {
1565 				op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1566 			}
1567 			ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1568 		}
1569 
1570 		/* Must send response using old security layer */
1571 		rs->sr_sasldata = (response.bv_len ? &response : NULL);
1572 		send_ldap_sasl( op, rs );
1573 
1574 		/* Now dispose of the old security layer.
1575 		 */
1576 		if ( ctx ) {
1577 			ldap_pvt_thread_mutex_lock( &op->o_conn->c_mutex );
1578 			ldap_pvt_sasl_remove( op->o_conn->c_sb );
1579 			op->o_conn->c_sasl_sockctx = op->o_conn->c_sasl_authctx;
1580 			ldap_pvt_thread_mutex_unlock( &op->o_conn->c_mutex );
1581 			sasl_dispose( &ctx );
1582 		}
1583 	} else if ( sc == SASL_CONTINUE ) {
1584 		rs->sr_err = LDAP_SASL_BIND_IN_PROGRESS,
1585 		rs->sr_text = sasl_errdetail( ctx );
1586 		rs->sr_sasldata = &response;
1587 		send_ldap_sasl( op, rs );
1588 
1589 	} else {
1590 		BER_BVZERO( &op->o_conn->c_sasl_dn );
1591 		rs->sr_text = sasl_errdetail( ctx );
1592 		rs->sr_err = slap_sasl_err2ldap( sc ),
1593 		send_ldap_result( op, rs );
1594 	}
1595 
1596 	Debug(LDAP_DEBUG_TRACE, "<== slap_sasl_bind: rc=%d\n", rs->sr_err, 0, 0);
1597 
1598 #elif defined(SLAP_BUILTIN_SASL)
1599 	/* built-in SASL implementation */
1600 	SASL_CTX *ctx = op->o_conn->c_sasl_authctx;
1601 
1602 	if ( ctx == NULL ) {
1603 		send_ldap_error( op, rs, LDAP_OTHER,
1604 			"Internal SASL Error" );
1605 
1606 	} else if ( bvmatch( &ext_bv, &op->o_conn->c_sasl_bind_mech ) ) {
1607 		/* EXTERNAL */
1608 
1609 		if( op->orb_cred.bv_len ) {
1610 			rs->sr_text = "proxy authorization not supported";
1611 			rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
1612 			send_ldap_result( op, rs );
1613 
1614 		} else {
1615 			op->orb_edn = ctx->sc_external_id;
1616 			rs->sr_err = LDAP_SUCCESS;
1617 			rs->sr_sasldata = NULL;
1618 			send_ldap_sasl( op, rs );
1619 		}
1620 
1621 	} else {
1622 		send_ldap_error( op, rs, LDAP_AUTH_METHOD_NOT_SUPPORTED,
1623 			"requested SASL mechanism not supported" );
1624 	}
1625 #else
1626 	send_ldap_error( op, rs, LDAP_AUTH_METHOD_NOT_SUPPORTED,
1627 		"SASL not supported" );
1628 #endif
1629 
1630 	return rs->sr_err;
1631 }
1632 
slap_sasl_secprops(const char * in)1633 char* slap_sasl_secprops( const char *in )
1634 {
1635 #ifdef HAVE_CYRUS_SASL
1636 	int rc = ldap_pvt_sasl_secprops( in, &sasl_secprops );
1637 
1638 	return rc == LDAP_SUCCESS ? NULL : "Invalid security properties";
1639 #else
1640 	return "SASL not supported";
1641 #endif
1642 }
1643 
slap_sasl_secprops_unparse(struct berval * bv)1644 void slap_sasl_secprops_unparse( struct berval *bv )
1645 {
1646 #ifdef HAVE_CYRUS_SASL
1647 	ldap_pvt_sasl_secprops_unparse( &sasl_secprops, bv );
1648 #endif
1649 }
1650 
1651 #ifdef HAVE_CYRUS_SASL
1652 int
slap_sasl_setpass(Operation * op,SlapReply * rs)1653 slap_sasl_setpass( Operation *op, SlapReply *rs )
1654 {
1655 	struct berval id = BER_BVNULL;	/* needs to come from connection */
1656 	struct berval new = BER_BVNULL;
1657 	struct berval old = BER_BVNULL;
1658 
1659 	assert( ber_bvcmp( &slap_EXOP_MODIFY_PASSWD, &op->ore_reqoid ) == 0 );
1660 
1661 	rs->sr_err = sasl_getprop( op->o_conn->c_sasl_authctx, SASL_USERNAME,
1662 		(SASL_CONST void **)(char *)&id.bv_val );
1663 
1664 	if( rs->sr_err != SASL_OK ) {
1665 		rs->sr_text = "unable to retrieve SASL username";
1666 		rs->sr_err = LDAP_OTHER;
1667 		goto done;
1668 	}
1669 
1670 	Debug( LDAP_DEBUG_ARGS, "==> slap_sasl_setpass: \"%s\"\n",
1671 		id.bv_val ? id.bv_val : "", 0, 0 );
1672 
1673 	rs->sr_err = slap_passwd_parse( op->ore_reqdata,
1674 		NULL, &old, &new, &rs->sr_text );
1675 
1676 	if( rs->sr_err != LDAP_SUCCESS ) {
1677 		goto done;
1678 	}
1679 
1680 	if( new.bv_len == 0 ) {
1681 		slap_passwd_generate(&new);
1682 
1683 		if( new.bv_len == 0 ) {
1684 			rs->sr_text = "password generation failed.";
1685 			rs->sr_err = LDAP_OTHER;
1686 			goto done;
1687 		}
1688 
1689 		rs->sr_rspdata = slap_passwd_return( &new );
1690 	}
1691 
1692 	rs->sr_err = sasl_setpass( op->o_conn->c_sasl_authctx, id.bv_val,
1693 		new.bv_val, new.bv_len, old.bv_val, old.bv_len, 0 );
1694 	if( rs->sr_err != SASL_OK ) {
1695 		rs->sr_text = sasl_errdetail( op->o_conn->c_sasl_authctx );
1696 	}
1697 	switch(rs->sr_err) {
1698 		case SASL_OK:
1699 			rs->sr_err = LDAP_SUCCESS;
1700 			break;
1701 
1702 		case SASL_NOCHANGE:
1703 		case SASL_NOMECH:
1704 		case SASL_DISABLED:
1705 		case SASL_PWLOCK:
1706 		case SASL_FAIL:
1707 		case SASL_BADPARAM:
1708 		default:
1709 			rs->sr_err = LDAP_OTHER;
1710 	}
1711 
1712 done:
1713 	return rs->sr_err;
1714 }
1715 #endif /* HAVE_CYRUS_SASL */
1716 
1717 /* Take any sort of identity string and return a DN with the "dn:" prefix. The
1718  * string returned in *dn is in its own allocated memory, and must be free'd
1719  * by the calling process.  -Mark Adamson, Carnegie Mellon
1720  *
1721  * The "dn:" prefix is no longer used anywhere inside slapd. It is only used
1722  * on strings passed in directly from SASL.  -Howard Chu, Symas Corp.
1723  */
1724 
1725 #define SET_NONE	0
1726 #define	SET_DN		1
1727 #define	SET_U		2
1728 
slap_sasl_getdn(Connection * conn,Operation * op,struct berval * id,char * user_realm,struct berval * dn,int flags)1729 int slap_sasl_getdn( Connection *conn, Operation *op, struct berval *id,
1730 	char *user_realm, struct berval *dn, int flags )
1731 {
1732 	int rc, is_dn = SET_NONE, do_norm = 1;
1733 	struct berval dn2, *mech;
1734 
1735 	assert( conn != NULL );
1736 	assert( id != NULL );
1737 
1738 	Debug( LDAP_DEBUG_ARGS, "slap_sasl_getdn: conn %lu id=%s [len=%lu]\n",
1739 		conn->c_connid,
1740 		BER_BVISNULL( id ) ? "NULL" : ( BER_BVISEMPTY( id ) ? "<empty>" : id->bv_val ),
1741 		BER_BVISNULL( id ) ? 0 : ( BER_BVISEMPTY( id ) ? 0 :
1742 		                           (unsigned long) id->bv_len ) );
1743 
1744 	if ( !op ) {
1745 		op = conn->c_sasl_bindop;
1746 	}
1747 	assert( op != NULL );
1748 
1749 	BER_BVZERO( dn );
1750 
1751 	if ( !BER_BVISNULL( id ) ) {
1752 		/* Blatantly anonymous ID */
1753 		static struct berval bv_anonymous = BER_BVC( "anonymous" );
1754 
1755 		if ( ber_bvstrcasecmp( id, &bv_anonymous ) == 0 ) {
1756 			return( LDAP_SUCCESS );
1757 		}
1758 
1759 	} else {
1760 		/* FIXME: if empty, should we stop? */
1761 		BER_BVSTR( id, "" );
1762 	}
1763 
1764 	if ( !BER_BVISEMPTY( &conn->c_sasl_bind_mech ) ) {
1765 		mech = &conn->c_sasl_bind_mech;
1766 	} else {
1767 		mech = &conn->c_authmech;
1768 	}
1769 
1770 	/* An authcID needs to be converted to authzID form. Set the
1771 	 * values directly into *dn; they will be normalized later. (and
1772 	 * normalizing always makes a new copy.) An ID from a TLS certificate
1773 	 * is already normalized, so copy it and skip normalization.
1774 	 */
1775 	if( flags & SLAP_GETDN_AUTHCID ) {
1776 		if( bvmatch( mech, &ext_bv )) {
1777 			/* EXTERNAL DNs are already normalized */
1778 			assert( !BER_BVISNULL( id ) );
1779 
1780 			do_norm = 0;
1781 			is_dn = SET_DN;
1782 			ber_dupbv_x( dn, id, op->o_tmpmemctx );
1783 
1784 		} else {
1785 			/* convert to u:<username> form */
1786 			is_dn = SET_U;
1787 			*dn = *id;
1788 		}
1789 	}
1790 
1791 	if( is_dn == SET_NONE ) {
1792 		if( !strncasecmp( id->bv_val, "u:", STRLENOF( "u:" ) ) ) {
1793 			is_dn = SET_U;
1794 			dn->bv_val = id->bv_val + STRLENOF( "u:" );
1795 			dn->bv_len = id->bv_len - STRLENOF( "u:" );
1796 
1797 		} else if ( !strncasecmp( id->bv_val, "dn:", STRLENOF( "dn:" ) ) ) {
1798 			is_dn = SET_DN;
1799 			dn->bv_val = id->bv_val + STRLENOF( "dn:" );
1800 			dn->bv_len = id->bv_len - STRLENOF( "dn:" );
1801 		}
1802 	}
1803 
1804 	/* No other possibilities from here */
1805 	if( is_dn == SET_NONE ) {
1806 		BER_BVZERO( dn );
1807 		return( LDAP_INAPPROPRIATE_AUTH );
1808 	}
1809 
1810 	/* Username strings */
1811 	if( is_dn == SET_U ) {
1812 		/* ITS#3419: values may need escape */
1813 		LDAPRDN		DN[ 5 ];
1814 		LDAPAVA 	*RDNs[ 4 ][ 2 ];
1815 		LDAPAVA 	AVAs[ 4 ];
1816 		int		irdn;
1817 
1818 		irdn = 0;
1819 		DN[ irdn ] = RDNs[ irdn ];
1820 		RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1821 		AVAs[ irdn ].la_attr = slap_schema.si_ad_uid->ad_cname;
1822 		AVAs[ irdn ].la_value = *dn;
1823 		AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1824 		AVAs[ irdn ].la_private = NULL;
1825 		RDNs[ irdn ][ 1 ] = NULL;
1826 
1827 		if ( user_realm && *user_realm ) {
1828 			irdn++;
1829 			DN[ irdn ] = RDNs[ irdn ];
1830 			RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1831 			AVAs[ irdn ].la_attr = slap_schema.si_ad_cn->ad_cname;
1832 			ber_str2bv( user_realm, 0, 0, &AVAs[ irdn ].la_value );
1833 			AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1834 			AVAs[ irdn ].la_private = NULL;
1835 			RDNs[ irdn ][ 1 ] = NULL;
1836 		}
1837 
1838 		if ( !BER_BVISNULL( mech ) ) {
1839 			irdn++;
1840 			DN[ irdn ] = RDNs[ irdn ];
1841 			RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1842 			AVAs[ irdn ].la_attr = slap_schema.si_ad_cn->ad_cname;
1843 			AVAs[ irdn ].la_value = *mech;
1844 			AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1845 			AVAs[ irdn ].la_private = NULL;
1846 			RDNs[ irdn ][ 1 ] = NULL;
1847 		}
1848 
1849 		irdn++;
1850 		DN[ irdn ] = RDNs[ irdn ];
1851 		RDNs[ irdn ][ 0 ] = &AVAs[ irdn ];
1852 		AVAs[ irdn ].la_attr = slap_schema.si_ad_cn->ad_cname;
1853 		BER_BVSTR( &AVAs[ irdn ].la_value, "auth" );
1854 		AVAs[ irdn ].la_flags = LDAP_AVA_NULL;
1855 		AVAs[ irdn ].la_private = NULL;
1856 		RDNs[ irdn ][ 1 ] = NULL;
1857 
1858 		irdn++;
1859 		DN[ irdn ] = NULL;
1860 
1861 		rc = ldap_dn2bv_x( DN, dn, LDAP_DN_FORMAT_LDAPV3,
1862 				op->o_tmpmemctx );
1863 		if ( rc != LDAP_SUCCESS ) {
1864 			BER_BVZERO( dn );
1865 			return rc;
1866 		}
1867 
1868 		Debug( LDAP_DEBUG_TRACE,
1869 			"slap_sasl_getdn: u:id converted to %s\n",
1870 			dn->bv_val, 0, 0 );
1871 
1872 	} else {
1873 
1874 		/* Dup the DN in any case, so we don't risk
1875 		 * leaks or dangling pointers later,
1876 		 * and the DN value is '\0' terminated */
1877 		ber_dupbv_x( &dn2, dn, op->o_tmpmemctx );
1878 		dn->bv_val = dn2.bv_val;
1879 	}
1880 
1881 	/* All strings are in DN form now. Normalize if needed. */
1882 	if ( do_norm ) {
1883 		rc = dnNormalize( 0, NULL, NULL, dn, &dn2, op->o_tmpmemctx );
1884 
1885 		/* User DNs were constructed above and must be freed now */
1886 		slap_sl_free( dn->bv_val, op->o_tmpmemctx );
1887 
1888 		if ( rc != LDAP_SUCCESS ) {
1889 			BER_BVZERO( dn );
1890 			return rc;
1891 		}
1892 		*dn = dn2;
1893 	}
1894 
1895 	/* Run thru regexp */
1896 	slap_sasl2dn( op, dn, &dn2, flags );
1897 	if( !BER_BVISNULL( &dn2 ) ) {
1898 		slap_sl_free( dn->bv_val, op->o_tmpmemctx );
1899 		*dn = dn2;
1900 		Debug( LDAP_DEBUG_TRACE,
1901 			"slap_sasl_getdn: dn:id converted to %s\n",
1902 			dn->bv_val, 0, 0 );
1903 	}
1904 
1905 	return( LDAP_SUCCESS );
1906 }
1907