CachedMapBasedSimplePolicyRepository.java

  1. /*
  2.  * GovWay - A customizable API Gateway
  3.  * https://govway.org
  4.  *
  5.  * Copyright (c) 2005-2025 Link.it srl (https://link.it).
  6.  *
  7.  * This program is free software: you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License version 3, as published by
  9.  * the Free Software Foundation.
  10.  *
  11.  * This program is distributed in the hope that it will be useful,
  12.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.  * GNU General Public License for more details.
  15.  *
  16.  * You should have received a copy of the GNU General Public License
  17.  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18.  *
  19.  */

  20. package org.openspcoop2.utils.xacml;

  21. import java.io.ByteArrayOutputStream;
  22. import java.io.IOException;
  23. import java.math.BigInteger;
  24. import java.security.MessageDigest;
  25. import java.security.NoSuchAlgorithmException;
  26. import java.util.ArrayList;
  27. import java.util.Arrays;
  28. import java.util.Collection;
  29. import java.util.HashMap;
  30. import java.util.List;
  31. import java.util.Map;

  32. import org.herasaf.xacml.core.WritingException;
  33. import org.herasaf.xacml.core.context.impl.AttributeType;
  34. import org.herasaf.xacml.core.context.impl.RequestType;
  35. import org.herasaf.xacml.core.context.impl.ResourceType;
  36. import org.herasaf.xacml.core.dataTypeAttribute.impl.StringDataTypeAttribute;
  37. import org.herasaf.xacml.core.function.Function;
  38. import org.herasaf.xacml.core.function.impl.equalityPredicates.StringEqualFunction;
  39. import org.herasaf.xacml.core.policy.Evaluatable;
  40. import org.herasaf.xacml.core.policy.EvaluatableID;
  41. import org.herasaf.xacml.core.policy.PolicyMarshaller;
  42. import org.herasaf.xacml.core.policy.impl.ActionAttributeDesignatorType;
  43. import org.herasaf.xacml.core.policy.impl.ActionMatchType;
  44. import org.herasaf.xacml.core.policy.impl.ActionsType;
  45. import org.herasaf.xacml.core.policy.impl.EvaluatableIDImpl;
  46. import org.herasaf.xacml.core.policy.impl.ObjectFactory;
  47. import org.herasaf.xacml.core.policy.impl.PolicyType;
  48. import org.herasaf.xacml.core.policy.impl.ResourceAttributeDesignatorType;
  49. import org.herasaf.xacml.core.policy.impl.ResourceMatchType;
  50. import org.herasaf.xacml.core.policy.impl.ResourcesType;
  51. import org.herasaf.xacml.core.policy.impl.TargetType;
  52. import org.herasaf.xacml.core.simplePDP.OrderedMapBasedSimplePolicyRepository;
  53. import org.slf4j.Logger;

  54. /**
  55.  * CachedMapBasedSimplePolicyRepository
  56.  *
  57.  * @author Bussu Giovanni (bussu@link.it)
  58.  * @author $Author$
  59.  * @version $Rev$, $Date$
  60.  */
  61. public class CachedMapBasedSimplePolicyRepository extends
  62. OrderedMapBasedSimplePolicyRepository {

  63.     private Map<EvaluatableID, String> cacheMap;
  64.     private MessageDigest md;
  65.     private Logger log;
  66.     /**
  67.      * Indicazione se usare la risorsa (con attribute id dato da RESOURCE_ATTRIBUTE_ID_TO_MATCH)
  68.      * o la action (con attribute id dato da ACTION_ATTRIBUTE_ID_TO_MATCH)
  69.      * per capire qual e' la policy da usare
  70.      */
  71.     public static final boolean USE_RESOURCE_TO_MATCH_POLICY = true;
  72.    
  73.    
  74.     public static final String RESOURCE_ATTRIBUTE_ID_TO_MATCH = "___resource-id___";
  75.     public static final String ACTION_ATTRIBUTE_ID_TO_MATCH = "urn:oasis:names:tc:xacml:1.0:action:action-id";

  76.     public CachedMapBasedSimplePolicyRepository(Logger log) throws PolicyException {
  77.         super();
  78.         this.cacheMap = new HashMap<EvaluatableID, String>();
  79.         this.log = log;
  80.         try {
  81.             this.md = MessageDigest.getInstance("SHA-256");
  82.         } catch (NoSuchAlgorithmException e) {
  83.             throw new PolicyException(e);
  84.         }
  85.     }

  86.     public boolean existsPolicy(EvaluatableID id, String policyString) {
  87.         return this.cacheMap.containsKey(id) && this.cacheMap.get(id).equals(this.hash(policyString));
  88.     }

  89.     public void deploy(Evaluatable evaluatable, String policyString) {
  90.         if(super.individualEvaluatables.containsKey(evaluatable.getId())) {
  91.             this.undeploy(evaluatable.getId());
  92.         }
  93.         super.deploy(evaluatable);
  94.         this.cacheMap.put(evaluatable.getId(), this.hash(policyString));
  95.     }

  96.     @Override
  97.     public void deploy(Evaluatable evaluatable) {
  98.         if(USE_RESOURCE_TO_MATCH_POLICY) {
  99.             addResourceToPolicy((PolicyType)evaluatable, evaluatable.getId().toString());
  100.         } else {
  101.             addActionToPolicy((PolicyType)evaluatable, evaluatable.getId().toString());
  102.         }

  103.         if(super.individualEvaluatables.containsKey(evaluatable.getId())) {
  104.             this.undeploy(evaluatable.getId());
  105.         }
  106.         super.deploy(evaluatable);
  107.         this.cacheMap.put(evaluatable.getId(), this.hash(unmarshallPolicy(evaluatable)));
  108.     }

  109.     private static void addActionToPolicy(PolicyType policy1, String key) {
  110.        
  111.         ObjectFactory factory = new ObjectFactory();
  112.        
  113.         TargetType target = factory.createTargetType();
  114.        
  115.         if(policy1.getTarget() != null) {
  116.             target = policy1.getTarget();
  117.         }

  118.         org.herasaf.xacml.core.policy.impl.ActionType action =  factory.createActionType();

  119.         ActionMatchType actionMatch = factory.createActionMatchType();
  120.         Function function = new StringEqualFunction();
  121.         actionMatch.setMatchFunction(function);
  122.         ActionAttributeDesignatorType attributeDesignator = factory.createActionAttributeDesignatorType();
  123.         attributeDesignator.setMustBePresent(true);
  124.         attributeDesignator.setAttributeId(ACTION_ATTRIBUTE_ID_TO_MATCH);
  125.         attributeDesignator.setDataType(new StringDataTypeAttribute());
  126.         actionMatch.setActionAttributeDesignator(attributeDesignator);
  127.         org.herasaf.xacml.core.policy.impl.AttributeValueType attributeValue = new org.herasaf.xacml.core.policy.impl.AttributeValueType();
  128.         attributeValue.getContent().add(key);
  129.         attributeValue.setDataType(new StringDataTypeAttribute());
  130.         actionMatch.setAttributeValue(attributeValue);
  131.         action.getActionMatches().add(actionMatch);
  132.         ActionsType actions = factory.createActionsType();
  133.         actions.getActions().add(action);
  134.         target.setActions(actions);
  135.         policy1.setTarget(target);
  136.     }

  137.     private static void addResourceToPolicy(PolicyType policy1, String key) {
  138.        
  139.         ObjectFactory factory = new ObjectFactory();
  140.        
  141.         TargetType target = factory.createTargetType();
  142.        
  143.         if(policy1.getTarget() != null) {
  144.             target = policy1.getTarget();
  145.         }

  146.         org.herasaf.xacml.core.policy.impl.ResourceType resource =  factory.createResourceType();

  147.         ResourceMatchType resourceMatch = factory.createResourceMatchType();
  148.         Function function = new StringEqualFunction();
  149.         resourceMatch.setMatchFunction(function);
  150.         ResourceAttributeDesignatorType attributeDesignator = factory.createResourceAttributeDesignatorType();
  151.         attributeDesignator.setMustBePresent(true);
  152.         attributeDesignator.setAttributeId(RESOURCE_ATTRIBUTE_ID_TO_MATCH);
  153.         attributeDesignator.setDataType(new StringDataTypeAttribute());
  154.         resourceMatch.setResourceAttributeDesignator(attributeDesignator);
  155.         org.herasaf.xacml.core.policy.impl.AttributeValueType attributeValue = new org.herasaf.xacml.core.policy.impl.AttributeValueType();
  156.         attributeValue.getContent().add(key);
  157.         attributeValue.setDataType(new StringDataTypeAttribute());
  158.         resourceMatch.setAttributeValue(attributeValue);
  159.         resource.getResourceMatches().add(resourceMatch);
  160.         ResourcesType resources = factory.createResourcesType();
  161.         resources.getResources().add(resource);
  162.         target.setResources(resources);
  163.         policy1.setTarget(target);
  164.     }

  165.     public String unmarshallPolicy(Evaluatable eval) {
  166.         ByteArrayOutputStream baos = null;
  167.         try{
  168.             baos = new ByteArrayOutputStream();
  169.             PolicyMarshaller.marshal(eval, baos);
  170.             return baos.toString();
  171.         } catch(WritingException e) {
  172.             return null;
  173.         } finally {
  174.             if(baos != null) {
  175.                 try {
  176.                     baos.flush();
  177.                 } catch (IOException e) {}
  178.                 try {
  179.                     baos.close();
  180.                 } catch (IOException e) {}
  181.             }
  182.         }
  183.     }
  184.    
  185.     public void deploy(Collection<Evaluatable> evaluatables, String policyString) {
  186.         for (Evaluatable eval : evaluatables) {
  187.             this.deploy(eval, this.hash(policyString));
  188.         }
  189.     }

  190.     @Override
  191.     public void undeploy(EvaluatableID evaluatable) {
  192.         super.undeploy(evaluatable);
  193.         this.cacheMap.remove(evaluatable);
  194.     }

  195.     public void undeploy(Collection<EvaluatableID> evaluatables, String policyString) {
  196.         super.undeploy(evaluatables);
  197.         for (EvaluatableID eval : evaluatables) {
  198.             this.cacheMap.remove(eval);
  199.         }
  200.     }


  201.     private String hash(String policyString) {
  202.         String digest = toHex(this.md.digest(policyString.getBytes()));
  203.         return digest;
  204.     }

  205.     private static String toHex(byte[] bytes) {
  206.         BigInteger bi = new BigInteger(1, bytes);
  207.         return String.format("%0" + (bytes.length << 1) + "X", bi);
  208.     }
  209.    
  210.     @Override
  211.     public List<Evaluatable> getEvaluatables(RequestType request) {
  212.         try {
  213.             String key = getKey(request);
  214.             this.log.info("KEY: " + key);
  215.             if(key != null) {
  216.                 EvaluatableIDImpl policyId = new EvaluatableIDImpl(key);
  217.                 Evaluatable eval = super.getEvaluatable(policyId);
  218.                 this.log.info("eval is null? " + (eval == null));
  219.                 if(eval != null) {
  220.                     ByteArrayOutputStream baos = new ByteArrayOutputStream();
  221.                     PolicyMarshaller.marshal(eval, baos);
  222.                     this.log.info("eval:" +new String(baos.toByteArray()));
  223.                 }
  224.                 return Arrays.asList(eval);
  225.             } else {
  226.                 return new ArrayList<Evaluatable>();
  227.             }
  228.         } catch(Exception e){}
  229.         return super.getEvaluatables(request);              
  230.     }

  231.     private String getKey(RequestType request) {
  232.         try {
  233.             if(USE_RESOURCE_TO_MATCH_POLICY) {
  234.                 for(ResourceType resource: request.getResources()) {
  235.                     for(AttributeType attribute: resource.getAttributes()) {
  236.                         if(attribute.getAttributeId().equals(RESOURCE_ATTRIBUTE_ID_TO_MATCH)) {
  237.                             return (String) attribute.getAttributeValues().get(0).getContent().get(0);
  238.                         }
  239.                     }
  240.                 }
  241.                 return null;
  242.             } else {
  243.                 for(AttributeType attribute: request.getAction().getAttributes()) {
  244.                     if(attribute.getAttributeId().equals(ACTION_ATTRIBUTE_ID_TO_MATCH)) {
  245.                         return (String) attribute.getAttributeValues().get(0).getContent().get(0);
  246.                     }
  247.                 }
  248.                 return null;
  249.             }
  250.            
  251.         } catch(Exception e) {
  252.             return null;
  253.         }
  254.     }

  255. }