Refactoring to support ALF-9510, ALF-8702

ALF-8702: Solr-Repository SSL Communications (see solr/source/solr/instance/HowToSetUpSolr.txt
ALF-9510: Initial checkin

git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/HEAD/root@30005 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
Steven Glover
2011-08-23 18:34:15 +00:00
parent 6f73e4153c
commit f7f23f6eb7
22 changed files with 1109 additions and 269 deletions

View File

@@ -0,0 +1,68 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.encryption;
import org.springframework.context.ApplicationEvent;
import org.springframework.extensions.surf.util.AbstractLifecycleBean;
/**
*
* @since 4.0
*
*/
public class BootstrapReEncryptor extends AbstractLifecycleBean
{
private boolean enabled;
private ReEncryptor reEncryptor;
private KeyStoreParameters oldKeyStoreParameters;
public void setEnabled(boolean enabled)
{
this.enabled = enabled;
}
public void setReEncryptor(ReEncryptor reEncryptor)
{
this.reEncryptor = reEncryptor;
}
public void setOldKeyStoreParameters(KeyStoreParameters oldKeyStoreParameters)
{
this.oldKeyStoreParameters = oldKeyStoreParameters;
}
public void reEncrypt()
{
reEncryptor.execute(oldKeyStoreParameters);
}
@Override
protected void onBootstrap(ApplicationEvent event)
{
if(enabled)
{
reEncrypt();
}
}
@Override
protected void onShutdown(ApplicationEvent event)
{
}
}

View File

@@ -18,17 +18,6 @@
*/
package org.alfresco.encryption;
import java.io.Serializable;
import java.security.InvalidKeyException;
import java.util.List;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.attributes.AttributeService;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.EqualsHelper;
import org.alfresco.util.GUID;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationEvent;
@@ -38,6 +27,7 @@ import org.springframework.extensions.surf.util.AbstractLifecycleBean;
* The EncryptionChecker checks the state of the repository's encryption system.
* In particular it checks:
* <ul>
* <li> that the keystore exists and, if not, creates one.
* <li> that the encryption keys have not been changed. If so, the bootstrap will be halted.
* </ul>
*
@@ -47,96 +37,31 @@ import org.springframework.extensions.surf.util.AbstractLifecycleBean;
public class EncryptionChecker extends AbstractLifecycleBean
{
private static Log logger = LogFactory. getLog(EncryptionChecker.class);
public static String TOP_LEVEL_KEY = "keyCheck";
private static enum KEY_STATUS
{
OK, CHANGED, MISSING;
};
private TransactionService transactionService;
private AttributeService attributeService;
private Encryptor encryptor;
private List<String> keyAliases;
public void setTransactionService(TransactionService transactionService)
private KeyStoreChecker keyStoreChecker;
private KeyStoreParameters keyStoreParameters;
private KeyResourceLoader keyResourceLoader;
public void setkeyStoreParameters(KeyStoreParameters keyStoreParameters)
{
this.transactionService = transactionService;
this.keyStoreParameters = keyStoreParameters;
}
public void setAttributeService(AttributeService attributeService)
public void setKeyStoreChecker(KeyStoreChecker keyStoreChecker)
{
this.attributeService = attributeService;
this.keyStoreChecker = keyStoreChecker;
}
public void setKeyAliases(List<String> keyAliases)
public void setKeyResourceLoader(KeyResourceLoader keyResourceLoader)
{
this.keyAliases = keyAliases;
}
public void setEncryptor(Encryptor encryptor)
{
this.encryptor = encryptor;
}
private void removeKey(String keyAlias)
{
attributeService.removeAttributes(TOP_LEVEL_KEY);
logger.info("Removed registered key " + keyAlias);
}
private KEY_STATUS checkKey(String keyAlias)
{
if(attributeService.exists(TOP_LEVEL_KEY, keyAlias))
{
try
{
// check that the key has not changed by decrypting the encrypted guid attribute
// comparing against the guid
KeyCheck keyCheck = (KeyCheck)attributeService.getAttribute(TOP_LEVEL_KEY, keyAlias);
Serializable storedGUID = encryptor.unsealObject(keyAlias, keyCheck.getEncrypted());
return EqualsHelper.nullSafeEquals(storedGUID, keyCheck.getGuid()) ? KEY_STATUS.OK : KEY_STATUS.CHANGED;
}
catch(InvalidKeyException e)
{
// key exception indicates that the key has changed - it can't decrypt the
// previously-encrypted data
return KEY_STATUS.CHANGED;
}
}
else
{
// register the key by creating an attribute that stores a guid and its encrypted value
String guid = GUID.generate();
Serializable encrypted = encryptor.sealObject(keyAlias, null, guid);
KeyCheck keyCheck = new KeyCheck(guid, encrypted);
attributeService.createAttribute(keyCheck, TOP_LEVEL_KEY, keyAlias);
logger.info("Registered key " + keyAlias);
return KEY_STATUS.MISSING;
}
this.keyResourceLoader = keyResourceLoader;
}
@Override
protected void onBootstrap(ApplicationEvent event)
{
RetryingTransactionHelper retryingTransactionHelper = transactionService.getRetryingTransactionHelper();
final RetryingTransactionCallback<Void> checkKeysCallback = new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
for(String keyAlias : keyAliases)
{
KEY_STATUS keyStatus = checkKey(keyAlias);
if(keyStatus == KEY_STATUS.CHANGED)
{
// Note: this will halt the application bootstrap.
throw new AlfrescoRuntimeException("The key with alias " + keyAlias + " has been changed, re-instate the previous keystore");
}
}
return null;
}
};
retryingTransactionHelper.doInTransaction(checkKeysCallback, false);
AlfrescoKeyStore mainKeyStore = new CachingKeyStore(keyStoreParameters, keyResourceLoader);
keyStoreChecker.checkKeyStore(mainKeyStore);
}
@Override
@@ -144,70 +69,4 @@ public class EncryptionChecker extends AbstractLifecycleBean
{
}
public void removeRegisteredKeys()
{
RetryingTransactionHelper retryingTransactionHelper = transactionService.getRetryingTransactionHelper();
final RetryingTransactionCallback<Void> removeKeysCallback = new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
for(String keyAlias : keyAliases)
{
removeKey(keyAlias);
}
return null;
}
};
retryingTransactionHelper.doInTransaction(removeKeysCallback, false);
}
/**
* A KeyCheck object stores a well-known guid and it's encrypted value.
*
* @since 4.0
*
*/
private static class KeyCheck implements Serializable
{
private static final long serialVersionUID = 4514315444977162903L;
private String guid;
private Serializable encrypted;
public KeyCheck(String guid, Serializable encrypted)
{
super();
this.guid = guid;
this.encrypted = encrypted;
}
public String getGuid()
{
return guid;
}
public Serializable getEncrypted()
{
return encrypted;
}
public boolean equals(Object other)
{
if(this == other)
{
return true;
}
if(!(other instanceof KeyCheck))
{
return false;
}
KeyCheck keyCheck = (KeyCheck)other;
return EqualsHelper.nullSafeEquals(keyCheck.getGuid(), getGuid()) &&
EqualsHelper.nullSafeEquals(keyCheck.getEncrypted(), getEncrypted());
}
}
}

View File

@@ -0,0 +1,353 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.encryption;
import java.io.FileOutputStream;
import java.io.Serializable;
import java.security.InvalidKeyException;
import java.security.Key;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.attributes.AttributeService;
import org.alfresco.service.cmr.attributes.AttributeService.AttributeQueryCallback;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.EqualsHelper;
import org.alfresco.util.GUID;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Validates an Alfresco keystore by ensuring that it's registered keys have not changed.
*
* @since 4.0
*
*/
public class KeyStoreChecker
{
public static String TOP_LEVEL_KEY = "keyCheck";
private static final Log logger = LogFactory.getLog(KeyStoreChecker.class);
private static enum KEY_STATUS
{
OK, CHANGED, MISSING;
};
private AttributeService attributeService;
private Encryptor encryptor;
private TransactionService transactionService;
public KeyStoreChecker()
{
}
public void setAttributeService(AttributeService attributeService)
{
this.attributeService = attributeService;
}
public void setEncryptor(Encryptor encryptor)
{
this.encryptor = encryptor;
}
public void setTransactionService(TransactionService transactionService)
{
this.transactionService = transactionService;
}
public KeyStoreChecker(AttributeService attributeService, Encryptor encryptor, TransactionService transactionService)
{
this.attributeService = attributeService;
this.transactionService = transactionService;
this.encryptor = encryptor;
}
private KEY_STATUS checkKey(AlfrescoKeyStore keyStore, String keyAlias)
{
if(attributeService.exists(TOP_LEVEL_KEY, keyStore.getLocation(), keyAlias))
{
try
{
// check that the key has not changed by decrypting the encrypted guid attribute
// comparing against the guid
KeyCheck keyCheck = (KeyCheck)attributeService.getAttribute(TOP_LEVEL_KEY, keyStore.getLocation(), keyAlias);
Serializable storedGUID = encryptor.unsealObject(keyAlias, keyCheck.getEncrypted());
return EqualsHelper.nullSafeEquals(storedGUID, keyCheck.getGuid()) ? KEY_STATUS.OK : KEY_STATUS.CHANGED;
}
catch(InvalidKeyException e)
{
// key exception indicates that the key has changed - it can't decrypt the
// previously-encrypted data
return KEY_STATUS.CHANGED;
}
}
else
{
return KEY_STATUS.MISSING;
}
}
private void registerKey(AlfrescoKeyStore keyStore, String keyAlias)
{
// register the key by creating an attribute that stores a guid and its encrypted value
String guid = GUID.generate();
Serializable encrypted = encryptor.sealObject(keyAlias, null, guid);
KeyCheck keyCheck = new KeyCheck(guid, encrypted);
attributeService.createAttribute(keyCheck, TOP_LEVEL_KEY, keyStore.getLocation(), keyAlias);
logger.info("Registered key " + keyAlias);
}
protected KeysReport getKeysReport(AlfrescoKeyStore keyStore)
{
final List<String> registeredKeys = new ArrayList<String>();
if(attributeService.exists(TOP_LEVEL_KEY, keyStore.getLocation()))
{
attributeService.getAttributes(new AttributeQueryCallback()
{
public boolean handleAttribute(Long id, Serializable value,
Serializable[] keys)
{
registeredKeys.add((String)value);
return true;
}
},
TOP_LEVEL_KEY, keyStore.getLocation());
}
List<String> keyAliasesChanged = new ArrayList<String>();
List<String> keyAliasesUnchanged = new ArrayList<String>();
for(String keyAlias : registeredKeys)
{
KEY_STATUS keyStatus = checkKey(keyStore, keyAlias);
if(keyStatus == KEY_STATUS.CHANGED)
{
keyAliasesChanged.add(keyAlias);
}
else
{
keyAliasesUnchanged.add(keyAlias);
}
}
return new KeysReport(keyAliasesChanged, keyAliasesUnchanged);
}
public void checkKeyStore(final AlfrescoKeyStore keyStore)
{
RetryingTransactionHelper retryingTransactionHelper = transactionService.getRetryingTransactionHelper();
final RetryingTransactionCallback<Void> checkKeysCallback = new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
KeysReport keysReport = getKeysReport(keyStore);
// Check for the existence of a key store first
if(keyStore.exists())
{
// The keystore exists - check whether any keys have been changed
if(keysReport.getKeysChanged().size() > 0)
{
// Note: this will halt the application bootstrap.
throw new AlfrescoRuntimeException("The keys with aliases " + keysReport.getKeysChanged() + " have been changed, re-instate the previous keystore");
}
}
else
{
// keystore not found, check whether any keys have been registered
if(keysReport.getKeysChanged().size() + keysReport.getKeysUnchanged().size() > 0)
{
// Note: this will halt the application bootstrap.
throw new AlfrescoRuntimeException("Keys have already been registered, re-instate the previous keystore");
}
// no keys found, create a new keystore
// TODO
if(logger.isDebugEnabled())
{
logger.debug("Keystore not found, creating...");
}
createKeyStore(keyStore);
}
return null;
}
};
retryingTransactionHelper.doInTransaction(checkKeysCallback, false);
}
protected void createKeyStore(AlfrescoKeyStore keyStore)
{
new CreatingKeyStore(keyStore).create();
}
public static class KeysReport
{
private List<String> keysChanged;
private List<String> keysUnchanged;
public KeysReport(List<String> keysChanged, List<String> keysUnchanged)
{
super();
this.keysChanged = keysChanged;
this.keysUnchanged = keysUnchanged;
}
public List<String> getKeysChanged()
{
return keysChanged;
}
public List<String> getKeysUnchanged()
{
return keysUnchanged;
}
}
/**
* A KeyCheck object stores a well-known guid and it's encrypted value.
*
* @since 4.0
*
*/
private static class KeyCheck implements Serializable
{
private static final long serialVersionUID = 4514315444977162903L;
private String guid;
private Serializable encrypted;
public KeyCheck(String guid, Serializable encrypted)
{
super();
this.guid = guid;
this.encrypted = encrypted;
}
public String getGuid()
{
return guid;
}
public Serializable getEncrypted()
{
return encrypted;
}
public boolean equals(Object other)
{
if(this == other)
{
return true;
}
if(!(other instanceof KeyCheck))
{
return false;
}
KeyCheck keyCheck = (KeyCheck)other;
return EqualsHelper.nullSafeEquals(keyCheck.getGuid(), getGuid()) &&
EqualsHelper.nullSafeEquals(keyCheck.getEncrypted(), getEncrypted());
}
}
public void removeRegisteredKeys(final AlfrescoKeyStore keyStore)
{
RetryingTransactionHelper retryingTransactionHelper = transactionService.getRetryingTransactionHelper();
final RetryingTransactionCallback<Void> removeKeysCallback = new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
attributeService.removeAttributes(TOP_LEVEL_KEY, keyStore.getLocation());
return null;
}
};
retryingTransactionHelper.doInTransaction(removeKeysCallback, false);
}
private class CreatingKeyStore extends CachingKeyStore
{
CreatingKeyStore(AlfrescoKeyStore keyStore)
{
super(keyStore.getkeyStoreParameters(), keyStore.getKeyResourceLoader());
}
public void create()
{
KeyInfoManager keyInfoManager = null;
try
{
keyInfoManager = getKeyInfoManager();
ks.load(null, null);
String keyStorePassword = keyInfoManager.getKeyStorePassword();
if(keyStorePassword == null)
{
throw new AlfrescoRuntimeException("Key store password is null for keystore at location " + getLocation()
+ ", key store meta data location" + getKeyMetaDataFileLocation());
}
// Add keys from the passwords file to the keystore
for(Map.Entry<String, CachingKeyStore.KeyInformation> keyEntry : keyInfoManager.getKeyInfo().entrySet())
{
KeyInformation keyInfo = keyInfoManager.getKeyInformation(keyEntry.getKey());
String keyPassword = keyInfo.getPassword();
if(keyPassword == null)
{
throw new AlfrescoRuntimeException("No password found for encryption key " + keyEntry.getKey());
}
Key key = generateSecretKey(keyEntry.getValue());
ks.setKeyEntry(keyInfo.getAlias(), key, keyInfo.getPassword().toCharArray(), null);
}
ks.store(new FileOutputStream(getLocation()), keyStorePassword.toCharArray());
// Register the key store keys
for(Map.Entry<String, CachingKeyStore.KeyInformation> keyEntry : keyInfoManager.getKeyInfo().entrySet())
{
registerKey(this, keyEntry.getKey());
}
}
catch(Throwable e)
{
throw new AlfrescoRuntimeException(
"Failed to create keystore: \n" +
" Location: " + getLocation() + "\n" +
" Provider: " + getProvider() + "\n" +
" Type: " + getType(),
e);
}
finally
{
if(keyInfoManager != null)
{
keyInfoManager.clear();
}
}
}
}
}

View File

@@ -18,12 +18,15 @@
*/
package org.alfresco.encryption;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.Key;
import java.security.KeyStore;
import java.security.UnrecoverableKeyException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import junit.framework.TestCase;
@@ -55,21 +58,71 @@ public class KeyStoreKeyProviderTest extends TestCase
/* package */ static KeystoreKeyProvider getTestKeyStoreProvider()
{
Map<String, String> passwords = new HashMap<String, String>(5);
passwords.put(KeystoreKeyProvider.KEY_KEYSTORE_PASSWORD, "ksPwd2");
passwords.put(AlfrescoKeyStore.KEY_KEYSTORE_PASSWORD, "ksPwd2");
passwords.put(ALIAS_ONE, "aliasPwd1");
passwords.put(ALIAS_TWO, "aliasPwd2");
KeystoreKeyProvider ks = new KeystoreKeyProvider(
FILE_TWO,
getKeyStoreLoader(),
"SunJCE",
"JCEKS",
passwords);
return ks;
KeyStoreParameters encryptionParameters = new KeyStoreParameters("JCEKS", "SunJCE", null, FILE_TWO);
KeystoreKeyProvider keyProvider = new KeystoreKeyProvider(encryptionParameters, getKeyStoreLoader(passwords));
// FILE_TWO,
// getKeyStoreLoader(),
// "SunJCE",
// "JCEKS",
// passwords);
return keyProvider;
}
/* package */ static KeystoreKeyProvider getTestKeyStoreProvider(String keyStoreLocation, Map<String, String> passwords)
{
// Map<String, String> passwords = new HashMap<String, String>(5);
// passwords.put(KeyStoreManager.KEY_KEYSTORE_PASSWORD, "ksPwd2");
// passwords.put(ALIAS_ONE, "aliasPwd1");
// passwords.put(ALIAS_TWO, "aliasPwd2");
KeyStoreParameters encryptionParameters = new KeyStoreParameters("JCEKS", "SunJCE", null, keyStoreLocation);
KeystoreKeyProvider keyProvider = new KeystoreKeyProvider(encryptionParameters, getKeyStoreLoader(passwords));
// FILE_TWO,
// getKeyStoreLoader(),
// "SunJCE",
// "JCEKS",
// passwords);
return keyProvider;
}
protected static KeyResourceLoader getKeyStoreLoader()
private static class TestKeyResourceLoader extends SpringKeyResourceLoader
{
return new SpringKeyResourceLoader();
private Properties props;
TestKeyResourceLoader(Map<String, String> passwords)
{
StringBuilder aliases = new StringBuilder();
props = new Properties();
int i = 0;
for(Map.Entry<String, String> password : passwords.entrySet())
{
props.put(password.getKey() + ".password", password.getValue());
aliases.append(password.getKey());
if(i < passwords.size() - 1)
{
aliases.append(",");
i++;
}
}
props.put("aliases", aliases.toString());
}
@Override
public Properties loadKeyMetaData(String keyMetaDataFileLocation)
throws IOException, FileNotFoundException
{
return props;
}
}
protected static KeyResourceLoader getKeyStoreLoader(Map<String, String> passwords)
{
return new TestKeyResourceLoader(passwords);
}
public void setUp() throws Exception
@@ -78,24 +131,28 @@ public class KeyStoreKeyProviderTest extends TestCase
public void testNoKeyStorePasswords() throws Exception
{
KeystoreKeyProvider keyProvider = new KeystoreKeyProvider(
FILE_ONE,
getKeyStoreLoader(),
"SunJCE",
"JCEKS",
Collections.<String,String>emptyMap());
KeystoreKeyProvider keyProvider = getTestKeyStoreProvider(FILE_ONE, Collections.<String,String>emptyMap());
// KeystoreKeyProvider keyProvider = new KeystoreKeyProvider(
// FILE_ONE,
// getKeyStoreLoader(),
// "SunJCE",
// "JCEKS",
// Collections.<String,String>emptyMap());
// This has succeeded because we have not attempted to access it
assertNull("Should be no keys available", keyProvider.getKey(ALIAS_ONE));
}
public void testKeyStoreWithOnlyAliasPasswords() throws Exception
{
KeystoreKeyProvider keyProvider = new KeystoreKeyProvider(
FILE_TWO,
getKeyStoreLoader(),
"SunJCE",
"JCEKS",
Collections.singletonMap(ALIAS_ONE, "aliasPwd1"));
KeystoreKeyProvider keyProvider = getTestKeyStoreProvider(FILE_ONE, Collections.singletonMap(ALIAS_ONE, "aliasPwd1"));
// KeystoreKeyProvider keyProvider = new KeystoreKeyProvider(
// FILE_TWO,
// getKeyStoreLoader(),
// "SunJCE",
// "JCEKS",
// Collections.singletonMap(ALIAS_ONE, "aliasPwd1"));
// This has succeeded because we have not attempted to access it
assertNotNull("Should be able to key alias with same password", keyProvider.getKey(ALIAS_ONE));
}
@@ -104,12 +161,14 @@ public class KeyStoreKeyProviderTest extends TestCase
{
try
{
new KeystoreKeyProvider(
FILE_ONE,
getKeyStoreLoader(),
"SunJCE",
"JCEKS",
Collections.singletonMap(ALIAS_ONE, "password_fail"));
getTestKeyStoreProvider(FILE_ONE, Collections.singletonMap(ALIAS_ONE, "password_fail"));
// new KeystoreKeyProvider(
// FILE_ONE,
// getKeyStoreLoader(),
// "SunJCE",
// "JCEKS",
// Collections.singletonMap(ALIAS_ONE, "password_fail"));
fail("Expect to fail because password is incorrect");
}
catch (AlfrescoRuntimeException e)
@@ -123,12 +182,13 @@ public class KeyStoreKeyProviderTest extends TestCase
{
try
{
new KeystoreKeyProvider(
FILE_TWO,
getKeyStoreLoader(),
"SunJCE",
"JCEKS",
Collections.singletonMap(ALIAS_TWO, "password_fail"));
getTestKeyStoreProvider(FILE_TWO, Collections.singletonMap(ALIAS_TWO, "password_fail"));
// new KeystoreKeyProvider(
// FILE_TWO,
// getKeyStoreLoader(),
// "SunJCE",
// "JCEKS",
// Collections.singletonMap(ALIAS_TWO, "password_fail"));
fail("Expect to fail because password is incorrect");
}
catch (AlfrescoRuntimeException e)
@@ -140,12 +200,14 @@ public class KeyStoreKeyProviderTest extends TestCase
public void testAliasWithCorrectPassword_One() throws Exception
{
KeystoreKeyProvider ks = new KeystoreKeyProvider(
FILE_ONE,
getKeyStoreLoader(),
"SunJCE",
"JCEKS",
Collections.singletonMap(ALIAS_ONE, "aliasPwd1"));
KeystoreKeyProvider ks = getTestKeyStoreProvider(FILE_ONE, Collections.singletonMap(ALIAS_ONE, "aliasPwd1"));
// KeystoreKeyProvider ks = new KeystoreKeyProvider(
// FILE_ONE,
// getKeyStoreLoader(),
// "SunJCE",
// "JCEKS",
// Collections.singletonMap(ALIAS_ONE, "aliasPwd1"));
Key keyOne = ks.getKey(ALIAS_ONE);
assertNotNull(keyOne);
}
@@ -155,12 +217,16 @@ public class KeyStoreKeyProviderTest extends TestCase
Map<String, String> passwords = new HashMap<String, String>(5);
passwords.put(ALIAS_ONE, "aliasPwd1");
passwords.put(ALIAS_TWO, "aliasPwd2");
KeystoreKeyProvider ks = new KeystoreKeyProvider(
FILE_TWO,
getKeyStoreLoader(),
"SunJCE",
"JCEKS",
passwords);
KeystoreKeyProvider ks = getTestKeyStoreProvider(FILE_TWO, passwords);
// KeystoreKeyProvider ks = new KeystoreKeyProvider(
// FILE_TWO,
// getKeyStoreLoader(),
// "SunJCE",
// "JCEKS",
// passwords);
assertNotNull(ks.getKey(ALIAS_ONE));
assertNotNull(ks.getKey(ALIAS_TWO));
}
@@ -171,12 +237,14 @@ public class KeyStoreKeyProviderTest extends TestCase
passwords.put(ALIAS_ONE, "aliasPwd1");
passwords.put(ALIAS_TWO, "aliasPwd2");
passwords.put(ALIAS_THREE, "aliasPwd3");
KeystoreKeyProvider ks = new KeystoreKeyProvider(
FILE_THREE,
getKeyStoreLoader(),
"SunJCE",
"JCEKS",
passwords);
KeystoreKeyProvider ks = getTestKeyStoreProvider(FILE_THREE, passwords);
// KeystoreKeyProvider ks = new KeystoreKeyProvider(
// FILE_THREE,
// getKeyStoreLoader(),
// "SunJCE",
// "JCEKS",
// passwords);
assertNotNull(ks.getKey(ALIAS_ONE));
assertNotNull(ks.getKey(ALIAS_TWO));
assertNull(ks.getKey(ALIAS_THREE));

View File

@@ -0,0 +1,228 @@
/*
* Copyright (C) 2005-2011 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.encryption;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.crypto.SealedObject;
import org.alfresco.repo.batch.BatchProcessWorkProvider;
import org.alfresco.repo.batch.BatchProcessor;
import org.alfresco.repo.dictionary.DictionaryDAO;
import org.alfresco.repo.dictionary.NamespaceDAO;
import org.alfresco.repo.domain.node.NodeDAO;
import org.alfresco.repo.domain.node.NodePropertyEntity;
import org.alfresco.repo.domain.node.NodePropertyKey;
import org.alfresco.repo.domain.qname.QNameDAO;
import org.alfresco.repo.node.encryption.MetadataEncryptor;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
import org.alfresco.service.cmr.dictionary.DictionaryService;
import org.alfresco.service.cmr.dictionary.PropertyDefinition;
import org.alfresco.service.namespace.NamespaceService;
import org.alfresco.service.namespace.QName;
import org.alfresco.service.transaction.TransactionService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.extensions.surf.util.I18NUtil;
// TODO use Batch code to run in parallel
// TODO lock so that only one encryptor can run at a time
/**
* Re-encrypts encryptable repository properties using a new set of encryption keys.
* Decrypts the repository properties using the default encryptor, falling back to
* a backup decryptor (using the old encryption keys) if necessary, and then re-encrypts
* the properties.
*
* The system can stay running during this operation.
*
* @since 4.0
*/
public class ReEncryptor implements ApplicationContextAware
{
private static Log logger = LogFactory.getLog(ReEncryptor.class);
private NodeDAO nodeDAO;
private NamespaceDAO namespaceDAO;
private DictionaryDAO dictionaryDAO;
private DictionaryService dictionaryService;
private QNameDAO qnameDAO;
private MetadataEncryptor metadataEncryptor;
private ApplicationContext applicationContext;
private TransactionService transactionService;
private RetryingTransactionHelper transactionHelper;
/**
* Set the transaction provider so that each execution can be performed within a transaction
*/
public void setTransactionService(TransactionService transactionService)
{
this.transactionService = transactionService;
this.transactionHelper = transactionService.getRetryingTransactionHelper();
this.transactionHelper.setForceWritable(true);
}
// protected MetadataEncryptor getMetadataEncryptor(EncryptionParameters encryptionParameters)
// {
// DefaultEncryptor encryptor = new DefaultEncryptor();
// encryptor.setCipherAlgorithm(encryptionParameters.getCipherAlgorithm());
// encryptor.setCipherProvider(null);
// KeystoreKeyProvider keyProvider = new KeystoreKeyProvider();
// keyProvider.setLocation(encryptionParameters.getKeyStoreLocation());
// keyProvider.setPasswordsFileLocation(encryptionParameters.getPasswordFileLocation());
// keyProvider.setType(encryptionParameters.getKeyStoreType());
// keyProvider.setKeyResourceLoader(new SpringKeyResourceLoader());
// keyProvider.setProvider(encryptionParameters.getKeyStoreProvider()
// );
//
// encryptor.setKeyProvider(keyProvider);
//
// MetadataEncryptor metadataEncryptor = new MetadataEncryptor();
// metadataEncryptor.setEncryptor(encryptor);
// metadataEncryptor.setDictionaryService(dictionaryService);
//
// return metadataEncryptor;
// }
public void setMetadataEncryptor(MetadataEncryptor metadataEncryptor)
{
this.metadataEncryptor = metadataEncryptor;
}
public void init()
{
}
public void reencrypt(final KeyStoreParameters newEncryptionParameters, final List<NodePropertyEntity> properties)
{
BatchProcessor.BatchProcessWorker<NodePropertyEntity> worker = new BatchProcessor.BatchProcessWorker<NodePropertyEntity>()
{
public String getIdentifier(NodePropertyEntity entity)
{
return String.valueOf(entity.getNodeId());
}
public void beforeProcess() throws Throwable
{
}
public void afterProcess() throws Throwable
{
}
public void process(NodePropertyEntity entity) throws Throwable
{
Object value = entity.getValue();
if(value instanceof SealedObject)
{
SealedObject sealed = (SealedObject)value;
NodePropertyKey nodeKey = entity.getKey();
QName propertyQName = qnameDAO.getQName(nodeKey.getQnameId()).getSecond();
// metadataEncryptor uses a fallback encryptor; decryption will try the
// default (new) keys first (which will fail for properties created before the
// change in keys), followed by the backup keys.
Serializable decrypted = metadataEncryptor.decrypt(propertyQName, sealed);
// Re-encrypt. The new keys will be used.
Serializable resealed = metadataEncryptor.encrypt(propertyQName, decrypted);
// TODO update resealed using batch update?
// does the node DAO do batch updating?
nodeDAO.setNodeProperties(entity.getNodeId(), Collections.singletonMap(propertyQName, resealed));
}
else
{
// TODO
}
}
};
BatchProcessWorkProvider<NodePropertyEntity> provider = new BatchProcessWorkProvider<NodePropertyEntity>()
{
private int start = 0;
@Override
public int getTotalEstimatedWorkSize()
{
return properties.size();
}
@Override
public Collection<NodePropertyEntity> getNextWork()
{
int end = start + 20;
if(end > properties.size())
{
end = properties.size();
}
List<NodePropertyEntity> sublist = properties.subList(start, end);
start += 20;
return sublist;
}
};
// Migrate using 2 threads, 20 authorities per transaction. Log every 100 entries.
// TODO, propertize these numbers
new BatchProcessor<NodePropertyEntity>(
I18NUtil.getMessage(""),
transactionHelper,
provider,
2, 20,
applicationContext,
logger, 100).process(worker, true);
}
public void execute(KeyStoreParameters newEncryptionParameters)
{
// Proceed only if fallback is available i.e. the systems has both old and new keys
if(metadataEncryptor.isFallbackAvailable())
{
QName model = QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, namespaceDAO);
// get properties that are encrypted
Collection<PropertyDefinition> propertyDefs = dictionaryDAO.getProperties(model, DataTypeDefinition.ENCRYPTED);
List<NodePropertyEntity> properties = nodeDAO.getProperties(propertyDefs);
// reencrypt these properties
reencrypt(newEncryptionParameters, properties);
}
else
{
// TODO
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException
{
this.applicationContext = applicationContext;
}
}