diff options
Diffstat (limited to 'ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom')
6 files changed, 841 insertions, 0 deletions
diff --git a/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/CustomDataTypeFactory.java b/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/CustomDataTypeFactory.java new file mode 100644 index 000000000..9e3442ff0 --- /dev/null +++ b/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/CustomDataTypeFactory.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-TEST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pdp.test.custom; + +import java.util.HashMap; +import java.util.Map; + +import com.att.research.xacml.api.DataType; +import com.att.research.xacml.api.DataTypeFactory; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.std.datatypes.DataTypes; + +public class CustomDataTypeFactory extends DataTypeFactory { + private static final Map<Identifier,DataType<?>> mapIdentifiersToDataTypes = new HashMap<Identifier,DataType<?>>(); + private static boolean mapNeedsInit = true; + + public static final DataTypePrivateKey DT_PRIVATEKEY = DataTypePrivateKey.newInstance(); + public static final DataTypePublicKey DT_PUBLICKEY = DataTypePublicKey.newInstance(); + + private static void registerDataType(DataType<?> dataType) { + if (dataType != null && dataType.getId() != null) { + mapIdentifiersToDataTypes.put(dataType.getId(), dataType); + } + } + + private static void initMap() { + if (mapNeedsInit) { + synchronized(mapIdentifiersToDataTypes) { + if (mapNeedsInit) { + registerDataType(DataTypes.DT_ANYURI); + registerDataType(DataTypes.DT_BASE64BINARY); + registerDataType(DataTypes.DT_BOOLEAN); + registerDataType(DataTypes.DT_DATE); + registerDataType(DataTypes.DT_DATETIME); + registerDataType(DataTypes.DT_DAYTIMEDURATION); + registerDataType(DataTypes.DT_DNSNAME); + registerDataType(DataTypes.DT_DOUBLE); + registerDataType(DataTypes.DT_HEXBINARY); + registerDataType(DataTypes.DT_INTEGER); + registerDataType(DataTypes.DT_IPADDRESS); + registerDataType(DataTypes.DT_RFC822NAME); + registerDataType(DataTypes.DT_STRING); + registerDataType(DataTypes.DT_TIME); + registerDataType(DataTypes.DT_X500NAME); + registerDataType(DataTypes.DT_XPATHEXPRESSION); + registerDataType(DataTypes.DT_YEARMONTHDURATION); + // + // These are the custom data types! + // + registerDataType(DT_PRIVATEKEY); + registerDataType(DT_PUBLICKEY); + // + // Done + // + mapNeedsInit = false; + } + } + } + } + + public CustomDataTypeFactory() { + initMap(); + } + + @Override + public DataType<?> getDataType(Identifier dataTypeId) { + return mapIdentifiersToDataTypes.get(dataTypeId); + } + +} diff --git a/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/CustomFunctionDefinitionFactory.java b/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/CustomFunctionDefinitionFactory.java new file mode 100644 index 000000000..3b86236d4 --- /dev/null +++ b/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/CustomFunctionDefinitionFactory.java @@ -0,0 +1,90 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-TEST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pdp.test.custom; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.util.HashMap; +import java.util.Map; + +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacmlatt.pdp.policy.FunctionDefinition; +import com.att.research.xacmlatt.pdp.policy.FunctionDefinitionFactory; +import com.att.research.xacmlatt.pdp.std.StdFunctions; +import com.att.research.xacmlatt.pdp.std.functions.FunctionDefinitionBagOneAndOnly; + +public class CustomFunctionDefinitionFactory extends FunctionDefinitionFactory { + private static Map<Identifier,FunctionDefinition> mapFunctionDefinitions = new HashMap<Identifier,FunctionDefinition>(); + private static boolean needMapInit = true; + + public static final Identifier ID_FUNCTION_PRIVATEKEY_ONE_AND_ONLY = new IdentifierImpl("urn:com:att:research:xacml:custom:function:3.0:rsa:privatekey-one-and-only"); + public static final Identifier ID_FUNCTION_PUBLICKEY_ONE_AND_ONLY = new IdentifierImpl("urn:com:att:research:xacml:custom:function:3.0:rsa:publickey-one-and-only"); + + public static final FunctionDefinition FD_PRIVATEKEY_ONE_AND_ONLY = new FunctionDefinitionBagOneAndOnly<PrivateKey>(ID_FUNCTION_PRIVATEKEY_ONE_AND_ONLY, DataTypePrivateKey.newInstance()); + public static final FunctionDefinition FD_PUBLICKEY_ONE_AND_ONLY = new FunctionDefinitionBagOneAndOnly<PublicKey>(ID_FUNCTION_PUBLICKEY_ONE_AND_ONLY, DataTypePublicKey.newInstance()); + + private static void register(FunctionDefinition functionDefinition) { + mapFunctionDefinitions.put(functionDefinition.getId(), functionDefinition); + } + + private static void initMap() { + if (needMapInit) { + synchronized(mapFunctionDefinitions) { + if (needMapInit) { + needMapInit = false; + Field[] declaredFields = StdFunctions.class.getDeclaredFields(); + for (Field field : declaredFields) { + if (Modifier.isStatic(field.getModifiers()) && + field.getName().startsWith(StdFunctions.FD_PREFIX) && + FunctionDefinition.class.isAssignableFrom(field.getType()) && + Modifier.isPublic(field.getModifiers()) + ) { + try { + register((FunctionDefinition)(field.get(null))); + } catch (IllegalAccessException ex) { + + } + } + } + // + // Our custom function + // + register(FunctionDefinitionDecrypt.newInstance()); + register(FD_PRIVATEKEY_ONE_AND_ONLY); + register(FD_PUBLICKEY_ONE_AND_ONLY); + } + } + } + } + + public CustomFunctionDefinitionFactory() { + initMap(); + } + + @Override + public FunctionDefinition getFunctionDefinition(Identifier functionId) { + return mapFunctionDefinitions.get(functionId); + } + +} diff --git a/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/DataTypePrivateKey.java b/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/DataTypePrivateKey.java new file mode 100644 index 000000000..3f84ef36e --- /dev/null +++ b/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/DataTypePrivateKey.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-TEST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pdp.test.custom; + +import java.security.PrivateKey; + +import com.att.research.xacml.api.DataTypeException; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.datatypes.DataTypeBase; + +public class DataTypePrivateKey extends DataTypeBase<PrivateKey> { + public static final Identifier DT_PRIVATEKEY = new IdentifierImpl("urn:com:att:research:xacml:custom:3.0:rsa:private"); + private static final DataTypePrivateKey singleInstance = new DataTypePrivateKey(); + + private DataTypePrivateKey() { + super(DT_PRIVATEKEY, PrivateKey.class); + } + + public static DataTypePrivateKey newInstance() { + return singleInstance; + } + + @Override + public PrivateKey convert(Object source) throws DataTypeException { + if (source == null || (source instanceof PrivateKey) ) { + return (PrivateKey) source; + } else if (source instanceof byte[]) { + return (PrivateKey) source; + } else if (source instanceof String) { + return (PrivateKey) (Object) ((String) source).getBytes(); + } + throw new DataTypeException(this, "Failed to convert \"" + source.getClass().getCanonicalName()); + } + +} diff --git a/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/DataTypePublicKey.java b/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/DataTypePublicKey.java new file mode 100644 index 000000000..ce28c534a --- /dev/null +++ b/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/DataTypePublicKey.java @@ -0,0 +1,54 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-TEST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pdp.test.custom; + +import java.security.PublicKey; + +import com.att.research.xacml.api.DataTypeException; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.datatypes.DataTypeBase; + +public class DataTypePublicKey extends DataTypeBase<PublicKey> { + public static final Identifier DT_PUBLICKEY = new IdentifierImpl("urn:com:att:research:xacml:custom:3.0:rsa:public"); + private static final DataTypePublicKey singleInstance = new DataTypePublicKey(); + + public DataTypePublicKey() { + super(DT_PUBLICKEY, PublicKey.class); + } + + public static DataTypePublicKey newInstance() { + return singleInstance; + } + + @Override + public PublicKey convert(Object source) throws DataTypeException { + if (source == null || (source instanceof PublicKey) ) { + return (PublicKey) source; + } else if (source instanceof byte[]) { + return (PublicKey) source; + } else if (source instanceof String) { + return (PublicKey) (Object) ((String) source).getBytes(); + } + throw new DataTypeException(this, "Failed to convert \"" + source.getClass().getCanonicalName()); + } + +} diff --git a/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/FunctionDefinitionDecrypt.java b/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/FunctionDefinitionDecrypt.java new file mode 100644 index 000000000..fafef2ae8 --- /dev/null +++ b/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/FunctionDefinitionDecrypt.java @@ -0,0 +1,162 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-TEST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pdp.test.custom; + +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.util.List; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; + +import com.att.research.xacml.api.DataType; +import com.att.research.xacml.api.DataTypeException; +import com.att.research.xacml.api.Identifier; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdStatus; +import com.att.research.xacml.std.StdStatusCode; +import com.att.research.xacml.std.datatypes.DataTypeHexBinary; +import com.att.research.xacml.std.datatypes.DataTypeString; +import com.att.research.xacml.std.datatypes.HexBinary; +import com.att.research.xacmlatt.pdp.eval.EvaluationContext; +import com.att.research.xacmlatt.pdp.policy.ExpressionResult; +import com.att.research.xacmlatt.pdp.policy.FunctionArgument; +import com.att.research.xacmlatt.pdp.policy.FunctionDefinition; +import com.att.research.xacmlatt.pdp.std.functions.ConvertedArgument; + +public class FunctionDefinitionDecrypt implements FunctionDefinition { + public static final Identifier FD_RSA_DECRYPT = new IdentifierImpl("urn:com:att:research:xacml:custom:function:3.0:rsa:decrypt"); + private static final FunctionDefinitionDecrypt singleInstance = new FunctionDefinitionDecrypt(); + + public static FunctionDefinitionDecrypt newInstance() { + return singleInstance; + } + + @Override + public Identifier getId() { + return FD_RSA_DECRYPT; + } + + @Override + public Identifier getDataTypeId() { + return XACML3.ID_DATATYPE_STRING; + } + + @Override + public boolean returnsBag() { + return false; + } + + @Override + public ExpressionResult evaluate(EvaluationContext evaluationContext, List<FunctionArgument> arguments) { + if (arguments == null || arguments.size() < 2) { + return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, expecting 2 arguments.")); + } + // + // What is the first argument? + // + FunctionArgument arg0 = arguments.get(0); + if (arg0.isBag()) { + // + // We don't support bags right now + // + return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, not expecting a bag for argument 0.")); + } + if (arg0.getValue().getDataTypeId().equals(XACML3.ID_DATATYPE_HEXBINARY) == false) { + // + // Should be a String + // + return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, expected a Hex Binary for argument 0.")); + } + // + // Convert the argument + // + ConvertedArgument<HexBinary> data = new ConvertedArgument<HexBinary>(arg0, DataTypeHexBinary.newInstance(), false); + if (! data.isOk()) { + return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, argument 0 failed to convert to Hex Binary.")); + } + // + // Ok - check the 2nd argument + // + FunctionArgument arg1 = arguments.get(1); + if (arg1.isBag()) { + // + // We don't support bags right now + // + return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, not expecting a bag for argument 1.")); + } + if (arg1.getValue().getDataTypeId().equals(DataTypePrivateKey.DT_PRIVATEKEY) || + arg1.getValue().getDataTypeId().equals(DataTypePublicKey.DT_PUBLICKEY)) { + // + // Ok - let's try to decrypt + // + Cipher cipher; + try { + cipher = Cipher.getInstance("RSA"); + if (arg1.getValue().getDataTypeId().equals(DataTypePrivateKey.DT_PRIVATEKEY)) { + // + // Using the private key + // + DataType<PrivateKey> pkDatatype = DataTypePrivateKey.newInstance(); + ConvertedArgument<PrivateKey> privateKey = new ConvertedArgument<PrivateKey>(arg1, pkDatatype, false); + if ( ! privateKey.isOk()) { + return ExpressionResult.newError(new StdStatus(privateKey.getStatus().getStatusCode(), "Decrypt: " + privateKey.getStatus().getStatusMessage())); + } + // + // Setup decryption + // + cipher.init(Cipher.DECRYPT_MODE, privateKey.getValue()); + } else if (arg1.getValue().getDataTypeId().equals(DataTypePublicKey.DT_PUBLICKEY)) { + // + // Using the private key + // + DataType<PublicKey> pkDatatype = DataTypePublicKey.newInstance(); + ConvertedArgument<PublicKey> publicKey = new ConvertedArgument<PublicKey>(arg1, pkDatatype, false); + if ( ! publicKey.isOk()) { + return ExpressionResult.newError(new StdStatus(publicKey.getStatus().getStatusCode(), "Decrypt: " + publicKey.getStatus().getStatusMessage())); + } + // + // Setup decryption + // + cipher.init(Cipher.DECRYPT_MODE, publicKey.getValue()); + } + // + // Do the decryption + // + byte[] decryptedData = cipher.doFinal(data.getValue().getData()); + String decryptedString = new String(decryptedData); + // + // All good, return the decrypted string + // + return ExpressionResult.newSingle(DataTypeString.newInstance().createAttributeValue(decryptedString)); + } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | DataTypeException e) { + return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed: " + e.getLocalizedMessage())); + } + } + return ExpressionResult.newError(new StdStatus(StdStatusCode.STATUS_CODE_PROCESSING_ERROR, "Decrypt failed, expecting public/private key datatype for argument 1.")); + } + +} diff --git a/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/TestCustom.java b/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/TestCustom.java new file mode 100644 index 000000000..b3f2455de --- /dev/null +++ b/ECOMP-TEST/src/test/java/org/openecomp/policy/pdp/test/custom/TestCustom.java @@ -0,0 +1,393 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP-TEST + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.pdp.test.custom; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.net.MalformedURLException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.security.InvalidKeyException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.util.ArrayList; +import java.util.List; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.GnuParser; +import org.apache.commons.cli.Option; +import org.apache.commons.cli.ParseException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.openecomp.policy.pdp.test.TestBase; + +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.api.DataType; +import com.att.research.xacml.api.DataTypeException; +import com.att.research.xacml.api.Request; +import com.att.research.xacml.api.RequestAttributes; +import com.att.research.xacml.api.XACML3; +import com.att.research.xacml.api.pep.PEPException; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdMutableAttribute; +import com.att.research.xacml.std.StdMutableRequest; +import com.att.research.xacml.std.StdMutableRequestAttributes; +import com.att.research.xacml.std.dom.DOMStructureException; +import com.att.research.xacml.std.json.JSONStructureException; +import com.att.research.xacml.util.FactoryException; + +/** + * TestCustom is an application that tests the extensibility and configurability of the AT&T XACML API. + * + * It creates a custom datatype definition factory that adds in custom data types for RSA + * PublicKey and PrivateKey. + * + * It creates a custom function definition factory that adds in custom decryption function for decrypting data. It + * also derives and loads custom functions for the RSA public/private key datatypes for the bag function: one-and-only. + * + * + */ +public class TestCustom extends TestBase { + private static final Log logger = LogFactory.getLog(TestCustom.class); + + // + // Our public's + // + public static final String ALGORITHM = "RSA"; + public static final String PRIVATEKEY_FILE = "PrivateKey.key"; + public static final String PUBLICKEY_FILE = "PublicKey.key"; + + public static final String DECRYPTION_INPUT_STRING = "This is the SECRET value!"; + + public static final String DECRYPTION_INPUT_ID = "com:att:research:xacml:test:custom:encrypted-data"; + // + // Our keys + // + protected PublicKey publicKey = null; + protected PrivateKey privateKey = null; + // + // Our command line parameters + // + public static final String OPTION_GENERATE = "generate"; + + static { + options.addOption(new Option(OPTION_GENERATE, false, "Generate a private/public key pair.")); + } + + /** + * This function generates the public/private key pair. Should never have to call this again, this was + * called once to generate the keys. They were saved into the testsets/custom/datatype-function sub-directory. + */ + public void generateKeyPair() { + // + // Generate a RSA private/public key pair + // + KeyPairGenerator keyGen; + try { + keyGen = KeyPairGenerator.getInstance(ALGORITHM); + } catch (NoSuchAlgorithmException e) { + logger.error("failed to generate keypair: " + e); + return; + } + keyGen.initialize(1024); + final KeyPair key = keyGen.generateKeyPair(); + // + // Save the keys to disk + // + Path file = Paths.get(this.directory, PRIVATEKEY_FILE); + try (ObjectOutputStream os = new ObjectOutputStream(Files.newOutputStream(file))) { + os.writeObject(key.getPrivate()); + } catch (IOException e) { + e.printStackTrace(); + } + file = Paths.get(this.directory, PUBLICKEY_FILE); + try (ObjectOutputStream os = new ObjectOutputStream(Files.newOutputStream(file))) { + os.writeObject(key.getPublic()); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public TestCustom(String[] args) throws ParseException, MalformedURLException, HelpException { + super(args); + } + + /* (non-Javadoc) + * + * Simply look for command line option: -generate + * This generates the public/private key. Shouldn't need to call it again, the keys have + * already been generated and saved. + * + * @see org.openecomp.policy.pdp.test.TestBase#parseCommands(java.lang.String[]) + */ + @Override + protected void parseCommands(String[] args) throws ParseException, MalformedURLException, HelpException { + // + // Have our parent class parse its options out + // + super.parseCommands(args); + // + // Parse the command line options + // + CommandLine cl; + cl = new GnuParser().parse(options, args); + if (cl.hasOption(OPTION_GENERATE)) { + // + // Really only need to do this once to setup the test. + // + this.generateKeyPair(); + } + } + + /* (non-Javadoc) + * + * After our parent class configure's itself, all this needs to do is read in + * the public/private key's into objects. + * + * @see org.openecomp.policy.pdp.test.TestBase#configure() + */ + @Override + protected void configure() throws FactoryException { + // + // Have our super do its thing + // + super.configure(); + // + // Read in the public key + // + try { + this.publicKey = (PublicKey) new ObjectInputStream(Files.newInputStream(Paths.get(this.directory, PUBLICKEY_FILE))).readObject(); + } catch (ClassNotFoundException | IOException e) { + logger.error(e); + } + // + // Read in the private key + // + try { + this.privateKey = (PrivateKey) new ObjectInputStream(Files.newInputStream(Paths.get(this.directory, PRIVATEKEY_FILE))).readObject(); + } catch (ClassNotFoundException | IOException e) { + logger.error(e); + } + } + + /* (non-Javadoc) + * + * Here we add 2 attributes into the request: 1) the private key, and 2) a String that was encrypted using the public key. + * + * The goal is to have the custom decrypt function use the private key to decrypt that string. + * + * @see org.openecomp.policy.pdp.test.TestBase#generateRequest(java.nio.file.Path, java.lang.String) + */ + @Override + protected Request generateRequest(Path file, String group) throws JSONStructureException, DOMStructureException, PEPException { + // + // Have our super class do its work + // + Request oldRequest = super.generateRequest(file, group); + // + // Copy the request attributes + // + List<StdMutableRequestAttributes> attributes = new ArrayList<StdMutableRequestAttributes>(); + for (RequestAttributes a : oldRequest.getRequestAttributes()) { + attributes.add(new StdMutableRequestAttributes(a)); + } + // + // We are supplying the private key as an attribute for the decryption function to use: + // + // (NOTE: Ideally this would be provided by a custom PIP provider, not the PEP) + // + // ID=com:att:research:xacml:test:custom:privatekey + // Issuer=com:att:research:xacml:test:custom + // Category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject + // Datatype=urn:com:att:research:xacml:custom:3.0:rsa:private + // + DataType<?> dtExtended = dataTypeFactory.getDataType(DataTypePrivateKey.DT_PRIVATEKEY); + if (dtExtended == null) { + logger.error("Failed to get private key datatype."); + return null; + } + // + // Create the attribute value + // + try { + AttributeValue<?> attributeValue = dtExtended.createAttributeValue(this.privateKey); + // + // Create the attribute + // + StdMutableAttribute newAttribute = new StdMutableAttribute(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT, + new IdentifierImpl("com:att:research:xacml:test:custom:privatekey"), + attributeValue, + "com:att:research:xacml:test:custom", + false); + boolean added = false; + for (StdMutableRequestAttributes a : attributes) { + // + // Does the category exist? + // + if (a.getCategory().equals(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT)) { + // + // Yes - add in the new attribute value + // + a.add(newAttribute); + added = true; + break; + } + } + if (added == false) { + // + // New category - create it and add it in + // + StdMutableRequestAttributes a = new StdMutableRequestAttributes(); + a.setCategory(newAttribute.getCategory()); + a.add(newAttribute); + attributes.add(a); + } + } catch (DataTypeException e) { + logger.error(e); + return null; + } + // + // We are also supplying this attribute which is the secret text encrypted with + // the public key. + // + // ID=com:att:research:xacml:test:custom:encrypted-data + // Issuer= + // Category=urn:oasis:names:tc:xacml:1.0:subject-category:access-subject + // Datatype=http://www.w3.org/2001/XMLSchema#hexBinary + // + // Encrypt it + // + byte[] encryptedData = null; + try { + Cipher cipher = Cipher.getInstance(ALGORITHM); + cipher.init(Cipher.ENCRYPT_MODE, this.publicKey); + // + // This is just a hack to test a decryption of the wrong value. + // + if (group.equals("Permit")) { + encryptedData = cipher.doFinal(DECRYPTION_INPUT_STRING.getBytes()); + } else { + encryptedData = cipher.doFinal("This is NOT the secret".getBytes()); + } + } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { + logger.error(e); + return null; + } + // + // Sanity check (for the Permit request) + // + try { + if (group.equals("Permit")) { + Cipher cipher = Cipher.getInstance(ALGORITHM); + cipher.init(Cipher.DECRYPT_MODE, this.privateKey); + byte[] decryptedData = cipher.doFinal(encryptedData); + if (new String(decryptedData).equals(DECRYPTION_INPUT_STRING)) { + logger.info("Sanity check passed: decrypted the encrypted data."); + } else { + logger.error("Sanity check failed to decrypt the encrypted data."); + return null; + } + } + } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) { + logger.error(e); + } + // + // Get our datatype factory + // + dtExtended = dataTypeFactory.getDataType(XACML3.ID_DATATYPE_HEXBINARY); + if (dtExtended == null) { + logger.error("Failed to get hex binary datatype."); + return null; + } + // + // Create the attribute value + // + try { + AttributeValue<?> attributeValue = dtExtended.createAttributeValue(encryptedData); + // + // Create the attribute + // + StdMutableAttribute newAttribute = new StdMutableAttribute(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT, + new IdentifierImpl("com:att:research:xacml:test:custom:encrypted-data"), + attributeValue, + null, + false); + boolean added = false; + for (StdMutableRequestAttributes a : attributes) { + // + // Does the category exist? + // + if (a.getCategory().equals(XACML3.ID_SUBJECT_CATEGORY_ACCESS_SUBJECT)) { + // + // Yes - add in the new attribute value + // + a.add(newAttribute); + added = true; + break; + } + } + if (added == false) { + // + // New category - create it and add it in + // + StdMutableRequestAttributes a = new StdMutableRequestAttributes(); + a.setCategory(newAttribute.getCategory()); + a.add(newAttribute); + attributes.add(a); + } + } catch (DataTypeException e) { + logger.error(e); + return null; + } + // + // Now form our final request + // + StdMutableRequest newRequest = new StdMutableRequest(); + newRequest.setCombinedDecision(oldRequest.getCombinedDecision()); + newRequest.setRequestDefaults(oldRequest.getRequestDefaults()); + newRequest.setReturnPolicyIdList(oldRequest.getReturnPolicyIdList()); + newRequest.setStatus(oldRequest.getStatus()); + for (StdMutableRequestAttributes a : attributes) { + newRequest.add(a); + } + return newRequest; + } + + public static void main(String[] args) { + try { + new TestCustom(args).run(); + } catch (ParseException | IOException | FactoryException e) { + logger.error(e); + } catch (HelpException e) { + } + } + +} |