Add .gitignore and .ratignore files for various directories
Some checks failed
continuous-integration/drone/push Build is failing
Some checks failed
continuous-integration/drone/push Build is failing
This commit is contained in:
0
extensions/guacamole-vault/.ratignore
Normal file
0
extensions/guacamole-vault/.ratignore
Normal file
@@ -0,0 +1,81 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
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.
|
||||
-->
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
|
||||
http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.apache.guacamole</groupId>
|
||||
<artifactId>guacamole-vault-base</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<name>guacamole-vault-base</name>
|
||||
<url>http://guacamole.apache.org/</url>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<groupId>org.apache.guacamole</groupId>
|
||||
<artifactId>guacamole-vault</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- Guacamole Extension API -->
|
||||
<dependency>
|
||||
<groupId>org.apache.guacamole</groupId>
|
||||
<artifactId>guacamole-ext</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Jackson for YAML support -->
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.dataformat</groupId>
|
||||
<artifactId>jackson-dataformat-yaml</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- JUnit -->
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Guice -->
|
||||
<dependency>
|
||||
<groupId>com.google.inject</groupId>
|
||||
<artifactId>guice</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.inject.extensions</groupId>
|
||||
<artifactId>guice-assistedinject</artifactId>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* 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.guacamole.vault;
|
||||
|
||||
import com.google.inject.Guice;
|
||||
import com.google.inject.Injector;
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
import org.apache.guacamole.environment.Environment;
|
||||
import org.apache.guacamole.net.auth.AbstractAuthenticationProvider;
|
||||
import org.apache.guacamole.net.auth.AuthenticatedUser;
|
||||
import org.apache.guacamole.net.auth.Credentials;
|
||||
import org.apache.guacamole.net.auth.UserContext;
|
||||
import org.apache.guacamole.vault.conf.VaultConfigurationService;
|
||||
import org.apache.guacamole.vault.user.VaultUserContextFactory;
|
||||
|
||||
/**
|
||||
* AuthenticationProvider implementation which automatically injects tokens
|
||||
* containing the values of secrets retrieved from a vault.
|
||||
*/
|
||||
public abstract class VaultAuthenticationProvider
|
||||
extends AbstractAuthenticationProvider {
|
||||
|
||||
/**
|
||||
* Factory for creating instances of the relevant vault-specific
|
||||
* UserContext implementation.
|
||||
*/
|
||||
private final VaultUserContextFactory userContextFactory;
|
||||
|
||||
/**
|
||||
* Creates a new VaultAuthenticationProvider which uses the given module to
|
||||
* configure dependency injection.
|
||||
*
|
||||
* @param module
|
||||
* The module to use to configure dependency injection.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the properties file containing vault-mapped Guacamole
|
||||
* configuration properties exists but cannot be read.
|
||||
*/
|
||||
protected VaultAuthenticationProvider(VaultAuthenticationProviderModule module)
|
||||
throws GuacamoleException {
|
||||
|
||||
Injector injector = Guice.createInjector(module);
|
||||
this.userContextFactory = injector.getInstance(VaultUserContextFactory.class);
|
||||
|
||||
// Automatically pull properties from vault
|
||||
Environment environment = injector.getInstance(Environment.class);
|
||||
VaultConfigurationService confService = injector.getInstance(VaultConfigurationService.class);
|
||||
environment.addGuacamoleProperties(confService.getProperties());
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserContext decorate(UserContext context,
|
||||
AuthenticatedUser authenticatedUser, Credentials credentials)
|
||||
throws GuacamoleException {
|
||||
return userContextFactory.create(context);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* 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.guacamole.vault;
|
||||
|
||||
import com.google.inject.AbstractModule;
|
||||
import com.google.inject.assistedinject.FactoryModuleBuilder;
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
import org.apache.guacamole.environment.Environment;
|
||||
import org.apache.guacamole.environment.LocalEnvironment;
|
||||
import org.apache.guacamole.net.auth.UserContext;
|
||||
import org.apache.guacamole.vault.user.VaultUserContext;
|
||||
import org.apache.guacamole.vault.user.VaultUserContextFactory;
|
||||
|
||||
/**
|
||||
* Guice module which configures injections specific to the base support for
|
||||
* key vaults. When adding support for a key vault provider, a subclass
|
||||
* specific to that vault implementation will need to be created.
|
||||
*
|
||||
* @see KsmAuthenticationProviderModule
|
||||
*/
|
||||
public abstract class VaultAuthenticationProviderModule extends AbstractModule {
|
||||
|
||||
/**
|
||||
* Guacamole server environment.
|
||||
*/
|
||||
private final Environment environment;
|
||||
|
||||
/**
|
||||
* Creates a new VaultAuthenticationProviderModule which configures
|
||||
* dependency injection for the authentication provider of a vault
|
||||
* implementation.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs while retrieving the Guacamole server
|
||||
* environment.
|
||||
*/
|
||||
public VaultAuthenticationProviderModule() throws GuacamoleException {
|
||||
this.environment = LocalEnvironment.getInstance();
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures injections for interfaces which are implementation-specific
|
||||
* to the vault service in use. Subclasses MUST provide a version of this
|
||||
* function which binds concrete implementations to the following
|
||||
* interfaces:
|
||||
*
|
||||
* - VaultConfigurationService
|
||||
* - VaultSecretService
|
||||
*
|
||||
* @see KsmAuthenticationProviderModule
|
||||
*/
|
||||
protected abstract void configureVault();
|
||||
|
||||
/**
|
||||
* Returns the instance of the Guacamole server environment which will be
|
||||
* exposed to other classes via dependency injection.
|
||||
*
|
||||
* @return
|
||||
* The instance of the Guacamole server environment which will be
|
||||
* exposed via dependency injection.
|
||||
*/
|
||||
protected Environment getEnvironment() {
|
||||
return environment;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure() {
|
||||
|
||||
// Bind Guacamole server environment
|
||||
bind(Environment.class).toInstance(environment);
|
||||
|
||||
// Bind factory for creating UserContexts
|
||||
install(new FactoryModuleBuilder()
|
||||
.implement(UserContext.class, VaultUserContext.class)
|
||||
.build(VaultUserContextFactory.class));
|
||||
|
||||
// Bind all other implementation-specific interfaces
|
||||
configureVault();
|
||||
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,72 @@
|
||||
/*
|
||||
* 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.guacamole.vault.conf;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
import org.apache.guacamole.form.Form;
|
||||
|
||||
/**
|
||||
* A service that exposes attributes for the admin UI, specific to the vault
|
||||
* implementation. Any vault implementation will need to expose the attributes
|
||||
* necessary for that implementation.
|
||||
*/
|
||||
public interface VaultAttributeService {
|
||||
|
||||
/**
|
||||
* Return all custom connection attributes to be exposed through the
|
||||
* admin UI for the current vault implementation.
|
||||
*
|
||||
* @return
|
||||
* All custom connection attributes to be exposed through the
|
||||
* admin UI for the current vault implementation.
|
||||
*/
|
||||
public Collection<Form> getConnectionAttributes();
|
||||
|
||||
/**
|
||||
* Return all custom connection group attributes to be exposed through the
|
||||
* admin UI for the current vault implementation.
|
||||
*
|
||||
* @return
|
||||
* All custom connection group attributes to be exposed through the
|
||||
* admin UI for the current vault implementation.
|
||||
*/
|
||||
public Collection<Form> getConnectionGroupAttributes();
|
||||
|
||||
/**
|
||||
* Return all custom user attributes to be exposed through the admin UI for
|
||||
* the current vault implementation.
|
||||
*
|
||||
* @return
|
||||
* All custom user attributes to be exposed through the admin UI for
|
||||
* the current vault implementation.
|
||||
*/
|
||||
public Collection<Form> getUserAttributes();
|
||||
|
||||
/**
|
||||
* Return all user preference attributes to be exposed through the user
|
||||
* preferences UI for the current vault implementation.
|
||||
*
|
||||
* @return
|
||||
* All user preference attributes to be exposed through the user
|
||||
* preferences UI for the current vault implementation.
|
||||
*/
|
||||
public Collection<Form> getUserPreferenceAttributes();
|
||||
}
|
@@ -0,0 +1,226 @@
|
||||
/*
|
||||
* 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.guacamole.vault.conf;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
|
||||
import com.google.inject.Inject;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.Collections;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
import org.apache.guacamole.GuacamoleServerException;
|
||||
import org.apache.guacamole.environment.Environment;
|
||||
import org.apache.guacamole.properties.FileGuacamoleProperties;
|
||||
import org.apache.guacamole.properties.GuacamoleProperties;
|
||||
import org.apache.guacamole.properties.PropertiesGuacamoleProperties;
|
||||
import org.apache.guacamole.vault.VaultAuthenticationProviderModule;
|
||||
import org.apache.guacamole.vault.secret.VaultSecretService;
|
||||
|
||||
/**
|
||||
* Base class for services which retrieve key vault configuration information.
|
||||
* A concrete implementation of this class must be defined and bound for key
|
||||
* vault support to work.
|
||||
*
|
||||
* @see VaultAuthenticationProviderModule
|
||||
*/
|
||||
public abstract class VaultConfigurationService {
|
||||
|
||||
/**
|
||||
* The Guacamole server environment.
|
||||
*/
|
||||
@Inject
|
||||
private Environment environment;
|
||||
|
||||
@Inject
|
||||
private VaultSecretService secretService;
|
||||
|
||||
/**
|
||||
* ObjectMapper for deserializing YAML.
|
||||
*/
|
||||
private final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
|
||||
|
||||
/**
|
||||
* The name of the file containing a YAML mapping of Guacamole parameter
|
||||
* token to vault secret name.
|
||||
*/
|
||||
private final String tokenMappingFilename;
|
||||
|
||||
/**
|
||||
* The name of the properties file containing Guacamole configuration
|
||||
* properties. Unlike guacamole.properties, the values of these properties
|
||||
* are read from the vault. Each property is expected to contain a secret
|
||||
* name instead of a property value.
|
||||
*/
|
||||
private final String propertiesFilename;
|
||||
|
||||
/**
|
||||
* Creates a new VaultConfigurationService which retrieves the token/secret
|
||||
* mappings and Guacamole configuration properties from the files with the
|
||||
* given names.
|
||||
*
|
||||
* @param tokenMappingFilename
|
||||
* The name of the YAML file containing the token/secret mapping.
|
||||
*
|
||||
* @param propertiesFilename
|
||||
* The name of the properties file containing Guacamole configuration
|
||||
* properties whose values are the names of corresponding secrets.
|
||||
*/
|
||||
protected VaultConfigurationService(String tokenMappingFilename,
|
||||
String propertiesFilename) {
|
||||
this.tokenMappingFilename = tokenMappingFilename;
|
||||
this.propertiesFilename = propertiesFilename;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a mapping dictating the name of the secret which maps to each
|
||||
* parameter token. In the returned mapping, the value of each entry is the
|
||||
* name of the secret to use to populate the value of the parameter token,
|
||||
* and the key of each entry is the name of the parameter token which
|
||||
* should receive the value of the secret.
|
||||
*
|
||||
* The name of the secret may contain its own tokens, which will be
|
||||
* substituted using values from the given filter. See the definition of
|
||||
* VaultUserContext for the names of these tokens and the contexts in which
|
||||
* they can be applied to secret names.
|
||||
*
|
||||
* @return
|
||||
* A mapping dictating the name of the secret which maps to each
|
||||
* parameter token.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the YAML file defining the token/secret mapping cannot be read.
|
||||
*/
|
||||
public Map<String, String> getTokenMapping() throws GuacamoleException {
|
||||
|
||||
// Get configuration file from GUACAMOLE_HOME
|
||||
File confFile = new File(environment.getGuacamoleHome(), tokenMappingFilename);
|
||||
if (!confFile.exists())
|
||||
return Collections.emptyMap();
|
||||
|
||||
// Deserialize token mapping from YAML
|
||||
try {
|
||||
|
||||
Map<String, String> mapping = mapper.readValue(confFile, new TypeReference<Map<String, String>>() {});
|
||||
if (mapping == null)
|
||||
return Collections.emptyMap();
|
||||
|
||||
return mapping;
|
||||
|
||||
}
|
||||
|
||||
// Fail if YAML is invalid/unreadable
|
||||
catch (IOException e) {
|
||||
throw new GuacamoleServerException("Unable to read token mapping "
|
||||
+ "configuration file \"" + tokenMappingFilename + "\".", e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a GuacamoleProperties instance which automatically reads the
|
||||
* values of requested properties from the vault. The name of the secret
|
||||
* corresponding to a property stored in the vault is defined via the
|
||||
* properties filename supplied at construction time.
|
||||
*
|
||||
* @return
|
||||
* A GuacamoleProperties instance which automatically reads property
|
||||
* values from the vault.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the properties file containing the property/secret mappings
|
||||
* exists but cannot be read.
|
||||
*/
|
||||
public GuacamoleProperties getProperties() throws GuacamoleException {
|
||||
|
||||
// Use empty properties if file cannot be found
|
||||
File propFile = new File(environment.getGuacamoleHome(), propertiesFilename);
|
||||
if (!propFile.exists())
|
||||
return new PropertiesGuacamoleProperties(new Properties());
|
||||
|
||||
// Automatically pull properties from vault
|
||||
return new FileGuacamoleProperties(propFile) {
|
||||
|
||||
@Override
|
||||
public String getProperty(String name) throws GuacamoleException {
|
||||
try {
|
||||
|
||||
String secretName = super.getProperty(name);
|
||||
if (secretName == null)
|
||||
return null;
|
||||
|
||||
return secretService.getValue(secretName).get();
|
||||
|
||||
}
|
||||
catch (InterruptedException | ExecutionException e) {
|
||||
|
||||
if (e.getCause() instanceof GuacamoleException)
|
||||
throw (GuacamoleException) e;
|
||||
|
||||
throw new GuacamoleServerException(String.format("Property "
|
||||
+ "\"%s\" could not be retrieved from the vault.", name), e);
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether Windows domains should be split out from usernames when
|
||||
* fetched from the vault.
|
||||
*
|
||||
* For example: "DOMAIN\\user" or "user@DOMAIN" should both
|
||||
* be split into seperate username and domain tokens if this configuration
|
||||
* is true. If false, no domain token should be created and the above values
|
||||
* should be stored directly in the username token.
|
||||
*
|
||||
* @return
|
||||
* true if windows domains should be split out from usernames, false
|
||||
* otherwise.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the value specified within guacamole.properties cannot be
|
||||
* parsed.
|
||||
*/
|
||||
public abstract boolean getSplitWindowsUsernames() throws GuacamoleException;
|
||||
|
||||
/**
|
||||
* Return whether domains should be considered when matching user records
|
||||
* that are fetched from the vault.
|
||||
*
|
||||
* If set to true, the username and domain must both match when matching
|
||||
* records from the vault. If false, only the username will be considered.
|
||||
*
|
||||
* @return
|
||||
* true if both the username and domain should be considered when
|
||||
* matching user records from the vault.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the value specified within guacamole.properties cannot be
|
||||
* parsed.
|
||||
*/
|
||||
public abstract boolean getMatchUserRecordsByDomain() throws GuacamoleException;
|
||||
|
||||
}
|
@@ -0,0 +1,200 @@
|
||||
/*
|
||||
* 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.guacamole.vault.secret;
|
||||
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
import org.apache.guacamole.GuacamoleServerException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Caching implementation of VaultSecretService. Requests for the values of
|
||||
* secrets will automatically be cached for a duration determined by the
|
||||
* implementation. Subclasses must implement refreshCachedSecret() to provide
|
||||
* a mechanism for CachedVaultSecretService to explicitly retrieve a value
|
||||
* which is missing from the cache or has expired.
|
||||
*/
|
||||
public abstract class CachedVaultSecretService implements VaultSecretService {
|
||||
|
||||
/**
|
||||
* Logger for this class.
|
||||
*/
|
||||
private static final Logger logger = LoggerFactory.getLogger(CachedVaultSecretService.class);
|
||||
|
||||
/**
|
||||
* The cached value of a secret.
|
||||
*/
|
||||
protected class CachedSecret {
|
||||
|
||||
/**
|
||||
* A Future which contains or will contain the value of the secret at
|
||||
* the time it was last retrieved.
|
||||
*/
|
||||
private final Future<String> value;
|
||||
|
||||
/**
|
||||
* The time the value should be considered out-of-date, in milliseconds
|
||||
* since midnight of January 1, 1970 UTC.
|
||||
*/
|
||||
private final long expires;
|
||||
|
||||
/**
|
||||
* Creates a new CachedSecret which represents a cached snapshot of the
|
||||
* value of a secret. Each CachedSecret has a limited lifespan after
|
||||
* which it should be considered out-of-date.
|
||||
*
|
||||
* @param value
|
||||
* A Future which contains or will contain the current value of the
|
||||
* secret. If no such secret exists, the given Future should
|
||||
* complete with null.
|
||||
*
|
||||
* @param ttl
|
||||
* The maximum number of milliseconds that this value should be
|
||||
* cached.
|
||||
*/
|
||||
public CachedSecret(Future<String> value, int ttl) {
|
||||
this.value = value;
|
||||
this.expires = System.currentTimeMillis() + ttl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of the secret at the time it was last retrieved.
|
||||
* The actual value of the secret may have changed.
|
||||
*
|
||||
* @return
|
||||
* A Future which will eventually complete with the value of the
|
||||
* secret at the time it was last retrieved. If no such secret
|
||||
* exists, the Future will be completed with null. If an error
|
||||
* occurs which prevents retrieval of the secret, that error will
|
||||
* be exposed through an ExecutionException when an attempt is made
|
||||
* to retrieve the value from the Future.
|
||||
*/
|
||||
public Future<String> getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether this specific cached value has expired. Expired
|
||||
* values will be automatically refreshed by CachedVaultSecretService.
|
||||
*
|
||||
* @return
|
||||
* true if this cached value has expired, false otherwise.
|
||||
*/
|
||||
public boolean isExpired() {
|
||||
return System.currentTimeMillis() >= expires;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Cache of past requests to retrieve secrets. Expired secrets are lazily
|
||||
* removed.
|
||||
*/
|
||||
private final ConcurrentHashMap<String, Future<CachedSecret>> cache = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* Explicitly retrieves the value of the secret having the given name,
|
||||
* returning a result that can be cached. The length of time that this
|
||||
* specific value will be cached is determined by the TTL value provided to
|
||||
* the returned CachedSecret. This function will be automatically invoked
|
||||
* in response to calls to getValue() when the requested secret is either
|
||||
* not cached or has expired. Expired secrets are not removed from the
|
||||
* cache until another request is made for that secret.
|
||||
*
|
||||
* @param name
|
||||
* The name of the secret to retrieve.
|
||||
*
|
||||
* @return
|
||||
* A CachedSecret which defines the current value of the secret and the
|
||||
* point in time that value should be considered potentially
|
||||
* out-of-date.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs while retrieving the secret from the vault.
|
||||
*/
|
||||
protected abstract CachedSecret refreshCachedSecret(String name)
|
||||
throws GuacamoleException;
|
||||
|
||||
@Override
|
||||
public Future<String> getValue(String name) throws GuacamoleException {
|
||||
|
||||
CompletableFuture<CachedSecret> refreshEntry;
|
||||
|
||||
try {
|
||||
|
||||
// Attempt to use cached result of previous call
|
||||
Future<CachedSecret> cachedEntry = cache.get(name);
|
||||
if (cachedEntry != null) {
|
||||
|
||||
// Use cached result if not yet expired
|
||||
CachedSecret secret = cachedEntry.get();
|
||||
if (!secret.isExpired()) {
|
||||
logger.debug("Using cached secret for \"{}\".", name);
|
||||
return secret.getValue();
|
||||
}
|
||||
|
||||
// Evict if expired
|
||||
else {
|
||||
logger.debug("Cached secret for \"{}\" is expired.", name);
|
||||
cache.remove(name, cachedEntry);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// If no cached result, or result is too old, race with other
|
||||
// threads to be the thread which refreshes the entry
|
||||
refreshEntry = new CompletableFuture<>();
|
||||
cachedEntry = cache.putIfAbsent(name, refreshEntry);
|
||||
|
||||
// If a refresh operation is already in progress, wait for that
|
||||
// operation to complete and use its value
|
||||
if (cachedEntry != null)
|
||||
return cachedEntry.get().getValue();
|
||||
|
||||
}
|
||||
catch (InterruptedException | ExecutionException e) {
|
||||
throw new GuacamoleServerException("Attempt to retrieve secret "
|
||||
+ "failed.", e);
|
||||
}
|
||||
|
||||
// If we reach this far, the cache entry is stale or missing, and it's
|
||||
// this thread's responsibility to refresh the entry
|
||||
try {
|
||||
CachedSecret secret = refreshCachedSecret(name);
|
||||
refreshEntry.complete(secret);
|
||||
logger.debug("Cached secret for \"{}\" will be refreshed.", name);
|
||||
return secret.getValue();
|
||||
}
|
||||
|
||||
// Abort the refresh operation if an error occurs
|
||||
catch (Error | RuntimeException | GuacamoleException e) {
|
||||
refreshEntry.completeExceptionally(e);
|
||||
cache.remove(name, refreshEntry);
|
||||
logger.debug("Cached secret for \"{}\" could not be refreshed.", name);
|
||||
throw e;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
* 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.guacamole.vault.secret;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.Future;
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
import org.apache.guacamole.net.auth.Connectable;
|
||||
import org.apache.guacamole.net.auth.UserContext;
|
||||
import org.apache.guacamole.protocol.GuacamoleConfiguration;
|
||||
import org.apache.guacamole.token.TokenFilter;
|
||||
|
||||
/**
|
||||
* Generic service for retrieving the value of a secret stored in a vault.
|
||||
*/
|
||||
public interface VaultSecretService {
|
||||
|
||||
/**
|
||||
* Translates an arbitrary string, which may contain characters not allowed
|
||||
* by the vault implementation, into a string which is valid within a
|
||||
* secret name. The type of transformation performed on the string, if any,
|
||||
* will depend on the specific requirements of the vault provider.
|
||||
*
|
||||
* NOTE: It is critical that this transformation is deterministic and
|
||||
* reasonably predictable for users. If an implementation must apply a
|
||||
* transformation to secret names, that transformation needs to be
|
||||
* documented.
|
||||
*
|
||||
* @param nameComponent
|
||||
* An arbitrary string intended for use within a secret name, but which
|
||||
* may contain characters not allowed by the vault implementation.
|
||||
*
|
||||
* @return
|
||||
* A string containing essentially the same content as the provided
|
||||
* string, but transformed deterministically such that it is acceptable
|
||||
* as a component of a secret name by the vault provider.
|
||||
*/
|
||||
String canonicalize(String nameComponent);
|
||||
|
||||
/**
|
||||
* Returns a Future which eventually completes with the value of the secret
|
||||
* having the given name. If no such secret exists, the Future will be
|
||||
* completed with null. The secrets retrieved from this method are independent
|
||||
* of the context of the particular connection being established, or any
|
||||
* associated user context.
|
||||
*
|
||||
* @param name
|
||||
* The name of the secret to retrieve.
|
||||
*
|
||||
* @return
|
||||
* A Future which completes with value of the secret having the given
|
||||
* name. If no such secret exists, the Future will be completed with
|
||||
* null. If an error occurs asynchronously which prevents retrieval of
|
||||
* the secret, that error will be exposed through an ExecutionException
|
||||
* when an attempt is made to retrieve the value from the Future.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the secret cannot be retrieved due to an error.
|
||||
*/
|
||||
Future<String> getValue(String name) throws GuacamoleException;
|
||||
|
||||
/**
|
||||
* Returns a Future which eventually completes with the value of the secret
|
||||
* having the given name. If no such secret exists, the Future will be
|
||||
* completed with null. The connection or connection group, as well as the
|
||||
* user context associated with the request are provided for additional context.
|
||||
*
|
||||
* @param userContext
|
||||
* The user context associated with the connection or connection group for
|
||||
* which the secret is being retrieved.
|
||||
*
|
||||
* @param connectable
|
||||
* The connection or connection group for which the secret is being retrieved.
|
||||
*
|
||||
* @param name
|
||||
* The name of the secret to retrieve.
|
||||
*
|
||||
* @return
|
||||
* A Future which completes with value of the secret having the given
|
||||
* name. If no such secret exists, the Future will be completed with
|
||||
* null. If an error occurs asynchronously which prevents retrieval of
|
||||
* the secret, that error will be exposed through an ExecutionException
|
||||
* when an attempt is made to retrieve the value from the Future.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the secret cannot be retrieved due to an error.
|
||||
*/
|
||||
Future<String> getValue(UserContext userContext, Connectable connectable,
|
||||
String name) throws GuacamoleException;
|
||||
|
||||
/**
|
||||
* Returns a map of token names to corresponding Futures which eventually
|
||||
* complete with the value of that token, where each token is dynamically
|
||||
* defined based on connection parameters. If a vault implementation allows
|
||||
* for predictable secrets based on the parameters of a connection, this
|
||||
* function should be implemented to provide automatic tokens for those
|
||||
* secrets and remove the need for manual mapping via YAML.
|
||||
*
|
||||
* @param userContext
|
||||
* The user context from which the connectable originated.
|
||||
*
|
||||
* @param connectable
|
||||
* The connection or connection group for which the tokens are being replaced.
|
||||
*
|
||||
* @param config
|
||||
* The configuration of the Guacamole connection for which tokens are
|
||||
* being generated. This configuration may be empty or partial,
|
||||
* depending on the underlying implementation.
|
||||
*
|
||||
* @param filter
|
||||
* A TokenFilter instance that applies any tokens already available to
|
||||
* be applied to the configuration of the Guacamole connection. These
|
||||
* tokens will consist of tokens already supplied to connect().
|
||||
*
|
||||
* @return
|
||||
* A map of token names to their corresponding future values, where
|
||||
* each token and value may be dynamically determined based on the
|
||||
* connection configuration.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs producing the tokens and values required for the
|
||||
* given configuration.
|
||||
*/
|
||||
Map<String, Future<String>> getTokens(UserContext userContext, Connectable connectable,
|
||||
GuacamoleConfiguration config, TokenFilter filter) throws GuacamoleException;
|
||||
|
||||
}
|
@@ -0,0 +1,157 @@
|
||||
/*
|
||||
* 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.guacamole.vault.secret;
|
||||
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
|
||||
/**
|
||||
* A class representing a Windows username, which may optionally also include
|
||||
* a domain. This class can be used to parse the username and domain out of a
|
||||
* username from a vault.
|
||||
*/
|
||||
public class WindowsUsername {
|
||||
|
||||
/**
|
||||
* A pattern for matching a down-level logon name containing a Windows
|
||||
* domain and username - e.g. domain\\user. For more information, see
|
||||
* https://docs.microsoft.com/en-us/windows/win32/secauthn/user-name-formats#down-level-logon-name
|
||||
*/
|
||||
private static final Pattern DOWN_LEVEL_LOGON_NAME_PATTERN = Pattern.compile(
|
||||
"(?<domain>[^@\\\\]+)\\\\(?<username>[^@\\\\]+)");
|
||||
|
||||
/**
|
||||
* A pattern for matching a user principal name containing a Windows
|
||||
* domain and username - e.g. user@domain. For more information, see
|
||||
* https://docs.microsoft.com/en-us/windows/win32/secauthn/user-name-formats#user-principal-name
|
||||
*/
|
||||
private static final Pattern USER_PRINCIPAL_NAME_PATTERN = Pattern.compile(
|
||||
"(?<username>[^@\\\\]+)@(?<domain>[^@\\\\]+)");
|
||||
|
||||
/**
|
||||
* The username associated with the potential Windows domain/username
|
||||
* value. If no domain is found, the username field will contain the
|
||||
* entire value as read from the vault.
|
||||
*/
|
||||
private final String username;
|
||||
|
||||
/**
|
||||
* The dinaun associated with the potential Windows domain/username
|
||||
* value. If no domain is found, this will be null.
|
||||
*/
|
||||
private final String domain;
|
||||
|
||||
/**
|
||||
* Create a WindowsUsername record with no associated domain.
|
||||
*
|
||||
* @param username
|
||||
* The username, which should be the entire value as extracted
|
||||
* from the vault.
|
||||
*/
|
||||
private WindowsUsername(@Nonnull String username) {
|
||||
this.username = username;
|
||||
this.domain = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a WindowsUsername record with a username and a domain.
|
||||
*
|
||||
* @param username
|
||||
* The username portion of the field value from the vault.
|
||||
*
|
||||
* @param domain
|
||||
* The domain portion of the field value from the vault.
|
||||
*/
|
||||
private WindowsUsername(
|
||||
@Nonnull String username, @Nonnull String domain) {
|
||||
this.username = username;
|
||||
this.domain = domain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the value of the username as extracted from the vault field.
|
||||
* If the domain is null, this will be the entire field value.
|
||||
*
|
||||
* @return
|
||||
* The username value as extracted from the vault field.
|
||||
*/
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the value of the domain as extracted from the vault field.
|
||||
* If this is null, it means that no domain was found in the vault field.
|
||||
*
|
||||
* @return
|
||||
* The domain value as extracted from the vault field.
|
||||
*/
|
||||
public String getDomain() {
|
||||
return domain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if a domain was found in the vault field, false otherwise.
|
||||
*
|
||||
* @return
|
||||
* true if a domain was found in the vault field, false otherwise.
|
||||
*/
|
||||
public boolean hasDomain() {
|
||||
return this.domain != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip off a Windows domain from the provided username, if one is
|
||||
* present. For example: "DOMAIN\\user" or "user@DOMAIN" will both
|
||||
* be stripped to just "user". Note: neither the '@' or '\\' characters
|
||||
* are valid in Windows usernames.
|
||||
*
|
||||
* @param vaultField
|
||||
* The raw field value as retrieved from the vault. This might contain
|
||||
* a Windows domain.
|
||||
*
|
||||
* @return
|
||||
* The provided username with the Windows domain stripped off, if one
|
||||
* is present.
|
||||
*/
|
||||
public static WindowsUsername splitWindowsUsernameFromDomain(String vaultField) {
|
||||
|
||||
// If it's the down-level logon format, return the extracted username and domain
|
||||
Matcher downLevelLogonMatcher = DOWN_LEVEL_LOGON_NAME_PATTERN.matcher(vaultField);
|
||||
if (downLevelLogonMatcher.matches())
|
||||
return new WindowsUsername(
|
||||
downLevelLogonMatcher.group("username"),
|
||||
downLevelLogonMatcher.group("domain"));
|
||||
|
||||
// If it's the user principal format, return the extracted username and domain
|
||||
Matcher userPrincipalMatcher = USER_PRINCIPAL_NAME_PATTERN.matcher(vaultField);
|
||||
if (userPrincipalMatcher.matches())
|
||||
return new WindowsUsername(
|
||||
userPrincipalMatcher.group("username"),
|
||||
userPrincipalMatcher.group("domain"));
|
||||
|
||||
// If none of the expected formats matched, return the username with do domain
|
||||
return new WindowsUsername(vaultField);
|
||||
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,140 @@
|
||||
/*
|
||||
* 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.guacamole.vault.user;
|
||||
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
import org.apache.guacamole.net.auth.ActiveConnection;
|
||||
import org.apache.guacamole.net.auth.Connection;
|
||||
import org.apache.guacamole.net.auth.ConnectionGroup;
|
||||
import org.apache.guacamole.net.auth.Directory;
|
||||
import org.apache.guacamole.net.auth.SharingProfile;
|
||||
import org.apache.guacamole.net.auth.User;
|
||||
import org.apache.guacamole.net.auth.UserGroup;
|
||||
|
||||
/**
|
||||
* A service that allows a vault implementation to override the directory
|
||||
* for any entity that a user context may return.
|
||||
*/
|
||||
public abstract class VaultDirectoryService {
|
||||
|
||||
/**
|
||||
* Given an existing User Directory, return a new Directory for
|
||||
* this vault implementation.
|
||||
*
|
||||
* @return
|
||||
* A new User Directory based on the provided Directory.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs while creating the Directory.
|
||||
*/
|
||||
public Directory<User> getUserDirectory(
|
||||
Directory<User> underlyingDirectory) throws GuacamoleException {
|
||||
|
||||
// By default, the provided directly will be returned unchanged
|
||||
return underlyingDirectory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an existing UserGroup Directory, return a new Directory for
|
||||
* this vault implementation.
|
||||
*
|
||||
* @return
|
||||
* A new UserGroup Directory based on the provided Directory.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs while creating the Directory.
|
||||
*/
|
||||
public Directory<UserGroup> getUserGroupDirectory(
|
||||
Directory<UserGroup> underlyingDirectory) throws GuacamoleException {
|
||||
|
||||
// Unless overriden in the vault implementation, the underlying directory
|
||||
// will be returned directly
|
||||
return underlyingDirectory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an existing Connection Directory, return a new Directory for
|
||||
* this vault implementation.
|
||||
*
|
||||
* @return
|
||||
* A new Connection Directory based on the provided Directory.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs while creating the Directory.
|
||||
*/
|
||||
public Directory<Connection> getConnectionDirectory(
|
||||
Directory<Connection> underlyingDirectory) throws GuacamoleException {
|
||||
|
||||
// By default, the provided directly will be returned unchanged
|
||||
return underlyingDirectory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an existing ConnectionGroup Directory, return a new Directory for
|
||||
* this vault implementation.
|
||||
*
|
||||
* @return
|
||||
* A new ConnectionGroup Directory based on the provided Directory.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs while creating the Directory.
|
||||
*/
|
||||
public Directory<ConnectionGroup> getConnectionGroupDirectory(
|
||||
Directory<ConnectionGroup> underlyingDirectory) throws GuacamoleException {
|
||||
|
||||
// By default, the provided directly will be returned unchanged
|
||||
return underlyingDirectory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an existing ActiveConnection Directory, return a new Directory for
|
||||
* this vault implementation.
|
||||
*
|
||||
* @return
|
||||
* A new ActiveConnection Directory based on the provided Directory.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs while creating the Directory.
|
||||
*/
|
||||
public Directory<ActiveConnection> getActiveConnectionDirectory(
|
||||
Directory<ActiveConnection> underlyingDirectory) throws GuacamoleException {
|
||||
|
||||
// By default, the provided directly will be returned unchanged
|
||||
return underlyingDirectory;
|
||||
}
|
||||
|
||||
/**
|
||||
* Given an existing SharingProfile Directory, return a new Directory for
|
||||
* this vault implementation.
|
||||
*
|
||||
* @return
|
||||
* A new SharingProfile Directory based on the provided Directory.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs while creating the Directory.
|
||||
*/
|
||||
public Directory<SharingProfile> getSharingProfileDirectory(
|
||||
Directory<SharingProfile> underlyingDirectory) throws GuacamoleException {
|
||||
|
||||
// By default, the provided directly will be returned unchanged
|
||||
return underlyingDirectory;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,528 @@
|
||||
/*
|
||||
* 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.guacamole.vault.user;
|
||||
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.assistedinject.Assisted;
|
||||
import com.google.inject.assistedinject.AssistedInject;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
import org.apache.guacamole.GuacamoleServerException;
|
||||
import org.apache.guacamole.form.Form;
|
||||
import org.apache.guacamole.net.auth.ActiveConnection;
|
||||
import org.apache.guacamole.net.auth.Connectable;
|
||||
import org.apache.guacamole.net.auth.Connection;
|
||||
import org.apache.guacamole.net.auth.ConnectionGroup;
|
||||
import org.apache.guacamole.net.auth.Directory;
|
||||
import org.apache.guacamole.net.auth.SharingProfile;
|
||||
import org.apache.guacamole.net.auth.TokenInjectingUserContext;
|
||||
import org.apache.guacamole.net.auth.User;
|
||||
import org.apache.guacamole.net.auth.UserContext;
|
||||
import org.apache.guacamole.net.auth.UserGroup;
|
||||
import org.apache.guacamole.protocol.GuacamoleConfiguration;
|
||||
import org.apache.guacamole.token.GuacamoleTokenUndefinedException;
|
||||
import org.apache.guacamole.token.TokenFilter;
|
||||
import org.apache.guacamole.vault.conf.VaultAttributeService;
|
||||
import org.apache.guacamole.vault.conf.VaultConfigurationService;
|
||||
import org.apache.guacamole.vault.secret.VaultSecretService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* UserContext implementation which automatically injects tokens containing the
|
||||
* values of secrets retrieved from a vault.
|
||||
*/
|
||||
public class VaultUserContext extends TokenInjectingUserContext {
|
||||
|
||||
/**
|
||||
* Logger for this class.
|
||||
*/
|
||||
private static final Logger logger = LoggerFactory.getLogger(VaultUserContext.class);
|
||||
|
||||
/**
|
||||
* The name of the token which will be replaced with the username of the
|
||||
* current user if specified within the name of a secret. Unlike the
|
||||
* standard GUAC_USERNAME token, the username stored with the object
|
||||
* representing the user is used here, not necessarily the username
|
||||
* provided during authentication. This token applies to both connections
|
||||
* and connection groups.
|
||||
*/
|
||||
private static final String USERNAME_TOKEN = "USERNAME";
|
||||
|
||||
/**
|
||||
* The name of the token which will be replaced with the name of the
|
||||
* current connection group if specified within the name of a secret. This
|
||||
* token only applies only to connection groups.
|
||||
*/
|
||||
private static final String CONNECTION_GROUP_NAME_TOKEN = "CONNECTION_GROUP_NAME";
|
||||
|
||||
/**
|
||||
* The name of the token which will be replaced with the identifier of the
|
||||
* current connection group if specified within the name of a secret. This
|
||||
* token only applies only to connection groups.
|
||||
*/
|
||||
private static final String CONNECTION_GROUP_IDENTIFIER_TOKEN = "CONNECTION_GROUP_ID";
|
||||
|
||||
/**
|
||||
* The name of the token which will be replaced with the \"hostname\"
|
||||
* connection parameter of the current connection if specified within the
|
||||
* name of a secret. If the \"hostname\" parameter cannot be retrieved, or
|
||||
* if the parameter is blank, the token will not be replaced and any
|
||||
* secrets involving that token will not be retrieved. This token only
|
||||
* applies only to connections.
|
||||
*/
|
||||
private static final String CONNECTION_HOSTNAME_TOKEN = "CONNECTION_HOSTNAME";
|
||||
|
||||
/**
|
||||
* The name of the token which will be replaced with the \"username\"
|
||||
* connection parameter of the current connection if specified within the
|
||||
* name of a secret. If the \"username\" parameter cannot be retrieved, or
|
||||
* if the parameter is blank, the token will not be replaced and any
|
||||
* secrets involving that token will not be retrieved. This token only
|
||||
* applies only to connections.
|
||||
*/
|
||||
private static final String CONNECTION_USERNAME_TOKEN = "CONNECTION_USERNAME";
|
||||
|
||||
/**
|
||||
* The name of the token which will be replaced with the name of the
|
||||
* current connection if specified within the name of a secret. This token
|
||||
* only applies only to connections.
|
||||
*/
|
||||
private static final String CONNECTION_NAME_TOKEN = "CONNECTION_NAME";
|
||||
|
||||
/**
|
||||
* The name of the token which will be replaced with the identifier of the
|
||||
* current connection if specified within the name of a secret. This token
|
||||
* only applies only to connections.
|
||||
*/
|
||||
private static final String CONNECTION_IDENTIFIER_TOKEN = "CONNECTION_ID";
|
||||
|
||||
/**
|
||||
* Service for retrieving configuration information.
|
||||
*/
|
||||
@Inject
|
||||
private VaultConfigurationService confService;
|
||||
|
||||
/**
|
||||
* Service for retrieving the values of secrets stored in a vault.
|
||||
*/
|
||||
@Inject
|
||||
private VaultSecretService secretService;
|
||||
|
||||
/**
|
||||
* Service for retrieving any custom attributes defined for the
|
||||
* current vault implementation.
|
||||
*/
|
||||
@Inject
|
||||
private VaultAttributeService attributeService;
|
||||
|
||||
/**
|
||||
* Service for modifying any underlying directories for the current
|
||||
* vault implementation.
|
||||
*/
|
||||
@Inject
|
||||
private VaultDirectoryService directoryService;
|
||||
|
||||
/**
|
||||
* Creates a new VaultUserContext which automatically injects tokens
|
||||
* containing values of secrets retrieved from a vault. The given
|
||||
* UserContext is decorated such that connections and connection groups
|
||||
* will receive additional tokens during the connection process.
|
||||
*
|
||||
* Note that this class depends on concrete implementations of the
|
||||
* following classes to be provided via dependency injection:
|
||||
*
|
||||
* - VaultConfigurationService
|
||||
* - VaultSecretService
|
||||
*
|
||||
* Bindings providing these concrete implementations will need to be
|
||||
* provided by subclasses of VaultAuthenticationProviderModule for each
|
||||
* supported vault.
|
||||
*
|
||||
* @param userContext
|
||||
* The UserContext instance to decorate.
|
||||
*/
|
||||
@AssistedInject
|
||||
public VaultUserContext(@Assisted UserContext userContext) {
|
||||
super(userContext);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new TokenFilter instance with token values set for all tokens
|
||||
* which are not specific to connections or connection groups. Currently,
|
||||
* this is only the vault-specific username token ("USERNAME"). Each token
|
||||
* stored within the returned TokenFilter via setToken() will be
|
||||
* automatically canonicalized for use within secret names.
|
||||
*
|
||||
* @return
|
||||
* A new TokenFilter instance with token values set for all tokens
|
||||
* which are not specific to connections or connection groups.
|
||||
*/
|
||||
private TokenFilter createFilter() {
|
||||
|
||||
// Create filter that automatically canonicalizes all token values
|
||||
TokenFilter filter = new TokenFilter() {
|
||||
|
||||
@Override
|
||||
public void setToken(String name, String value) {
|
||||
super.setToken(name, secretService.canonicalize(value));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTokens(Map<String, String> tokens) {
|
||||
tokens.entrySet().forEach((entry) -> setToken(entry.getKey(), entry.getValue()));
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
filter.setToken(USERNAME_TOKEN, self().getIdentifier());
|
||||
return filter;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiates asynchronous retrieval of all applicable tokens and
|
||||
* corresponding values from the vault, using the given TokenFilter to
|
||||
* filter tokens within the secret names prior to retrieving those secrets.
|
||||
*
|
||||
* @param connectable
|
||||
* The connection or connection group to which the connection is being
|
||||
* established.
|
||||
*
|
||||
* @param tokenMapping
|
||||
* The mapping dictating the name of the secret which maps to each
|
||||
* parameter token, where the key is the name of the parameter token
|
||||
* and the value is the name of the secret. The name of the secret
|
||||
* may contain its own tokens, which will be substituted using values
|
||||
* from the given filter.
|
||||
*
|
||||
* @param secretNameFilter
|
||||
* The filter to use to substitute values for tokens in the names of
|
||||
* secrets to be retrieved from the vault.
|
||||
*
|
||||
* @param config
|
||||
* The GuacamoleConfiguration of the connection for which tokens are
|
||||
* being retrieved, if available. This may be null.
|
||||
*
|
||||
* @param configFilter
|
||||
* A TokenFilter instance that applies any tokens already available to
|
||||
* be applied to the configuration of the Guacamole connection. These
|
||||
* tokens will consist of tokens already supplied to connect().
|
||||
*
|
||||
* @return
|
||||
* A Map of token name to Future, where each Future represents the
|
||||
* pending retrieval operation which will ultimately be completed with
|
||||
* the value of all secrets mapped to that token.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the value for any applicable secret cannot be retrieved from the
|
||||
* vault due to an error.
|
||||
*/
|
||||
private Map<String, Future<String>> getTokens(
|
||||
Connectable connectable, Map<String, String> tokenMapping,
|
||||
TokenFilter secretNameFilter, GuacamoleConfiguration config,
|
||||
TokenFilter configFilter) throws GuacamoleException {
|
||||
|
||||
// Populate map with pending secret retrieval operations corresponding
|
||||
// to each mapped token
|
||||
Map<String, Future<String>> pendingTokens = new HashMap<>(tokenMapping.size());
|
||||
for (Map.Entry<String, String> entry : tokenMapping.entrySet()) {
|
||||
|
||||
// Translate secret pattern into secret name, ignoring any
|
||||
// secrets which cannot be translated
|
||||
String secretName;
|
||||
try {
|
||||
secretName = secretNameFilter.filterStrict(entry.getValue());
|
||||
}
|
||||
catch (GuacamoleTokenUndefinedException e) {
|
||||
logger.debug("Secret for token \"{}\" will not be retrieved. "
|
||||
+ "Token \"{}\" within mapped secret name has no "
|
||||
+ "defined value in the current context.",
|
||||
entry.getKey(), e.getTokenName());
|
||||
continue;
|
||||
}
|
||||
|
||||
// Initiate asynchronous retrieval of the token value
|
||||
String tokenName = entry.getKey();
|
||||
Future<String> secret = secretService.getValue(
|
||||
this, connectable, secretName);
|
||||
pendingTokens.put(tokenName, secret);
|
||||
|
||||
}
|
||||
|
||||
// Additionally include any dynamic, parameter-based tokens
|
||||
pendingTokens.putAll(secretService.getTokens(
|
||||
this, connectable, config, configFilter));
|
||||
|
||||
return pendingTokens;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for all pending secret retrieval operations to complete,
|
||||
* transforming each Future within the given Map into its contained String
|
||||
* value.
|
||||
*
|
||||
* @param pendingTokens
|
||||
* A Map of token name to Future, where each Future represents the
|
||||
* pending retrieval operation which will ultimately be completed with
|
||||
* the value of all secrets mapped to that token.
|
||||
*
|
||||
* @return
|
||||
* A Map of token name to the corresponding String value retrieved for
|
||||
* that token from the vault.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the value for any applicable secret cannot be retrieved from the
|
||||
* vault due to an error.
|
||||
*/
|
||||
private Map<String, String> resolve(Map<String,
|
||||
Future<String>> pendingTokens) throws GuacamoleException {
|
||||
|
||||
// Populate map with tokens containing the values of their
|
||||
// corresponding secrets
|
||||
Map<String, String> tokens = new HashMap<>(pendingTokens.size());
|
||||
for (Map.Entry<String, Future<String>> entry : pendingTokens.entrySet()) {
|
||||
|
||||
// Complete secret retrieval operation, blocking if necessary
|
||||
String secretValue;
|
||||
try {
|
||||
secretValue = entry.getValue().get();
|
||||
}
|
||||
catch (InterruptedException | ExecutionException e) {
|
||||
throw new GuacamoleServerException("Retrieval of secret value "
|
||||
+ "failed.", e);
|
||||
}
|
||||
|
||||
// If a value is defined for the secret in question, store that
|
||||
// value under the mapped token
|
||||
String tokenName = entry.getKey();
|
||||
if (secretValue != null) {
|
||||
tokens.put(tokenName, secretValue);
|
||||
logger.debug("Token \"{}\" populated with value from "
|
||||
+ "secret.", tokenName);
|
||||
}
|
||||
else
|
||||
logger.debug("Token \"{}\" not populated. Mapped "
|
||||
+ "secret has no value.", tokenName);
|
||||
|
||||
}
|
||||
|
||||
return tokens;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void addTokens(ConnectionGroup connectionGroup,
|
||||
Map<String, String> tokens) throws GuacamoleException {
|
||||
|
||||
String name = connectionGroup.getName();
|
||||
String identifier = connectionGroup.getIdentifier();
|
||||
logger.debug("Injecting tokens from vault for connection group "
|
||||
+ "\"{}\" (\"{}\").", identifier, name);
|
||||
|
||||
// Add general and connection-group-specific tokens
|
||||
TokenFilter filter = createFilter();
|
||||
filter.setToken(CONNECTION_GROUP_NAME_TOKEN, name);
|
||||
filter.setToken(CONNECTION_GROUP_IDENTIFIER_TOKEN, identifier);
|
||||
|
||||
// Substitute tokens producing secret names, retrieving and storing
|
||||
// those secrets as parameter tokens
|
||||
tokens.putAll(resolve(getTokens(
|
||||
connectionGroup, confService.getTokenMapping(), filter,
|
||||
null, new TokenFilter(tokens))));
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the GuacamoleConfiguration of the given Connection. If
|
||||
* possible, privileged access to the configuration is obtained first. Note
|
||||
* that the underlying extension is not required to allow privileged
|
||||
* access, nor is it required to expose the underlying configuration at
|
||||
* all.
|
||||
*
|
||||
* @param connection
|
||||
* The connection to retrieve the configuration from.
|
||||
*
|
||||
* @return
|
||||
* The GuacamoleConfiguration associated with the given connection,
|
||||
* which may be partial or empty.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error prevents privileged retrieval of the configuration.
|
||||
*/
|
||||
private GuacamoleConfiguration getConnectionConfiguration(Connection connection)
|
||||
throws GuacamoleException {
|
||||
|
||||
String identifier = connection.getIdentifier();
|
||||
|
||||
// Obtain privileged access to parameters if possible (note that the
|
||||
// UserContext returned by getPrivileged() is not guaranteed to
|
||||
// actually be privileged)
|
||||
Connection privilegedConnection = getPrivileged().getConnectionDirectory().get(identifier);
|
||||
if (privilegedConnection != null)
|
||||
return privilegedConnection.getConfiguration();
|
||||
|
||||
// Fall back to unprivileged access if not implemented/allowed by
|
||||
// extension
|
||||
return connection.getConfiguration();
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void addTokens(Connection connection, Map<String, String> tokens)
|
||||
throws GuacamoleException {
|
||||
|
||||
String name = connection.getName();
|
||||
String identifier = connection.getIdentifier();
|
||||
logger.debug("Injecting tokens from vault for connection \"{}\" "
|
||||
+ "(\"{}\").", identifier, name);
|
||||
|
||||
// Add general and connection-specific tokens
|
||||
TokenFilter filter = createFilter();
|
||||
filter.setToken(CONNECTION_NAME_TOKEN, connection.getName());
|
||||
filter.setToken(CONNECTION_IDENTIFIER_TOKEN, identifier);
|
||||
// Add hostname and username tokens if available (implementations are
|
||||
// not required to expose connection configuration details)
|
||||
|
||||
GuacamoleConfiguration config = getConnectionConfiguration(connection);
|
||||
Map<String, String> parameters = config.getParameters();
|
||||
|
||||
String hostname = parameters.get("hostname");
|
||||
if (hostname != null && !hostname.isEmpty())
|
||||
filter.setToken(CONNECTION_HOSTNAME_TOKEN, hostname);
|
||||
else
|
||||
logger.debug("Hostname for connection \"{}\" (\"{}\") not "
|
||||
+ "available. \"{}\" token will not be populated in "
|
||||
+ "secret names.", identifier, name,
|
||||
CONNECTION_HOSTNAME_TOKEN);
|
||||
|
||||
String username = parameters.get("username");
|
||||
if (username != null && !username.isEmpty())
|
||||
filter.setToken(CONNECTION_USERNAME_TOKEN, username);
|
||||
else
|
||||
logger.debug("Username for connection \"{}\" (\"{}\") not "
|
||||
+ "available. \"{}\" token will not be populated in "
|
||||
+ "secret names.", identifier, name,
|
||||
CONNECTION_USERNAME_TOKEN);
|
||||
|
||||
// Substitute tokens producing secret names, retrieving and storing
|
||||
// those secrets as parameter tokens
|
||||
tokens.putAll(resolve(getTokens(connection, confService.getTokenMapping(),
|
||||
filter, config, new TokenFilter(tokens))));
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Directory<User> getUserDirectory() throws GuacamoleException {
|
||||
|
||||
// Defer to the vault-specific directory service
|
||||
return directoryService.getUserDirectory(super.getUserDirectory());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Directory<UserGroup> getUserGroupDirectory() throws GuacamoleException {
|
||||
|
||||
// Defer to the vault-specific directory service
|
||||
return directoryService.getUserGroupDirectory(super.getUserGroupDirectory());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Directory<Connection> getConnectionDirectory() throws GuacamoleException {
|
||||
|
||||
// Defer to the vault-specific directory service
|
||||
return directoryService.getConnectionDirectory(super.getConnectionDirectory());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Directory<ConnectionGroup> getConnectionGroupDirectory() throws GuacamoleException {
|
||||
|
||||
// Defer to the vault-specific directory service
|
||||
return directoryService.getConnectionGroupDirectory(super.getConnectionGroupDirectory());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Directory<ActiveConnection> getActiveConnectionDirectory() throws GuacamoleException {
|
||||
|
||||
// Defer to the vault-specific directory service
|
||||
return directoryService.getActiveConnectionDirectory(super.getActiveConnectionDirectory());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Directory<SharingProfile> getSharingProfileDirectory() throws GuacamoleException {
|
||||
|
||||
// Defer to the vault-specific directory service
|
||||
return directoryService.getSharingProfileDirectory(super.getSharingProfileDirectory());
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<Form> getUserAttributes() {
|
||||
|
||||
// Add any custom attributes to any previously defined attributes
|
||||
return Collections.unmodifiableCollection(Stream.concat(
|
||||
super.getUserAttributes().stream(),
|
||||
attributeService.getUserAttributes().stream()
|
||||
).collect(Collectors.toList()));
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<Form> getUserPreferenceAttributes() {
|
||||
|
||||
// Add any custom preference attributes to any previously defined attributes
|
||||
return Collections.unmodifiableCollection(Stream.concat(
|
||||
super.getUserPreferenceAttributes().stream(),
|
||||
attributeService.getUserPreferenceAttributes().stream()
|
||||
).collect(Collectors.toList()));
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<Form> getConnectionAttributes() {
|
||||
|
||||
// Add any custom attributes to any previously defined attributes
|
||||
return Collections.unmodifiableCollection(Stream.concat(
|
||||
super.getConnectionAttributes().stream(),
|
||||
attributeService.getConnectionAttributes().stream()
|
||||
).collect(Collectors.toList()));
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<Form> getConnectionGroupAttributes() {
|
||||
|
||||
// Add any custom attributes to any previously defined attributes
|
||||
return Collections.unmodifiableCollection(Stream.concat(
|
||||
super.getConnectionGroupAttributes().stream(),
|
||||
attributeService.getConnectionGroupAttributes().stream()
|
||||
).collect(Collectors.toList()));
|
||||
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* 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.guacamole.vault.user;
|
||||
|
||||
import org.apache.guacamole.net.auth.UserContext;
|
||||
|
||||
/**
|
||||
* Factory for creating UserContext instances which automatically inject tokens
|
||||
* containing the values of secrets retrieved from a vault.
|
||||
*/
|
||||
public interface VaultUserContextFactory {
|
||||
|
||||
/**
|
||||
* Returns a new instance of a UserContext implementation which
|
||||
* automatically injects tokens containing values of secrets retrieved from
|
||||
* a vault. The given UserContext is decorated such that connections and
|
||||
* connection groups will receive additional tokens during the connection
|
||||
* process.
|
||||
*
|
||||
* @param userContext
|
||||
* The UserContext instance to decorate.
|
||||
*
|
||||
* @return
|
||||
* A new UserContext instance which automatically injects tokens
|
||||
* containing values of secrets retrieved from a vault.
|
||||
*/
|
||||
UserContext create(UserContext userContext);
|
||||
|
||||
}
|
@@ -0,0 +1,7 @@
|
||||
{
|
||||
|
||||
"DATA_SOURCE_AZURE_KEYVAULT" : {
|
||||
"NAME" : "Azure Key Vault"
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* 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.guacamole.vault.secret;
|
||||
|
||||
import org.junit.Test;
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Class to test the parsing functionality of the WindowsUsername class.
|
||||
*/
|
||||
public class WindowsUsernameTest {
|
||||
|
||||
/**
|
||||
* Verify that the splitWindowsUsernameFromDomain() method correctly strips Windows
|
||||
* domains from provided usernames that include them, and does not modify
|
||||
* usernames that do not have Windows domains.
|
||||
*/
|
||||
@Test
|
||||
public void testSplitWindowsUsernameFromDomain() {
|
||||
|
||||
WindowsUsername usernameAndDomain;
|
||||
|
||||
// If no Windows domain is present in the provided field, the username should
|
||||
// contain the entire field, and no domain should be returned
|
||||
usernameAndDomain = WindowsUsername.splitWindowsUsernameFromDomain("bob");
|
||||
assertEquals(usernameAndDomain.getUsername(), "bob");
|
||||
assertFalse(usernameAndDomain.hasDomain());
|
||||
|
||||
// It should parse down-level logon name style domains
|
||||
usernameAndDomain = WindowsUsername.splitWindowsUsernameFromDomain("localhost\\bob");
|
||||
assertEquals("bob", usernameAndDomain.getUsername(), "bob");
|
||||
assertTrue(usernameAndDomain.hasDomain());
|
||||
assertEquals("localhost", usernameAndDomain.getDomain());
|
||||
|
||||
// It should parse user principal name style domains
|
||||
usernameAndDomain = WindowsUsername.splitWindowsUsernameFromDomain("bob@localhost");
|
||||
assertEquals("bob", usernameAndDomain.getUsername(), "bob");
|
||||
assertTrue(usernameAndDomain.hasDomain());
|
||||
assertEquals("localhost", usernameAndDomain.getDomain());
|
||||
|
||||
// It should not match if there are an invalid number of separators
|
||||
List<String> invalidSeparators = Arrays.asList(
|
||||
"bob@local@host", "local\\host\\bob",
|
||||
"bob\\local@host", "local@host\\bob");
|
||||
invalidSeparators.stream().forEach(
|
||||
invalidSeparator -> {
|
||||
|
||||
// An invalid number of separators means that the parse failed -
|
||||
// there should be no detected domain, and the entire field value
|
||||
// should be returned as the username
|
||||
WindowsUsername parseOutput =
|
||||
WindowsUsername.splitWindowsUsernameFromDomain(invalidSeparator);
|
||||
assertFalse(parseOutput.hasDomain());
|
||||
assertEquals(invalidSeparator, parseOutput.getUsername());
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,62 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
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.
|
||||
-->
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
|
||||
http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.apache.guacamole</groupId>
|
||||
<artifactId>guacamole-vault-dist</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
<name>guacamole-vault-dist</name>
|
||||
<url>http://guacamole.apache.org/</url>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
</properties>
|
||||
|
||||
<parent>
|
||||
<groupId>org.apache.guacamole</groupId>
|
||||
<artifactId>guacamole-vault</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- Keeper Secrets Manager Extension -->
|
||||
<dependency>
|
||||
<groupId>org.apache.guacamole</groupId>
|
||||
<artifactId>guacamole-vault-ksm</artifactId>
|
||||
<version>1.6.0</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
<!-- Dist .tar.gz for guacamole-vault should be named after the parent
|
||||
guacamole-vault project, not after guacamole-vault-dist -->
|
||||
<finalName>${project.parent.artifactId}-${project.parent.version}</finalName>
|
||||
|
||||
</build>
|
||||
|
||||
</project>
|
@@ -0,0 +1,54 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
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.
|
||||
-->
|
||||
<assembly
|
||||
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
|
||||
|
||||
<id>dist</id>
|
||||
<baseDirectory>${project.parent.artifactId}-${project.parent.version}</baseDirectory>
|
||||
|
||||
<!-- Output .tar.gz -->
|
||||
<formats>
|
||||
<format>tar.gz</format>
|
||||
</formats>
|
||||
|
||||
<!-- Include extension .jars -->
|
||||
<dependencySets>
|
||||
|
||||
<!-- Keeper Secrets Manager extension .jar -->
|
||||
<dependencySet>
|
||||
<outputDirectory>ksm</outputDirectory>
|
||||
<includes>
|
||||
<include>org.apache.guacamole:guacamole-vault-ksm</include>
|
||||
</includes>
|
||||
</dependencySet>
|
||||
|
||||
</dependencySets>
|
||||
|
||||
<!-- Licenses -->
|
||||
<fileSets>
|
||||
<fileSet>
|
||||
<outputDirectory></outputDirectory>
|
||||
<directory>target/licenses</directory>
|
||||
</fileSet>
|
||||
</fileSets>
|
||||
|
||||
</assembly>
|
114
extensions/guacamole-vault/modules/guacamole-vault-ksm/pom.xml
Normal file
114
extensions/guacamole-vault/modules/guacamole-vault-ksm/pom.xml
Normal file
@@ -0,0 +1,114 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
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.
|
||||
-->
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
|
||||
http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.apache.guacamole</groupId>
|
||||
<artifactId>guacamole-vault-ksm</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
<version>1.6.0</version>
|
||||
<name>guacamole-vault-ksm</name>
|
||||
<url>http://guacamole.apache.org/</url>
|
||||
|
||||
<parent>
|
||||
<groupId>org.apache.guacamole</groupId>
|
||||
<artifactId>guacamole-vault</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<relativePath>../../</relativePath>
|
||||
</parent>
|
||||
|
||||
<properties>
|
||||
<kotlin.version>1.9.25</kotlin.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<!-- Guacamole Extension API -->
|
||||
<dependency>
|
||||
<groupId>org.apache.guacamole</groupId>
|
||||
<artifactId>guacamole-ext</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- Guacamole base key vault support -->
|
||||
<dependency>
|
||||
<groupId>org.apache.guacamole</groupId>
|
||||
<artifactId>guacamole-vault-base</artifactId>
|
||||
<version>1.6.0</version>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.keepersecurity.secrets-manager</groupId>
|
||||
<artifactId>core</artifactId>
|
||||
<version>17.0.0</version>
|
||||
|
||||
<!-- Correct version conflict (different versions across transitive
|
||||
dependencies) -->
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-reflect</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-stdlib</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-stdlib-common</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-stdlib-jdk8</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
|
||||
</dependency>
|
||||
|
||||
<!-- Use same version of Kotlin across all dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-reflect</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-stdlib</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.jetbrains.kotlin</groupId>
|
||||
<artifactId>kotlin-stdlib-jdk8</artifactId>
|
||||
<version>${kotlin.version}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Use FIPS variant of Bouncy Castle crypto library -->
|
||||
<dependency>
|
||||
<groupId>org.bouncycastle</groupId>
|
||||
<artifactId>bc-fips</artifactId>
|
||||
<version>2.1.0</version>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
|
||||
</project>
|
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* 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.guacamole.vault.ksm;
|
||||
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
|
||||
/**
|
||||
* A class that is basically equivalent to the standard Supplier class in
|
||||
* Java, except that the get() function can throw GuacamoleException, which
|
||||
* is impossible with any of the standard Java lambda type classes, since
|
||||
* none of them can handle checked exceptions
|
||||
*
|
||||
* @param <T>
|
||||
* The type of object which will be returned as a result of calling
|
||||
* get().
|
||||
*/
|
||||
public interface GuacamoleExceptionSupplier<T> {
|
||||
|
||||
/**
|
||||
* Returns a value of the declared type.
|
||||
*
|
||||
* @return
|
||||
* A value of the declared type.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs while attemping to calculate the return value.
|
||||
*/
|
||||
public T get() throws GuacamoleException;
|
||||
|
||||
}
|
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* 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.guacamole.vault.ksm;
|
||||
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
import org.apache.guacamole.vault.VaultAuthenticationProvider;
|
||||
|
||||
/**
|
||||
* VaultAuthenticationProvider implementation which reads secrets from Keeper
|
||||
* Secrets Manager
|
||||
*/
|
||||
public class KsmAuthenticationProvider extends VaultAuthenticationProvider {
|
||||
|
||||
/**
|
||||
* Creates a new KsmKeyVaultAuthenticationProvider which reads secrets
|
||||
* from a configured Keeper Secrets Manager.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If configuration details cannot be read from guacamole.properties.
|
||||
*/
|
||||
public KsmAuthenticationProvider() throws GuacamoleException {
|
||||
super(new KsmAuthenticationProviderModule());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getIdentifier() {
|
||||
return "keeper-secrets-manager";
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* 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.guacamole.vault.ksm;
|
||||
|
||||
import java.security.Security;
|
||||
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
import org.apache.guacamole.vault.VaultAuthenticationProviderModule;
|
||||
import org.apache.guacamole.vault.ksm.conf.KsmAttributeService;
|
||||
import org.apache.guacamole.vault.ksm.conf.KsmConfigurationService;
|
||||
import org.apache.guacamole.vault.ksm.secret.KsmSecretService;
|
||||
import org.apache.guacamole.vault.ksm.user.KsmConnectionGroup;
|
||||
import org.apache.guacamole.vault.ksm.user.KsmDirectoryService;
|
||||
import org.apache.guacamole.vault.ksm.user.KsmUserFactory;
|
||||
import org.apache.guacamole.vault.ksm.user.KsmUser;
|
||||
import org.apache.guacamole.vault.conf.VaultAttributeService;
|
||||
import org.apache.guacamole.vault.conf.VaultConfigurationService;
|
||||
import org.apache.guacamole.vault.ksm.secret.KsmClient;
|
||||
import org.apache.guacamole.vault.ksm.secret.KsmClientFactory;
|
||||
import org.apache.guacamole.vault.ksm.secret.KsmRecordService;
|
||||
import org.apache.guacamole.vault.secret.VaultSecretService;
|
||||
import org.apache.guacamole.vault.user.VaultDirectoryService;
|
||||
|
||||
import org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider;
|
||||
|
||||
import com.google.inject.assistedinject.FactoryModuleBuilder;
|
||||
|
||||
/**
|
||||
* Guice module which configures injections specific to Keeper Secrets
|
||||
* Manager support.
|
||||
*/
|
||||
public class KsmAuthenticationProviderModule
|
||||
extends VaultAuthenticationProviderModule {
|
||||
|
||||
/**
|
||||
* Creates a new KsmAuthenticationProviderModule which
|
||||
* configures dependency injection for the Keeper Secrets Manager
|
||||
* authentication provider and related services.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If configuration details in guacamole.properties cannot be parsed.
|
||||
*/
|
||||
public KsmAuthenticationProviderModule() throws GuacamoleException {
|
||||
// KSM recommends using BouncyCastleFipsProvider to avoid potential
|
||||
// issues (for example with FIPS enabled RHEL).
|
||||
// https://docs.keeper.io/en/secrets-manager/secrets-manager/developer-sdk-library/java-sdk
|
||||
// The addProvider method checks for duplications internally,
|
||||
// so it is safe to add the same provider multiple times.
|
||||
Security.addProvider(new BouncyCastleFipsProvider());
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configureVault() {
|
||||
|
||||
// Bind services specific to Keeper Secrets Manager
|
||||
bind(KsmRecordService.class);
|
||||
bind(KsmAttributeService.class);
|
||||
bind(VaultAttributeService.class).to(KsmAttributeService.class);
|
||||
bind(VaultConfigurationService.class).to(KsmConfigurationService.class);
|
||||
bind(VaultSecretService.class).to(KsmSecretService.class);
|
||||
bind(VaultDirectoryService.class).to(KsmDirectoryService.class);
|
||||
|
||||
// Bind factory for creating KSM Clients
|
||||
install(new FactoryModuleBuilder()
|
||||
.implement(KsmClient.class, KsmClient.class)
|
||||
.build(KsmClientFactory.class));
|
||||
|
||||
// Bind factory for creating KsmUsers
|
||||
install(new FactoryModuleBuilder()
|
||||
.implement(KsmUser.class, KsmUser.class)
|
||||
.build(KsmUserFactory.class));
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,356 @@
|
||||
/*
|
||||
* 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.guacamole.vault.ksm.conf;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
import org.apache.guacamole.form.BooleanField;
|
||||
import org.apache.guacamole.form.Form;
|
||||
import org.apache.guacamole.form.TextField;
|
||||
import org.apache.guacamole.language.TranslatableGuacamoleClientException;
|
||||
import org.apache.guacamole.vault.conf.VaultAttributeService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.Singleton;
|
||||
import com.keepersecurity.secretsManager.core.InMemoryStorage;
|
||||
import com.keepersecurity.secretsManager.core.SecretsManager;
|
||||
import com.keepersecurity.secretsManager.core.SecretsManagerOptions;
|
||||
|
||||
/**
|
||||
* A service that exposes KSM-specific attributes, allowing setting KSM
|
||||
* configuration through the admin interface.
|
||||
*/
|
||||
@Singleton
|
||||
public class KsmAttributeService implements VaultAttributeService {
|
||||
|
||||
/**
|
||||
* Logger for this class.
|
||||
*/
|
||||
private static final Logger logger = LoggerFactory.getLogger(KsmAttributeService.class);
|
||||
|
||||
/**
|
||||
* Service for retrieving KSM configuration details.
|
||||
*/
|
||||
@Inject
|
||||
private KsmConfigurationService configurationService;
|
||||
|
||||
/**
|
||||
* A singleton ObjectMapper for converting a Map to a JSON string when
|
||||
* generating a base64-encoded JSON KSM config blob.
|
||||
*/
|
||||
private static final ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
/**
|
||||
* All expected fields in the KSM configuration JSON blob.
|
||||
*/
|
||||
private static final List<String> EXPECTED_KSM_FIELDS = (
|
||||
Collections.unmodifiableList(Arrays.asList(
|
||||
SecretsManager.KEY_HOSTNAME,
|
||||
SecretsManager.KEY_CLIENT_ID,
|
||||
SecretsManager.KEY_PRIVATE_KEY,
|
||||
SecretsManager.KEY_CLIENT_KEY,
|
||||
SecretsManager.KEY_APP_KEY,
|
||||
SecretsManager.KEY_OWNER_PUBLIC_KEY,
|
||||
SecretsManager.KEY_SERVER_PUBIC_KEY_ID
|
||||
)));
|
||||
|
||||
/**
|
||||
* The name of the attribute which can contain a KSM configuration blob
|
||||
* associated with either a connection group or user.
|
||||
*/
|
||||
public static final String KSM_CONFIGURATION_ATTRIBUTE = "ksm-config";
|
||||
|
||||
/**
|
||||
* The KSM configuration attribute contains sensitive information, so it
|
||||
* should not be exposed through the directory. Instead, if a value is
|
||||
* set on the attributes of an object, the following value will be exposed
|
||||
* in its place, and correspondingly the underlying value will not be
|
||||
* changed if this value is provided to an update call.
|
||||
*/
|
||||
public static final String KSM_ATTRIBUTE_PLACEHOLDER_VALUE = "**********";
|
||||
|
||||
/**
|
||||
* All attributes related to configuring the KSM vault on a
|
||||
* per-connection-group or per-user basis.
|
||||
*/
|
||||
public static final Form KSM_CONFIGURATION_FORM = new Form("ksm-config",
|
||||
Arrays.asList(new TextField(KSM_CONFIGURATION_ATTRIBUTE)));
|
||||
|
||||
/**
|
||||
* All KSM-specific attributes for users, connections, or connection groups, organized by form.
|
||||
*/
|
||||
public static final Collection<Form> KSM_ATTRIBUTES =
|
||||
Collections.unmodifiableCollection(Arrays.asList(KSM_CONFIGURATION_FORM));
|
||||
|
||||
/**
|
||||
* The name of the attribute which can controls whether a KSM user configuration
|
||||
* is enabled on a connection-by-connection basis.
|
||||
*/
|
||||
public static final String KSM_USER_CONFIG_ENABLED_ATTRIBUTE = "ksm-user-config-enabled";
|
||||
|
||||
/**
|
||||
* The string value used by KSM attributes to represent the boolean value "true".
|
||||
*/
|
||||
public static final String TRUTH_VALUE = "true";
|
||||
|
||||
/**
|
||||
* All attributes related to configuring the KSM vault on a per-connection basis.
|
||||
*/
|
||||
public static final Form KSM_CONNECTION_FORM = new Form("ksm-config",
|
||||
Arrays.asList(new BooleanField(KSM_USER_CONFIG_ENABLED_ATTRIBUTE, TRUTH_VALUE)));
|
||||
|
||||
/**
|
||||
* All KSM-specific attributes for connections, organized by form.
|
||||
*/
|
||||
public static final Collection<Form> KSM_CONNECTION_ATTRIBUTES =
|
||||
Collections.unmodifiableCollection(Arrays.asList(KSM_CONNECTION_FORM));
|
||||
|
||||
@Override
|
||||
public Collection<Form> getConnectionAttributes() {
|
||||
return KSM_CONNECTION_ATTRIBUTES;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<Form> getConnectionGroupAttributes() {
|
||||
return KSM_ATTRIBUTES;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<Form> getUserAttributes() {
|
||||
|
||||
try {
|
||||
|
||||
// Expose the user attributes IFF user-level KSM configuration is enabled
|
||||
return configurationService.getAllowUserConfig() ? KSM_ATTRIBUTES : Collections.emptyList();
|
||||
|
||||
}
|
||||
|
||||
catch (GuacamoleException e) {
|
||||
|
||||
logger.warn(
|
||||
"Unable to determine if KSM user attributes "
|
||||
+ "should be exposed due to config parsing error: {}.", e.getMessage());
|
||||
logger.debug(
|
||||
"Config parsing error prevented checking user attribute configuration",
|
||||
e);
|
||||
|
||||
// If the configuration can't be parsed, default to not exposing the attributes
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<Form> getUserPreferenceAttributes() {
|
||||
|
||||
// KSM-specific user preference attributes have the same semantics as
|
||||
// user attributes
|
||||
return getUserAttributes();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize the value of the provided KSM config attribute. If the provided
|
||||
* config value is non-empty, it will be replaced with the placeholder
|
||||
* value to avoid leaking sensitive information. If the value is empty, it
|
||||
* will be replaced by `null`.
|
||||
*
|
||||
* @param ksmAttributeValue
|
||||
* The KSM configuration attribute value to sanitize.
|
||||
*
|
||||
* @return
|
||||
* The sanitized KSM configuration attribute value, stripped of any
|
||||
* sensitive information.
|
||||
*/
|
||||
public static String sanitizeKsmAttributeValue(String ksmAttributeValue) {
|
||||
|
||||
// Any non-empty values may contain sensitive information, and should
|
||||
// be replaced by the safe placeholder value
|
||||
if (ksmAttributeValue != null && !ksmAttributeValue.trim().isEmpty())
|
||||
return KSM_ATTRIBUTE_PLACEHOLDER_VALUE;
|
||||
|
||||
// If the configuration value is empty, expose a null value
|
||||
else
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Return true if the provided input is a valid base64-encoded string,
|
||||
* false otherwise.
|
||||
*
|
||||
* @param input
|
||||
* The string to check if base-64 encoded.
|
||||
*
|
||||
* @return
|
||||
* true if the provided input is a valid base64-encoded string,
|
||||
* false otherwise.
|
||||
*/
|
||||
private static boolean isBase64(String input) {
|
||||
|
||||
try {
|
||||
Base64.getDecoder().decode(input);
|
||||
return true;
|
||||
} catch (IllegalArgumentException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a map of attribute values, check for the presence of the
|
||||
* KSM_CONFIGURATION_ATTRIBUTE attribute. If it's set, check if it's a valid
|
||||
* KSM one-time token. If so, attempt to translate it to a base-64-encoded
|
||||
* json KSM config blob. If it's already a KSM config blob, validate it as
|
||||
* config blob. If either validation fails, a GuacamoleException will be thrown.
|
||||
* The processed attribute values will be returned.
|
||||
*
|
||||
* @param attributes
|
||||
* The attributes for which the KSM configuration attribute
|
||||
* parsing/validation should be performed.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the KSM_CONFIGURATION_ATTRIBUTE is set, but fails to validate as
|
||||
* either a KSM one-time-token, or a KSM base64-encoded JSON config blob.
|
||||
*/
|
||||
public Map<String, String> processAttributes(
|
||||
Map<String, String> attributes) throws GuacamoleException {
|
||||
|
||||
// Get the value of the KSM config attribute in the provided map
|
||||
String ksmConfigValue = attributes.get(
|
||||
KsmAttributeService.KSM_CONFIGURATION_ATTRIBUTE);
|
||||
|
||||
// If the placeholder value was provided, do not update the attribute
|
||||
if (KsmAttributeService.KSM_ATTRIBUTE_PLACEHOLDER_VALUE.equals(ksmConfigValue)) {
|
||||
|
||||
// Remove the attribute from the map so it won't be updated
|
||||
attributes = new HashMap<>(attributes);
|
||||
attributes.remove(KsmAttributeService.KSM_CONFIGURATION_ATTRIBUTE);
|
||||
|
||||
}
|
||||
|
||||
// Check if the attribute is set to a non-empty value
|
||||
else if (ksmConfigValue != null && !ksmConfigValue.trim().isEmpty()) {
|
||||
|
||||
// If it's already base64-encoded, it's a KSM configuration blob,
|
||||
// so validate it immediately
|
||||
if (isBase64(ksmConfigValue)) {
|
||||
|
||||
// Attempt to validate the config as a base64-econded KSM config blob
|
||||
try {
|
||||
KsmConfig.parseKsmConfig(ksmConfigValue);
|
||||
|
||||
// If it validates, the entity can be left alone - it's already valid
|
||||
return attributes;
|
||||
}
|
||||
|
||||
catch (GuacamoleException exception) {
|
||||
|
||||
// If the parsing attempt fails, throw a translatable error for display
|
||||
// on the frontend
|
||||
throw new TranslatableGuacamoleClientException(
|
||||
"Invalid base64-encoded JSON KSM config provided for "
|
||||
+ KsmAttributeService.KSM_CONFIGURATION_ATTRIBUTE + " attribute",
|
||||
"CONNECTION_GROUP_ATTRIBUTES.ERROR_INVALID_KSM_CONFIG_BLOB",
|
||||
exception);
|
||||
}
|
||||
}
|
||||
|
||||
// It wasn't a valid base64-encoded string, it should be a one-time token, so
|
||||
// attempt to validat it as such, and if valid, update the attribute to the
|
||||
// base64 config blob generated by the token
|
||||
try {
|
||||
|
||||
// Create an initially empty storage to be populated using the one-time token
|
||||
InMemoryStorage storage = new InMemoryStorage();
|
||||
|
||||
// Populate the in-memory storage using the one-time-token
|
||||
SecretsManager.initializeStorage(storage, ksmConfigValue, null);
|
||||
|
||||
// Create an options object using the values we extracted from the one-time token
|
||||
SecretsManagerOptions options = new SecretsManagerOptions(
|
||||
storage, null,
|
||||
configurationService.getAllowUnverifiedCertificate());
|
||||
|
||||
// Attempt to fetch secrets using the options we created. This will both validate
|
||||
// that the configuration works, and potentially populate missing fields that the
|
||||
// initializeStorage() call did not set.
|
||||
SecretsManager.getSecrets(options);
|
||||
|
||||
// Create a map to store the extracted values from the KSM storage
|
||||
Map<String, String> configMap = new HashMap<>();
|
||||
|
||||
// Go through all the expected fields, extract from the KSM storage,
|
||||
// and write to the newly created map
|
||||
EXPECTED_KSM_FIELDS.forEach(configKey -> {
|
||||
|
||||
// Only write the value into the new map if non-null
|
||||
String value = storage.getString(configKey);
|
||||
if (value != null)
|
||||
configMap.put(configKey, value);
|
||||
|
||||
});
|
||||
|
||||
// JSON-encode the value, and then base64 encode that to get the format
|
||||
// that KSM would expect
|
||||
String jsonString = objectMapper.writeValueAsString(configMap);
|
||||
String base64EncodedJson = Base64.getEncoder().encodeToString(
|
||||
jsonString.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
// Finally, try to parse the newly generated token as a KSM config. If this
|
||||
// works, the config should be fully functional
|
||||
KsmConfig.parseKsmConfig(base64EncodedJson);
|
||||
|
||||
// Make a copy of the existing attributes, modifying just the value for
|
||||
// KSM_CONFIGURATION_ATTRIBUTE
|
||||
attributes = new HashMap<>(attributes);
|
||||
attributes.put(
|
||||
KsmAttributeService.KSM_CONFIGURATION_ATTRIBUTE, base64EncodedJson);
|
||||
|
||||
}
|
||||
|
||||
// The KSM SDK only throws raw Exceptions, so we can't be more specific
|
||||
catch (Exception exception) {
|
||||
|
||||
// If the parsing attempt fails, throw a translatable error for display
|
||||
// on the frontend
|
||||
throw new TranslatableGuacamoleClientException(
|
||||
"Invalid one-time KSM token provided for "
|
||||
+ KsmAttributeService.KSM_CONFIGURATION_ATTRIBUTE + " attribute",
|
||||
"CONNECTION_GROUP_ATTRIBUTES.ERROR_INVALID_KSM_ONE_TIME_TOKEN",
|
||||
exception);
|
||||
}
|
||||
}
|
||||
|
||||
return attributes;
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* 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.guacamole.vault.ksm.conf;
|
||||
|
||||
import com.keepersecurity.secretsManager.core.InMemoryStorage;
|
||||
import com.keepersecurity.secretsManager.core.KeyValueStorage;
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
import org.apache.guacamole.GuacamoleServerException;
|
||||
|
||||
/**
|
||||
* A utility for parsing base64-encoded JSON, as output by the Keeper Commander
|
||||
* CLI tool via the "sm client add" command into a Keeper Secrets Manager
|
||||
* {@link KeyValueStorage} object.
|
||||
*/
|
||||
public class KsmConfig {
|
||||
|
||||
/**
|
||||
* Given a base64-encoded JSON KSM configuration, parse and return a
|
||||
* KeyValueStorage object.
|
||||
*
|
||||
* @param value
|
||||
* The base64-encoded JSON KSM configuration to parse.
|
||||
*
|
||||
* @return
|
||||
* The KeyValueStorage that is a result of the parsing operation
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the provided value is not valid base-64 encoded JSON KSM configuration.
|
||||
*/
|
||||
public static KeyValueStorage parseKsmConfig(String value) throws GuacamoleException {
|
||||
|
||||
// Parse base64 value as KSM config storage
|
||||
try {
|
||||
return new InMemoryStorage(value);
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
throw new GuacamoleServerException("Invalid base64 configuration "
|
||||
+ "for Keeper Secrets Manager.", e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,275 @@
|
||||
/*
|
||||
* 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.guacamole.vault.ksm.conf;
|
||||
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.Singleton;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
import org.apache.guacamole.GuacamoleServerException;
|
||||
import org.apache.guacamole.environment.Environment;
|
||||
import org.apache.guacamole.properties.BooleanGuacamoleProperty;
|
||||
import org.apache.guacamole.properties.LongGuacamoleProperty;
|
||||
import org.apache.guacamole.properties.StringGuacamoleProperty;
|
||||
import org.apache.guacamole.vault.conf.VaultConfigurationService;
|
||||
|
||||
import com.keepersecurity.secretsManager.core.InMemoryStorage;
|
||||
import com.keepersecurity.secretsManager.core.KeyValueStorage;
|
||||
import com.keepersecurity.secretsManager.core.SecretsManagerOptions;
|
||||
|
||||
/**
|
||||
* Service for retrieving configuration information regarding the Keeper
|
||||
* Secrets Manager authentication extension.
|
||||
*/
|
||||
@Singleton
|
||||
public class KsmConfigurationService extends VaultConfigurationService {
|
||||
|
||||
/**
|
||||
* The Guacamole server environment.
|
||||
*/
|
||||
@Inject
|
||||
private Environment environment;
|
||||
|
||||
/**
|
||||
* The name of the file which contains the YAML mapping of connection
|
||||
* parameter token to secrets within Keeper Secrets Manager.
|
||||
*/
|
||||
private static final String TOKEN_MAPPING_FILENAME = "ksm-token-mapping.yml";
|
||||
|
||||
/**
|
||||
* The name of the properties file containing Guacamole configuration
|
||||
* properties whose values are the names of corresponding secrets within
|
||||
* Keeper Secrets Manager.
|
||||
*/
|
||||
private static final String PROPERTIES_FILENAME = "guacamole.properties.ksm";
|
||||
|
||||
/**
|
||||
* The base64-encoded configuration information generated by the Keeper
|
||||
* Commander CLI tool.
|
||||
*/
|
||||
private static final StringGuacamoleProperty KSM_CONFIG = new StringGuacamoleProperty() {
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "ksm-config";
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether unverified server certificates should be accepted.
|
||||
*/
|
||||
private static final BooleanGuacamoleProperty ALLOW_UNVERIFIED_CERT = new BooleanGuacamoleProperty() {
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "ksm-allow-unverified-cert";
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether users should be able to supply their own KSM configurations.
|
||||
*/
|
||||
private static final BooleanGuacamoleProperty ALLOW_USER_CONFIG = new BooleanGuacamoleProperty() {
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "ksm-allow-user-config";
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether windows domains should be stripped off from usernames that are
|
||||
* read from the KSM vault.
|
||||
*/
|
||||
private static final BooleanGuacamoleProperty STRIP_WINDOWS_DOMAINS = new BooleanGuacamoleProperty() {
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "ksm-strip-windows-domains";
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether domains should be considered when matching login records in the KSM vault.
|
||||
* If true, both the domain and username must match for a record to match when using
|
||||
* tokens like "KEEPER_USER_*". If false, only the username must match.
|
||||
*/
|
||||
private static final BooleanGuacamoleProperty MATCH_USER_DOMAINS = new BooleanGuacamoleProperty() {
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "ksm-match-domains-for-users";
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The minimum number of milliseconds between KSM API calls.
|
||||
*/
|
||||
private static final LongGuacamoleProperty KSM_API_CALL_INTERVAL = new LongGuacamoleProperty() {
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return "ksm-api-call-interval";
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a new KsmConfigurationService which reads the configuration
|
||||
* from "ksm-token-mapping.yml" and properties from
|
||||
* "guacamole.properties.ksm". The token mapping is a YAML file which lists
|
||||
* each connection parameter token and the name of the secret from which
|
||||
* the value for that token should be read, while the properties file is an
|
||||
* alternative to guacamole.properties where each property value is the
|
||||
* name of a secret containing the actual value.
|
||||
*/
|
||||
public KsmConfigurationService() {
|
||||
super(TOKEN_MAPPING_FILENAME, PROPERTIES_FILENAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether unverified server certificates should be accepted when
|
||||
* communicating with Keeper Secrets Manager.
|
||||
*
|
||||
* @return
|
||||
* true if unverified server certificates should be accepted, false
|
||||
* otherwise.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the value specified within guacamole.properties cannot be
|
||||
* parsed.
|
||||
*/
|
||||
public boolean getAllowUnverifiedCertificate() throws GuacamoleException {
|
||||
return environment.getProperty(ALLOW_UNVERIFIED_CERT, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether user-level KSM configs should be enabled. If this
|
||||
* flag is set to true, users can edit their own KSM configs, as can
|
||||
* admins. If set to false, no existing user-specific KSM configuration
|
||||
* will be exposed through the UI or used when looking up secrets.
|
||||
*
|
||||
* @return
|
||||
* true if user-specific KSM configuration is enabled, false otherwise.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the value specified within guacamole.properties cannot be
|
||||
* parsed.
|
||||
*/
|
||||
public boolean getAllowUserConfig() throws GuacamoleException {
|
||||
return environment.getProperty(ALLOW_USER_CONFIG, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getSplitWindowsUsernames() throws GuacamoleException {
|
||||
return environment.getProperty(STRIP_WINDOWS_DOMAINS, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean getMatchUserRecordsByDomain() throws GuacamoleException {
|
||||
return environment.getProperty(MATCH_USER_DOMAINS, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the minimum number of milliseconds between KSM API calls. If not
|
||||
* otherwise configured, this value will be 10 seconds.
|
||||
*
|
||||
* @return
|
||||
* The minimum number of milliseconds between KSM API calls.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the value specified within guacamole.properties cannot be
|
||||
* parsed or does not exist.
|
||||
*/
|
||||
public long getKsmApiInterval() throws GuacamoleException {
|
||||
return environment.getProperty(KSM_API_CALL_INTERVAL, 10000L);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the globally-defined base-64-encoded JSON KSM configuration blob
|
||||
* as a string.
|
||||
*
|
||||
* @return
|
||||
* The globally-defined base-64-encoded JSON KSM configuration blob
|
||||
* as a string.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the value specified within guacamole.properties cannot be
|
||||
* parsed or does not exist.
|
||||
*/
|
||||
@Nonnull
|
||||
@SuppressWarnings("null")
|
||||
public String getKsmConfig() throws GuacamoleException {
|
||||
|
||||
// This will always return a non-null value; an exception would be
|
||||
// thrown if the required value is not set
|
||||
return environment.getRequiredProperty(KSM_CONFIG);
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a base64-encoded JSON KSM configuration, parse and return a
|
||||
* KeyValueStorage object.
|
||||
*
|
||||
* @param value
|
||||
* The base64-encoded JSON KSM configuration to parse.
|
||||
*
|
||||
* @return
|
||||
* The KeyValueStorage that is a result of the parsing operation
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the provided value is not valid base-64 encoded JSON KSM configuration.
|
||||
*/
|
||||
private static KeyValueStorage parseKsmConfig(String value) throws GuacamoleException {
|
||||
|
||||
// Parse base64 value as KSM config storage
|
||||
try {
|
||||
return new InMemoryStorage(value);
|
||||
}
|
||||
catch (IllegalArgumentException e) {
|
||||
throw new GuacamoleServerException("Invalid base64 configuration "
|
||||
+ "for Keeper Secrets Manager.", e);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the options required to authenticate with Keeper Secrets Manager
|
||||
* when retrieving secrets. These options are read from the contents of
|
||||
* base64-encoded JSON configuration data generated by the Keeper Commander
|
||||
* CLI tool. This configuration data must be passed directly as an argument.
|
||||
*
|
||||
* @param ksmConfig
|
||||
* The KSM configuration blob to parse.
|
||||
*
|
||||
* @return
|
||||
* The options that should be used when connecting to Keeper Secrets
|
||||
* Manager when retrieving secrets.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an invalid ksmConfig parameter is provided.
|
||||
*/
|
||||
@Nonnull
|
||||
public SecretsManagerOptions getSecretsManagerOptions(@Nonnull String ksmConfig) throws GuacamoleException {
|
||||
|
||||
return new SecretsManagerOptions(
|
||||
parseKsmConfig(ksmConfig), null, getAllowUnverifiedCertificate());
|
||||
}
|
||||
}
|
@@ -0,0 +1,675 @@
|
||||
/*
|
||||
* 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.guacamole.vault.ksm.secret;
|
||||
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.assistedinject.Assisted;
|
||||
import com.google.inject.assistedinject.AssistedInject;
|
||||
import com.keepersecurity.secretsManager.core.Hosts;
|
||||
import com.keepersecurity.secretsManager.core.KeeperRecord;
|
||||
import com.keepersecurity.secretsManager.core.KeeperSecrets;
|
||||
import com.keepersecurity.secretsManager.core.Login;
|
||||
import com.keepersecurity.secretsManager.core.Notation;
|
||||
import com.keepersecurity.secretsManager.core.SecretsManager;
|
||||
import com.keepersecurity.secretsManager.core.SecretsManagerOptions;
|
||||
|
||||
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.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.locks.ReadWriteLock;
|
||||
import java.util.concurrent.locks.ReentrantReadWriteLock;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
import org.apache.guacamole.vault.ksm.conf.KsmConfigurationService;
|
||||
import org.apache.guacamole.vault.secret.WindowsUsername;
|
||||
import org.apache.guacamole.vault.ksm.GuacamoleExceptionSupplier;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Client which retrieves records from Keeper Secrets Manager, allowing
|
||||
* content-based record retrieval. Note that because KSM is zero-knowledge,
|
||||
* searching or indexing based on content can only be accomplished by
|
||||
* retrieving and indexing everything. Except for record UIDs (which contain no
|
||||
* information), it's not possible for the server to perform a search of
|
||||
* content on the client's behalf. The client has to perform its own search.
|
||||
*/
|
||||
public class KsmClient {
|
||||
|
||||
/**
|
||||
* Logger for this class.
|
||||
*/
|
||||
private static final Logger logger = LoggerFactory.getLogger(KsmClient.class);
|
||||
|
||||
/**
|
||||
* Service for retrieving configuration information.
|
||||
*/
|
||||
@Inject
|
||||
private KsmConfigurationService confService;
|
||||
|
||||
/**
|
||||
* Service for retrieving data from records.
|
||||
*/
|
||||
@Inject
|
||||
private KsmRecordService recordService;
|
||||
|
||||
/**
|
||||
* The publicly-accessible URL for Keeper's documentation covering Keeper
|
||||
* notation.
|
||||
*/
|
||||
private static final String KEEPER_NOTATION_DOC_URL =
|
||||
"https://docs.keeper.io/secrets-manager/secrets-manager/about/keeper-notation";
|
||||
|
||||
/**
|
||||
* The regular expression that Keeper notation must match to be related to
|
||||
* file retrieval. As the Keeper SDK provides mutually-exclusive for
|
||||
* retrieving secret values and files via notation, the notation must first
|
||||
* be tested to determine whether it refers to a file.
|
||||
*/
|
||||
private static final Pattern KEEPER_FILE_NOTATION = Pattern.compile("^(keeper://)?[^/]*/file/.+");
|
||||
|
||||
/**
|
||||
* The KSM configuration associated with this client instance.
|
||||
*/
|
||||
private final SecretsManagerOptions ksmConfig;
|
||||
|
||||
/**
|
||||
* Read/write lock which guards access to all cached data, including the
|
||||
* timestamp recording the last time the cache was refreshed. Readers of
|
||||
* the cache must first acquire (and eventually release) the read lock, and
|
||||
* writers of the cache must first acquire (and eventually release) the
|
||||
* write lock.
|
||||
*/
|
||||
private final ReadWriteLock cacheLock = new ReentrantReadWriteLock();
|
||||
|
||||
/**
|
||||
* The maximum amount of time that an entry will be stored in the cache
|
||||
* before being refreshed, in milliseconds. This is also the shortest
|
||||
* possible interval between API calls to KSM.
|
||||
*/
|
||||
private final long cacheInterval;
|
||||
|
||||
/**
|
||||
* The timestamp that the cache was last refreshed, in milliseconds, as
|
||||
* returned by System.currentTimeMillis(). This value is automatically
|
||||
* updated if {@link #validateCache()} refreshes the cache. This value must
|
||||
* not be accessed without {@link #cacheLock} acquired appropriately.
|
||||
*/
|
||||
private volatile long cacheTimestamp = 0;
|
||||
|
||||
/**
|
||||
* The full cached set of secrets last retrieved from Keeper Secrets
|
||||
* Manager. This value is automatically updated if {@link #validateCache()}
|
||||
* refreshes the cache. This value must not be accessed without
|
||||
* {@link #cacheLock} acquired appropriately.
|
||||
*/
|
||||
private KeeperSecrets cachedSecrets = null;
|
||||
|
||||
/**
|
||||
* All records retrieved from Keeper Secrets Manager, where each key is the
|
||||
* UID of the corresponding record. The contents of this Map are
|
||||
* automatically updated if {@link #validateCache()} refreshes the cache.
|
||||
* This Map must not be accessed without {@link #cacheLock} acquired
|
||||
* appropriately.
|
||||
*/
|
||||
private final Map<String, KeeperRecord> cachedRecordsByUid = new HashMap<>();
|
||||
|
||||
/**
|
||||
* All records retrieved from Keeper Secrets Manager, where each key is the
|
||||
* hostname or IP address of the corresponding record. The hostname or IP
|
||||
* address of a record is determined by {@link Hosts} fields, thus a record
|
||||
* may be associated with multiple hosts. If a record is associated with
|
||||
* multiple hosts, there will be multiple references to that record within
|
||||
* this Map. The contents of this Map are automatically updated if
|
||||
* {@link #validateCache()} refreshes the cache. This Map must not be
|
||||
* accessed without {@link #cacheLock} acquired appropriately. Before using
|
||||
* a value from this Map, {@link #cachedAmbiguousHosts} must first be
|
||||
* checked to verify that there is indeed only one record associated with
|
||||
* that host.
|
||||
*/
|
||||
private final Map<String, KeeperRecord> cachedRecordsByHost = new HashMap<>();
|
||||
|
||||
/**
|
||||
* The set of all hostnames or IP addresses that are associated with
|
||||
* multiple records, and thus cannot uniquely identify a record. The
|
||||
* contents of this Set are automatically updated if
|
||||
* {@link #validateCache()} refreshes the cache. This Set must not be
|
||||
* accessed without {@link #cacheLock} acquired appropriately.This Set
|
||||
* must be checked before using a value retrieved from
|
||||
* {@link #cachedRecordsByHost}.
|
||||
*/
|
||||
private final Set<String> cachedAmbiguousHosts = new HashSet<>();
|
||||
|
||||
/**
|
||||
* All records retrieved from Keeper Secrets Manager, where each key is the
|
||||
* username/domain of the corresponding record. The username of a record is
|
||||
* determined by {@link Login} and "domain" fields, thus a record may be
|
||||
* associated with multiple users. If a record is associated with multiple
|
||||
* users, there will be multiple references to that record within this Map.
|
||||
* The contents of this Map are automatically updated if
|
||||
* {@link #validateCache()} refreshes the cache. This Map must not be accessed
|
||||
* without {@link #cacheLock} acquired appropriately. Before using a value from
|
||||
* this Map, {@link #cachedAmbiguousUsers} must first be checked to
|
||||
* verify that there is indeed only one record associated with that user.
|
||||
*/
|
||||
private final Map<UserLogin, KeeperRecord> cachedRecordsByUser = new HashMap<>();
|
||||
|
||||
/**
|
||||
* The set of all username/domain combos that are associated with multiple
|
||||
* records, and thus cannot uniquely identify a record. The contents of
|
||||
* this Set are automatically updated if {@link #validateCache()} refreshes
|
||||
* the cache. This Set must not be accessed without {@link #cacheLock}
|
||||
* acquired appropriately. This Set must be checked before using a value
|
||||
* retrieved from {@link #cachedRecordsByUser}.
|
||||
*/
|
||||
private final Set<UserLogin> cachedAmbiguousUsers = new HashSet<>();
|
||||
|
||||
/**
|
||||
* All records retrieved from Keeper Secrets Manager, where each key is the
|
||||
* domain of the corresponding record. The domain of a record is
|
||||
* determined by {@link Login} fields, thus a record may be associated with
|
||||
* multiple domains. If a record is associated with multiple domains, there
|
||||
* will be multiple references to that record within this Map. The contents
|
||||
* of this Map are automatically updated if {@link #validateCache()}
|
||||
* refreshes the cache. This Map must not be accessed without
|
||||
* {@link #cacheLock} acquired appropriately. Before using a value from
|
||||
* this Map, {@link #cachedAmbiguousDomains} must first be checked to
|
||||
* verify that there is indeed only one record associated with that domain.
|
||||
*/
|
||||
private final Map<String, KeeperRecord> cachedRecordsByDomain = new HashMap<>();
|
||||
|
||||
/**
|
||||
* The set of all domains that are associated with multiple records, and
|
||||
* thus cannot uniquely identify a record. The contents of this Set are
|
||||
* automatically updated if {@link #validateCache()} refreshes the cache.
|
||||
* This Set must not be accessed without {@link #cacheLock} acquired
|
||||
* appropriately. This Set must be checked before using a value retrieved
|
||||
* from {@link #cachedRecordsByDomain}.
|
||||
*/
|
||||
private final Set<String> cachedAmbiguousDomains = new HashSet<>();
|
||||
|
||||
/**
|
||||
* Create a new KSM client based around the provided KSM configuration and
|
||||
* API timeout setting.
|
||||
*
|
||||
* @param ksmConfig
|
||||
* The KSM configuration to use when retrieving properties from KSM.
|
||||
*
|
||||
* @param apiInterval
|
||||
* The minimum number of milliseconds that must elapse between KSM API
|
||||
* calls.
|
||||
*/
|
||||
@AssistedInject
|
||||
public KsmClient(
|
||||
@Assisted SecretsManagerOptions ksmConfig,
|
||||
@Assisted long apiInterval) {
|
||||
this.ksmConfig = ksmConfig;
|
||||
this.cacheInterval = apiInterval;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that all cached data is current with respect to
|
||||
* {@link #cacheInterval}, refreshing data from the server as needed.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs preventing the cached data from being refreshed.
|
||||
*/
|
||||
private void validateCache() throws GuacamoleException {
|
||||
|
||||
long currentTime = System.currentTimeMillis();
|
||||
|
||||
// Perform a read-only check that the cache has actually expired before
|
||||
// continuing
|
||||
cacheLock.readLock().lock();
|
||||
try {
|
||||
if (currentTime - cacheTimestamp < cacheInterval)
|
||||
return;
|
||||
}
|
||||
finally {
|
||||
cacheLock.readLock().unlock();
|
||||
}
|
||||
|
||||
cacheLock.writeLock().lock();
|
||||
try {
|
||||
|
||||
// Cache may have been updated since the read-only check. Re-verify
|
||||
// that the cache has expired before continuing with a full refresh
|
||||
if (currentTime - cacheTimestamp < cacheInterval)
|
||||
return;
|
||||
|
||||
// Attempt to pull all records first, allowing that operation to
|
||||
// succeed/fail BEFORE we clear out the last cached success
|
||||
KeeperSecrets secrets = SecretsManager.getSecrets(ksmConfig);
|
||||
List<KeeperRecord> records = secrets.getRecords();
|
||||
|
||||
// Store all secrets within cache
|
||||
cachedSecrets = secrets;
|
||||
|
||||
// Clear unambiguous cache of all records by UID
|
||||
cachedRecordsByUid.clear();
|
||||
|
||||
// Clear cache of host-based records
|
||||
cachedAmbiguousHosts.clear();
|
||||
cachedRecordsByHost.clear();
|
||||
|
||||
// Clear cache of login-based records
|
||||
cachedAmbiguousUsers.clear();
|
||||
cachedRecordsByUser.clear();
|
||||
|
||||
// Clear cache of domain-based records
|
||||
cachedAmbiguousDomains.clear();
|
||||
cachedRecordsByDomain.clear();
|
||||
|
||||
// Parse configuration
|
||||
final boolean shouldSplitUsernames = confService.getSplitWindowsUsernames();
|
||||
final boolean shouldMatchByDomain = confService.getMatchUserRecordsByDomain();
|
||||
|
||||
// Store all records, sorting each into host-based, login-based,
|
||||
// and domain-based buckets
|
||||
records.forEach(record -> {
|
||||
|
||||
// Store based on UID ...
|
||||
cachedRecordsByUid.put(record.getRecordUid(), record);
|
||||
|
||||
// ... and hostname/address
|
||||
String hostname = recordService.getHostname(record);
|
||||
addRecordForHost(record, hostname);
|
||||
|
||||
// ... and domain
|
||||
String domain = recordService.getDomain(record);
|
||||
addRecordForDomain(record, domain);
|
||||
|
||||
// Get the username off of the record
|
||||
String username = recordService.getUsername(record);
|
||||
|
||||
// If we have a username, and there isn't already a domain explicitly defined
|
||||
if (username != null && domain == null && shouldSplitUsernames) {
|
||||
|
||||
// Attempt to split out the domain of the username
|
||||
WindowsUsername usernameAndDomain = (
|
||||
WindowsUsername.splitWindowsUsernameFromDomain(username));
|
||||
|
||||
// Use the username-split domain if available
|
||||
if (usernameAndDomain.hasDomain()) {
|
||||
domain = usernameAndDomain.getDomain();
|
||||
username = usernameAndDomain.getUsername();
|
||||
addRecordForDomain(record, domain);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// If domain matching is not enabled for user records,
|
||||
// explicitly set all domains to null to allow matching
|
||||
// on username only
|
||||
if (!shouldMatchByDomain)
|
||||
domain = null;
|
||||
|
||||
// Store based on login ONLY if no hostname (will otherwise
|
||||
// result in ambiguous entries for servers tied to identical
|
||||
// accounts)
|
||||
if (hostname == null)
|
||||
addRecordForLogin(record, username, domain);
|
||||
|
||||
});
|
||||
|
||||
// Cache has been refreshed
|
||||
this.cacheTimestamp = System.currentTimeMillis();
|
||||
|
||||
}
|
||||
finally {
|
||||
cacheLock.writeLock().unlock();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Associates the given record with the given domain. The domain may be
|
||||
* null. Both {@link #cachedRecordsByDomain} and {@link #cachedAmbiguousDomains}
|
||||
* are updated appropriately. The write lock of {@link #cacheLock} must
|
||||
* already be acquired before invoking this function.
|
||||
*
|
||||
* @param record
|
||||
* The record to associate with the domains in the given field.
|
||||
*
|
||||
* @param domain
|
||||
* The domain that the given record should be associated with.
|
||||
* This may be null.
|
||||
*/
|
||||
private void addRecordForDomain(KeeperRecord record, String domain) {
|
||||
|
||||
if (domain == null)
|
||||
return;
|
||||
|
||||
KeeperRecord existing = cachedRecordsByDomain.putIfAbsent(domain, record);
|
||||
if (existing != null && record != existing)
|
||||
cachedAmbiguousDomains.add(domain);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Associates the given record with the given hostname. The hostname may be
|
||||
* null. Both {@link #cachedRecordsByHost} and {@link #cachedAmbiguousHosts}
|
||||
* are updated appropriately. The write lock of {@link #cacheLock} must
|
||||
* already be acquired before invoking this function.
|
||||
*
|
||||
* @param record
|
||||
* The record to associate with the hosts in the given field.
|
||||
*
|
||||
* @param hostname
|
||||
* The hostname/address that the given record should be associated
|
||||
* with. This may be null.
|
||||
*/
|
||||
private void addRecordForHost(KeeperRecord record, String hostname) {
|
||||
|
||||
if (hostname == null)
|
||||
return;
|
||||
|
||||
KeeperRecord existing = cachedRecordsByHost.putIfAbsent(hostname, record);
|
||||
if (existing != null && record != existing)
|
||||
cachedAmbiguousHosts.add(hostname);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Associates the given record with the given user, and optional domain.
|
||||
* The given username or domain may be null. Both {@link #cachedRecordsByUser}
|
||||
* and {@link #cachedAmbiguousUsers} are updated appropriately. The write
|
||||
* lock of {@link #cacheLock} must already be acquired before invoking this
|
||||
* function.
|
||||
*
|
||||
* @param record
|
||||
* The record to associate with the given user.
|
||||
*
|
||||
* @param username
|
||||
* The username that the given record should be associated with. This
|
||||
* may be null.
|
||||
*
|
||||
* @param domain
|
||||
* The domain that the given record should be associated with. This
|
||||
* may be null.
|
||||
*/
|
||||
private void addRecordForLogin(
|
||||
KeeperRecord record, String username, String domain) {
|
||||
|
||||
if (username == null)
|
||||
return;
|
||||
|
||||
UserLogin userDomain = new UserLogin(username, domain);
|
||||
KeeperRecord existing = cachedRecordsByUser.putIfAbsent(
|
||||
userDomain, record);
|
||||
if (existing != null && record != existing)
|
||||
cachedAmbiguousUsers.add(userDomain);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all records accessible via Keeper Secrets Manager. The records
|
||||
* returned are arbitrarily ordered.
|
||||
*
|
||||
* @return
|
||||
* An unmodifiable Collection of all records accessible via Keeper
|
||||
* Secrets Manager, in no particular order.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs that prevents records from being retrieved.
|
||||
*/
|
||||
public Collection<KeeperRecord> getRecords() throws GuacamoleException {
|
||||
validateCache();
|
||||
cacheLock.readLock().lock();
|
||||
try {
|
||||
return Collections.unmodifiableCollection(cachedRecordsByUid.values());
|
||||
}
|
||||
finally {
|
||||
cacheLock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the record having the given UID. If no such record exists, null
|
||||
* is returned.
|
||||
*
|
||||
* @param uid
|
||||
* The UID of the record to return.
|
||||
*
|
||||
* @return
|
||||
* The record having the given UID, or null if there is no such record.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs that prevents the record from being retrieved.
|
||||
*/
|
||||
public KeeperRecord getRecord(String uid) throws GuacamoleException {
|
||||
validateCache();
|
||||
cacheLock.readLock().lock();
|
||||
try {
|
||||
return cachedRecordsByUid.get(uid);
|
||||
}
|
||||
finally {
|
||||
cacheLock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the record associated with the given hostname or IP address. If
|
||||
* no such record exists, or there are multiple such records, null is
|
||||
* returned.
|
||||
*
|
||||
* @param hostname
|
||||
* The hostname of the record to return.
|
||||
*
|
||||
* @return
|
||||
* The record associated with the given hostname, or null if there is
|
||||
* no such record or multiple such records.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs that prevents the record from being retrieved.
|
||||
*/
|
||||
public KeeperRecord getRecordByHost(String hostname) throws GuacamoleException {
|
||||
validateCache();
|
||||
cacheLock.readLock().lock();
|
||||
try {
|
||||
|
||||
if (cachedAmbiguousHosts.contains(hostname)) {
|
||||
logger.debug("The hostname/address \"{}\" is referenced by "
|
||||
+ "multiple Keeper records and cannot be used to "
|
||||
+ "locate individual secrets.", hostname);
|
||||
return null;
|
||||
}
|
||||
|
||||
return cachedRecordsByHost.get(hostname);
|
||||
|
||||
}
|
||||
finally {
|
||||
cacheLock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the record associated with the given username and domain. If no
|
||||
* such record exists, or there are multiple such records, null is returned.
|
||||
*
|
||||
* @param username
|
||||
* The username of the record to return.
|
||||
*
|
||||
* @param domain
|
||||
* The domain of the record to return, or null if no domain exists.
|
||||
*
|
||||
* @return
|
||||
* The record associated with the given username and domain, or null
|
||||
* if there is no such record or multiple such records.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs that prevents the record from being retrieved.
|
||||
*/
|
||||
public KeeperRecord getRecordByLogin(
|
||||
String username, String domain) throws GuacamoleException {
|
||||
|
||||
validateCache();
|
||||
cacheLock.readLock().lock();
|
||||
|
||||
UserLogin userDomain = new UserLogin(username, domain);
|
||||
|
||||
try {
|
||||
|
||||
if (cachedAmbiguousUsers.contains(userDomain)) {
|
||||
logger.debug("The username \"{}\" with domain \"{}\" is "
|
||||
+ "referenced by multiple Keeper records and "
|
||||
+ "cannot be used to locate individual secrets.",
|
||||
username, domain);
|
||||
return null;
|
||||
}
|
||||
|
||||
return cachedRecordsByUser.get(userDomain);
|
||||
|
||||
}
|
||||
finally {
|
||||
cacheLock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the record associated with the given domain. If no such record
|
||||
* exists, or there are multiple such records, null is returned.
|
||||
*
|
||||
* @param domain
|
||||
* The domain of the record to return.
|
||||
*
|
||||
* @return
|
||||
* The record associated with the given domain, or null if there is
|
||||
* no such record or multiple such records.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs that prevents the record from being retrieved.
|
||||
*/
|
||||
public KeeperRecord getRecordByDomain(String domain) throws GuacamoleException {
|
||||
validateCache();
|
||||
cacheLock.readLock().lock();
|
||||
try {
|
||||
|
||||
if (cachedAmbiguousDomains.contains(domain)) {
|
||||
logger.debug("The domain \"{}\" is referenced by multiple "
|
||||
+ "Keeper records and cannot be used to locate "
|
||||
+ "individual secrets.", domain);
|
||||
return null;
|
||||
}
|
||||
|
||||
return cachedRecordsByDomain.get(domain);
|
||||
|
||||
}
|
||||
finally {
|
||||
cacheLock.readLock().unlock();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of the secret stored within Keeper Secrets Manager and
|
||||
* represented by the given Keeper notation. Keeper notation locates the
|
||||
* value of a specific field, custom field, or file associated with a
|
||||
* specific record. See: https://docs.keeper.io/secrets-manager/secrets-manager/about/keeper-notation
|
||||
*
|
||||
* @param notation
|
||||
* The Keeper notation of the secret to retrieve.
|
||||
*
|
||||
* @return
|
||||
* A Future which completes with the value of the secret represented by
|
||||
* the given Keeper notation, or null if there is no such secret.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the requested secret cannot be retrieved or the Keeper notation
|
||||
* is invalid.
|
||||
*/
|
||||
public Future<String> getSecret(String notation) throws GuacamoleException {
|
||||
return getSecret(notation, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value of the secret stored within Keeper Secrets Manager and
|
||||
* represented by the given Keeper notation. Keeper notation locates the
|
||||
* value of a specific field, custom field, or file associated with a
|
||||
* specific record. See: https://docs.keeper.io/secrets-manager/secrets-manager/about/keeper-notation
|
||||
* If a fallbackFunction is provided, it will be invoked to generate
|
||||
* a return value in the case where no secret is found with the given
|
||||
* keeper notation.
|
||||
*
|
||||
* @param notation
|
||||
* The Keeper notation of the secret to retrieve.
|
||||
*
|
||||
* @param fallbackFunction
|
||||
* A function to invoke in order to produce a Future for return,
|
||||
* if the requested secret is not found. If the provided Function
|
||||
* is null, it will not be run.
|
||||
*
|
||||
* @return
|
||||
* A Future which completes with the value of the secret represented by
|
||||
* the given Keeper notation, or null if there is no such secret.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If the requested secret cannot be retrieved or the Keeper notation
|
||||
* is invalid.
|
||||
*/
|
||||
public Future<String> getSecret(
|
||||
String notation,
|
||||
@Nullable GuacamoleExceptionSupplier<Future<String>> fallbackFunction)
|
||||
throws GuacamoleException {
|
||||
validateCache();
|
||||
cacheLock.readLock().lock();
|
||||
try {
|
||||
|
||||
// Retrieve any relevant file asynchronously
|
||||
Matcher fileNotationMatcher = KEEPER_FILE_NOTATION.matcher(notation);
|
||||
if (fileNotationMatcher.matches())
|
||||
return recordService.download(Notation.getFile(cachedSecrets, notation));
|
||||
|
||||
// Retrieve string values synchronously
|
||||
return CompletableFuture.completedFuture(Notation.getValue(cachedSecrets, notation));
|
||||
|
||||
}
|
||||
|
||||
// Unfortunately, the notation parser within the Keeper SDK
|
||||
// only throws plain Errors and Exceptions.
|
||||
// There is no way to differentiate if an error is caused by
|
||||
// a non-existing record or a pure parse failure.
|
||||
catch (Error | Exception e) {
|
||||
logger.warn("Keeper notation \"{}\" could not be resolved "
|
||||
+ "to a record: {}", notation, e.getMessage());
|
||||
logger.debug("Retrieval of record by Keeper notation failed.", e);
|
||||
|
||||
// If the secret is not found, invoke the fallback function
|
||||
if (fallbackFunction != null)
|
||||
return fallbackFunction.get();
|
||||
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
finally {
|
||||
cacheLock.readLock().unlock();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* 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.guacamole.vault.ksm.secret;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
|
||||
import com.keepersecurity.secretsManager.core.SecretsManagerOptions;
|
||||
|
||||
/**
|
||||
* Factory for creating KsmClient instances.
|
||||
*/
|
||||
public interface KsmClientFactory {
|
||||
|
||||
/**
|
||||
* Returns a new instance of a KsmClient instance associated with
|
||||
* the provided KSM configuration options and API interval.
|
||||
*
|
||||
* @param ksmConfigOptions
|
||||
* The KSM config options to use when constructing the KsmClient
|
||||
* object.
|
||||
*
|
||||
* @param apiInterval
|
||||
* The minimum number of milliseconds that must elapse between KSM API
|
||||
* calls.
|
||||
*
|
||||
* @return
|
||||
* A new KsmClient instance associated with the provided KSM config
|
||||
* options.
|
||||
*/
|
||||
KsmClient create(
|
||||
@Nonnull SecretsManagerOptions ksmConfigOptions, long apiInterval);
|
||||
|
||||
}
|
@@ -0,0 +1,645 @@
|
||||
/*
|
||||
* 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.guacamole.vault.ksm.secret;
|
||||
|
||||
import com.google.inject.Singleton;
|
||||
import com.keepersecurity.secretsManager.core.HiddenField;
|
||||
import com.keepersecurity.secretsManager.core.Host;
|
||||
import com.keepersecurity.secretsManager.core.Hosts;
|
||||
import com.keepersecurity.secretsManager.core.KeeperFile;
|
||||
import com.keepersecurity.secretsManager.core.KeeperRecord;
|
||||
import com.keepersecurity.secretsManager.core.KeeperRecordData;
|
||||
import com.keepersecurity.secretsManager.core.KeeperRecordField;
|
||||
import com.keepersecurity.secretsManager.core.KeyPair;
|
||||
import com.keepersecurity.secretsManager.core.KeyPairs;
|
||||
import com.keepersecurity.secretsManager.core.Login;
|
||||
import com.keepersecurity.secretsManager.core.PamHostnames;
|
||||
import com.keepersecurity.secretsManager.core.Password;
|
||||
import com.keepersecurity.secretsManager.core.SecretsManager;
|
||||
import com.keepersecurity.secretsManager.core.Text;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
|
||||
/**
|
||||
* Service for automatically parsing out secrets and data from Keeper records.
|
||||
*/
|
||||
@Singleton
|
||||
public class KsmRecordService {
|
||||
|
||||
/**
|
||||
* Regular expression which matches the labels of custom fields containing
|
||||
* domains.
|
||||
*/
|
||||
private static final Pattern DOMAIN_LABEL_PATTERN =
|
||||
Pattern.compile("domain", Pattern.CASE_INSENSITIVE);
|
||||
|
||||
/**
|
||||
* Regular expression which matches the labels of custom fields containing
|
||||
* hostnames/addresses.
|
||||
*/
|
||||
private static final Pattern HOSTNAME_LABEL_PATTERN =
|
||||
Pattern.compile("hostname|(ip\\s*)?address", Pattern.CASE_INSENSITIVE);
|
||||
|
||||
/**
|
||||
* Regular expression which matches the labels of custom fields containing
|
||||
* usernames.
|
||||
*/
|
||||
private static final Pattern USERNAME_LABEL_PATTERN =
|
||||
Pattern.compile("username", Pattern.CASE_INSENSITIVE);
|
||||
|
||||
/**
|
||||
* Regular expression which matches the labels of custom fields containing
|
||||
* passwords.
|
||||
*/
|
||||
private static final Pattern PASSWORD_LABEL_PATTERN =
|
||||
Pattern.compile("password", Pattern.CASE_INSENSITIVE);
|
||||
|
||||
/**
|
||||
* Regular expression which matches the labels of custom fields containing
|
||||
* passphrases for private keys.
|
||||
*/
|
||||
private static final Pattern PASSPHRASE_LABEL_PATTERN =
|
||||
Pattern.compile("passphrase", Pattern.CASE_INSENSITIVE);
|
||||
|
||||
/**
|
||||
* Regular expression which matches the labels of custom fields containing
|
||||
* private keys.
|
||||
*/
|
||||
private static final Pattern PRIVATE_KEY_CUSTOM_LABEL_PATTERN =
|
||||
Pattern.compile("private\\s*key", Pattern.CASE_INSENSITIVE);
|
||||
|
||||
/**
|
||||
* Regular expression which matches the labels of standard fields containing
|
||||
* private keys.
|
||||
*/
|
||||
private static final Pattern PRIVATE_KEY_STANDARD_LABEL_PATTERN =
|
||||
Pattern.compile("private\\s*pem\\s*key", Pattern.CASE_INSENSITIVE);
|
||||
|
||||
/**
|
||||
* Regular expression which matches the filenames of private keys attached
|
||||
* to Keeper records.
|
||||
*/
|
||||
private static final Pattern PRIVATE_KEY_FILENAME_PATTERN =
|
||||
Pattern.compile(".*\\.pem", Pattern.CASE_INSENSITIVE);
|
||||
|
||||
/**
|
||||
* Returns the single value stored in the given list. If the list is empty
|
||||
* or contains multiple values, null is returned. Note that null will also
|
||||
* be returned if the single value stored in the list is itself null.
|
||||
*
|
||||
* @param <T>
|
||||
* The type of object stored in the list.
|
||||
*
|
||||
* @param values
|
||||
* The list to retrieve a single value from.
|
||||
*
|
||||
* @return
|
||||
* The single value stored in the given list, or null if the list is
|
||||
* empty or contains multiple values.
|
||||
*/
|
||||
private <T> T getSingleValue(List<T> values) {
|
||||
|
||||
if (values == null || values.size() != 1)
|
||||
return null;
|
||||
|
||||
return values.get(0);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the single value stored in the given list of strings. If the
|
||||
* list is empty, contains multiple values, or contains only a single empty
|
||||
* string, null is returned. Note that null will also be returned if the
|
||||
* single value stored in the list is itself null.
|
||||
*
|
||||
* @param values
|
||||
* The list to retrieve a single value from.
|
||||
*
|
||||
* @return
|
||||
* The single value stored in the given list, or null if the list is
|
||||
* empty, contains multiple values, or contains only a single empty
|
||||
* string.
|
||||
*/
|
||||
private String getSingleStringValue(List<String> values) {
|
||||
|
||||
String value = getSingleValue(values);
|
||||
if (value != null && !value.isEmpty())
|
||||
return value;
|
||||
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the single value stored in the given list, additionally
|
||||
* performing a mapping transformation on the single value. If the list is
|
||||
* empty or contains multiple values, null is returned. Note that null will
|
||||
* also be returned if the mapping transformation returns null for the
|
||||
* single value stored in the list.
|
||||
*
|
||||
* @param <T>
|
||||
* The type of object stored in the list.
|
||||
*
|
||||
* @param <R>
|
||||
* The type of object to return.
|
||||
*
|
||||
* @param values
|
||||
* The list to retrieve a single value from.
|
||||
*
|
||||
* @param mapper
|
||||
* The function to use to map the single object of type T to type R.
|
||||
*
|
||||
* @return
|
||||
* The single value stored in the given list, transformed using the
|
||||
* provided mapping function, or null if the list is empty or contains
|
||||
* multiple values.
|
||||
*/
|
||||
private <T, R> R getSingleValue(List<T> values, Function<T, R> mapper) {
|
||||
|
||||
T value = getSingleValue(values);
|
||||
if (value == null)
|
||||
return null;
|
||||
|
||||
return mapper.apply(value);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the single value stored in the given list of strings,
|
||||
* additionally performing a mapping transformation on the single value. If
|
||||
* the list is empty, contains multiple values, or contains only a single
|
||||
* empty string, null is returned. Note that null will also be returned if
|
||||
* the mapping transformation returns null for the single value stored in
|
||||
* the list.
|
||||
*
|
||||
* @param <T>
|
||||
* The type of object stored in the list.
|
||||
*
|
||||
* @param values
|
||||
* The list to retrieve a single value from.
|
||||
*
|
||||
* @param mapper
|
||||
* The function to use to map the single object of type T to type R.
|
||||
*
|
||||
* @return
|
||||
* The single value stored in the given list, transformed using the
|
||||
* provided mapping function, or null if the list is empty, contains
|
||||
* multiple values, or contains only a single empty string.
|
||||
*/
|
||||
private <T> String getSingleStringValue(List<T> values, Function<T, String> mapper) {
|
||||
|
||||
String value = getSingleValue(values, mapper);
|
||||
if (value != null && !value.isEmpty())
|
||||
return value;
|
||||
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the instance of the only field that has the given type and
|
||||
* matches the given label pattern. If there are no such fields, or
|
||||
* multiple such fields, null is returned.
|
||||
*
|
||||
* @param <T>
|
||||
* The type of field to return.
|
||||
*
|
||||
* @param fields
|
||||
* The list of fields to retrieve the field from. For convenience, this
|
||||
* may be null. A null list will be considered equivalent to an empty
|
||||
* list.
|
||||
*
|
||||
* @param fieldClass
|
||||
* The class representing the type of field to return.
|
||||
*
|
||||
* @param labelPattern
|
||||
* The pattern to match against the desired field's label, or null if
|
||||
* no label pattern match should be performed.
|
||||
*
|
||||
* @return
|
||||
* The field having the given type and matching the given label
|
||||
* pattern, or null if there is not exactly one such field.
|
||||
*/
|
||||
@SuppressWarnings("unchecked") // Manually verified with isAssignableFrom()
|
||||
private <T extends KeeperRecordField> T getField(List<KeeperRecordField> fields,
|
||||
Class<T> fieldClass, Pattern labelPattern) {
|
||||
|
||||
// There are no fields if no List was provided at all
|
||||
if (fields == null)
|
||||
return null;
|
||||
|
||||
T foundField = null;
|
||||
for (KeeperRecordField field : fields) {
|
||||
|
||||
// Ignore fields of wrong class
|
||||
if (!fieldClass.isAssignableFrom(field.getClass()))
|
||||
continue;
|
||||
|
||||
// Match against provided pattern, if any
|
||||
if (labelPattern != null) {
|
||||
|
||||
// Ignore fields without labels if a label match is requested
|
||||
String label = field.getLabel();
|
||||
if (label == null)
|
||||
continue;
|
||||
|
||||
// Ignore fields whose labels do not match
|
||||
Matcher labelMatcher = labelPattern.matcher(label);
|
||||
if (!labelMatcher.matches())
|
||||
continue;
|
||||
|
||||
}
|
||||
|
||||
// Ignore ambiguous fields
|
||||
if (foundField != null)
|
||||
return null;
|
||||
|
||||
// Tentative match found - we can use this as long as no other
|
||||
// field matches the criteria
|
||||
foundField = (T) field;
|
||||
|
||||
}
|
||||
|
||||
return foundField;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the instance of the only field that has the given type and
|
||||
* matches the given label pattern. If there are no such fields, or
|
||||
* multiple such fields, null is returned. Both standard and custom fields
|
||||
* are searched. As standard fields do not have labels, any given label
|
||||
* pattern is ignored for standard fields.
|
||||
*
|
||||
* @param <T>
|
||||
* The type of field to return.
|
||||
*
|
||||
* @param record
|
||||
* The Keeper record to retrieve the field from.
|
||||
*
|
||||
* @param fieldClass
|
||||
* The class representing the type of field to return.
|
||||
*
|
||||
* @param labelPattern
|
||||
* The pattern to match against the labels of custom fields, or null if
|
||||
* no label pattern match should be performed.
|
||||
*
|
||||
* @return
|
||||
* The field having the given type and matching the given label
|
||||
* pattern, or null if there is not exactly one such field.
|
||||
*/
|
||||
private <T extends KeeperRecordField> T getField(KeeperRecord record,
|
||||
Class<T> fieldClass, Pattern labelPattern) {
|
||||
|
||||
KeeperRecordData data = record.getData();
|
||||
|
||||
// Attempt to find standard field first, ignoring custom fields if a
|
||||
// standard field exists (NOTE: standard fields do not have labels)
|
||||
T field = getField(data.getFields(), fieldClass, null);
|
||||
if (field != null)
|
||||
return field;
|
||||
|
||||
// Fall back on custom fields
|
||||
return getField(data.getCustom(), fieldClass, labelPattern);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the file attached to the give Keeper record whose filename
|
||||
* matches the given pattern. If there are no such files, or multiple such
|
||||
* files, null is returned.
|
||||
*
|
||||
* @param record
|
||||
* The record to retrieve the file from.
|
||||
*
|
||||
* @param filenamePattern
|
||||
* The pattern to match filenames against.
|
||||
*
|
||||
* @return
|
||||
* The single matching file attached to the given Keeper record, or
|
||||
* null if there is not exactly one matching file.
|
||||
*/
|
||||
private KeeperFile getFile(KeeperRecord record, Pattern filenamePattern) {
|
||||
|
||||
List<KeeperFile> files = record.getFiles();
|
||||
if (files == null)
|
||||
return null;
|
||||
|
||||
KeeperFile foundFile = null;
|
||||
for (KeeperFile file : files) {
|
||||
|
||||
// Ignore files whose filenames do not match
|
||||
Matcher filenameMatcher = filenamePattern.matcher(file.getData().getName());
|
||||
if (!filenameMatcher.matches())
|
||||
continue;
|
||||
|
||||
// Ignore ambiguous fields
|
||||
if (foundFile != null)
|
||||
return null;
|
||||
|
||||
foundFile = file;
|
||||
|
||||
}
|
||||
|
||||
return foundFile;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads the given file from the Keeper vault asynchronously. All files
|
||||
* are read as UTF-8.
|
||||
*
|
||||
* @param file
|
||||
* The file to download, which may be null.
|
||||
*
|
||||
* @return
|
||||
* A Future which resolves with the contents of the file once
|
||||
* downloaded. If no file was provided (file was null), this Future
|
||||
* resolves with null.
|
||||
*/
|
||||
public Future<String> download(final KeeperFile file) {
|
||||
|
||||
if (file == null)
|
||||
return CompletableFuture.completedFuture(null);
|
||||
|
||||
return CompletableFuture.supplyAsync(() -> {
|
||||
return new String(SecretsManager.downloadFile(file), StandardCharsets.UTF_8);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the single hostname (or address) associated with the given
|
||||
* record. If the record has no associated hostname, or multiple hostnames,
|
||||
* null is returned. Hostnames are retrieved from "Hosts" or "PamHostnames"
|
||||
* fields, as well as "Text" and "Hidden" fields that have the label
|
||||
* "hostname", "address", or "ip address" (case-insensitive, space optional).
|
||||
* These field types are checked in the above order, and the first matching
|
||||
* field is returned.
|
||||
*
|
||||
* @param record
|
||||
* The record to retrieve the hostname from.
|
||||
*
|
||||
* @return
|
||||
* The hostname associated with the given record, or null if the record
|
||||
* has no associated hostname or multiple hostnames.
|
||||
*/
|
||||
public String getHostname(KeeperRecord record) {
|
||||
|
||||
// Prefer standard login field
|
||||
Hosts hostsField = getField(record, Hosts.class, null);
|
||||
if (hostsField != null)
|
||||
return getSingleStringValue(hostsField.getValue(), Host::getHostName);
|
||||
|
||||
// Next, try a PAM hostname
|
||||
PamHostnames pamHostsField = getField(record, PamHostnames.class, null);
|
||||
if (pamHostsField != null)
|
||||
return getSingleStringValue(pamHostsField.getValue(), Host::getHostName);
|
||||
|
||||
KeeperRecordData data = record.getData();
|
||||
List<KeeperRecordField> custom = data.getCustom();
|
||||
|
||||
// Use text "hostname" custom field as fallback ...
|
||||
Text textField = getField(custom, Text.class, HOSTNAME_LABEL_PATTERN);
|
||||
if (textField != null)
|
||||
return getSingleStringValue(textField.getValue());
|
||||
|
||||
// ... or hidden "hostname" custom field
|
||||
HiddenField hiddenField = getField(custom, HiddenField.class, HOSTNAME_LABEL_PATTERN);
|
||||
if (hiddenField != null)
|
||||
return getSingleStringValue(hiddenField.getValue());
|
||||
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the single username associated with the given record. If the
|
||||
* record has no associated username, or multiple usernames, null is
|
||||
* returned. Usernames are retrieved from "Login" fields, as well as
|
||||
* "Text" and "Hidden" fields that have the label "username"
|
||||
* (case-insensitive).
|
||||
*
|
||||
* @param record
|
||||
* The record to retrieve the username from.
|
||||
*
|
||||
* @return
|
||||
* The username associated with the given record, or null if the record
|
||||
* has no associated username or multiple usernames.
|
||||
*/
|
||||
public String getUsername(KeeperRecord record) {
|
||||
|
||||
// Prefer standard login field
|
||||
Login loginField = getField(record, Login.class, null);
|
||||
if (loginField != null)
|
||||
return getSingleStringValue(loginField.getValue());
|
||||
|
||||
KeeperRecordData data = record.getData();
|
||||
List<KeeperRecordField> custom = data.getCustom();
|
||||
|
||||
// Use text "username" custom field as fallback ...
|
||||
Text textField = getField(custom, Text.class, USERNAME_LABEL_PATTERN);
|
||||
if (textField != null)
|
||||
return getSingleStringValue(textField.getValue());
|
||||
|
||||
// ... or hidden "username" custom field
|
||||
HiddenField hiddenField = getField(custom, HiddenField.class, USERNAME_LABEL_PATTERN);
|
||||
if (hiddenField != null)
|
||||
return getSingleStringValue(hiddenField.getValue());
|
||||
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the single domain associated with the given record. If the
|
||||
* record has no associated domain, or multiple domains, null is
|
||||
* returned. Domains are retrieved from "Text" and "Hidden" fields
|
||||
* that have the label "domain" (case-insensitive).
|
||||
*
|
||||
* @param record
|
||||
* The record to retrieve the domain from.
|
||||
*
|
||||
* @return
|
||||
* The domain associated with the given record, or null if the record
|
||||
* has no associated domain or multiple domains.
|
||||
*/
|
||||
public String getDomain(KeeperRecord record) {
|
||||
|
||||
KeeperRecordData data = record.getData();
|
||||
List<KeeperRecordField> custom = data.getCustom();
|
||||
|
||||
// First check text "domain" custom field ...
|
||||
Text textField = getField(custom, Text.class, DOMAIN_LABEL_PATTERN);
|
||||
if (textField != null)
|
||||
return getSingleStringValue(textField.getValue());
|
||||
|
||||
// ... or hidden "domain" custom field if that's not found
|
||||
HiddenField hiddenField = getField(custom, HiddenField.class, DOMAIN_LABEL_PATTERN);
|
||||
if (hiddenField != null)
|
||||
return getSingleStringValue(hiddenField.getValue());
|
||||
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the password associated with the given record. Both standard and
|
||||
* custom fields are searched. Only "Password" and "Hidden" field types are
|
||||
* considered. Custom fields must additionally have the label "password"
|
||||
* (case-insensitive).
|
||||
*
|
||||
* @param record
|
||||
* The record to retrieve the password from.
|
||||
*
|
||||
* @return
|
||||
* The password associated with the given record, or null if the record
|
||||
* has no associated password.
|
||||
*/
|
||||
public String getPassword(KeeperRecord record) {
|
||||
|
||||
Password passwordField = getField(record, Password.class, PASSWORD_LABEL_PATTERN);
|
||||
if (passwordField != null)
|
||||
return getSingleStringValue(passwordField.getValue());
|
||||
|
||||
HiddenField hiddenField = getField(record, HiddenField.class, PASSWORD_LABEL_PATTERN);
|
||||
if (hiddenField != null)
|
||||
return getSingleStringValue(hiddenField.getValue());
|
||||
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the private key associated with the given record. If the record
|
||||
* has no associated private key, or multiple private keys, null is
|
||||
* returned. Private keys are retrieved from "KeyPairs" fields.
|
||||
* Alternatively, private keys are retrieved from PEM-type attachments or
|
||||
* standard "Hidden" fields with the label "private pem key", or custom
|
||||
* fields with the label "private key" if they are "KeyPairs", "Password",
|
||||
* or "Hidden" fields. All label matching is case-insensitive, with spaces
|
||||
* between words being optional. If file downloads are required, they will
|
||||
* be performed asynchronously.
|
||||
*
|
||||
* @param record
|
||||
* The record to retrieve the private key from.
|
||||
*
|
||||
* @return
|
||||
* A Future which resolves with the private key associated with the
|
||||
* given record. If the record has no associated private key or
|
||||
* multiple private keys, the returned Future will resolve to null.
|
||||
*/
|
||||
public Future<String> getPrivateKey(KeeperRecord record) {
|
||||
|
||||
// Attempt to find single matching keypair field
|
||||
KeyPairs keyPairsField = getField(
|
||||
record, KeyPairs.class, PRIVATE_KEY_CUSTOM_LABEL_PATTERN);
|
||||
if (keyPairsField != null) {
|
||||
String privateKey = getSingleStringValue(keyPairsField.getValue(), KeyPair::getPrivateKey);
|
||||
if (privateKey != null && !privateKey.isEmpty())
|
||||
return CompletableFuture.completedFuture(privateKey);
|
||||
}
|
||||
|
||||
// Lacking a typed keypair field, prefer a PEM-type attachment
|
||||
KeeperFile keyFile = getFile(record, PRIVATE_KEY_FILENAME_PATTERN);
|
||||
if (keyFile != null)
|
||||
return download(keyFile);
|
||||
|
||||
KeeperRecordData data = record.getData();
|
||||
List<KeeperRecordField> custom = data.getCustom();
|
||||
|
||||
// Use a hidden "private pem key" standard field as fallback ...
|
||||
HiddenField hiddenField = getField(
|
||||
data.getFields(), HiddenField.class, PRIVATE_KEY_STANDARD_LABEL_PATTERN);
|
||||
if (hiddenField != null)
|
||||
return CompletableFuture.completedFuture(getSingleStringValue(hiddenField.getValue()));
|
||||
|
||||
// ... or password "private key" custom field ...
|
||||
Password passwordField = getField(
|
||||
custom, Password.class, PRIVATE_KEY_CUSTOM_LABEL_PATTERN);
|
||||
if (passwordField != null)
|
||||
return CompletableFuture.completedFuture(getSingleStringValue(passwordField.getValue()));
|
||||
|
||||
// ... or hidden "private key" custom field
|
||||
hiddenField = getField(
|
||||
custom, HiddenField.class, PRIVATE_KEY_CUSTOM_LABEL_PATTERN);
|
||||
if (hiddenField != null)
|
||||
return CompletableFuture.completedFuture(getSingleStringValue(hiddenField.getValue()));
|
||||
|
||||
return CompletableFuture.completedFuture(null);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the passphrase for the private key associated with the given
|
||||
* record. Both standard and custom fields are searched. Only "Password"
|
||||
* and "Hidden" field types are considered. Custom fields must additionally
|
||||
* have the label "passphrase" (case-insensitive). Note that there is no
|
||||
* specific association between private keys and passphrases in the
|
||||
* "KeyPairs" field type.
|
||||
*
|
||||
* @param record
|
||||
* The record to retrieve the passphrase from.
|
||||
*
|
||||
* @return
|
||||
* The passphrase for the private key associated with the given record,
|
||||
* or null if there is no such passphrase associated with the record.
|
||||
*/
|
||||
public String getPassphrase(KeeperRecord record) {
|
||||
|
||||
KeeperRecordData data = record.getData();
|
||||
List<KeeperRecordField> fields = data.getFields();
|
||||
List<KeeperRecordField> custom = data.getCustom();
|
||||
|
||||
// For records with a standard keypair field, the passphrase is the
|
||||
// standard password field
|
||||
if (getField(fields, KeyPairs.class, null) != null) {
|
||||
Password passwordField = getField(fields, Password.class, null);
|
||||
if (passwordField != null)
|
||||
return getSingleStringValue(passwordField.getValue());
|
||||
}
|
||||
|
||||
// For records WITHOUT a standard keypair field, the passphrase can
|
||||
// only reasonably be a custom field (consider a "Login" record with
|
||||
// a pair of custom hidden fields for the private key and passphrase:
|
||||
// the standard password field of the "Login" record refers to the
|
||||
// user's own password, if any, not the passphrase of their key)
|
||||
|
||||
// Use password "private key" custom field as fallback ...
|
||||
Password passwordField = getField(custom, Password.class, PASSPHRASE_LABEL_PATTERN);
|
||||
if (passwordField != null)
|
||||
return getSingleStringValue(passwordField.getValue());
|
||||
|
||||
// ... or hidden "private key" custom field
|
||||
HiddenField hiddenField = getField(custom, HiddenField.class, PASSPHRASE_LABEL_PATTERN);
|
||||
if (hiddenField != null)
|
||||
return getSingleStringValue(hiddenField.getValue());
|
||||
|
||||
return null;
|
||||
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,530 @@
|
||||
/*
|
||||
* 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.guacamole.vault.ksm.secret;
|
||||
|
||||
import com.google.common.base.Objects;
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.Singleton;
|
||||
import com.keepersecurity.secretsManager.core.KeeperRecord;
|
||||
import com.keepersecurity.secretsManager.core.SecretsManagerOptions;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
import java.util.concurrent.Future;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
import org.apache.guacamole.net.auth.Attributes;
|
||||
import org.apache.guacamole.net.auth.Connectable;
|
||||
import org.apache.guacamole.net.auth.Connection;
|
||||
import org.apache.guacamole.net.auth.ConnectionGroup;
|
||||
import org.apache.guacamole.net.auth.Directory;
|
||||
import org.apache.guacamole.net.auth.User;
|
||||
import org.apache.guacamole.net.auth.UserContext;
|
||||
import org.apache.guacamole.protocol.GuacamoleConfiguration;
|
||||
import org.apache.guacamole.token.TokenFilter;
|
||||
import org.apache.guacamole.vault.ksm.GuacamoleExceptionSupplier;
|
||||
import org.apache.guacamole.vault.ksm.conf.KsmAttributeService;
|
||||
import org.apache.guacamole.vault.ksm.conf.KsmConfigurationService;
|
||||
import org.apache.guacamole.vault.ksm.user.KsmDirectory;
|
||||
import org.apache.guacamole.vault.secret.VaultSecretService;
|
||||
import org.apache.guacamole.vault.secret.WindowsUsername;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Service which retrieves secrets from Keeper Secrets Manager.
|
||||
* The configuration used to connect to KSM can be set at a global
|
||||
* level using guacamole.properties, or using a connection group
|
||||
* attribute.
|
||||
*/
|
||||
@Singleton
|
||||
public class KsmSecretService implements VaultSecretService {
|
||||
|
||||
/**
|
||||
* Logger for this class.
|
||||
*/
|
||||
private static final Logger logger = LoggerFactory.getLogger(VaultSecretService.class);
|
||||
|
||||
/**
|
||||
* Service for retrieving data from records.
|
||||
*/
|
||||
@Inject
|
||||
private KsmRecordService recordService;
|
||||
|
||||
/**
|
||||
* Service for retrieving configuration information.
|
||||
*/
|
||||
@Inject
|
||||
private KsmConfigurationService confService;
|
||||
|
||||
/**
|
||||
* Factory for creating KSM client instances.
|
||||
*/
|
||||
@Inject
|
||||
private KsmClientFactory ksmClientFactory;
|
||||
|
||||
/**
|
||||
* A map of base-64 encoded JSON KSM config blobs to associated KSM client instances.
|
||||
* A distinct KSM client will exist for every KSM config.
|
||||
*/
|
||||
private final ConcurrentMap<String, KsmClient> ksmClientMap = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* Create and return a KSM client for the provided KSM config if not already
|
||||
* present in the client map, otherwise return the existing client entry.
|
||||
*
|
||||
* @param ksmConfig
|
||||
* The base-64 encoded JSON KSM config blob associated with the client entry.
|
||||
* If an associated entry does not already exist, it will be created using
|
||||
* this configuration.
|
||||
*
|
||||
* @return
|
||||
* A KSM client for the provided KSM config if not already present in the
|
||||
* client map, otherwise the existing client entry.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs while creating the KSM client.
|
||||
*/
|
||||
private KsmClient getClient(@Nonnull String ksmConfig)
|
||||
throws GuacamoleException {
|
||||
|
||||
// If a client already exists for the provided config, use it
|
||||
KsmClient ksmClient = ksmClientMap.get(ksmConfig);
|
||||
if (ksmClient != null)
|
||||
return ksmClient;
|
||||
|
||||
// Create and store a new KSM client instance for the provided KSM config blob
|
||||
SecretsManagerOptions options = confService.getSecretsManagerOptions(ksmConfig);
|
||||
ksmClient = ksmClientFactory.create(options, confService.getKsmApiInterval());
|
||||
KsmClient prevClient = ksmClientMap.putIfAbsent(ksmConfig, ksmClient);
|
||||
|
||||
// If the client was already set before this thread got there, use the existing one
|
||||
return prevClient != null ? prevClient : ksmClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String canonicalize(String nameComponent) {
|
||||
try {
|
||||
|
||||
// As Keeper notation is essentially a URL, encode all components
|
||||
// using standard URL escaping
|
||||
return URLEncoder.encode(nameComponent, "UTF-8");
|
||||
|
||||
}
|
||||
catch (UnsupportedEncodingException e) {
|
||||
throw new UnsupportedOperationException("Unexpected lack of UTF-8 support.", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Future<String> getValue(UserContext userContext, Connectable connectable,
|
||||
String name) throws GuacamoleException {
|
||||
|
||||
// Attempt to find a KSM config for this connection or group
|
||||
String ksmConfig = getConnectionGroupKsmConfig(userContext, connectable);
|
||||
|
||||
return getClient(ksmConfig).getSecret(name, new GuacamoleExceptionSupplier<Future<String>>() {
|
||||
|
||||
@Override
|
||||
public Future<String> get() throws GuacamoleException {
|
||||
|
||||
// Get the user-supplied KSM config, if allowed by config and
|
||||
// set by the user
|
||||
String userKsmConfig = getUserKSMConfig(userContext, connectable);
|
||||
|
||||
// If the user config happens to be the same as admin-defined one,
|
||||
// don't bother trying again
|
||||
if (userKsmConfig != null && !Objects.equal(userKsmConfig, ksmConfig))
|
||||
return getClient(userKsmConfig).getSecret(name);
|
||||
|
||||
return CompletableFuture.completedFuture(null);
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Future<String> getValue(String name) throws GuacamoleException {
|
||||
|
||||
// Use the default KSM configuration from guacamole.properties
|
||||
return getClient(confService.getKsmConfig()).getSecret(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds contextual parameter tokens for the secrets in the given record to
|
||||
* the given map of existing tokens. The values of each token are
|
||||
* determined from secrets within the record. Depending on the record, this
|
||||
* will be a subset of the username, password, private key, and passphrase.
|
||||
*
|
||||
* @param tokens
|
||||
* The map of parameter tokens that any new tokens should be added to.
|
||||
*
|
||||
* @param prefix
|
||||
* The prefix that should be prepended to each added token.
|
||||
*
|
||||
* @param record
|
||||
* The record to retrieve secrets from when generating tokens. This may
|
||||
* be null.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If configuration details in guacamole.properties cannot be parsed.
|
||||
*/
|
||||
private void addRecordTokens(Map<String, Future<String>> tokens, String prefix,
|
||||
KeeperRecord record) throws GuacamoleException {
|
||||
|
||||
if (record == null)
|
||||
return;
|
||||
|
||||
// Domain of server-related record
|
||||
String domain = recordService.getDomain(record);
|
||||
if (domain != null)
|
||||
tokens.put(prefix + "DOMAIN", CompletableFuture.completedFuture(domain));
|
||||
|
||||
// Username of server-related record
|
||||
String username = recordService.getUsername(record);
|
||||
if (username != null) {
|
||||
|
||||
// If the record had no directly defined domain, but there is a
|
||||
// username, and the configuration is enabled to split Windows
|
||||
// domains out of usernames, attempt to split the domain out now
|
||||
if (domain == null && confService.getSplitWindowsUsernames()) {
|
||||
WindowsUsername usernameAndDomain =
|
||||
WindowsUsername.splitWindowsUsernameFromDomain(username);
|
||||
|
||||
// Always store the username token
|
||||
tokens.put(prefix + "USERNAME", CompletableFuture.completedFuture(
|
||||
usernameAndDomain.getUsername()));
|
||||
|
||||
// Only store the domain if one is detected
|
||||
if (usernameAndDomain.hasDomain())
|
||||
tokens.put(prefix + "DOMAIN", CompletableFuture.completedFuture(
|
||||
usernameAndDomain.getDomain()));
|
||||
|
||||
}
|
||||
|
||||
// If splitting is not enabled, store the whole value in the USERNAME token
|
||||
else {
|
||||
tokens.put(prefix + "USERNAME", CompletableFuture.completedFuture(username));
|
||||
}
|
||||
}
|
||||
|
||||
// Password of server-related record
|
||||
String password = recordService.getPassword(record);
|
||||
if (password != null)
|
||||
tokens.put(prefix + "PASSWORD", CompletableFuture.completedFuture(password));
|
||||
|
||||
// Key passphrase of server-related record
|
||||
String passphrase = recordService.getPassphrase(record);
|
||||
if (passphrase != null)
|
||||
tokens.put(prefix + "PASSPHRASE", CompletableFuture.completedFuture(passphrase));
|
||||
|
||||
// Private key of server-related record
|
||||
Future<String> privateKey = recordService.getPrivateKey(record);
|
||||
tokens.put(prefix + "KEY", privateKey);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for a KSM configuration attribute, recursing up the connection group tree
|
||||
* until a connection group with the appropriate attribute is found. If the KSM config
|
||||
* is found, it will be returned. If not, the default value from the config file will
|
||||
* be returned.
|
||||
*
|
||||
* @param userContext
|
||||
* The userContext associated with the connection or connection group.
|
||||
*
|
||||
* @param connectable
|
||||
* A connection or connection group for which the tokens are being replaced.
|
||||
*
|
||||
* @return
|
||||
* The value of the KSM configuration attribute if found in the tree, the default
|
||||
* KSM config blob defined in guacamole.properties otherwise.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs while attempting to retrieve the KSM config attribute, or if
|
||||
* no KSM config is found in the connection group tree, and the value is also not
|
||||
* defined in the config file.
|
||||
*/
|
||||
@Nonnull
|
||||
private String getConnectionGroupKsmConfig(
|
||||
UserContext userContext, Connectable connectable) throws GuacamoleException {
|
||||
|
||||
// Check to make sure it's a usable type before proceeding
|
||||
if (
|
||||
!(connectable instanceof Connection)
|
||||
&& !(connectable instanceof ConnectionGroup)) {
|
||||
logger.warn(
|
||||
"Unsupported Connectable type: {}; skipping KSM config lookup.",
|
||||
connectable.getClass());
|
||||
|
||||
// Use the default value if searching is impossible
|
||||
return confService.getKsmConfig();
|
||||
}
|
||||
|
||||
// For connections, start searching the parent group for the KSM config
|
||||
// For connection groups, start searching the group directly
|
||||
String parentIdentifier = (connectable instanceof Connection)
|
||||
? ((Connection) connectable).getParentIdentifier()
|
||||
: ((ConnectionGroup) connectable).getIdentifier();
|
||||
|
||||
// Keep track of all group identifiers seen while recursing up the tree
|
||||
// in case there's a cycle - if the same identifier is ever seen twice,
|
||||
// the search is over.
|
||||
Set<String> observedIdentifiers = new HashSet<>();
|
||||
observedIdentifiers.add(parentIdentifier);
|
||||
|
||||
// Use the unwrapped connection group directory to avoid KSM config
|
||||
// value sanitization
|
||||
Directory<ConnectionGroup> connectionGroupDirectory = (
|
||||
(KsmDirectory<ConnectionGroup>) userContext.getConnectionGroupDirectory()
|
||||
).getUnderlyingDirectory();
|
||||
|
||||
while (true) {
|
||||
|
||||
// Fetch the parent group, if one exists
|
||||
ConnectionGroup group = connectionGroupDirectory.get(parentIdentifier);
|
||||
if (group == null)
|
||||
break;
|
||||
|
||||
// If the current connection group has the KSM configuration attribute
|
||||
// set to a non-empty value, return immediately
|
||||
String ksmConfig = group.getAttributes().get(KsmAttributeService.KSM_CONFIGURATION_ATTRIBUTE);
|
||||
if (ksmConfig != null && !ksmConfig.trim().isEmpty())
|
||||
return ksmConfig;
|
||||
|
||||
// Otherwise, keep searching up the tree until an appropriate configuration is found
|
||||
parentIdentifier = group.getParentIdentifier();
|
||||
|
||||
// If the parent is a group that's already been seen, this is a cycle, so there's no
|
||||
// need to search any further
|
||||
if (!observedIdentifiers.add(parentIdentifier))
|
||||
break;
|
||||
}
|
||||
|
||||
// If no KSM configuration was ever found, use the default value
|
||||
return confService.getKsmConfig();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if user-level KSM configuration is enabled for the given
|
||||
* Connectable, false otherwise.
|
||||
*
|
||||
* @param connectable
|
||||
* The connectable to check for whether user-level KSM configs are
|
||||
* enabled.
|
||||
*
|
||||
* @return
|
||||
* True if user-level KSM configuration is enabled for the given
|
||||
* Connectable, false otherwise.
|
||||
*/
|
||||
private boolean isKsmUserConfigEnabled(Connectable connectable) {
|
||||
|
||||
// User-level config is enabled IFF the appropriate attribute is set to true
|
||||
if (connectable instanceof Attributes)
|
||||
return KsmAttributeService.TRUTH_VALUE.equals(((Attributes) connectable).getAttributes().get(
|
||||
KsmAttributeService.KSM_USER_CONFIG_ENABLED_ATTRIBUTE));
|
||||
|
||||
// If there's no attributes to check, the user config cannot be enabled
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the KSM config blob for the current user IFF user KSM configs
|
||||
* are enabled globally, and are enabled for the given connectable. If no
|
||||
* KSM config exists for the given user or KSM configs are not enabled,
|
||||
* null will be returned.
|
||||
*
|
||||
* @param userContext
|
||||
* The user context from which the current user should be fetched.
|
||||
*
|
||||
* @param connectable
|
||||
* The connectable to which the connection is being established. This
|
||||
* is the conneciton which will be checked to see if user KSM configs
|
||||
* are enabled.
|
||||
*
|
||||
* @return
|
||||
* The base64 encoded KSM config blob for the current user if one
|
||||
* exists, and if user KSM configs are enabled globally and for the
|
||||
* provided connectable.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs while attempting to fetch the KSM config.
|
||||
*/
|
||||
private String getUserKSMConfig(
|
||||
UserContext userContext, Connectable connectable) throws GuacamoleException {
|
||||
|
||||
// If user KSM configs are enabled globally, and for the given connectable,
|
||||
// return the user-specific KSM config, if one exists
|
||||
if (confService.getAllowUserConfig() && isKsmUserConfigEnabled(connectable)) {
|
||||
|
||||
// Get the underlying user, to avoid the KSM config sanitization
|
||||
User self = (
|
||||
((KsmDirectory<User>) userContext.getUserDirectory())
|
||||
.getUnderlyingDirectory().get(userContext.self().getIdentifier()));
|
||||
|
||||
return self.getAttributes().get(
|
||||
KsmAttributeService.KSM_CONFIGURATION_ATTRIBUTE);
|
||||
}
|
||||
|
||||
|
||||
// If user-specific KSM config is disabled globally or for the given
|
||||
// connectable, return null to indicate that no user config exists
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Use the provided KSM client to add parameter tokens tokens to the
|
||||
* provided token map. The supplied filter will be used to replace
|
||||
* existing tokens in the provided connection parameters before KSM
|
||||
* record lookup. The supplied GuacamoleConfiguration instance will
|
||||
* be used to check the protocol, in case RDP-specific behavior is
|
||||
* needed.
|
||||
|
||||
* @param config
|
||||
* The GuacamoleConfiguration associated with the Connectable for which
|
||||
* tokens are being added.
|
||||
*
|
||||
* @param ksm
|
||||
* The KSM client to use when fetching records.
|
||||
*
|
||||
* @param tokens
|
||||
* The tokens to which any fetched KSM record values should be added.
|
||||
*
|
||||
* @param parameters
|
||||
* The connection parameters associated with the Connectable for which
|
||||
* tokens are being added.
|
||||
*
|
||||
* @throws GuacamoleException
|
||||
* If an error occurs while attempting to fetch KSM records or check
|
||||
* configuration settings.
|
||||
*/
|
||||
private void addConnectableTokens(
|
||||
GuacamoleConfiguration config, KsmClient ksm, Map<String, Future<String>> tokens,
|
||||
Map<String, String> parameters, TokenFilter filter) throws GuacamoleException {
|
||||
|
||||
// Retrieve and define server-specific tokens, if any
|
||||
String hostname = parameters.get("hostname");
|
||||
if (hostname != null && !hostname.isEmpty())
|
||||
addRecordTokens(tokens, "KEEPER_SERVER_",
|
||||
ksm.getRecordByHost(filter.filter(hostname)));
|
||||
|
||||
// Tokens specific to RDP
|
||||
if ("rdp".equals(config.getProtocol())) {
|
||||
|
||||
// Retrieve and define gateway server-specific tokens, if any
|
||||
String gatewayHostname = parameters.get("gateway-hostname");
|
||||
if (gatewayHostname != null && !gatewayHostname.isEmpty())
|
||||
addRecordTokens(tokens, "KEEPER_GATEWAY_",
|
||||
ksm.getRecordByHost(filter.filter(gatewayHostname)));
|
||||
|
||||
// Retrieve and define domain tokens, if any
|
||||
String domain = parameters.get("domain");
|
||||
String filteredDomain = null;
|
||||
if (domain != null && !domain.isEmpty()) {
|
||||
filteredDomain = filter.filter(domain);
|
||||
addRecordTokens(tokens, "KEEPER_DOMAIN_",
|
||||
ksm.getRecordByDomain(filteredDomain));
|
||||
}
|
||||
|
||||
// Retrieve and define gateway domain tokens, if any
|
||||
String gatewayDomain = parameters.get("gateway-domain");
|
||||
String filteredGatewayDomain = null;
|
||||
if (gatewayDomain != null && !gatewayDomain.isEmpty()) {
|
||||
filteredGatewayDomain = filter.filter(gatewayDomain);
|
||||
addRecordTokens(tokens, "KEEPER_GATEWAY_DOMAIN_",
|
||||
ksm.getRecordByDomain(filteredGatewayDomain));
|
||||
}
|
||||
|
||||
// If domain matching is disabled for user records,
|
||||
// explicitly set the domains to null when storing
|
||||
// user records to enable username-only matching
|
||||
if (!confService.getMatchUserRecordsByDomain()) {
|
||||
filteredDomain = null;
|
||||
filteredGatewayDomain = null;
|
||||
}
|
||||
|
||||
// Retrieve and define user-specific tokens, if any
|
||||
String username = parameters.get("username");
|
||||
if (username != null && !username.isEmpty())
|
||||
addRecordTokens(tokens, "KEEPER_USER_",
|
||||
ksm.getRecordByLogin(filter.filter(username),
|
||||
filteredDomain));
|
||||
|
||||
// Retrieve and define gateway user-specific tokens, if any
|
||||
String gatewayUsername = parameters.get("gateway-username");
|
||||
if (gatewayUsername != null && !gatewayUsername.isEmpty())
|
||||
addRecordTokens(tokens, "KEEPER_GATEWAY_USER_",
|
||||
ksm.getRecordByLogin(
|
||||
filter.filter(gatewayUsername),
|
||||
filteredGatewayDomain));
|
||||
}
|
||||
|
||||
else {
|
||||
|
||||
// Retrieve and define user-specific tokens, if any
|
||||
// NOTE that non-RDP connections do not have a domain
|
||||
// field in the connection parameters, so the domain
|
||||
// will always be null
|
||||
String username = parameters.get("username");
|
||||
if (username != null && !username.isEmpty())
|
||||
addRecordTokens(tokens, "KEEPER_USER_",
|
||||
ksm.getRecordByLogin(filter.filter(username), null));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Future<String>> getTokens(UserContext userContext, Connectable connectable,
|
||||
GuacamoleConfiguration config, TokenFilter filter) throws GuacamoleException {
|
||||
|
||||
Map<String, Future<String>> tokens = new HashMap<>();
|
||||
Map<String, String> parameters = config.getParameters();
|
||||
|
||||
// Only use the user-specific KSM config if explicitly enabled in the global
|
||||
// configuration, AND for the specific connectable being connected to
|
||||
String userKsmConfig = getUserKSMConfig(userContext, connectable);
|
||||
if (userKsmConfig != null && !userKsmConfig.trim().isEmpty())
|
||||
addConnectableTokens(
|
||||
config, getClient(userKsmConfig), tokens, parameters, filter);
|
||||
|
||||
// Add connection group or globally defined tokens after the user-specific
|
||||
// ones to ensure that the user config will be overriden on collision
|
||||
String ksmConfig = getConnectionGroupKsmConfig(userContext, connectable);
|
||||
addConnectableTokens(
|
||||
config, getClient(ksmConfig), tokens, parameters, filter);
|
||||
|
||||
return tokens;
|
||||
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
* 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.guacamole.vault.ksm.secret;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
/**
|
||||
* A class intended for use as a key in KSM user record client cache. This
|
||||
* class contains both a username and a password. When identifying a KSM
|
||||
* record using token syntax like "KEEPER_USER_*", the user record will
|
||||
* actually be identified by both the user and domain, if the appropriate
|
||||
* settings are enabled.
|
||||
*/
|
||||
class UserLogin {
|
||||
|
||||
/**
|
||||
* The username associated with the user record.
|
||||
* This field should never be null.
|
||||
*/
|
||||
private final String username;
|
||||
|
||||
/**
|
||||
* The domain associated with the user record.
|
||||
* This field can be null.
|
||||
*/
|
||||
private final String domain;
|
||||
|
||||
/**
|
||||
* Create a new UserLogin instance with the provided username and
|
||||
* domain. The domain may be null, but the username should never be.
|
||||
*
|
||||
* @param username
|
||||
* The username to create the UserLogin instance with. This should
|
||||
* never be null.
|
||||
*
|
||||
* @param domain
|
||||
* The domain to create the UserLogin instance with. This can be null.
|
||||
*/
|
||||
UserLogin(@Nonnull String username, @Nullable String domain) {
|
||||
this.username = username;
|
||||
this.domain = domain;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
|
||||
return Objects.hash(domain, username);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
|
||||
// Check if the other object is this exact object
|
||||
if (this == obj)
|
||||
return true;
|
||||
|
||||
// Check if the other object is null
|
||||
if (obj == null)
|
||||
return false;
|
||||
|
||||
// Check if the other object is also a UserLogin
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
|
||||
// If the other object is also a UserLogin, it must
|
||||
// have the same username and domain
|
||||
UserLogin other = (UserLogin) obj;
|
||||
return Objects.equals(username, other.username)
|
||||
&& Objects.equals(domain, other.domain);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the username associated with this UserLogin.
|
||||
*
|
||||
* @return
|
||||
* The username associated with this UserLogin.
|
||||
*/
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Get the domain associated with this UserLogin.
|
||||
*
|
||||
* @return
|
||||
* The domain associated with this UserLogin.
|
||||
*/
|
||||
public String getDomain() {
|
||||
return domain;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* 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.guacamole.vault.ksm.user;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.guacamole.net.auth.DelegatingConnection;
|
||||
import org.apache.guacamole.vault.ksm.conf.KsmAttributeService;
|
||||
import org.apache.guacamole.net.auth.Connection;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
|
||||
/**
|
||||
* A Connection that explicitly adds a blank entry for any defined KSM
|
||||
* connection attributes. This ensures that any such field will always
|
||||
* be displayed to the user when editing a connection through the UI.
|
||||
*/
|
||||
public class KsmConnection extends DelegatingConnection {
|
||||
|
||||
/**
|
||||
* Create a new Vault connection wrapping the provided Connection record. Any
|
||||
* attributes defined in the provided connection attribute forms will have empty
|
||||
* values automatically populated when getAttributes() is called.
|
||||
*
|
||||
* @param connection
|
||||
* The connection record to wrap.
|
||||
*/
|
||||
KsmConnection(Connection connection) {
|
||||
super(connection);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the underlying wrapped connection record.
|
||||
*
|
||||
* @return
|
||||
* The wrapped connection record.
|
||||
*/
|
||||
Connection getUnderlyingConnection() {
|
||||
return getDelegateConnection();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> getAttributes() {
|
||||
|
||||
// Make a copy of the existing map
|
||||
Map<String, String> attributes = Maps.newHashMap(super.getAttributes());
|
||||
|
||||
// Add the user-config-enabled configuration attribute
|
||||
attributes.putIfAbsent(KsmAttributeService.KSM_USER_CONFIG_ENABLED_ATTRIBUTE, null);
|
||||
return attributes;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* 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.guacamole.vault.ksm.user;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.guacamole.net.auth.ConnectionGroup;
|
||||
import org.apache.guacamole.net.auth.DelegatingConnectionGroup;
|
||||
import org.apache.guacamole.vault.ksm.conf.KsmAttributeService;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
|
||||
/**
|
||||
* A KSM-specific connection group implementation that always exposes
|
||||
* the KSM_CONFIGURATION_ATTRIBUTE attribute, even when no value is set.
|
||||
* The value of the attribute will be sanitized if non-empty. This ensures
|
||||
* that the attribute will always show up in the UI, even for connection
|
||||
* groups that don't already have it set, and that any sensitive information
|
||||
* in the attribute value will not be exposed.
|
||||
*/
|
||||
public class KsmConnectionGroup extends DelegatingConnectionGroup {
|
||||
|
||||
/**
|
||||
* Create a new KsmConnectionGroup wrapping the provided ConnectionGroup record.
|
||||
*
|
||||
* @param connectionGroup
|
||||
* The ConnectionGroup record to wrap.
|
||||
*/
|
||||
KsmConnectionGroup(ConnectionGroup connectionGroup) {
|
||||
super(connectionGroup);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the underlying wrapped connection group record.
|
||||
*
|
||||
* @return
|
||||
* The wrapped connection group record.
|
||||
*/
|
||||
ConnectionGroup getUnderlyingConnectionGroup() {
|
||||
return getDelegateConnectionGroup();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the underlying ConnectionGroup that's wrapped by this KsmConnectionGroup.
|
||||
*
|
||||
* @return
|
||||
* The underlying ConnectionGroup that's wrapped by this KsmConnectionGroup.
|
||||
*/
|
||||
ConnectionGroup getUnderlyConnectionGroup() {
|
||||
return getDelegateConnectionGroup();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> getAttributes() {
|
||||
|
||||
// Make a copy of the existing map
|
||||
Map<String, String> attributes = Maps.newHashMap(super.getAttributes());
|
||||
|
||||
// Sanitize the KSM configuration attribute, and ensure the attribute
|
||||
// is always present
|
||||
attributes.put(
|
||||
KsmAttributeService.KSM_CONFIGURATION_ATTRIBUTE,
|
||||
KsmAttributeService.sanitizeKsmAttributeValue(
|
||||
attributes.get(KsmAttributeService.KSM_CONFIGURATION_ATTRIBUTE)));
|
||||
|
||||
return attributes;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* 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.guacamole.vault.ksm.user;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
import org.apache.guacamole.net.auth.DelegatingDirectory;
|
||||
import org.apache.guacamole.net.auth.Directory;
|
||||
import org.apache.guacamole.net.auth.Identifiable;
|
||||
|
||||
/**
|
||||
* A KSM-specific version of DecoratingDirectory that exposes the underlying
|
||||
* directory for when it's needed.
|
||||
*/
|
||||
public abstract class KsmDirectory<ObjectType extends Identifiable>
|
||||
extends DelegatingDirectory<ObjectType> {
|
||||
|
||||
/**
|
||||
* Create a new KsmDirectory, delegating to the provided directory.
|
||||
*
|
||||
* @param directory
|
||||
* The directory to delegate to.
|
||||
*/
|
||||
public KsmDirectory(Directory<ObjectType> directory) {
|
||||
super(directory);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the underlying directory that this DecoratingDirectory is
|
||||
* delegating to.
|
||||
*
|
||||
* @return
|
||||
* The underlying directory.
|
||||
*/
|
||||
public Directory<ObjectType> getUnderlyingDirectory() {
|
||||
return getDelegateDirectory();
|
||||
}
|
||||
|
||||
/**
|
||||
* Process and return a potentially-modified version of the object
|
||||
* with the same identifier in the wrapped directory.
|
||||
*
|
||||
* @param object
|
||||
* The object from the underlying directory.
|
||||
*
|
||||
* @return
|
||||
* A potentially-modified version of the object with the same
|
||||
* identifier in the wrapped directory.
|
||||
*/
|
||||
protected abstract ObjectType wrap(ObjectType object);
|
||||
|
||||
@Override
|
||||
public ObjectType get(String identifier) throws GuacamoleException {
|
||||
|
||||
// Process and return the object from the wrapped directory
|
||||
return wrap(super.get(identifier));
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<ObjectType> getAll(Collection<String> identifiers)
|
||||
throws GuacamoleException {
|
||||
|
||||
// Process and return each object from the wrapped directory
|
||||
return super.getAll(identifiers).stream().map(
|
||||
superObject -> wrap(superObject)
|
||||
).collect(Collectors.toList());
|
||||
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,186 @@
|
||||
/*
|
||||
* 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.guacamole.vault.ksm.user;
|
||||
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
import org.apache.guacamole.net.auth.Connection;
|
||||
import org.apache.guacamole.net.auth.ConnectionGroup;
|
||||
import org.apache.guacamole.net.auth.DecoratingDirectory;
|
||||
import org.apache.guacamole.net.auth.Directory;
|
||||
import org.apache.guacamole.net.auth.User;
|
||||
import org.apache.guacamole.vault.ksm.conf.KsmAttributeService;
|
||||
import org.apache.guacamole.vault.user.VaultDirectoryService;
|
||||
|
||||
import com.google.inject.Inject;
|
||||
|
||||
/**
|
||||
* A KSM-specific vault directory service that wraps the connection group directory
|
||||
* to enable automatic translation of KSM one-time tokens into base64-encoded JSON
|
||||
* config bundles.
|
||||
*/
|
||||
public class KsmDirectoryService extends VaultDirectoryService {
|
||||
|
||||
/**
|
||||
* A factory for constructing new KsmUser instances.
|
||||
*/
|
||||
@Inject
|
||||
private KsmUserFactory ksmUserFactory;
|
||||
|
||||
/**
|
||||
* Service for retrieving any custom attributes defined for the
|
||||
* current vault implementation and processing of said attributes.
|
||||
*/
|
||||
@Inject
|
||||
private KsmAttributeService attributeService;
|
||||
|
||||
@Override
|
||||
public Directory<Connection> getConnectionDirectory(
|
||||
Directory<Connection> underlyingDirectory) throws GuacamoleException {
|
||||
|
||||
// A Connection directory that will decorate all connections with a
|
||||
// KsmConnection wrapper to ensure that all defined KSM fields will
|
||||
// be exposed in the connection group attributes.
|
||||
return new DecoratingDirectory<Connection>(underlyingDirectory) {
|
||||
|
||||
@Override
|
||||
protected Connection decorate(Connection connection) throws GuacamoleException {
|
||||
|
||||
// Wrap in a KsmConnection class to ensure that all defined KSM fields will be
|
||||
// present
|
||||
return new KsmConnection(connection);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Connection undecorate(Connection connection) throws GuacamoleException {
|
||||
|
||||
// Unwrap the KsmConnection
|
||||
return ((KsmConnection) connection).getUnderlyingConnection();
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Directory<ConnectionGroup> getConnectionGroupDirectory(
|
||||
Directory<ConnectionGroup> underlyingDirectory) throws GuacamoleException {
|
||||
|
||||
// A ConnectionGroup directory that will intercept add and update calls to
|
||||
// validate KSM configurations, and translate one-time-tokens, if possible,
|
||||
// as well as ensuring that all ConnectionGroups returned include the
|
||||
// KSM_CONFIGURATION_ATTRIBUTE attribute, so it will be available in the UI.
|
||||
// The value of the KSM_CONFIGURATION_ATTRIBUTE will be sanitized if set.
|
||||
return new KsmDirectory<ConnectionGroup>(underlyingDirectory) {
|
||||
|
||||
@Override
|
||||
public void add(ConnectionGroup connectionGroup) throws GuacamoleException {
|
||||
|
||||
// Process attribute values before saving
|
||||
connectionGroup.setAttributes(
|
||||
attributeService.processAttributes(
|
||||
connectionGroup.getAttributes()));
|
||||
|
||||
super.add(connectionGroup);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(ConnectionGroup connectionGroup) throws GuacamoleException {
|
||||
|
||||
// Unwrap the existing ConnectionGroup
|
||||
if (connectionGroup instanceof KsmConnectionGroup)
|
||||
connectionGroup = ((KsmConnectionGroup) connectionGroup).getUnderlyingConnectionGroup();
|
||||
|
||||
// Process attribute values before saving
|
||||
connectionGroup.setAttributes(
|
||||
attributeService.processAttributes(
|
||||
connectionGroup.getAttributes()));
|
||||
|
||||
super.update(connectionGroup);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ConnectionGroup wrap(ConnectionGroup object) {
|
||||
|
||||
// Do not process the ConnectionGroup further if it does not exist
|
||||
if (object == null)
|
||||
return null;
|
||||
|
||||
// Sanitize values when a ConnectionGroup is fetched from the directory
|
||||
return new KsmConnectionGroup(object);
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public Directory<User> getUserDirectory(
|
||||
Directory<User> underlyingDirectory) throws GuacamoleException {
|
||||
|
||||
// A User directory that will intercept add and update calls to
|
||||
// validate KSM configurations, and translate one-time-tokens, if possible
|
||||
// Additionally, this directory will will decorate all users with a
|
||||
// KsmUser wrapper to ensure that all defined KSM fields will be exposed
|
||||
// in the user attributes. The value of the KSM_CONFIGURATION_ATTRIBUTE
|
||||
// will be sanitized if set.
|
||||
return new KsmDirectory<User>(underlyingDirectory) {
|
||||
|
||||
@Override
|
||||
public void add(User user) throws GuacamoleException {
|
||||
|
||||
// Process attribute values before saving
|
||||
user.setAttributes(
|
||||
attributeService.processAttributes(
|
||||
user.getAttributes()));
|
||||
|
||||
super.add(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void update(User user) throws GuacamoleException {
|
||||
|
||||
// Unwrap the existing user
|
||||
if (user instanceof KsmUser)
|
||||
user = ((KsmUser) user).getUnderlyingUser();
|
||||
|
||||
// Process attribute values before saving
|
||||
user.setAttributes(
|
||||
attributeService.processAttributes(
|
||||
user.getAttributes()));
|
||||
|
||||
super.update(user);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
protected User wrap(User object) {
|
||||
|
||||
// Do not process the user further if it does not exist
|
||||
if (object == null)
|
||||
return null;
|
||||
|
||||
// Sanitize values when a user is fetched from the directory
|
||||
return ksmUserFactory.create(object);
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
}
|
@@ -0,0 +1,115 @@
|
||||
/*
|
||||
* 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.guacamole.vault.ksm.user;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.guacamole.GuacamoleException;
|
||||
import org.apache.guacamole.net.auth.User;
|
||||
import org.apache.guacamole.net.auth.DelegatingUser;
|
||||
import org.apache.guacamole.vault.ksm.conf.KsmAttributeService;
|
||||
import org.apache.guacamole.vault.ksm.conf.KsmConfigurationService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.collect.Maps;
|
||||
import com.google.inject.Inject;
|
||||
import com.google.inject.assistedinject.Assisted;
|
||||
import com.google.inject.assistedinject.AssistedInject;
|
||||
|
||||
/**
|
||||
* A KSM-specific user implementation that exposes the
|
||||
* KSM_CONFIGURATION_ATTRIBUTE attribute even if no value is set. but only
|
||||
* if user-specific KSM configuration is enabled. The value of the attribute
|
||||
* will be sanitized if non-empty. This ensures that the attribute will always
|
||||
* show up in the UI when the feature is enabled, even for users that don't
|
||||
* already have it set, and that any sensitive information in the attribute
|
||||
* value will not be exposed.
|
||||
*/
|
||||
public class KsmUser extends DelegatingUser {
|
||||
|
||||
/**
|
||||
* Logger for this class.
|
||||
*/
|
||||
private static final Logger logger = LoggerFactory.getLogger(KsmUser.class);
|
||||
|
||||
/**
|
||||
* Service for retrieving KSM configuration details.
|
||||
*/
|
||||
@Inject
|
||||
private KsmConfigurationService configurationService;
|
||||
|
||||
/**
|
||||
* Create a new Ksmuser wrapping the provided User record.
|
||||
*
|
||||
* @param user
|
||||
* The User record to wrap.
|
||||
*/
|
||||
@AssistedInject
|
||||
KsmUser(@Assisted User user) {
|
||||
super(user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the underlying wrapped user record.
|
||||
*
|
||||
* @return
|
||||
* The wrapped user record.
|
||||
*/
|
||||
User getUnderlyingUser() {
|
||||
return getDelegateUser();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> getAttributes() {
|
||||
|
||||
// Make a copy of the existing map
|
||||
Map<String, String> attributes = Maps.newHashMap(super.getAttributes());
|
||||
|
||||
// Figure out if user-level KSM config is enabled
|
||||
boolean userKsmConfigEnabled = false;
|
||||
try {
|
||||
userKsmConfigEnabled = configurationService.getAllowUserConfig();
|
||||
} catch (GuacamoleException e) {
|
||||
|
||||
logger.warn(
|
||||
"Disabling user KSM config due to exception: {}"
|
||||
, e.getMessage());
|
||||
logger.debug("Error looking up if user KSM config is enabled.", e);
|
||||
|
||||
}
|
||||
|
||||
// If user-specific KSM configuration is not enabled, do not expose the
|
||||
// attribute at all
|
||||
if (!userKsmConfigEnabled)
|
||||
attributes.remove(KsmAttributeService.KSM_CONFIGURATION_ATTRIBUTE);
|
||||
|
||||
else
|
||||
// Sanitize the KSM configuration attribute, and ensure the attribute
|
||||
// is always present
|
||||
attributes.put(
|
||||
KsmAttributeService.KSM_CONFIGURATION_ATTRIBUTE,
|
||||
KsmAttributeService.sanitizeKsmAttributeValue(
|
||||
attributes.get(KsmAttributeService.KSM_CONFIGURATION_ATTRIBUTE)));
|
||||
|
||||
return attributes;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* 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.guacamole.vault.ksm.user;
|
||||
|
||||
import org.apache.guacamole.net.auth.User;
|
||||
|
||||
/**
|
||||
* Factory for creating KSM-specific users, which wrap an underlying User.
|
||||
*/
|
||||
public interface KsmUserFactory {
|
||||
|
||||
/**
|
||||
* Returns a new instance of a KsmUser, wrapping the provided underlying User.
|
||||
*
|
||||
* @param user
|
||||
* The underlying User that should be wrapped.
|
||||
*
|
||||
* @return
|
||||
* A new instance of a KsmUser, wrapping the provided underlying User.
|
||||
*/
|
||||
KsmUser create(User user);
|
||||
|
||||
}
|
@@ -0,0 +1,16 @@
|
||||
{
|
||||
|
||||
"guacamoleVersion" : "1.6.0",
|
||||
|
||||
"name" : "Keeper Secrets Manager",
|
||||
"namespace" : "keeper-secrets-manager",
|
||||
|
||||
"authProviders" : [
|
||||
"org.apache.guacamole.vault.ksm.KsmAuthenticationProvider"
|
||||
],
|
||||
|
||||
"translations" : [
|
||||
"translations/en.json"
|
||||
]
|
||||
|
||||
}
|
@@ -0,0 +1,25 @@
|
||||
{
|
||||
|
||||
"DATA_SOURCE_KEEPER_SECRETS_MANAGER" : {
|
||||
"NAME" : "Keeper Secrets Manager"
|
||||
},
|
||||
|
||||
"CONNECTION_ATTRIBUTES" : {
|
||||
"SECTION_HEADER_KSM_CONFIG" : "Keeper Secrets Manager",
|
||||
"FIELD_HEADER_KSM_USER_CONFIG_ENABLED" : "Allow user-provided KSM configuration"
|
||||
},
|
||||
|
||||
"CONNECTION_GROUP_ATTRIBUTES" : {
|
||||
"SECTION_HEADER_KSM_CONFIG" : "Keeper Secrets Manager",
|
||||
"FIELD_HEADER_KSM_CONFIG" : "KSM Service Configuration ",
|
||||
|
||||
"ERROR_INVALID_KSM_CONFIG_BLOB" : "The provided base64-encoded KSM configuration blob is not valid. Please ensure that you have copied the entire blob.",
|
||||
"ERROR_INVALID_KSM_ONE_TIME_TOKEN" : "The provided configuration is not a valid KSM one-time token or base64-encoded configuration blob. Please ensure that you have copied the entire token value."
|
||||
},
|
||||
|
||||
"USER_ATTRIBUTES" : {
|
||||
"SECTION_HEADER_KSM_CONFIG" : "Keeper Secrets Manager",
|
||||
"FIELD_HEADER_KSM_CONFIG" : "KSM Service Configuration "
|
||||
}
|
||||
|
||||
}
|
67
extensions/guacamole-vault/pom.xml
Normal file
67
extensions/guacamole-vault/pom.xml
Normal file
@@ -0,0 +1,67 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
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.
|
||||
-->
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
|
||||
http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.apache.guacamole</groupId>
|
||||
<artifactId>guacamole-vault</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
<version>1.6.0</version>
|
||||
<name>guacamole-vault</name>
|
||||
<url>http://guacamole.apache.org/</url>
|
||||
|
||||
<parent>
|
||||
<groupId>org.apache.guacamole</groupId>
|
||||
<artifactId>extensions</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<relativePath>../</relativePath>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
|
||||
<!-- Distribution .tar.gz -->
|
||||
<module>modules/guacamole-vault-dist</module>
|
||||
|
||||
<!-- Base key vault classes -->
|
||||
<module>modules/guacamole-vault-base</module>
|
||||
|
||||
<!-- Provider-specific implementations -->
|
||||
<module>modules/guacamole-vault-ksm</module>
|
||||
|
||||
</modules>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
|
||||
<!-- Guacamole Extension API -->
|
||||
<dependency>
|
||||
<groupId>org.apache.guacamole</groupId>
|
||||
<artifactId>guacamole-ext</artifactId>
|
||||
<version>1.6.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
</project>
|
Reference in New Issue
Block a user