Merged 5.1.N (5.1.2) to 5.2.N (5.2.1)

125605 rmunteanu: Merged 5.1.1 (5.1.1) to 5.1.N (5.1.2)
      125498 slanglois: MNT-16155 Update source headers - remove svn:eol-style property on Java and JSP source files


git-svn-id: https://svn.alfresco.com/repos/alfresco-enterprise/alfresco/BRANCHES/DEV/5.2.N/root@125783 c4b6b30b-aa2e-2d43-bbcb-ca4b014f7261
This commit is contained in:
Raluca Munteanu
2016-04-26 13:03:25 +00:00
parent 8674e2bfc8
commit dc6b2852d0
830 changed files with 142585 additions and 142585 deletions

View File

@@ -1,64 +1,64 @@
package org.alfresco.encryption;
import org.alfresco.error.AlfrescoRuntimeException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.extensions.surf.util.AbstractLifecycleBean;
/**
*
* @since 4.0
*
*/
public class BootstrapReEncryptor extends AbstractLifecycleBean
{
private static Log logger = LogFactory.getLog(BootstrapReEncryptor.class);
private boolean enabled;
private ReEncryptor reEncryptor;
public void setEnabled(boolean enabled)
{
this.enabled = enabled;
}
public void setReEncryptor(ReEncryptor reEncryptor)
{
this.reEncryptor = reEncryptor;
}
public int reEncrypt()
{
try
{
return reEncryptor.bootstrapReEncrypt();
}
catch(MissingKeyException e)
{
throw new AlfrescoRuntimeException("Bootstrap re-encryption failed", e);
}
}
@Override
protected void onBootstrap(ApplicationEvent event)
{
if(enabled)
{
if(logger.isDebugEnabled())
{
logger.debug("Re-encrypting encryptable properties...");
}
int propertiesReEncrypted = reEncrypt();
if(logger.isDebugEnabled())
{
logger.debug("...done, re-encrypted " + propertiesReEncrypted + " properties.");
}
}
}
@Override
protected void onShutdown(ApplicationEvent event)
{
}
package org.alfresco.encryption;
import org.alfresco.error.AlfrescoRuntimeException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.extensions.surf.util.AbstractLifecycleBean;
/**
*
* @since 4.0
*
*/
public class BootstrapReEncryptor extends AbstractLifecycleBean
{
private static Log logger = LogFactory.getLog(BootstrapReEncryptor.class);
private boolean enabled;
private ReEncryptor reEncryptor;
public void setEnabled(boolean enabled)
{
this.enabled = enabled;
}
public void setReEncryptor(ReEncryptor reEncryptor)
{
this.reEncryptor = reEncryptor;
}
public int reEncrypt()
{
try
{
return reEncryptor.bootstrapReEncrypt();
}
catch(MissingKeyException e)
{
throw new AlfrescoRuntimeException("Bootstrap re-encryption failed", e);
}
}
@Override
protected void onBootstrap(ApplicationEvent event)
{
if(enabled)
{
if(logger.isDebugEnabled())
{
logger.debug("Re-encrypting encryptable properties...");
}
int propertiesReEncrypted = reEncrypt();
if(logger.isDebugEnabled())
{
logger.debug("...done, re-encrypted " + propertiesReEncrypted + " properties.");
}
}
}
@Override
protected void onShutdown(ApplicationEvent event)
{
}
}

View File

@@ -1,66 +1,66 @@
package org.alfresco.encryption;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.transaction.TransactionService;
import org.springframework.context.ApplicationEvent;
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>
*
* @since 4.0
*
*/
public class EncryptionChecker extends AbstractLifecycleBean
{
private TransactionService transactionService;
private KeyStoreChecker keyStoreChecker;
public void setKeyStoreChecker(KeyStoreChecker keyStoreChecker)
{
this.keyStoreChecker = keyStoreChecker;
}
public void setTransactionService(TransactionService transactionService)
{
this.transactionService = transactionService;
}
@Override
protected void onBootstrap(ApplicationEvent event)
{
RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
txnHelper.setForceWritable(true); // Force write in case server is read-only
txnHelper.doInTransaction(new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
try
{
keyStoreChecker.validateKeyStores();
}
catch(Throwable e)
{
// Just throw as a runtime exception
throw new AlfrescoRuntimeException("Keystores are invalid", e);
}
return null;
}
});
}
@Override
protected void onShutdown(ApplicationEvent event)
{
}
}
package org.alfresco.encryption;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.transaction.TransactionService;
import org.springframework.context.ApplicationEvent;
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>
*
* @since 4.0
*
*/
public class EncryptionChecker extends AbstractLifecycleBean
{
private TransactionService transactionService;
private KeyStoreChecker keyStoreChecker;
public void setKeyStoreChecker(KeyStoreChecker keyStoreChecker)
{
this.keyStoreChecker = keyStoreChecker;
}
public void setTransactionService(TransactionService transactionService)
{
this.transactionService = transactionService;
}
@Override
protected void onBootstrap(ApplicationEvent event)
{
RetryingTransactionHelper txnHelper = transactionService.getRetryingTransactionHelper();
txnHelper.setForceWritable(true); // Force write in case server is read-only
txnHelper.doInTransaction(new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
try
{
keyStoreChecker.validateKeyStores();
}
catch(Throwable e)
{
// Just throw as a runtime exception
throw new AlfrescoRuntimeException("Keystores are invalid", e);
}
return null;
}
});
}
@Override
protected void onShutdown(ApplicationEvent event)
{
}
}

View File

@@ -1,208 +1,208 @@
package org.alfresco.encryption;
import java.io.Serializable;
import java.security.InvalidKeyException;
import java.security.Key;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
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.alfresco.util.Pair;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Registered Encryption Keys are stored in the AttributeService directly under a top level key defined by
* TOP_LEVEL_KEY (which means that all key aliases must be unique across however many keystores are being used).
*
* @since 4.0
*
*/
// TODO caching? This will probably not be used extensively.
// TODO instead of persisting the Pair when registering a key, create two attributes per key (one for the
// guid and one for the encrypted value of the guid). This means a custom class does not need to be bound to
// the attribute service.
public class EncryptionKeysRegistryImpl implements EncryptionKeysRegistry
{
public static String TOP_LEVEL_KEY = "keyCheck";
private static final Log logger = LogFactory.getLog(EncryptionKeysRegistryImpl.class);
private TransactionService transactionService;
private AttributeService attributeService;
private String cipherAlgorithm;
private String cipherProvider;
public void setAttributeService(AttributeService attributeService)
{
this.attributeService = attributeService;
}
public void setCipherAlgorithm(String cipherAlgorithm)
{
this.cipherAlgorithm = cipherAlgorithm;
}
public void setCipherProvider(String cipherProvider)
{
this.cipherProvider = cipherProvider;
}
public void setTransactionService(TransactionService transactionService)
{
this.transactionService = transactionService;
}
protected Encryptor getEncryptor(final KeyMap keys)
{
DefaultEncryptor encryptor = new DefaultEncryptor();
encryptor.setCipherAlgorithm(cipherAlgorithm);
encryptor.setCipherProvider(cipherProvider);
encryptor.setKeyProvider(new KeyProvider()
{
@Override
public Key getKey(String keyAlias)
{
return keys.getCachedKey(keyAlias).getKey();
}
});
return encryptor;
}
public void init()
{
}
public void registerKey(String keyAlias, Key key)
{
if(isKeyRegistered(keyAlias))
{
throw new IllegalArgumentException("Key " + keyAlias + " is already registered");
}
// register the key by creating an attribute that stores a guid and its encrypted value
String guid = GUID.generate();
KeyMap keys = new KeyMap();
keys.setKey(keyAlias, key);
Encryptor encryptor = getEncryptor(keys);
Serializable encrypted = encryptor.sealObject(keyAlias, null, guid);
Pair<String, Serializable> keyCheck = new Pair<String, Serializable>(guid, encrypted);
attributeService.createAttribute(keyCheck, TOP_LEVEL_KEY, keyAlias);
logger.info("Registered key " + keyAlias);
}
public void unregisterKey(String keyAlias)
{
attributeService.removeAttribute(TOP_LEVEL_KEY, keyAlias);
}
public boolean isKeyRegistered(String keyAlias)
{
try
{
return (attributeService.getAttribute(TOP_LEVEL_KEY, keyAlias) != null);
}
catch(Throwable e)
{
// there is an issue getting the attribute. Remove it.
attributeService.removeAttribute(TOP_LEVEL_KEY, keyAlias);
return (attributeService.getAttribute(TOP_LEVEL_KEY, keyAlias) != null);
}
}
public List<String> getRegisteredKeys(final Set<String> keyStoreKeys)
{
final List<String> registeredKeys = new ArrayList<String>();
attributeService.getAttributes(new AttributeQueryCallback()
{
public boolean handleAttribute(Long id, Serializable value,
Serializable[] keys)
{
// Add as a registered key if the keystore contains the key
String keyAlias = (String)keys[1];
if(keyStoreKeys.contains(keyAlias))
{
registeredKeys.add(keyAlias);
}
return true;
}
},
TOP_LEVEL_KEY);
return registeredKeys;
}
@SuppressWarnings("unchecked")
public KEY_STATUS checkKey(String keyAlias, Key key)
{
Pair<String, Serializable> keyCheck = null;
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
try
{
keyCheck = (Pair<String, Serializable>)attributeService.getAttribute(TOP_LEVEL_KEY, keyAlias);
}
catch(Throwable e)
{
// there is an issue getting the attribute. Remove it.
attributeService.removeAttribute(TOP_LEVEL_KEY, keyAlias);
return KEY_STATUS.MISSING;
}
if(keyCheck == null)
{
return KEY_STATUS.MISSING;
}
KeyMap keys = new KeyMap();
keys.setKey(keyAlias, key);
Encryptor encryptor = getEncryptor(keys);
Serializable storedGUID = encryptor.unsealObject(keyAlias, keyCheck.getSecond());
return EqualsHelper.nullSafeEquals(storedGUID, keyCheck.getFirst()) ? 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;
}
}
// note that this removes _all_ keys in the keystore. Use with care.
public void removeRegisteredKeys(final Set<String> keys)
{
RetryingTransactionHelper retryingTransactionHelper = transactionService.getRetryingTransactionHelper();
final RetryingTransactionCallback<Void> removeKeysCallback = new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
for(String keyAlias : keys)
{
attributeService.removeAttribute(TOP_LEVEL_KEY, keyAlias);
}
return null;
}
};
retryingTransactionHelper.doInTransaction(removeKeysCallback, false);
}
}
package org.alfresco.encryption;
import java.io.Serializable;
import java.security.InvalidKeyException;
import java.security.Key;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
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.alfresco.util.Pair;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* Registered Encryption Keys are stored in the AttributeService directly under a top level key defined by
* TOP_LEVEL_KEY (which means that all key aliases must be unique across however many keystores are being used).
*
* @since 4.0
*
*/
// TODO caching? This will probably not be used extensively.
// TODO instead of persisting the Pair when registering a key, create two attributes per key (one for the
// guid and one for the encrypted value of the guid). This means a custom class does not need to be bound to
// the attribute service.
public class EncryptionKeysRegistryImpl implements EncryptionKeysRegistry
{
public static String TOP_LEVEL_KEY = "keyCheck";
private static final Log logger = LogFactory.getLog(EncryptionKeysRegistryImpl.class);
private TransactionService transactionService;
private AttributeService attributeService;
private String cipherAlgorithm;
private String cipherProvider;
public void setAttributeService(AttributeService attributeService)
{
this.attributeService = attributeService;
}
public void setCipherAlgorithm(String cipherAlgorithm)
{
this.cipherAlgorithm = cipherAlgorithm;
}
public void setCipherProvider(String cipherProvider)
{
this.cipherProvider = cipherProvider;
}
public void setTransactionService(TransactionService transactionService)
{
this.transactionService = transactionService;
}
protected Encryptor getEncryptor(final KeyMap keys)
{
DefaultEncryptor encryptor = new DefaultEncryptor();
encryptor.setCipherAlgorithm(cipherAlgorithm);
encryptor.setCipherProvider(cipherProvider);
encryptor.setKeyProvider(new KeyProvider()
{
@Override
public Key getKey(String keyAlias)
{
return keys.getCachedKey(keyAlias).getKey();
}
});
return encryptor;
}
public void init()
{
}
public void registerKey(String keyAlias, Key key)
{
if(isKeyRegistered(keyAlias))
{
throw new IllegalArgumentException("Key " + keyAlias + " is already registered");
}
// register the key by creating an attribute that stores a guid and its encrypted value
String guid = GUID.generate();
KeyMap keys = new KeyMap();
keys.setKey(keyAlias, key);
Encryptor encryptor = getEncryptor(keys);
Serializable encrypted = encryptor.sealObject(keyAlias, null, guid);
Pair<String, Serializable> keyCheck = new Pair<String, Serializable>(guid, encrypted);
attributeService.createAttribute(keyCheck, TOP_LEVEL_KEY, keyAlias);
logger.info("Registered key " + keyAlias);
}
public void unregisterKey(String keyAlias)
{
attributeService.removeAttribute(TOP_LEVEL_KEY, keyAlias);
}
public boolean isKeyRegistered(String keyAlias)
{
try
{
return (attributeService.getAttribute(TOP_LEVEL_KEY, keyAlias) != null);
}
catch(Throwable e)
{
// there is an issue getting the attribute. Remove it.
attributeService.removeAttribute(TOP_LEVEL_KEY, keyAlias);
return (attributeService.getAttribute(TOP_LEVEL_KEY, keyAlias) != null);
}
}
public List<String> getRegisteredKeys(final Set<String> keyStoreKeys)
{
final List<String> registeredKeys = new ArrayList<String>();
attributeService.getAttributes(new AttributeQueryCallback()
{
public boolean handleAttribute(Long id, Serializable value,
Serializable[] keys)
{
// Add as a registered key if the keystore contains the key
String keyAlias = (String)keys[1];
if(keyStoreKeys.contains(keyAlias))
{
registeredKeys.add(keyAlias);
}
return true;
}
},
TOP_LEVEL_KEY);
return registeredKeys;
}
@SuppressWarnings("unchecked")
public KEY_STATUS checkKey(String keyAlias, Key key)
{
Pair<String, Serializable> keyCheck = null;
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
try
{
keyCheck = (Pair<String, Serializable>)attributeService.getAttribute(TOP_LEVEL_KEY, keyAlias);
}
catch(Throwable e)
{
// there is an issue getting the attribute. Remove it.
attributeService.removeAttribute(TOP_LEVEL_KEY, keyAlias);
return KEY_STATUS.MISSING;
}
if(keyCheck == null)
{
return KEY_STATUS.MISSING;
}
KeyMap keys = new KeyMap();
keys.setKey(keyAlias, key);
Encryptor encryptor = getEncryptor(keys);
Serializable storedGUID = encryptor.unsealObject(keyAlias, keyCheck.getSecond());
return EqualsHelper.nullSafeEquals(storedGUID, keyCheck.getFirst()) ? 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;
}
}
// note that this removes _all_ keys in the keystore. Use with care.
public void removeRegisteredKeys(final Set<String> keys)
{
RetryingTransactionHelper retryingTransactionHelper = transactionService.getRetryingTransactionHelper();
final RetryingTransactionCallback<Void> removeKeysCallback = new RetryingTransactionCallback<Void>()
{
public Void execute() throws Throwable
{
for(String keyAlias : keys)
{
attributeService.removeAttribute(TOP_LEVEL_KEY, keyAlias);
}
return null;
}
};
retryingTransactionHelper.doInTransaction(removeKeysCallback, false);
}
}

View File

@@ -1,30 +1,30 @@
package org.alfresco.encryption;
/**
* Checks the repository key stores.
*
* @since 4.0
*
*/
public class KeyStoreChecker
{
private AlfrescoKeyStore mainKeyStore;
public KeyStoreChecker()
{
}
public void setMainKeyStore(AlfrescoKeyStore mainKeyStore)
{
this.mainKeyStore = mainKeyStore;
}
public void validateKeyStores() throws InvalidKeystoreException, MissingKeyException
{
mainKeyStore.validateKeys();
if(!mainKeyStore.exists())
{
mainKeyStore.create();
}
}
}
package org.alfresco.encryption;
/**
* Checks the repository key stores.
*
* @since 4.0
*
*/
public class KeyStoreChecker
{
private AlfrescoKeyStore mainKeyStore;
public KeyStoreChecker()
{
}
public void setMainKeyStore(AlfrescoKeyStore mainKeyStore)
{
this.mainKeyStore = mainKeyStore;
}
public void validateKeyStores() throws InvalidKeystoreException, MissingKeyException
{
mainKeyStore.validateKeys();
if(!mainKeyStore.exists())
{
mainKeyStore.create();
}
}
}

View File

@@ -1,335 +1,335 @@
package org.alfresco.encryption;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
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.domain.node.NodeDAO;
import org.alfresco.repo.domain.node.NodePropertyEntity;
import org.alfresco.repo.domain.node.NodePropertyKey;
import org.alfresco.repo.domain.node.NodePropertyValue;
import org.alfresco.repo.domain.qname.QNameDAO;
import org.alfresco.repo.lock.JobLockService;
import org.alfresco.repo.lock.LockAcquisitionException;
import org.alfresco.repo.node.encryption.MetadataEncryptor;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
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;
/**
* 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.
*
* Can run in one of two ways:
*
* <ul>
* <li> during bootstrap.
* <li> by using JMX (available only to Enterprise). In this case, the system can stay running while the re-encryption takes place.
* </ul>
*
* @since 4.0
*/
public class ReEncryptor implements ApplicationContextAware
{
private static Log logger = LogFactory.getLog(ReEncryptor.class);
private NodeDAO nodeDAO;
private DictionaryDAO dictionaryDAO;
private QNameDAO qnameDAO;
private MetadataEncryptor metadataEncryptor;
private ApplicationContext applicationContext;
private TransactionService transactionService;
private RetryingTransactionHelper transactionHelper;
private int numThreads;
private int chunkSize;
private boolean splitTxns = true;
private static final QName LOCK = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "OrphanReaper");
private JobLockService jobLockService;
/**
* 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();
}
public void setMetadataEncryptor(MetadataEncryptor metadataEncryptor)
{
this.metadataEncryptor = metadataEncryptor;
}
public MetadataEncryptor getMetadataEncryptor()
{
return metadataEncryptor;
}
public void setJobLockService(JobLockService jobLockService)
{
this.jobLockService = jobLockService;
}
public void setNumThreads(int numThreads)
{
this.numThreads = numThreads;
}
public void setChunkSize(int chunkSize)
{
this.chunkSize = chunkSize;
}
public void setSplitTxns(boolean splitTxns)
{
this.splitTxns = splitTxns;
}
public void setNodeDAO(NodeDAO nodeDAO)
{
this.nodeDAO = nodeDAO;
}
public void setDictionaryDAO(DictionaryDAO dictionaryDAO)
{
this.dictionaryDAO = dictionaryDAO;
}
public void setQnameDAO(QNameDAO qnameDAO)
{
this.qnameDAO = qnameDAO;
}
/**
* Attempts to get the lock. If the lock couldn't be taken, then <tt>null</tt> is returned.
*
* @return Returns the lock token or <tt>null</tt>
*/
private String getLock(long time)
{
try
{
return jobLockService.getLock(LOCK, time);
}
catch (LockAcquisitionException e)
{
return null;
}
}
/**
* Attempts to get the lock. If it fails, the current transaction is marked for rollback.
*/
private void refreshLock(String lockToken, long time)
{
if (lockToken == null)
{
throw new IllegalArgumentException("Must provide existing lockToken");
}
jobLockService.refreshLock(lockToken, LOCK, time);
}
protected void reEncryptProperties(final List<NodePropertyEntity> properties, final String lockToken)
{
final Iterator<NodePropertyEntity> it = properties.iterator();
// TODO use BatchProcessWorkerAdaptor?
BatchProcessor.BatchProcessWorker<NodePropertyEntity> worker = new BatchProcessor.BatchProcessWorker<NodePropertyEntity>()
{
public String getIdentifier(NodePropertyEntity entity)
{
return String.valueOf(entity.getNodeId());
}
public void beforeProcess() throws Throwable
{
refreshLock(lockToken, chunkSize * 100L);
}
public void afterProcess() throws Throwable
{
}
public void process(final NodePropertyEntity entity) throws Throwable
{
NodePropertyValue nodePropValue = entity.getValue();
// TODO check that we have the correct type i.e. can be cast to Serializable
Serializable value = nodePropValue.getSerializableValue();
if(value instanceof SealedObject)
{
SealedObject sealed = (SealedObject)value;
NodePropertyKey propertyKey = entity.getKey();
QName propertyQName = qnameDAO.getQName(propertyKey.getQnameId()).getSecond();
// decrypt...
Serializable decrypted = metadataEncryptor.decrypt(propertyQName, sealed);
// ...and then re-encrypt. The new key 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
{
NodePropertyKey nodeKey = entity.getKey();
QName propertyQName = qnameDAO.getQName(nodeKey.getQnameId()).getSecond();
logger.warn("Encountered an encrypted property that is not a SealedObject, for node id " +
entity.getNodeId() + ", property " + propertyQName);
}
}
};
BatchProcessWorkProvider<NodePropertyEntity> provider = new BatchProcessWorkProvider<NodePropertyEntity>()
{
@Override
public int getTotalEstimatedWorkSize()
{
return properties.size();
}
@Override
public Collection<NodePropertyEntity> getNextWork()
{
List<NodePropertyEntity> sublist = new ArrayList<NodePropertyEntity>(chunkSize);
synchronized(it)
{
int count = 0;
while(it.hasNext() && count < chunkSize)
{
sublist.add(it.next());
count++;
}
}
return sublist;
}
};
new BatchProcessor<NodePropertyEntity>(
"Reencryptor",
transactionHelper,
provider,
numThreads, chunkSize,
applicationContext,
logger, 100).process(worker, splitTxns);
}
/**
* Re-encrypt using the configured backup keystore to decrypt and the main keystore to encrypt
*/
public int bootstrapReEncrypt() throws MissingKeyException
{
if(!metadataEncryptor.backupKeyAvailable(KeyProvider.ALIAS_METADATA))
{
throw new MissingKeyException("Backup key store is either not present or does not contain a metadata encryption key");
}
return reEncrypt();
}
/**
* Re-encrypt by decrypting using the configured keystore and encrypting using a keystore configured using the provided new key store parameters.
* Called from e.g. JMX.
*
* Assumes that the main key store has been already been reloaded.
*
* Note: it is the responsibility of the end user to ensure that the underlying keystores have been set up appropriately
* i.e. the old key store is backed up to the location defined by the property '${dir.keystore}/backup-keystore' and the new
* key store replaces it. This can be done while the repository is running.
*/
public int reEncrypt() throws MissingKeyException
{
if(!metadataEncryptor.keyAvailable(KeyProvider.ALIAS_METADATA))
{
throw new MissingKeyException("Main key store is either not present or does not contain a metadata encryption key");
}
if(!metadataEncryptor.backupKeyAvailable(KeyProvider.ALIAS_METADATA))
{
throw new MissingKeyException("Backup key store is either not present or does not contain a metadata encryption key");
}
int numProps = reEncryptImpl();
return numProps;
}
protected int reEncryptImpl()
{
// Take out a re-encryptor lock
RetryingTransactionCallback<String> txnWork = new RetryingTransactionCallback<String>()
{
public String execute() throws Exception
{
String lockToken = getLock(20000L);
return lockToken;
}
};
String lockToken = transactionService.getRetryingTransactionHelper().doInTransaction(txnWork, false, true);
if(lockToken == null)
{
logger.warn("Can't get lock. Assume multiple re-encryptors ...");
return 0;
}
// get encrypted properties
Collection<PropertyDefinition> propertyDefs = dictionaryDAO.getPropertiesOfDataType(DataTypeDefinition.ENCRYPTED);
Set<QName> qnames = new HashSet<QName>();
for(PropertyDefinition propDef : propertyDefs)
{
qnames.add(propDef.getName());
}
// TODO use callback mechanism, or select based on set of nodes?
List<NodePropertyEntity> properties = nodeDAO.selectNodePropertiesByTypes(qnames);
if(logger.isDebugEnabled())
{
logger.debug("Found " + properties.size() + " properties to re-encrypt...");
}
// reencrypt these properties TODO don't call if num props == 0
reEncryptProperties(properties, lockToken);
if(logger.isDebugEnabled())
{
logger.debug("...done re-encrypting.");
}
return properties.size();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
this.applicationContext = applicationContext;
}
}
package org.alfresco.encryption;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
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.domain.node.NodeDAO;
import org.alfresco.repo.domain.node.NodePropertyEntity;
import org.alfresco.repo.domain.node.NodePropertyKey;
import org.alfresco.repo.domain.node.NodePropertyValue;
import org.alfresco.repo.domain.qname.QNameDAO;
import org.alfresco.repo.lock.JobLockService;
import org.alfresco.repo.lock.LockAcquisitionException;
import org.alfresco.repo.node.encryption.MetadataEncryptor;
import org.alfresco.repo.transaction.RetryingTransactionHelper;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.service.cmr.dictionary.DataTypeDefinition;
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;
/**
* 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.
*
* Can run in one of two ways:
*
* <ul>
* <li> during bootstrap.
* <li> by using JMX (available only to Enterprise). In this case, the system can stay running while the re-encryption takes place.
* </ul>
*
* @since 4.0
*/
public class ReEncryptor implements ApplicationContextAware
{
private static Log logger = LogFactory.getLog(ReEncryptor.class);
private NodeDAO nodeDAO;
private DictionaryDAO dictionaryDAO;
private QNameDAO qnameDAO;
private MetadataEncryptor metadataEncryptor;
private ApplicationContext applicationContext;
private TransactionService transactionService;
private RetryingTransactionHelper transactionHelper;
private int numThreads;
private int chunkSize;
private boolean splitTxns = true;
private static final QName LOCK = QName.createQName(NamespaceService.SYSTEM_MODEL_1_0_URI, "OrphanReaper");
private JobLockService jobLockService;
/**
* 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();
}
public void setMetadataEncryptor(MetadataEncryptor metadataEncryptor)
{
this.metadataEncryptor = metadataEncryptor;
}
public MetadataEncryptor getMetadataEncryptor()
{
return metadataEncryptor;
}
public void setJobLockService(JobLockService jobLockService)
{
this.jobLockService = jobLockService;
}
public void setNumThreads(int numThreads)
{
this.numThreads = numThreads;
}
public void setChunkSize(int chunkSize)
{
this.chunkSize = chunkSize;
}
public void setSplitTxns(boolean splitTxns)
{
this.splitTxns = splitTxns;
}
public void setNodeDAO(NodeDAO nodeDAO)
{
this.nodeDAO = nodeDAO;
}
public void setDictionaryDAO(DictionaryDAO dictionaryDAO)
{
this.dictionaryDAO = dictionaryDAO;
}
public void setQnameDAO(QNameDAO qnameDAO)
{
this.qnameDAO = qnameDAO;
}
/**
* Attempts to get the lock. If the lock couldn't be taken, then <tt>null</tt> is returned.
*
* @return Returns the lock token or <tt>null</tt>
*/
private String getLock(long time)
{
try
{
return jobLockService.getLock(LOCK, time);
}
catch (LockAcquisitionException e)
{
return null;
}
}
/**
* Attempts to get the lock. If it fails, the current transaction is marked for rollback.
*/
private void refreshLock(String lockToken, long time)
{
if (lockToken == null)
{
throw new IllegalArgumentException("Must provide existing lockToken");
}
jobLockService.refreshLock(lockToken, LOCK, time);
}
protected void reEncryptProperties(final List<NodePropertyEntity> properties, final String lockToken)
{
final Iterator<NodePropertyEntity> it = properties.iterator();
// TODO use BatchProcessWorkerAdaptor?
BatchProcessor.BatchProcessWorker<NodePropertyEntity> worker = new BatchProcessor.BatchProcessWorker<NodePropertyEntity>()
{
public String getIdentifier(NodePropertyEntity entity)
{
return String.valueOf(entity.getNodeId());
}
public void beforeProcess() throws Throwable
{
refreshLock(lockToken, chunkSize * 100L);
}
public void afterProcess() throws Throwable
{
}
public void process(final NodePropertyEntity entity) throws Throwable
{
NodePropertyValue nodePropValue = entity.getValue();
// TODO check that we have the correct type i.e. can be cast to Serializable
Serializable value = nodePropValue.getSerializableValue();
if(value instanceof SealedObject)
{
SealedObject sealed = (SealedObject)value;
NodePropertyKey propertyKey = entity.getKey();
QName propertyQName = qnameDAO.getQName(propertyKey.getQnameId()).getSecond();
// decrypt...
Serializable decrypted = metadataEncryptor.decrypt(propertyQName, sealed);
// ...and then re-encrypt. The new key 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
{
NodePropertyKey nodeKey = entity.getKey();
QName propertyQName = qnameDAO.getQName(nodeKey.getQnameId()).getSecond();
logger.warn("Encountered an encrypted property that is not a SealedObject, for node id " +
entity.getNodeId() + ", property " + propertyQName);
}
}
};
BatchProcessWorkProvider<NodePropertyEntity> provider = new BatchProcessWorkProvider<NodePropertyEntity>()
{
@Override
public int getTotalEstimatedWorkSize()
{
return properties.size();
}
@Override
public Collection<NodePropertyEntity> getNextWork()
{
List<NodePropertyEntity> sublist = new ArrayList<NodePropertyEntity>(chunkSize);
synchronized(it)
{
int count = 0;
while(it.hasNext() && count < chunkSize)
{
sublist.add(it.next());
count++;
}
}
return sublist;
}
};
new BatchProcessor<NodePropertyEntity>(
"Reencryptor",
transactionHelper,
provider,
numThreads, chunkSize,
applicationContext,
logger, 100).process(worker, splitTxns);
}
/**
* Re-encrypt using the configured backup keystore to decrypt and the main keystore to encrypt
*/
public int bootstrapReEncrypt() throws MissingKeyException
{
if(!metadataEncryptor.backupKeyAvailable(KeyProvider.ALIAS_METADATA))
{
throw new MissingKeyException("Backup key store is either not present or does not contain a metadata encryption key");
}
return reEncrypt();
}
/**
* Re-encrypt by decrypting using the configured keystore and encrypting using a keystore configured using the provided new key store parameters.
* Called from e.g. JMX.
*
* Assumes that the main key store has been already been reloaded.
*
* Note: it is the responsibility of the end user to ensure that the underlying keystores have been set up appropriately
* i.e. the old key store is backed up to the location defined by the property '${dir.keystore}/backup-keystore' and the new
* key store replaces it. This can be done while the repository is running.
*/
public int reEncrypt() throws MissingKeyException
{
if(!metadataEncryptor.keyAvailable(KeyProvider.ALIAS_METADATA))
{
throw new MissingKeyException("Main key store is either not present or does not contain a metadata encryption key");
}
if(!metadataEncryptor.backupKeyAvailable(KeyProvider.ALIAS_METADATA))
{
throw new MissingKeyException("Backup key store is either not present or does not contain a metadata encryption key");
}
int numProps = reEncryptImpl();
return numProps;
}
protected int reEncryptImpl()
{
// Take out a re-encryptor lock
RetryingTransactionCallback<String> txnWork = new RetryingTransactionCallback<String>()
{
public String execute() throws Exception
{
String lockToken = getLock(20000L);
return lockToken;
}
};
String lockToken = transactionService.getRetryingTransactionHelper().doInTransaction(txnWork, false, true);
if(lockToken == null)
{
logger.warn("Can't get lock. Assume multiple re-encryptors ...");
return 0;
}
// get encrypted properties
Collection<PropertyDefinition> propertyDefs = dictionaryDAO.getPropertiesOfDataType(DataTypeDefinition.ENCRYPTED);
Set<QName> qnames = new HashSet<QName>();
for(PropertyDefinition propDef : propertyDefs)
{
qnames.add(propDef.getName());
}
// TODO use callback mechanism, or select based on set of nodes?
List<NodePropertyEntity> properties = nodeDAO.selectNodePropertiesByTypes(qnames);
if(logger.isDebugEnabled())
{
logger.debug("Found " + properties.size() + " properties to re-encrypt...");
}
// reencrypt these properties TODO don't call if num props == 0
reEncryptProperties(properties, lockToken);
if(logger.isDebugEnabled())
{
logger.debug("...done re-encrypting.");
}
return properties.size();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
this.applicationContext = applicationContext;
}
}