JOSEUtils.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.security.message.jose;

  21. import java.net.Proxy;
  22. import java.net.URI;
  23. import java.security.cert.Certificate;
  24. import java.security.cert.X509Certificate;
  25. import java.util.ArrayList;
  26. import java.util.Enumeration;
  27. import java.util.HashMap;
  28. import java.util.List;
  29. import java.util.Map;
  30. import java.util.Properties;

  31. import org.apache.commons.lang.StringUtils;
  32. import org.apache.cxf.rt.security.rs.RSSecurityConstants;
  33. import org.openspcoop2.core.commons.DBUtils;
  34. import org.openspcoop2.core.constants.CostantiConnettori;
  35. import org.openspcoop2.core.mvc.properties.utils.MultiPropertiesUtilities;
  36. import org.openspcoop2.message.OpenSPCoop2Message;
  37. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  38. import org.openspcoop2.security.SecurityException;
  39. import org.openspcoop2.security.keystore.BYOKUnwrapManager;
  40. import org.openspcoop2.security.keystore.CRLCertstore;
  41. import org.openspcoop2.security.keystore.HttpStore;
  42. import org.openspcoop2.security.keystore.KeyPairStore;
  43. import org.openspcoop2.security.keystore.MerlinKeystore;
  44. import org.openspcoop2.security.keystore.MerlinTruststore;
  45. import org.openspcoop2.security.keystore.PublicKeyStore;
  46. import org.openspcoop2.security.keystore.cache.GestoreKeystoreCache;
  47. import org.openspcoop2.security.message.constants.SecurityConstants;
  48. import org.openspcoop2.utils.LoggerWrapperFactory;
  49. import org.openspcoop2.utils.Utilities;
  50. import org.openspcoop2.utils.UtilsException;
  51. import org.openspcoop2.utils.certificate.JWKSet;
  52. import org.openspcoop2.utils.certificate.KeyStore;
  53. import org.openspcoop2.utils.certificate.KeystoreType;
  54. import org.openspcoop2.utils.certificate.KeystoreUtils;
  55. import org.openspcoop2.utils.certificate.byok.BYOKProvider;
  56. import org.openspcoop2.utils.certificate.byok.BYOKRequestParams;
  57. import org.openspcoop2.utils.certificate.remote.IRemoteStoreProvider;
  58. import org.openspcoop2.utils.certificate.remote.RemoteKeyType;
  59. import org.openspcoop2.utils.certificate.remote.RemoteStoreConfig;
  60. import org.openspcoop2.utils.security.JOSESerialization;
  61. import org.openspcoop2.utils.security.JWTOptions;
  62. import org.openspcoop2.utils.security.JwtHeaders;
  63. import org.openspcoop2.utils.transport.http.HttpForwardProxyConfig;
  64. import org.openspcoop2.utils.transport.http.HttpForwardProxyOptions;
  65. import org.openspcoop2.utils.transport.http.HttpOptions;
  66. import org.openspcoop2.utils.transport.http.HttpProxyOptions;
  67. import org.openspcoop2.utils.transport.http.HttpsOptions;
  68. import org.slf4j.Logger;

  69. /**    
  70.  * JOSEUtils
  71.  *
  72.  * @author Poli Andrea (poli@link.it)
  73.  * @author $Author$
  74.  * @version $Rev$, $Date$
  75.  */
  76. public class JOSEUtils {

  77.     private JOSEUtils() {}
  78.    
  79.     public static JOSESerialization toJOSESerialization(String mode) throws SecurityException {
  80.         if(SecurityConstants.SIGNATURE_MODE_JSON.equals(mode)) {
  81.             return JOSESerialization.JSON;
  82.         }
  83.         else if(SecurityConstants.SIGNATURE_MODE_COMPACT.equals(mode)) {
  84.             return JOSESerialization.COMPACT;
  85.         }
  86.         else {
  87.             throw new SecurityException("Mode '"+mode+"' unsupported");
  88.         }
  89.     }
  90.    
  91.     public static JwtHeaders getJwtHeaders(Map<String, Object> properties, OpenSPCoop2Message message) throws SecurityException {
  92.         return getJwtHeaders(properties, message, null, null, null);
  93.     }
  94.     public static JwtHeaders getJwtHeaders(Map<String, Object> properties, OpenSPCoop2Message message,
  95.             String alias) throws SecurityException {
  96.         return getJwtHeaders(properties, message, alias, null, null);
  97.     }
  98.     public static JwtHeaders getJwtHeaders(Map<String, Object> properties, OpenSPCoop2Message message,
  99.             String alias, JWKSet jwkSet) throws SecurityException {
  100.         return getJwtHeaders(properties, message, alias, jwkSet, null);
  101.     }
  102.     public static JwtHeaders getJwtHeaders(Map<String, Object> properties, OpenSPCoop2Message message,
  103.             String alias, KeyStore keystore) throws SecurityException {
  104.         return getJwtHeaders(properties, message, alias, null, keystore);
  105.     }
  106.     private static JwtHeaders getJwtHeaders(Map<String, Object> properties, OpenSPCoop2Message message,
  107.             String alias, JWKSet jwkSet,
  108.             KeyStore keystore) throws SecurityException {
  109.         JwtHeaders hdrs = new JwtHeaders();
  110.        
  111.         if(properties.containsKey(SecurityConstants.JOSE_KID)) {
  112.             String value = (String) properties.get(SecurityConstants.JOSE_KID);
  113.             if(value!=null) {
  114.                 value = value.trim();
  115.             }
  116.             if(SecurityConstants.JOSE_KID_TRUE.equalsIgnoreCase(value)) {
  117.                 hdrs.setKid(alias);
  118.             }
  119.         }
  120.         else if(properties.containsKey(SecurityConstants.JOSE_KID_CUSTOM)) {
  121.             String value = (String) properties.get(SecurityConstants.JOSE_KID_CUSTOM);
  122.             if(value!=null) {
  123.                 value = value.trim();
  124.                 hdrs.setKid(value);
  125.             }
  126.         }
  127.        
  128.         if(properties.containsKey(SecurityConstants.JOSE_INCLUDE_CERT)) {
  129.             String value = (String) properties.get(SecurityConstants.JOSE_INCLUDE_CERT);
  130.             if(value!=null) {
  131.                 value = value.trim();
  132.             }
  133.             if(SecurityConstants.JOSE_INCLUDE_CERT_TRUE.equalsIgnoreCase(value)) {
  134.                 try {
  135.                     if(alias==null) {
  136.                         throw new SecurityException("Alias undefined (required for include cert)");
  137.                     }
  138.                     if(jwkSet!=null) {
  139.                         hdrs.setJwKey(jwkSet.getJsonWebKeys(), alias);
  140.                     }
  141.                     else if(keystore!=null) {
  142.                        
  143.                         boolean certChain = false;
  144.                         if(properties.containsKey(SecurityConstants.JOSE_INCLUDE_CERT_CHAIN)) {
  145.                             String valueChain = (String) properties.get(SecurityConstants.JOSE_INCLUDE_CERT_CHAIN);
  146.                             if(valueChain!=null) {
  147.                                 valueChain = valueChain.trim();
  148.                             }
  149.                             if(SecurityConstants.JOSE_INCLUDE_CERT_CHAIN_TRUE.equalsIgnoreCase(valueChain)) {
  150.                                 certChain = true;
  151.                             }
  152.                         }
  153.                        
  154.                         /**
  155.                         System.out.println("\n\n==============================================");
  156.                         System.out.println("ALIAS: ["+alias+"]");
  157.                         Certificate[] chain = keystore.getCertificateChain(alias);
  158.                         if(chain!=null) {
  159.                             System.out.println("CHAINS: ["+chain.length+"]");
  160.                         }
  161.                         for (int i = 0; i < chain.length; i++) {
  162.                             System.out.println("CHAIN["+i+"]: ["+(((X509Certificate)chain[i]).getSubjectX500Principal().toString()+"]"));
  163.                         }
  164.                         System.out.println("CERT: ["+(((X509Certificate)keystore.getCertificate(alias)).getSubjectX500Principal().toString()+"]"));
  165.                         */
  166.                         if(certChain) {
  167.                             Certificate[] certificateChain = keystore.getCertificateChain(alias);
  168.                             if(certificateChain!=null && certificateChain.length>0) {
  169.                                 for (int i = 0; i < certificateChain.length; i++) {
  170.                                     hdrs.addX509cert((X509Certificate)certificateChain[i]);
  171.                                 }
  172.                             }
  173.                             else {
  174.                                 hdrs.addX509cert((X509Certificate)keystore.getCertificate(alias));
  175.                             }
  176.                         }
  177.                         else {
  178.                             hdrs.addX509cert((X509Certificate)keystore.getCertificate(alias));
  179.                         }
  180.                         hdrs.setAddX5C(true);
  181.                     }
  182.                 }catch(Exception e) {
  183.                     throw new SecurityException(e.getMessage(),e);
  184.                 }
  185.             }
  186.         }
  187.        
  188.         if(properties.containsKey(SecurityConstants.JOSE_INCLUDE_CERT_SHA)) {
  189.             String value = (String) properties.get(SecurityConstants.JOSE_INCLUDE_CERT_SHA);
  190.             if(value!=null) {
  191.                 value = value.trim();
  192.             }
  193.             if(hdrs.getX509c()==null || hdrs.getX509c().isEmpty()) {
  194.                 if(keystore==null) {
  195.                     throw new SecurityException("Keystore undefined (required for digest '"+value+"')");
  196.                 }
  197.                 if(alias==null) {
  198.                     throw new SecurityException("Alias undefined (required for digest '"+value+"')");
  199.                 }
  200.                 Certificate cert = null;
  201.                 try {
  202.                     cert = keystore.getCertificate(alias);
  203.                 }catch(Exception e) {
  204.                     throw new SecurityException(e.getMessage(),e);
  205.                 }
  206.                 if(cert==null) {
  207.                     throw new SecurityException("Certificate with alias '"+alias+"' not found (required for digest '"+value+"')");
  208.                 }
  209.                 hdrs.addX509cert((X509Certificate)cert);
  210.             }
  211.             if(SecurityConstants.JOSE_INCLUDE_CERT_SHA_1.equalsIgnoreCase(value)) {
  212.                 try {
  213.                     hdrs.setX509IncludeCertSha1(true);
  214.                 }catch(Exception e) {
  215.                     throw new SecurityException(e.getMessage(),e);
  216.                 }
  217.             }
  218.             else if(SecurityConstants.JOSE_INCLUDE_CERT_SHA_256.equalsIgnoreCase(value)) {
  219.                 try {
  220.                     hdrs.setX509IncludeCertSha256(true);
  221.                 }catch(Exception e) {
  222.                     throw new SecurityException(e.getMessage(),e);
  223.                 }
  224.             }
  225.             else {
  226.                 throw new SecurityException("Value '"+value+"' unknowkn for property '"+SecurityConstants.JOSE_INCLUDE_CERT_SHA+"'");
  227.             }
  228.         }
  229.        
  230.         if(properties.containsKey(SecurityConstants.JOSE_CONTENT_TYPE)) {
  231.             String value = (String) properties.get(SecurityConstants.JOSE_CONTENT_TYPE);
  232.             if(value!=null) {
  233.                 value = value.trim();
  234.             }
  235.             if(SecurityConstants.JOSE_CONTENT_TYPE_TRUE.equalsIgnoreCase(value)) {
  236.                 try {
  237.                     hdrs.setContentType(message.getContentType());
  238.                 }catch(Exception e) {
  239.                     throw new SecurityException(e.getMessage(),e);
  240.                 }
  241.             }
  242.         }
  243.        
  244.         if(properties.containsKey(SecurityConstants.JOSE_TYPE)) {
  245.             String value = (String) properties.get(SecurityConstants.JOSE_TYPE);
  246.             if(value!=null) {
  247.                 value = value.trim();
  248.             }
  249.             if(value!=null && !StringUtils.isEmpty(value)) {
  250.                 hdrs.setType(value);
  251.             }
  252.         }
  253.        
  254.         if(properties.containsKey(SecurityConstants.JOSE_X509_URL)) {
  255.             String value = (String) properties.get(SecurityConstants.JOSE_X509_URL);
  256.             if(value!=null) {
  257.                 value = value.trim();
  258.             }
  259.             if(value!=null && !StringUtils.isEmpty(value)) {
  260.                 try {
  261.                     hdrs.setX509Url(new URI(value));
  262.                 }catch(Exception e) {
  263.                     throw new SecurityException(e.getMessage(),e);
  264.                 }
  265.             }
  266.         }
  267.        
  268.         if(properties.containsKey(SecurityConstants.JOSE_JWK_SET_URL)) {
  269.             String value = (String) properties.get(SecurityConstants.JOSE_JWK_SET_URL);
  270.             if(value!=null) {
  271.                 value = value.trim();
  272.             }
  273.             if(value!=null && !StringUtils.isEmpty(value)) {
  274.                 try {
  275.                     hdrs.setJwkUrl(new URI(value));
  276.                 }catch(Exception e) {
  277.                     throw new SecurityException(e.getMessage(),e);
  278.                 }
  279.             }
  280.         }
  281.        
  282.         if(properties.containsKey(SecurityConstants.JOSE_CRITICAL_HEADERS)) {
  283.             String value = (String) properties.get(SecurityConstants.JOSE_CRITICAL_HEADERS);
  284.             if(value!=null) {
  285.                 value = value.trim();
  286.             }
  287.             if(value!=null && !StringUtils.isEmpty(value)) {
  288.                 if(value.contains(SecurityConstants.JOSE_CRITICAL_HEADERS_SEPARATOR)) {
  289.                     String [] tmp = value.split(SecurityConstants.JOSE_CRITICAL_HEADERS_SEPARATOR);
  290.                     for (String v : tmp) {
  291.                         if(v!=null) {
  292.                             v = v.trim();
  293.                             if(!StringUtils.isEmpty(v)) {
  294.                                 hdrs.addCriticalHeader(v);
  295.                             }
  296.                         }
  297.                     }
  298.                 }
  299.                 else {
  300.                     hdrs.addCriticalHeader(value);
  301.                 }
  302.             }
  303.         }
  304.        
  305.         try {
  306.             Properties pConvert = new Properties();
  307.             pConvert.putAll(properties);
  308.             Properties pExts = Utilities.readProperties(SecurityConstants.JOSE_EXT_HEADER_PREFIX, pConvert);
  309.             if(pExts!=null && pExts.size()>0) {
  310.                 Enumeration<?> names = pExts.propertyNames();
  311.                 while (names.hasMoreElements()) {
  312.                     Object oName = names.nextElement();
  313.                     if(oName instanceof String) {
  314.                         String name = (String) oName;
  315.                         if(name!=null) {
  316.                             name = name.trim();
  317.                             if(name.endsWith(SecurityConstants.JOSE_EXT_HEADER_SUFFIX_NAME)) {
  318.                                 String hdrName = pExts.getProperty(name);
  319.                                 String confName = name.substring(0, name.indexOf(SecurityConstants.JOSE_EXT_HEADER_SUFFIX_NAME));
  320.                                 String nameValue = confName+SecurityConstants.JOSE_EXT_HEADER_SUFFIX_VALUE;
  321.                                 String hdrValue = pExts.getProperty(nameValue);
  322.                                 if(hdrValue==null) {
  323.                                     throw new SecurityException("Property '"+SecurityConstants.JOSE_EXT_HEADER_PREFIX+nameValue+"' not found");
  324.                                 }
  325.                                 hdrs.addExtension(hdrName, hdrValue);
  326.                             }
  327.                         }
  328.                     }
  329.                 }
  330.             }
  331.         }catch(Exception e) {
  332.             throw new SecurityException(e.getMessage(),e);
  333.         }
  334.        
  335.         return hdrs;
  336.        
  337.        
  338.     }

  339.    
  340.     public static boolean useJwtHeadersMapProperties(Map<String, Properties> properties, JWTOptions options) {
  341.         Properties defaultProperties = MultiPropertiesUtilities.getDefaultProperties(properties);
  342.         return useJwtHeaders(defaultProperties, options);
  343.     }
  344.     public static boolean useJwtHeadersMap(Map<String, Object> propertiesParam, JWTOptions options) {
  345.         Properties properties = new Properties();
  346.         properties.putAll(propertiesParam);
  347.         return useJwtHeaders(properties, options);
  348.     }
  349.     public static boolean useJwtHeaders(Properties properties, JWTOptions options) {
  350.    
  351.         boolean useJwtHeaders = false;
  352.         if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS)) {
  353.             String value = (String) properties.get(SecurityConstants.JOSE_USE_HEADERS);
  354.             if(value!=null) {
  355.                 value = value.trim();
  356.                 useJwtHeaders = SecurityConstants.JOSE_USE_HEADERS_TRUE.equalsIgnoreCase(value);
  357.             }
  358.            
  359.             if(useJwtHeaders) {
  360.                
  361.                 if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS_X5C)) {
  362.                     value = (String) properties.get(SecurityConstants.JOSE_USE_HEADERS_X5C);
  363.                     if(value!=null) {
  364.                         value = value.trim();
  365.                         options.setPermitUseHeaderX5C(SecurityConstants.JOSE_USE_HEADERS_TRUE.equalsIgnoreCase(value));
  366.                     }
  367.                 }
  368.                
  369.                 if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS_X5U)) {
  370.                     value = (String) properties.get(SecurityConstants.JOSE_USE_HEADERS_X5U);
  371.                     if(value!=null) {
  372.                         value = value.trim();
  373.                         options.setPermitUseHeaderX5U(SecurityConstants.JOSE_USE_HEADERS_TRUE.equalsIgnoreCase(value));
  374.                     }
  375.                 }
  376.                
  377.                 if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS_X5T)) {
  378.                     value = (String) properties.get(SecurityConstants.JOSE_USE_HEADERS_X5T);
  379.                     if(value!=null) {
  380.                         value = value.trim();
  381.                         options.setPermitUseHeaderX5T(SecurityConstants.JOSE_USE_HEADERS_TRUE.equalsIgnoreCase(value));
  382.                     }
  383.                 }
  384.                
  385.                 if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS_X5T_256)) {
  386.                     value = (String) properties.get(SecurityConstants.JOSE_USE_HEADERS_X5T_256);
  387.                     if(value!=null) {
  388.                         value = value.trim();
  389.                         options.setPermitUseHeaderX5T_256(SecurityConstants.JOSE_USE_HEADERS_TRUE.equalsIgnoreCase(value));
  390.                     }
  391.                 }
  392.                
  393.                 if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS_JWK)) {
  394.                     value = (String) properties.get(SecurityConstants.JOSE_USE_HEADERS_JWK);
  395.                     if(value!=null) {
  396.                         value = value.trim();
  397.                         options.setPermitUseHeaderJWK(SecurityConstants.JOSE_USE_HEADERS_TRUE.equalsIgnoreCase(value));
  398.                     }
  399.                 }
  400.                
  401.                 if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS_JKU)) {
  402.                     value = (String) properties.get(SecurityConstants.JOSE_USE_HEADERS_JKU);
  403.                     if(value!=null) {
  404.                         value = value.trim();
  405.                         options.setPermitUseHeaderJKU(SecurityConstants.JOSE_USE_HEADERS_TRUE.equalsIgnoreCase(value));
  406.                     }
  407.                 }
  408.                
  409.                 if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS_KID)) {
  410.                     value = (String) properties.get(SecurityConstants.JOSE_USE_HEADERS_KID);
  411.                     if(value!=null) {
  412.                         value = value.trim();
  413.                         options.setPermitUseHeaderKID(SecurityConstants.JOSE_USE_HEADERS_TRUE.equalsIgnoreCase(value));
  414.                     }
  415.                 }
  416.                
  417.             }
  418.         }
  419.        
  420.         return useJwtHeaders;
  421.     }
  422.    

  423.     public static Properties toSslConfigJwtUrlHeader(Map<String, Object> propertiesParam) {
  424.         Properties properties = null;
  425.         if(propertiesParam.containsKey(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_FILE)) {
  426.             String keystoreFile = (String) propertiesParam.get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_FILE);
  427.             if(keystoreFile!=null) {
  428.                
  429.                 properties = new Properties();
  430.                
  431.                 properties.put(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_FILE, keystoreFile);
  432.                
  433.                 String keystoreType = (String) propertiesParam.get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_TYPE);
  434.                 if(keystoreType!=null) {
  435.                     properties.put(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_TYPE, keystoreType);
  436.                 }
  437.                
  438.                 String keystorePassword = (String) propertiesParam.get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_PASSWORD);
  439.                 if(keystorePassword!=null) {
  440.                     properties.put(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_PASSWORD, keystorePassword);
  441.                 }
  442.             }
  443.         }
  444.         return properties;
  445.     }
  446.     public static KeyStore readTrustStoreSsl(RequestInfo requestInfo, Map<String, Object> propertiesParam) throws SecurityException {
  447.         Properties properties = new Properties();
  448.         properties.putAll(propertiesParam);
  449.         return readTrustStoreSsl(requestInfo, properties);
  450.     }
  451.     public static KeyStore readTrustStoreSsl(RequestInfo requestInfo, Properties properties) throws SecurityException {
  452.         return readTrustStoreEngine(requestInfo, properties, SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_FILE,
  453.                 SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_TYPE,
  454.                 SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_PASSWORD);
  455.     }

  456.     public static KeyStore readTrustStoreJwtX509Cert(RequestInfo requestInfo, Map<String, Object> propertiesParam) throws SecurityException {
  457.         Properties properties = new Properties();
  458.         properties.putAll(propertiesParam);
  459.         return readTrustStoreJwtX509Cert(requestInfo, properties);
  460.     }
  461.     public static KeyStore readTrustStoreJwtX509Cert(RequestInfo requestInfo, Properties properties) throws SecurityException {
  462.         return readTrustStoreEngine(requestInfo, properties, SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_FILE,
  463.                 SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_TYPE,
  464.                 SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_PASSWORD);
  465.     }

  466.     public static boolean isJWKSetTrustStore(Map<String, Object> propertiesParam) {
  467.         Properties properties = new Properties();
  468.         properties.putAll(propertiesParam);
  469.         return isJWKSetTrustStore(properties);
  470.     }
  471.     public static boolean isJWKSetTrustStore(Properties properties) {
  472.         if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_TYPE)) {
  473.             String truststoreType = (String) properties.get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_TYPE);
  474.             if(truststoreType!=null) {
  475.                 return SecurityConstants.KEYSTORE_TYPE_JWK_VALUE.equalsIgnoreCase(truststoreType);
  476.             }
  477.         }
  478.         return false;
  479.     }
  480.        
  481.     public static JWKSet readTrustStoreJwtJsonWebKeysCert(RequestInfo requestInfo, Map<String, Object> propertiesParam) throws SecurityException {
  482.         Properties properties = new Properties();
  483.         properties.putAll(propertiesParam);
  484.         return readTrustStoreJwtJsonWebKeysCert(requestInfo, properties);
  485.     }
  486.     public static JWKSet readTrustStoreJwtJsonWebKeysCert(RequestInfo requestInfo, Properties properties) throws SecurityException {
  487.        
  488.         if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_FILE)) {
  489.             String truststoreFile = (String) properties.get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_FILE);
  490.             if(truststoreFile!=null) {
  491.                 truststoreFile = truststoreFile.trim();
  492.             }
  493.             else {
  494.                 throw new SecurityException("Truststore value in property '"+SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_FILE+"' is null");
  495.             }
  496.             try {
  497.                 return GestoreKeystoreCache.getJwkSetStore(requestInfo, truststoreFile).getJwkSet();
  498.             }catch(Exception e) {
  499.                 throw new SecurityException(e.getMessage(),e);
  500.             }
  501.         }
  502.        
  503.         return null;
  504.     }
  505.    
  506.     public static boolean isPublicKeyTrustStore(Map<String, Object> propertiesParam) {
  507.         Properties properties = new Properties();
  508.         properties.putAll(propertiesParam);
  509.         return isPublicKeyTrustStore(properties);
  510.     }
  511.     public static boolean isPublicKeyTrustStore(Properties properties) {
  512.         if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_TYPE)) {
  513.             String truststoreType = (String) properties.get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_TYPE);
  514.             if(truststoreType!=null) {
  515.                 return SecurityConstants.KEYSTORE_TYPE_PUBLIC_KEY_VALUE.equalsIgnoreCase(truststoreType);
  516.             }
  517.         }
  518.         return false;
  519.     }
  520.    
  521.     public static JWKSet readTrustStorePublicKey(RequestInfo requestInfo, Map<String, Object> propertiesParam) throws SecurityException {
  522.         Properties properties = new Properties();
  523.         properties.putAll(propertiesParam);
  524.         return readTrustStorePublicKey(requestInfo, properties);
  525.     }
  526.     public static JWKSet readTrustStorePublicKey(RequestInfo requestInfo, Properties properties) throws SecurityException {
  527.        
  528.         if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_FILE)) {
  529.             String truststoreFile = (String) properties.get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_FILE);
  530.             if(truststoreFile!=null) {
  531.                 truststoreFile = truststoreFile.trim();
  532.             }
  533.             else {
  534.                 throw new SecurityException("Truststore value in property '"+SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_FILE+"' is null");
  535.             }
  536.             String truststoreAlgo = (String) properties.get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_KEY_PAIR_ALGORITHM);
  537.             if(truststoreAlgo!=null) {
  538.                 truststoreAlgo = truststoreAlgo.trim();
  539.             }
  540.             else {
  541.                 throw new SecurityException("Key algorithm value in property '"+SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_KEY_PAIR_ALGORITHM+"' is null");
  542.             }
  543.             try {
  544.                 return GestoreKeystoreCache.getPublicKeyStore(requestInfo, truststoreFile, truststoreAlgo).getJwkSet();
  545.             }catch(Exception e) {
  546.                 throw new SecurityException(e.getMessage(),e);
  547.             }
  548.         }
  549.        
  550.         return null;
  551.     }
  552.    
  553.     public static boolean isRemoteStore(Map<String, Object> propertiesParam) {
  554.         Properties properties = new Properties();
  555.         properties.putAll(propertiesParam);
  556.         return isRemoteStore(properties);
  557.     }
  558.     public static boolean isRemoteStore(Properties properties) {
  559.         try {
  560.             IRemoteStoreProvider provider = null;
  561.             if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_REMOTE_STORE_PROVIDER)) {
  562.                 provider = (IRemoteStoreProvider) properties.get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_REMOTE_STORE_PROVIDER);
  563.             }
  564.            
  565.             RemoteKeyType keyType = null;
  566.             if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_REMOTE_STORE_KEY_TYPE)) {
  567.                 keyType = (RemoteKeyType) properties.get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_REMOTE_STORE_KEY_TYPE);
  568.             }
  569.            
  570.             RemoteStoreConfig config = null;
  571.             if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_REMOTE_STORE_CONFIG)) {
  572.                 config = (RemoteStoreConfig) properties.get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_REMOTE_STORE_CONFIG);
  573.             }
  574.            
  575.             return provider!=null && keyType!=null && config!=null;
  576.            
  577.         }catch(Exception e) {
  578.             return false;
  579.         }
  580.        
  581.     }
  582.    
  583.    
  584.     public static boolean isKeyPairKeystore(Map<String, Object> propertiesParam) {
  585.         Properties properties = new Properties();
  586.         properties.putAll(propertiesParam);
  587.         return isKeyPairKeystore(properties);
  588.     }
  589.     public static boolean isKeyPairKeystore(Properties properties) {
  590.         if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS_KEYSTORE_TYPE)) {
  591.             String keystoreType = (String) properties.get(SecurityConstants.JOSE_USE_HEADERS_KEYSTORE_TYPE);
  592.             if(keystoreType!=null) {
  593.                 return SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(keystoreType);
  594.             }
  595.         }
  596.         return false;
  597.     }
  598.    
  599.     public static boolean isJWKSetKeyStore(Map<String, Object> propertiesParam) {
  600.         Properties properties = new Properties();
  601.         properties.putAll(propertiesParam);
  602.         return isJWKSetKeyStore(properties);
  603.     }
  604.     public static boolean isJWKSetKeyStore(Properties properties) {
  605.         if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS_KEYSTORE_TYPE)) {
  606.             String truststoreType = (String) properties.get(SecurityConstants.JOSE_USE_HEADERS_KEYSTORE_TYPE);
  607.             if(truststoreType!=null) {
  608.                 return SecurityConstants.KEYSTORE_TYPE_JWK_VALUE.equalsIgnoreCase(truststoreType);
  609.             }
  610.         }
  611.         return false;
  612.     }
  613.    
  614.     public static JWKSet readKeyStoreJwtJsonWebKeysCert(RequestInfo requestInfo, Map<String, Object> propertiesParam) throws SecurityException {
  615.         Properties properties = new Properties();
  616.         properties.putAll(propertiesParam);
  617.         return readKeyStoreJwtJsonWebKeysCert(requestInfo, properties);
  618.     }
  619.     public static JWKSet readKeyStoreJwtJsonWebKeysCert(RequestInfo requestInfo, Properties properties) throws SecurityException {
  620.        
  621.         if(properties.containsKey(SecurityConstants.JOSE_USE_HEADERS_KEYSTORE_FILE)) {
  622.             String keystoreFile = (String) properties.get(SecurityConstants.JOSE_USE_HEADERS_KEYSTORE_FILE);
  623.             if(keystoreFile!=null) {
  624.                 keystoreFile = keystoreFile.trim();
  625.             }
  626.             else {
  627.                 throw new SecurityException("Keystore value in property '"+SecurityConstants.JOSE_USE_HEADERS_KEYSTORE_FILE+"' is null");
  628.             }
  629.             try {
  630.                 return GestoreKeystoreCache.getJwkSetStore(requestInfo, keystoreFile).getJwkSet();
  631.             }catch(Exception e) {
  632.                 throw new SecurityException(e.getMessage(),e);
  633.             }
  634.         }
  635.        
  636.         return null;
  637.     }
  638.        
  639.     public static KeyStore readKeyStoreJwtX509Cert(RequestInfo requestInfo, Map<String, Object> propertiesParam) throws SecurityException {
  640.         Properties properties = new Properties();
  641.         properties.putAll(propertiesParam);
  642.         return readKeyStoreJwtX509Cert(requestInfo, properties);
  643.     }
  644.     public static KeyStore readKeyStoreJwtX509Cert(RequestInfo requestInfo, Properties properties) throws SecurityException {
  645.         return readTrustStoreEngine(requestInfo, properties, SecurityConstants.JOSE_USE_HEADERS_KEYSTORE_FILE,
  646.                 SecurityConstants.JOSE_USE_HEADERS_KEYSTORE_TYPE,
  647.                 SecurityConstants.JOSE_USE_HEADERS_KEYSTORE_PASSWORD);
  648.     }
  649.    
  650.     public static Map<String, String> covertToJwtX509CertMapAliasPassword(Map<String, Object> propertiesParam) throws SecurityException, UtilsException {
  651.         Properties properties = new Properties();
  652.         properties.putAll(propertiesParam);
  653.         return readJwtX509CertMapAliasPassword(properties);
  654.     }
  655.     public static Map<String, String> readJwtX509CertMapAliasPassword(Properties properties) throws SecurityException, UtilsException {
  656.         try {
  657.             HashMap<String, String> map = new HashMap<>();
  658.             Properties pMap = Utilities.readProperties(SecurityConstants.JOSE_USE_HEADERS_KEYSTORE_MAP_ALIAS_PW, properties);
  659.             if(pMap!=null && pMap.size()>0) {
  660.                 Enumeration<?> names = pMap.propertyNames();
  661.                 while (names.hasMoreElements()) {
  662.                     Object oName = names.nextElement();
  663.                     if(oName instanceof String) {
  664.                         String name = (String) oName;
  665.                         name = name.trim();
  666.                         if(name.endsWith(SecurityConstants.JOSE_USE_HEADERS_KEYSTORE_MAP_ALIAS_PW_SUFFIX_ALIAS)) {
  667.                             String alias = pMap.getProperty(name);
  668.                             String confName = name.substring(0, name.indexOf(SecurityConstants.JOSE_USE_HEADERS_KEYSTORE_MAP_ALIAS_PW_SUFFIX_ALIAS));
  669.                             String namePassword = confName+SecurityConstants.JOSE_USE_HEADERS_KEYSTORE_MAP_ALIAS_PW_SUFFIX_PW;
  670.                             String password = pMap.getProperty(namePassword);
  671.                             if(password==null) {
  672.                                 throw new SecurityException("Property '"+SecurityConstants.JOSE_USE_HEADERS_KEYSTORE_MAP_ALIAS_PW+namePassword+"' not found");
  673.                             }
  674.                             map.put(alias, password);
  675.                         }
  676.                     }
  677.                 }
  678.             }
  679.             if(!map.isEmpty()) {
  680.                 return map;
  681.             }
  682.             else {
  683.                 return null;
  684.             }
  685.         }catch(Exception e) {
  686.             throw new SecurityException(e.getMessage(),e);
  687.         }
  688.     }
  689.        
  690.     private static KeyStore readTrustStoreEngine(RequestInfo requestInfo, Properties properties, String file, String type, String password) throws SecurityException {
  691.        
  692.         KeyStore keystore = null;
  693.        
  694.         String requiredPropertyPrefix = "Required property '";
  695.        
  696.         if(properties.containsKey(file)) {
  697.             String keystoreFile = (String) properties.get(file);
  698.             if(keystoreFile!=null) {
  699.                 keystoreFile = keystoreFile.trim();
  700.                
  701.                 if(!properties.containsKey(type)) {
  702.                     throw new SecurityException(requiredPropertyPrefix+type+"' not found");
  703.                 }
  704.                 String keystoreType = (String) properties.get(type);
  705.                 if(keystoreType==null) {
  706.                     throw new SecurityException(requiredPropertyPrefix+type+"' is empty");
  707.                 }
  708.                 keystoreType = keystoreType.trim();
  709.                
  710.                 boolean requiredPassword = true;
  711.                 if(!properties.containsKey(password)) {
  712.                     if(
  713.                             (KeystoreType.JKS.isType(keystoreType) && !DBUtils.isTruststoreJksPasswordRequired())
  714.                             ||
  715.                             (KeystoreType.PKCS12.isType(keystoreType) && !DBUtils.isTruststorePkcs12PasswordRequired())
  716.                     ) {
  717.                         requiredPassword = false;
  718.                     }
  719.                     if(requiredPassword) {
  720.                         throw new SecurityException(requiredPropertyPrefix+password+"' not found");
  721.                     }
  722.                 }
  723.                 String keystorePassword = (String) properties.get(password);
  724.                 if(keystorePassword==null && requiredPassword) {
  725.                     throw new SecurityException(requiredPropertyPrefix+password+"' is empty");
  726.                 }
  727.                 else if(keystorePassword!=null) {
  728.                     keystorePassword = keystorePassword.trim();
  729.                 }
  730.                
  731.                 keystore = GestoreKeystoreCache.getMerlinTruststore(requestInfo, keystoreFile, keystoreType, keystorePassword).getTrustStore();
  732.             }
  733.         }
  734.        
  735.         return keystore;
  736.     }
  737.    
  738.     public static final String HTTP_PROTOCOL = "http";
  739.     public static final String HTTPS_PROTOCOL = "https";
  740.    
  741.     public static void injectKeystore(RequestInfo requestInfo, Map<String, Object> dynamicMap, Properties properties, Logger log) {
  742.         try {
  743.             injectKeystore(requestInfo, dynamicMap, properties, log, false);
  744.         }catch(SecurityException e) {
  745.             // ignore per default
  746.         }
  747.     }
  748.     public static void injectKeystore(RequestInfo requestInfo, Map<String, Object> dynamicMap, Properties properties, Logger log, boolean throwError) throws SecurityException {
  749.        
  750.         if(log==null) {
  751.             log = LoggerWrapperFactory.getLogger(JOSEUtils.class);
  752.         }
  753.        
  754.         if(properties!=null && properties.containsKey(SecurityConstants.JOSE_KEYSTORE_FILE)) {
  755.            
  756.             String file = properties.getProperty(SecurityConstants.JOSE_KEYSTORE_FILE);
  757.             String type = properties.getProperty(SecurityConstants.JOSE_KEYSTORE_TYPE);
  758.             if(type==null) {
  759.                 type = SecurityConstants.KEYSTORE_TYPE_JKS_VALUE;
  760.             }
  761.             String password = properties.getProperty(SecurityConstants.JOSE_KEYSTORE_PSWD);
  762.             boolean passwordDefined = (password!=null && !"".equals(password));
  763.            
  764.             String byokPropertyName =  SecurityConstants.JOSE_KEYSTORE_BYOK_POLICY;
  765.             String byokProperty = properties.getProperty(byokPropertyName);
  766.             BYOKRequestParams byokParams = null;
  767.             BYOKUnwrapManager byokManager = null;
  768.             if(BYOKProvider.isPolicyDefined(byokProperty)){
  769.                 try {
  770.                     byokParams = BYOKProvider.getBYOKRequestParamsByUnwrapBYOKPolicy(byokProperty,
  771.                             dynamicMap!=null ? dynamicMap : new HashMap<>() );
  772.                     byokManager = new BYOKUnwrapManager(byokProperty, byokParams);
  773.                 }catch(Exception e) {
  774.                     String error = "Errore durante istanziazione del byok unwrap manager '"+byokProperty+"': "+e.getMessage();
  775.                     log.error(error,e);
  776.                     if(throwError) {
  777.                         throw new SecurityException(error, e);
  778.                     }
  779.                 }
  780.             }
  781.            
  782.             if(file!=null && !"".equals(file) ) {
  783.                
  784.                 if(SecurityConstants.KEYSTORE_TYPE_KEY_PAIR_VALUE.equalsIgnoreCase(type)) {
  785.                    
  786.                     String privateKeyPassword = properties.getProperty(RSSecurityConstants.RSSEC_KEY_PSWD);
  787.                    
  788.                     String algorithmPropertyName =  SecurityConstants.JOSE_KEYSTORE_KEY_ALGORITHM;
  789.                     String algorithmProperty = properties.getProperty(algorithmPropertyName);
  790.                    
  791.                     String publicKeyPropertyName =  SecurityConstants.JOSE_KEYSTORE_PUBLIC_KEY;
  792.                     String publicKeyProperty = properties.getProperty(publicKeyPropertyName);
  793.                     if(publicKeyProperty==null || "".equals(publicKeyProperty) ) {
  794.                         String error = "Errore durante l'accesso al keyPair '"+file+"': property public key file ("+publicKeyPropertyName+") undefined";
  795.                         log.error(error);
  796.                         if(throwError) {
  797.                             throw new SecurityException(error);
  798.                         }
  799.                     }
  800.                     else {
  801.                         KeyPairStore keyPair = null;
  802.                         if(file.startsWith(HTTP_PROTOCOL) || file.startsWith(HTTPS_PROTOCOL)) {
  803.                             byte[] privateKey = readHttpStore(properties, requestInfo, file, log, throwError);
  804.                        
  805.                             byte[] publicKey = null;
  806.                             if(publicKeyProperty.startsWith(HTTP_PROTOCOL) || publicKeyProperty.startsWith(HTTPS_PROTOCOL)) {
  807.                                 publicKey = readHttpStore(properties, requestInfo, publicKeyProperty, log, throwError);
  808.                             }
  809.                             else {
  810.                                 String error = "Errore durante l'accesso al keyPair '"+file+"': property public key file ("+publicKeyPropertyName+") expected as http resource: '"+publicKeyProperty+"'";
  811.                                 log.error(error);
  812.                                 if(throwError) {
  813.                                     throw new SecurityException(error);
  814.                                 }
  815.                             }
  816.                            
  817.                             try {
  818.                                 keyPair = new KeyPairStore(privateKey, publicKey, privateKeyPassword, algorithmProperty, byokParams);
  819.                             }catch(Exception e) {
  820.                                 String error = "Errore durante istanziazione del keyPair (http resource) '"+file+"'/'"+publicKeyProperty+"': "+e.getMessage();
  821.                                 log.error(error,e);
  822.                                 if(throwError) {
  823.                                     throw new SecurityException(error, e);
  824.                                 }
  825.                             }
  826.                         }
  827.                         else {
  828.                             try {
  829.                                 keyPair = GestoreKeystoreCache.getKeyPairStore(requestInfo, file, publicKeyProperty, privateKeyPassword, algorithmProperty, byokParams);
  830.                             }catch(Exception e) {
  831.                                 String error = "Errore durante istanziazione del keyPair '"+file+"'/'"+publicKeyProperty+"': "+e.getMessage();
  832.                                 log.error(error,e);
  833.                                 if(throwError) {
  834.                                     throw new SecurityException(error, e);
  835.                                 }
  836.                             }
  837.                         }
  838.                         if(keyPair!=null) {
  839.                             try {
  840.                                 String jwkSet = keyPair.getJwkSet().getJson();
  841.                                 String jwkSetKid = keyPair.getJwkSetKid();
  842.                                
  843.                                 properties.remove(SecurityConstants.JOSE_KEYSTORE_FILE);
  844.                                 properties.remove(SecurityConstants.JOSE_KEYSTORE_PSWD);
  845.                                 properties.remove(algorithmPropertyName);
  846.                                 properties.remove(publicKeyPropertyName);
  847.                                 properties.remove(RSSecurityConstants.RSSEC_KEY_PSWD);
  848.                                 properties.remove(SecurityConstants.JOSE_KEYSTORE_KEY_ALIAS);
  849.                                 properties.remove(SecurityConstants.JOSE_KEYSTORE_TYPE);
  850.                                 properties.put(SecurityConstants.JOSE_KEYSTORE_JWKSET, jwkSet);
  851.                                 properties.put(SecurityConstants.JOSE_KEYSTORE_KEY_ALIAS, jwkSetKid);
  852.                                 properties.put(SecurityConstants.JOSE_KEYSTORE_TYPE, SecurityConstants.KEYSTORE_TYPE_JWK_VALUE);
  853.                             }catch(Exception e) {
  854.                                 String error = "Errore durante istanziazione del keyPair '"+file+"'/'"+publicKeyProperty+"': "+e.getMessage();
  855.                                 log.error(error,e);
  856.                                 if(throwError) {
  857.                                     throw new SecurityException(error, e);
  858.                                 }
  859.                             }
  860.                         }
  861.                     }
  862.                    
  863.                 }
  864.                
  865.                 else if(SecurityConstants.KEYSTORE_TYPE_PUBLIC_KEY_VALUE.equalsIgnoreCase(type)) {
  866.                    
  867.                     String algorithmPropertyName =  SecurityConstants.JOSE_KEYSTORE_KEY_ALGORITHM;
  868.                     String algorithmProperty = properties.getProperty(algorithmPropertyName);
  869.                    
  870.                     PublicKeyStore publicKeyStore = null;
  871.                     if(file.startsWith(HTTP_PROTOCOL) || file.startsWith(HTTPS_PROTOCOL)) {
  872.                         byte[] publicKey = readHttpStore(properties, requestInfo, file, log, throwError);
  873.                                            
  874.                         try {
  875.                             publicKeyStore = new PublicKeyStore(publicKey, algorithmProperty);
  876.                         }catch(Exception e) {
  877.                             String error = "Errore durante istanziazione della chiave pubblica (http resource) '"+file+"': "+e.getMessage();
  878.                             log.error(error,e);
  879.                             if(throwError) {
  880.                                 throw new SecurityException(error, e);
  881.                             }
  882.                         }
  883.                     }
  884.                     else {
  885.                         try {
  886.                             publicKeyStore = GestoreKeystoreCache.getPublicKeyStore(requestInfo, file, algorithmProperty);
  887.                         }catch(Exception e) {
  888.                             String error = "Errore durante istanziazione della chiave pubblica '"+file+"': "+e.getMessage();
  889.                             log.error(error,e);
  890.                             if(throwError) {
  891.                                 throw new SecurityException(error, e);
  892.                             }
  893.                         }
  894.                     }
  895.                     if(publicKeyStore!=null) {
  896.                         try {
  897.                             String jwkSet = publicKeyStore.getJwkSet().getJson();
  898.                             String jwkSetKid = publicKeyStore.getJwkSetKid();
  899.                            
  900.                             properties.remove(SecurityConstants.JOSE_KEYSTORE_FILE);
  901.                             properties.remove(SecurityConstants.JOSE_KEYSTORE_PSWD);
  902.                             properties.remove(algorithmPropertyName);
  903.                             properties.remove(RSSecurityConstants.RSSEC_KEY_PSWD);
  904.                             properties.remove(SecurityConstants.JOSE_KEYSTORE_KEY_ALIAS);
  905.                             properties.remove(SecurityConstants.JOSE_KEYSTORE_TYPE);
  906.                             properties.put(SecurityConstants.JOSE_KEYSTORE_JWKSET, jwkSet);
  907.                             properties.put(SecurityConstants.JOSE_KEYSTORE_KEY_ALIAS, jwkSetKid);
  908.                             properties.put(SecurityConstants.JOSE_KEYSTORE_TYPE, SecurityConstants.KEYSTORE_TYPE_JWK_VALUE);
  909.                         }catch(Exception e) {
  910.                             String error = "Errore durante istanziazione della chiave pubblica '"+file+"': "+e.getMessage();
  911.                             log.error(error,e);
  912.                             if(throwError) {
  913.                                 throw new SecurityException(error, e);
  914.                             }
  915.                         }
  916.                     }
  917.                    
  918.                 }
  919.                
  920.                 else if( passwordDefined
  921.                         ||
  922.                         ((!DBUtils.isKeystoreJksPasswordRequired()) && SecurityConstants.KEYSTORE_TYPE_JKS_VALUE.equalsIgnoreCase(type))
  923.                         ||
  924.                         ((!DBUtils.isKeystorePkcs12PasswordRequired()) && SecurityConstants.KEYSTORE_TYPE_PKCS12_VALUE.equalsIgnoreCase(type))
  925.                         ||
  926.                         SecurityConstants.KEYSTORE_TYPE_JWK_VALUE.equalsIgnoreCase(type)) {
  927.                    
  928.                     if(file.startsWith(HTTP_PROTOCOL) || file.startsWith(HTTPS_PROTOCOL)) {
  929.                        
  930.                         byte[]content = readHttpStore(properties, requestInfo, file, log, throwError);
  931.                        
  932.                         if(byokManager!=null) {
  933.                             try {
  934.                                 content = byokManager.unwrap(content);
  935.                             }catch(Exception e) {
  936.                                 String error = "Errore durante l'unwrap del keystore ottenuto via http '"+file+"': "+e.getMessage();
  937.                                 log.error(error,e);
  938.                                 if(throwError) {
  939.                                     throw new SecurityException(error, e);
  940.                                 }
  941.                             }
  942.                         }
  943.                        
  944.                         if(content!=null) {
  945.                             if(SecurityConstants.KEYSTORE_TYPE_JWK_VALUE.equalsIgnoreCase(type)) {
  946.                                 properties.remove(SecurityConstants.JOSE_KEYSTORE_FILE);
  947.                                 properties.remove(SecurityConstants.JOSE_KEYSTORE_PSWD);
  948.                                 properties.put(SecurityConstants.JOSE_KEYSTORE_JWKSET, new String(content));
  949.                             }
  950.                             else {
  951.                                 java.security.KeyStore keystore = null;
  952.                                 try {
  953.                                     keystore = KeystoreUtils.readKeystore(content, type, password);
  954.                                 }catch(Exception e) {
  955.                                     String error = "Errore durante istanziazione del keystore ottenuto via http '"+file+"': "+e.getMessage();
  956.                                     log.error(error,e);
  957.                                     keystore = null;
  958.                                     if(throwError) {
  959.                                         throw new SecurityException(error, e);
  960.                                     }
  961.                                 }
  962.                                 if(keystore!=null) {
  963.                                     properties.remove(SecurityConstants.JOSE_KEYSTORE_FILE);
  964.                                     // properties.remove(SecurityConstants.JOSE_KEYSTORE_TYPE); non va rimosso, serve per jceks
  965.                                     properties.remove(SecurityConstants.JOSE_KEYSTORE_PSWD);
  966.                                     properties.put(SecurityConstants.JOSE_KEYSTORE, keystore);
  967.                                 }
  968.                             }
  969.                         }
  970.                     }
  971.                     else {
  972.                         if(SecurityConstants.KEYSTORE_TYPE_JWK_VALUE.equalsIgnoreCase(type)) {
  973.                             String jwkSet = null;
  974.                             try {
  975.                                 jwkSet = GestoreKeystoreCache.getJwkSetStore(requestInfo, file, byokParams).getJwkSetContent();
  976.                             }catch(Exception e) {
  977.                                 String error = "Errore durante l'accesso al jwk set '"+file+"': "+e.getMessage();
  978.                                 log.error(error,e);
  979.                                 if(throwError) {
  980.                                     throw new SecurityException(error, e);
  981.                                 }
  982.                             }
  983.                             if(jwkSet!=null) {
  984.                                 properties.remove(SecurityConstants.JOSE_KEYSTORE_FILE);
  985.                                 properties.remove(SecurityConstants.JOSE_KEYSTORE_PSWD);
  986.                                 properties.put(SecurityConstants.JOSE_KEYSTORE_JWKSET, jwkSet);
  987.                             }
  988.                         }
  989.                         else {
  990.                             java.security.KeyStore keystore = null;
  991.                             try {
  992.                                 MerlinKeystore merlinKeystore = GestoreKeystoreCache.getMerlinKeystore(requestInfo, file, type, password, byokParams);
  993.                                 if(merlinKeystore==null) {
  994.                                     throw new SecurityException("Keystore '"+file+"' undefined");
  995.                                 }
  996.                                 KeyStore keystoreUtils = merlinKeystore.getKeyStore();
  997.                                 if(keystoreUtils==null) {
  998.                                     throw new SecurityException("Keystore '"+file+"' undefined");
  999.                                 }
  1000.                                 keystore = keystoreUtils.getKeystore();
  1001.                             }catch(Exception e) {
  1002.                                 String error = "Errore durante l'accesso al keystore '"+file+"': "+e.getMessage();
  1003.                                 log.error(error,e);
  1004.                                 if(throwError) {
  1005.                                     throw new SecurityException(error, e);
  1006.                                 }
  1007.                             }
  1008.                             if(keystore!=null) {
  1009.                                 properties.remove(SecurityConstants.JOSE_KEYSTORE_FILE);
  1010.                                 // properties.remove(SecurityConstants.JOSE_KEYSTORE_TYPE); non va rimosso, serve per jceks
  1011.                                 properties.remove(SecurityConstants.JOSE_KEYSTORE_PSWD);
  1012.                                 properties.put(SecurityConstants.JOSE_KEYSTORE, keystore);
  1013.                             }
  1014.                         }
  1015.                     }
  1016.                 }
  1017.             }
  1018.         }
  1019.        
  1020.     }
  1021.    
  1022.     public static byte[] readHttpStore(Properties properties, RequestInfo requestInfo, String file, Logger log, boolean throwError) throws SecurityException {
  1023.         return readHttpStore( properties, requestInfo, file, log, throwError, false);
  1024.     }
  1025.     public static byte[] readHttpStore(Properties properties, RequestInfo requestInfo, String file, Logger log, boolean throwError, boolean forceNoCache) throws SecurityException {
  1026.         byte[]content = null;
  1027.         try {
  1028.             boolean trustAll = false;
  1029.             String trustStoreAllSslProperty = properties.getProperty(JOSECostanti.ID_TRUSTSTORE_SSL_KEYSTORE_TRUSTALL);
  1030.             trustAll = trustStoreAllSslProperty!=null && "true".equalsIgnoreCase(trustStoreAllSslProperty);
  1031.            
  1032.             String trustStoreSslPropertyName = JOSECostanti.ID_TRUSTSTORE_SSL_KEYSTORE_FILE;
  1033.             String trustStoreSslProperty =  properties.getProperty(trustStoreSslPropertyName);
  1034.             MerlinTruststore trustStoreSsl = null;
  1035.             if(trustStoreSslProperty!=null) {
  1036.                 String trustStoreSslPasswordPropertyName = JOSECostanti.ID_TRUSTSTORE_SSL_KEYSTORE_PASSWORD;
  1037.                 String trustStoreSslTypePropertyName = JOSECostanti.ID_TRUSTSTORE_SSL_KEYSTORE_TYPE;
  1038.                 String trustStoreSslPasswordProperty = properties.getProperty(trustStoreSslPasswordPropertyName);
  1039.                 String trustStoreSslTypeProperty = properties.getProperty(trustStoreSslTypePropertyName);
  1040.                 if(trustStoreSslTypeProperty==null) {
  1041.                     throw new SecurityException("TrustStore ssl type undefined");
  1042.                 }
  1043.                 if(trustStoreSslPasswordProperty==null) {
  1044.                     boolean required = true;
  1045.                     if(KeystoreType.JKS.isType(trustStoreSslTypeProperty)) {
  1046.                         required = DBUtils.isTruststoreJksPasswordRequired();
  1047.                     }
  1048.                     else if(KeystoreType.PKCS12.isType(trustStoreSslTypeProperty)) {
  1049.                         required = DBUtils.isTruststorePkcs12PasswordRequired();
  1050.                     }
  1051.                     if(required) {
  1052.                         throw new SecurityException("TrustStore ssl password undefined");
  1053.                     }
  1054.                 }
  1055.                 trustStoreSsl = GestoreKeystoreCache.getMerlinTruststore(requestInfo, trustStoreSslProperty, trustStoreSslTypeProperty, trustStoreSslPasswordProperty);
  1056.             }
  1057.            
  1058.             String trustStoreSslCrlPropertyName =  JOSECostanti.ID_TRUSTSTORE_SSL_KEYSTORE_CRL;
  1059.             String trustStoreSslCrlProperty =  properties.getProperty(trustStoreSslCrlPropertyName);
  1060.             CRLCertstore crlStore = null;
  1061.             if(trustStoreSslCrlProperty!=null) {
  1062.                 crlStore = GestoreKeystoreCache.getCRLCertstore(requestInfo, trustStoreSslCrlProperty);
  1063.             }
  1064.            
  1065.             String trustStoreSslConnectionTimeoutPropertyName =  JOSECostanti.ID_TRUSTSTORE_SSL_KEYSTORE_CONNECTION_TIMEOUT;
  1066.             String trustStoreSslReadTimeoutPropertyName =  JOSECostanti.ID_TRUSTSTORE_SSL_KEYSTORE_READ_TIMEOUT;
  1067.             String trustStoreSslConnectionTimeoutProperty =  properties.getProperty(trustStoreSslConnectionTimeoutPropertyName);
  1068.             String trustStoreSslReadTimeoutProperty =  properties.getProperty(trustStoreSslReadTimeoutPropertyName);
  1069.             Integer connectionTimeout = null;
  1070.             Integer readTimeout = null;
  1071.             if(trustStoreSslConnectionTimeoutProperty!=null && trustStoreSslReadTimeoutProperty!=null) {
  1072.                 connectionTimeout = Integer.valueOf(trustStoreSslConnectionTimeoutProperty);
  1073.                 readTimeout = Integer.valueOf(trustStoreSslReadTimeoutProperty);
  1074.             }
  1075.            
  1076.             List<HttpOptions> list = new ArrayList<>();
  1077.            
  1078.             String trustStoreSslHostnameVerifier =  properties.getProperty(JOSECostanti.ID_TRUSTSTORE_SSL_KEYSTORE_HOSTNAME_VERIFIER);
  1079.             if(trustStoreSslHostnameVerifier!=null && StringUtils.isNotEmpty(trustStoreSslHostnameVerifier)) {
  1080.                 HttpsOptions op = new HttpsOptions();
  1081.                 op.setHostnameVerifier("true".equals(trustStoreSslHostnameVerifier)); // lascio default a false
  1082.                 list.add(op);
  1083.             }
  1084.            
  1085.             String forwardProxyEndpoint = properties.getProperty(JOSECostanti.ID_FORWARD_PROXY_ENDPOINT);
  1086.             if(forwardProxyEndpoint!=null && StringUtils.isNotEmpty(forwardProxyEndpoint)) {
  1087.                 HttpForwardProxyOptions op = new HttpForwardProxyOptions();
  1088.                 op.setForwardProxyEndpoint(forwardProxyEndpoint);
  1089.                
  1090.                 HttpForwardProxyConfig c = new HttpForwardProxyConfig();
  1091.                 String forwardProxyHeader = properties.getProperty(JOSECostanti.ID_FORWARD_PROXY_HEADER);
  1092.                 String forwardProxyQuery = properties.getProperty(JOSECostanti.ID_FORWARD_PROXY_QUERY);
  1093.                 if(forwardProxyHeader!=null && StringUtils.isNotEmpty(forwardProxyHeader)) {
  1094.                     c.setHeader(forwardProxyHeader);
  1095.                     String forwardProxyHeaderBase64 = properties.getProperty(JOSECostanti.ID_FORWARD_PROXY_HEADER_BASE64);
  1096.                     if(forwardProxyHeaderBase64!=null && StringUtils.isNotEmpty(forwardProxyHeaderBase64)) {
  1097.                         c.setHeaderBase64("false".equals(forwardProxyHeaderBase64)); // default true
  1098.                     }
  1099.                 }
  1100.                 else if(forwardProxyQuery!=null && StringUtils.isNotEmpty(forwardProxyQuery)) {
  1101.                     c.setQuery(forwardProxyQuery);
  1102.                     String forwardProxyQueryBase64 = properties.getProperty(JOSECostanti.ID_FORWARD_PROXY_QUERY_BASE64);
  1103.                     if(forwardProxyQueryBase64!=null && StringUtils.isNotEmpty(forwardProxyQueryBase64)) {
  1104.                         c.setQueryBase64("false".equals(forwardProxyQueryBase64)); // default true
  1105.                     }
  1106.                 }
  1107.                 else {
  1108.                     throw new SecurityException("ForwardProxy header o query required");
  1109.                 }
  1110.                 op.setForwardProxyConfig(c);
  1111.                
  1112.                 list.add(op);
  1113.             }
  1114.            
  1115.             String proxyType = properties.getProperty(JOSECostanti.ID_PROXY_TYPE);
  1116.             if(proxyType!=null && StringUtils.isNotEmpty(proxyType)) {
  1117.                 HttpProxyOptions op = new HttpProxyOptions();
  1118.                 if(CostantiConnettori.CONNETTORE_HTTP_PROXY_TYPE_VALUE_HTTP.equals(proxyType)){
  1119.                     op.setProxyType(Proxy.Type.HTTP);
  1120.                 }
  1121.                 else if(CostantiConnettori.CONNETTORE_HTTP_PROXY_TYPE_VALUE_HTTPS.equals(proxyType)){
  1122.                     op.setProxyType(Proxy.Type.HTTP); // voluto
  1123.                 }
  1124.                 else{
  1125.                     throw new SecurityException("Proxy type '"+proxyType+"' unsupported");
  1126.                 }
  1127.                
  1128.                 String proxyHostname = properties.getProperty(JOSECostanti.ID_PROXY_HOSTNAME);
  1129.                 if(proxyHostname!=null && StringUtils.isNotEmpty(proxyHostname)) {
  1130.                     op.setProxyHostname(proxyHostname);
  1131.                 }
  1132.                 else{
  1133.                     throw new SecurityException("Proxy hostname undefined");
  1134.                 }
  1135.                
  1136.                 String proxyPort = properties.getProperty(JOSECostanti.ID_PROXY_HOSTNAME);
  1137.                 if(proxyPort!=null && StringUtils.isNotEmpty(proxyPort)) {
  1138.                     try {
  1139.                         op.setProxyPort(Integer.valueOf(proxyPort));
  1140.                     }catch(Exception e) {
  1141.                         throw new SecurityException("Proxy port '"+proxyPort+"' invalid: "+e.getMessage());
  1142.                     }
  1143.                 }
  1144.                 else{
  1145.                     throw new SecurityException("Proxy port undefined");
  1146.                 }
  1147.                
  1148.                 String proxyUsername = properties.getProperty(JOSECostanti.ID_PROXY_USERNAME);
  1149.                 if(proxyUsername!=null && StringUtils.isNotEmpty(proxyUsername)) {
  1150.                     op.setProxyUsername(proxyUsername);
  1151.                     String proxyPassword = properties.getProperty(JOSECostanti.ID_PROXY_USERNAME);
  1152.                     if(proxyPassword!=null) {
  1153.                         op.setProxyPassword(proxyPassword);
  1154.                     }
  1155.                 }
  1156.                
  1157.                 list.add(op);
  1158.             }
  1159.            
  1160.             HttpOptions [] options = null;
  1161.             if(!list.isEmpty()) {
  1162.                 options = list.toArray(new HttpOptions[1]);
  1163.             }
  1164.             if(forceNoCache) {
  1165.                 if(connectionTimeout!=null && readTimeout!=null) {
  1166.                     if(trustStoreSsl!=null) {
  1167.                         if(crlStore!=null) {
  1168.                             content = new HttpStore(file, connectionTimeout, readTimeout, trustStoreSsl, crlStore, options).getStoreBytes();
  1169.                         }
  1170.                         else {
  1171.                             content = new HttpStore(file, connectionTimeout, readTimeout, trustStoreSsl, options).getStoreBytes();
  1172.                         }
  1173.                     }
  1174.                     else if(trustAll) {
  1175.                         content = new HttpStore(file, connectionTimeout, readTimeout, trustAll, options).getStoreBytes();
  1176.                     }
  1177.                     else {
  1178.                         content = new HttpStore(file, connectionTimeout, readTimeout, options).getStoreBytes();
  1179.                     }
  1180.                 }
  1181.                 else {
  1182.                     if(trustStoreSsl!=null) {
  1183.                         if(crlStore!=null) {
  1184.                             content = new HttpStore(file, trustStoreSsl, crlStore, options).getStoreBytes();
  1185.                         }
  1186.                         else {
  1187.                             content = new HttpStore(file, trustStoreSsl, options).getStoreBytes();
  1188.                         }
  1189.                     }
  1190.                     else if(trustAll) {
  1191.                         content = new HttpStore(file, trustAll, options).getStoreBytes();
  1192.                     }
  1193.                     else {
  1194.                         content = new HttpStore(file, options).getStoreBytes();
  1195.                     }
  1196.                 }
  1197.             }
  1198.             else {
  1199.                 if(connectionTimeout!=null && readTimeout!=null) {
  1200.                     if(trustStoreSsl!=null) {
  1201.                         if(crlStore!=null) {
  1202.                             content = GestoreKeystoreCache.getHttpStore(requestInfo, file, connectionTimeout, readTimeout, trustStoreSsl, crlStore, options).getStoreBytes();
  1203.                         }
  1204.                         else {
  1205.                             content = GestoreKeystoreCache.getHttpStore(requestInfo, file, connectionTimeout, readTimeout, trustStoreSsl, options).getStoreBytes();
  1206.                         }
  1207.                     }
  1208.                     else if(trustAll) {
  1209.                         content = GestoreKeystoreCache.getHttpStore(requestInfo, file, connectionTimeout, readTimeout, trustAll, options).getStoreBytes();
  1210.                     }
  1211.                     else {
  1212.                         content = GestoreKeystoreCache.getHttpStore(requestInfo, file, connectionTimeout, readTimeout, options).getStoreBytes();
  1213.                     }
  1214.                 }
  1215.                 else {
  1216.                     if(trustStoreSsl!=null) {
  1217.                         if(crlStore!=null) {
  1218.                             content = GestoreKeystoreCache.getHttpStore(requestInfo, file, trustStoreSsl, crlStore, options).getStoreBytes();
  1219.                         }
  1220.                         else {
  1221.                             content = GestoreKeystoreCache.getHttpStore(requestInfo, file, trustStoreSsl, options).getStoreBytes();
  1222.                         }
  1223.                     }
  1224.                     else if(trustAll) {
  1225.                         content = GestoreKeystoreCache.getHttpStore(requestInfo, file, trustAll, options).getStoreBytes();
  1226.                     }
  1227.                     else {
  1228.                         content = GestoreKeystoreCache.getHttpStore(requestInfo, file, options).getStoreBytes();
  1229.                     }
  1230.                 }
  1231.             }
  1232.         }catch(Exception e) {
  1233.             String error = "Errore durante l'accesso al keystore via http '"+file+"': "+e.getMessage();
  1234.             log.error(error,e);
  1235.             if(throwError) {
  1236.                 throw new SecurityException(error, e);
  1237.             }
  1238.         }
  1239.         return content;
  1240.     }
  1241. }