summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--BRMSGateway/config.properties5
-rw-r--r--BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java21
-rw-r--r--LogParser/parserlog.properties5
-rw-r--r--LogParser/src/main/java/org/onap/xacml/parser/ParseLog.java15
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java18
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java30
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java16
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java4
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java13
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java59
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java50
-rw-r--r--ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java13
-rw-r--r--ONAP-PAP-REST/xacml.pap.properties8
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java13
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java81
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java49
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPApiAuth.java94
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestConfig.java211
-rw-r--r--ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/AuthenticationService.java22
-rw-r--r--ONAP-PDP-REST/xacml.pdp.properties3
-rw-r--r--ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRestProperties.java13
-rw-r--r--ONAP-SDK-APP/src/main/java/org/onap/portalapp/conf/ExternalAppConfig.java209
-rw-r--r--ONAP-SDK-APP/xacml.admin.properties5
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java9
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java20
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java264
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java8
-rw-r--r--POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java5
-rw-r--r--PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java5
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/CryptoUtils.java256
-rw-r--r--PolicyEngineUtils/src/main/java/org/onap/policy/utils/PeCryptoUtils.java102
-rw-r--r--PolicyEngineUtils/src/test/java/org/onap/policy/utils/PeCryptoUtilsTest.java64
-rw-r--r--PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/CryptoUtilsTest.java128
-rw-r--r--packages/base/src/files/install/servers/brmsgw/config.properties5
-rw-r--r--packages/base/src/files/install/servers/console/bin/xacml.admin.properties7
-rw-r--r--packages/base/src/files/install/servers/pap/bin/xacml.pap.properties7
-rw-r--r--packages/base/src/files/install/servers/paplp/bin/parserlog.properties5
-rw-r--r--packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties4
-rwxr-xr-xpackages/base/src/files/install/servers/pdplp/bin/parserlog.properties5
39 files changed, 854 insertions, 997 deletions
diff --git a/BRMSGateway/config.properties b/BRMSGateway/config.properties
index d99e0e658..2ef1a28be 100644
--- a/BRMSGateway/config.properties
+++ b/BRMSGateway/config.properties
@@ -2,7 +2,7 @@
# ============LICENSE_START=======================================================
# ONAP Policy Engine
# ================================================================================
-# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+# Copyright (C) 2017-2019 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.
@@ -80,3 +80,6 @@ ping_interval=30000
brms.dependency.version=1.4.0-SNAPSHOT
ENVIRONMENT = DEVL
+
+# AES key for password encryption in config files
+#org.onap.policy.encryption.aes.key=12345678901234567890123456789012
diff --git a/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java b/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java
index 4466afe3c..a48aac04e 100644
--- a/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java
+++ b/BRMSGateway/src/main/java/org/onap/policy/brms/api/BrmsPush.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -25,7 +25,6 @@ import com.att.nsa.cambria.client.CambriaBatchingPublisher;
import com.att.nsa.cambria.client.CambriaClientBuilders;
import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder;
import com.fasterxml.jackson.core.JsonProcessingException;
-
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@@ -53,14 +52,12 @@ import java.util.concurrent.TimeUnit;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Pattern;
-
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.ws.rs.ProcessingException;
-
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.maven.model.Dependency;
@@ -93,6 +90,7 @@ import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.utils.BackUpHandler;
import org.onap.policy.utils.BackUpMonitor;
import org.onap.policy.utils.BusPublisher;
+import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
@@ -120,6 +118,7 @@ public class BrmsPush {
private static final String[] GOALS = { "clean", "deploy" };
private static final String DEFAULT_VERSION = "1.4.0-SNAPSHOT";
private static final String DEPENDENCY_FILE = "dependency.json";
+ private static final String PROP_AES_KEY = "org.onap.policy.encryption.aes.key";
public static final String BRMSPERSISTENCE = "brmsEclipselink.persistencexml";
private static Map<String, String> modifiedGroups = new HashMap<>();
@@ -187,6 +186,9 @@ public class BrmsPush {
throw new PolicyException(XACMLErrorConstants.ERROR_DATA_ISSUE
+ "Data/File Read Error while reading from the property file.");
}
+ // init the aes key from prop or env
+ PeCryptoUtils.initAesKey(config.getProperty(PROP_AES_KEY));
+
LOGGER.info("Trying to set up IntegrityMonitor");
String resourceName = null;
try {
@@ -254,7 +256,7 @@ public class BrmsPush {
repUrlList.add(repUrl);
}
repUserName = config.getProperty("repositoryUsername");
- repPassword = config.getProperty("repositoryPassword");
+ repPassword = PeCryptoUtils.decrypt(config.getProperty("repositoryPassword"));
if (repUserName == null || repPassword == null) {
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
+ "repostoryUserName and respositoryPassword properties are required.");
@@ -521,8 +523,10 @@ public class BrmsPush {
LOGGER.info("Updated Local Memory values with values from database.");
} catch (final Exception exception) {
LOGGER.error("Unable to sync group info", exception);
- et.rollback();
- throw exception;
+ if (et.isActive()) {
+ et.rollback();
+ }
+
}
}
@@ -581,7 +585,6 @@ public class BrmsPush {
} catch (final Exception exception) {
LOGGER.error("Unable add policy to database", exception);
et.rollback();
- throw exception;
}
}
@@ -1147,7 +1150,6 @@ public class BrmsPush {
} catch (final Exception exception) {
LOGGER.error("Unable add/update policy group to database for controller name: " + name, exception);
et.rollback();
- throw exception;
}
}
@@ -1203,7 +1205,6 @@ public class BrmsPush {
} catch (final Exception exception) {
LOGGER.error("Unable remove policy from group to database for policy name: " + policyName, exception);
et.rollback();
- throw exception;
}
}
diff --git a/LogParser/parserlog.properties b/LogParser/parserlog.properties
index accf33866..a41fc4cbc 100644
--- a/LogParser/parserlog.properties
+++ b/LogParser/parserlog.properties
@@ -2,7 +2,7 @@
# ============LICENSE_START=======================================================
# LogParser
# ================================================================================
-# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+# Copyright (C) 2017-2019 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.
@@ -38,3 +38,6 @@ LOGPATH=C:\\Workspaces\\HealthCheck\\pap-rest.log
PARSERLOGPATH=parserlog.log
node_type=logparser
site_name=site_1
+
+# AES key for password encryption in config files
+#org.onap.policy.encryption.aes.key=12345678901234567890123456789012
diff --git a/LogParser/src/main/java/org/onap/xacml/parser/ParseLog.java b/LogParser/src/main/java/org/onap/xacml/parser/ParseLog.java
index 54e86d250..f12522af6 100644
--- a/LogParser/src/main/java/org/onap/xacml/parser/ParseLog.java
+++ b/LogParser/src/main/java/org/onap/xacml/parser/ParseLog.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* LogParser
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -45,12 +45,11 @@ import java.util.Timer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Stream;
-
import org.apache.log4j.Logger;
import org.onap.policy.common.im.IntegrityMonitor;
import org.onap.policy.common.im.IntegrityMonitorException;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.utils.CryptoUtils;
+import org.onap.policy.utils.PeCryptoUtils;
import org.onap.xacml.parser.LogEntryObject.LogType;
/**
@@ -62,6 +61,7 @@ public class ParseLog {
// only logging last line of each log file processed to the log4j log file defined by property - PARSERLOGPATH
private static final Logger log4jlogger = Logger.getLogger(ParseLog.class.getName());
+ private static final String PROP_AES_KEY = "org.onap.policy.encryption.aes.key";
// processing logging
private static org.onap.policy.common.logging.flexlogger.Logger logger =
@@ -393,7 +393,7 @@ public class ParseLog {
logger.debug("builder.toString(): " + builder.toString());
if (builder.toString().contains(last + dataFileName + lineRead)) {
final String[] parseString = builder.toString().split(last + dataFileName + lineRead);
- final String returnValue = parseString[1].replace("\r", "");
+ final String returnValue = parseString[1].replace("\r", "");
return returnValue.trim();
}
builder = new StringBuilder();
@@ -886,9 +886,10 @@ public class ParseLog {
jdbcUrl = config.getProperty("JDBC_URL").replace("'", "");
jdbcUser = config.getProperty("JDBC_USER");
jdbcDriver = config.getProperty("JDBC_DRIVER");
- jdbcPassword = CryptoUtils.decryptTxtNoExStr(config.getProperty("JDBC_PASSWORD", ""));
- config.setProperty("javax.persistence.jdbc.password",
- CryptoUtils.decryptTxtNoExStr(config.getProperty("javax.persistence.jdbc.password", "")));
+
+ PeCryptoUtils.initAesKey(config.getProperty(PROP_AES_KEY));
+ jdbcPassword = PeCryptoUtils.decrypt(config.getProperty("JDBC_PASSWORD"));
+ config.setProperty("javax.persistence.jdbc.password", jdbcPassword);
return config;
} catch (final IOException e) {
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java
index 614ba85df..9ccccff05 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java
@@ -2,15 +2,15 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* ================================================================================
* 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.
@@ -18,21 +18,20 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest;
import java.io.FileInputStream;
-import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
-
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
-
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.utils.CryptoUtils;
+import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.utils.PeCryptoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@@ -64,7 +63,8 @@ public class PAPRestConfig extends WebMvcConfigurerAdapter {
setDbDriver(prop.getProperty("javax.persistence.jdbc.driver"));
setDbUrl(prop.getProperty("javax.persistence.jdbc.url"));
setDbUserName(prop.getProperty("javax.persistence.jdbc.user"));
- setDbPassword( CryptoUtils.decryptTxtNoExStr(prop.getProperty("javax.persistence.jdbc.password", "")));
+ PeCryptoUtils.initAesKey(prop.getProperty(XACMLRestProperties.PROP_AES_KEY));
+ setDbPassword(PeCryptoUtils.decrypt(prop.getProperty("javax.persistence.jdbc.password")));
}catch(Exception e){
LOGGER.error("Exception Occured while loading properties file"+e);
}
@@ -131,7 +131,7 @@ public class PAPRestConfig extends WebMvcConfigurerAdapter {
}
public static void setDbPassword(String dbPassword) {
- PAPRestConfig.dbPassword = CryptoUtils.decryptTxtNoExStr(dbPassword);
+ PAPRestConfig.dbPassword = dbPassword;
}
}
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java
index bd000381b..22f919e4b 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2018-2019 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.
@@ -17,8 +17,11 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest;
+import com.att.research.xacml.util.XACMLProperties;
+import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
@@ -30,10 +33,8 @@ import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-
import org.json.JSONObject;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
@@ -45,7 +46,7 @@ import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.ActionBodyEntity;
import org.onap.policy.rest.jpa.ConfigurationDataEntity;
import org.onap.policy.rest.jpa.PolicyDBDaoEntity;
-import org.onap.policy.utils.CryptoUtils;
+import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
@@ -60,12 +61,10 @@ import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
@Controller
public class UpdateOthersPAPS {
- private static final Logger policyLogger = FlexLogger.getLogger(UpdateOthersPAPS.class);
+ private static final Logger policyLogger = FlexLogger.getLogger(UpdateOthersPAPS.class);
private static CommonClassDao commonClassDao;
@@ -82,7 +81,7 @@ public class UpdateOthersPAPS {
}
@Autowired
- private UpdateOthersPAPS(CommonClassDao commonClassDao){
+ private UpdateOthersPAPS(CommonClassDao commonClassDao) {
UpdateOthersPAPS.commonClassDao = commonClassDao;
}
@@ -110,14 +109,15 @@ public class UpdateOthersPAPS {
String password = papId.getPassword();
Base64.Encoder encoder = Base64.getEncoder();
String txt;
- try{
- txt = new String(CryptoUtils.decryptTxt(password), StandardCharsets.UTF_8);
- } catch(Exception e){
+ try {
+ PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
+ txt = PeCryptoUtils.decrypt(password);
+ } catch (Exception e) {
policyLogger.debug(e);
//if we can't decrypt, might as well try it anyway
txt = password;
}
- String encoding = encoder.encodeToString((userName+":"+txt).getBytes(StandardCharsets.UTF_8));
+ String encoding = encoder.encodeToString((userName + ":" + txt).getBytes(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Basic " + encoding);
headers.set("Content-Type", contentType);
@@ -237,4 +237,4 @@ public class UpdateOthersPAPS {
policyLogger.error("Exception Occured While closing the File input stream"+e);
}
}
-} \ No newline at end of file
+}
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java
index 889905eb6..f2e038721 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java
@@ -75,7 +75,7 @@ import org.onap.policy.pap.xacml.restAuth.CheckPDP;
import org.onap.policy.rest.XACMLRest;
import org.onap.policy.rest.XACMLRestProperties;
import org.onap.policy.rest.dao.PolicyDBException;
-import org.onap.policy.utils.CryptoUtils;
+import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.api.pap.ONAPPapEngineFactory;
@@ -89,7 +89,7 @@ import org.onap.policy.xacml.std.pap.StdPDPPolicy;
import org.onap.policy.xacml.std.pap.StdPDPStatus;
/**
- * Servlet implementation class XacmlPapServlet
+ * Servlet implementation class XacmlPapServlet.
*/
@WebServlet(description = "Implements the XACML PAP RESTful API.", urlPatterns = {"/"},
loadOnStartup = 1,
@@ -264,14 +264,13 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
}
// Create an IntegrityMonitor
if (properties.getProperty(PERSISTENCE_JDBC_PWD) != null) {
- properties.setProperty(PERSISTENCE_JDBC_PWD, CryptoUtils
- .decryptTxtNoExStr(properties.getProperty(PERSISTENCE_JDBC_PWD, "")));
+ properties.setProperty(PERSISTENCE_JDBC_PWD,
+ PeCryptoUtils.decrypt(properties.getProperty(PERSISTENCE_JDBC_PWD, "")));
}
im = IntegrityMonitor.getInstance(papResourceName, properties);
// Create an IntegrityAudit
ia = new IntegrityAudit(papResourceName, AUDIT_PAP_PERSISTENCE_UNIT, properties);
ia.startAuditThread();
-
// we are about to call the PDPs and give them their configuration.
// To do that we need to have the URL of this PAP so we can
// construct the Policy file URLs
@@ -298,7 +297,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
LOGGER.info("PapServlet: calling auditLocalFileSystem for PDP group audit");
LOGGER.info("PapServlet: old group is " + papEngine.getDefaultGroup().toString());
- // get the current filesystem group and update from the database if needed
+ // get the current filesystem group and update from the database
+ // if needed
StdPDPGroup group = (StdPDPGroup) papEngine.getDefaultGroup();
StdPDPGroup updatedGroup = policyDbDao.auditLocalFileSystem(group);
if (updatedGroup != null) {
@@ -456,8 +456,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList
throw new PAPException("papDbUser is null");
}
setPapDbUser(papDbUser);
- papDbPd = CryptoUtils.decryptTxtNoExStr(
- XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD, ""));
+ PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
+ papDbPd = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD));
if (papDbPd == null) {
PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet",
" ERROR: Bad papDbPassword property entry");
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java
index cd02c2bfe..2e2a74015 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java
@@ -35,7 +35,7 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.rest.XACMLRestProperties;
import org.onap.policy.rest.jpa.PolicyDBDaoEntity;
-import org.onap.policy.utils.CryptoUtils;
+import org.onap.policy.utils.PeCryptoUtils;
public class NotifyOtherPaps {
@@ -108,7 +108,7 @@ public class NotifyOtherPaps {
String username = dbdEntity.getUsername();
String txt;
try {
- txt = new String(CryptoUtils.decryptTxt(dbdEntity.getPassword()), StandardCharsets.UTF_8);
+ txt = PeCryptoUtils.decrypt(dbdEntity.getPassword());
} catch (Exception e) {
LOGGER.debug(e);
// if we can't decrypt, might as well try it anyway
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java
index 9f5933850..9a39b6ed1 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java
@@ -58,7 +58,7 @@ import org.onap.policy.rest.jpa.GroupEntity;
import org.onap.policy.rest.jpa.PdpEntity;
import org.onap.policy.rest.jpa.PolicyDBDaoEntity;
import org.onap.policy.rest.jpa.PolicyEntity;
-import org.onap.policy.utils.CryptoUtils;
+import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.api.pap.OnapPDP;
import org.onap.policy.xacml.api.pap.OnapPDPGroup;
@@ -280,7 +280,7 @@ public class PolicyDBDao {
}
if (urlUserPass[2] == null || "".equals(urlUserPass[2])) {
String passwordPropertyValue =
- XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
+ PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
if (passwordPropertyValue != null) {
urlUserPass[2] = passwordPropertyValue;
}
@@ -343,14 +343,7 @@ public class PolicyDBDao {
}
// encrypt the password
- String txt = null;
- try {
- txt = CryptoUtils.encryptTxt(url[2].getBytes(StandardCharsets.UTF_8));
- } catch (Exception e) {
- logger.debug(e);
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR,
- "Could not encrypt PAP password");
- }
+ String txt = PeCryptoUtils.encrypt(url[2]);
if (foundPolicyDBDaoEntity == null) {
PolicyDBDaoEntity newPolicyDBDaoEntity = new PolicyDBDaoEntity();
newPolicyDBDaoEntity.setPolicyDBDaoUrl(url[0]);
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java
index 79b07e2b9..f04be861b 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 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.
@@ -17,8 +17,17 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.elk.client;
+import com.google.gson.Gson;
+import io.searchbox.client.JestClientFactory;
+import io.searchbox.client.config.HttpClientConfig;
+import io.searchbox.client.http.JestHttpClient;
+import io.searchbox.core.Bulk;
+import io.searchbox.core.Bulk.Builder;
+import io.searchbox.core.BulkResult;
+import io.searchbox.core.Index;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
@@ -34,21 +43,6 @@ import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
-
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.utils.CryptoUtils;
-import org.onap.policy.xacml.util.XACMLPolicyScanner;
-
-import com.google.gson.Gson;
-
-import io.searchbox.client.JestClientFactory;
-import io.searchbox.client.config.HttpClientConfig;
-import io.searchbox.client.http.JestHttpClient;
-import io.searchbox.core.Bulk;
-import io.searchbox.core.Bulk.Builder;
-import io.searchbox.core.BulkResult;
-import io.searchbox.core.Index;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
@@ -56,24 +50,28 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.utils.PeCryptoUtils;
+import org.onap.policy.xacml.util.XACMLPolicyScanner;
/**
- * This code will deals with parsing the XACML content on reading from
+ * This code will deals with parsing the XACML content on reading from
* database(PolicyEntity, ConfigurationDataEntity and ActionBodyEntity tables)
* and convert the data into json to do bulk operation on putting to elastic search database.
* Which is used to support Elastic Search in Policy Application GUI to search policies.
- *
- *
- *
+ *
+ *
+ *
* properties should be configured in policyelk.properties
*
*/
public class ElasticSearchPolicyUpdate {
private static final Logger LOGGER = FlexLogger.getLogger(ElasticSearchPolicyUpdate.class);
- protected final static JestClientFactory jestFactory = new JestClientFactory();
+ protected static final JestClientFactory jestFactory = new JestClientFactory();
public static void main(String[] args) {
@@ -86,23 +84,24 @@ public class ElasticSearchPolicyUpdate {
String propertyFile = System.getProperty("PROPERTY_FILE");
Properties config = new Properties();
Path file = Paths.get(propertyFile);
- if(!file.toFile().exists()){
+ if (!file.toFile().exists()) {
LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString());
- }else{
- if(file.toString().endsWith(".properties")){
+ } else {
+ if (file.toString().endsWith(".properties")) {
try {
InputStream in = new FileInputStream(file.toFile());
config.load(in);
elkURL = config.getProperty("policy.elk.url");
databseUrl = config.getProperty("policy.database.url");
userName = config.getProperty("policy.database.username");
- txt = CryptoUtils.decryptTxtNoExStr(config.getProperty("policy.database.password"));
+ txt = PeCryptoUtils.decrypt(config.getProperty("policy.database.password"));
databaseDriver = config.getProperty("policy.database.driver");
- if(elkURL == null || databseUrl == null || userName == null || txt == null || databaseDriver == null){
+ if (elkURL == null || databseUrl == null || userName == null || txt == null
+ || databaseDriver == null) {
LOGGER.error("please check the elk configuration");
}
} catch (Exception e) {
- LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString(),e);
+ LOGGER.error("Config File doesn't Exist in the specified Path " + file.toString(), e);
}
}
}
@@ -379,4 +378,4 @@ public class ElasticSearchPolicyUpdate {
}
}
}
-} \ No newline at end of file
+}
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java
index 0ac6c7009..10cc81549 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 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.
@@ -20,32 +20,48 @@
package org.onap.policy.pap.xacml.restAuth;
+import com.att.research.xacml.util.XACMLProperties;
+import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.StringTokenizer;
-
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
import org.onap.policy.rest.XACMLRestProperties;
-import org.onap.policy.utils.CryptoUtils;
-
-import com.att.research.xacml.util.XACMLProperties;
+import org.onap.policy.utils.PeCryptoUtils;
public class AuthenticationService {
- private String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
- private String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
+ private String papId = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
+ private String papPass = null;
+ /**
+ * Authenticate.
+ *
+ * @param authCredentials the auth credentials
+ * @return true, if successful
+ */
public boolean authenticate(String authCredentials) {
- if (null == authCredentials)
+ if (null == authCredentials) {
return false;
+ }
// header value format will be "Basic encodedstring" for Basic authentication.
- final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", "");
+ final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", "");
String usernameAndPassword = null;
+
+ try {
+ String secretKey = XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY);
+ PeCryptoUtils.initAesKey(secretKey);
+ papPass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
+ } catch (Exception e) {
+ PolicyLogger.error(e);
+ }
+
try {
byte[] decodedBytes = Base64.getDecoder().decode(encodedUserPassword);
- usernameAndPassword = new String(decodedBytes, "UTF-8");
+ usernameAndPassword = new String(decodedBytes, StandardCharsets.UTF_8);
} catch (Exception e) {
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AuthenticationService", "Exception decoding username and password");
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AuthenticationService",
+ "Exception decoding username and password");
return false;
}
try {
@@ -53,10 +69,10 @@ public class AuthenticationService {
final String username = tokenizer.nextToken();
final String password = tokenizer.nextToken();
- boolean authenticationStatus = papID.equals(username) && papPass.equals(password);
- return authenticationStatus;
- } catch (Exception e){
- PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AuthenticationService", "Exception authenticating user");
+ return papId.equals(username) && papPass.equals(password);
+ } catch (Exception e) {
+ PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "AuthenticationService",
+ "Exception authenticating user");
return false;
}
}
diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java
index cddcb2a4c..181dd0910 100644
--- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java
+++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017,2019 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.
@@ -20,6 +20,7 @@
package org.onap.policy.pap.xacml.restAuth;
+import com.att.research.xacml.api.pap.PAPException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -36,16 +37,14 @@ import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
-
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
+import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
-import com.att.research.xacml.api.pap.PAPException;
-
public class CheckPDP {
private static Path pdpPath = null;
@@ -148,7 +147,7 @@ public class CheckPDP {
if(pdpValues.size()==3){
// 1:2 will be UserID:Password
String userID = pdpValues.get(1);
- String pass = pdpValues.get(2);
+ String pass = PeCryptoUtils.decrypt(pdpValues.get(2));
Base64.Encoder encoder = Base64.getEncoder();
// 0 - PDPURL
pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8)));
diff --git a/ONAP-PAP-REST/xacml.pap.properties b/ONAP-PAP-REST/xacml.pap.properties
index c26e96ff9..6ce51473d 100644
--- a/ONAP-PAP-REST/xacml.pap.properties
+++ b/ONAP-PAP-REST/xacml.pap.properties
@@ -2,7 +2,7 @@
# ============LICENSE_START=======================================================
# ONAP-PAP-REST
# ================================================================================
-# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+# Copyright (C) 2017-2019 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.
@@ -158,4 +158,8 @@ CLIENT_KEY=
#Micro Service Model Properties
xacml.policy.msOnapName=http://org.onap
-xacml.policy.msPolicyName=http://org.onap.policy \ No newline at end of file
+xacml.policy.msPolicyName=http://org.onap.policy
+
+
+# AES key for password encryption in config files
+#org.onap.policy.encryption.aes.key=12345678901234567890123456789012
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java
index 5462dd908..0fab3db61 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/PapUrlResolver.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP-PDP-REST
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 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.
@@ -20,6 +20,7 @@
package org.onap.policy.pdp.rest;
+import com.att.research.xacml.util.XACMLProperties;
import java.net.URI;
import java.text.DateFormat;
import java.text.ParseException;
@@ -28,13 +29,10 @@ import java.util.Date;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Properties;
-
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.rest.XACMLRestProperties;
-import org.onap.policy.utils.CryptoUtils;
-
-import com.att.research.xacml.util.XACMLProperties;
+import org.onap.policy.utils.PeCryptoUtils;
public class PapUrlResolver {
private static final Logger LOGGER = FlexLogger.getLogger(PapUrlResolver.class);
@@ -119,10 +117,11 @@ public class PapUrlResolver {
String userId = null;
String pass = null;
userId = XACMLProperties.getProperty(urls[i] + "." + XACMLRestProperties.PROP_PAP_USERID);
- pass = XACMLProperties.getProperty(urls[i] + "." + CryptoUtils.decryptTxtNoExStr(XACMLRestProperties.PROP_PAP_PASS));
+ pass = XACMLProperties.getProperty(urls[i] + "."
+ + PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)));
if (userId == null || pass == null) {
userId = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
- pass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
+ pass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
}
if (userId == null || pass == null) {
userId = "";
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java
index c227d9d2a..c86e21c09 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/XACMLPdpServlet.java
@@ -7,9 +7,9 @@
* 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.
@@ -20,6 +20,17 @@
package org.onap.policy.pdp.rest;
+import com.att.research.xacml.api.Request;
+import com.att.research.xacml.api.Response;
+import com.att.research.xacml.api.pap.PDPStatus.Status;
+import com.att.research.xacml.api.pdp.PDPEngine;
+import com.att.research.xacml.api.pdp.PDPException;
+import com.att.research.xacml.std.dom.DOMRequest;
+import com.att.research.xacml.std.dom.DOMResponse;
+import com.att.research.xacml.std.json.JSONRequest;
+import com.att.research.xacml.std.json.JSONResponse;
+import com.att.research.xacml.util.XACMLProperties;
+import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -60,40 +71,30 @@ import org.onap.policy.common.logging.eelf.PolicyLogger;
import org.onap.policy.pdp.rest.jmx.PdpRestMonitor;
import org.onap.policy.rest.XACMLRest;
import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.pdp.std.functions.PolicyList;
import org.onap.policy.xacml.std.pap.StdPDPStatus;
-import com.att.research.xacml.api.Request;
-import com.att.research.xacml.api.Response;
-import com.att.research.xacml.api.pap.PDPStatus.Status;
-import com.att.research.xacml.api.pdp.PDPEngine;
-import com.att.research.xacml.api.pdp.PDPException;
-import com.att.research.xacml.std.dom.DOMRequest;
-import com.att.research.xacml.std.dom.DOMResponse;
-import com.att.research.xacml.std.json.JSONRequest;
-import com.att.research.xacml.std.json.JSONResponse;
-import com.att.research.xacml.util.XACMLProperties;
-import com.fasterxml.jackson.databind.ObjectMapper;
/**
* Servlet implementation class XacmlPdpServlet
- *
+ *
* This is an implementation of the XACML 3.0 RESTful Interface with added features to support simple PAP RESTful API
* for policy publishing and PIP configuration changes.
- *
+ *
* If you are running this the first time, then we recommend you look at the xacml.pdp.properties file. This properties
* file has all the default parameter settings. If you are running the servlet as is, then we recommend setting up
* you're container to run it on port 8080 with context "/pdp". Wherever the default working directory is set to, a
* "config" directory will be created that holds the policy and pip cache. This setting is located in the
* xacml.pdp.properties file.
- *
+ *
* When you are ready to customize, you can create a separate xacml.pdp.properties on you're local file system and setup
* the parameters as you wish. Just set the Java VM System variable to point to that file:
- *
+ *
* -Dxacml.properties=/opt/app/xacml/etc/xacml.pdp.properties
- *
+ *
* Or if you only want to change one or two properties, simply set the Java VM System variable for that property.
- *
+ *
* -Dxacml.rest.pdp.register=false
*
*
@@ -268,9 +269,13 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
properties.getProperty("createUpdatePolicy.impl.className", CREATE_UPDATE_POLICY_SERVICE);
setCreateUpdatePolicyConstructor(createUpdateResourceName);
+ PeCryptoUtils.initAesKey(properties.getProperty(XACMLRestProperties.PROP_AES_KEY));
+
// Create an IntegrityMonitor
try {
logger.info("Creating IntegrityMonitor");
+ properties.setProperty("javax.persistence.jdbc.password",
+ PeCryptoUtils.decrypt(properties.getProperty("javax.persistence.jdbc.password", "")));
im = IntegrityMonitor.getInstance(pdpResourceName, properties);
} catch (Exception e) {
PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "Failed to create IntegrityMonitor" + e);
@@ -380,42 +385,42 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
/**
* PUT - The PAP engine sends configuration information using HTTP PUT request.
- *
+ *
* One parameter is expected:
- *
+ *
* config=[policy|pip|all]
- *
+ *
* policy - Expect a properties file that contains updated lists of the root and referenced policies that the PDP
* should be using for PEP requests.
- *
+ *
* Specifically should AT LEAST contain the following properties: xacml.rootPolicies xacml.referencedPolicies
- *
+ *
* In addition, any relevant information needed by the PDP to load or retrieve the policies to store in its cache.
*
* EXAMPLE: xacml.rootPolicies=PolicyA.1, PolicyB.1
*
* PolicyA.1.url=http://localhost:9090/PAP?id=b2d7b86d-d8f1-4adf-ba9d-b68b2a90bee1&version=1
* PolicyB.1.url=http://localhost:9090/PAP/id=be962404-27f6-41d8-9521-5acb7f0238be&version=1
- *
+ *
* xacml.referencedPolicies=RefPolicyC.1, RefPolicyD.1
*
* RefPolicyC.1.url=http://localhost:9090/PAP?id=foobar&version=1
* RefPolicyD.1.url=http://localhost:9090/PAP/id=example&version=1
- *
+ *
* pip - Expect a properties file that contain PIP engine configuration properties.
- *
+ *
* Specifically should AT LEAST the following property: xacml.pip.engines
- *
+ *
* In addition, any relevant information needed by the PDP to load and configure the PIPs.
- *
+ *
* EXAMPLE: xacml.pip.engines=foo,bar
- *
+ *
* foo.classname=com.foo foo.sample=abc foo.example=xyz ......
- *
+ *
* bar.classname=com.bar ......
- *
+ *
* all - Expect ALL new configuration properties for the PDP
- *
+ *
* @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
*/
@Override
@@ -625,13 +630,13 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
/**
* Parameters: type=hb|config|Status
- *
+ *
* 1. HeartBeat Status HeartBeat OK - All Policies are Loaded, All PIPs are Loaded LOADING_IN_PROGRESS - Currently
* loading a new policy set/pip configuration LAST_UPDATE_FAILED - Need to track the items that failed during last
* update LOAD_FAILURE - ??? Need to determine what information is sent and how 2. Configuration 3. Status return
* the StdPDPStatus object in the Response content
- *
- *
+ *
+ *
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
@Override
@@ -812,8 +817,8 @@ public class XACMLPdpServlet extends HttpServlet implements Runnable {
/**
* POST - We expect XACML requests to be posted by PEP applications. They can be in the form of XML or JSON
* according to the XACML 3.0 Specifications for both.
- *
- *
+ *
+ *
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
@Override
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java
index 425bcebf9..7704a96a6 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/api/services/PAPServices.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PDP-REST
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 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.
@@ -17,8 +17,11 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pdp.rest.api.services;
+import com.att.research.xacml.util.XACMLProperties;
+import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -33,20 +36,16 @@ import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-
import org.apache.commons.io.IOUtils;
import org.onap.policy.api.PolicyException;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.pdp.rest.config.PDPApiAuth;
import org.onap.policy.rest.XACMLRestProperties;
-import org.onap.policy.utils.CryptoUtils;
+import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.std.pap.StdPDPPolicy;
-import com.att.research.xacml.util.XACMLProperties;
-import com.fasterxml.jackson.databind.ObjectMapper;
-
public class PAPServices {
private static final String SUCCESS = "success";
private static Logger LOGGER = FlexLogger.getLogger(PAPServices.class.getName());
@@ -79,10 +78,9 @@ public class PAPServices {
private String getPAPEncoding() {
if (encoding == null) {
- final String userID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
- final String pass =
- CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
- final Base64.Encoder encoder = Base64.getEncoder();
+ String userID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
+ String pass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
+ Base64.Encoder encoder = Base64.getEncoder();
encoding = encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8));
}
return encoding;
@@ -131,7 +129,7 @@ public class PAPServices {
String fullURL = getPAP();
fullURL = checkParameter(parameters, fullURL);
final URL url = new URL(fullURL);
- LOGGER.debug("--- Sending Request to PAP : " + url.toString() + " ---");
+ LOGGER.info("--- Sending Request to PAP : " + url.toString() + " ---" + " RequestId:" + requestID);
// Open the connection
connection = (HttpURLConnection) url.openConnection();
// Setting Content-Type
@@ -149,9 +147,9 @@ public class PAPServices {
// Adding RequestID
if (requestID == null) {
requestID = UUID.randomUUID();
- LOGGER.info("No request ID provided, sending generated ID: " + requestID.toString());
+ LOGGER.debug("No request ID provided, sending generated ID: " + requestID.toString());
} else {
- LOGGER.info("Using provided request ID: " + requestID.toString());
+ LOGGER.debug("Using provided request ID: " + requestID.toString());
}
connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
if (content != null && (content instanceof InputStream)) {
@@ -168,6 +166,9 @@ public class PAPServices {
if (!isJunit) {
mapper.writeValue(connection.getOutputStream(), content);
}
+ } else {
+ LOGGER.info(XACMLErrorConstants.ERROR_DATA_ISSUE + "content is null for calling: " + url.getHost()
+ + requestID.toString());
}
// DO the connect
connection.connect();
@@ -215,10 +216,12 @@ public class PAPServices {
}
} else {
response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "connection is null";
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "connection is null - RequestId: " + requestID);
}
return response;
} else {
response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to get valid response from PAP(s) " + paps;
+ LOGGER.error("For RequestId: " + requestID + ", " + response);
return response;
}
}
@@ -228,7 +231,7 @@ public class PAPServices {
String version = null;
HttpURLConnection connection = null;
final String[] parameters = {"apiflag=version", "policyScope=" + policyScope, "filePrefix=" + filePrefix,
- "policyName=" + policyName};
+ "policyName=" + policyName};
if (paps == null || paps.isEmpty()) {
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.");
} else {
@@ -311,7 +314,8 @@ public class PAPServices {
version = "pe300";
} else {
LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE
- + "BAD REQUEST: Error occured while getting the version from the PAP. The request may be incorrect. The response code of the URL is '"
+ + "BAD REQUEST: Error occured while getting the version from the PAP. "
+ + "The request may be incorrect. The response code of the URL is '"
+ connection.getResponseCode() + "'");
}
} catch (final IOException e) {
@@ -436,14 +440,16 @@ public class PAPServices {
+ "Please create a new Dictionary Item or use the update API to modify the existing one.";
} else if ("duplicateGroup".equals(connection.getHeaderField("error"))) {
response = XACMLErrorConstants.ERROR_DATA_ISSUE
- + "Group Policy Scope List Exist Error: The Group Policy Scope List for this Dictionary Item already exist in the database. "
+ + "Group Policy Scope List Exist Error: "
+ + "The Group Policy Scope List for this Dictionary Item already exist in the database. "
+ "Duplicate Group Policy Scope Lists for multiple groupNames is not allowed. "
- + "Please review the request and verify that the groupPolicyScopeListData1 is unique compared to existing groups.";
+ + "Please review the request and "
+ + "verify that the groupPolicyScopeListData1 is unique compared to existing groups.";
} else if ("PolicyInPDP".equals(connection.getHeaderField("error"))) {
response = XACMLErrorConstants.ERROR_DATA_ISSUE
+ "Policy Exist Error: The Policy trying to be deleted is active in PDP. "
+ "Active PDP Polcies are not allowed to be deleted from PAP. "
- + "Please First remove the policy from PDP in order to successfully delete the Policy from PAP.";
+ + "Please First remove the policy from PDP in order to successfully delete the Policy from PAP";
}
LOGGER.error(response);
} else if (connection.getResponseCode() == 500 && connection.getHeaderField("error") != null) {
@@ -457,7 +463,8 @@ public class PAPServices {
response = connection.getHeaderField("message");
} else if ("unknown".equals(connection.getHeaderField("error"))) {
response = XACMLErrorConstants.ERROR_UNKNOWN
- + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.";
+ + "Failed to delete the policy for an unknown reason. "
+ + "Check the file system and other logs for further information.";
} else if ("deleteConfig".equals(connection.getHeaderField("error"))) {
response = XACMLErrorConstants.ERROR_DATA_ISSUE
+ "Cannot delete the configuration or action body file in specified location.";
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPApiAuth.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPApiAuth.java
index 246f5a26d..163298186 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPApiAuth.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPApiAuth.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PDP-REST
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 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.
@@ -17,8 +17,10 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pdp.rest.config;
+import com.att.research.xacml.util.XACMLProperties;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -33,7 +35,6 @@ import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
-
import org.onap.policy.api.PolicyEngineException;
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
@@ -41,21 +42,20 @@ import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.rest.XACMLRestProperties;
import org.onap.policy.utils.AAFPolicyClient;
import org.onap.policy.utils.AAFPolicyException;
+import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
-import com.att.research.xacml.util.XACMLProperties;
-
public class PDPApiAuth {
private static final Logger LOGGER = FlexLogger.getLogger(PDPApiAuth.class);
private static String environment = null;
private static Path clientPath = null;
- private static Map<String,ArrayList<String>> clientMap = null;
+ private static Map<String, ArrayList<String>> clientMap = null;
private static Long oldModified = null;
private static AAFPolicyClient aafClient = null;
- private PDPApiAuth(){
+ private PDPApiAuth() {
// Private Constructor
}
@@ -65,7 +65,7 @@ public class PDPApiAuth {
public static void setProperty() {
environment = XACMLProperties.getProperty("ENVIRONMENT", "DEVL");
String clientFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PEP_IDFILE);
- if(clientFile!=null){
+ if (clientFile != null) {
clientPath = Paths.get(clientFile);
}
try {
@@ -76,84 +76,84 @@ public class PDPApiAuth {
}
/*
- * Return Environment value of the PDP servlet.
+ * Return Environment value of the PDP servlet.
*/
public static String getEnvironment() {
- if(environment==null){
+ if (environment == null) {
setProperty();
}
return environment;
}
/*
- * Security check for authentication and authorizations.
+ * Security check for authentication and authorizations.
*/
- public static boolean checkPermissions(String clientEncoding, String requestID,
- String resource) {
- try{
+ public static boolean checkPermissions(String clientEncoding, String requestID, String resource) {
+ try {
String[] userNamePass = PolicyUtils.decodeBasicEncoding(clientEncoding);
- if(userNamePass==null || userNamePass.length==0){
+ if (userNamePass == null || userNamePass.length == 0) {
String usernameAndPassword = null;
byte[] decodedBytes = Base64.getDecoder().decode(clientEncoding);
usernameAndPassword = new String(decodedBytes, "UTF-8");
StringTokenizer tokenizer = new StringTokenizer(usernameAndPassword, ":");
String username = tokenizer.nextToken();
String password = tokenizer.nextToken();
- userNamePass= new String[]{username, password};
+ userNamePass = new String[] {username, password};
}
LOGGER.info("User " + userNamePass[0] + " is Accessing Policy Engine API.");
Boolean result = false;
- // Check Backward Compatibility.
- try{
+ // Check Backward Compatibility.
+ try {
/*
- * If AAF is NOT enabled in the properties we will allow the user to
- * continue to use the client.properties file to authenticate.
- * Note: Disabling AAF is for testing purposes and not intended for production.
+ * If AAF is NOT enabled in the properties we will allow the user to continue to use the
+ * client.properties file to authenticate. Note: Disabling AAF is for testing purposes and not intended
+ * for production.
*/
if ("false".equals(XACMLProperties.getProperty("enable_aaf"))) {
result = clientAuth(userNamePass);
}
- }catch(Exception e){
+ } catch (Exception e) {
LOGGER.error(MessageCodes.ERROR_PERMISSIONS, e);
}
- if(!result){
+ if (!result) {
String aafPolicyNameSpace = XACMLProperties.getProperty("policy.aaf.namespace");
String aafResource = XACMLProperties.getProperty("policy.aaf.root.permission");
String type = null;
- if(!userNamePass[0].contains("@") && aafPolicyNameSpace!= null){
+ if (!userNamePass[0].contains("@") && aafPolicyNameSpace != null) {
userNamePass[0] = userNamePass[0] + "@" + reverseNamespace(aafPolicyNameSpace);
- }else{
+ } else {
LOGGER.info("No AAF NameSpace specified in properties");
}
- if(aafResource != null){
+ if (aafResource != null) {
type = aafResource + "." + resource;
- }else{
+ } else {
LOGGER.warn("No AAF Resource specified in properties");
return false;
}
- LOGGER.info("Contacting AAF in : " + environment);
+ LOGGER.info("Contacting AAF in : " + environment);
result = aafClient.checkAuthPerm(userNamePass[0], userNamePass[1], type, environment, "*");
}
return result;
- }catch(Exception e){
+ } catch (Exception e) {
LOGGER.error(MessageCodes.ERROR_PERMISSIONS, e);
return false;
}
}
- private static Boolean clientAuth(String[] userNamePass){
- if(clientPath==null){
+ private static Boolean clientAuth(String[] userNamePass) {
+ if (clientPath == null) {
setProperty();
}
if (!clientPath.toFile().exists()) {
return false;
- }else if(clientPath.toString().endsWith(".properties")) {
+ } else if (clientPath.toString().endsWith(".properties")) {
try {
readProps(clientPath);
- if (clientMap.containsKey(userNamePass[0]) && clientMap.get(userNamePass[0]).get(0).equals(userNamePass[1])) {
+ if (clientMap.containsKey(userNamePass[0])
+ && clientMap.get(userNamePass[0]).get(0).equals(userNamePass[1])) {
return true;
}
- }catch(PolicyEngineException e){
+ } catch (PolicyEngineException e) {
LOGGER.error(MessageCodes.ERROR_PERMISSIONS, e);
return false;
}
@@ -163,12 +163,12 @@ public class PDPApiAuth {
private static String reverseNamespace(String namespace) {
final List<String> components = Arrays.asList(namespace.split("\\."));
- Collections.reverse(components);
+ Collections.reverse(components);
return String.join(".", components);
}
- private static Map<String, ArrayList<String>> readProps(Path clientPath) throws PolicyEngineException{
- if(oldModified!=null){
+ private static Map<String, ArrayList<String>> readProps(Path clientPath) throws PolicyEngineException {
+ if (oldModified != null) {
Long newModified = clientPath.toFile().lastModified();
if (newModified == oldModified) {
return clientMap;
@@ -180,27 +180,31 @@ public class PDPApiAuth {
in = new FileInputStream(clientPath.toFile());
clientProp.load(in);
} catch (IOException e) {
- LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR , e);
- throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Load the Properties file", e);
+ LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR, e);
+ throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Load the Properties file",
+ e);
}
// Read the Properties and Load the Clients and their scopes.
clientMap = new HashMap<>();
- //
+ //
for (Object propKey : clientProp.keySet()) {
- String clientID = (String)propKey;
+ String clientID = (String) propKey;
String clientValue = clientProp.getProperty(clientID);
if (clientValue != null && clientValue.contains(",")) {
ArrayList<String> clientValues = new ArrayList<>(Arrays.asList(clientValue.split("\\s*,\\s*")));
- if(clientValues.get(0)!=null || clientValues.get(1)!=null || clientValues.get(0).isEmpty() || clientValues.get(1).isEmpty()){
+ if (clientValues.get(0) != null || clientValues.get(1) != null || clientValues.get(0).isEmpty()
+ || clientValues.get(1).isEmpty()) {
+ clientValues.set(0, PeCryptoUtils.decrypt(clientValues.get(0)));
clientMap.put(clientID, clientValues);
}
}
}
if (clientMap.isEmpty()) {
- LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS + "No Clients ID , Client Key and Scopes are available. Cannot serve any Clients !!");
+ LOGGER.debug(XACMLErrorConstants.ERROR_PERMISSIONS
+ + "No Clients ID , Client Key and Scopes are available. Cannot serve any Clients !!");
throw new PolicyEngineException("Empty Client file");
}
oldModified = clientPath.toFile().lastModified();
return clientMap;
}
-} \ No newline at end of file
+}
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestConfig.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestConfig.java
index b563c6cce..9c3213bef 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestConfig.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/config/PDPRestConfig.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PDP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017,2019 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.
@@ -17,23 +17,21 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pdp.rest.config;
import java.io.FileInputStream;
-import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
-
import javax.annotation.PostConstruct;
import javax.servlet.MultipartConfigElement;
import javax.sql.DataSource;
-
import org.apache.tomcat.dbcp.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.onap.policy.common.logging.eelf.PolicyLogger;
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
-import org.onap.policy.pdp.rest.api.controller.PolicyEngineServices;
+import org.onap.policy.utils.PeCryptoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
@@ -43,7 +41,6 @@ import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
-
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
@@ -55,124 +52,118 @@ import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableWebMvc
@EnableSwagger2
-@ComponentScan(basePackages = { "org.onap.*", "com.*" })
-public class PDPRestConfig extends WebMvcConfigurerAdapter{
-
- private static final Logger LOGGER = FlexLogger.getLogger(PDPRestConfig.class);
-
- private static String dbDriver = null;
- private static String dbUrl = null;
- private static String dbUserName = null;
- private static String dbPassword = null;
-
- @PostConstruct
- public void init(){
- Properties prop = new Properties();
- try (InputStream input = new FileInputStream("xacml.pdp.properties")){
- // load a properties file
- prop.load(input);
- setDbDriver(prop.getProperty("javax.persistence.jdbc.driver"));
- setDbUrl(prop.getProperty("javax.persistence.jdbc.url"));
- setDbUserName(prop.getProperty("javax.persistence.jdbc.user"));
- setDbPassword(prop.getProperty("javax.persistence.jdbc.password"));
- }catch(Exception e){
- LOGGER.error("Exception Occured while loading properties file"+e);
- }
- }
-
- @Override
+@ComponentScan(basePackages = {"org.onap.*", "com.*"})
+public class PDPRestConfig extends WebMvcConfigurerAdapter {
+
+ private static final Logger LOGGER = FlexLogger.getLogger(PDPRestConfig.class);
+
+ private static String dbDriver = null;
+ private static String dbUrl = null;
+ private static String dbUserName = null;
+ private static String dbPassword = null;
+
+ @PostConstruct
+ public void init() {
+ Properties prop = new Properties();
+ try (InputStream input = new FileInputStream("xacml.pdp.properties")) {
+ // load a properties file
+ prop.load(input);
+ setDbDriver(prop.getProperty("javax.persistence.jdbc.driver"));
+ setDbUrl(prop.getProperty("javax.persistence.jdbc.url"));
+ setDbUserName(prop.getProperty("javax.persistence.jdbc.user"));
+ PeCryptoUtils.initAesKey(prop.getProperty("org.onap.policy.encryption.aes.key"));
+ setDbPassword(PeCryptoUtils.decrypt(prop.getProperty("javax.persistence.jdbc.password")));
+ } catch (Exception e) {
+ LOGGER.error("Exception Occured while loading properties file" + e);
+ }
+ }
+
+ @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
-
- private ApiInfo apiInfo(){
- return new ApiInfoBuilder()
- .title("Policy Engine REST API")
- .description("This API helps to make queries against Policy Engine")
- .version("3.0")
- .build();
+
+ private ApiInfo apiInfo() {
+ return new ApiInfoBuilder().title("Policy Engine REST API")
+ .description("This API helps to make queries against Policy Engine").version("3.0").build();
}
-
+
@Bean
- public Docket policyAPI(){
+ public Docket policyAPI() {
PolicyLogger.info("Setting up Swagger... ");
- return new Docket(DocumentationType.SWAGGER_2)
- .select()
- .apis(RequestHandlerSelectors.basePackage("org.onap.policy.pdp.rest.api"))
- .paths(PathSelectors.any())
- .build()
- .apiInfo(apiInfo());
- }
-
- @Bean(name = "dataSource")
- public DataSource getDataSource() {
- BasicDataSource dataSource = new BasicDataSource();
- dataSource.setDriverClassName(PDPRestConfig.getDbDriver());
- dataSource.setUrl(PDPRestConfig.getDbUrl());
- dataSource.setUsername(PDPRestConfig.getDbUserName());
- dataSource.setPassword(PDPRestConfig.getDbPassword());
- return dataSource;
- }
-
- @Autowired
- @Bean(name = "sessionFactory")
- public SessionFactory getSessionFactory(DataSource dataSource) {
- LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
- sessionBuilder.scanPackages("org.onap.*", "com.*");
- sessionBuilder.addProperties(getHibernateProperties());
- return sessionBuilder.buildSessionFactory();
- }
-
- private Properties getHibernateProperties() {
- Properties properties = new Properties();
- properties.put("hibernate.show_sql", "true");
- properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
- return properties;
- }
-
- @Autowired
- @Bean(name = "transactionManager")
- public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
- return new HibernateTransactionManager(sessionFactory);
- }
-
+ return new Docket(DocumentationType.SWAGGER_2).select()
+ .apis(RequestHandlerSelectors.basePackage("org.onap.policy.pdp.rest.api")).paths(PathSelectors.any())
+ .build().apiInfo(apiInfo());
+ }
+
+ @Bean(name = "dataSource")
+ public DataSource getDataSource() {
+ BasicDataSource dataSource = new BasicDataSource();
+ dataSource.setDriverClassName(PDPRestConfig.getDbDriver());
+ dataSource.setUrl(PDPRestConfig.getDbUrl());
+ dataSource.setUsername(PDPRestConfig.getDbUserName());
+ dataSource.setPassword(PDPRestConfig.getDbPassword());
+ return dataSource;
+ }
+
+ @Autowired
+ @Bean(name = "sessionFactory")
+ public SessionFactory getSessionFactory(DataSource dataSource) {
+ LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
+ sessionBuilder.scanPackages("org.onap.*", "com.*");
+ sessionBuilder.addProperties(getHibernateProperties());
+ return sessionBuilder.buildSessionFactory();
+ }
+
+ private Properties getHibernateProperties() {
+ Properties properties = new Properties();
+ properties.put("hibernate.show_sql", "true");
+ properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
+ return properties;
+ }
+
+ @Autowired
+ @Bean(name = "transactionManager")
+ public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
+ return new HibernateTransactionManager(sessionFactory);
+ }
+
@Bean
- public MultipartConfigElement multipartConfigElement(){
+ public MultipartConfigElement multipartConfigElement() {
String location = System.getProperty("java.io.tmpdir");
- MultipartConfigElement mp = new MultipartConfigElement(location);
- return mp;
+ return new MultipartConfigElement(location);
}
- public static String getDbDriver() {
- return dbDriver;
- }
+ public static String getDbDriver() {
+ return dbDriver;
+ }
- public static void setDbDriver(String dbDriver) {
- PDPRestConfig.dbDriver = dbDriver;
- }
+ public static void setDbDriver(String dbDriver) {
+ PDPRestConfig.dbDriver = dbDriver;
+ }
- public static String getDbUrl() {
- return dbUrl;
- }
+ public static String getDbUrl() {
+ return dbUrl;
+ }
- public static void setDbUrl(String dbUrl) {
- PDPRestConfig.dbUrl = dbUrl;
- }
+ public static void setDbUrl(String dbUrl) {
+ PDPRestConfig.dbUrl = dbUrl;
+ }
- public static String getDbUserName() {
- return dbUserName;
- }
+ public static String getDbUserName() {
+ return dbUserName;
+ }
- public static void setDbUserName(String dbUserName) {
- PDPRestConfig.dbUserName = dbUserName;
- }
+ public static void setDbUserName(String dbUserName) {
+ PDPRestConfig.dbUserName = dbUserName;
+ }
- public static String getDbPassword() {
- return dbPassword;
- }
+ public static String getDbPassword() {
+ return dbPassword;
+ }
- public static void setDbPassword(String dbPassword) {
- PDPRestConfig.dbPassword = dbPassword;
- }
+ public static void setDbPassword(String dbPassword) {
+ PDPRestConfig.dbPassword = dbPassword;
+ }
}
diff --git a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/AuthenticationService.java b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/AuthenticationService.java
index 0d066c59c..b1b092431 100644
--- a/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/AuthenticationService.java
+++ b/ONAP-PDP-REST/src/main/java/org/onap/policy/pdp/rest/restAuth/AuthenticationService.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-PDP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017,2019 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.
@@ -20,25 +20,23 @@
package org.onap.policy.pdp.rest.restAuth;
+import com.att.research.xacml.util.XACMLProperties;
import java.util.Base64;
import java.util.StringTokenizer;
-
-import org.onap.policy.rest.XACMLRestProperties;
-
-import com.att.research.xacml.util.XACMLProperties;
-
import org.onap.policy.common.logging.eelf.MessageCodes;
import org.onap.policy.common.logging.eelf.PolicyLogger;
+import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.utils.PeCryptoUtils;
public class AuthenticationService {
private String pdpID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_USERID);
- private String pdpPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_PASS);
-
+ private String pdpPass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_PASS));
+
public boolean authenticate(String authCredentials) {
if (null == authCredentials)
return false;
- // header value format will be "Basic encodedstring" for Basic authentication.
+ // header value format will be "Basic encodedstring" for Basic authentication.
final String encodedUserPassword = authCredentials.replaceFirst("Basic" + " ", "");
String usernameAndPassword = null;
try {
@@ -58,5 +56,5 @@ public class AuthenticationService {
return false;
}
}
-
+
}
diff --git a/ONAP-PDP-REST/xacml.pdp.properties b/ONAP-PDP-REST/xacml.pdp.properties
index 90e0f5c3c..51feec6f5 100644
--- a/ONAP-PDP-REST/xacml.pdp.properties
+++ b/ONAP-PDP-REST/xacml.pdp.properties
@@ -199,3 +199,6 @@ msToscaModel.home=/home/users/PolicyEngine/webapps/ConfigPAP/
# Decision Response settings.
# can be either PERMIT or DENY.
decision.indeterminate.response=PERMIT
+
+# AES key for password encryption in config files
+#org.onap.policy.encryption.aes.key=12345678901234567890123456789012
diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRestProperties.java b/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRestProperties.java
index edb7e830f..f7f887cef 100644
--- a/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRestProperties.java
+++ b/ONAP-REST/src/main/java/org/onap/policy/rest/XACMLRestProperties.java
@@ -2,14 +2,14 @@
* ============LICENSE_START=======================================================
* ONAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 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.
@@ -25,7 +25,7 @@ import com.att.research.xacml.util.XACMLProperties;
/**
* These are XACML Properties that are relevant to the RESTful API interface for
* the PDP, PAP and AC interfaces.
- *
+ *
*
*/
public class XACMLRestProperties extends XACMLProperties {
@@ -456,6 +456,11 @@ public class XACMLRestProperties extends XACMLProperties {
* */
public static final String PROP_PAP_INCOMINGNOTIFICATION_TRIES = "xacml.rest.pap.incomingnotification.tries";
+ /*
+ * The encryption key
+ */
+ public static final String PROP_AES_KEY = "org.onap.policy.encryption.aes.key";
+
// Static class, hide constructor
private XACMLRestProperties() {
diff --git a/ONAP-SDK-APP/src/main/java/org/onap/portalapp/conf/ExternalAppConfig.java b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/conf/ExternalAppConfig.java
index 20601724c..7f4f62855 100644
--- a/ONAP-SDK-APP/src/main/java/org/onap/portalapp/conf/ExternalAppConfig.java
+++ b/ONAP-SDK-APP/src/main/java/org/onap/portalapp/conf/ExternalAppConfig.java
@@ -2,7 +2,7 @@
* ================================================================================
* ONAP Portal SDK
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property
+ * Copyright (C) 2017-2019 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.
@@ -17,11 +17,12 @@
* limitations under the License.
* ================================================================================
*/
+
package org.onap.portalapp.conf;
import java.util.ArrayList;
import java.util.List;
-
+import org.onap.policy.utils.PeCryptoUtils;
import org.onap.portalapp.login.LoginStrategyImpl;
import org.onap.portalapp.scheduler.RegistryAdapter;
import org.onap.portalsdk.core.auth.LoginStrategy;
@@ -48,125 +49,125 @@ import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
/**
- * ONAP Portal SDK sample application. Extends core AppConfig class to
- * reuse interceptors, view resolvers and other features defined there.
+ * ONAP Portal SDK sample application. Extends core AppConfig class to reuse interceptors, view resolvers and other
+ * features defined there.
*/
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "org.onap")
-@PropertySource(value = { "${container.classpath:}/WEB-INF/conf/app/test.properties" }, ignoreResourceNotFound = true)
+@PropertySource(value = {"${container.classpath:}/WEB-INF/conf/app/test.properties"}, ignoreResourceNotFound = true)
@Profile("src")
@EnableAsync
@EnableScheduling
public class ExternalAppConfig extends AppConfig implements Configurable {
- EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppConfig.class);
-
- private RegistryAdapter schedulerRegistryAdapter;
+ EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAppConfig.class);
+
+ private RegistryAdapter schedulerRegistryAdapter;
- @Configuration
- @Import(SystemProperties.class)
- static class InnerConfiguration {
- }
+ @Configuration
+ @Import(SystemProperties.class)
+ static class InnerConfiguration {
+ }
- /**
- * @see org.onap.portalsdk.core.conf.AppConfig#viewResolver()
- */
- @Override
- public ViewResolver viewResolver() {
- return super.viewResolver();
- }
+ /**
+ * @see org.onap.portalsdk.core.conf.AppConfig#viewResolver()
+ */
+ @Override
+ public ViewResolver viewResolver() {
+ return super.viewResolver();
+ }
- /**
- * @see org.onap.portalsdk.core.conf.AppConfig#addResourceHandlers(ResourceHandlerRegistry)
- *
- * @param registry
- */
- @Override
- public void addResourceHandlers(ResourceHandlerRegistry registry) {
- super.addResourceHandlers(registry);
- }
+ /**
+ * @see org.onap.portalsdk.core.conf.AppConfig#addResourceHandlers(ResourceHandlerRegistry)
+ *
+ * @param registry
+ */
+ @Override
+ public void addResourceHandlers(ResourceHandlerRegistry registry) {
+ super.addResourceHandlers(registry);
+ }
- /**
- * @see org.onap.portalsdk.core.conf.AppConfig#dataAccessService()
- */
- @Override
- public DataAccessService dataAccessService() {
- // Echo the JDBC URL to assist developers when starting the app.
- System.out.println("ExternalAppConfig: " + SystemProperties.DB_CONNECTIONURL + " is "
- + SystemProperties.getProperty(SystemProperties.DB_CONNECTIONURL));
- return super.dataAccessService();
- }
+ /**
+ * @see org.onap.portalsdk.core.conf.AppConfig#dataAccessService()
+ */
+ @Override
+ public DataAccessService dataAccessService() {
+ // Echo the JDBC URL to assist developers when starting the app.
+ System.out.println("ExternalAppConfig: " + SystemProperties.DB_CONNECTIONURL + " is "
+ + SystemProperties.getProperty(SystemProperties.DB_CONNECTIONURL));
+ System.setProperty(SystemProperties.DB_PASSWORD,
+ PeCryptoUtils.decrypt(SystemProperties.getProperty(SystemProperties.DB_PASSWORD)));
+ return super.dataAccessService();
+ }
- /**
- * Creates a new list with a single entry that is the external app
- * definitions.xml path.
- *
- * @return List of String, size 1
- */
- @Override
- public List<String> addTileDefinitions() {
- List<String> definitions = new ArrayList<>();
- definitions.add("/WEB-INF/defs/definitions.xml");
- return definitions;
- }
+ /**
+ * Creates a new list with a single entry that is the external app definitions.xml path.
+ *
+ * @return List of String, size 1
+ */
+ @Override
+ public List<String> addTileDefinitions() {
+ List<String> definitions = new ArrayList<>();
+ definitions.add("/WEB-INF/defs/definitions.xml");
+ return definitions;
+ }
- /**
- * Adds request interceptors to the specified registry by calling
- * {@link AppConfig#addInterceptors(InterceptorRegistry)}, but excludes
- * certain paths from the session timeout interceptor.
- */
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- super.setExcludeUrlPathsForSessionTimeout("/login_external", "*/login_external.htm", "login", "/login.htm",
- "/api*", "/single_signon.htm", "/single_signon");
- super.addInterceptors(registry);
- }
+ /**
+ * Adds request interceptors to the specified registry by calling
+ * {@link AppConfig#addInterceptors(InterceptorRegistry)}, but excludes certain paths from the session timeout
+ * interceptor.
+ */
+ @Override
+ public void addInterceptors(InterceptorRegistry registry) {
+ super.setExcludeUrlPathsForSessionTimeout("/login_external", "*/login_external.htm", "login", "/login.htm",
+ "/api*", "/single_signon.htm", "/single_signon");
+ super.addInterceptors(registry);
+ }
- /**
- * Creates and returns a new instance of a {@link CacheManager} class.
- *
- * @return New instance of {@link CacheManager}
- */
- @Bean
- public AbstractCacheManager cacheManager() {
- return new CacheManager();
- }
+ /**
+ * Creates and returns a new instance of a {@link CacheManager} class.
+ *
+ * @return New instance of {@link CacheManager}
+ */
+ @Bean
+ public AbstractCacheManager cacheManager() {
+ return new CacheManager();
+ }
- /**
- * Creates and returns a new instance of a {@link SchedulerFactoryBean} and
- * populates it with triggers.
- *
- * @return New instance of {@link SchedulerFactoryBean}
- * @throws Exception
- */
- // @Bean // ANNOTATION COMMENTED OUT
- // APPLICATIONS REQUIRING QUARTZ SHOULD RESTORE ANNOTATION
- public SchedulerFactoryBean schedulerFactoryBean(){
- SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
- scheduler.setTriggers(schedulerRegistryAdapter.getTriggers());
- scheduler.setConfigLocation(appApplicationContext.getResource("WEB-INF/conf/quartz.properties"));
- try {
- scheduler.setDataSource(dataSource());
- } catch (Exception e) {
- logger.error("Exception occured While Setting DataSource for schedulerfactorybean"+e);
- return null;
- }
- return scheduler;
- }
+ /**
+ * Creates and returns a new instance of a {@link SchedulerFactoryBean} and populates it with triggers.
+ *
+ * @return New instance of {@link SchedulerFactoryBean}
+ * @throws Exception
+ */
+ // @Bean // ANNOTATION COMMENTED OUT
+ // APPLICATIONS REQUIRING QUARTZ SHOULD RESTORE ANNOTATION
+ public SchedulerFactoryBean schedulerFactoryBean() {
+ SchedulerFactoryBean scheduler = new SchedulerFactoryBean();
+ scheduler.setTriggers(schedulerRegistryAdapter.getTriggers());
+ scheduler.setConfigLocation(appApplicationContext.getResource("WEB-INF/conf/quartz.properties"));
+ try {
+ scheduler.setDataSource(dataSource());
+ } catch (Exception e) {
+ logger.error("Exception occured While Setting DataSource for schedulerfactorybean" + e);
+ return null;
+ }
+ return scheduler;
+ }
- /**
- * Sets the scheduler registry adapter.
- *
- * @param schedulerRegistryAdapter
- */
- @Autowired
- public void setSchedulerRegistryAdapter(final RegistryAdapter schedulerRegistryAdapter) {
- this.schedulerRegistryAdapter = schedulerRegistryAdapter;
- }
+ /**
+ * Sets the scheduler registry adapter.
+ *
+ * @param schedulerRegistryAdapter
+ */
+ @Autowired
+ public void setSchedulerRegistryAdapter(final RegistryAdapter schedulerRegistryAdapter) {
+ this.schedulerRegistryAdapter = schedulerRegistryAdapter;
+ }
- @Bean
- public LoginStrategy loginStrategy() {
- return new LoginStrategyImpl();
- }
+ @Bean
+ public LoginStrategy loginStrategy() {
+ return new LoginStrategyImpl();
+ }
}
diff --git a/ONAP-SDK-APP/xacml.admin.properties b/ONAP-SDK-APP/xacml.admin.properties
index 8e6852805..0a7f3882c 100644
--- a/ONAP-SDK-APP/xacml.admin.properties
+++ b/ONAP-SDK-APP/xacml.admin.properties
@@ -2,7 +2,7 @@
# ============LICENSE_START=======================================================
# ONAP Policy Engine
# ================================================================================
-# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+# Copyright (C) 2017-2019 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.
@@ -205,3 +205,6 @@ xacml.policy.msPolicyName=http://org.onap.policy
#Size limit (in bytes) for file uploads
file.size.limit=30000000
+
+# AES key for password encryption in config files
+#org.onap.policy.encryption.aes.key=12345678901234567890123456789012 \ No newline at end of file
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java
index f91815992..26b9798ac 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
@@ -23,6 +23,7 @@
package org.onap.policy.admin;
+import com.att.research.xacml.util.XACMLProperties;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -38,14 +39,12 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
-
import org.onap.policy.common.logging.flexlogger.FlexLogger;
import org.onap.policy.common.logging.flexlogger.Logger;
import org.onap.policy.rest.XACMLRestProperties;
+import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
-import com.att.research.xacml.util.XACMLProperties;
-
/**
* What is not good about this class is that once a value has been set for pdpProperties path you cannot change it. That
* may be ok for a highly controlled production environment in which nothing changes, but not a very good
@@ -170,7 +169,7 @@ public class CheckPDP {
if (pdpValues.size() == 3) {
// 1:2 will be UserID:Password
String userID = pdpValues.get(1);
- String pass = pdpValues.get(2);
+ String pass = PeCryptoUtils.decrypt(pdpValues.get(2));
Base64.Encoder encoder = Base64.getEncoder();
// 0 - PDPURL
pdpMap.put(pdpValues.get(0),
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
index d289feaaf..513fc5795 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java
@@ -22,6 +22,9 @@
package org.onap.policy.admin;
+import com.att.research.xacml.util.XACMLProperties;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
@@ -37,8 +40,14 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
-import java.util.*;
-
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonReader;
@@ -50,7 +59,6 @@ import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
@@ -74,15 +82,13 @@ import org.onap.policy.rest.jpa.PolicyEditorScopes;
import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.rest.jpa.PolicyVersion;
import org.onap.policy.rest.jpa.UserInfo;
+import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.utils.UserUtils.Pair;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.util.XACMLPolicyScanner;
import org.onap.portalsdk.core.web.support.UserUtils;
-import com.att.research.xacml.util.XACMLProperties;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
@WebServlet(value = "/fm/*", loadOnStartup = 1, initParams = {
@WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.admin.properties", description = "The location of the properties file holding configuration information.") })
@@ -168,6 +174,8 @@ public class PolicyManagerServlet extends HttpServlet {
// Common initialization
//
XACMLRest.xacmlInit(servletConfig);
+ // init aes key from prop or env
+ PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
//
// Initialize ClosedLoop JSON
//
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java
index 6935c7203..03dbccfd9 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java
@@ -2,16 +2,16 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
* 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.
@@ -19,8 +19,14 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.admin;
+import com.att.research.xacml.util.XACMLProperties;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
@@ -33,10 +39,8 @@ import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
-
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@@ -53,6 +57,7 @@ import org.onap.policy.rest.XACMLRestProperties;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
import org.onap.policy.rest.dao.CommonClassDao;
import org.onap.policy.rest.jpa.PolicyVersion;
+import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
@@ -69,16 +74,10 @@ import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
-import org.onap.policy.utils.CryptoUtils;
-import com.att.research.xacml.util.XACMLProperties;
-import com.fasterxml.jackson.databind.DeserializationFeature;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.SerializationFeature;
@RestController
@RequestMapping("/")
-public class PolicyRestController extends RestrictedBaseController{
+public class PolicyRestController extends RestrictedBaseController {
private static final Logger policyLogger = FlexLogger.getLogger(PolicyRestController.class);
@@ -105,12 +104,12 @@ public class PolicyRestController extends RestrictedBaseController{
private static CommonClassDao commonClassDao;
- public PolicyRestController(){
- //default constructor
+ public PolicyRestController() {
+ // default constructor
}
@Autowired
- private PolicyRestController(CommonClassDao commonClassDao){
+ private PolicyRestController(CommonClassDao commonClassDao) {
PolicyRestController.commonClassDao = commonClassDao;
}
@@ -124,30 +123,30 @@ public class PolicyRestController extends RestrictedBaseController{
- @RequestMapping(value={"/policycreation/save_policy"}, method={RequestMethod.POST})
+ @RequestMapping(value = {"/policycreation/save_policy"}, method = {RequestMethod.POST})
public void policyCreationController(HttpServletRequest request, HttpServletResponse response) {
String userId = UserUtils.getUserSession(request).getOrgUserId();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
- try{
+ try {
updateAndSendToPAP(request, response, userId, mapper);
- }catch(Exception e){
- policyLogger.error("Exception Occured while saving policy" , e);
+ } catch (Exception e) {
+ policyLogger.error("Exception Occured while saving policy", e);
}
}
- private void updateAndSendToPAP(HttpServletRequest request, HttpServletResponse response, String userId, ObjectMapper mapper) throws IOException {
+ private void updateAndSendToPAP(HttpServletRequest request, HttpServletResponse response, String userId,
+ ObjectMapper mapper) throws IOException {
JsonNode root = mapper.readTree(request.getReader());
policyLogger.info(
- "****************************************Logging UserID while Create/Update Policy**************************************************");
- policyLogger.info(
- USER_ID + userId + "Policy Data Object: " + root.get(PolicyController.getPolicydata()).get("policy")
- .toString());
+ "****************************************Logging UserID while Create/Update Policy**************************************************");
+ policyLogger.info(USER_ID + userId + "Policy Data Object: "
+ + root.get(PolicyController.getPolicydata()).get("policy").toString());
policyLogger.info(
- "***********************************************************************************************************************************");
+ "***********************************************************************************************************************************");
- PolicyRestAdapter policyData = mapper
- .readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
+ PolicyRestAdapter policyData = mapper.readValue(
+ root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
modifyPolicyData(root, policyData);
if (policyData.getConfigPolicyType() != null) {
@@ -178,8 +177,8 @@ public class PolicyRestController extends RestrictedBaseController{
String mode = "EditPolicy";
String watchPolicyName = policyName.replace(XML, "");
String version = watchPolicyName.substring(watchPolicyName.lastIndexOf('.') + 1);
- watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.'))
- .replace(".", File.separator);
+ watchPolicyName =
+ watchPolicyName.substring(0, watchPolicyName.lastIndexOf('.')).replace(".", File.separator);
String policyVersionName = watchPolicyName.replace(".", File.separator);
watchPolicyName = watchPolicyName + "." + version + XML;
PolicyVersion entityItem = new PolicyVersion();
@@ -203,24 +202,24 @@ public class PolicyRestController extends RestrictedBaseController{
}
private void modifyPolicyData(JsonNode root, PolicyRestAdapter policyData) {
- if(FILE.equals(root.get(PolicyController.getPolicydata()).get(MODEL).get(TYPE).toString().replace("\"", ""))){
+ if (FILE.equals(root.get(PolicyController.getPolicydata()).get(MODEL).get(TYPE).toString().replace("\"", ""))) {
policyData.setEditPolicy(true);
}
- if(root.get(PolicyController.getPolicydata()).get(MODEL).get(PATH).size() != 0){
+ if (root.get(PolicyController.getPolicydata()).get(MODEL).get(PATH).size() != 0) {
String dirName = "";
- for(int i = 0; i < root.get(PolicyController.getPolicydata()).get(MODEL).get(PATH).size(); i++){
- dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(
- MODEL).get(PATH).get(i).toString().replace("\"", "") + File.separator;
+ for (int i = 0; i < root.get(PolicyController.getPolicydata()).get(MODEL).get(PATH).size(); i++) {
+ dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(MODEL).get(PATH)
+ .get(i).toString().replace("\"", "") + File.separator;
}
- if(policyData.isEditPolicy()){
+ if (policyData.isEditPolicy()) {
policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
- }else{
- policyData.setDomainDir(dirName + root.get(PolicyController.getPolicydata()).get(
- MODEL).get(NAME).toString().replace("\"", ""));
+ } else {
+ policyData.setDomainDir(dirName
+ + root.get(PolicyController.getPolicydata()).get(MODEL).get(NAME).toString().replace("\"", ""));
}
- }else{
+ } else {
String domain = root.get(PolicyController.getPolicydata()).get(MODEL).get(NAME).toString();
- if(domain.contains("/")){
+ if (domain.contains("/")) {
domain = domain.substring(0, domain.lastIndexOf('/')).replace("/", File.separator);
}
domain = domain.replace("\"", "");
@@ -229,13 +228,12 @@ public class PolicyRestController extends RestrictedBaseController{
}
- private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method){
+ private ResponseEntity<?> sendToPAP(String body, String requestURI, HttpMethod method) {
String papUrl = PolicyController.getPapUrl();
String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
- String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
-
+ String papPass = PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
Base64.Encoder encoder = Base64.getEncoder();
- String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
+ String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
headers.set(AUTHORIZATION, BASIC + encoding);
headers.set(CONTENT_TYPE, PolicyController.getContenttype());
@@ -245,46 +243,51 @@ public class PolicyRestController extends RestrictedBaseController{
ResponseEntity<?> result = null;
HttpClientErrorException exception = null;
String uri = requestURI;
- if(uri.startsWith("/")){
- uri = uri.substring(uri.indexOf('/')+1);
+ if (uri.startsWith("/")) {
+ uri = uri.substring(uri.indexOf('/') + 1);
}
uri = "onap" + uri.substring(uri.indexOf('/'));
- try{
+ try {
result = restTemplate.exchange(papUrl + uri, method, requestEntity, String.class);
- }catch(Exception e){
+ } catch (Exception e) {
policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e);
exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
- if("409 Conflict".equals(e.getMessage())){
+ if ("409 Conflict".equals(e.getMessage())) {
return ResponseEntity.ok(HttpServletResponse.SC_CONFLICT);
}
}
- if(exception != null && exception.getStatusCode()!=null){
- if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){
- String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ;
+ if (exception != null && exception.getStatusCode() != null) {
+ if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {
+ String message = XACMLErrorConstants.ERROR_PERMISSIONS + ":" + exception.getStatusCode() + ":"
+ + "ERROR_AUTH_GET_PERM";
policyLogger.error(message);
}
- if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){
- String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
+ if (exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
+ String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":" + exception.getStatusCode() + ":"
+ + exception.getResponseBodyAsString();
policyLogger.error(message);
}
- if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){
- String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
+ if (exception.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
+ String message =
+ XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception;
policyLogger.error(message);
}
- String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString();
+ String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + exception.getStatusCode() + ":"
+ + exception.getResponseBodyAsString();
policyLogger.error(message);
}
return result;
}
- private String callPAP(HttpServletRequest request , String method, String uriValue){
+ private String callPAP(HttpServletRequest request, String method, String uriValue) {
String uri = uriValue;
String papUrl = PolicyController.getPapUrl();
String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
- String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
+ PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
+ String papPass = PeCryptoUtils.decrypt((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)));
Base64.Encoder encoder = Base64.getEncoder();
- String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8));
+ String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
headers.set(AUTHORIZATION, BASIC + encoding);
headers.set(CONTENT_TYPE, PolicyController.getContenttype());
@@ -294,21 +297,21 @@ public class PolicyRestController extends RestrictedBaseController{
List<FileItem> items;
FileItem item = null;
File file = null;
- if(uri.contains(IMPORT_DICTIONARY)){
+ if (uri.contains(IMPORT_DICTIONARY)) {
try {
items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
item = items.get(0);
file = new File(item.getName());
String newFile = file.toString();
- uri = uri +"&dictionaryName="+newFile;
+ uri = uri + "&dictionaryName=" + newFile;
} catch (Exception e2) {
- policyLogger.error("Exception Occured while calling PAP with import dictionary request"+e2);
+ policyLogger.error("Exception Occured while calling PAP with import dictionary request" + e2);
}
}
try {
URL url = new URL(papUrl + uri);
- connection = (HttpURLConnection)url.openConnection();
+ connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(false);
@@ -316,8 +319,8 @@ public class PolicyRestController extends RestrictedBaseController{
connection.setDoOutput(true);
connection.setDoInput(true);
- if(uri.contains("searchPolicy?action=delete&")){
- //do something
+ if (uri.contains("searchPolicy?action=delete&")) {
+ // do something
return doConnect(connection);
}
@@ -325,9 +328,9 @@ public class PolicyRestController extends RestrictedBaseController{
return doConnect(connection);
} catch (Exception e) {
- policyLogger.error("Exception Occured"+e);
- }finally{
- if(file != null && file.exists() && file.delete()){
+ policyLogger.error("Exception Occured" + e);
+ } finally {
+ if (file != null && file.exists() && file.delete()) {
policyLogger.info("File Deleted Successfully");
}
if (connection != null) {
@@ -339,7 +342,8 @@ public class PolicyRestController extends RestrictedBaseController{
is.close();
}
} catch (IOException ex) {
- policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex);
+ policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex,
+ ex);
}
connection.disconnect();
}
@@ -348,7 +352,7 @@ public class PolicyRestController extends RestrictedBaseController{
}
private void checkURI(HttpServletRequest request, String uri, HttpURLConnection connection, FileItem item)
- throws IOException {
+ throws IOException {
String boundary;
if (!(uri.endsWith("set_BRMSParamData") || uri.contains(IMPORT_DICTIONARY))) {
connection.setRequestProperty(CONTENT_TYPE, PolicyController.getContenttype());
@@ -364,7 +368,7 @@ public class PolicyRestController extends RestrictedBaseController{
// send current configuration
try (InputStream content = new ByteArrayInputStream(json.getBytes());
- OutputStream os = connection.getOutputStream()) {
+ OutputStream os = connection.getOutputStream()) {
int count = IOUtils.copy(content, os);
if (policyLogger.isDebugEnabled()) {
policyLogger.debug("copied to output, bytes=" + count);
@@ -390,28 +394,28 @@ public class PolicyRestController extends RestrictedBaseController{
JsonNode root = null;
try {
root = mapper.readTree(request.getReader());
- }catch (Exception e1) {
- policyLogger.error("Exception Occured while calling PAP"+e1);
+ } catch (Exception e1) {
+ policyLogger.error("Exception Occured while calling PAP" + e1);
}
return root;
}
- private String doConnect(final HttpURLConnection connection) throws IOException{
+ private String doConnect(final HttpURLConnection connection) throws IOException {
connection.connect();
int responseCode = connection.getResponseCode();
- if(responseCode == 200){
+ if (responseCode == 200) {
// get the response content into a String
String responseJson = null;
// read the inputStream into a buffer (trick found online scans entire input looking for end-of-file)
- try(java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) {
+ try (java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream())) {
scanner.useDelimiter("\\A");
responseJson = scanner.hasNext() ? scanner.next() : "";
- } catch (Exception e){
- //Reason for rethrowing the exception is if any exception occurs during reading of inputsteam
- //then the exception handling is done by the outer block without returning the response immediately
- //Also finally block is existing only in outer block and not here so all exception handling is
- //done in only one place
- policyLogger.error("Exception Occured"+e);
+ } catch (Exception e) {
+ // Reason for rethrowing the exception is if any exception occurs during reading of inputsteam
+ // then the exception handling is done by the outer block without returning the response immediately
+ // Also finally block is existing only in outer block and not here so all exception handling is
+ // done in only one place
+ policyLogger.error("Exception Occured" + e);
throw e;
}
@@ -421,14 +425,14 @@ public class PolicyRestController extends RestrictedBaseController{
return null;
}
- @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET})
- public void getDictionaryController(HttpServletRequest request, HttpServletResponse response){
+ @RequestMapping(value = {"/getDictionary/*"}, method = {RequestMethod.GET})
+ public void getDictionaryController(HttpServletRequest request, HttpServletResponse response) {
String uri = request.getRequestURI().replace("/getDictionary", "");
String body;
ResponseEntity<?> responseEntity = sendToPAP(null, uri, HttpMethod.GET);
- if(responseEntity != null){
+ if (responseEntity != null) {
body = responseEntity.getBody().toString();
- }else{
+ } else {
body = "";
}
try {
@@ -438,72 +442,79 @@ public class PolicyRestController extends RestrictedBaseController{
}
}
- @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST})
- public void saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException{
+ @RequestMapping(value = {"/saveDictionary/*/*"}, method = {RequestMethod.POST})
+ public void saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
String userId = "";
String uri = request.getRequestURI().replace("/saveDictionary", "");
- if(uri.startsWith("/")){
- uri = uri.substring(uri.indexOf('/')+1);
+ if (uri.startsWith("/")) {
+ uri = uri.substring(uri.indexOf('/') + 1);
}
uri = ONAP + uri.substring(uri.indexOf('/'));
- if(uri.contains(IMPORT_DICTIONARY)){
+ if (uri.contains(IMPORT_DICTIONARY)) {
userId = UserUtils.getUserSession(request).getOrgUserId();
- uri = uri+ "?userId=" +userId;
+ uri = uri + "?userId=" + userId;
}
- policyLogger.info("****************************************Logging UserID while Saving Dictionary*****************************************************");
+ policyLogger.info(
+ "****************************************Logging UserID while Saving Dictionary*****************************************************");
policyLogger.info(USER_ID + userId);
- policyLogger.info("***********************************************************************************************************************************");
+ policyLogger.info(
+ "***********************************************************************************************************************************");
String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
- if(body != null && !body.isEmpty()){
+ if (body != null && !body.isEmpty()) {
response.getWriter().write(body);
- }else{
+ } else {
response.getWriter().write("Failed");
}
}
- @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST})
- public void deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ @RequestMapping(value = {"/deleteDictionary/*/*"}, method = {RequestMethod.POST})
+ public void deletetDictionaryController(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
String uri = request.getRequestURI().replace("/deleteDictionary", "");
- if(uri.startsWith("/")){
- uri = uri.substring(uri.indexOf('/')+1);
+ if (uri.startsWith("/")) {
+ uri = uri.substring(uri.indexOf('/') + 1);
}
uri = ONAP + uri.substring(uri.indexOf('/'));
String userId = UserUtils.getUserSession(request).getOrgUserId();
- policyLogger.info("****************************************Logging UserID while Deleting Dictionary*****************************************************");
+ policyLogger.info(
+ "****************************************Logging UserID while Deleting Dictionary*****************************************************");
policyLogger.info(USER_ID + userId);
- policyLogger.info("*************************************************************************************************************************************");
+ policyLogger.info(
+ "*************************************************************************************************************************************");
String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
- if(body != null && !body.isEmpty()){
+ if (body != null && !body.isEmpty()) {
response.getWriter().write(body);
- }else{
+ } else {
response.getWriter().write("Failed");
}
}
- @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST})
- public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws IOException {
+ @RequestMapping(value = {"/searchDictionary"}, method = {RequestMethod.POST})
+ public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response)
+ throws IOException {
Object resultList;
String uri = request.getRequestURI();
- if(uri.startsWith("/")){
- uri = uri.substring(uri.indexOf('/')+1);
+ if (uri.startsWith("/")) {
+ uri = uri.substring(uri.indexOf('/') + 1);
}
uri = ONAP + uri.substring(uri.indexOf('/'));
- try{
+ try {
String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
- if(body.contains("CouldNotConnectException")){
+ if (body.contains("CouldNotConnectException")) {
List<String> data = new ArrayList<>();
data.add("Elastic Search Server is down");
resultList = data;
- }else{
+ } else {
JSONObject json = new JSONObject(body);
resultList = json.get("policyresult");
}
- }catch(Exception e){
- policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e);
+ } catch (Exception e) {
+ policyLogger.error(
+ XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e);
List<String> data = new ArrayList<>();
data.add("Elastic Search Server is down");
resultList = data;
@@ -517,26 +528,26 @@ public class PolicyRestController extends RestrictedBaseController{
return null;
}
- @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST})
- public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException{
+ @RequestMapping(value = {"/searchPolicy"}, method = {RequestMethod.POST})
+ public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws IOException {
Object resultList;
- String uri = request.getRequestURI()+"?action=search";
- if(uri.startsWith("/")){
- uri = uri.substring(uri.indexOf('/')+1);
+ String uri = request.getRequestURI() + "?action=search";
+ if (uri.startsWith("/")) {
+ uri = uri.substring(uri.indexOf('/') + 1);
}
uri = ONAP + uri.substring(uri.indexOf('/'));
String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim());
JSONObject json = new JSONObject(body);
- try{
+ try {
resultList = json.get("policyresult");
- }catch(Exception e){
+ } catch (Exception e) {
List<String> data = new ArrayList<>();
resultList = json.get(DATA);
data.add("Exception");
data.add(resultList.toString());
resultList = data;
- policyLogger.error("Exception Occured while searching for Policy in Elastic Database" +e);
+ policyLogger.error("Exception Occured while searching for Policy in Elastic Database" + e);
}
response.setCharacterEncoding(UTF_8);
@@ -549,13 +560,14 @@ public class PolicyRestController extends RestrictedBaseController{
return null;
}
- public void deleteElasticData(String fileName){
- String uri = "searchPolicy?action=delete&policyName='"+fileName+"'";
+ public void deleteElasticData(String fileName) {
+ String uri = "searchPolicy?action=delete&policyName='" + fileName + "'";
callPAP(null, "POST", uri.trim());
}
- public String notifyOtherPAPSToUpdateConfigurations(String mode, String newName, String oldName){
- String uri = "onap/notifyOtherPAPs?action="+mode+"&newPolicyName="+newName+"&oldPolicyName="+oldName+"";
+ public String notifyOtherPAPSToUpdateConfigurations(String mode, String newName, String oldName) {
+ String uri =
+ "onap/notifyOtherPAPs?action=" + mode + "&newPolicyName=" + newName + "&oldPolicyName=" + oldName + "";
return callPAP(null, "POST", uri.trim());
}
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java
index 2ccc92eb3..91bdc772b 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java
@@ -2,7 +2,7 @@
* ============LICENSE_START=======================================================
* ONAP Policy Engine
* ================================================================================
- * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
* Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
* Modifications Copyright (C) 2019 Bell Canada
* ================================================================================
@@ -42,7 +42,7 @@ import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.onap.policy.rest.XACMLRestProperties;
import org.onap.policy.rest.adapter.PolicyRestAdapter;
-import org.onap.policy.utils.CryptoUtils;
+import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.api.pap.OnapPDP;
import org.onap.policy.xacml.api.pap.OnapPDPGroup;
@@ -329,7 +329,9 @@ public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAP
HttpURLConnection connection = null;
String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID);
LOGGER.info("User Id is " + papID);
- String papPass = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
+ PeCryptoUtils.initAesKey(XACMLProperties.getProperty(XACMLRestProperties.PROP_AES_KEY));
+ String papPass = PeCryptoUtils
+ .decrypt(PeCryptoUtils.decrypt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)));
Base64.Encoder encoder = Base64.getEncoder();
String encoding = encoder.encodeToString((papID + ":" + papPass).getBytes(StandardCharsets.UTF_8));
Object contentObj = content;
diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
index 3485163e4..700aa3a57 100644
--- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
+++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java
@@ -59,6 +59,7 @@ import org.onap.policy.rest.jpa.FunctionDefinition;
import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.rest.jpa.PolicyVersion;
import org.onap.policy.rest.jpa.UserInfo;
+import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.utils.UserUtils.Pair;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
@@ -209,12 +210,12 @@ public class PolicyController extends RestrictedBaseController {
setLogdbDriver(prop.getProperty("xacml.log.db.driver"));
setLogdbUrl(prop.getProperty("xacml.log.db.url"));
setLogdbUserName(prop.getProperty("xacml.log.db.user"));
- setLogdbPassword(prop.getProperty("xacml.log.db.password"));
+ setLogdbPassword(PeCryptoUtils.decrypt(prop.getProperty("xacml.log.db.password")));
setLogdbDialect(prop.getProperty("onap.dialect"));
// Xacml Database Properties
setXacmldbUrl(prop.getProperty("javax.persistence.jdbc.url"));
setXacmldbUserName(prop.getProperty("javax.persistence.jdbc.user"));
- setXacmldbPassword(prop.getProperty("javax.persistence.jdbc.password"));
+ setXacmldbPassword(PeCryptoUtils.decrypt(prop.getProperty("javax.persistence.jdbc.password")));
// AutoPuh
setAutoPushAvailable(prop.getProperty("xacml.automatic.push"));
setAutoPushDSClosedLoop(prop.getProperty("xacml.autopush.closedloop"));
diff --git a/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java b/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java
index ab356ec17..a4c1e9852 100644
--- a/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java
+++ b/PolicyEngineAPI/src/main/java/org/onap/policy/std/StdPolicyEngine.java
@@ -125,6 +125,7 @@ import org.onap.policy.models.APIDictionaryResponse;
import org.onap.policy.models.APIPolicyConfigResponse;
import org.onap.policy.std.utils.PolicyCommonConfigConstants;
import org.onap.policy.utils.AAFEnvironment;
+import org.onap.policy.utils.PeCryptoUtils;
import org.onap.policy.utils.PolicyUtils;
import org.onap.policy.xacml.api.XACMLErrorConstants;
import org.springframework.core.io.FileSystemResource;
@@ -989,7 +990,7 @@ public class StdPolicyEngine {
}
private String getClientKeyFromProperties(final Properties prop) {
- final String clientKeyValue = prop.getProperty(CLIENT_KEY_PROP_NAME);
+ final String clientKeyValue = PeCryptoUtils.decrypt(prop.getProperty(CLIENT_KEY_PROP_NAME));
try {
return PolicyUtils.decode(clientKeyValue);
} catch (UnsupportedEncodingException | IllegalArgumentException e) {
@@ -1095,7 +1096,7 @@ public class StdPolicyEngine {
pdps.add(pdpValues.get(0));
// 1:2 will be UserID:Password
final String userID = pdpValues.get(1);
- final String userPas = pdpValues.get(2);
+ final String userPas = PeCryptoUtils.decrypt(pdpValues.get(2));
final Base64.Encoder encoder = Base64.getEncoder();
encoding.add(encoder.encodeToString((userID + ":" + userPas).getBytes(StandardCharsets.UTF_8)));
} else {
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/CryptoUtils.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/CryptoUtils.java
deleted file mode 100644
index 15a93bdab..000000000
--- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/CryptoUtils.java
+++ /dev/null
@@ -1,256 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * PolicyEngineUtils
- * ================================================================================
- * Copyright (C) 2018 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.onap.policy.utils;
-
-import java.nio.charset.StandardCharsets;
-import java.security.AlgorithmParameters;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-import java.security.Key;
-import java.util.Base64;
-
-import javax.crypto.BadPaddingException;
-import javax.crypto.Cipher;
-import javax.crypto.IllegalBlockSizeException;
-import javax.crypto.NoSuchPaddingException;
-import javax.crypto.spec.SecretKeySpec;
-import javax.xml.bind.DatatypeConverter;
-
-import org.onap.policy.common.logging.flexlogger.FlexLogger;
-import org.onap.policy.common.logging.flexlogger.Logger;
-
-public class CryptoUtils {
- private static final Logger LOGGER = FlexLogger.getLogger(CryptoUtils.class);
- private static final String CIPHER_TYPE = "AES/CBC/PKCS5Padding";
- private static Key mKey = null;
- private static AlgorithmParameters mAlgParm = null;
-
- static {
- //the hadcoded key is to be removed in a future iteration
- try {
- String kval = "bmpybWJrbGN4dG9wbGF3Zg==";
- String algp = "BBBpbml0VmVjVGhpc0lzVGhl";
-
- byte[] kvalb = DatatypeConverter.parseBase64Binary(kval);
- byte[] algb = DatatypeConverter.parseBase64Binary(algp);
-
- mKey = new SecretKeySpec(kvalb, "AES");
-
- mAlgParm = AlgorithmParameters.getInstance("AES");
- mAlgParm.init(algb, "ASN.1");
-
- } catch (Exception ex) {
- throw new ExceptionInInitializerError(ex);
- }
- }
-
- private CryptoUtils() {
- // Private Constructor
- }
-
- /**
- * Decrypt txt.
- *
- * @param encryptedTxt
- * text to be decrypted, Base 64 UrlEncoded
- * @return the byte[]
- * @throws NoSuchAlgorithmException
- * the no such algorithm exception
- * @throws NoSuchPaddingException
- * the no such padding exception
- * @throws InvalidAlgorithmParameterException
- * the invalid algorithm parameter exception
- * @throws InvalidKeyException
- * the invalid key exception
- * @throws IllegalBlockSizeException
- * the illegal block size exception
- * @throws BadPaddingException
- * the bad padding exception
- */
- public static byte[] decryptTxt(String encryptedTxt)
- throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException,
- InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
- Cipher cipher = Cipher.getInstance(CIPHER_TYPE);
- cipher.init(Cipher.DECRYPT_MODE, mKey, mAlgParm);
-
- return cipher.doFinal(Base64.getUrlDecoder().decode(encryptedTxt.getBytes(StandardCharsets.UTF_8)));
- }
-
- /**
- * Decrypt txt.
- *
- * @param encryptedTxt
- * text to be decrypted, Base 64 UrlEncoded
- * @param mKey
- * the key as Base 64
- * @return the byte[]
- * @throws NoSuchAlgorithmException
- * the no such algorithm exception
- * @throws NoSuchPaddingException
- * the no such padding exception
- * @throws InvalidAlgorithmParameterException
- * the invalid algorithm parameter exception
- * @throws InvalidKeyException
- * the invalid key exception
- * @throws IllegalBlockSizeException
- * the illegal block size exception
- * @throws BadPaddingException
- * the bad padding exception
- */
- public static byte[] decryptTxt(String encryptedTxt, String base64BinaryKey)
- throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException,
- InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
-
- byte[] keyValueByte = DatatypeConverter.parseBase64Binary(base64BinaryKey);
- Key paramKey = new SecretKeySpec(keyValueByte, "AES");
- Cipher cipher = Cipher.getInstance(CIPHER_TYPE);
- cipher.init(Cipher.DECRYPT_MODE, paramKey, mAlgParm);
-
- return cipher.doFinal(Base64.getUrlDecoder().decode(encryptedTxt.getBytes(StandardCharsets.UTF_8)));
- }
-
- /**
- * Decrypt txt, no exceptions thrown.
- *
- * @param encryptedTxt
- * text to be decrypted, Base 64 UrlEncoded
- * @return the decrypted text, or the original text if it could not be
- * decrypted
- */
- public static byte[] decryptTxtNoEx(String encryptedTxt) {
-
- try {
- if (encryptedTxt == null || encryptedTxt.isEmpty()) {
- LOGGER.info("decryptTxtNoEx: Input param encryptedTxt is empty");
- return new byte[0];
- }
- return decryptTxt(encryptedTxt);
- } catch (Exception e) {
- try {
- LOGGER.info("decryptTxtNoEx: Exception while decrypting : " + e);
- return (encryptedTxt != null) ? encryptedTxt.getBytes(StandardCharsets.UTF_8) : new byte[0];
- } catch (Exception e1) {
- LOGGER.warn("decryptTxtNoEx: Exception on sending default : " + e1);
- return new byte[0];
- }
- }
- }
-
- /**
- * Decrypt txt, no exceptions thrown.
- *
- * @param encryptedTxt
- * text to be decrypted, Base 64 UrlEncoded
- * @return the decrypted text, or the original text if it could not be
- * decrypted
- */
- public static String decryptTxtNoExStr(String encryptedTxt) {
- return new String(decryptTxtNoEx(encryptedTxt), StandardCharsets.UTF_8);
- }
-
- /**
- * Encrypt txt.
- *
- * @param plainTxt
- * the plain txt
- * @return the encrypted string
- * @throws NoSuchPaddingException
- * the no such padding exception
- * @throws InvalidAlgorithmParameterException
- * the invalid algorithm parameter exception
- * @throws NoSuchAlgorithmException
- * the no such algorithm exception
- * @throws InvalidKeyException
- * the invalid key exception
- * @throws IllegalBlockSizeException
- * the illegal block size exception
- * @throws BadPaddingException
- * the bad padding exception
- */
- public static String encryptTxt(byte[] plainTxt)
- throws NoSuchPaddingException, InvalidAlgorithmParameterException,
- NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
-
- Cipher cipher = Cipher.getInstance(CIPHER_TYPE);
- cipher.init(Cipher.ENCRYPT_MODE, mKey, mAlgParm);
-
- byte[] encryption = cipher.doFinal(plainTxt);
- return new String(Base64.getUrlEncoder().encode(encryption), StandardCharsets.UTF_8);
- }
-
- /**
- * Encrypt txt.
- *
- * @param plainTxt
- * the plain txt to be encrypted
- * @param base64BinaryKey
- * the key as lexical representation of Base64 Binary
- * @return the encrypted string
- * @throws NoSuchPaddingException
- * the no such padding exception
- * @throws InvalidAlgorithmParameterException
- * the invalid algorithm parameter exception
- * @throws NoSuchAlgorithmException
- * the no such algorithm exception
- * @throws InvalidKeyException
- * the invalid key exception
- * @throws IllegalBlockSizeException
- * the illegal block size exception
- * @throws BadPaddingException
- * the bad padding exception
- */
- public static String encryptTxt(byte[] plainTxt, String base64BinaryKey)
- throws NoSuchPaddingException, InvalidAlgorithmParameterException,
- NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
-
- byte[] keyValueByte = DatatypeConverter.parseBase64Binary(base64BinaryKey);
- Key paramKey = new SecretKeySpec(keyValueByte, "AES");
- Cipher cipher = Cipher.getInstance(CIPHER_TYPE);
- cipher.init(Cipher.ENCRYPT_MODE, paramKey, mAlgParm);
-
- byte[] encryption = cipher.doFinal(plainTxt);
- return new String(Base64.getMimeEncoder().encode(encryption), StandardCharsets.UTF_8);
- }
-
- /**
- * Encrypt txt, no exceptions thrown
- *
- * @param plainTxt
- * the plain txt to be encrypted
- * @return the encrypted String , or the original text if it could not be
- * encrypted
- */
- public static String encryptTxtNoEx(byte[] plainTxt) {
-
- if (plainTxt == null || plainTxt.length == 0) {
- LOGGER.error("encryptTxtNoEx: Input param plainTxt is not valid");
- return "";
- }
-
- try {
- return encryptTxt(plainTxt);
- } catch (Exception e) {
- LOGGER.error("encryptTxtNoEx: Exception while decryption : " + e);
- return new String(plainTxt, StandardCharsets.UTF_8);
- }
- }
-
-} \ No newline at end of file
diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PeCryptoUtils.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PeCryptoUtils.java
new file mode 100644
index 000000000..9863f03ad
--- /dev/null
+++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PeCryptoUtils.java
@@ -0,0 +1,102 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP Policy Engine
+ * ================================================================================
+ * Copyright (C) 2019 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.onap.policy.utils;
+
+import java.security.GeneralSecurityException;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import org.apache.commons.lang3.StringUtils;
+import org.onap.policy.common.logging.flexlogger.FlexLogger;
+import org.onap.policy.common.logging.flexlogger.Logger;
+import org.onap.policy.common.utils.security.CryptoUtils;
+
+public class PeCryptoUtils {
+
+ private static Logger logger = FlexLogger.getLogger(PeCryptoUtils.class);
+ private static final String PROP_AES_KEY = "org.onap.policy.encryption.aes.key";
+ private static CryptoUtils cryptoUtils = null;
+ private static String secretKey = System.getenv("AES_ENCRYPTION_KEY");
+ private static final Map<String, String> decryptCache = new ConcurrentHashMap<>();
+ private static final Map<String, String> encryptCache = new ConcurrentHashMap<>();
+
+
+ private PeCryptoUtils() {}
+
+ /**
+ * Inits the aes key.
+ *
+ * @param theSecretKey the the secret key
+ */
+ public static synchronized void initAesKey(String theSecretKey) {
+ String secKey = theSecretKey;
+ if (cryptoUtils == null) {
+ if (StringUtils.isBlank(secKey)) {
+ secKey = System.getProperty(PROP_AES_KEY);
+ }
+ if (StringUtils.isBlank(secKey)) {
+ secKey = secretKey;
+ }
+ cryptoUtils = new CryptoUtils(secKey);
+ }
+ }
+
+ /**
+ * Encrypt a value based on the Policy Encryption Key.
+ *
+ * @param value The plain text string
+ * @return The encrypted String
+ */
+ public static String encrypt(String value) {
+
+ if (cryptoUtils == null || StringUtils.isBlank(value)) {
+ return value;
+ }
+
+ return encryptCache.computeIfAbsent(value, k -> {
+ try {
+ return cryptoUtils.encrypt(k);
+ } catch (GeneralSecurityException e) {
+ logger.error("Could not decrypt value - exception: ", e);
+ return value;
+ }
+ });
+ }
+
+ /**
+ * Decrypt a value based on the Policy Encryption Key if string begin with 'enc:'.
+ *
+ * @param value The encrypted string that must be decrypted using the Policy Encryption Key
+ * @return The String decrypted if string begin with 'enc:'
+ */
+ public static String decrypt(String value) {
+ if (cryptoUtils == null || StringUtils.isBlank(value)) {
+ return value;
+ }
+ return decryptCache.computeIfAbsent(value, k -> {
+ try {
+ return cryptoUtils.decrypt(k);
+ } catch (GeneralSecurityException e) {
+ logger.error("Could not decrypt value - exception: ", e);
+ return value;
+ }
+ });
+ }
+}
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/PeCryptoUtilsTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/PeCryptoUtilsTest.java
new file mode 100644
index 000000000..3765ff2e3
--- /dev/null
+++ b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/PeCryptoUtilsTest.java
@@ -0,0 +1,64 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * ONAP-REST
+ * ================================================================================
+ * Copyright (C) 2019 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.onap.policy.utils;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import java.security.GeneralSecurityException;
+import org.junit.Before;
+import org.junit.Test;
+import org.powermock.reflect.Whitebox;
+
+
+public class PeCryptoUtilsTest {
+ private final String pass = "policy_user";
+ private final String secretKey = "bmpybWJrbGN4dG9wbGF3Zg==";
+ private final String encryptedPass = "enc:5ID9PoqWIzBaut+KQcAFBtci9CKDRcCNRHRjdBnXM5U=";
+ private static final String PROP_AES_KEY = "org.onap.policy.encryption.aes.key";
+
+ @Before
+ public void reset() {
+ Whitebox.setInternalState( PeCryptoUtils.class, "cryptoUtils", (PeCryptoUtils)null);
+
+ }
+
+ @Test
+ public void testEncrypt() throws GeneralSecurityException {
+ assertEquals(pass, PeCryptoUtils.encrypt(pass));
+ PeCryptoUtils.initAesKey(secretKey);
+ System.out.println("original value : " + pass + " encrypted value: " + PeCryptoUtils.encrypt(pass));
+ assertNotNull(PeCryptoUtils.encrypt(pass));
+ }
+
+ @Test
+ public void testDecrypt() throws Exception {
+ assertEquals(pass, PeCryptoUtils.decrypt(pass));
+ System.setProperty(PROP_AES_KEY, secretKey);
+ PeCryptoUtils.initAesKey(null);
+ System.clearProperty(PROP_AES_KEY);
+ assertEquals(pass, PeCryptoUtils.decrypt(encryptedPass));
+ Whitebox.setInternalState( PeCryptoUtils.class, "cryptoUtils", (PeCryptoUtils)null);
+ Whitebox.setInternalState( PeCryptoUtils.class, "secretKey", secretKey);
+ PeCryptoUtils.initAesKey(" ");
+ assertEquals(pass, PeCryptoUtils.decrypt(pass));
+ }
+
+}
diff --git a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/CryptoUtilsTest.java b/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/CryptoUtilsTest.java
deleted file mode 100644
index e2ca78a06..000000000
--- a/PolicyEngineUtils/src/test/java/org/onap/policy/utils/test/CryptoUtilsTest.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*-
- * ============LICENSE_START=======================================================
- * PolicyEngineUtils
- * ================================================================================
- * Copyright (C) 2018 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.onap.policy.utils.test;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertArrayEquals;
-
-import java.nio.charset.StandardCharsets;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.InvalidKeyException;
-import java.security.NoSuchAlgorithmException;
-
-import javax.crypto.BadPaddingException;
-import javax.crypto.IllegalBlockSizeException;
-import javax.crypto.NoSuchPaddingException;
-
-import org.junit.Test;
-import org.onap.policy.utils.CryptoUtils;
-
-public class CryptoUtilsTest {
-
- @Test
- public final void testDecryptTxt() throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
- InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
- {
- String decryptedTxt = new String(CryptoUtils.decryptTxt("g0uHKXCLyzJ6wSbpphNGsA=="), StandardCharsets.UTF_8);
- assertEquals("mypass", decryptedTxt);
- }
-
- @Test
- public final void testDecryptTxtWithKey() throws InvalidKeyException, NoSuchAlgorithmException,
- NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
- {
- String decryptedTxt = new String(CryptoUtils.decryptTxt("g0uHKXCLyzJ6wSbpphNGsA==", "bmpybWJrbGN4dG9wbGF3Zg=="),
- StandardCharsets.UTF_8);
- assertEquals("mypass", decryptedTxt);
- }
-
- @Test
- public final void testDecryptTxtNoEx() {
- String decryptedTxt = new String(CryptoUtils.decryptTxtNoEx("g0uHKXCLyzJ6wSbpphNGsA=="),
- StandardCharsets.UTF_8);
- assertEquals("mypass", decryptedTxt);
-
- }
-
- @Test
- public final void testDecryptTxtNoExStr() {
- assertEquals("mypass", CryptoUtils.decryptTxtNoExStr("g0uHKXCLyzJ6wSbpphNGsA=="));
- }
- @Test
- public final void testDecryptTxtNoExInvalidInput() {
- assertArrayEquals(new byte[0], CryptoUtils.decryptTxtNoEx(null));
- assertArrayEquals(new byte[0], CryptoUtils.decryptTxtNoEx(""));
- // ensure backward compatibility
- assertEquals("bogus", new String(CryptoUtils.decryptTxtNoEx("bogus"), StandardCharsets.UTF_8));
- assertEquals("admin123", CryptoUtils.decryptTxtNoExStr("admin123"));
- assertEquals("password", CryptoUtils.decryptTxtNoExStr("password"));
- }
-
- @Test(expected = IllegalArgumentException.class)
- public final void testDecryptTxtInvalidInput() throws InvalidKeyException, NoSuchAlgorithmException,
- NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException
- {
- CryptoUtils.decryptTxt("bogus");
- }
-
- @Test
- public final void testEncryptTxt() throws InvalidKeyException, NoSuchPaddingException,
- InvalidAlgorithmParameterException, NoSuchAlgorithmException, IllegalBlockSizeException,
- BadPaddingException {
- String txtStr = "mypass";
- byte[] txt = txtStr.getBytes(StandardCharsets.UTF_8);
- assertEquals("g0uHKXCLyzJ6wSbpphNGsA==", CryptoUtils.encryptTxt(txt));
- }
-
- @Test
- public final void testEncryptTxtWithKey() throws InvalidKeyException,
- NoSuchPaddingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
- IllegalBlockSizeException, BadPaddingException {
- String txtStr = "mypass";
- byte[] txt = txtStr.getBytes(StandardCharsets.UTF_8);
- assertEquals("g0uHKXCLyzJ6wSbpphNGsA==", CryptoUtils.encryptTxt(txt, "bmpybWJrbGN4dG9wbGF3Zg=="));
- }
-
- @Test
- public final void testEncryptTxtNoEx() {
- String txtStr = "mypass";
- byte[] txt = txtStr.getBytes(StandardCharsets.UTF_8);
- assertEquals("g0uHKXCLyzJ6wSbpphNGsA==", CryptoUtils.encryptTxtNoEx(txt));
- }
-
- @Test
- public final void testEncryptTxtNoExInvalidInput() {
- String txtStr = "";
- byte[] txt = txtStr.getBytes(StandardCharsets.UTF_8);
- assertEquals("", CryptoUtils.encryptTxtNoEx(txt));
- assertEquals("", CryptoUtils.encryptTxtNoEx(null));
- }
-
- @Test(expected = InvalidKeyException.class)
- public final void testEncryptTxtWithKeyInvalid() throws InvalidKeyException,
- NoSuchPaddingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
- IllegalBlockSizeException, BadPaddingException {
- String txtStr = "mypass";
- byte[] txt = txtStr.getBytes(StandardCharsets.UTF_8);
- CryptoUtils.encryptTxt(txt, "mykey");
- }
-
-
-} \ No newline at end of file
diff --git a/packages/base/src/files/install/servers/brmsgw/config.properties b/packages/base/src/files/install/servers/brmsgw/config.properties
index 9402a057b..c16df02b5 100644
--- a/packages/base/src/files/install/servers/brmsgw/config.properties
+++ b/packages/base/src/files/install/servers/brmsgw/config.properties
@@ -2,7 +2,7 @@
# ============LICENSE_START=======================================================
# ONAP Policy Engine
# ================================================================================
-# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+# Copyright (C) 2017,2019 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.
@@ -87,3 +87,6 @@ ping_interval=30000
brms.dependency.version=1.3.0-SNAPSHOT
CLIENT_FILE=client.properties
+
+# AES key for password encryption in config files
+#org.onap.policy.encryption.aes.key=12345678901234567890123456789012 \ No newline at end of file
diff --git a/packages/base/src/files/install/servers/console/bin/xacml.admin.properties b/packages/base/src/files/install/servers/console/bin/xacml.admin.properties
index a890a2938..55ede743c 100644
--- a/packages/base/src/files/install/servers/console/bin/xacml.admin.properties
+++ b/packages/base/src/files/install/servers/console/bin/xacml.admin.properties
@@ -2,7 +2,7 @@
# ============LICENSE_START=======================================================
# ONAP Policy Engine
# ================================================================================
-# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+# Copyright (C) 2017-2019 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.
@@ -211,4 +211,7 @@ xacml.policy.msOnapName=${{policy_msOnapName}}
xacml.policy.msPolicyName=${{policy_msPolicyName}}
#Size limit (in bytes) for file uploads
-file.size.limit=30000000 \ No newline at end of file
+file.size.limit=30000000
+
+# AES key for password encryption in config files
+#org.onap.policy.encryption.aes.key=12345678901234567890123456789012 \ No newline at end of file
diff --git a/packages/base/src/files/install/servers/pap/bin/xacml.pap.properties b/packages/base/src/files/install/servers/pap/bin/xacml.pap.properties
index 2a14641e9..384e8f483 100644
--- a/packages/base/src/files/install/servers/pap/bin/xacml.pap.properties
+++ b/packages/base/src/files/install/servers/pap/bin/xacml.pap.properties
@@ -2,7 +2,7 @@
# ============LICENSE_START=======================================================
# ONAP Policy Engine
# ================================================================================
-# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+# Copyright (C) 2017,2019 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.
@@ -135,4 +135,7 @@ ENVIRONMENT=${{ENVIRONMENT}}
#Micro Service Model Properties
xacml.policy.msOnapName=${{policy_msOnapName}}
-xacml.policy.msPolicyName=${{policy_msPolicyName}} \ No newline at end of file
+xacml.policy.msPolicyName=${{policy_msPolicyName}}
+
+# AES key for password encryption in config files
+#org.onap.policy.encryption.aes.key=12345678901234567890123456789012 \ No newline at end of file
diff --git a/packages/base/src/files/install/servers/paplp/bin/parserlog.properties b/packages/base/src/files/install/servers/paplp/bin/parserlog.properties
index 721fc77d6..0796c56c7 100644
--- a/packages/base/src/files/install/servers/paplp/bin/parserlog.properties
+++ b/packages/base/src/files/install/servers/paplp/bin/parserlog.properties
@@ -2,7 +2,7 @@
# ============LICENSE_START=======================================================
# ONAP Policy Engine
# ================================================================================
-# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+# Copyright (C) 2017-2019 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.
@@ -59,3 +59,6 @@ test_trans_interval=${{test_trans_interval}}
write_fpc_interval=${{write_fpc_interval}}
max_fpc_update_interval=${{max_fpc_update_interval}}
test_via_jmx=${{test_via_jmx}}
+
+# AES key for password encryption in config files
+#org.onap.policy.encryption.aes.key=12345678901234567890123456789012
diff --git a/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties b/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties
index 8835fe45d..e8e28793a 100644
--- a/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties
+++ b/packages/base/src/files/install/servers/pdp/bin/xacml.pdp.properties
@@ -165,4 +165,6 @@ gui_url=https://${{AAF_HOST}}:8095/AAF_NS.gui.2.1
# can be either PERMIT or DENY.
decision.indeterminate.response=${{DECISION_INDETERMINATE_RESPONSE}}
-msToscaModel.home=${{REST_PDP_WEBAPPS}} \ No newline at end of file
+msToscaModel.home=${{REST_PDP_WEBAPPS}}
+# AES key for password encryption in config files
+#org.onap.policy.encryption.aes.key=12345678901234567890123456789012
diff --git a/packages/base/src/files/install/servers/pdplp/bin/parserlog.properties b/packages/base/src/files/install/servers/pdplp/bin/parserlog.properties
index c2b3e5ffc..6e5448806 100755
--- a/packages/base/src/files/install/servers/pdplp/bin/parserlog.properties
+++ b/packages/base/src/files/install/servers/pdplp/bin/parserlog.properties
@@ -2,7 +2,7 @@
# ============LICENSE_START=======================================================
# ONAP Policy Engine
# ================================================================================
-# Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+# Copyright (C) 2017-2019 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.
@@ -59,3 +59,6 @@ test_trans_interval=${{test_trans_interval}}
write_fpc_interval=${{write_fpc_interval}}
max_fpc_update_interval=${{max_fpc_update_interval}}
test_via_jmx=${{test_via_jmx}}
+
+# AES key for password encryption in config files
+#org.onap.policy.encryption.aes.key=12345678901234567890123456789012