diff --git a/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md b/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md index c0ea9c3a792..42b6625aa5d 100644 --- a/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md +++ b/zookeeper-docs/src/main/resources/markdown/zookeeperAdmin.md @@ -1578,6 +1578,70 @@ and [SASL authentication for ZooKeeper](https://cwiki.apache.org/confluence/disp Then set this property **zookeeper.ssl.authProvider=[scheme]** and that provider will be used for secure authentication. +##### LinkedIn X509 znode-group ACL support + +The optional group provider maps an authenticated certificate identity to domains +stored under `/zookeeper/uri-domain-map//`. Each client ID is +one znode name; lookup is exact, and a client can belong to multiple domains. +The server does **not** create this mapping root. An absent root is supported: +clients initially receive their certificate identity, and a persistent recursive +watch updates connected clients when operators create, change or remove mappings. +Updates cover both secure and unified-port TLS connections. + +Configure the provider in `zoo.cfg`: + +``` +authProvider.x509=org.apache.zookeeper.server.auth.znode.groupacl.X509ZNodeGroupAclProvider +ssl.x509.clientCertIdType=SAN +ssl.x509.clientCertIdSanMatchType=6 +ssl.x509.clientCertIdSanMatchRegex=^urn:example: +``` + +Use the usual TLS key/trust store settings and leave `ssl.authProvider` unset; +that separate setting selects an X509 provider supplying custom TLS managers. +The group provider uses the configured stores, including password-file settings, +and does not change hostname verification, reverse DNS or FIPS policy. + +The following names are `zoo.cfg` keys; Java system properties add `zookeeper.`. +SAN selection also works with the ordinary X509 provider. + +| Key | Default / meaning | +| --- | --- | +| `ssl.x509.clientCertIdType` | Subject DN; `SAN` selects a subject alternative name. | +| `ssl.x509.clientCertIdSanMatchType` | Unset; SAN type 0–8, for example 6 for URI. | +| `ssl.x509.clientCertIdSanMatchRegex` | `.*`; must select exactly one SAN of the configured type. | +| `ssl.x509.clientCertIdSanExtractRegex` | `.*`; extracts from that SAN using a regex match. | +| `ssl.x509.clientCertIdSanExtractMatcherGroupIndex` | `0`; regex capture group to use as the identity. | +| `X509ZNodeGroupAclProvider.setX509ClientIdAsAcl` | `false`; replace supplied ACLs with authenticated domain/client IDs, each with ALL permissions. | +| `X509ZNodeGroupAclProvider.allowedClientIdAsAclDomains` | Empty; comma-separated IDs to use for automatic ACLs when the global switch is off. | +| `X509ZNodeGroupAclProvider.superUserId` | Empty; comma-separated certificate identities with unrestricted access and permission to choose ACLs. | +| `X509ZNodeGroupAclProvider.crossDomainAccessDomainName` | Empty; comma-separated domains with cross-domain access. Automatic ACLs for their writes use `x509:`. | +| `X509ZNodeGroupAclProvider.openReadAccessPathPrefix` | Empty; comma-separated literal path prefixes receiving `world:anyone` READ permission during enabled group ACL processing, even when supplied ownership ACLs are retained. | +| `X509ZNodeGroupAclProvider.storeAuthedClientId` | `false`; retain the certificate ID alongside mapped domains on non-dedicated servers. | +| `X509ZNodeGroupAclProvider.dedicatedDomain` | Unset; restrict TLS connections to one domain instead of applying automatic group ACLs. | +| `X509ZNodeGroupAclProvider.enforceDedicatedDomain` | `true`; when false, log a domain mismatch without disconnecting it. | + +Unsuccessful SAN selection falls back to Subject DN. Unknown but trusted clients +receive `x509:` rather than a mapped domain. Explicit creator ACLs expand +the authenticated identities normally; no SPIFFE or legacy-identity translation +is performed. Automatic ACL replacement applies to both create and setACL, not +just creation. On non-dedicated servers using the group provider, configured +open-read prefixes add READ permission when the global automatic-ACL switch is +enabled or authenticated X509 IDs match the automatic-ACL allowlist. This also +applies when a writer keeps supplied ownership ACLs: explicit X509 superusers and +non-X509 clients still undergo ordinary ACL validation, with the configured READ +permission added. Dedicated-domain mode, inactive group ACL processing and +nonmatching prefixes do not add this permission. Cross-domain users and explicit +superusers are exempt from dedicated-domain connection filtering. + +Treat mapping writes as privilege changes: bootstrap the root deliberately and +protect its subtree's ACLs against unauthorized create/delete operations. The +feature does not secure plaintext listeners or make existing znodes private. +READ/watch checks and existing ACLs remain enforced. Configure the same policy +on every server before startup; configuration is cached, whereas mapping znodes +are watched dynamically. Enabling automatic ACLs or dedicated-domain enforcement +is an intentional access-policy change and should be qualified before rollout. + * *zookeeper.ensembleAuthName* : (Java system property only: **zookeeper.ensembleAuthName**) **New in 3.6.0:** diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/NettyServerCnxnFactory.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/NettyServerCnxnFactory.java index 914a18d92dd..9e96ea3185b 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/NettyServerCnxnFactory.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/NettyServerCnxnFactory.java @@ -72,6 +72,7 @@ import org.apache.zookeeper.common.X509Exception.SSLContextException; import org.apache.zookeeper.server.NettyServerCnxn.HandshakeState; import org.apache.zookeeper.server.auth.ProviderRegistry; +import org.apache.zookeeper.server.auth.ServerAuthenticationProvider; import org.apache.zookeeper.server.auth.X509AuthenticationProvider; import org.apache.zookeeper.server.quorum.QuorumPeerConfig; import org.slf4j.Logger; @@ -445,7 +446,10 @@ public void operationComplete(Future future) { String authProviderProp = System.getProperty(x509Util.getSslAuthProviderProperty(), "x509"); - X509AuthenticationProvider authProvider = (X509AuthenticationProvider) ProviderRegistry.getProvider(authProviderProp); + // All implementations of the AuthenticationProvider interface should be supported here. Currently + // any custom implementation of X509AuthenticationProvider or ServerAuthenticationProvider is + // supported with backward compatability. + ServerAuthenticationProvider authProvider = ProviderRegistry.getServerProvider(authProviderProp); if (authProvider == null) { LOG.error("X509 Auth provider not found: {}", authProviderProp); @@ -453,7 +457,8 @@ public void operationComplete(Future future) { return; } - KeeperException.Code code = authProvider.handleAuthentication(cnxn, null); + KeeperException.Code code = authProvider.handleAuthentication( + new ServerAuthenticationProvider.ServerObjs(zkServer, cnxn), null); if (KeeperException.Code.OK != code) { zkServer.serverStats().incrementAuthFailedCount(); LOG.error("Authentication failed for session 0x{}", Long.toHexString(cnxn.getSessionId())); diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/PrepRequestProcessor.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/PrepRequestProcessor.java index 28ea11a695f..b7e90e930b1 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/PrepRequestProcessor.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/PrepRequestProcessor.java @@ -26,6 +26,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; @@ -33,6 +34,7 @@ import java.util.Properties; import java.util.Set; import java.util.concurrent.LinkedBlockingQueue; +import java.util.stream.Collectors; import org.apache.jute.BinaryOutputArchive; import org.apache.jute.Record; import org.apache.zookeeper.CreateMode; @@ -60,6 +62,8 @@ import org.apache.zookeeper.server.ZooKeeperServer.PrecalculatedDigest; import org.apache.zookeeper.server.auth.ProviderRegistry; import org.apache.zookeeper.server.auth.ServerAuthenticationProvider; +import org.apache.zookeeper.server.auth.X509AuthenticationConfig; +import org.apache.zookeeper.server.auth.X509AuthenticationUtil; import org.apache.zookeeper.server.quorum.LeaderZooKeeperServer; import org.apache.zookeeper.server.quorum.QuorumPeer.QuorumServer; import org.apache.zookeeper.server.quorum.QuorumPeerConfig; @@ -1024,6 +1028,64 @@ public static List fixupACL(String path, List authInfo, List acls) throw new KeeperException.InvalidACLException(path); } List rv = new ArrayList<>(); + + // Overwrite the acl list for users (except super user) when the auth provider is + // X509ZnodeGroupAclProvider, and isX509ClientIdAsAclEnabled is true. Note that + // clientIdAsAcl can be partially enabled for specific domains by adding them to + // the allowedClientIdAsAclDomains list. + // + // Set x509 ZNode ACL as the client's corresponding domain name. This domain name denotes a + // ZNode group the client belongs to and can be derived from the client URI-domain mapping + // (UriDomainMappingHelper). + // Cases where such grouping by override applies are: + // Single domain user / cross domain components -> set (x509 : domainName) as znode ACL + // Users whose extracted clientId is not found in the ClientURIDomainMapping + // -> set (x509: clientURI) as znode ACL + // Examples that will not be handled by the "following logic" are: + // x509 super user, plaintext port clients, any user when dedicated server is enabled + // -> will go through original zk fixupACL logic + Set enabledX509ClientIdAsACL = authInfo.stream() + .filter(id -> X509AuthenticationUtil.X509_SCHEME.equals(id.getScheme())) + .map(Id::getId) + .collect(Collectors.toCollection(HashSet::new)); + if (!X509AuthenticationConfig.getInstance().isX509ClientIdAsAclEnabled()) { + // If clientIdAsAclEnabled is true, all the X509 auth entries should be added to the ACL. If it's not enabled, + // only preserve the ones that are present in allowedClientIdAsAclDomains. If the intersection is empty, + // overwriting the ACL will be disabled. + enabledX509ClientIdAsACL + .removeIf(id -> !X509AuthenticationConfig.getInstance().getAllowedClientIdAsAclDomains().contains(id)); + } + + if ((!enabledX509ClientIdAsACL.isEmpty() || X509AuthenticationConfig.getInstance().isX509ClientIdAsAclEnabled()) + && X509AuthenticationConfig.getInstance().isX509ZnodeGroupAclEnabled() + && !X509AuthenticationConfig.getInstance().isZnodeGroupAclDedicatedServerEnabled()) { + boolean isUserProvidedAclOverriden = false; + for (Id id : authInfo) { + boolean isX509 = enabledX509ClientIdAsACL.contains(id.getId()); + boolean isX509CrossDomainComponent = + id.getScheme().equals(X509AuthenticationUtil.SUPERUSER_AUTH_SCHEME) + && !X509AuthenticationConfig.getInstance().getZnodeGroupAclSuperUserIds() + .contains(id.getId()); + if (isX509 || isX509CrossDomainComponent) { + rv.add(new ACL(ZooDefs.Perms.ALL, + new Id(X509AuthenticationUtil.X509_SCHEME, id.getId()))); + isUserProvidedAclOverriden = true; + } + } + // If the znode path contains open read access node path prefix, add (world:anyone, r) + if (X509AuthenticationConfig.getInstance().getZnodeGroupAclOpenReadAccessPathPrefixes() + .stream().anyMatch(path::startsWith)) { + rv.add(new ACL(ZooDefs.Perms.READ, ZooDefs.Ids.ANYONE_ID_UNSAFE)); + } + if (isUserProvidedAclOverriden) { + // Only for users who are handled by the above logic, return the result, + // for others should continue to original fixupACL logic. This variable is necessary + // because if path is open read path, its open read ACL will be added to the list, + // regardless of user category, so rv's size won't be a good indicator here. + return rv; + } + } + for (ACL a : uniqacls) { LOG.debug("Processing ACL: {}", a); if (a == null) { diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/ServerCnxn.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/ServerCnxn.java index 7282c17150e..5b927f33993 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/ServerCnxn.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/ServerCnxn.java @@ -106,7 +106,8 @@ public enum DisconnectReason { AUTH_PROVIDER_NOT_FOUND("auth provider not found"), FAILED_HANDSHAKE("Unsuccessful handshake"), CLIENT_RATE_LIMIT("Client hits rate limiting threshold"), - CLIENT_CNX_LIMIT("Client hits connection limiting threshold"); + CLIENT_CNX_LIMIT("Client hits connection limiting threshold"), + SSL_AUTH_FAILURE("ssl_auth_failure"); String disconnectReason; diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/X509AuthenticationConfig.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/X509AuthenticationConfig.java new file mode 100644 index 00000000000..1499b256106 --- /dev/null +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/X509AuthenticationConfig.java @@ -0,0 +1,484 @@ +/* + * 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.zookeeper.server.auth; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.collect.ImmutableSet; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Arrays; +import java.util.Collections; +import java.util.Set; +import java.util.stream.Collectors; +import org.apache.zookeeper.server.auth.znode.groupacl.X509ZNodeGroupAclProvider; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * This class contains config properties for x509-based authentication + */ +public class X509AuthenticationConfig { + private static final Logger LOG = LoggerFactory.getLogger(X509AuthenticationConfig.class); + private static X509AuthenticationConfig instance = null; + private static final String LOG_MSG_PREFIX = X509AuthenticationConfig.class.getName() + "::"; + + private X509AuthenticationConfig() { + } + + /** + * X509AuthenticationConfig are loaded lazily and hence spotbugs DC_DOUBLECHECK warning is supressed. + * @return + */ + @SuppressFBWarnings("DC_DOUBLECHECK") + public static X509AuthenticationConfig getInstance() { + if (instance == null) { + synchronized (X509AuthenticationConfig.class) { + if (instance == null) { + instance = new X509AuthenticationConfig(); + } + } + } + return instance; + } + + // The following System Property keys are used to extract clientId from the client cert. + + /** + * Config prefix for x509-related config properties. + * The property keys start with this prefix apply to both {@link org.apache.zookeeper.server.auth.X509AuthenticationProvider} + * and {@link org.apache.zookeeper.server.auth.znode.groupacl.X509ZNodeGroupAclProvider} + */ + public static final String SSL_X509_CONFIG_PREFIX = "zookeeper.ssl.x509."; + /** + * Determines which field in the x509 certificate to be used for client Id: + * SAN (subject alternative name) or SDN (subject domain name) (default) + */ + public static final String SSL_X509_CLIENT_CERT_ID_TYPE = + SSL_X509_CONFIG_PREFIX + "clientCertIdType"; + /** The field in SAN to be used for client URI extraction */ + public static final String SSL_X509_CLIENT_CERT_ID_SAN_MATCH_TYPE = + SSL_X509_CONFIG_PREFIX + "clientCertIdSanMatchType"; + /** Match Regex is used to choose which entry to use, default value ".*" */ + public static final String SSL_X509_CLIENT_CERT_ID_SAN_MATCH_REGEX = + SSL_X509_CONFIG_PREFIX + "clientCertIdSanMatchRegex"; + /** Extract Regex is used to construct a client ID (acl entity) to return, default value ".*" */ + public static final String SSL_X509_CLIENT_CERT_ID_SAN_EXTRACT_REGEX = + SSL_X509_CONFIG_PREFIX + "clientCertIdSanExtractRegex"; + /** Specifies match group index for the extract regex (i in Matcher.group(i)), default value 0 */ + public static final String SSL_X509_CLIENT_CERT_ID_SAN_EXTRACT_MATCHER_GROUP_INDEX = + SSL_X509_CONFIG_PREFIX + "clientCertIdSanExtractMatcherGroupIndex"; + public static final String SUBJECT_ALTERNATIVE_NAME_SHORT = "SAN"; + private static final String DEFAULT_REGEX = ".*"; + private String clientCertIdType; + private int clientCertIdSanMatchType = -1; + private String clientCertIdSanMatchRegex; + private String clientCertIdSanExtractRegex; + private int clientCertIdSanExtractMatcherGroupIndex = -1; + + // ZooKeeper server-side config properties for ZNode group ACL feature + + /** + * Config prefix for znode group acl-related config properties + */ + public static final String ZNODE_GROUP_ACL_CONFIG_PREFIX = "zookeeper.X509ZNodeGroupAclProvider."; + + /** + * Enables/disables whether znodes created by auth'ed clients. + * Should be enabled if znode group acl feature is desired; otherwise, it should be disabled. + * When this property is enabled: + * 1. Should have ACL fields populated with the client Id given by the authentication provider. + * 2. Users do not have the right to manually operate on znode ACLs + * 3. {@value ZOOKEEPER_ZNODEGROUPACL_SUPERUSER_ID} has the ability to operate on znode ACLs + * Has the same effect as the ZK client using ZooDefs.Ids.CREATOR_ALL_ACL. + */ + public static final String SET_X509_CLIENT_ID_AS_ACL = + ZNODE_GROUP_ACL_CONFIG_PREFIX + "setX509ClientIdAsAcl"; + /** + * A list of domain names that will have cross-domain access privilege, separated by "," + */ + public static final String CROSS_DOMAIN_ACCESS_DOMAIN_NAME = + ZNODE_GROUP_ACL_CONFIG_PREFIX + "crossDomainAccessDomainName"; + /** + * A user-defined URI represents a super user, same concept as the original x509 superuser. + * Super user can operate on the znode to set ACLs. + */ + public static final String ZOOKEEPER_ZNODEGROUPACL_SUPERUSER_ID = + ZNODE_GROUP_ACL_CONFIG_PREFIX + "superUserId"; + /** + * A list of znode path prefixes, separated by ",". + * Znode whose path starts with the defined path prefix would have open read access. + * Meaning the znode will have (world:anyone, r) ACL. + */ + public static final String OPEN_READ_ACCESS_PATH_PREFIX = + ZNODE_GROUP_ACL_CONFIG_PREFIX + "openReadAccessPathPrefix"; + /** + * If the server is dedicated for one domain, use this config property to define the domain name, + * and enable connection filtering feature for this domain. + */ + public static final String DEDICATED_DOMAIN = ZNODE_GROUP_ACL_CONFIG_PREFIX + "dedicatedDomain"; + /** + * This config property applies only to dedicated server. When true (default), domain specific connection filtering is + * enabled and enforced. When false, the server simply logs a warning message but doesn't actually filter/disconnect + * the connection if it does not belong to dedicated domain. + */ + public static final String ENFORCE_DEDICATED_DOMAIN = ZNODE_GROUP_ACL_CONFIG_PREFIX + "enforceDedicatedDomain"; + /** + * This config property applies to non-dedicated server. If this property is set to true, + * clientId extracted from the certificate will be stored in authInfo, along with the matched + * domain name. + */ + public static final String STORE_AUTHED_CLIENT_ID = ZNODE_GROUP_ACL_CONFIG_PREFIX + "storeAuthedClientId"; + /** + * A list of domain names that can set node ACLs as their own client ID. + */ + public static final String ALLOWED_CLIENT_ID_AS_ACL_DOMAINS = + ZNODE_GROUP_ACL_CONFIG_PREFIX + "allowedClientIdAsAclDomains"; + + // The root path for client URI - domain mapping that stored in zk data tree. Refer to + // {@link org.apache.zookeeper.server.auth.znode.groupacl.ZkClientUriDomainMappingHelper} for + // details about client URI - domain mapping. Operators create this path; server startup does not. + private static final String ZNODE_GROUP_ACL_CLIENTURI_DOMAIN_MAPPING_ROOT_PATH = "/zookeeper/uri-domain-map"; + + private String x509ClientIdAsAclEnabled; + private String znodeGroupAclSuperUserIdStr; + private String znodeGroupAclCrossDomainAccessDomainNameStr; + private String znodeGroupAclOpenReadAccessPathPrefixStr; + private String znodeGroupAclServerDedicatedDomain; + private String znodeGroupAclServerShouldEnforceDedicatedDomain; + private String storeAuthedClientIdEnabled; + private String allowedClientIdAsAclDomainsStr; + + // Although using "volatile" keyword with double checked locking could prevent the undesired + //creation of multiple objects; not using here for the consideration of read performance + private Set openReadAccessPathPrefixes; + private Set crossDomainAccessDomains; + private Set znodeGroupAclSuperUserIds; + private volatile Set allowedClientIdAsAclDomains; + private final Object openReadAccessPathPrefixesLock = new Object(); + private final Object crossDomainAccessDomainsLock = new Object(); + private final Object znodeGroupAclSuperUserIdsLock = new Object(); + private final Object allowedClientIdAsAclDomainsLock = new Object(); + + // Setters for X509 properties + + public void setClientCertIdType(String clientCertIdType) { + LOG.debug("{} = {}", SSL_X509_CLIENT_CERT_ID_TYPE, clientCertIdType); + this.clientCertIdType = clientCertIdType; + } + + public void setClientCertIdSanMatchType(String clientCertIdSanMatchType) { + LOG.debug("{} = {}", SSL_X509_CLIENT_CERT_ID_SAN_MATCH_TYPE, clientCertIdSanMatchType); + if (clientCertIdSanMatchType == null) { + return; + } + try { + this.clientCertIdSanMatchType = Integer.parseInt(clientCertIdSanMatchType); + } catch (NumberFormatException e) { + String errMsg = + LOG_MSG_PREFIX + "Could not parse number for clientCertIdSanMatchType, provided value: " + + clientCertIdSanMatchType; + LOG.error(errMsg); + throw new IllegalArgumentException(errMsg); + } + } + + public void setClientCertIdSanMatchRegex(String clientCertIdSanMatchRegex) { + LOG.debug("{} = {}", SSL_X509_CLIENT_CERT_ID_SAN_MATCH_REGEX, clientCertIdSanMatchRegex); + this.clientCertIdSanMatchRegex = clientCertIdSanMatchRegex; + } + + public void setClientCertIdSanExtractRegex(String clientCertIdSanExtractRegex) { + LOG.debug("{} = {}", SSL_X509_CLIENT_CERT_ID_SAN_EXTRACT_REGEX, clientCertIdSanExtractRegex); + this.clientCertIdSanExtractRegex = clientCertIdSanExtractRegex; + } + + public void setClientCertIdSanExtractMatcherGroupIndex( + String clientCertIdSanExtractMatcherGroupIndex) { + LOG.debug("{} = {}", SSL_X509_CLIENT_CERT_ID_SAN_EXTRACT_MATCHER_GROUP_INDEX, clientCertIdSanExtractMatcherGroupIndex); + if (clientCertIdSanExtractMatcherGroupIndex == null) { + return; + } + try { + this.clientCertIdSanExtractMatcherGroupIndex = + Integer.parseInt(clientCertIdSanExtractMatcherGroupIndex); + } catch (NumberFormatException e) { + String errMsg = LOG_MSG_PREFIX + + "Could not parse number for clientCertIdSanExtractMatcherGroupIndex, provided value: " + + clientCertIdSanExtractMatcherGroupIndex; + LOG.error(errMsg); + throw new IllegalArgumentException(errMsg); + } + } + + // Setters for X509 Znode Group Acl properties + + public void setX509ClientIdAsAclEnabled(String enabled) { + LOG.debug("{} = {}", SET_X509_CLIENT_ID_AS_ACL, enabled); + x509ClientIdAsAclEnabled = enabled; + } + + public void setZnodeGroupAclSuperUserIdStr(String znodeGroupAclSuperUserIdStr) { + LOG.debug("{} = {}", ZOOKEEPER_ZNODEGROUPACL_SUPERUSER_ID, znodeGroupAclSuperUserIdStr); + this.znodeGroupAclSuperUserIdStr = znodeGroupAclSuperUserIdStr; + } + + public void setZnodeGroupAclCrossDomainAccessDomainNameStr( + String znodeGroupAclCrossDomainAccessDomainNameStr) { + LOG.debug("{} = {}", CROSS_DOMAIN_ACCESS_DOMAIN_NAME, znodeGroupAclCrossDomainAccessDomainNameStr); + this.znodeGroupAclCrossDomainAccessDomainNameStr = znodeGroupAclCrossDomainAccessDomainNameStr; + } + + public void setZnodeGroupAclOpenReadAccessPathPrefixStr( + String znodeGroupAclOpenReadAccessPathPrefixStr) { + LOG.debug("{} = {}", OPEN_READ_ACCESS_PATH_PREFIX, znodeGroupAclOpenReadAccessPathPrefixStr); + this.znodeGroupAclOpenReadAccessPathPrefixStr = znodeGroupAclOpenReadAccessPathPrefixStr; + } + + public void setAllowedClientIdAsAclDomainsStr(String allowedClientIdAsAclDomainsStr) { + this.allowedClientIdAsAclDomainsStr = allowedClientIdAsAclDomainsStr; + } + + public void setZnodeGroupAclServerDedicatedDomain(String znodeGroupAclServerDedicatedDomain) { + LOG.info("{} = {}", DEDICATED_DOMAIN, znodeGroupAclServerDedicatedDomain); + this.znodeGroupAclServerDedicatedDomain = znodeGroupAclServerDedicatedDomain; + } + + public void setZnodeGroupAclServerShouldEnforceDedicatedDomain(String znodeGroupAclServerShouldEnforceDedicatedDomain) { + LOG.info("{} = {}", ENFORCE_DEDICATED_DOMAIN, znodeGroupAclServerShouldEnforceDedicatedDomain); + this.znodeGroupAclServerShouldEnforceDedicatedDomain = znodeGroupAclServerShouldEnforceDedicatedDomain; + } + + public void setStoreAuthedClientIdEnabled(String enabled) { + LOG.debug("{} = {}", STORE_AUTHED_CLIENT_ID, enabled); + storeAuthedClientIdEnabled = enabled; + } + + // Getters for X509 properties + + public String getClientCertIdType() { + if (clientCertIdType == null) { + setClientCertIdType(System.getProperty(SSL_X509_CLIENT_CERT_ID_TYPE)); + } + return clientCertIdType; + } + + public int getClientCertIdSanMatchType() { + if (clientCertIdSanMatchType == -1) { + setClientCertIdSanMatchType(System.getProperty(SSL_X509_CLIENT_CERT_ID_SAN_MATCH_TYPE)); + } + return clientCertIdSanMatchType; + } + + public String getClientCertIdSanMatchRegex() { + if (clientCertIdSanMatchRegex == null) { + setClientCertIdSanMatchRegex(System.getProperty(SSL_X509_CLIENT_CERT_ID_SAN_MATCH_REGEX)); + } + return clientCertIdSanMatchRegex == null ? DEFAULT_REGEX : clientCertIdSanMatchRegex; + } + + public String getClientCertIdSanExtractRegex() { + if (clientCertIdSanExtractRegex == null) { + setClientCertIdSanExtractRegex(System.getProperty(SSL_X509_CLIENT_CERT_ID_SAN_EXTRACT_REGEX)); + } + return clientCertIdSanExtractRegex == null ? DEFAULT_REGEX : clientCertIdSanExtractRegex; + } + + public int getClientCertIdSanExtractMatcherGroupIndex() { + if (clientCertIdSanExtractMatcherGroupIndex == -1) { + setClientCertIdSanExtractMatcherGroupIndex( + System.getProperty(SSL_X509_CLIENT_CERT_ID_SAN_EXTRACT_MATCHER_GROUP_INDEX)); + } + return clientCertIdSanExtractMatcherGroupIndex == -1 ? 0 + : clientCertIdSanExtractMatcherGroupIndex; + } + + // Getters for X509 Znode Group Acl properties + + public boolean isX509ClientIdAsAclEnabled() { + return Boolean.parseBoolean(x509ClientIdAsAclEnabled) || Boolean + .parseBoolean(System.getProperty(SET_X509_CLIENT_ID_AS_ACL)); + } + + @SuppressFBWarnings("DC_DOUBLECHECK") + public Set getZnodeGroupAclSuperUserIds() { + if (znodeGroupAclSuperUserIds == null) { + synchronized (znodeGroupAclSuperUserIdsLock) { + if (znodeGroupAclSuperUserIds == null) { + znodeGroupAclSuperUserIds = loadSuperUserIds(); + } + } + } + return znodeGroupAclSuperUserIds; + } + + /** + * crossDomainAccessDomains are loaded lazily and hence spotbugs DC_DOUBLECHECK warning is supressed. + * @return + */ + @SuppressFBWarnings("DC_DOUBLECHECK") + public Set getZnodeGroupAclCrossDomainAccessDomains() { + if (crossDomainAccessDomains == null) { + synchronized (crossDomainAccessDomainsLock) { + if (crossDomainAccessDomains == null) { + crossDomainAccessDomains = loadCrossDomainAccessDomainNames(); + } + } + } + return crossDomainAccessDomains; + } + + /** + * openReadAccessPathPrefixes are loaded lazily and hence spotbugs DC_DOUBLECHECK warning is supressed. + * @return + */ + @SuppressFBWarnings("DC_DOUBLECHECK") + public Set getZnodeGroupAclOpenReadAccessPathPrefixes() { + if (openReadAccessPathPrefixes == null) { + synchronized (openReadAccessPathPrefixesLock) { + if (openReadAccessPathPrefixes == null) { + openReadAccessPathPrefixes = loadOpenReadAccessPathPrefixes(); + } + } + } + return openReadAccessPathPrefixes; + } + + public Set getAllowedClientIdAsAclDomains() { + if (allowedClientIdAsAclDomains == null) { + synchronized (allowedClientIdAsAclDomainsLock) { + if (allowedClientIdAsAclDomains == null) { + allowedClientIdAsAclDomains = loadAllowedClientIdAsAclDomains(); + } + } + } + return allowedClientIdAsAclDomains; + } + + public String getZnodeGroupAclServerDedicatedDomain() { + if (znodeGroupAclServerDedicatedDomain == null) { + setZnodeGroupAclServerDedicatedDomain(System.getProperty(DEDICATED_DOMAIN)); + } + return znodeGroupAclServerDedicatedDomain; + } + + public boolean isEnforceDedicatedDomainEnabled() { + if (znodeGroupAclServerShouldEnforceDedicatedDomain == null) { + setZnodeGroupAclServerShouldEnforceDedicatedDomain(System.getProperty(ENFORCE_DEDICATED_DOMAIN, "true")); + } + return Boolean.parseBoolean(znodeGroupAclServerShouldEnforceDedicatedDomain); + } + + public String getZnodeGroupAclClientUriDomainMappingRootPath() { + return ZNODE_GROUP_ACL_CLIENTURI_DOMAIN_MAPPING_ROOT_PATH; + } + + public boolean isStoreAuthedClientIdEnabled() { + return Boolean.parseBoolean(storeAuthedClientIdEnabled) || Boolean + .parseBoolean(System.getProperty(STORE_AUTHED_CLIENT_ID)); + } + + private Set loadSuperUserIds() { + if (znodeGroupAclSuperUserIdStr == null) { + setZnodeGroupAclSuperUserIdStr(System.getProperty(ZOOKEEPER_ZNODEGROUPACL_SUPERUSER_ID)); + } + if (znodeGroupAclSuperUserIdStr == null || znodeGroupAclSuperUserIdStr.isEmpty()) { + return Collections.emptySet(); + } + return Arrays.stream(znodeGroupAclSuperUserIdStr.split(",")).filter(str -> str.length() > 0) + .collect(Collectors.toSet()); + } + + /** + * Helper method for Znode Group Acl feature + * Get open read access path prefixes from config + * @return A set of path prefixes + */ + private Set loadOpenReadAccessPathPrefixes() { + if (znodeGroupAclOpenReadAccessPathPrefixStr == null) { + setZnodeGroupAclOpenReadAccessPathPrefixStr(System.getProperty(OPEN_READ_ACCESS_PATH_PREFIX)); + } + if (znodeGroupAclOpenReadAccessPathPrefixStr == null + || znodeGroupAclOpenReadAccessPathPrefixStr.isEmpty()) { + return Collections.emptySet(); + } + return Arrays.stream(znodeGroupAclOpenReadAccessPathPrefixStr.split(",")) + .filter(str -> str.length() > 0).collect(Collectors.toSet()); + } + + /** + * Helper method for Znode Group Acl feature + * Get open read access path prefixes from config + * @return A set of path prefixes + */ + private Set loadAllowedClientIdAsAclDomains() { + synchronized (allowedClientIdAsAclDomainsLock) { + if (allowedClientIdAsAclDomainsStr == null) { + setAllowedClientIdAsAclDomainsStr(System.getProperty(ALLOWED_CLIENT_ID_AS_ACL_DOMAINS)); + } + if (allowedClientIdAsAclDomainsStr == null || allowedClientIdAsAclDomainsStr.isEmpty()) { + return Collections.emptySet(); + } + return ImmutableSet.copyOf(Arrays.stream(allowedClientIdAsAclDomainsStr.split(",")) + .filter(str -> str.length() > 0) + .collect(Collectors.toSet())); + } + } + + /** + * Helper method for Znode Group Acl feature + * Get the domain names that are mapped to cross-domain access privilege + * @return A set of domain names + */ + private Set loadCrossDomainAccessDomainNames() { + if (znodeGroupAclCrossDomainAccessDomainNameStr == null) { + setZnodeGroupAclCrossDomainAccessDomainNameStr(System.getProperty(CROSS_DOMAIN_ACCESS_DOMAIN_NAME)); + } + if (znodeGroupAclCrossDomainAccessDomainNameStr == null || znodeGroupAclCrossDomainAccessDomainNameStr + .isEmpty()) { + return Collections.emptySet(); + } + return Arrays.stream(znodeGroupAclCrossDomainAccessDomainNameStr.split(",")) + .filter(str -> str.length() > 0).collect(Collectors.toSet()); + } + + /** + * Check if server dedicated domain config property is set + * This check is only meaningful when x509 znode group acl feature is enabled + * @return true if a domain is set as the server's dedicated domain; false if not set + */ + public boolean isZnodeGroupAclDedicatedServerEnabled() { + return isX509ZnodeGroupAclEnabled() && getZnodeGroupAclServerDedicatedDomain() != null + && !getZnodeGroupAclServerDedicatedDomain().isEmpty(); + } + + /** + * Check if x509 znode group acl feature is enabled + * @return true if enabled; false if not + */ + public boolean isX509ZnodeGroupAclEnabled() { + return ProviderRegistry + .getServerProvider(X509AuthenticationUtil.X509_SCHEME) instanceof X509ZNodeGroupAclProvider; + } + + @VisibleForTesting + public static void reset() { + synchronized (X509AuthenticationConfig.class) { + instance = null; + } + } +} diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/X509AuthenticationProvider.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/X509AuthenticationProvider.java index 246c13f715b..f78b0864688 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/X509AuthenticationProvider.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/X509AuthenticationProvider.java @@ -191,7 +191,7 @@ public KeeperException.Code handleAuthentication(ServerCnxn cnxn, byte[] authDat * @return Identifier string to be associated with the client. */ protected String getClientId(X509Certificate clientCert) { - return clientCert.getSubjectX500Principal().getName(); + return X509AuthenticationUtil.getClientId(clientCert); } @Override diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/X509AuthenticationUtil.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/X509AuthenticationUtil.java new file mode 100644 index 00000000000..0f2778b6ad9 --- /dev/null +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/X509AuthenticationUtil.java @@ -0,0 +1,266 @@ +/* + * 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.zookeeper.server.auth; + +import java.security.cert.CertificateException; +import java.security.cert.CertificateParsingException; +import java.security.cert.X509Certificate; +import java.util.Collection; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import javax.net.ssl.X509KeyManager; +import javax.net.ssl.X509TrustManager; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.common.ClientX509Util; +import org.apache.zookeeper.common.X509Exception; +import org.apache.zookeeper.common.X509Util; +import org.apache.zookeeper.common.ZKConfig; +import org.apache.zookeeper.server.ServerCnxn; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Util class for x509 certificate-based authentication providers. + */ +public class X509AuthenticationUtil extends X509Util { + + private static final Logger LOG = LoggerFactory.getLogger(X509AuthenticationUtil.class); + + // Super user Auth Id scheme + public static final String SUPERUSER_AUTH_SCHEME = "super"; + public static final String X509_SCHEME = "x509"; + + @Override + protected String getConfigPrefix() { + return X509AuthenticationConfig.SSL_X509_CONFIG_PREFIX; + } + + @Override + protected boolean shouldVerifyClientHostname() { + return false; + } + + @Override + protected boolean shouldAllowReverseDnsLookup() { + return false; + } + + /** + * Create key manager from config for x509-based authentication provider + * @param config ZooKeeper config + * @return An X509KeyManager instance + */ + public static X509KeyManager createKeyManager(ZKConfig config) { + try (X509Util x509Util = new ClientX509Util()) { + String keyStoreLocation = config.getProperty(x509Util.getSslKeystoreLocationProperty(), ""); + String keyStorePassword = x509Util.getPasswordFromConfigPropertyOrFile(config, + x509Util.getSslKeystorePasswdProperty(), x509Util.getSslKeystorePasswdPathProperty()); + String keyStoreTypeProp = config.getProperty(x509Util.getSslKeystoreTypeProperty()); + + X509KeyManager km = null; + if (keyStoreLocation.isEmpty()) { + LOG.warn("Key store location not specified for SSL"); + } else { + try { + km = X509Util.createKeyManager(keyStoreLocation, keyStorePassword, keyStoreTypeProp); + } catch (X509Exception.KeyManagerException e) { + LOG.error("Failed to create key manager", e); + } + } + return km; + } + } + + /** + * Create trust manager from config for x509-based authentication provider + * @param config ZooKeeper config + * @return An X509TrustManager instance + */ + public static X509TrustManager createTrustManager(ZKConfig config) { + try (X509Util x509Util = new ClientX509Util()) { + boolean crlEnabled = + Boolean.parseBoolean(config.getProperty(x509Util.getSslCrlEnabledProperty())); + boolean ocspEnabled = + Boolean.parseBoolean(config.getProperty(x509Util.getSslOcspEnabledProperty())); + boolean hostnameVerificationEnabled = Boolean + .parseBoolean(config.getProperty(x509Util.getSslHostnameVerificationEnabledProperty())); + boolean allowReverseDnsLookup = Boolean + .parseBoolean(config.getProperty(x509Util.getSslAllowReverseDnsLookupProperty())); + String trustStoreLocation = + config.getProperty(x509Util.getSslTruststoreLocationProperty(), ""); + String trustStorePassword = x509Util.getPasswordFromConfigPropertyOrFile(config, + x509Util.getSslTruststorePasswdProperty(), x509Util.getSslTruststorePasswdPathProperty()); + String trustStoreTypeProp = config.getProperty(x509Util.getSslTruststoreTypeProperty()); + + X509TrustManager tm = null; + if (trustStoreLocation.isEmpty()) { + LOG.warn("Truststore location not specified for SSL"); + } else { + try { + tm = X509Util + .createTrustManager(trustStoreLocation, trustStorePassword, trustStoreTypeProp, + crlEnabled, ocspEnabled, hostnameVerificationEnabled, false, + allowReverseDnsLookup, X509Util.getFipsMode(config)); + } catch (X509Exception.TrustManagerException e) { + LOG.error("Failed to create trust manager", e); + } + } + return tm; + } + } + + /** + * Determine the string to be used as the remote host session Id for + * authorization purposes. Associate this client identifier with a + * ServerCnxn that has been authenticated over SSL, and any ACLs that refer + * to the authenticated client. + * + * @param clientCert Authenticated X509Certificate associated with the + * remote host. + * @return Identifier string to be associated with the client. + * The clientId can be any string matched and extracted using regex from Subject Distinguished Name or + * Subject Alternative Name from x509 certificate. + * The clientId string is intended to be an URI for client and map the client to certain domain. + */ + public static String getClientId(X509Certificate clientCert) { + String clientCertIdType = X509AuthenticationConfig.getInstance().getClientCertIdType(); + if (clientCertIdType != null && clientCertIdType + .equalsIgnoreCase(X509AuthenticationConfig.SUBJECT_ALTERNATIVE_NAME_SHORT)) { + try { + return X509AuthenticationUtil.matchAndExtractSAN(clientCert); + } catch (Exception ce) { + LOG.warn("Failed to match and extract a client ID from SAN. Using Subject DN instead.", ce); + } + } + // return Subject DN by default + return clientCert.getSubjectX500Principal().getName(); + } + + /** + * Extract the authenticated client Id from the specified server connection object. + * @param cnxn Server connection object that contains the certificate. + * @param trustManager X509 TrustManager for authentication. + * @return Identifier string to be associated with the client. + * The clientId can be any string matched and extracted using regex from Subject Distinguished Name or + * Subject Alternative Name from x509 certificate. + * The clientId string is intended to be an URI for client and map the client to certain domain. + * @throws KeeperException.AuthFailedException Failed to authenticate the client certificate + */ + public static String getClientId(ServerCnxn cnxn, X509TrustManager trustManager) + throws KeeperException.AuthFailedException { + X509Certificate clientCert = X509AuthenticationUtil.getAuthenticatedClientCert(cnxn, trustManager); + return X509AuthenticationUtil.getClientId(clientCert); + } + + /** + * Extract SAN field from an X509 certificate + * @param clientCert Client x509 certificate + * @return Subject alternative name (SAN) string + * @throws CertificateParsingException + */ + private static String matchAndExtractSAN(X509Certificate clientCert) + throws CertificateParsingException { + int matchType = X509AuthenticationConfig.getInstance().getClientCertIdSanMatchType(); + String matchRegex = X509AuthenticationConfig.getInstance().getClientCertIdSanMatchRegex(); + String extractRegex = X509AuthenticationConfig.getInstance().getClientCertIdSanExtractRegex(); + int extractMatcherGroupIndex = + X509AuthenticationConfig.getInstance().getClientCertIdSanExtractMatcherGroupIndex(); + LOG.debug("Using SAN from client cert to extract client ID. matchType: {}, matchRegex: {}, extractRegex: {}, " + + "extractMatcherGroupIndex: {}", matchType, matchRegex, extractRegex, + extractMatcherGroupIndex); + if (matchRegex == null || extractRegex == null || matchType < 0 || matchType > 8) { + // SAN extension must be in the range of [0, 8]. + // See GeneralName object defined in RFC 5280 (The ASN.1 definition of the SubjectAltName extension) + String errStr = "Client cert ID type 'SAN' was provided but matchType or matchRegex given is invalid! " + + "matchType: " + matchType + " matchRegex: " + matchRegex; + LOG.error(errStr); + throw new IllegalArgumentException(errStr); + } + // filter by match type and match regex + LOG.debug("Number of SAN entries found in client cert: " + clientCert.getSubjectAlternativeNames().size()); + Pattern matchPattern = Pattern.compile(matchRegex); + Collection> matched = clientCert.getSubjectAlternativeNames().stream().filter( + list -> list.get(0).equals(matchType) && matchPattern.matcher((CharSequence) list.get(1)) + .find()).collect(Collectors.toList()); + + LOG.debug("Number of SAN entries matched: " + matched.size() + ". Printing all matches..."); + for (List match : matched) { + LOG.debug("Match: (" + match.get(0) + ", " + match.get(1) + ")"); + } + + // if there are more than one match or 0 matches, throw an error + if (matched.size() != 1) { + String errStr = "Zero or multiple matches found in SAN! Please fix match type and regex so that exactly one match " + + "is found."; + LOG.error(errStr); + throw new IllegalArgumentException(errStr); + } + + // Extract a substring from the found match using extractRegex + Pattern extractPattern = Pattern.compile(extractRegex); + Matcher matcher = extractPattern.matcher(matched.iterator().next().get(1).toString()); + if (matcher.find()) { + // If extractMatcherGroupIndex is not given, return the 1st index by default + String result = matcher.group(extractMatcherGroupIndex); + LOG.debug("Returning extracted client ID: {} using Matcher group index: {}", result, extractMatcherGroupIndex); + return result; + } + String errStr = "Failed to find an extract substring to determine client ID. Please review the extract regex."; + LOG.error(errStr); + throw new IllegalArgumentException(errStr); + } + + /** + * Get a client certificate from server connection object and authenticate the certificate using X509TrustManager + * @param cnxn ServerCnxn object + * @param trustManager + * @return The authenticated client certificate + * @throws KeeperException.AuthFailedException Failed to authenticate the client certificate + */ + public static X509Certificate getAuthenticatedClientCert(ServerCnxn cnxn, X509TrustManager trustManager) + throws KeeperException.AuthFailedException { + X509Certificate[] certChain = (X509Certificate[]) cnxn.getClientCertificateChain(); + + if (certChain == null || certChain.length == 0) { + String errMsg = "No X509 certificate is found in cert chain."; + LOG.error(errMsg); + throw new KeeperException.AuthFailedException(); + } + + X509Certificate clientCert = certChain[0]; + + if (trustManager == null) { + String errMsg = "No trust manager available to authenticate session 0x" + Long.toHexString(cnxn.getSessionId()); + LOG.error(errMsg); + throw new KeeperException.AuthFailedException(); + } + + try { + // Authenticate client certificate + trustManager.checkClientTrusted((X509Certificate[]) cnxn.getClientCertificateChain(), clientCert.getPublicKey().getAlgorithm()); + } catch (CertificateException ce) { + String errMsg = "Failed to trust certificate for session 0x" + Long.toHexString(cnxn.getSessionId()); + LOG.error(errMsg, ce); + throw new KeeperException.AuthFailedException(); + } + return certChain[0]; + } +} diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/znode/groupacl/ClientUriDomainMappingHelper.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/znode/groupacl/ClientUriDomainMappingHelper.java new file mode 100644 index 00000000000..b74b27c5e3a --- /dev/null +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/znode/groupacl/ClientUriDomainMappingHelper.java @@ -0,0 +1,51 @@ +/* + * 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.zookeeper.server.auth.znode.groupacl; + +import java.util.Set; +import org.apache.zookeeper.server.ServerCnxn; + +/** + * Helper class for looking up the domain name for the client connection. It uses the client's + * Uniform Resource Identifier (URI) to look up the application domain it belongs to. + * + * This class is to be used for ZNode group-based security where one or more clients can be + * "authorized" to be given clientId that matches the application domain name. + * + * To illustrate ZNode group-based security, ZNodes written by a host of "foo" applications will + * have "foo" as an ACL entity with all accesses (rwcd). Then all ZooKeeper clients belonging to + * "foo" application will be "authorized" as "foo", as in at TLS handshake/auth time, they will be + * given "foo" as the clientId. These clients will present their client X509 certificates with their + * URIs, and this ClientUriDomainMappingHelper will be used at auth time to convert the extracted + * URI to the appropriate domain name "foo". + */ +public interface ClientUriDomainMappingHelper { + /** + * Return a set of application domain names that the given clientUri maps to. + * @param clientUri + * @return set of domain names. If not found, returns an empty set. + */ + Set getDomains(String clientUri); + + /** + * Update the domain-based AuthInfo for the specified connection. + * @param cnxn Connection to update + */ + void updateDomainBasedAuthInfo(ServerCnxn cnxn); +} diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/znode/groupacl/ConnectionAuthInfoUpdater.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/znode/groupacl/ConnectionAuthInfoUpdater.java new file mode 100644 index 00000000000..da5c1a38ff5 --- /dev/null +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/znode/groupacl/ConnectionAuthInfoUpdater.java @@ -0,0 +1,35 @@ +/* + * 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.zookeeper.server.auth.znode.groupacl; + +import java.util.Map; +import java.util.Set; +import org.apache.zookeeper.server.ServerCnxn; + +/** + * Interface that declares method to update connection AuthInfo when the client URI to domain mapping is updated. + */ +interface ConnectionAuthInfoUpdater { + /** + * Update the AuthInfo of all the connections based on the specified client URI to domain information. + * @param cnxn connection to be updated. + * @param clientUriToDomainNames + */ + void updateAuthInfo(ServerCnxn cnxn, Map> clientUriToDomainNames); +} diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/znode/groupacl/X509ZNodeGroupAclProvider.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/znode/groupacl/X509ZNodeGroupAclProvider.java new file mode 100644 index 00000000000..34869b83c4f --- /dev/null +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/znode/groupacl/X509ZNodeGroupAclProvider.java @@ -0,0 +1,286 @@ +/* + * 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.zookeeper.server.auth.znode.groupacl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import javax.net.ssl.X509KeyManager; +import javax.net.ssl.X509TrustManager; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.common.ZKConfig; +import org.apache.zookeeper.data.Id; +import org.apache.zookeeper.server.ServerCnxn; +import org.apache.zookeeper.server.ZooKeeperServer; +import org.apache.zookeeper.server.auth.ServerAuthenticationProvider; +import org.apache.zookeeper.server.auth.X509AuthenticationConfig; +import org.apache.zookeeper.server.auth.X509AuthenticationUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * A ServerAuthenticationProvider implementation that does both authentication and authorization for protecting znodes from unauthorized access. + * Znodes are grouped into domains according to their ownership, and clients are granted access permission to domains. + * Authentication mechanism is same as in X509AuthenticationProvider. If authentication is failed, + * decline the connection request. + * Authorization is done by checking clientId which is usually an URI (uniform resource identifier)in ACL metadata for matched domains. + * Detailed step for authorization is: + * 1. Acl provider attempts to extract the clientId from the cert provided by the client + * 2. Acl provider attempts to look up the client's domain using the clientId and ClientUriDomainMappingHelper + * 3. If matched domain is found, add the domain in authInfo in the connection object; + * if no matched domain is found, add the clientId in authInfo instead; either way, establish the connection. + * This class is meant to support the following use patterns: + * 1. Single domain: The creator and the accessor to the znodes belong to the same domain. This is + * the most straightforward use case, and accessors in other domains won't be able to access the + * znodes due to their clientId not matching any in the znodes. + * 2. Super user domain: The accessors need permission to access znodes created by creators belong + * to multiple domains. In this case the accessors will be mapped to super user domain and be + * given super user privilege. + * 3. Open read access: The znodes need to be accessed by accessors from many different domains, so when + * the creators create these znodes, these nodes will be given "open read access" (see below). + * Optional features include: + * "auto-set ACL": add ZooDefs.Ids.CREATOR_ALL_ACL to all newly-created znodes, + * "open read access": this feature concerns read access only. Add (world, anyone r) to all + * newly-written znodes whose path prefixes are given in the znode group acl config + * (comma-delimited, multiple such prefixes are possible). + * "store authed clientId": If enabled, the server will store the clientId in authInfo, in addition + * to the matched domain. This feature is only available in non-dedicated server cases. + * "connection filtering": If the server is a dedicated server that only serves one domain, + * the name of the domain is made the "dedicatedDomain" of the server. The server will decline + * the connection requests from client who belongs to a domain that does not match with the + * server's dedicated domain, only allow connection to be established with client belong to the + * dedicated domain. Usually this feature is combined with "auto-set ACL" to be false, so + * all the znodes created on dedicated server will be getting OPEN_ACL_UNSAFE ACL, meaning that + * read/write access to these znodes is open to all the clients connected to this server. + */ +public class X509ZNodeGroupAclProvider extends ServerAuthenticationProvider { + private static final Logger LOG = LoggerFactory.getLogger(X509ZNodeGroupAclProvider.class); + private final X509TrustManager trustManager; + private final X509KeyManager keyManager; + // Although using "volatile" keyword with double checked locking could prevent the undesired + //creation of multiple objects; not using here for the consideration of read performance + private ClientUriDomainMappingHelper uriDomainMappingHelper = null; + + public X509ZNodeGroupAclProvider() { + ZKConfig config = new ZKConfig(); + this.keyManager = X509AuthenticationUtil.createKeyManager(config); + this.trustManager = X509AuthenticationUtil.createTrustManager(config); + } + + public X509ZNodeGroupAclProvider(X509TrustManager trustManager, X509KeyManager keyManager) { + this.trustManager = trustManager; + this.keyManager = keyManager; + } + + @Override + public KeeperException.Code handleAuthentication(ServerObjs serverObjs, byte[] authData) { + // 1. Authenticate connection + ServerCnxn cnxn = serverObjs.getCnxn(); + try { + X509AuthenticationUtil.getAuthenticatedClientCert(cnxn, trustManager); + } catch (KeeperException.AuthFailedException e) { + return KeeperException.Code.AUTHFAILED; + } catch (Exception e) { + // Failed to extract clientId from certificate + LOG.error("Failed to extract URI from certificate for session 0x{}", Long.toHexString(cnxn.getSessionId()), e); + return KeeperException.Code.OK; + } + + // 2. Authorize connection based on domains. + try { + ClientUriDomainMappingHelper helper = getUriDomainMappingHelper(serverObjs.getZks()); + // Initially assign AuthInfo to the new connection by triggering the helper update method. + helper.updateDomainBasedAuthInfo(cnxn); + } catch (Exception e) { + LOG.error("Failed to authorize session 0x{}", Long.toHexString(cnxn.getSessionId()), e); + } + + // Authentication is done regardless of whether authorization is done or not. + return KeeperException.Code.OK; + } + + @Override + public boolean matches(ServerObjs serverObjs, MatchValues matchValues) { + // Not checking for super user here because the check is already covered + // in checkAcl() in ZookeeperServer.class + return matchValues.getId().equals(matchValues.getAclExpr()); + } + + @Override + public String getScheme() { + // Same scheme as X509AuthenticationProvider since they both use x509 certificate + return "x509"; + } + + @Override + public boolean isAuthenticated() { + return true; + } + + @Override + public boolean isValid(String id) { + // Id can be of multiple format since it can be either a domain or a client URI, + // so the check on Id format can be expensive. + // For users, the Id to be set is extracted by server therefore it must be of valid format. + // Validity of client URI is checked in X509AuthenticationUtil.getClientId when authentication + // is done; validity of domain names are checked when client URI - domain pairs are set in + // ClientUriDomainMapping. + // Only superusers can manually set ACL, who we should trust. + // Therefore it is necessary to perform this check. + return true; + } + + /** + * Initialize a new ClientUriDomainMappingHelper instance lazily if it hasn't been instantiated for the ACL provider. + * Since it's lazy initialization suppressing spotbugs DC_DOUBLECHECK warning. + * Supressing IS2_INCONSISTENT_SYNC warning for uriDomainMappingHelper since it's guarded correctly by synchronized block. + * @param zks + */ + @SuppressFBWarnings({"DC_DOUBLECHECK", "IS2_INCONSISTENT_SYNC"}) + private ClientUriDomainMappingHelper getUriDomainMappingHelper(ZooKeeperServer zks) { + if (uriDomainMappingHelper == null) { + synchronized (this) { + if (uriDomainMappingHelper == null) { + ZkClientUriDomainMappingHelper helper = new ZkClientUriDomainMappingHelper(zks); + // Set up AuthInfo updater to refresh connection AuthInfo on any client domain changes. + // TODO Making the anonymous class to a separate updater implementation class if any other Acl provider shares + // the same logic. + helper.setDomainAuthUpdater((cnxn, clientUriToDomainNames) -> { + try { + String clientId = X509AuthenticationUtil.getClientId(cnxn, trustManager); + assignAuthInfo(cnxn, clientId, + clientUriToDomainNames.getOrDefault(clientId, Collections.emptySet())); + } catch (UnsupportedOperationException unsupportedEx) { + LOG.info("Cannot update AuthInfo for session 0x{} since the operation is not supported.", + Long.toHexString(cnxn.getSessionId())); + } catch (KeeperException.AuthFailedException authEx) { + LOG.error("Failed to authenticate session 0x{} for AuthInfo update. Revoking all of its ZNodeGroupAcl AuthInfo.", + Long.toHexString(cnxn.getSessionId()), authEx); + try { + cnxn.getAuthInfo() + .stream() + .filter(id -> isZnodeGroupAclScheme(id.getScheme())) + .forEach(id -> cnxn.removeAuthInfo(id)); + } catch (Exception ex) { + LOG.error("Failed to revoke AuthInfo for session 0x{}.", + Long.toHexString(cnxn.getSessionId()), ex); + } + } catch (Exception e) { + LOG.error("Failed to update AuthInfo for session 0x{}. Keep the existing ZNodeGroupAcl AuthInfo.", + Long.toHexString(cnxn.getSessionId()), e); + // TODO Emitting errors to ZK metrics so the out-of-date AuthInfo can trigger alerts and get fixed. + } + }); + uriDomainMappingHelper = helper; + LOG.info("New UriDomainMappingHelper has been instantiated."); + } + } + } + return uriDomainMappingHelper; + } + + /** + * Assign AuthInfo to the specified connection. + * Note, do not use this method outside the implementation of ConnectionAuthInfoUpdater.updateAuthInfo. Otherwise, + * concurrency control is required to prevent inconsistent update. + * + * @param cnxn Client connection to be updated + * @param clientId ClientId to be potentially used as the AuthInfo Id if the client is super user. + * The clientId can be any string matched and extracted using regex from Subject Distinguished + * Name or Subject Alternative Name from x509 certificate. + * The clientId string is intended to be an URI for client and map the client to certain domain. + * The user can use the properties defined in X509AuthenticationUtil to extract a desired string as + * clientId. + * @param domains Domains to be used as the AuthInfo Id. + */ + private void assignAuthInfo(ServerCnxn cnxn, String clientId, Set domains) { + Set superUserDomainNames = X509AuthenticationConfig.getInstance().getZnodeGroupAclCrossDomainAccessDomains(); + Set superUsers = X509AuthenticationConfig.getInstance().getZnodeGroupAclSuperUserIds(); + + Set newAuthIds = new HashSet<>(); + + // Find interesecting super user domains/cross domains from provided domains list + List commonSuperUserDomains = + superUserDomainNames.stream().filter(domains::contains).collect(Collectors.toList()); + + // Check if user belongs to super user id group + if (superUsers.contains(clientId)) { + newAuthIds.add(new Id(X509AuthenticationUtil.SUPERUSER_AUTH_SCHEME, clientId)); + } else if (!commonSuperUserDomains.isEmpty()) { + // For cross domain components, add (super:domainName) in authInfo + // "super" scheme gives access to all znodes without checking znode ACL vs authorized domain name + commonSuperUserDomains.stream().forEach(d -> + newAuthIds.add(new Id(X509AuthenticationUtil.SUPERUSER_AUTH_SCHEME, d))); + } else if (X509AuthenticationConfig.getInstance().isZnodeGroupAclDedicatedServerEnabled()) { + // If connection filtering feature is turned on, use connection filtering instead of normal authorization + String serverNamespace = X509AuthenticationConfig.getInstance().getZnodeGroupAclServerDedicatedDomain(); + if (domains.contains(serverNamespace)) { + LOG.info("Id '{}' belongs to domain that matches server namespace '{}', authorized for access.", + clientId, serverNamespace); + // Same as storing authenticated user info in X509AuthenticationProvider + newAuthIds.add(new Id(getScheme(), clientId)); + } else { + if (X509AuthenticationConfig.getInstance().isEnforceDedicatedDomainEnabled()) { + LOG.error("Id '{}' does not belong to domain that matches server namespace '{}', disconnecting the connection.", + clientId, serverNamespace); + cnxn.close(ServerCnxn.DisconnectReason.SSL_AUTH_FAILURE); + } else { + LOG.warn("Id '{}' does not belong to domain that matches server namespace '{}'. Allowing connection for now, " + + "but client connection will be blocked/disconnected in future when dedicated domain connection " + + "filtering is enforced.", clientId, serverNamespace); + } + } + } else { + // For other cases, add (x509:domainName) in authInfo + domains.stream().forEach(d -> newAuthIds.add(new Id(getScheme(), d))); + // If no domain is matched for the clientId, then clientId will be added to authInfo; + // if StoreAuthedClientId feature is enabled, clientId will be added to authInfo in addition + // to matched domain names. + if (domains.isEmpty() || X509AuthenticationConfig.getInstance().isStoreAuthedClientIdEnabled()) { + newAuthIds.add(new Id(getScheme(), clientId)); + } + } + + // Update the existing connection AuthInfo accordingly. + Set currentCnxnAuthIds = new HashSet<>(cnxn.getAuthInfo()); + currentCnxnAuthIds.stream().forEach(id -> { + // Remove all previously assigned ZNodeGroupAcls that are no longer valid. + if (isZnodeGroupAclScheme(id.getScheme()) && !newAuthIds.contains(id)) { + cnxn.removeAuthInfo(id); + LOG.info("Authenticated Id 'scheme: {}, id: {}' has been removed from session 0x{} of host {}.", + id.getScheme(), id.getId(), Long.toHexString(cnxn.getSessionId()), cnxn.getHostAddress()); + } + }); + + newAuthIds.stream().forEach(id -> { + if (!currentCnxnAuthIds.contains(id)) { + cnxn.addAuthInfo(id); + LOG.info("Authenticated Id 'scheme: {}, id: {}' has been added to session 0x{} from host {}.", + id.getScheme(), id.getId(), Long.toHexString(cnxn.getSessionId()), cnxn.getHostAddress()); + } + }); + } + + private boolean isZnodeGroupAclScheme(String scheme) { + return scheme.equals(X509AuthenticationUtil.SUPERUSER_AUTH_SCHEME) || scheme.equals(getScheme()); + } +} diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/znode/groupacl/ZkClientUriDomainMappingHelper.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/znode/groupacl/ZkClientUriDomainMappingHelper.java new file mode 100644 index 00000000000..9e102ba31fc --- /dev/null +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/znode/groupacl/ZkClientUriDomainMappingHelper.java @@ -0,0 +1,198 @@ +/* + * 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.zookeeper.server.auth.znode.groupacl; + +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.ZooDefs; +import org.apache.zookeeper.data.ACL; +import org.apache.zookeeper.server.DumbWatcher; +import org.apache.zookeeper.server.ServerCnxn; +import org.apache.zookeeper.server.ServerCnxnFactory; +import org.apache.zookeeper.server.ZooKeeperServer; +import org.apache.zookeeper.server.auth.X509AuthenticationConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * An implementation of ClientUriDomainMappingHelper that stores the mapping inside the ZK server + * as a hierarchy of ZNodes. + * + * Note that the mapping metadata itself will be stored in ZKDatabase as a ZNode tree and will also + * be cached inside this helper object. This helper object watches the clientUri-domain ZNodes and + * updates the internal Map accordingly. + * + * The following illustrates the ZNode hierarchy: + * . (root) + * └── /zookeeper/uri-domain-map (mapping root path) + * ├── bar (application domain) + * │ ├── bar0 (client URI) + * │ └── bar1 (client URI) + * └── foo (application domain) + * ├── foo1 (client URI) + * ├── foo2 (client URI) + * └── foo3 (client URI) + * + * Note: It is not expected that there would be too many distinct client URIs so as to overwhelm + * heap usage. + */ +public class ZkClientUriDomainMappingHelper implements ClientUriDomainMappingHelper { + + private static final Logger LOG = LoggerFactory.getLogger(ZkClientUriDomainMappingHelper.class); + + private final ZooKeeperServer zks; + private final String rootPath; + + private volatile Map> clientUriToDomainNames = Collections.emptyMap(); + private ConnectionAuthInfoUpdater updater = null; + + public ZkClientUriDomainMappingHelper(ZooKeeperServer zks) { + this.zks = zks; + + this.rootPath = + X509AuthenticationConfig.getInstance().getZnodeGroupAclClientUriDomainMappingRootPath(); + LOG.info("Client URI domain mapping root path: {}", this.rootPath); + if (rootPath == null) { + throw new IllegalStateException( + "Client URI domain mapping root path config is not set!"); + } + + if (zks.getZKDatabase().getNode(rootPath) == null) { + LOG.warn("Client URI domain mapping root path {} does not exist.", this.rootPath); + } + + addWatches(); + parseZNodeMapping(); + } + + /** + * @return True if the new updater is setup to the helper instance. False if the specified updater is not set since + * another updater has already been configured. + */ + @SuppressFBWarnings("DC_DOUBLECHECK") + boolean setDomainAuthUpdater(ConnectionAuthInfoUpdater updater) { + if (this.updater == null) { + synchronized (this) { + if (this.updater == null) { + this.updater = updater; + return true; + } + } + } + return false; + } + + /** + * Install a persistent recursive watch on the root path. + * The watcher has to be added here instead of in {@link org.apache.zookeeper.server.auth.znode.groupacl.X509ZNodeGroupAclProvider} + * because this class is one layer above connections, and is a central place to handle add watch, + * process event, etc logic for all the connections in this server. + * Therefore, only one watch needs to be added per server. + */ + private void addWatches() { + zks.getZKDatabase().addWatch(rootPath, new MappingRootWatcher(), ZooDefs.AddWatchModes.persistentRecursive); + } + + /** + * Read ZNodes under the root path and populates clientUriToDomainNames. + * Note: this is not thread-safe nor atomic; however, we do not need such strong guarantee with + * this read operation. + * + * Also, note that this is a purely in-memory operation, so re-parsing the entire tree should not + * be a big overhead considering how infrequently the mapping is supposed to be changed. + */ + private void parseZNodeMapping() { + Map> newClientUriToDomainNames = new HashMap<>(); + try { + List domainNames = zks.getZKDatabase().getChildren(rootPath, null, null); + domainNames.forEach(domainName -> { + try { + List clientUris = + zks.getZKDatabase().getChildren(rootPath + "/" + domainName, null, null); + clientUris.forEach(clientUri -> { + LOG.info("Registering client URI domain mapping: {} --> {}", clientUri, domainName); + newClientUriToDomainNames.computeIfAbsent(clientUri, k -> new HashSet<>()).add(domainName); + }); + } catch (KeeperException.NoNodeException e) { + LOG.warn("No clientUri ZNodes found under domain: {}", domainName); + } + }); + } catch (KeeperException.NoNodeException e) { + LOG.warn("No application domain ZNodes found in root path: {}", rootPath); + } + clientUriToDomainNames = newClientUriToDomainNames; + } + + @Override + public Set getDomains(String clientUri) { + return clientUriToDomainNames.getOrDefault(clientUri, Collections.emptySet()); + } + + @Override + public void updateDomainBasedAuthInfo(ServerCnxn cnxn) { + if (updater != null && cnxn != null) { + // UpdateAuthInfo is triggered on new connection, as well as any URI-domain map ZNode changes. + // To prevent inconsistent update, concurrency control is necessary. + synchronized (updater) { + updater.updateAuthInfo(cnxn, clientUriToDomainNames); + } + } + } + + /** + * The watcher used to listen on client uri - domain mapping root path for mapping update + * Extends DumbWatcher instead of ServerCnxn because there are some package-private methods in + * ServerCnxn which cannot be overridden here, such as {@code abstract void setSessionId(long sessionId);}. + */ + public class MappingRootWatcher extends DumbWatcher { + @Override + public void process(WatchedEvent event, List znodeAcl) { + LOG.info("Processing watched event: {}", event.toString()); + parseZNodeMapping(); + // Update AuthInfo for all the known connections. + // Note : It is not ideal to iterate over all plaintext connections which are connected over non-TLS but right now + // there is no way to find out if connection on unified port is using SSLHandler or nonSSLHandler. Anyways, we + // should not ideally have any nonSSLHandler connections on unified port after complete rollout. + + // TODO Change to read SecureServerCnxnFactory only. The current logic is to support unit test who is not creating + // a secured server cnxn factory. It won't cause any problem but is not technically correct. + + // Since port unification is supported, TLS requests could be made on unified as well as secure port. Hence iterate + // over all connections to update auth info. + ServerCnxnFactory factory = zks.getServerCnxnFactory(); + LOG.info("Updating auth info for connections"); + // TODO Evaluate performance impact and potentially use thread pool to parallelize the AuthInfo update. + if (factory != null) { + factory.getConnections().forEach(cnxn -> updateDomainBasedAuthInfo(cnxn)); + } + ServerCnxnFactory secureFactory = zks.getSecureServerCnxnFactory(); + LOG.info("Updating auth info for TLS connections"); + if (secureFactory != null) { + secureFactory.getConnections().forEach(cnxn -> updateDomainBasedAuthInfo(cnxn)); + } + } + } +} diff --git a/zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/QuorumPeerConfig.java b/zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/QuorumPeerConfig.java index e2ef8a7e261..b8e84351f43 100644 --- a/zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/QuorumPeerConfig.java +++ b/zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/QuorumPeerConfig.java @@ -47,6 +47,7 @@ import org.apache.zookeeper.metrics.impl.DefaultMetricsProvider; import org.apache.zookeeper.server.ZooKeeperServer; import org.apache.zookeeper.server.auth.ProviderRegistry; +import org.apache.zookeeper.server.auth.X509AuthenticationConfig; import org.apache.zookeeper.server.backup.BackupConfig; import org.apache.zookeeper.server.backup.BackupSystemProperty; import org.apache.zookeeper.server.quorum.QuorumPeer.LearnerType; @@ -371,6 +372,36 @@ public void parseProperties(Properties zkProp) throws IOException, ConfigExcepti backupConfigBuilder.setTimetableStoragePath(value); } else if (key.equals(BackupSystemProperty.BACKUP_TIMETABLE_BACKUP_INTERVAL_MS)) { backupConfigBuilder.setTimetableBackupIntervalInMs(Long.parseLong(value)); + } else if (key.equals(X509AuthenticationConfig.SET_X509_CLIENT_ID_AS_ACL)) { + // These X509AuthenticationConfig constants include the "zookeeper." prefix, so + // fully qualified zoo.cfg keys invoke the setters here. The usual unprefixed keys + // fall through to the default branch, which adds "zookeeper." and sets system + // properties read by the X509AuthenticationConfig getters. + X509AuthenticationConfig.getInstance().setX509ClientIdAsAclEnabled(value); + } else if (key.equals(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_TYPE)) { + X509AuthenticationConfig.getInstance().setClientCertIdType(value); + } else if (key.equals(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_MATCH_TYPE)) { + X509AuthenticationConfig.getInstance().setClientCertIdSanMatchType(value); + } else if (key.equals(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_MATCH_REGEX)) { + X509AuthenticationConfig.getInstance().setClientCertIdSanMatchRegex(value); + } else if (key.equals(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_EXTRACT_REGEX)) { + X509AuthenticationConfig.getInstance().setClientCertIdSanExtractRegex(value); + } else if (key.equals(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_EXTRACT_MATCHER_GROUP_INDEX)) { + X509AuthenticationConfig.getInstance().setClientCertIdSanExtractMatcherGroupIndex(value); + } else if (key.equals(X509AuthenticationConfig.CROSS_DOMAIN_ACCESS_DOMAIN_NAME)) { + X509AuthenticationConfig.getInstance().setZnodeGroupAclCrossDomainAccessDomainNameStr(value); + } else if (key.equals(X509AuthenticationConfig.DEDICATED_DOMAIN)) { + X509AuthenticationConfig.getInstance().setZnodeGroupAclServerDedicatedDomain(value); + } else if (key.equals(X509AuthenticationConfig.ZOOKEEPER_ZNODEGROUPACL_SUPERUSER_ID)) { + X509AuthenticationConfig.getInstance().setZnodeGroupAclSuperUserIdStr(value); + } else if (key.equals(X509AuthenticationConfig.OPEN_READ_ACCESS_PATH_PREFIX)) { + X509AuthenticationConfig.getInstance().setZnodeGroupAclOpenReadAccessPathPrefixStr(value); + } else if (key.equals(X509AuthenticationConfig.STORE_AUTHED_CLIENT_ID)) { + X509AuthenticationConfig.getInstance().setStoreAuthedClientIdEnabled(value); + } else if (key.equals(X509AuthenticationConfig.ALLOWED_CLIENT_ID_AS_ACL_DOMAINS)) { + X509AuthenticationConfig.getInstance().setAllowedClientIdAsAclDomainsStr(value); + } else if (key.equals(X509AuthenticationConfig.ENFORCE_DEDICATED_DOMAIN)) { + X509AuthenticationConfig.getInstance().setZnodeGroupAclServerShouldEnforceDedicatedDomain(value); } else if (key.equals("standaloneEnabled")) { setStandaloneEnabled(parseBoolean(key, value)); } else if (key.equals("reconfigEnabled")) { diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509TestHelpers.java b/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509TestHelpers.java index fb1371a3da7..31c3af69f07 100644 --- a/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509TestHelpers.java +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/common/X509TestHelpers.java @@ -130,6 +130,25 @@ now, new Date(now.getTime() */ public static X509Certificate newCert( X509Certificate caCert, KeyPair caKeyPair, X500Name certSubject, PublicKey certPublicKey, long expirationMillis) throws IOException, OperatorCreationException, GeneralSecurityException { + return newCertSignedBy(caCert, caKeyPair, certSubject, certPublicKey, + getLocalhostSubjectAltNames(), expirationMillis); + } + + /** + * Variant of {@link #newCert} that installs the supplied SANs instead of the default + * localhost SANs. Used by tests that need certs with specific URI SANs (e.g., SPIFFE URIs). + */ + public static X509Certificate newCertWithSans( + X509Certificate caCert, KeyPair caKeyPair, X500Name certSubject, PublicKey certPublicKey, + GeneralNames sans, long expirationMillis) + throws IOException, OperatorCreationException, GeneralSecurityException { + return newCertSignedBy(caCert, caKeyPair, certSubject, certPublicKey, sans, expirationMillis); + } + + private static X509Certificate newCertSignedBy( + X509Certificate caCert, KeyPair caKeyPair, X500Name certSubject, PublicKey certPublicKey, + GeneralNames sans, long expirationMillis) + throws IOException, OperatorCreationException, GeneralSecurityException { if (!caKeyPair.getPublic().equals(caCert.getPublicKey())) { throw new IllegalArgumentException("CA private key does not match the public key in the CA cert"); } @@ -142,7 +161,7 @@ public static X509Certificate newCert( | KeyUsage.keyEncipherment)); builder.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(new KeyPurposeId[]{KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth})); - builder.addExtension(Extension.subjectAlternativeName, false, getLocalhostSubjectAltNames()); + builder.addExtension(Extension.subjectAlternativeName, false, sans); return buildAndSignCertificate(caKeyPair.getPrivate(), builder); } diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/RequestThrottlerTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/RequestThrottlerTest.java index 15259207599..a04ef9f88f0 100644 --- a/zookeeper-server/src/test/java/org/apache/zookeeper/server/RequestThrottlerTest.java +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/RequestThrottlerTest.java @@ -235,6 +235,9 @@ public void testRequestThrottler() throws Exception { // wait for more than one STALL_TIME to reduce timeout before wakeup assertTrue(entered.await(STALL_TIME + 5000, TimeUnit.MILLISECONDS)); + // The consumer can enter pRequest before the producer records the enqueue metric. + WaitForCondition allRequestsQueued = () -> getCounterMetric("prep_processor_request_queued") == TOTAL_REQUESTS; + waitFor("requests not all queued", allRequestsQueued, 5); Map metrics = MetricsUtils.currentServerMetrics(); assertEquals(TOTAL_REQUESTS, (long) metrics.get("prep_processor_request_queued")); } diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/auth/X509AuthenticationConfigTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/auth/X509AuthenticationConfigTest.java new file mode 100644 index 00000000000..71ecce82dbe --- /dev/null +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/auth/X509AuthenticationConfigTest.java @@ -0,0 +1,53 @@ +/* + * 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.zookeeper.server.auth; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import java.util.Properties; +import org.apache.zookeeper.ZKTestCase; +import org.apache.zookeeper.server.quorum.QuorumPeerConfig; +import org.apache.zookeeper.test.ClientBase; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +public class X509AuthenticationConfigTest extends ZKTestCase { + @AfterEach + public void tearDown() { + System.clearProperty(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_TYPE); + System.clearProperty(X509AuthenticationConfig.ENFORCE_DEDICATED_DOMAIN); + System.clearProperty(X509AuthenticationConfig.ZOOKEEPER_ZNODEGROUPACL_SUPERUSER_ID); + X509AuthenticationConfig.reset(); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + public void testConfigurationFilePrefixes(boolean fullyQualified) throws Exception { + X509AuthenticationConfig.reset(); + String prefix = fullyQualified ? "zookeeper." : ""; + Properties properties = new Properties(); + properties.setProperty("dataDir", ClientBase.createTmpDir().getAbsolutePath()); + properties.setProperty(prefix + "ssl.x509.clientCertIdType", "SAN"); + properties.setProperty(prefix + "X509ZNodeGroupAclProvider.enforceDedicatedDomain", "false"); + new QuorumPeerConfig().parseProperties(properties); + assertEquals("SAN", X509AuthenticationConfig.getInstance().getClientCertIdType()); + assertFalse(X509AuthenticationConfig.getInstance().isEnforceDedicatedDomainEnabled()); + assertFalse(X509AuthenticationConfig.getInstance().isX509ClientIdAsAclEnabled()); + } +} diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/auth/znode/groupacl/TestFixupACL.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/auth/znode/groupacl/TestFixupACL.java new file mode 100644 index 00000000000..ebdd5e7ea7d --- /dev/null +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/auth/znode/groupacl/TestFixupACL.java @@ -0,0 +1,259 @@ +/* + * 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.zookeeper.server.auth.znode.groupacl; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.ZooDefs; +import org.apache.zookeeper.data.ACL; +import org.apache.zookeeper.data.Id; +import org.apache.zookeeper.server.PrepRequestProcessor; +import org.apache.zookeeper.server.auth.ProviderRegistry; +import org.apache.zookeeper.server.auth.X509AuthenticationConfig; +import org.apache.zookeeper.server.auth.X509AuthenticationProvider; +import org.apache.zookeeper.server.auth.X509AuthenticationUtil; +import org.junit.Assert; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * This class test fixupACL method in {@link org.apache.zookeeper.server.PrepRequestProcessor} + * under the znode group acl settings + */ +public class TestFixupACL { + private final String testPath = "/zookeeper/testPath"; + private final String dedicatedDomain = "dedicatedDomain"; + private final String crossDomain = "crossDomain"; + private final List singleDomainAuthInfo = + Collections.singletonList(new Id(X509AuthenticationUtil.X509_SCHEME, "domain")); + private final List superUserAuthInfo = + Collections.singletonList(new Id("super", "superUserId")); + private final List crossDomainComponentAuthInfo = + Collections.singletonList(new Id("super", crossDomain)); + private final List dedicatedDomainAuthInfo = + Collections.singletonList(new Id(X509AuthenticationUtil.X509_SCHEME, dedicatedDomain)); + private final List multiIdAuthInfo = new ArrayList<>(); + + { + multiIdAuthInfo.add(new Id(X509AuthenticationUtil.X509_SCHEME, "domain1")); + multiIdAuthInfo.add(new Id(X509AuthenticationUtil.X509_SCHEME, "domain2")); + } + + private final List nonX509AuthInfo = + Collections.singletonList(new Id("ip", "127.0.0.1:2183")); + + private List aclList = new ArrayList<>(); + + { + aclList + .add(new ACL(ZooDefs.Perms.ALL, new Id(X509AuthenticationUtil.X509_SCHEME, "toBeAdded"))); + aclList.add(new ACL(ZooDefs.Perms.ALL, ZooDefs.Ids.ANYONE_ID_UNSAFE)); + } + + private final Map SYSTEM_PROPERTIES = new HashMap<>(); + + { + SYSTEM_PROPERTIES + .put("zookeeper.authProvider.x509", X509ZNodeGroupAclProvider.class.getCanonicalName()); + SYSTEM_PROPERTIES.put(X509AuthenticationConfig.SET_X509_CLIENT_ID_AS_ACL, "true"); + SYSTEM_PROPERTIES + .put(X509AuthenticationConfig.ZOOKEEPER_ZNODEGROUPACL_SUPERUSER_ID, "superUserId"); + } + + @BeforeEach + public void before() { + X509AuthenticationConfig.reset(); + SYSTEM_PROPERTIES.forEach(System::setProperty); + ProviderRegistry.initialize(); + } + + @AfterEach + public void after() { + SYSTEM_PROPERTIES.keySet().forEach(System::clearProperty); + X509AuthenticationConfig.reset(); + ProviderRegistry.reset(); + } + + @Test + public void testCrossDomainComponents() throws KeeperException.InvalidACLException { + // User provided ACL list will not be honored for cross domain components. + // (x509 : domain name) will be set to the znodes + List returnedList = + PrepRequestProcessor.fixupACL(testPath, crossDomainComponentAuthInfo, aclList); + assertACLsEqual( + Collections.singletonList(new ACL(ZooDefs.Perms.ALL, new Id(X509AuthenticationUtil.X509_SCHEME, crossDomain))), + returnedList + ); + } + + @Test + public void testSuperUserId() throws KeeperException.InvalidACLException { + // User provided ACL list will be honored for super users. + // No additional ACLs to be set to the znodes besides the user provided ACL list + List returnedList = PrepRequestProcessor.fixupACL(testPath, superUserAuthInfo, aclList); + assertACLsEqual(aclList, returnedList); + } + + @Test + public void testSingleDomainUser() throws KeeperException.InvalidACLException { + // User provided ACL list will not be honored for single domain users. + // (x509 : domain name) will be set to the znodes + List returnedList = PrepRequestProcessor.fixupACL(testPath, singleDomainAuthInfo, aclList); + assertACLsEqual(Collections.singletonList(new ACL(ZooDefs.Perms.ALL, singleDomainAuthInfo.get(0))), returnedList); + } + + @Test + public void testDedicatedServer() throws KeeperException.InvalidACLException { + // Should route to original fixupACL logic + withProperty(X509AuthenticationConfig.DEDICATED_DOMAIN, dedicatedDomain, () -> { + List returnedList = + PrepRequestProcessor.fixupACL(testPath, dedicatedDomainAuthInfo, aclList); + assertACLsEqual(aclList, returnedList); + }); + } + + @Test + public void testOpenReadPaths() throws KeeperException.InvalidACLException { + // Should add (world: anyone, r) to returned ACL list + withProperty(X509AuthenticationConfig.OPEN_READ_ACCESS_PATH_PREFIX, testPath, () -> { + List returnedList = PrepRequestProcessor.fixupACL(testPath, singleDomainAuthInfo, aclList); + List expected = new ArrayList<>(); + expected.add(new ACL(ZooDefs.Perms.READ, ZooDefs.Ids.ANYONE_ID_UNSAFE)); + expected.add(new ACL(ZooDefs.Perms.ALL, singleDomainAuthInfo.get(0))); + assertACLsEqual(expected, returnedList); + }); + } + + @Test + public void testMultiId() throws KeeperException.InvalidACLException { + // User provided ACL list will not be honored for single domain users. + // One ACL of (x509 : domain name) for each of the Id in authInfo will be set to the znodes + List returnedList = PrepRequestProcessor.fixupACL(testPath, multiIdAuthInfo, aclList); + List expectedList = multiIdAuthInfo.stream() + .map(id -> new ACL(ZooDefs.Perms.ALL, id)) + .collect(Collectors.toList()); + assertACLsEqual(expectedList, returnedList); + } + + @Test + public void testNonX509ZnodeGroupAclUser() throws KeeperException.InvalidACLException { + // Should route to original fixupACL logic + List returnedList = PrepRequestProcessor.fixupACL(testPath, nonX509AuthInfo, aclList); + assertACLsEqual(aclList, returnedList); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + public void testOpenReadPreservesNonOverriddenOwnershipAcl(boolean superUser) throws KeeperException.InvalidACLException { + withProperty(X509AuthenticationConfig.OPEN_READ_ACCESS_PATH_PREFIX, testPath, () -> { + List privateAcl = Collections.singletonList(new ACL(ZooDefs.Perms.ALL, new Id("x509", "CN=owner"))); + List returned = PrepRequestProcessor.fixupACL( + testPath, superUser ? superUserAuthInfo : nonX509AuthInfo, privateAcl); + List expected = new ArrayList<>(privateAcl); + expected.add(new ACL(ZooDefs.Perms.READ, ZooDefs.Ids.ANYONE_ID_UNSAFE)); + assertACLsEqual(expected, returned); + }); + } + + @Test + public void testOpenReadStillValidatesAndExpandsNonX509Acl() throws KeeperException.InvalidACLException { + withProperty(X509AuthenticationConfig.OPEN_READ_ACCESS_PATH_PREFIX, "/", () -> { + Id owner = new Id("digest", "example:hash"); + List authInfo = Collections.singletonList(owner); + List expected = new ArrayList<>(); + expected.add(new ACL(ZooDefs.Perms.ALL, owner)); + expected.add(new ACL(ZooDefs.Perms.READ, ZooDefs.Ids.ANYONE_ID_UNSAFE)); + assertACLsEqual(expected, PrepRequestProcessor.fixupACL(testPath, authInfo, ZooDefs.Ids.CREATOR_ALL_ACL)); + Assert.assertThrows(KeeperException.InvalidACLException.class, () -> PrepRequestProcessor.fixupACL( + testPath, authInfo, Collections.singletonList(new ACL(ZooDefs.Perms.ALL, new Id("unknown", "owner"))))); + }); + } + + @ParameterizedTest + @CsvSource({"true,true,false,/private", "true,false,false,/", "false,true,false,/", "true,true,true,/"}) + public void testOpenReadRequiresMatchingPathAndActiveGroupProcessing( + boolean groupProvider, boolean automatic, boolean dedicated, String prefix) throws KeeperException.InvalidACLException { + withProperty("zookeeper.authProvider.x509", + (groupProvider ? X509ZNodeGroupAclProvider.class : X509AuthenticationProvider.class).getCanonicalName(), () -> { + ProviderRegistry.reset(); + withProperty(X509AuthenticationConfig.SET_X509_CLIENT_ID_AS_ACL, Boolean.toString(automatic), () -> { + withProperty(X509AuthenticationConfig.DEDICATED_DOMAIN, dedicated ? dedicatedDomain : "", () -> { + withProperty(X509AuthenticationConfig.OPEN_READ_ACCESS_PATH_PREFIX, prefix, () -> { + List privateAcl = Collections.singletonList(new ACL(ZooDefs.Perms.ALL, new Id("x509", "CN=owner"))); + assertACLsEqual(privateAcl, PrepRequestProcessor.fixupACL(testPath, superUserAuthInfo, privateAcl)); + }); + }); + }); + }); + } + + @Test + public void testAllowedClientIdAsAclDomains() throws KeeperException.InvalidACLException { + withProperty(X509AuthenticationConfig.SET_X509_CLIENT_ID_AS_ACL, "false", () -> { + withProperty(X509AuthenticationConfig.ALLOWED_CLIENT_ID_AS_ACL_DOMAINS, "d0,d1", () -> { + // setClientIdAsACL is disabled but d0 and d1 appear in the allowlist so the returned ACL should contain d0 and + // d1 but not d2. + List authInfo = new ArrayList<>(); + List input = new ArrayList<>(); + for (int i = 0; i < 3; i++) { + Id id = new Id(X509AuthenticationUtil.X509_SCHEME, "d" + i); + authInfo.add(id); + input.add(new ACL(ZooDefs.Perms.ALL, id)); + } + List expected = input.subList(0, 2); + List returnedList = PrepRequestProcessor.fixupACL(testPath, authInfo, input); + assertACLsEqual(expected, returnedList); + }); + }); + } + + private static void assertACLsEqual(Collection expected, Collection actual) { + Assert.assertEquals(new HashSet<>(expected), new HashSet<>(actual)); + } + + private static void withProperty(String key, String value, Callable callable) throws KeeperException.InvalidACLException { + String oldValue = System.setProperty(key, value); + // Reset the config to ensure it picks up the new property value + X509AuthenticationConfig.reset(); + try { + callable.call(); + } finally { + if (oldValue != null) { + System.setProperty(key, oldValue); + } else { + System.clearProperty(key); + } + } + } + + private interface Callable { + void call() throws KeeperException.InvalidACLException; + } +} diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/auth/znode/groupacl/X509GroupAclIntegrationTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/auth/znode/groupacl/X509GroupAclIntegrationTest.java new file mode 100644 index 00000000000..e304b0f976b --- /dev/null +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/auth/znode/groupacl/X509GroupAclIntegrationTest.java @@ -0,0 +1,376 @@ +/* + * 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.zookeeper.server.auth.znode.groupacl; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyPair; +import java.security.KeyStore; +import java.security.Security; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import org.apache.zookeeper.AddWatchMode; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.PortAssignment; +import org.apache.zookeeper.WatchedEvent; +import org.apache.zookeeper.Watcher; +import org.apache.zookeeper.ZKTestCase; +import org.apache.zookeeper.ZKUtil; +import org.apache.zookeeper.ZooDefs; +import org.apache.zookeeper.ZooKeeper; +import org.apache.zookeeper.client.ZKClientConfig; +import org.apache.zookeeper.common.ClientX509Util; +import org.apache.zookeeper.common.X509TestHelpers; +import org.apache.zookeeper.data.ACL; +import org.apache.zookeeper.data.Id; +import org.apache.zookeeper.server.NIOServerCnxnFactory; +import org.apache.zookeeper.server.NettyServerCnxnFactory; +import org.apache.zookeeper.server.ServerCnxn; +import org.apache.zookeeper.server.ServerCnxnFactory; +import org.apache.zookeeper.server.ZooKeeperServer; +import org.apache.zookeeper.server.auth.ProviderRegistry; +import org.apache.zookeeper.server.auth.X509AuthenticationConfig; +import org.apache.zookeeper.test.ClientBase; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +/** Real CA-signed certificates, Netty TLS, clients and persistent mapping watches. */ +public class X509GroupAclIntegrationTest extends ZKTestCase { + private static final String ROOT = "/zookeeper/uri-domain-map"; + private static final String PASSWORD = "testpass"; + private final Map savedProperties = new HashMap<>(); + private final List clients = new ArrayList<>(); + private final Map keyStores = new HashMap<>(); + private final Map> states = new HashMap<>(); + private ClientX509Util x509; + private ZooKeeperServer server; + private NIOServerCnxnFactory adminFactory; + private NettyServerCnxnFactory tlsFactory; + private ZooKeeper admin; + private String tlsAddress; + private static boolean addedProvider; + + @BeforeAll + public static void registerProvider() { + if (Security.getProvider("BC") == null) { + Security.addProvider(new BouncyCastleProvider()); + addedProvider = true; + } + } + + @AfterAll + public static void removeProvider() { + if (addedProvider) { + Security.removeProvider("BC"); + } + } + + private void property(String key, String value) { + if (!savedProperties.containsKey(key)) { + savedProperties.put(key, System.getProperty(key)); + } + System.setProperty(key, value); + } + + private void start(boolean unified, boolean automatic) throws Exception { + X509AuthenticationConfig.reset(); + File directory = ClientBase.createTmpDir(); + KeyPair caKey = X509TestHelpers.generateRSAKeyPair(); + X509Certificate ca = X509TestHelpers.newSelfSignedCACert(new X500Name("CN=P03 test CA"), caKey, 86400000); + Path trustStore = directory.toPath().resolve("trust.jks"); + KeyStore trust = KeyStore.getInstance("JKS"); + trust.load(null, PASSWORD.toCharArray()); + trust.setCertificateEntry("ca", ca); + try (OutputStream out = Files.newOutputStream(trustStore)) { + trust.store(out, PASSWORD.toCharArray()); + } + for (String name : new String[]{"server", "alice", "bob", "super"}) { + KeyPair key = X509TestHelpers.generateRSAKeyPair(); + GeneralNames sans = new GeneralNames(new GeneralName[]{ + new GeneralName(GeneralName.dNSName, "localhost"), + new GeneralName(GeneralName.iPAddress, "127.0.0.1"), + new GeneralName(GeneralName.uniformResourceIdentifier, "urn:example:" + name)}); + X509Certificate cert = X509TestHelpers.newCertWithSans( + ca, caKey, new X500Name("CN=" + name), key.getPublic(), sans, 86400000); + KeyStore store = KeyStore.getInstance("JKS"); + store.load(null, PASSWORD.toCharArray()); + store.setKeyEntry(name, key.getPrivate(), PASSWORD.toCharArray(), new Certificate[]{cert, ca}); + Path path = directory.toPath().resolve(name + ".jks"); + try (OutputStream out = Files.newOutputStream(path)) { + store.store(out, PASSWORD.toCharArray()); + } + keyStores.put(name, path); + } + x509 = new ClientX509Util(); + property(x509.getSslKeystoreLocationProperty(), keyStores.get("server").toString()); + property(x509.getSslKeystorePasswdProperty(), PASSWORD); + property(x509.getSslKeystoreTypeProperty(), "JKS"); + property(x509.getSslTruststoreLocationProperty(), trustStore.toString()); + property(x509.getSslTruststorePasswdProperty(), PASSWORD); + property(x509.getSslTruststoreTypeProperty(), "JKS"); + property(x509.getSslHostnameVerificationEnabledProperty(), "true"); + property("zookeeper.authProvider.x509", X509ZNodeGroupAclProvider.class.getName()); + property(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_TYPE, "SAN"); + property(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_MATCH_TYPE, "6"); + property(X509AuthenticationConfig.ZOOKEEPER_ZNODEGROUPACL_SUPERUSER_ID, "urn:example:super"); + if (automatic) { + property(X509AuthenticationConfig.SET_X509_CLIENT_ID_AS_ACL, "true"); + } + property(NettyServerCnxnFactory.PORT_UNIFICATION_KEY, Boolean.toString(unified)); + ProviderRegistry.reset(); + server = new ZooKeeperServer(directory, directory, 3000); + adminFactory = new NIOServerCnxnFactory(); + adminFactory.configure(new InetSocketAddress("127.0.0.1", PortAssignment.unique()), 20, -1, false); + adminFactory.startup(server); + admin = ClientBase.createZKClient("127.0.0.1:" + adminFactory.getLocalPort()); + property(ServerCnxnFactory.ZOOKEEPER_SERVER_CNXN_FACTORY, NettyServerCnxnFactory.class.getName()); + tlsFactory = (NettyServerCnxnFactory) ServerCnxnFactory.createFactory(); + tlsFactory.configure(new InetSocketAddress("127.0.0.1", PortAssignment.unique()), 20, -1, !unified); + tlsFactory.startup(server, false); + tlsAddress = "127.0.0.1:" + tlsFactory.getLocalPort(); + } + + private ZooKeeper connect(String name, Watcher watcher) throws Exception { + ZKClientConfig config = new ZKClientConfig(); + config.setProperty(ZKClientConfig.SECURE_CLIENT, "true"); + config.setProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET, "org.apache.zookeeper.ClientCnxnSocketNetty"); + config.setProperty(x509.getSslKeystoreLocationProperty(), keyStores.get(name).toString()); + LinkedBlockingQueue events = new LinkedBlockingQueue<>(); + ZooKeeper client = new ZooKeeper(tlsAddress, 15000, event -> { + if (event.getType() == Watcher.Event.EventType.None) { + events.add(event.getState()); + } + watcher.process(event); + }, config); + clients.add(client); + states.put(client, events); + return client; + } + + private ZooKeeper connect(String name) throws Exception { + CountDownLatch connected = new CountDownLatch(1); + ZooKeeper client = connect(name, event -> { + if (event.getState() == Watcher.Event.KeeperState.SyncConnected) { + connected.countDown(); + } + }); + assertTrue(connected.await(10, TimeUnit.SECONDS), "TLS client did not connect: " + name); + return client; + } + + private void map(String domain, String name) throws Exception { + for (String path : new String[]{ROOT, ROOT + "/" + domain, ROOT + "/" + domain + "/urn:example:" + name}) { + if (admin.exists(path, false) == null) { + admin.create(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + } + } + } + + private List acl(String id) { + return Collections.singletonList(new ACL(ZooDefs.Perms.ALL, new Id("x509", id))); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + public void testMappingLifecycleAndReadAuthorization(boolean unified) throws Exception { + start(unified, true); + assertNull(admin.exists(ROOT, false)); + ZooKeeper alice = connect("alice"); + assertNull(admin.exists(ROOT, false), "authentication must not create the mapping root"); + alice.create("/unmapped", new byte[]{1}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + assertEquals(acl("urn:example:alice"), alice.getACL("/unmapped", null)); + map("teamA", "alice"); + map("teamB", "bob"); + alice.create("/owned", new byte[]{2}, ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT); + assertEquals(acl("teamA"), alice.getACL("/owned", null)); + ZooKeeper bob = connect("bob"); + assertThrows(KeeperException.NoAuthException.class, () -> bob.getData("/owned", true, null)); + assertThrows(KeeperException.NoAuthException.class, () -> bob.getChildren("/owned", true)); + assertThrows(KeeperException.NoAuthException.class, () -> bob.exists("/owned", true)); + assertThrows(KeeperException.NoAuthException.class, () -> bob.setData("/owned", new byte[]{3}, -1)); + alice.setACL("/owned", ZooDefs.Ids.OPEN_ACL_UNSAFE, -1); + assertEquals(acl("teamA"), alice.getACL("/owned", null), "automatic ACL must not become world writable"); + + ZooKeeper superUser = connect("super"); + LinkedBlockingQueue events = new LinkedBlockingQueue<>(); + bob.addWatch("/", event -> { + if (event.getType() != Watcher.Event.EventType.None) { + events.add(event); + } + }, AddWatchMode.PERSISTENT_RECURSIVE); + superUser.setData("/owned", new byte[]{4}, -1); + superUser.create("/barrier", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + WatchedEvent event = events.poll(10, TimeUnit.SECONDS); + assertNotNull(event); + assertEquals("/barrier", event.getPath(), "a denied READ watch must not disclose /owned"); + assertNull(events.poll(200, TimeUnit.MILLISECONDS)); + + map("teamA", "bob"); + assertArrayEquals(new byte[]{4}, bob.getData("/owned", false, null)); + admin.delete(ROOT + "/teamA/urn:example:bob", -1); + assertThrows(KeeperException.NoAuthException.class, () -> bob.getData("/owned", false, null)); + long sessionId = alice.getSessionId(); + states.values().forEach(LinkedBlockingQueue::clear); + tlsFactory.closeAll(ServerCnxn.DisconnectReason.CHANNEL_DISCONNECTED); + for (ZooKeeper client : clients) { + assertEquals(Watcher.Event.KeeperState.Disconnected, states.get(client).poll(10, TimeUnit.SECONDS)); + assertEquals(Watcher.Event.KeeperState.SyncConnected, states.get(client).poll(10, TimeUnit.SECONDS)); + } + assertEquals(sessionId, alice.getSessionId()); + assertArrayEquals(new byte[]{4}, alice.getData("/owned", false, null)); + assertThrows(KeeperException.NoAuthException.class, () -> bob.getData("/owned", false, null)); + + ZKUtil.deleteRecursive(admin, ROOT); + assertThrows(KeeperException.NoAuthException.class, () -> alice.getData("/owned", false, null)); + map("teamA", "alice"); + assertArrayEquals(new byte[]{4}, alice.getData("/owned", false, null)); + superUser.setACL("/owned", ZooDefs.Ids.OPEN_ACL_UNSAFE, -1); + assertArrayEquals(new byte[]{4}, bob.getData("/owned", false, null)); + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + public void testSuperUserOpenReadPreservesOwnershipOnCreateAndSetAcl(boolean unified) throws Exception { + property(X509AuthenticationConfig.OPEN_READ_ACCESS_PATH_PREFIX, "/"); + start(unified, true); + map("teamA", "alice"); + map("teamB", "bob"); + ZooKeeper superUser = connect("super"); + ZooKeeper alice = connect("alice"); + ZooKeeper bob = connect("bob"); + List ownerAcl = acl("teamA"); + List expected = new ArrayList<>(ownerAcl); + expected.add(new ACL(ZooDefs.Perms.READ, ZooDefs.Ids.ANYONE_ID_UNSAFE)); + superUser.create("/owned", new byte[]{1}, ownerAcl, CreateMode.PERSISTENT); + assertEquals(new HashSet<>(expected), new HashSet<>(superUser.getACL("/owned", null))); + assertArrayEquals(new byte[]{1}, bob.getData("/owned", false, null)); + assertThrows(KeeperException.NoAuthException.class, () -> bob.setData("/owned", new byte[]{2}, -1)); + assertThrows(KeeperException.NoAuthException.class, () -> bob.setACL("/owned", ownerAcl, -1)); + alice.setData("/owned", new byte[]{3}, -1); + + superUser.setACL("/owned", acl("teamB"), -1); + expected = new ArrayList<>(acl("teamB")); + expected.add(new ACL(ZooDefs.Perms.READ, ZooDefs.Ids.ANYONE_ID_UNSAFE)); + assertEquals(new HashSet<>(expected), new HashSet<>(superUser.getACL("/owned", null))); + assertArrayEquals(new byte[]{3}, alice.getData("/owned", false, null)); + assertThrows(KeeperException.NoAuthException.class, () -> alice.setData("/owned", new byte[]{4}, -1)); + assertThrows(KeeperException.NoAuthException.class, () -> alice.setACL("/owned", ownerAcl, -1)); + bob.setData("/owned", new byte[]{5}, -1); + assertArrayEquals(new byte[]{5}, alice.getData("/owned", false, null)); + } + + @ParameterizedTest + @CsvSource({"false,true", "true,true", "false,false", "true,false"}) + public void testDedicatedDomainFiltering(boolean unified, boolean enforce) throws Exception { + property(X509AuthenticationConfig.DEDICATED_DOMAIN, "teamA"); + property(X509AuthenticationConfig.ENFORCE_DEDICATED_DOMAIN, Boolean.toString(enforce)); + start(unified, false); + map("teamA", "alice"); + ZooKeeper alice = connect("alice"); + alice.create("/open", new byte[]{1}, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + ZooKeeper superUser = connect("super"); + assertArrayEquals(new byte[]{1}, superUser.getData("/open", false, null)); + CountDownLatch connected = new CountDownLatch(1); + ZooKeeper bob = connect("bob", event -> { + if (event.getState() == Watcher.Event.KeeperState.SyncConnected) { + connected.countDown(); + } + }); + if (enforce) { + assertFalse(connected.await(2, TimeUnit.SECONDS), "wrong-domain client must be disconnected"); + } else { + assertTrue(connected.await(10, TimeUnit.SECONDS)); + assertArrayEquals(new byte[]{1}, bob.getData("/open", false, null)); + } + } + + @ParameterizedTest + @ValueSource(booleans = {false, true}) + public void testAutomaticAclDisabledByDefault(boolean unified) throws Exception { + start(unified, false); + map("teamA", "alice"); + ZooKeeper alice = connect("alice"); + alice.create("/open", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + assertEquals(ZooDefs.Ids.OPEN_ACL_UNSAFE, alice.getACL("/open", null)); + alice.create("/creator", null, ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT); + assertEquals(acl("teamA"), alice.getACL("/creator", null)); + } + + @AfterEach + public void tearDown() throws Exception { + try { + for (ZooKeeper client : clients) { + client.close(); + } + if (admin != null) { + admin.close(); + } + if (tlsFactory != null) { + tlsFactory.shutdown(); + } + if (adminFactory != null) { + adminFactory.shutdown(); + } + if (server != null) { + server.shutdown(); + server.getZKDatabase().close(); + } + } finally { + if (x509 != null) { + x509.close(); + } + savedProperties.forEach((key, value) -> { + if (value == null) { + System.clearProperty(key); + } else { + System.setProperty(key, value); + } + }); + X509AuthenticationConfig.reset(); + ProviderRegistry.reset(); + } + } +} diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/auth/znode/groupacl/X509ZNodeGroupAclProviderTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/auth/znode/groupacl/X509ZNodeGroupAclProviderTest.java new file mode 100644 index 00000000000..49aed6d9e32 --- /dev/null +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/auth/znode/groupacl/X509ZNodeGroupAclProviderTest.java @@ -0,0 +1,380 @@ +/* + * 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.zookeeper.server.auth.znode.groupacl; + +import java.net.InetSocketAddress; +import java.security.cert.X509Certificate; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.PortAssignment; +import org.apache.zookeeper.ZKTestCase; +import org.apache.zookeeper.ZKUtil; +import org.apache.zookeeper.ZooDefs; +import org.apache.zookeeper.ZooKeeper; +import org.apache.zookeeper.data.Id; +import org.apache.zookeeper.server.MockServerCnxn; +import org.apache.zookeeper.server.NIOServerCnxnFactory; +import org.apache.zookeeper.server.ServerCnxn; +import org.apache.zookeeper.server.ZooKeeperServer; +import org.apache.zookeeper.server.auth.ServerAuthenticationProvider; +import org.apache.zookeeper.server.auth.X509AuthenticationConfig; +import org.apache.zookeeper.test.ClientBase; +import org.apache.zookeeper.test.X509AuthTest; +import org.junit.Assert; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class X509ZNodeGroupAclProviderTest extends ZKTestCase { + private static final Logger LOG = LoggerFactory.getLogger(X509ZNodeGroupAclProviderTest.class); + private static final String HOSTPORT = "127.0.0.1:" + PortAssignment.unique(); + private static X509AuthTest.TestCertificate domainXCert; + private static X509AuthTest.TestCertificate superCert; + private static X509AuthTest.TestCertificate superCert2; + private static X509AuthTest.TestCertificate unknownCert; + private static X509AuthTest.TestCertificate crossDomainCert; + private static final String CLIENT_CERT_ID_SAN_MATCH_TYPE = "6"; + private static final String SCHEME = "x509"; + private static ZooKeeperServer zks; + private TestNIOServerCnxnFactory serverCnxnFactory; + private ZooKeeper admin; + private static final String AUTH_PROVIDER_PROPERTY_NAME = "zookeeper.authProvider.x509"; + private static final String CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH = "/zookeeper/uri-domain-map"; + private static final String[] MAPPING_PATHS = {CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH, + CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/CrossDomain", + CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/CrossDomain/CrossDomainUser", + CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/DomainX", + CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/DomainX/DomainXUser", + CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/DomainY", + CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/DomainY/DomainYUser"}; + private static final Map SYSTEM_PROPERTIES = new HashMap<>(); + static { + SYSTEM_PROPERTIES.put(X509AuthenticationConfig.ZOOKEEPER_ZNODEGROUPACL_SUPERUSER_ID, "SuperUser,SuperUser2"); + SYSTEM_PROPERTIES.put("zookeeper.ssl.keyManager", "org.apache.zookeeper.test.X509AuthTest.TestKeyManager"); + SYSTEM_PROPERTIES.put("zookeeper.ssl.trustManager", "org.apache.zookeeper.test.X509AuthTest.TestTrustManager"); + SYSTEM_PROPERTIES.put(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_TYPE, X509AuthenticationConfig.SUBJECT_ALTERNATIVE_NAME_SHORT); + SYSTEM_PROPERTIES.put(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_MATCH_TYPE, CLIENT_CERT_ID_SAN_MATCH_TYPE); + SYSTEM_PROPERTIES.put(AUTH_PROVIDER_PROPERTY_NAME, X509ZNodeGroupAclProvider.class.getCanonicalName()); + SYSTEM_PROPERTIES.put(X509AuthenticationConfig.CROSS_DOMAIN_ACCESS_DOMAIN_NAME, "CrossDomain"); + } + + @BeforeEach + public void setUp() throws Exception { + X509AuthenticationConfig.reset(); + for (Map.Entry property : SYSTEM_PROPERTIES.entrySet()) { + System.setProperty(property.getKey(), property.getValue()); + } + LOG.info("Starting Zk..."); + zks = new ZooKeeperServer(testBaseDir, testBaseDir, 3000); + final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]); + serverCnxnFactory = new TestNIOServerCnxnFactory(); + serverCnxnFactory.configure(new InetSocketAddress(PORT), -1, -1); + serverCnxnFactory.startup(zks); + LOG.info("Waiting for server startup"); + Assert.assertTrue("waiting for server being up ", ClientBase.waitForServerUp(HOSTPORT, 300000)); + admin = ClientBase.createZKClient(HOSTPORT); + try { + ZKUtil.deleteRecursive(admin, CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH); + } catch (Exception ignored) { + } + + // Create test client certificates + domainXCert = new X509AuthTest.TestCertificate("CLIENT", "DomainXUser"); + superCert = new X509AuthTest.TestCertificate("SUPER", "SuperUser"); + superCert2 = new X509AuthTest.TestCertificate("SUPER", "SuperUser2"); + unknownCert = new X509AuthTest.TestCertificate("UNKNOWN", "UnknownUser"); + crossDomainCert = new X509AuthTest.TestCertificate("CLIENT", "CrossDomainUser"); + + // Create Client URI - domain mapping znodes + for (String path : MAPPING_PATHS) { + // Create ACL metadata + admin.create(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + } + } + + @AfterEach + public void cleanUp() throws InterruptedException, KeeperException { + LOG.info("X509ZNodeGroupAclProviderTest::cleanUp() called!"); + X509AuthenticationConfig.reset(); + ZKUtil.deleteRecursive(admin, CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH); + zks.shutdown(); + admin.close(); + serverCnxnFactory.shutdown(); + for (Map.Entry property : SYSTEM_PROPERTIES.entrySet()) { + System.clearProperty(property.getKey()); + } + System.clearProperty(X509AuthenticationConfig.DEDICATED_DOMAIN); + System.clearProperty(X509AuthenticationConfig.ENFORCE_DEDICATED_DOMAIN); + System.clearProperty(X509AuthenticationConfig.STORE_AUTHED_CLIENT_ID); + } + + @Test + public void testUntrustedClient() { + X509ZNodeGroupAclProvider provider = createProvider(domainXCert); + MockServerCnxn cnxn = new MockServerCnxn(); + cnxn.clientChain = new X509Certificate[]{unknownCert}; + Assert.assertEquals(KeeperException.Code.AUTHFAILED, provider + .handleAuthentication(new ServerAuthenticationProvider.ServerObjs(zks, cnxn), new byte[0])); + } + + @Test + public void testAuthorizedClient() { + X509ZNodeGroupAclProvider provider = createProvider(domainXCert); + MockServerCnxn cnxn = new MockServerCnxn(); + cnxn.clientChain = new X509Certificate[]{domainXCert}; + Assert.assertEquals(KeeperException.Code.OK, provider + .handleAuthentication(new ServerAuthenticationProvider.ServerObjs(zks, cnxn), new byte[0])); + List authInfo = cnxn.getAuthInfo(); + Assert.assertEquals(1, authInfo.size()); + Assert.assertEquals(SCHEME, authInfo.get(0).getScheme()); + Assert.assertEquals("DomainX", authInfo.get(0).getId()); + } + + @Test + public void testUnauthorizedClient() { + X509ZNodeGroupAclProvider provider = createProvider(unknownCert); + MockServerCnxn cnxn = new MockServerCnxn(); + cnxn.clientChain = new X509Certificate[]{unknownCert}; + Assert.assertEquals(KeeperException.Code.OK, provider + .handleAuthentication(new ServerAuthenticationProvider.ServerObjs(zks, cnxn), new byte[0])); + List authInfo = cnxn.getAuthInfo(); + Assert.assertEquals(1, authInfo.size()); + Assert.assertEquals(SCHEME, authInfo.get(0).getScheme()); + Assert.assertEquals("UnknownUser", authInfo.get(0).getId()); + } + + @Test + public void testSuperUser() { + // Belong to super user domain + X509ZNodeGroupAclProvider provider = createProvider(crossDomainCert); + MockServerCnxn cnxn = new MockServerCnxn(); + cnxn.clientChain = new X509Certificate[]{crossDomainCert}; + Assert.assertEquals(KeeperException.Code.OK, provider + .handleAuthentication(new ServerAuthenticationProvider.ServerObjs(zks, cnxn), new byte[0])); + List authInfo = cnxn.getAuthInfo(); + Assert.assertEquals(1, authInfo.size()); + Assert.assertEquals("super", authInfo.get(0).getScheme()); + Assert.assertEquals("CrossDomain", authInfo.get(0).getId()); + + // Directly set multiple service principals in config as super user + // 1st super user + provider = createProvider(superCert); + cnxn = new MockServerCnxn(); + cnxn.clientChain = new X509Certificate[]{superCert}; + Assert.assertEquals(KeeperException.Code.OK, provider + .handleAuthentication(new ServerAuthenticationProvider.ServerObjs(zks, cnxn), new byte[0])); + authInfo = cnxn.getAuthInfo(); + Assert.assertEquals(1, authInfo.size()); + Assert.assertEquals("super", authInfo.get(0).getScheme()); + Assert.assertEquals("SuperUser", authInfo.get(0).getId()); + + // 2nd super user + provider = createProvider(superCert2); + cnxn = new MockServerCnxn(); + cnxn.clientChain = new X509Certificate[]{superCert2}; + Assert.assertEquals(KeeperException.Code.OK, provider + .handleAuthentication(new ServerAuthenticationProvider.ServerObjs(zks, cnxn), new byte[0])); + authInfo = cnxn.getAuthInfo(); + Assert.assertEquals(1, authInfo.size()); + Assert.assertEquals("super", authInfo.get(0).getScheme()); + Assert.assertEquals("SuperUser2", authInfo.get(0).getId()); + } + + @Test + public void testAuthInfoAutoUpdate() throws InterruptedException, KeeperException { + String clientId = "DomainZUser"; + X509AuthTest.TestCertificate domainZCert = new X509AuthTest.TestCertificate("CLIENT", clientId); + String oldDomain = CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/DomainZ"; + String newDomain = CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/DomainZN"; + + admin.create(oldDomain, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + admin.create(oldDomain + "/" + clientId, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + + // Test with original domain info + X509ZNodeGroupAclProvider provider = createProvider(domainZCert); + MockServerCnxn cnxn = new MockServerCnxn(); + + // Inject the new connection to factory so it's AuthInfo will be auto-refreshed. + serverCnxnFactory.getClients().add(cnxn); + + // Check the original status. + cnxn.clientChain = new X509Certificate[]{domainZCert}; + Assert.assertEquals(KeeperException.Code.OK, provider + .handleAuthentication(new ServerAuthenticationProvider.ServerObjs(zks, cnxn), new byte[0])); + List authInfo = cnxn.getAuthInfo(); + Assert.assertEquals(1, authInfo.size()); + Assert.assertEquals(SCHEME, authInfo.get(0).getScheme()); + Assert.assertEquals("DomainZ", authInfo.get(0).getId()); + + // Add new domain info. + admin.create(newDomain, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + admin.create(newDomain + "/" + clientId, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + waitFor("AuthInfo is not updated after new domain created.", () -> { + return cnxn.getAuthInfo().size() == 2; + }, 3); + + // Remove the original domain info + admin.delete(oldDomain + "/" + clientId, -1); + admin.delete(oldDomain, -1); + waitFor("AuthInfo is not updated after old domain removed.", () -> { + List newAuthInfo = cnxn.getAuthInfo(); + return 1 == newAuthInfo.size() + && SCHEME.equals(newAuthInfo.get(0).getScheme()) + && newAuthInfo.get(0).getId().equals("DomainZN"); + }, 3); + } + + @Test + public void testConnectionFiltering() { + // Single domain user + System.setProperty(X509AuthenticationConfig.DEDICATED_DOMAIN, "DomainX"); + X509ZNodeGroupAclProvider provider = createProvider(domainXCert); + MockServerCnxn cnxn = new MockServerCnxn(); + cnxn.clientChain = new X509Certificate[]{domainXCert}; + Assert.assertEquals(KeeperException.Code.OK, provider + .handleAuthentication(new ServerAuthenticationProvider.ServerObjs(zks, cnxn), new byte[0])); + List authInfo = cnxn.getAuthInfo(); + Assert.assertEquals(1, authInfo.size()); + Assert.assertEquals(SCHEME, authInfo.get(0).getScheme()); + Assert.assertEquals("DomainXUser", authInfo.get(0).getId()); + + // Non-authorized user (connection filtering enforced) + ClosableMockServerCnxn closableMockServerCnxn = new ClosableMockServerCnxn(); + closableMockServerCnxn.clientChain = new X509Certificate[]{domainXCert}; + System.clearProperty(X509AuthenticationConfig.DEDICATED_DOMAIN); + System.setProperty(X509AuthenticationConfig.DEDICATED_DOMAIN, "DomainY"); + X509AuthenticationConfig.reset(); + provider = createProvider(domainXCert); + provider + .handleAuthentication(new ServerAuthenticationProvider.ServerObjs(zks, closableMockServerCnxn), new byte[0]); + Assert.assertTrue(closableMockServerCnxn.isClosed()); + System.clearProperty(X509AuthenticationConfig.DEDICATED_DOMAIN); + + // Non-authorized user (connection filtering not enforced) + closableMockServerCnxn = new ClosableMockServerCnxn(); + closableMockServerCnxn.clientChain = new X509Certificate[]{domainXCert}; + System.setProperty(X509AuthenticationConfig.DEDICATED_DOMAIN, "DomainY"); + System.setProperty(X509AuthenticationConfig.ENFORCE_DEDICATED_DOMAIN, "false"); + X509AuthenticationConfig.reset(); + provider = createProvider(domainXCert); + provider + .handleAuthentication(new ServerAuthenticationProvider.ServerObjs(zks, closableMockServerCnxn), new byte[0]); + Assert.assertFalse(closableMockServerCnxn.isClosed()); + System.clearProperty(X509AuthenticationConfig.DEDICATED_DOMAIN); + System.clearProperty(X509AuthenticationConfig.ENFORCE_DEDICATED_DOMAIN); + + // Super user + provider = createProvider(superCert); + cnxn = new MockServerCnxn(); + cnxn.clientChain = new X509Certificate[]{superCert}; + Assert.assertEquals(KeeperException.Code.OK, provider + .handleAuthentication(new ServerAuthenticationProvider.ServerObjs(zks, cnxn), new byte[0])); + authInfo = cnxn.getAuthInfo(); + Assert.assertEquals(1, authInfo.size()); + Assert.assertEquals("super", authInfo.get(0).getScheme()); + Assert.assertEquals("SuperUser", authInfo.get(0).getId()); + System.clearProperty(X509AuthenticationConfig.DEDICATED_DOMAIN); + + // Cross domain components + provider = createProvider(crossDomainCert); + cnxn = new MockServerCnxn(); + cnxn.clientChain = new X509Certificate[]{crossDomainCert}; + Assert.assertEquals(KeeperException.Code.OK, provider + .handleAuthentication(new ServerAuthenticationProvider.ServerObjs(zks, cnxn), new byte[0])); + authInfo = cnxn.getAuthInfo(); + Assert.assertEquals(1, authInfo.size()); + Assert.assertEquals("super", authInfo.get(0).getScheme()); + Assert.assertEquals("CrossDomain", authInfo.get(0).getId()); + } + + @Test + public void testStoreAuthedClientId() { + System.setProperty(X509AuthenticationConfig.STORE_AUTHED_CLIENT_ID, "true"); + + // Single domain user + X509ZNodeGroupAclProvider provider = createProvider(domainXCert); + MockServerCnxn cnxn = new MockServerCnxn(); + cnxn.clientChain = new X509Certificate[]{domainXCert}; + Assert.assertEquals(KeeperException.Code.OK, provider + .handleAuthentication(new ServerAuthenticationProvider.ServerObjs(zks, cnxn), new byte[0])); + List authInfo = cnxn.getAuthInfo(); + Assert.assertEquals(2, authInfo.size()); + Assert.assertEquals(SCHEME, authInfo.get(0).getScheme()); + Assert.assertEquals("DomainX", authInfo.get(0).getId()); + Assert.assertEquals(SCHEME, authInfo.get(1).getScheme()); + Assert.assertEquals("DomainXUser", authInfo.get(1).getId()); + + // Cross domain component - should be same no matter this feature is on or not + provider = createProvider(crossDomainCert); + cnxn = new MockServerCnxn(); + cnxn.clientChain = new X509Certificate[]{crossDomainCert}; + Assert.assertEquals(KeeperException.Code.OK, provider + .handleAuthentication(new ServerAuthenticationProvider.ServerObjs(zks, cnxn), new byte[0])); + authInfo = cnxn.getAuthInfo(); + Assert.assertEquals(1, authInfo.size()); + Assert.assertEquals("super", authInfo.get(0).getScheme()); + Assert.assertEquals("CrossDomain", authInfo.get(0).getId()); + + // Super user - should be same no matter this feature is on or not + provider = createProvider(superCert); + cnxn = new MockServerCnxn(); + cnxn.clientChain = new X509Certificate[]{superCert}; + Assert.assertEquals(KeeperException.Code.OK, provider + .handleAuthentication(new ServerAuthenticationProvider.ServerObjs(zks, cnxn), new byte[0])); + authInfo = cnxn.getAuthInfo(); + Assert.assertEquals(1, authInfo.size()); + Assert.assertEquals("super", authInfo.get(0).getScheme()); + Assert.assertEquals("SuperUser", authInfo.get(0).getId()); + + System.clearProperty(X509AuthenticationConfig.STORE_AUTHED_CLIENT_ID); + } + + private X509ZNodeGroupAclProvider createProvider(X509Certificate trustedCert) { + return new X509ZNodeGroupAclProvider(new X509AuthTest.TestTrustManager(trustedCert), + new X509AuthTest.TestKeyManager()); + } + + /** + * Special ServerCnxnFactory which Exposes the client list for testing auto-refresh AuthInfo. + */ + class TestNIOServerCnxnFactory extends NIOServerCnxnFactory { + Set getClients() { + return cnxns; + } + } + + private static class ClosableMockServerCnxn extends MockServerCnxn { + private boolean isClosed = false; + + @Override + public void close(DisconnectReason reason) { + isClosed = true; + } + + public boolean isClosed() { + return isClosed; + } + } +} diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/server/auth/znode/groupacl/ZkClientUriDomainMappingHelperTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/server/auth/znode/groupacl/ZkClientUriDomainMappingHelperTest.java new file mode 100644 index 00000000000..e04282d1d7c --- /dev/null +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/server/auth/znode/groupacl/ZkClientUriDomainMappingHelperTest.java @@ -0,0 +1,172 @@ +/* + * 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.zookeeper.server.auth.znode.groupacl; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import org.apache.zookeeper.CreateMode; +import org.apache.zookeeper.DummyWatcher; +import org.apache.zookeeper.KeeperException; +import org.apache.zookeeper.PortAssignment; +import org.apache.zookeeper.ZKTestCase; +import org.apache.zookeeper.ZooDefs; +import org.apache.zookeeper.ZooKeeper; +import org.apache.zookeeper.server.ServerCnxn; +import org.apache.zookeeper.server.ServerCnxnFactory; +import org.apache.zookeeper.server.ZooKeeperServer; +import org.apache.zookeeper.server.watch.WatchesReport; +import org.apache.zookeeper.test.ClientBase; +import org.junit.Assert; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@TestMethodOrder(MethodOrderer.Alphanumeric.class) +public class ZkClientUriDomainMappingHelperTest extends ZKTestCase { + private static final Logger LOG = + LoggerFactory.getLogger(ZkClientUriDomainMappingHelperTest.class); + private static final String HOSTPORT = "127.0.0.1:" + PortAssignment.unique(); + private static final String CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH = "/zookeeper/uri-domain-map"; + private static final int CONNECTION_TIMEOUT = 300000; + private static final String[] MAPPING_PATHS = { + CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH, + CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/bar", + CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/bar/bar0", + CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/bar/bar1", + CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/foo", + CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/foo/foo1", + CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/foo/foo2", + CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/foo/bar1" + }; + + private ZooKeeperServer zookeeperServer; + private ZooKeeper zookeeperClientConnection; + private ServerCnxnFactory serverCnxnFactory; + + @BeforeEach + public void setUp() throws IOException, InterruptedException, KeeperException { + LOG.info("Starting Zk..."); + File dataDir = ClientBase.createTmpDir(); + zookeeperServer = new ZooKeeperServer(dataDir, dataDir, 3000); + final int PORT = Integer.parseInt(HOSTPORT.split(":")[1]); + serverCnxnFactory = ServerCnxnFactory.createFactory(PORT, -1); + serverCnxnFactory.startup(zookeeperServer); + + LOG.info("Waiting for server startup"); + Assert.assertTrue("waiting for server being up ", + ClientBase.waitForServerUp(HOSTPORT, CONNECTION_TIMEOUT)); + zookeeperClientConnection = new ZooKeeper(HOSTPORT, CONNECTION_TIMEOUT, DummyWatcher.INSTANCE); + } + + @AfterEach + public void cleanUp() throws InterruptedException, IOException, KeeperException { + // Delete mapping znodes if they exist + for (int i = MAPPING_PATHS.length - 1; i >= 0; i--) { + if (zookeeperClientConnection.exists(MAPPING_PATHS[i], null) != null) { + zookeeperClientConnection.delete(MAPPING_PATHS[i], -1); + } + } + + + if (zookeeperClientConnection != null) { + zookeeperClientConnection.close(); + zookeeperClientConnection = null; + } + if (serverCnxnFactory != null) { + serverCnxnFactory.closeAll(ServerCnxn.DisconnectReason.SERVER_SHUTDOWN); + serverCnxnFactory.shutdown(); + serverCnxnFactory = null; + } + if (zookeeperServer != null) { + zookeeperServer.getZKDatabase().close(); + zookeeperServer.shutdown(); + zookeeperServer = null; + } + Assert.assertTrue("waiting for ZK server to shutdown", + ClientBase.waitForServerDown(HOSTPORT, CONNECTION_TIMEOUT)); + } + + /** + * Create a dummy mapping and verify that the helper correctly updates changes to the mapping + * stored in ZNodes. + * + * The following mapping will be used + * . (root) + * └── _CLIENT_URI_DOMAIN_MAPPING (mapping root path) + * ├── bar (application domain) + * │ ├── bar0 (client URI) + * │ └── bar1 (client URI) + * └── foo (application domain) + * ├── foo1 (client URI) + * ├── foo2 (client URI) + * └── bar1 (client URI) + */ + @Test + public void testA_ZkClientUriDomainMappingHelper() throws KeeperException, InterruptedException { + for (String path : MAPPING_PATHS) { + zookeeperClientConnection + .create(path, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + } + + ClientUriDomainMappingHelper helper = new ZkClientUriDomainMappingHelper(zookeeperServer); + + // For bar0, we should only get foo + Assert.assertEquals(Collections.singleton("bar"), helper.getDomains("bar0")); + + // For bar1, we should get bar and foo + Assert.assertEquals(new HashSet<>(Arrays.asList("bar", "foo")), helper.getDomains("bar1")); + + // Add a new application domain and add bar1 to it + try { + zookeeperClientConnection + .create(CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/new", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, + CreateMode.PERSISTENT); + zookeeperClientConnection.create(CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/new/bar1", null, + ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); + + // For bar1, we should get bar, foo, and new + Assert.assertEquals(new HashSet<>(Arrays.asList("bar", "foo", "new")), helper.getDomains("bar1")); + } finally { + // Remove the application domain and bar1 + zookeeperClientConnection.delete(CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/new/bar1", -1); + zookeeperClientConnection.delete(CLIENT_URI_DOMAIN_MAPPING_ROOT_PATH + "/new", -1); + } + + // For bar1, we should get bar and foo + Assert.assertEquals(new HashSet<>(Arrays.asList("bar", "foo")), helper.getDomains("bar1")); + } + + @Test + /** + * Make sure the watcher installed while instantiate ZkClientUriDomainMappingHelper does not break + * the functionality of getting watches + */ + public void testB_GetWatches() { + ClientUriDomainMappingHelper helper = new ZkClientUriDomainMappingHelper(zookeeperServer); + WatchesReport report = zookeeperServer.getZKDatabase().getDataTree().getWatches(); + Assert.assertEquals(1, report.getPaths(0).size()); + } +} diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReadOnlyModeTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReadOnlyModeTest.java index c8f4ac42cc4..908a64000fe 100644 --- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReadOnlyModeTest.java +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/ReadOnlyModeTest.java @@ -184,6 +184,7 @@ public void testConnectionEvents() throws Exception { } assertTrue(success, "Did not succeed in connecting in 30s"); assertFalse(watcher.readOnlyConnected, "The connection should not be read-only yet"); + zk.close(); // kill peer and wait no more than 5 seconds for read-only server // to be started (which should take one tickTime (2 seconds)) @@ -191,6 +192,7 @@ public void testConnectionEvents() throws Exception { // Re-connect the client (in case we were connected to the shut down // server and the local session was not persisted). + watcher = new CountdownWatcher(); zk = new ZooKeeper(qu.getConnString(), CONNECTION_TIMEOUT, watcher, true); long start = Time.currentElapsedTime(); while (!(zk.getState() == States.CONNECTEDREADONLY)) { diff --git a/zookeeper-server/src/test/java/org/apache/zookeeper/test/X509AuthTest.java b/zookeeper-server/src/test/java/org/apache/zookeeper/test/X509AuthTest.java index bb04a9fdd66..b0a434782d5 100644 --- a/zookeeper-server/src/test/java/org/apache/zookeeper/test/X509AuthTest.java +++ b/zookeeper-server/src/test/java/org/apache/zookeeper/test/X509AuthTest.java @@ -19,6 +19,7 @@ package org.apache.zookeeper.test; import static org.junit.jupiter.api.Assertions.assertEquals; +import com.google.common.annotations.VisibleForTesting; import java.math.BigInteger; import java.net.Socket; import java.security.InvalidKeyException; @@ -33,8 +34,12 @@ import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; import java.util.Date; +import java.util.List; import java.util.Set; import javax.net.ssl.X509KeyManager; import javax.net.ssl.X509TrustManager; @@ -42,9 +47,15 @@ import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.ZKTestCase; import org.apache.zookeeper.server.MockServerCnxn; +import org.apache.zookeeper.server.auth.X509AuthenticationConfig; import org.apache.zookeeper.server.auth.X509AuthenticationProvider; +import org.apache.zookeeper.server.auth.X509AuthenticationUtil; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + public class X509AuthTest extends ZKTestCase { @@ -54,6 +65,7 @@ public class X509AuthTest extends ZKTestCase { @BeforeEach public void setUp() { + X509AuthenticationConfig.reset(); System.setProperty("zookeeper.X509AuthenticationProvider.superUser", "CN=SUPER"); System.setProperty("zookeeper.ssl.keyManager", "org.apache.zookeeper.test.X509AuthTest.TestKeyManager"); System.setProperty("zookeeper.ssl.trustManager", "org.apache.zookeeper.test.X509AuthTest.TestTrustManager"); @@ -63,6 +75,19 @@ public void setUp() { unknownCert = new TestCertificate("UNKNOWN"); } + @AfterEach + public void tearDown() { + System.clearProperty("zookeeper.X509AuthenticationProvider.superUser"); + System.clearProperty("zookeeper.ssl.keyManager"); + System.clearProperty("zookeeper.ssl.trustManager"); + System.clearProperty(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_TYPE); + System.clearProperty(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_MATCH_TYPE); + System.clearProperty(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_MATCH_REGEX); + System.clearProperty(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_EXTRACT_REGEX); + System.clearProperty(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_EXTRACT_MATCHER_GROUP_INDEX); + X509AuthenticationConfig.reset(); + } + @Test public void testTrustedAuth() { X509AuthenticationProvider provider = createProvider(clientCert); @@ -88,7 +113,70 @@ public void testUntrustedAuth() { assertEquals(KeeperException.Code.AUTHFAILED, provider.handleAuthentication(cnxn, null)); } - private static class TestPublicKey implements PublicKey { + @Test + public void testSANBasedAuth() { + String clientCertIdType = "SAN"; + String clientCertIdSANMatchType = "6"; + // The following clientCertIdSANMatchRegex matches the entire SAN String + String clientCertIdSANMatchRegex = ".*"; + // TEST_SAN_STR = "a:b:c(d;e;f)" in the test. The following clientCertIdSANExtractRegex + // extracts the first element in the parentheses excluding "a:b:c(" and trailing ";*" + String clientCertIdSANExtractRegex = "^a:b:c\\((.+);.+;.+\\)$"; + // The following clientCertIdSANExtractMatcherGroupIndex specifies the first index in the + // Matcher group, which is "d" + String clientCertIdSANExtractMatcherGroupIndex = "1"; + String expectedClientIdFromSANExtraction = "d"; + + // Set JVM properties to enable SAN-based client id extraction + System.setProperty(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_TYPE, clientCertIdType); + System.setProperty(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_MATCH_TYPE, clientCertIdSANMatchType); + System.setProperty(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_MATCH_REGEX, clientCertIdSANMatchRegex); + System.setProperty(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_EXTRACT_REGEX, clientCertIdSANExtractRegex); + System.setProperty(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_EXTRACT_MATCHER_GROUP_INDEX, + clientCertIdSANExtractMatcherGroupIndex); + + X509AuthenticationProvider provider = createProvider(clientCert); + MockServerCnxn cnxn = new MockServerCnxn(); + cnxn.clientChain = new X509Certificate[]{clientCert}; + assertEquals(KeeperException.Code.OK, provider.handleAuthentication(cnxn, null)); + assertEquals(expectedClientIdFromSANExtraction, cnxn.getAuthInfo().get(0).getId()); + + // Remove JVM properties so they don't interfere with other tests + System.clearProperty(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_TYPE); + System.clearProperty(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_MATCH_TYPE); + System.clearProperty(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_MATCH_REGEX); + System.clearProperty(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_EXTRACT_REGEX); + System.clearProperty(X509AuthenticationConfig.SSL_X509_CLIENT_CERT_ID_SAN_EXTRACT_MATCHER_GROUP_INDEX); + X509AuthenticationConfig.reset(); + } + + @ParameterizedTest + @ValueSource(strings = {"wrong-type", "no-match", "multiple-matches", "bad-group", "bad-extract"}) + public void testInvalidSanSelectionFallsBackToSubject(String scenario) { + X509AuthenticationConfig config = X509AuthenticationConfig.getInstance(); + config.setClientCertIdType("SAN"); + config.setClientCertIdSanMatchType("6"); + TestCertificate certificate = clientCert; + if ("wrong-type".equals(scenario)) { + config.setClientCertIdSanMatchType("9"); + } else if ("no-match".equals(scenario)) { + config.setClientCertIdSanMatchRegex("^no-match$"); + } else if ("bad-group".equals(scenario)) { + config.setClientCertIdSanExtractMatcherGroupIndex("3"); + } else if ("bad-extract".equals(scenario)) { + config.setClientCertIdSanExtractRegex("^no-match$"); + } else { + certificate = new TestCertificate("CLIENT") { + @Override + public Collection> getSubjectAlternativeNames() { + return Arrays.asList(Arrays.asList(6, "urn:example:one"), Arrays.asList(6, "urn:example:two")); + } + }; + } + assertEquals("CN=CLIENT", X509AuthenticationUtil.getClientId(certificate)); + } + + protected static class TestPublicKey implements PublicKey { private static final long serialVersionUID = 1L; @Override @@ -106,17 +194,25 @@ public byte[] getEncoded() { } - private static class TestCertificate extends X509Certificate { - + public static class TestCertificate extends X509Certificate { + @VisibleForTesting + static final String TEST_SAN_STR = "a:b:c(d;e;f)"; private byte[] encoded; private X500Principal principal; private PublicKey publicKey; + private String subjectAlternativeName; + public TestCertificate(String name) { - encoded = name.getBytes(); - principal = new X500Principal("CN=" + name); - publicKey = new TestPublicKey(); + this(name, TEST_SAN_STR); } - @Override + + public TestCertificate(String name, String sanVal) { + encoded = name.getBytes(); + principal = new X500Principal("CN=" + name); + publicKey = new TestPublicKey(); + subjectAlternativeName = sanVal; + } + @Override public boolean hasUnsupportedCriticalExtension() { return false; } @@ -220,7 +316,13 @@ public PublicKey getPublicKey() { public X500Principal getSubjectX500Principal() { return principal; } - + @Override + public Collection> getSubjectAlternativeNames() { + List subjectAlternativeNamePair = new ArrayList<>(); + subjectAlternativeNamePair.add(6); + subjectAlternativeNamePair.add(subjectAlternativeName); + return Collections.singletonList(subjectAlternativeNamePair); + } } public static class TestKeyManager implements X509KeyManager {