+#ifdef LDAP_BACK_PROXY_AUTHZ
+/*
+ * ldap_back_proxy_authz_ctrl() prepends a proxyAuthz control
+ * to existing server-side controls if required; if not,
+ * the existing server-side controls are placed in *pctrls.
+ * The caller, after using the controls in client API
+ * operations, if ( *pctrls != op->o_ctrls ), should
+ * free( (*pctrls)[ 0 ] ) and free( *pctrls ).
+ * The function returns success if the control could
+ * be added if required, or if it did nothing; in the future,
+ * it might return some error if it failed.
+ *
+ * if no bind took place yet, but the connection is bound
+ * and the "proxyauthzdn" is set, then bind as "proxyauthzdn"
+ * and explicitly add proxyAuthz the control to every operation
+ * with the dn bound to the connection as control value.
+ *
+ * If no server-side controls are defined for the operation,
+ * simply add the proxyAuthz control; otherwise, if the
+ * proxyAuthz control is not already set, add it as
+ * the first one (FIXME: is controls order significant
+ * for security?).
+ */
+int
+ldap_back_proxy_authz_ctrl(
+ struct ldapconn *lc,
+ Operation *op,
+ SlapReply *rs,
+ LDAPControl ***pctrls )
+{
+ struct ldapinfo *li = (struct ldapinfo *) op->o_bd->be_private;
+ LDAPControl **ctrls = NULL;
+
+ *pctrls = NULL;
+
+ if ( ( lc->bound_dn.bv_val == NULL || lc->bound_dn.bv_len == 0 )
+ && ( op->o_conn && op->o_conn->c_dn.bv_val != NULL && op->o_conn->c_dn.bv_len != 0 )
+ && ( li->proxyauthzdn.bv_val != NULL && li->proxyauthzdn.bv_len != 0 ) ) {
+ int i = 0;
+
+ if ( !op->o_proxy_authz ) {
+ ctrls = ch_malloc( sizeof( LDAPControl * ) * (i + 2) );
+ ctrls[ 0 ] = ch_malloc( sizeof( LDAPControl ) );
+
+ ctrls[ 0 ]->ldctl_oid = LDAP_CONTROL_PROXY_AUTHZ;
+ ctrls[ 0 ]->ldctl_iscritical = 1;
+ ctrls[ 0 ]->ldctl_value.bv_len = op->o_conn->c_dn.bv_len + 3;
+ ctrls[ 0 ]->ldctl_value.bv_val = ch_malloc( ctrls[ 0 ]->ldctl_value.bv_len + 1 );
+ AC_MEMCPY( ctrls[ 0 ]->ldctl_value.bv_val, "dn:", sizeof( "dn:" ) - 1 );
+ AC_MEMCPY( ctrls[ 0 ]->ldctl_value.bv_val + sizeof( "dn:") - 1,
+ op->o_conn->c_dn.bv_val, op->o_conn->c_dn.bv_len + 1 );
+
+ if ( op->o_ctrls ) {
+ for ( i = 0; op->o_ctrls[ i ]; i++ ) {
+ ctrls[ i + 1 ] = op->o_ctrls[ i ];
+ }
+ }
+ ctrls[ i + 1 ] = NULL;
+
+ } else {
+ /*
+ * FIXME: we do not want to perform proxyAuthz
+ * on behalf of the client, because this would
+ * be performed with "proxyauthzdn" privileges.
+ *
+ * This might actually be too strict, since
+ * the "proxyauthzdn" saslAuthzTo, and each entry's
+ * saslAuthzFrom attributes may be crafted
+ * to avoid unwanted proxyAuthz to take place.
+ */
+#if 0
+ rs->sr_err = LDAP_UNWILLING_TO_PERFORM;
+ rs->sr_text = "proxyAuthz not allowed within namingContext";
+#endif
+ }
+ }
+
+ if ( ctrls == NULL ) {
+ ctrls = op->o_ctrls;
+ }
+
+ *pctrls = ctrls;
+
+ return rs->sr_err;
+}
+#endif /* LDAP_BACK_PROXY_AUTHZ */