Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -305,4 +305,10 @@ public interface LdapMessages {

@Message(level = MessageLevel.WARN, text = "Failed to register remote attribute type {1} with oid {2} from backend {0}: {3}")
void ldapRemoteAttributeTypeError(String backendName, String attributeName, String oid, @StackTrace(level = MessageLevel.DEBUG) Exception e);

@Message(level = MessageLevel.WARN, text = "Skipping malformed attributeMappings entry ''{0}''; expected a single remoteName:proxyName pair with a non-empty name on each side")
void ldapAttributeMappingSkipped(String pair);

@Message(level = MessageLevel.WARN, text = "Skipping attributeMappings entry ''{0}''; credential-bearing attributes cannot be renamed")
void ldapAttributeMappingSensitiveSkipped(String pair);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.knox.gateway.services.ldap.backend;

import org.apache.knox.gateway.i18n.messages.MessagesFactory;
import org.apache.knox.gateway.services.ldap.LdapMessages;

import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;

/**
* Bidirectional, case-insensitive mapping between a remote server's attribute names and the names
* the proxy exposes to clients. Configured per backend via {@code attributeMappings} as a
* comma-separated list of {@code remoteName:proxyName} pairs, for example
* {@code whenChanged:modifyTimestamp}. LDAP attribute names are case-insensitive, so all lookups
* ignore case.
* <p>
* The mapping is applied in three places so a renamed attribute behaves end to end:
* <ul>
* <li>when a remote entry is converted into a proxy entry, the remote name is replaced with the
* proxy name ({@link #toProxyName(String)});</li>
* <li>when a client's requested attribute list is forwarded to the remote server, the proxy name
* is replaced with the remote name ({@link #toRemoteName(String)});</li>
* <li>when a search filter referencing the proxy name is forwarded, the leaf is rewritten to the
* remote name ({@link #toRemoteName(String)}).</li>
* </ul>
*/
public final class AttributeNameMapper {

private static final LdapMessages LOG = MessagesFactory.get(LdapMessages.class);

private static final AttributeNameMapper EMPTY =
new AttributeNameMapper(new TreeMap<>(String.CASE_INSENSITIVE_ORDER));

// remote name -> proxy name (converting a remote entry into a proxy entry)
private final Map<String, String> remoteToProxy;
// proxy name -> remote name (translating requested attributes and search filters)
private final Map<String, String> proxyToRemote;

private AttributeNameMapper(Map<String, String> remoteToProxy) {
this.remoteToProxy = remoteToProxy;
final Map<String, String> inverse = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
for (Map.Entry<String, String> entry : remoteToProxy.entrySet()) {
// Last writer wins if two remote names map to the same proxy name; the reverse direction
// can only pick one, and a many-to-one rename is a misconfiguration regardless.
inverse.put(entry.getValue(), entry.getKey());
}
this.proxyToRemote = inverse;
}

/**
* Parses a comma-separated {@code remoteName:proxyName} configuration value. A null or blank
* value yields an empty mapper. A malformed pair (no colon, an empty side, or a stray second
* colon since an attribute name cannot contain one) is skipped with a warning rather than
* failing the whole backend, so one bad entry does not silently take the mapping down. A pair
* naming a credential-bearing attribute on either side is rejected: renaming one in would
* surface non-secret data under a credential name, and renaming one out would let a filter on
* the proxy name be rewritten against the remote credential attribute (a guessing oracle).
*/
public static AttributeNameMapper fromConfig(String configValue) {
if (configValue == null || configValue.trim().isEmpty()) {
return EMPTY;
}
final Map<String, String> remoteToProxy = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
for (String pair : configValue.split(",")) {
final String trimmed = pair.trim();
// A stray empty segment (e.g. a trailing comma) is benign; skip it silently.
if (trimmed.isEmpty()) {
continue;
}
final int colon = trimmed.indexOf(':');
// Require exactly one colon with a non-empty name on each side.
if (colon <= 0 || colon == trimmed.length() - 1
|| trimmed.indexOf(':', colon + 1) != -1) {
LOG.ldapAttributeMappingSkipped(trimmed);
continue;
}
final String remote = trimmed.substring(0, colon).trim();
final String proxy = trimmed.substring(colon + 1).trim();
if (remote.isEmpty() || proxy.isEmpty()) {
LOG.ldapAttributeMappingSkipped(trimmed);
continue;
}
if (isSensitive(remote) || isSensitive(proxy)) {
LOG.ldapAttributeMappingSensitiveSkipped(trimmed);
continue;
}
remoteToProxy.put(remote, proxy);
}
return remoteToProxy.isEmpty() ? EMPTY : new AttributeNameMapper(remoteToProxy);
}

private static boolean isSensitive(String name) {
return RemoteSchemaConverter.SENSITIVE_ATTRIBUTES.contains(name.toLowerCase(Locale.ROOT));
}

public boolean isEmpty() {
return remoteToProxy.isEmpty();
}

/** Returns the proxy name for a remote attribute, or {@code remoteName} itself when unmapped. */
public String toProxyName(String remoteName) {
if (remoteName == null) {
return null;
}
final String mapped = remoteToProxy.get(remoteName);
return mapped != null ? mapped : remoteName;
}

/** Returns the remote name for a proxy attribute, or {@code proxyName} itself when unmapped. */
public String toRemoteName(String proxyName) {
if (proxyName == null) {
return null;
}
final String mapped = proxyToRemote.get(proxyName);
return mapped != null ? mapped : proxyName;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,9 @@ public class LdapProxyBackend implements LdapBackend {
private String host;

private final RemoteSchemaConverter remoteSchemaConverter;
// Operator-configured remote<->proxy attribute name mapping (e.g. whenChanged<->modifyTimestamp).
// Applied when converting remote entries, forwarding requested attributes, and rewriting filters.
private final AttributeNameMapper attributeNameMapper;

// Proxy configuration
private final String proxyBaseDn; // Base DN for proxy entries (e.g., dc=proxy,dc=com)
Expand Down Expand Up @@ -209,6 +212,10 @@ public LdapProxyBackend(String name, Map<String, String> config) {
remoteUserObjectClass = config.getOrDefault("userObjectClass", "inetOrgPerson");
remoteGroupObjectClass = config.getOrDefault("groupObjectClass", "groupOfNames");

// Parse the operator-configured attribute name mapping (remoteName:proxyName pairs) before
// building the converter so it can rename attributes on remote entries and in filters.
attributeNameMapper = AttributeNameMapper.fromConfig(config.get("attributeMappings"));

remoteSchemaConverter = new RemoteSchemaConverter(proxyBaseDn,
proxyUserSearchBase,
proxyGroupSearchBase,
Expand All @@ -218,7 +225,8 @@ public LdapProxyBackend(String name, Map<String, String> config) {
remoteUserIdentifierAttribute,
remoteUserObjectClass,
remoteGroupObjectClass,
dnMappingEnabled);
dnMappingEnabled,
attributeNameMapper);

// Configure group lookup
useMemberOf = Boolean.parseBoolean(config.getOrDefault("useMemberOf", "false"));
Expand Down Expand Up @@ -796,8 +804,12 @@ public List<Entry> search(String searchBase, SearchScope searchScope, String fil
}

private String[] toRemoteAttributes(String[] attributes, boolean addMemberOf) {
// Translate the client-supplied (proxy-facing) names to their remote names first, so the
// proxy's own required remote attributes appended below are never themselves remapped. A
// mapping whose proxy name happened to collide with e.g. memberOf would otherwise rewrite
// the attribute the proxy adds for its own use and break group resolution.
final Set<String> remote = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
remote.addAll(Arrays.asList(attributes));
remote.addAll(Arrays.asList(mapRequestedAttributesToRemote(attributes)));

// The LDAP proxy treats memberOf as a user attribute. MemberOf is an operational attribute on some LDAP servers.
// Explicitly add memberOf to the attribute list for remote searches if it is a requested attribute.
Expand All @@ -814,6 +826,27 @@ private String[] toRemoteAttributes(String[] attributes, boolean addMemberOf) {
return remote.toArray(new String[0]);
}

/**
* Translates operator-mapped proxy attribute names in a requested-attribute list to the remote
* server's names, so the remote search asks for the name the server actually knows (e.g. a
* client request for {@code modifyTimestamp} is forwarded as {@code whenChanged}). Unmapped
* names (including {@code "*"}) pass through unchanged, and the array is only copied when a
* mapping is actually configured.
*
* @param attributes the requested attributes, in proxy-facing names
* @return the attributes translated to remote names
*/
String[] mapRequestedAttributesToRemote(String[] attributes) {
if (attributes == null || attributeNameMapper.isEmpty()) {
return attributes;
}
final String[] remoteAttributes = new String[attributes.length];
for (int i = 0; i < attributes.length; i++) {
remoteAttributes[i] = attributeNameMapper.toRemoteName(attributes[i]);
}
return remoteAttributes;
}

/**
* Returns true if the requested attributes include the given attribute or "*". Requested
* attributes may be names or OIDs, so they are compared by attribute type OID via the schema.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ public class RemoteSchemaConverter {
private final String remoteUserObjectClass;
private final String remoteGroupObjectClass;
private final boolean dnMappingEnabled;
// Operator-configured remote<->proxy attribute name mapping (e.g. whenChanged<->modifyTimestamp).
private final AttributeNameMapper attributeNameMapper;

public RemoteSchemaConverter(String proxyBaseDn,
String proxyUserSearchBase,
Expand All @@ -64,6 +66,22 @@ public RemoteSchemaConverter(String proxyBaseDn,
String remoteUserObjectClass,
String remoteGroupObjectClass,
boolean dnMappingEnabled) {
this(proxyBaseDn, proxyUserSearchBase, proxyGroupSearchBase, remoteBaseDn, remoteUserSearchBase,
remoteGroupSearchBase, remoteUserIdentifierAttribute, remoteUserObjectClass,
remoteGroupObjectClass, dnMappingEnabled, AttributeNameMapper.fromConfig(null));
}

public RemoteSchemaConverter(String proxyBaseDn,
String proxyUserSearchBase,
String proxyGroupSearchBase,
String remoteBaseDn,
String remoteUserSearchBase,
String remoteGroupSearchBase,
String remoteUserIdentifierAttribute,
String remoteUserObjectClass,
String remoteGroupObjectClass,
boolean dnMappingEnabled,
AttributeNameMapper attributeNameMapper) {
this.proxyBaseDn = proxyBaseDn;
this.proxyUserSearchBase = proxyUserSearchBase;
this.proxyGroupSearchBase = proxyGroupSearchBase;
Expand All @@ -74,6 +92,7 @@ public RemoteSchemaConverter(String proxyBaseDn,
this.remoteUserObjectClass = remoteUserObjectClass;
this.remoteGroupObjectClass = remoteGroupObjectClass;
this.dnMappingEnabled = dnMappingEnabled;
this.attributeNameMapper = attributeNameMapper;
}

/**
Expand Down Expand Up @@ -102,10 +121,13 @@ public Entry convertRemoteEntryToProxyEntry(Entry sourceEntry, SchemaManager sch
// OID rather than its name for schema-aware attributes, so the name must come from
// getUpId() (the attribute name as originally supplied) for the name-based checks below.
for (Attribute attribute : sourceEntry.getAttributes()) {
if (SENSITIVE_ATTRIBUTES.contains(attribute.getUpId().toLowerCase(Locale.ROOT))) {
final String remoteName = attribute.getUpId();
if (SENSITIVE_ATTRIBUTES.contains(remoteName.toLowerCase(Locale.ROOT))) {
continue;
}
copyAttribute(sourceEntry, entry, attribute.getUpId(), schemaManager);
// Rename the attribute to its proxy-facing name if one is configured (e.g. the remote
// whenChanged is surfaced as the standard modifyTimestamp); otherwise the name is kept.
copyAttribute(sourceEntry, entry, remoteName, attributeNameMapper.toProxyName(remoteName), schemaManager);
}

// Map user entry identifier attribute to uid for consistency if needed
Expand Down Expand Up @@ -142,7 +164,7 @@ public Entry convertRemoteEntryToProxyEntry(Entry sourceEntry, SchemaManager sch
* @throws LdapException if the filter cannot be converted
*/
public ExprNode convertProxyFilterToRemoteFilter(ExprNode filter, SchemaManager schemaManager) throws LdapException {
RemoteSchemaMappingVisitor remoteSchemaMappingVisitor = new RemoteSchemaMappingVisitor(remoteUserIdentifierAttribute, remoteUserObjectClass, remoteGroupObjectClass, schemaManager, this::convertProxyDnToRemoteDn);
RemoteSchemaMappingVisitor remoteSchemaMappingVisitor = new RemoteSchemaMappingVisitor(remoteUserIdentifierAttribute, remoteUserObjectClass, remoteGroupObjectClass, schemaManager, this::convertProxyDnToRemoteDn, attributeNameMapper);

Object result = filter.accept(remoteSchemaMappingVisitor);
if (result instanceof ExprNode) {
Expand All @@ -160,23 +182,41 @@ public ExprNode convertProxyFilterToRemoteFilter(ExprNode filter, SchemaManager
* @param schemaManager the schema manager
*/
public void copyAttribute(Entry source, Entry target, String attributeName, SchemaManager schemaManager) {
final Attribute attribute = source.get(attributeName);
copyAttribute(source, target, attributeName, attributeName, schemaManager);
}

/**
* Copy a remote attribute into the proxy entry under a (possibly different) target name. When
* {@code sourceName} and {@code targetName} differ the attribute is renamed (e.g. the remote
* {@code whenChanged} surfaced as the standard {@code modifyTimestamp}); the values are copied
* unchanged, which is safe because a renamed attribute is only configured when the two share a
* compatible value syntax. The DN-valued check uses the target name so the value conversion
* matches the schema the proxy entry is built against.
*
* @param source The remote entry
* @param target The proxy entry
* @param sourceName The attribute name on the remote entry
* @param targetName The attribute name to write on the proxy entry
* @param schemaManager the schema manager
*/
public void copyAttribute(Entry source, Entry target, String sourceName, String targetName, SchemaManager schemaManager) {
final Attribute attribute = source.get(sourceName);
if (attribute != null) {
// Only rewrite DNs for DN-valued attributes; other values (e.g. mail, description)
// are copied verbatim so they are not corrupted if they happen to contain a base DN.
final boolean convertDn = dnMappingEnabled && LdapUtils.isDnValued(attributeName, schemaManager);
final boolean convertDn = dnMappingEnabled && LdapUtils.isDnValued(targetName, schemaManager);

// Copy all values of the attribute (important for multi-valued attributes like objectClass)
for (Value value : attribute) {
try {
if (!value.isHumanReadable()) {
if (!target.contains(attributeName, value.getBytes())) {
target.add(attributeName, value.getBytes());
if (!target.contains(targetName, value.getBytes())) {
target.add(targetName, value.getBytes());
}
} else {
String valueString = convertDn ? convertRemoteDnToProxyDn(value.getString()) : value.getString();
if (!target.contains(attributeName, valueString)) {
target.add(attributeName, valueString);
if (!target.contains(targetName, valueString)) {
target.add(targetName, valueString);
}
}
} catch (LdapException e) {
Expand Down
Loading
Loading