* ============LICENSE_START=======================================================
* ONAP-PAP-REST
* ================================================================================
- * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * Copyright (C) 2017-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.
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
+import org.elasticsearch.common.Strings;
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.rest.jpa.PolicyDBDaoEntity;
import org.onap.policy.rest.jpa.PolicyEntity;
import org.onap.policy.rest.util.Webapps;
+import org.onap.policy.utils.CryptoUtils;
import org.onap.policy.xacml.api.pap.OnapPDP;
import org.onap.policy.xacml.api.pap.OnapPDPGroup;
import org.onap.policy.xacml.api.pap.PAPPolicyEngine;
}
}
if(urlUserPass[2] == null || urlUserPass[2].equals("")){
- String passwordPropertyValue = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS);
+ String passwordPropertyValue = CryptoUtils.decryptTxtNoExStr(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS));
if(passwordPropertyValue != null){
urlUserPass[2] = passwordPropertyValue;
}
return urlUserPass;
}
- private static String encryptPassword(String password) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
- Cipher cipher = Cipher.getInstance("AES");
- cipher.init(Cipher.ENCRYPT_MODE, aesKey());
- byte[] encryption = cipher.doFinal(password.getBytes("UTF-8"));
- logger.debug("Encryption value is " + encryption);
- return new String(Base64.getMimeEncoder().encode(encryption),"UTF-8");
- }
-
- private static String decryptPassword(String encryptedPassword) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
- Cipher cipher = Cipher.getInstance("AES");
- cipher.init(Cipher.DECRYPT_MODE, aesKey());
- byte[] password = cipher.doFinal(Base64.getDecoder().decode(encryptedPassword.getBytes("UTF-8")));
- return new String(password,"UTF-8");
- }
- private static Key aesKey(){
- byte[] aesValue = (new String("njrmbklcxtoplawf")).getBytes();
- return new SecretKeySpec(aesValue,"AES");
- }
/**
* Register the PolicyDBDao instance in the PolicyDBDaoEntity table
* @return Boolean, were we able to register?
private boolean register(){
logger.debug("register() as register() called");
String[] url = getPapUrlUserPass();
+ //--- check URL length
+ if(url == null || url.length<3){
+ return false;
+ }
+
EntityManager em = emf.createEntityManager();
try{
startTransactionSynced(em, 1000);
PolicyDBDaoEntity foundPolicyDBDaoEntity = em.find(PolicyDBDaoEntity.class, url[0]);
Query getPolicyDBDaoEntityQuery = em.createQuery("SELECT e FROM PolicyDBDaoEntity e WHERE e.policyDBDaoUrl=:url");
getPolicyDBDaoEntityQuery.setParameter("url", url[0]);
+ // 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", "Could not encrypt PAP password");
+ }
if(foundPolicyDBDaoEntity == null){
PolicyDBDaoEntity newPolicyDBDaoEntity = new PolicyDBDaoEntity();
em.persist(newPolicyDBDaoEntity);
newPolicyDBDaoEntity.setPolicyDBDaoUrl(url[0]);
newPolicyDBDaoEntity.setDescription("PAP server at "+url[0]);
newPolicyDBDaoEntity.setUsername(url[1]);
- try{
- newPolicyDBDaoEntity.setPassword(encryptPassword(url[2]));
- } catch(Exception e){
- logger.debug(e);
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not encrypt PAP password");
- }
+ newPolicyDBDaoEntity.setPassword(txt);
+
try{
em.getTransaction().commit();
} catch(Exception e){
}
} else {
//just want to update in order to change modified date
- String encryptedPassword = null;
- try{
- encryptedPassword = encryptPassword(url[2]);
- } catch(Exception e){
- logger.debug(e);
- PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not encrypt PAP password");
- }
+
if(url[1] != null && !stringEquals(url[1], foundPolicyDBDaoEntity.getUsername())){
foundPolicyDBDaoEntity.setUsername(url[1]);
}
- if(encryptedPassword != null && !stringEquals(encryptedPassword, foundPolicyDBDaoEntity.getPassword())){
- foundPolicyDBDaoEntity.setPassword(encryptedPassword);
+ if(txt != null && !stringEquals(txt, foundPolicyDBDaoEntity.getPassword())){
+ foundPolicyDBDaoEntity.setPassword(txt);
}
+
foundPolicyDBDaoEntity.preUpdate();
try{
em.getTransaction().commit();
PolicyDBDaoEntity dbdEntity = (PolicyDBDaoEntity)obj;
String o = dbdEntity.getPolicyDBDaoUrl();
String username = dbdEntity.getUsername();
- String password;
+ String txt;
try{
- password = decryptPassword(dbdEntity.getPassword());
+ txt = new String(CryptoUtils.decryptTxt(dbdEntity.getPassword()), StandardCharsets.UTF_8);
} catch(Exception e){
logger.debug(e);
//if we can't decrypt, might as well try it anyway
- password = dbdEntity.getPassword();
+ txt = dbdEntity.getPassword();
}
+
Base64.Encoder encoder = Base64.getEncoder();
- String encoding = encoder.encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
+ String encoding = encoder.encodeToString((username+":"+txt).getBytes(StandardCharsets.UTF_8));
HttpURLConnection connection = null;
UUID requestID = UUID.randomUUID();
URL url;
//
// Open up the connection
//
- logger.debug("Connecting with url: "+url);
+ logger.info("PolicyDBDao: NotifyOtherThread: notifying other PAPs of an update");
+ logger.info("Connecting with url: "+url);
try {
connection = (HttpURLConnection)url.openConnection();
} catch (Exception e) {
logger.warn("Caught Exception on: connection.getResponseCode() ", e);
}
+
connection.disconnect();
}
}
} else {
//convert PolicyEntity object to PDPPolicy
- String name = pdpPolicyId.replace(".xml", "");
+ String name = null;
+ name = pdpPolicyId.replace(".xml", "");
name = name.substring(0, name.lastIndexOf("."));
InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes());
pdpGroup.copyPolicyToFile(pdpPolicyId,name,policyStream);
try {
if(policy != null){
policyName = policy.getPolicyName();
- logger.debug("Deleting Policy: " + policy.getPolicyName());
+ logger.info("Deleting old Policy Config File for " + policy.getPolicyName());
action = "delete";
Path subFile = null;
}
private Path getPolicySubFile(String filename, String subFileType){
- logger.debug("getPolicySubFile(" + filename + ", " + subFileType + ")");
+ logger.info("getPolicySubFile(" + filename + ", " + subFileType + ")");
Path filePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS).toString(), subFileType);
File file = null;
finalPath = Paths.get(file.getAbsolutePath());
}
- logger.debug("end of getPolicySubFile: " + finalPath);
+ logger.info("end of getPolicySubFile: " + finalPath);
return finalPath;
}
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
- StdPDPGroup updatedGroup = null;
- try {
- Query groupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
- groupQuery.setParameter("groupId", group.getId());
- groupQuery.setParameter("deleted", false);
- List<?> groupQueryList = groupQuery.getResultList();
- if(groupQueryList!=null){
- GroupEntity dbgroup = (GroupEntity)groupQueryList.get(0);
- updatedGroup = synchronizeGroupPoliciesInFileSystem(group, dbgroup);
- }
- } catch (PAPException e) {
- logger.error(e);
- } catch (PolicyDBException e) {
- logger.error(e);
- } catch (Exception e) {
- logger.error(e);
+ Query groupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
+ groupQuery.setParameter("groupId", group.getId());
+ groupQuery.setParameter("deleted", false);
+ List<?> groupQueryList;
+ try{
+ groupQueryList = groupQuery.getResultList();
+ }catch(Exception e){
PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Caught Exception trying to check if group exists groupQuery.getResultList()");
throw new PersistenceException("Query failed trying to check if group "+group.getId()+" exists");
}
+ GroupEntity dbgroup = null;
+ if(groupQueryList!=null){
+ dbgroup = (GroupEntity)groupQueryList.get(0);
+ }
+
em.getTransaction().commit();
em.close();
+ StdPDPGroup updatedGroup = null;
+ try {
+ updatedGroup = synchronizeGroupPoliciesInFileSystem(group, dbgroup);
+ } catch (PAPException e) {
+ logger.error(e);
+ } catch (PolicyDBException e) {
+ logger.error(e);
+ }
logger.info("Group was updated during file system audit: " + updatedGroup.toString());
return updatedGroup;
@Override
public void updateGroup(OnapPDPGroup group, String username){
- logger.debug("updateGroup(PDPGroup group) as updateGroup("+group+","+username+") called");
+ logger.info("PolicyDBDao: updateGroup(PDPGroup group) as updateGroup("+group+","+username+") called");
if(group == null){
throw new IllegalArgumentException("PDPGroup group must not be null");
}
PolicyLogger.error("Somehow, more than one group with the same id "+group.getId()+" and deleted status were found in the database");
throw new PersistenceException("Somehow, more than one group with the same id "+group.getId()+" and deleted status were found in the database");
}
- GroupEntity groupToUpdate = (GroupEntity)getGroupQueryList.get(0);
- if(!stringEquals(groupToUpdate.getModifiedBy(), username)){
- groupToUpdate.setModifiedBy(username);
+ GroupEntity groupToUpdateInDB = (GroupEntity)getGroupQueryList.get(0);
+ if(!stringEquals(groupToUpdateInDB.getModifiedBy(), username)){
+ groupToUpdateInDB.setModifiedBy(username);
}
- if(group.getDescription() != null && !stringEquals(group.getDescription(),groupToUpdate.getDescription())){
- groupToUpdate.setDescription(group.getDescription());
+ if(group.getDescription() != null && !stringEquals(group.getDescription(),groupToUpdateInDB.getDescription())){
+ groupToUpdateInDB.setDescription(group.getDescription());
}
//let's find out what policies have been deleted
StdPDPGroup oldGroup = null;
if(oldGroup == null){
PolicyLogger.error("We cannot get the group from the papEngine to delete policies");
} else {
-
Set<String> newPolicySet = new HashSet<>(group.getPolicies().size());
//a multiple of n runtime is faster than n^2, so I am using a hashset to do the comparison
for(PDPPolicy pol: group.getPolicies()){
//should be fast since getPolicies uses a HashSet in StdPDPGroup
if(!newPolicySet.contains(pol.getId())){
String[] scopeAndName = getNameScopeAndVersionFromPdpPolicy(pol.getId());
- PolicyEntity policyToDelete;
+ PolicyEntity policyToDelete = null;
try{
- policyToDelete = getPolicy(scopeAndName[0],scopeAndName[1]);
+ if(scopeAndName!=null){
+ policyToDelete = getPolicy(scopeAndName[0],scopeAndName[1]);
+
+ if ("XACMLPapServlet.doDelete".equals(username)) {
+
+ Iterator<PolicyEntity> dbPolicyIt = groupToUpdateInDB.getPolicies().iterator();
+ String policyName = getPolicyNameAndVersionFromPolicyFileName(policyToDelete.getPolicyName())[0];
+
+ logger.info("PolicyDBDao: delete policy from GroupEntity");
+ try{
+ while(dbPolicyIt.hasNext()){
+ PolicyEntity dbpolicy = dbPolicyIt.next();
+ if(policyToDelete.getScope().equals(dbpolicy.getScope()) &&
+ getPolicyNameAndVersionFromPolicyFileName(dbpolicy.getPolicyName())[0].equals(policyName)) {
+ dbPolicyIt.remove();
+
+ logger.info("PolicyDBDao: deleting policy from the existing group:\n "
+ + "policyName is " + policyToDelete.getScope()+"."+policyToDelete.getPolicyName() + "\n"
+ + "group is " + groupToUpdateInDB.getGroupId());
+ }
+ }
+ }catch(Exception e){
+ logger.debug(e);
+ PolicyLogger.error("Could not delete policy with name: "+ policyToDelete.getScope()+"."+policyToDelete.getPolicyName()+"\n ID: "+ policyToDelete.getPolicyId());
+ }
+ }
+ }
+
}catch(Exception e){
PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "PolicyDBDao", "Could not get policy to remove: "+pol.getId());
throw new PersistenceException("Could not get policy to remove: "+pol.getId());
}
- groupToUpdate.getPolicies().remove(policyToDelete);
-
}
}
}
- if(group.getName() != null && !stringEquals(group.getName(),groupToUpdate.getgroupName())){
+
+ if(group.getName() != null && !stringEquals(group.getName(),groupToUpdateInDB.getgroupName())){
//we need to check if the new id exists in the database
String newGroupId = createNewPDPGroupId(group.getName());
Query checkGroupQuery = em.createQuery("SELECT g FROM GroupEntity g WHERE g.groupId=:groupId AND g.deleted=:deleted");
PolicyLogger.error("The new group name already exists, group id "+newGroupId);
throw new PersistenceException("The new group name already exists, group id "+newGroupId);
}
- groupToUpdate.setGroupId(newGroupId);
- groupToUpdate.setGroupName(group.getName());
+ groupToUpdateInDB.setGroupId(newGroupId);
+ groupToUpdateInDB.setGroupName(group.getName());
this.newGroupId = group.getId();
}
em.flush();
- this.groupId = groupToUpdate.getGroupKey();
+ this.groupId = groupToUpdateInDB.getGroupKey();
}
}
try{
while(policyIt.hasNext()){
PolicyEntity pol = policyIt.next();
- if(getPolicyNameAndVersionFromPolicyFileName(pol.getPolicyName())[0].equals(policyName)){
+ if(policy.getScope().equals(pol.getScope()) &&
+ getPolicyNameAndVersionFromPolicyFileName(pol.getPolicyName())[0].equals(policyName)) {
policyIt.remove();
}
}
em.flush();
// After adding policy to the db group we need to make sure the filesytem group is in sync with the db group
+ StdPDPGroup pdpGroup = null;
+ StdPDPGroup updatedGroup = null;
try {
- StdPDPGroup pdpGroup = (StdPDPGroup) papEngine.getGroup(group.getGroupId());
- return synchronizeGroupPoliciesInFileSystem(pdpGroup, group);
+ pdpGroup = (StdPDPGroup) papEngine.getGroup(group.getGroupId());
+ updatedGroup = synchronizeGroupPoliciesInFileSystem(pdpGroup, group);
} catch (PAPException e) {
logger.debug(e);
PolicyLogger.error("PolicyDBDao: Could not synchronize the filesystem group with the database group. " + e.getMessage());
}
-
- return null;
+
+ return updatedGroup;
}
}
String computeScope(String fullPath, String pathToExclude){
return PolicyDBDao.computeScope(fullPath, pathToExclude);
}
- String encryptPassword(String password) throws InvalidKeyException, UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException{
- return PolicyDBDao.encryptPassword(password);
- }
- String decryptPassword(String password) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException{
- return PolicyDBDao.decryptPassword(password);
- }
String getDescriptionFromXacml(String xacmlData){
return PolicyDBDao.getDescriptionFromXacml(xacmlData);
}
}
}
-}
+}
\ No newline at end of file