Change encrypt=true fields to no longer have a pre-pended salt value.

This is done by just setting the length of salt bytes to 0, but still
having a length byte prepended.

Add a feature to allow for certain fields to actually have a salt
prefix.  This is enabled by setting encrypt=salt in the entity
definition.

This change is slightly incompatible with existing code.  Old database
values will continue to be decrypted correctly.  However, newly
encrypted values will no longer have a salt prepended, while originally
they would.  This shouldn't be a problem in practice.

This change, along with the previous commit, finally allow for direct
lookup of encrypted values.  However, already stored values will not be
found.  To fix those, each database row will have to be read in by
ofbiz, then immediately written back out.

This is part two to completely fix OFBIZ-5959:
Person.socialSecurityNumber can't be used for findByAnd.

git-svn-id: https://svn.apache.org/repos/asf/ofbiz/trunk@1604968 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Adam Heath
2014-06-24 00:23:23 +00:00
parent 91b11ac4f8
commit 5bc5c4151f
12 changed files with 136 additions and 29 deletions
+9 -1
View File
@@ -135,7 +135,15 @@ under the License.
<xs:attribute name="name" type="xs:string" use="required"/>
<xs:attribute name="col-name" type="xs:string"/>
<xs:attribute name="type" type="xs:string" use="required"/>
<xs:attribute name="encrypt" default="false" type="boolean"/>
<xs:attribute name="encrypt" default="false">
<xs:simpleType>
<xs:restriction base="xs:token">
<xs:enumeration value="true"/>
<xs:enumeration value="false"/>
<xs:enumeration value="salt"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:attribute name="enable-audit-log" default="false" type="boolean">
<xs:annotation>
<xs:documentation>
@@ -197,6 +197,7 @@ under the License.
<field name="testingCryptoTypeId" type="id-ne"/>
<field name="unencryptedValue" type="description"/>
<field name="encryptedValue" type="description" encrypt="true"/>
<field name="saltedEncryptedValue" type="description" encrypt="salt"/>
<prim-key field="testingCryptoId"/>
</entity>
<view-entity entity-name="TestingCryptoRawView"
@@ -209,5 +210,10 @@ under the License.
<complex-alias-field entity-alias="TC" field="encryptedValue"/>
</complex-alias>
</alias>
<alias name="rawSaltedEncryptedValue">
<complex-alias operator="+">
<complex-alias-field entity-alias="TC" field="saltedEncryptedValue"/>
</complex-alias>
</alias>
</view-entity>
</entitymodel>
@@ -33,6 +33,7 @@ import org.ofbiz.entity.datasource.GenericHelperInfo;
import org.ofbiz.entity.eca.EntityEcaHandler;
import org.ofbiz.entity.model.DynamicViewEntity;
import org.ofbiz.entity.model.ModelEntity;
import org.ofbiz.entity.model.ModelField;
import org.ofbiz.entity.model.ModelFieldType;
import org.ofbiz.entity.model.ModelFieldTypeReader;
import org.ofbiz.entity.model.ModelGroupReader;
@@ -264,8 +265,11 @@ public interface Delegator {
public void encryptFields(List<? extends GenericEntity> entities) throws GenericEntityException;
@Deprecated
public Object encryptFieldValue(String entityName, Object fieldValue) throws EntityCryptoException;
public Object encryptFieldValue(String entityName, ModelField.EncryptMethod encryptMethod, Object fieldValue) throws EntityCryptoException;
/**
* Finds GenericValues by the conditions specified in the EntityCondition
* object, the the EntityCondition javadoc for more details. NOTE 20080502:
@@ -2644,13 +2644,14 @@ public class GenericDelegator implements Delegator {
Iterator<ModelField> i = model.getFieldsIterator();
while (i.hasNext()) {
ModelField field = i.next();
if (field.getEncrypt()) {
ModelField.EncryptMethod encryptMethod = field.getEncryptMethod();
if (encryptMethod.isEncrypted()) {
Object obj = entity.get(field.getName());
if (obj != null) {
if (obj instanceof String && UtilValidate.isEmpty(obj)) {
continue;
}
entity.dangerousSetNoCheckButFast(field, this.encryptFieldValue(entityName, obj));
entity.dangerousSetNoCheckButFast(field, this.encryptFieldValue(entityName, encryptMethod, obj));
}
}
}
@@ -2660,12 +2661,21 @@ public class GenericDelegator implements Delegator {
* @see org.ofbiz.entity.Delegator#encryptFieldValue(java.lang.String, java.lang.Object)
*/
@Override
@Deprecated
public Object encryptFieldValue(String entityName, Object fieldValue) throws EntityCryptoException {
return encryptFieldValue(entityName, null, fieldValue);
}
@Override
public Object encryptFieldValue(String entityName, ModelField.EncryptMethod encryptMethod, Object fieldValue) throws EntityCryptoException {
if (encryptMethod == null) {
encryptMethod = ModelField.EncryptMethod.TRUE;
}
if (fieldValue != null) {
if (fieldValue instanceof String && UtilValidate.isEmpty(fieldValue)) {
return fieldValue;
}
return this.crypto.encrypt(entityName, fieldValue);
return this.crypto.encrypt(entityName, encryptMethod, fieldValue);
}
return fieldValue;
}
@@ -2693,7 +2703,8 @@ public class GenericDelegator implements Delegator {
Iterator<ModelField> i = model.getFieldsIterator();
while (i.hasNext()) {
ModelField field = i.next();
if (field.getEncrypt()) {
ModelField.EncryptMethod encryptMethod = field.getEncryptMethod();
if (encryptMethod.isEncrypted()) {
String keyName = entityName;
if (model instanceof ModelViewEntity) {
ModelViewEntity modelView = (ModelViewEntity) model;
@@ -1335,7 +1335,7 @@ public class GenericEntity implements Map<String, Object>, LocalizedMap<Object>,
for (String curKey: new TreeSet<String>(fields.keySet())) {
Object curValue = fields.get(curKey);
ModelField field = this.getModelEntity().getField(curKey);
if (field.getEncrypt() && curValue instanceof String) {
if (field.getEncryptMethod().isEncrypted() && curValue instanceof String) {
String encryptField = (String) curValue;
// the encryptField may not actually be UTF8, it could be any
// random encoding; just treat it as a series of raw bytes.
@@ -171,9 +171,9 @@ public class EntityExpr extends EntityCondition {
} else {
return;
}
if (modelField != null && modelField.getEncrypt()) {
if (modelField != null && modelField.getEncryptMethod().isEncrypted()) {
try {
this.rhs = delegator.encryptFieldValue(modelEntity.getEntityName(), this.rhs);
this.rhs = delegator.encryptFieldValue(modelEntity.getEntityName(), modelField.getEncryptMethod(), this.rhs);
} catch (EntityCryptoException e) {
Debug.logWarning(e, "Error encrypting field [" + modelEntity.getEntityName() + "." + modelField.getName() + "] with value: " + this.rhs, module);
}
@@ -355,7 +355,7 @@ public class ModelEntity implements Comparable<ModelEntity>, Serializable {
enableAuditLog = "true".equals(fieldElement.getAttribute("enable-audit-log"));
}
newField = ModelField.create(this, description, existingField.getName(), type, colName, existingField.getColValue(), existingField.getFieldSet(),
existingField.getIsNotNull(), existingField.getIsPk(), existingField.getEncrypt(), existingField.getIsAutoCreatedInternal(),
existingField.getIsNotNull(), existingField.getIsPk(), existingField.getEncryptMethod(), existingField.getIsAutoCreatedInternal(),
enableAuditLog, existingField.getValidators());
}
// add to the entity as a new field
@@ -24,6 +24,7 @@ import java.util.Iterator;
import java.util.List;
import org.ofbiz.base.lang.ThreadSafe;
import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilXml;
import org.ofbiz.entity.jdbc.DatabaseUtil;
import org.w3c.dom.Document;
@@ -36,6 +37,27 @@ import org.w3c.dom.Element;
@ThreadSafe
@SuppressWarnings("serial")
public final class ModelField extends ModelChild {
public static final String module = ModelField.class.getName();
public enum EncryptMethod {
FALSE {
public boolean isEncrypted() {
return false;
}
},
TRUE {
public boolean isEncrypted() {
return true;
}
},
SALT {
public boolean isEncrypted() {
return true;
}
};
public abstract boolean isEncrypted();
}
/**
* Returns a new <code>ModelField</code> instance, initialized with the specified values.
@@ -67,6 +89,10 @@ public final class ModelField extends ModelChild {
* @param validators The validators for this field.
*/
public static ModelField create(ModelEntity modelEntity, String description, String name, String type, String colName, String colValue, String fieldSet, boolean isNotNull, boolean isPk, boolean encrypt, boolean isAutoCreatedInternal, boolean enableAuditLog, List<String> validators) {
return create(modelEntity, description, name, type, colName, colValue, fieldSet, isNotNull, isPk, encrypt ? EncryptMethod.TRUE : EncryptMethod.FALSE, isAutoCreatedInternal, enableAuditLog, validators);
}
public static ModelField create(ModelEntity modelEntity, String description, String name, String type, String colName, String colValue, String fieldSet, boolean isNotNull, boolean isPk, EncryptMethod encrypt, boolean isAutoCreatedInternal, boolean enableAuditLog, List<String> validators) {
// TODO: Validate parameters.
if (description == null) {
description = "";
@@ -121,7 +147,11 @@ public final class ModelField extends ModelChild {
if (isPk) {
isNotNull = true;
}
boolean encrypt = "true".equals(fieldElement.getAttribute("encrypt"));
EncryptMethod encrypt = EncryptMethod.valueOf(fieldElement.getAttribute("encrypt").toUpperCase());
if (encrypt == null) {
Debug.logWarning("invalid encrypt value: %s", module, fieldElement.getAttribute("encrypt"));
encrypt = EncryptMethod.FALSE;
}
boolean enableAuditLog = "true".equals(fieldElement.getAttribute("enable-audit-log"));
List<String>validators = Collections.emptyList();
List<? extends Element> elementList = UtilXml.childElementList(fieldElement, "validate");
@@ -151,7 +181,7 @@ public final class ModelField extends ModelChild {
String description = "";
String colValue = "";
String fieldSet = "";
boolean encrypt = false;
EncryptMethod encrypt = EncryptMethod.FALSE;
boolean enableAuditLog = false;
return new ModelField(modelEntity, description, name, type, colName, colValue, fieldSet, isNotNull, isPk, encrypt, false, enableAuditLog, Collections.<String>emptyList());
}
@@ -175,7 +205,7 @@ public final class ModelField extends ModelChild {
/** boolean which specifies whether or not the Field is a Primary Key */
private final boolean isPk;
private final boolean encrypt;
private final EncryptMethod encrypt;
private final boolean isNotNull;
private final boolean isAutoCreatedInternal;
private final boolean enableAuditLog;
@@ -186,7 +216,7 @@ public final class ModelField extends ModelChild {
/** validators to be called when an update is done */
private final List<String> validators;
private ModelField(ModelEntity modelEntity, String description, String name, String type, String colName, String colValue, String fieldSet, boolean isNotNull, boolean isPk, boolean encrypt, boolean isAutoCreatedInternal, boolean enableAuditLog, List<String> validators) {
private ModelField(ModelEntity modelEntity, String description, String name, String type, String colName, String colValue, String fieldSet, boolean isNotNull, boolean isPk, EncryptMethod encrypt, boolean isAutoCreatedInternal, boolean enableAuditLog, List<String> validators) {
super(modelEntity, description);
this.name = name;
this.type = type;
@@ -231,7 +261,12 @@ public final class ModelField extends ModelChild {
}
/** Returns <code>true</code> if this field is encrypted. */
@Deprecated
public boolean getEncrypt() {
return this.encrypt.isEncrypted();
}
public EncryptMethod getEncryptMethod() {
return this.encrypt;
}
@@ -267,8 +302,8 @@ public final class ModelField extends ModelChild {
root.setAttribute("col-name", this.getColName());
}
root.setAttribute("type", this.getType());
if (this.getEncrypt()) {
root.setAttribute("encrypt", "true");
if (this.getEncryptMethod().isEncrypted()) {
root.setAttribute("encrypt", this.getEncryptMethod().toString().toLowerCase());
}
if (this.getIsNotNull()) {
root.setAttribute("not-null", "true");
@@ -431,7 +431,7 @@ public class ModelViewEntity extends ModelEntity {
String fieldSet = "";
boolean isNotNull = false;
boolean isPk = false;
boolean encrypt = false;
ModelField.EncryptMethod encryptMethod = ModelField.EncryptMethod.FALSE;
boolean isAutoCreatedInternal = false;
boolean enableAuditLog = false;
List<String> validators = null;
@@ -458,7 +458,7 @@ public class ModelViewEntity extends ModelEntity {
} else {
isPk = aliasedField.getIsPk();
}
encrypt = aliasedField.getEncrypt();
encryptMethod = aliasedField.getEncryptMethod();
type = aliasedField.getType();
validators = aliasedField.getValidators();
colValue = alias.entityAlias + "." + SqlJdbcUtil.filterColName(aliasedField.getColName());
@@ -492,7 +492,7 @@ public class ModelViewEntity extends ModelEntity {
colValue = prefix + colValue + ")";
}
}
ModelField field = ModelField.create(this, description, name, type, colName, colValue, fieldSet, isNotNull, isPk, encrypt, isAutoCreatedInternal, enableAuditLog, validators);
ModelField field = ModelField.create(this, description, name, type, colName, colValue, fieldSet, isNotNull, isPk, encryptMethod, isAutoCreatedInternal, enableAuditLog, validators);
// if this is a groupBy field, add it to the groupBys list
if (alias.groupBy || groupByFields.contains(alias.name)) {
this.groupBys.add(field);
@@ -38,24 +38,32 @@ public class EntityCryptoTestSuite extends EntityTestCase {
GenericValue entity = delegator.findOne("TestingCrypto", UtilMisc.toMap("testingCryptoId", "1"), false);
assertNull(entity.getString("unencryptedValue"));
assertNull(entity.getString("encryptedValue"));
assertNull(entity.getString("saltedEncryptedValue"));
GenericValue view = delegator.findOne("TestingCryptoRawView", UtilMisc.toMap("testingCryptoId", "1"), false);
assertNull(view.getString("unencryptedValue"));
assertNull(view.getString("encryptedValue"));
assertNull(view.getString("saltedEncryptedValue"));
assertNull(view.getString("rawEncryptedValue"));
assertNull(view.getString("rawSaltedEncryptedValue"));
// Verify that encryption is taking place
entity.setString("unencryptedValue", nanoTime);
entity.setString("encryptedValue", nanoTime);
entity.setString("saltedEncryptedValue", nanoTime);
entity.store();
view.refresh();
assertEquals(nanoTime, view.getString("unencryptedValue"));
assertEquals(nanoTime, view.getString("encryptedValue"));
assertEquals(nanoTime, view.getString("saltedEncryptedValue"));
String initialValue = view.getString("rawEncryptedValue");
String initialSaltedValue = view.getString("rawSaltedEncryptedValue");
assertFalse(nanoTime.equals(initialValue));
assertFalse(nanoTime.equals(initialSaltedValue));
assertFalse(initialValue.equals(initialSaltedValue));
// Verify that the same value stored repeatedly gives different raw encrypted values.
entity.setString("encryptedValue", nanoTime);
entity.setString("saltedEncryptedValue", nanoTime);
entity.store();
entity.refresh(); // this is a bug; store() ends up setting the encrypted value *into* the entity
assertEquals(nanoTime, entity.getString("unencryptedValue"));
@@ -64,9 +72,28 @@ public class EntityCryptoTestSuite extends EntityTestCase {
view.refresh();
assertEquals(nanoTime, view.getString("unencryptedValue"));
assertEquals(nanoTime, view.getString("encryptedValue"));
assertEquals(nanoTime, view.getString("saltedEncryptedValue"));
String updatedValue = view.getString("rawEncryptedValue");
String updatedSaltedValue = view.getString("rawSaltedEncryptedValue");
assertFalse(nanoTime.equals(updatedValue));
assertFalse(initialValue.equals(updatedValue));
assertFalse(nanoTime.equals(updatedSaltedValue));
assertFalse(updatedValue.equals(updatedSaltedValue));
assertEquals(initialValue, updatedValue);
assertFalse(initialSaltedValue.equals(updatedSaltedValue));
}
public void testCryptoLookup() throws Exception {
String nanoTime = "" + System.nanoTime();
delegator.removeByAnd("TestingCrypto", UtilMisc.toMap("testingCryptoTypeId", "LOOKUP"));
delegator.create("TestingCrypto", UtilMisc.toMap("testingCryptoId", "lookup-null", "testingCryptoTypeId", "LOOKUP"));
delegator.create("TestingCrypto", UtilMisc.toMap("testingCryptoId", "lookup-value", "testingCryptoTypeId", "LOOKUP", "encryptedValue", nanoTime, "saltedEncryptedValue", nanoTime));
assertEquals(1, delegator.findByAnd("TestingCrypto", UtilMisc.toMap("testingCryptoTypeId", "LOOKUP", "encryptedValue", null), null, false).size());
assertEquals(1, delegator.findByAnd("TestingCrypto", UtilMisc.toMap("testingCryptoTypeId", "LOOKUP", "saltedEncryptedValue", null), null, false).size());
assertEquals(1, delegator.findByAnd("TestingCrypto", UtilMisc.toMap("testingCryptoTypeId", "LOOKUP", "encryptedValue", nanoTime), null, false).size());
assertEquals(0, delegator.findByAnd("TestingCrypto", UtilMisc.toMap("testingCryptoTypeId", "LOOKUP", "saltedEncryptedValue", nanoTime), null, false).size());
}
}
@@ -40,6 +40,7 @@ import org.ofbiz.entity.EntityCryptoException;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.transaction.TransactionUtil;
import org.ofbiz.entity.model.ModelField.EncryptMethod;
public final class EntityCrypto {
@@ -65,7 +66,13 @@ public final class EntityCrypto {
}
/** Encrypts an Object into an encrypted hex encoded String */
@Deprecated
public String encrypt(String keyName, Object obj) throws EntityCryptoException {
return encrypt(keyName, EncryptMethod.TRUE, obj);
}
/** Encrypts an Object into an encrypted hex encoded String */
public String encrypt(String keyName, EncryptMethod encryptMethod, Object obj) throws EntityCryptoException {
try {
SecretKey key = this.findKey(keyName, handlers[0]);
if (key == null) {
@@ -91,7 +98,7 @@ public final class EntityCrypto {
}
}
}
return handlers[0].encryptValue(key, UtilObject.getBytes(obj));
return handlers[0].encryptValue(encryptMethod, key, UtilObject.getBytes(obj));
} catch (GeneralException e) {
throw new EntityCryptoException(e);
}
@@ -212,7 +219,7 @@ public final class EntityCrypto {
protected abstract String encodeKey(SecretKey key) throws GeneralException;
protected abstract byte[] decryptValue(SecretKey key, String encryptedString) throws GeneralException;
protected abstract String encryptValue(SecretKey key, byte[] objBytes) throws GeneralException;
protected abstract String encryptValue(EncryptMethod encryptMethod, SecretKey key, byte[] objBytes) throws GeneralException;
}
protected static abstract class LegacyStorageHandler extends StorageHandler {
@@ -232,7 +239,7 @@ public final class EntityCrypto {
}
@Override
protected String encryptValue(SecretKey key, byte[] objBytes) throws GeneralException {
protected String encryptValue(EncryptMethod encryptMethod, SecretKey key, byte[] objBytes) throws GeneralException {
return StringUtil.toHexString(DesCrypt.encrypt(key, objBytes));
}
};
@@ -306,11 +313,19 @@ public final class EntityCrypto {
}
@Override
protected String encryptValue(SecretKey key, byte[] objBytes) throws GeneralException {
Random random = new Random();
// random length 5-16
byte[] saltBytes = new byte[5 + random.nextInt(11)];
random.nextBytes(saltBytes);
protected String encryptValue(EncryptMethod encryptMethod, SecretKey key, byte[] objBytes) throws GeneralException {
byte[] saltBytes;
switch (encryptMethod) {
case SALT:
Random random = new Random();
// random length 5-16
saltBytes = new byte[5 + random.nextInt(11)];
random.nextBytes(saltBytes);
break;
default:
saltBytes = new byte[0];
break;
}
byte[] allBytes = new byte[1 + saltBytes.length + objBytes.length];
allBytes[0] = (byte) saltBytes.length;
System.arraycopy(saltBytes, 0, allBytes, 1, saltBytes.length);
@@ -711,7 +711,8 @@ public class WebToolsServices {
javaNameMap.put("type", (field.getType()) != null ? field.getType() : null);
javaNameMap.put("javaType", (field.getType() != null && type != null) ? type.getJavaType() : "Undefined");
javaNameMap.put("sqlType", (type != null && type.getSqlType() != null) ? type.getSqlType() : "Undefined");
javaNameMap.put("encrypted", field.getEncrypt());
javaNameMap.put("encrypted", field.getEncryptMethod().isEncrypted());
javaNameMap.put("encryptMethod", field.getEncryptMethod());
javaNameList.add(javaNameMap);
}