Skip to content

Support TextEncryptor in new ConfigData framework #872

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 20, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
* Copyright 2013-2020 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.cloud.bootstrap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.boot.context.properties.bind.AbstractBindHandler;
import org.springframework.boot.context.properties.bind.BindContext;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.source.ConfigurationPropertyName;
import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
import org.springframework.security.crypto.encrypt.TextEncryptor;

/**
* BindHandler that uses a TextEncryptor to decrypt text if properly prefixed with
* {cipher}.
*
* @author Marcin Grzejszczak
* @since 3.0.0
*/
class TextEncryptorBindHandler extends AbstractBindHandler {

private static final Log logger = LogFactory.getLog(TextEncryptorBindHandler.class);

/**
* Prefix indicating an encrypted value.
*/
protected static final String ENCRYPTED_PROPERTY_PREFIX = "{cipher}";

private final TextEncryptor textEncryptor;

private final KeyProperties keyProperties;

TextEncryptorBindHandler(TextEncryptor textEncryptor, KeyProperties keyProperties) {
this.textEncryptor = textEncryptor;
this.keyProperties = keyProperties;
}

@Override
public Object onSuccess(ConfigurationPropertyName name, Bindable<?> target, BindContext context, Object result) {
if (result instanceof String && ((String) result).startsWith(ENCRYPTED_PROPERTY_PREFIX)) {
return decrypt(name.toString(), (String) result);
}
return result;
}

private String decrypt(String key, String original) {
String value = original.substring(ENCRYPTED_PROPERTY_PREFIX.length());
try {
value = this.textEncryptor.decrypt(value);
if (logger.isDebugEnabled()) {
logger.debug("Decrypted: key=" + key);
}
return value;
}
catch (Exception e) {
String message = "Cannot decrypt: key=" + key;
if (logger.isDebugEnabled()) {
logger.warn(message, e);
}
else {
logger.warn(message);
}
if (this.keyProperties.isFailOnError()) {
throw new IllegalStateException(message, e);
}
return "";
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
/*
* Copyright 2012-2020 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.cloud.bootstrap;

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.BootstrapContext;
import org.springframework.boot.BootstrapRegistry;
import org.springframework.boot.Bootstrapper;
import org.springframework.boot.context.properties.bind.BindHandler;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.cloud.bootstrap.encrypt.KeyProperties;
import org.springframework.cloud.bootstrap.encrypt.RsaProperties;
import org.springframework.cloud.context.encrypt.EncryptorFactory;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;
import org.springframework.security.rsa.crypto.RsaSecretEncryptor;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

/**
* Bootstrapper.
*
* @author Marcin Grzejszczak
* @since 3.0.0
*/
public class TextEncryptorConfigBootstrapper implements Bootstrapper {

private static final boolean RSA_IS_PRESENT = ClassUtils
.isPresent("org.springframework.security.rsa.crypto.RsaSecretEncryptor", null);

@Override
public void intitialize(BootstrapRegistry registry) {
if (!ClassUtils.isPresent("org.springframework.security.crypto.encrypt.TextEncryptor", null)) {
return;
}

registry.registerIfAbsent(KeyProperties.class, context -> context.get(Binder.class)
.bind(KeyProperties.PREFIX, KeyProperties.class).orElseGet(KeyProperties::new));
if (RSA_IS_PRESENT) {
registry.registerIfAbsent(RsaProperties.class, context -> context.get(Binder.class)
.bind(RsaProperties.PREFIX, RsaProperties.class).orElseGet(RsaProperties::new));
}
registry.registerIfAbsent(TextEncryptor.class, context -> {
KeyProperties keyProperties = context.get(KeyProperties.class);
if (keysConfigured(keyProperties)) {
if (RSA_IS_PRESENT) {
RsaProperties rsaProperties = context.get(RsaProperties.class);
return rsaTextEncryptor(keyProperties, rsaProperties);
}
return new EncryptorFactory(keyProperties.getSalt()).create(keyProperties.getKey());
}
// no keys configured
return new FailsafeTextEncryptor();
});
registry.registerIfAbsent(BindHandler.class, context -> {
TextEncryptor textEncryptor = context.get(TextEncryptor.class);
if (textEncryptor != null) {
KeyProperties keyProperties = context.get(KeyProperties.class);
return new TextEncryptorBindHandler(textEncryptor, keyProperties);
}
return null;
});

// promote beans to context
registry.addCloseListener(event -> {
if (isLegacyBootstrap(event.getApplicationContext().getEnvironment())) {
return;
}
BootstrapContext bootstrapContext = event.getBootstrapContext();
KeyProperties keyProperties = bootstrapContext.get(KeyProperties.class);
ConfigurableListableBeanFactory beanFactory = event.getApplicationContext().getBeanFactory();
if (keyProperties != null) {
beanFactory.registerSingleton("keyProperties", keyProperties);
}
if (RSA_IS_PRESENT) {
RsaProperties rsaProperties = bootstrapContext.get(RsaProperties.class);
if (rsaProperties != null) {
beanFactory.registerSingleton("rsaProperties", rsaProperties);
}
}
TextEncryptor textEncryptor = bootstrapContext.get(TextEncryptor.class);
if (textEncryptor != null) {
beanFactory.registerSingleton("textEncryptor", textEncryptor);
}
});
}

public static TextEncryptor rsaTextEncryptor(KeyProperties keyProperties, RsaProperties rsaProperties) {
KeyProperties.KeyStore keyStore = keyProperties.getKeyStore();
if (keyStore.getLocation() != null) {
if (keyStore.getLocation().exists()) {
return new RsaSecretEncryptor(
new KeyStoreKeyFactory(keyStore.getLocation(), keyStore.getPassword().toCharArray())
.getKeyPair(keyStore.getAlias(), keyStore.getSecret().toCharArray()),
rsaProperties.getAlgorithm(), rsaProperties.getSalt(), rsaProperties.isStrong());
}

throw new IllegalStateException("Invalid keystore location");
}

return new EncryptorFactory(keyProperties.getSalt()).create(keyProperties.getKey());
}

public static boolean keysConfigured(KeyProperties properties) {
if (hasProperty(properties.getKeyStore().getLocation())) {
if (hasProperty(properties.getKeyStore().getPassword())) {
return true;
}
return false;
}
else if (hasProperty(properties.getKey())) {
return true;
}
return false;
}

static boolean hasProperty(Object value) {
if (value instanceof String) {
return StringUtils.hasText((String) value);
}
return value != null;
}

static boolean isLegacyBootstrap(Environment environment) {
boolean isLegacy = environment.getProperty("spring.config.use-legacy-processing", Boolean.class, false);
boolean isBootstrapEnabled = environment.getProperty("spring.cloud.bootstrap.enabled", Boolean.class, false);
return isLegacy || isBootstrapEnabled;
}

/**
* TextEncryptor that just fails, so that users don't get a false sense of security
* adding ciphers to config files and not getting them decrypted.
*
* @author Dave Syer
*
*/
public static class FailsafeTextEncryptor implements TextEncryptor {

@Override
public String encrypt(String text) {
throw new UnsupportedOperationException(
"No encryption for FailsafeTextEncryptor. Did you configure the keystore correctly?");
}

@Override
public String decrypt(String encryptedText) {
throw new UnsupportedOperationException(
"No decryption for FailsafeTextEncryptor. Did you configure the keystore correctly?");
}

}

}
Loading