MessageSecurityReceiver_jose.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.security.PublicKey;
  22. import java.security.cert.X509Certificate;
  23. import java.util.Map;
  24. import java.util.Properties;

  25. import org.apache.commons.lang.StringUtils;
  26. import org.apache.cxf.rs.security.jose.jwk.JsonWebKeys;
  27. import org.openspcoop2.core.commons.DBUtils;
  28. import org.openspcoop2.core.constants.Costanti;
  29. import org.openspcoop2.generic_project.exception.NotFoundException;
  30. import org.openspcoop2.message.OpenSPCoop2Message;
  31. import org.openspcoop2.message.OpenSPCoop2RestJsonMessage;
  32. import org.openspcoop2.message.OpenSPCoop2RestMessage;
  33. import org.openspcoop2.message.constants.MessageType;
  34. import org.openspcoop2.message.constants.ServiceBinding;
  35. import org.openspcoop2.protocol.sdk.Busta;
  36. import org.openspcoop2.protocol.sdk.constants.CodiceErroreCooperazione;
  37. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  38. import org.openspcoop2.security.SecurityException;
  39. import org.openspcoop2.security.keystore.CRLCertstore;
  40. import org.openspcoop2.security.keystore.cache.GestoreKeystoreCache;
  41. import org.openspcoop2.security.keystore.cache.GestoreOCSPResource;
  42. import org.openspcoop2.security.keystore.cache.GestoreOCSPValidator;
  43. import org.openspcoop2.security.message.AbstractRESTMessageSecurityReceiver;
  44. import org.openspcoop2.security.message.MessageSecurityContext;
  45. import org.openspcoop2.security.message.constants.SecurityConstants;
  46. import org.openspcoop2.security.message.utils.EncryptionBean;
  47. import org.openspcoop2.security.message.utils.KeystoreUtils;
  48. import org.openspcoop2.security.message.utils.PropertiesUtils;
  49. import org.openspcoop2.security.message.utils.SignatureBean;
  50. import org.openspcoop2.utils.LoggerBuffer;
  51. import org.openspcoop2.utils.Utilities;
  52. import org.openspcoop2.utils.certificate.JWKSet;
  53. import org.openspcoop2.utils.certificate.KeyStore;
  54. import org.openspcoop2.utils.certificate.KeystoreType;
  55. import org.openspcoop2.utils.certificate.remote.IRemoteStoreProvider;
  56. import org.openspcoop2.utils.certificate.remote.RemoteKeyType;
  57. import org.openspcoop2.utils.certificate.remote.RemoteStoreConfig;
  58. import org.openspcoop2.utils.security.CertificateValidityCheck;
  59. import org.openspcoop2.utils.security.JOSESerialization;
  60. import org.openspcoop2.utils.security.JWTOptions;
  61. import org.openspcoop2.utils.security.JsonDecrypt;
  62. import org.openspcoop2.utils.security.JsonVerifySignature;
  63. import org.openspcoop2.utils.transport.http.IOCSPValidator;



  64. /**
  65.  * Classe per la gestione della WS-Security (WSDoAllReceiver).
  66.  *
  67.  * @author Lorenzo Nardi (nardi@link.it)
  68.  * @author $Author$
  69.  * @version $Rev$, $Date$
  70.  *
  71.  */
  72. public class MessageSecurityReceiver_jose extends AbstractRESTMessageSecurityReceiver {

  73.     private JOSESerialization joseSerialization = null;
  74.     private boolean detached = false;
  75.     private JsonVerifySignature jsonVerifierSignature = null;
  76.     private JsonDecrypt jsonDecrypt = null;

  77.     @Override
  78.     public void process(MessageSecurityContext messageSecurityContext,OpenSPCoop2Message messageParam,Busta busta,org.openspcoop2.utils.Map<Object> ctx) throws SecurityException{
  79.         process(messageSecurityContext, messageParam, busta,
  80.                 false, null, ctx);
  81.     }
  82.     public void process(MessageSecurityContext messageSecurityContext,OpenSPCoop2Message messageParam,Busta busta,
  83.             boolean bufferMessageReadOnly, String idTransazione,org.openspcoop2.utils.Map<Object> ctx) throws SecurityException{
  84.        
  85.         boolean signatureProcess = false;
  86.         boolean encryptProcess = false;
  87.         try{
  88.            
  89.             if(!ServiceBinding.REST.equals(messageParam.getServiceBinding())){
  90.                 throw new SecurityException(JOSECostanti.JOSE_ENGINE_DESCRIPTION+" usable only with REST Binding");
  91.             }
  92.             if(!MessageType.JSON.equals(messageParam.getMessageType())) {
  93.                 throw new SecurityException(JOSECostanti.JOSE_ENGINE_DESCRIPTION+" usable only with REST Binding and a json message, found: "+messageParam.getMessageType());
  94.             }
  95.             OpenSPCoop2RestJsonMessage restJsonMessage = messageParam.castAsRestJson();
  96.            
  97.             RequestInfo requestInfo = null;
  98.             if(ctx!=null && ctx.containsKey(Costanti.REQUEST_INFO)) {
  99.                 requestInfo = (RequestInfo) ctx.get(Costanti.REQUEST_INFO);
  100.             }
  101.            
  102.            
  103.            
  104.             // ********** Leggo operazioni ***************
  105.             boolean encrypt = false;
  106.             boolean signature = false;

  107.             String[]actions = ((String)messageSecurityContext.getIncomingProperties().get(SecurityConstants.ACTION)).split(" ");
  108.             for (int i = 0; i < actions.length; i++) {
  109.                 if(SecurityConstants.isActionEncryption(actions[i].trim()) || SecurityConstants.isActionDecryption(actions[i].trim())){
  110.                     encrypt = true;
  111.                 }
  112.                 else if(SecurityConstants.SIGNATURE_ACTION.equals(actions[i].trim())){
  113.                     signature = true;
  114.                 }
  115.                 else {
  116.                     throw new SecurityException(JOSECostanti.JOSE_ENGINE_DESCRIPTION+"; action '"+actions[i]+"' unsupported");
  117.                 }
  118.             }
  119.            
  120.             if(encrypt && signature) {
  121.                 throw new SecurityException(JOSECostanti.JOSE_ENGINE_DESCRIPTION+" usable only with one function beetwen encrypt or signature");
  122.             }
  123.             if(!encrypt && !signature) {
  124.                 throw new SecurityException(JOSECostanti.JOSE_ENGINE_DESCRIPTION+" require one function beetwen encrypt or signature");
  125.             }
  126.            
  127.            
  128.            
  129.            
  130.             if(signature) {
  131.                
  132.                
  133.                 // **************** Leggo parametri signature store **************************
  134.                            
  135.                 String mode = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.SIGNATURE_MODE);
  136.                 if(mode==null || "".equals(mode.trim())){
  137.                     throw new SecurityException(JOSECostanti.JOSE_ENGINE_VERIFIER_SIGNATURE_DESCRIPTION+" require '"+SecurityConstants.SIGNATURE_MODE+"' property");
  138.                 }
  139.                 try {
  140.                     this.joseSerialization = JOSEUtils.toJOSESerialization(mode);
  141.                 }catch(Exception e) {
  142.                     throw new SecurityException(JOSECostanti.JOSE_ENGINE_VERIFIER_SIGNATURE_DESCRIPTION+", '"+SecurityConstants.SIGNATURE_MODE+"' property error: "+e.getMessage(),e);
  143.                 }
  144.                 JWTOptions options = new JWTOptions(this.joseSerialization);
  145.                 boolean useHeaders = JOSEUtils.useJwtHeadersMap(messageSecurityContext.getIncomingProperties(), options);
  146.                
  147.                 SignatureBean bean = null;
  148.                 NotFoundException notFound = null;
  149.                 try {
  150.                     bean = PropertiesUtils.getReceiverSignatureBean(messageSecurityContext);
  151.                 }catch(NotFoundException e) {
  152.                     notFound = e;
  153.                 }
  154.                 if(bean!=null) {
  155.                     Properties signatureProperties = bean.getProperties();
  156.                     boolean throwError = true;
  157.                     Map<String,Object> dynamicMap = Costanti.readDynamicMap(ctx);
  158.                     JOSEUtils.injectKeystore(requestInfo, dynamicMap, signatureProperties, messageSecurityContext.getLog(), throwError); // serve per leggere il keystore dalla cache
  159.                     this.jsonVerifierSignature = new JsonVerifySignature(signatureProperties, options);
  160.                 }
  161.                 else if(useHeaders) {
  162.                    
  163.                     if(JOSEUtils.isRemoteStore(messageSecurityContext.getIncomingProperties())) {
  164.                         IRemoteStoreProvider provider = (IRemoteStoreProvider) messageSecurityContext.getIncomingProperties().get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_REMOTE_STORE_PROVIDER);
  165.                         RemoteKeyType keyType = (RemoteKeyType) messageSecurityContext.getIncomingProperties().get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_REMOTE_STORE_KEY_TYPE);
  166.                         RemoteStoreConfig config = (RemoteStoreConfig) messageSecurityContext.getIncomingProperties().get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_REMOTE_STORE_CONFIG);
  167.                         this.jsonVerifierSignature = new JsonVerifySignature(provider, keyType, config, options);
  168.                     }
  169.                     else if(JOSEUtils.isJWKSetTrustStore(messageSecurityContext.getIncomingProperties())) {
  170.                         JsonWebKeys jsonWebKeys = null;
  171.                         JWKSet jkwSet = JOSEUtils.readTrustStoreJwtJsonWebKeysCert(requestInfo, messageSecurityContext.getIncomingProperties());
  172.                         if(jkwSet!=null) {
  173.                             jsonWebKeys = jkwSet.getJsonWebKeys();
  174.                         }
  175.                         this.jsonVerifierSignature = new JsonVerifySignature(jsonWebKeys, options);
  176.                     }
  177.                     else if(JOSEUtils.isPublicKeyTrustStore(messageSecurityContext.getIncomingProperties())) {
  178.                         JsonWebKeys jsonWebKeys = null;
  179.                         JWKSet jkwSet = JOSEUtils.readTrustStorePublicKey(requestInfo, messageSecurityContext.getIncomingProperties());
  180.                         if(jkwSet!=null) {
  181.                             jsonWebKeys = jkwSet.getJsonWebKeys();
  182.                         }
  183.                         this.jsonVerifierSignature = new JsonVerifySignature(jsonWebKeys, options);
  184.                     }
  185.                     else {
  186.                         KeyStore trustStore = JOSEUtils.readTrustStoreJwtX509Cert(requestInfo, messageSecurityContext.getIncomingProperties());
  187.                         KeyStore trustStoreSsl = JOSEUtils.readTrustStoreSsl(requestInfo, messageSecurityContext.getIncomingProperties());
  188.                         this.jsonVerifierSignature = new JsonVerifySignature(trustStoreSsl, trustStore, options);
  189.                     }
  190.                 }
  191.                 else {  
  192.                     KeyStore signatureKS = null;
  193.                     KeyStore signatureTrustStoreKS = null;
  194.                     JWKSet signatureJWKSet = null;
  195.                     String aliasSignatureUser = null;
  196.                     try {
  197.                         bean = KeystoreUtils.getReceiverSignatureBean(messageSecurityContext, ctx);
  198.                     }catch(Exception e) {
  199.                         // Lancio come messaggio eccezione precedente
  200.                         if(notFound!=null) {
  201.                             messageSecurityContext.getLog().error(e.getMessage(),e);
  202.                             throw notFound;
  203.                         }
  204.                         else {
  205.                             throw e;
  206.                         }
  207.                     }
  208.                    
  209.                     signatureKS = bean.getKeystore();
  210.                     signatureTrustStoreKS = bean.getTruststore();
  211.                     signatureJWKSet = bean.getJwkSet();
  212.                     aliasSignatureUser = bean.getUser();

  213.                     if(signatureKS==null && signatureTrustStoreKS==null && signatureJWKSet==null) {
  214.                         throw new SecurityException(JOSECostanti.JOSE_ENGINE_VERIFIER_SIGNATURE_DESCRIPTION+" require truststore");
  215.                     }
  216.                     if(aliasSignatureUser==null) {
  217.                         throw new SecurityException(JOSECostanti.JOSE_ENGINE_VERIFIER_SIGNATURE_DESCRIPTION+" require alias certificate");
  218.                     }
  219.                    
  220.                     String signatureAlgorithm = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.SIGNATURE_ALGORITHM);
  221.                     if(signatureAlgorithm==null || "".equals(signatureAlgorithm.trim())){
  222.                         throw new SecurityException(JOSECostanti.JOSE_ENGINE_VERIFIER_SIGNATURE_DESCRIPTION+" require '"+SecurityConstants.SIGNATURE_ALGORITHM+"' property");
  223.                     }
  224.                    
  225.                     String symmetricKeyParam = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.SYMMETRIC_KEY);
  226.                     boolean symmetricKey = false;
  227.                     if(symmetricKeyParam!=null) {
  228.                         symmetricKey = SecurityConstants.SYMMETRIC_KEY_TRUE.equalsIgnoreCase(symmetricKeyParam);
  229.                     }
  230.                    
  231.                     if(signatureTrustStoreKS!=null) {
  232.                         this.jsonVerifierSignature = new JsonVerifySignature(signatureTrustStoreKS, aliasSignatureUser, signatureAlgorithm, options);  
  233.                     }
  234.                     else if(signatureKS!=null){
  235.                         this.jsonVerifierSignature = new JsonVerifySignature(signatureKS, aliasSignatureUser, signatureAlgorithm, options);
  236.                     }
  237.                     else {
  238.                         this.jsonVerifierSignature = new JsonVerifySignature(signatureJWKSet.getJsonWebKeys(), symmetricKey, aliasSignatureUser, signatureAlgorithm, options);  
  239.                     }
  240.                 }
  241.                
  242.                 String signatureDetachedParam = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.SIGNATURE_DETACHED);
  243.                 if(signatureDetachedParam!=null) {
  244.                     this.detached = SecurityConstants.SIGNATURE_DETACHED_TRUE.equalsIgnoreCase(signatureDetachedParam);
  245.                 }
  246.                
  247.                 String detachedSignature = null;
  248.                 if(this.detached) {
  249.                     detachedSignature = this.readDetachedSignatureFromMessage(messageSecurityContext.getIncomingProperties(),
  250.                             restJsonMessage, JOSECostanti.JOSE_ENGINE_VERIFIER_SIGNATURE_DESCRIPTION);
  251.                 }
  252.                
  253.                 String signatureValidityCheck = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.SIGNATURE_VALIDITY_CHECK);
  254.                 if(signatureValidityCheck!=null && StringUtils.isNotEmpty(signatureValidityCheck)) {
  255.                     CertificateValidityCheck c = CertificateValidityCheck.parseCertificateValidityCheck(signatureValidityCheck);
  256.                     if(c!=null) {
  257.                         this.jsonVerifierSignature.setValidityCheck(c);
  258.                     }
  259.                 }
  260.                
  261.                 String signatureCRL = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.SIGNATURE_CRL);
  262.                 if(signatureCRL==null || "".equals(signatureCRL)) {
  263.                     signatureCRL = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_CRL);  
  264.                 }
  265.                 String signatureOCSP = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.SIGNATURE_OCSP);
  266.                 if(signatureOCSP==null || "".equals(signatureOCSP)) {
  267.                     signatureOCSP = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_OCSP);    
  268.                 }
  269.                
  270.                 boolean crlByOcsp = false;
  271.                 if(this.jsonVerifierSignature.getTrustStoreCertificatiX509()!=null && signatureOCSP!=null && !"".equals(signatureOCSP)) {
  272.                     LoggerBuffer lb = new LoggerBuffer();
  273.                     lb.setLogDebug(messageSecurityContext.getLog());
  274.                     lb.setLogError(messageSecurityContext.getLog());
  275.                     GestoreOCSPResource ocspResourceReader = new GestoreOCSPResource(requestInfo);
  276.                     IOCSPValidator ocspValidator = null;
  277.                     try {
  278.                         ocspValidator = new GestoreOCSPValidator(requestInfo, lb,
  279.                                 this.jsonVerifierSignature.getTrustStoreCertificatiX509(),
  280.                                 signatureCRL,
  281.                                 signatureOCSP,
  282.                                 ocspResourceReader);
  283.                     }catch(Exception e){
  284.                         throw new SecurityException(JOSECostanti.JOSE_ENGINE_VERIFIER_SIGNATURE_DESCRIPTION+"; ocsp initialization (policy:'"+signatureOCSP+"') failed: "+e.getMessage(),e);
  285.                     }
  286.                     if(ocspValidator!=null) {
  287.                         this.jsonVerifierSignature.setOcspValidatorX509(ocspValidator);
  288.                         GestoreOCSPValidator gOcspValidator = (GestoreOCSPValidator) ocspValidator;
  289.                         if(gOcspValidator.getOcspConfig()!=null) {
  290.                             crlByOcsp = gOcspValidator.getOcspConfig().isCrl();
  291.                         }
  292.                     }
  293.                 }
  294.                
  295.                 if(signatureCRL!=null && !"".equals(signatureCRL) && !crlByOcsp) {
  296.                     CRLCertstore crlCertstore = GestoreKeystoreCache.getCRLCertstore(requestInfo, signatureCRL);
  297.                     if(crlCertstore==null) {
  298.                         throw new SecurityException("Process CRL '"+signatureCRL+"' failed");
  299.                     }
  300.                     this.jsonVerifierSignature.setCrlX509(crlCertstore.getCertStore());
  301.                 }
  302.                
  303.                 String httpsCRL = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_CRL);
  304.                 String httpsOCSP = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_OCSP);
  305.                
  306.                 boolean httpsCrlByOcsp = false;
  307.                 if(this.jsonVerifierSignature.getTrustStoreHttps()!=null && httpsOCSP!=null && !"".equals(httpsOCSP)) {
  308.                     LoggerBuffer lb = new LoggerBuffer();
  309.                     lb.setLogDebug(messageSecurityContext.getLog());
  310.                     lb.setLogError(messageSecurityContext.getLog());
  311.                     GestoreOCSPResource ocspResourceReader = new GestoreOCSPResource(requestInfo);
  312.                     IOCSPValidator ocspValidator = null;
  313.                     try {
  314.                         ocspValidator = new GestoreOCSPValidator(requestInfo, lb,
  315.                                 this.jsonVerifierSignature.getTrustStoreHttps(),
  316.                                 httpsCRL,
  317.                                 httpsOCSP,
  318.                                 ocspResourceReader);
  319.                     }catch(Exception e){
  320.                         throw new SecurityException(JOSECostanti.JOSE_ENGINE_VERIFIER_SIGNATURE_DESCRIPTION+"; ocsp initialization for https (policy:'"+signatureOCSP+"') failed: "+e.getMessage(),e);
  321.                     }
  322.                     if(ocspValidator!=null) {
  323.                         this.jsonVerifierSignature.setOcspValidatorHttps(ocspValidator);
  324.                         GestoreOCSPValidator gOcspValidator = (GestoreOCSPValidator) ocspValidator;
  325.                         if(gOcspValidator.getOcspConfig()!=null) {
  326.                             httpsCrlByOcsp = gOcspValidator.getOcspConfig().isCrl();
  327.                         }
  328.                     }
  329.                 }
  330.                
  331.                 if(httpsCRL!=null && !"".equals(httpsCRL) && !httpsCrlByOcsp) {
  332.                     CRLCertstore crlCertstore = GestoreKeystoreCache.getCRLCertstore(requestInfo, httpsCRL);
  333.                     if(crlCertstore==null) {
  334.                         throw new SecurityException("Process CRL '"+httpsCRL+"' failed");
  335.                     }
  336.                     this.jsonVerifierSignature.setCrlHttps(crlCertstore.getCertStore());
  337.                 }
  338.                
  339.                 // **************** Process **************************

  340.                 signatureProcess = true; // le eccezioni lanciate da adesso sono registrato con codice relative alla verifica
  341.                 boolean verify = false;
  342.                 try {
  343.                     if(this.detached) {
  344.                         verify = this.jsonVerifierSignature.verifyDetached(detachedSignature, restJsonMessage.getContent(bufferMessageReadOnly, idTransazione));
  345.                     }else {
  346.                         verify = this.jsonVerifierSignature.verify(restJsonMessage.getContent(bufferMessageReadOnly, idTransazione));
  347.                     }
  348.                 }catch(Exception e) {
  349.                     throw new SecurityException("Signature verification failed: "+e.getMessage(),e);
  350.                 }
  351.                 if(!verify) {
  352.                     throw new SecurityException("Signature verification failed");
  353.                 }
  354.                
  355.             } // fine signature
  356.            
  357.            
  358.            
  359.             else if(encrypt) {
  360.                
  361.                
  362.                 // **************** Leggo parametri encryption store **************************
  363.                            
  364.                 String mode = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.DECRYPTION_MODE);
  365.                 if(mode==null || "".equals(mode.trim())){
  366.                     throw new SecurityException(JOSECostanti.JOSE_ENGINE_DECRYPT_DESCRIPTION+" require '"+SecurityConstants.DECRYPTION_MODE+"' property");
  367.                 }
  368.                 try {
  369.                     this.joseSerialization = JOSEUtils.toJOSESerialization(mode);
  370.                 }catch(Exception e) {
  371.                     throw new SecurityException(JOSECostanti.JOSE_ENGINE_DECRYPT_DESCRIPTION+", '"+SecurityConstants.DECRYPTION_MODE+"' property error: "+e.getMessage(),e);
  372.                 }
  373.                 JWTOptions options = new JWTOptions(this.joseSerialization);
  374.                 boolean useHeaders = JOSEUtils.useJwtHeadersMap(messageSecurityContext.getIncomingProperties(), options);
  375.                
  376.                 EncryptionBean bean = null;
  377.                 NotFoundException notFound = null;
  378.                 try {
  379.                     bean = PropertiesUtils.getReceiverEncryptionBean(messageSecurityContext);
  380.                 }catch(NotFoundException e) {
  381.                     notFound = e;
  382.                 }
  383.                 if(bean!=null) {
  384.                     Properties encryptionProperties = bean.getProperties();
  385.                     boolean throwError = true;
  386.                     Map<String,Object> dynamicMap = Costanti.readDynamicMap(ctx);
  387.                     JOSEUtils.injectKeystore(requestInfo, dynamicMap, encryptionProperties, messageSecurityContext.getLog(), throwError); // serve per leggere il keystore dalla cache
  388.                     this.jsonDecrypt = new JsonDecrypt(encryptionProperties, options);  
  389.                 }
  390.                 else if(useHeaders) {
  391.                     KeyStore trustStoreSsl = JOSEUtils.readTrustStoreSsl(requestInfo, messageSecurityContext.getIncomingProperties());
  392.                     if(JOSEUtils.isJWKSetKeyStore(messageSecurityContext.getIncomingProperties())) {
  393.                         JsonWebKeys jsonWebKeys = null;
  394.                         JWKSet jkwSet = JOSEUtils.readKeyStoreJwtJsonWebKeysCert(requestInfo, messageSecurityContext.getIncomingProperties());
  395.                         if(jkwSet!=null) {
  396.                             jsonWebKeys = jkwSet.getJsonWebKeys();
  397.                         }
  398.                         this.jsonDecrypt = new JsonDecrypt(trustStoreSsl, jsonWebKeys, options);
  399.                     }
  400.                     else {
  401.                         KeyStore trustStore = JOSEUtils.readTrustStoreJwtX509Cert(requestInfo, messageSecurityContext.getIncomingProperties());
  402.                         KeyStore keyStore = JOSEUtils.readKeyStoreJwtX509Cert(requestInfo, messageSecurityContext.getIncomingProperties());
  403.                         Map<String, String> keystoreMapAliasPassword = JOSEUtils.covertToJwtX509CertMapAliasPassword(messageSecurityContext.getIncomingProperties());                      
  404.                         this.jsonDecrypt = new JsonDecrypt(trustStoreSsl, trustStore, keyStore, keystoreMapAliasPassword, options);
  405.                     }
  406.                 }
  407.                 else {  
  408.                     KeyStore encryptionKS = null;
  409.                     boolean encryptionSymmetric = false;
  410.                     JWKSet encryptionJWKSet = null;
  411.                     String aliasEncryptUser = null;
  412.                     String aliasEncryptPassword = null;
  413.                     try {
  414.                         bean = KeystoreUtils.getReceiverEncryptionBean(messageSecurityContext, ctx);
  415.                     }catch(Exception e) {
  416.                         // Lancio come messaggio eccezione precedente
  417.                         if(notFound!=null) {
  418.                             messageSecurityContext.getLog().error(e.getMessage(),e);
  419.                             throw notFound;
  420.                         }
  421.                         else {
  422.                             throw e;
  423.                         }
  424.                     }
  425.                    
  426.                     encryptionKS = bean.getKeystore();
  427.                     encryptionSymmetric = bean.isEncryptionSimmetric();
  428.                     encryptionJWKSet = bean.getJwkSet();
  429.                     aliasEncryptUser = bean.getUser();
  430.                     aliasEncryptPassword = bean.getPassword();

  431.                     if(encryptionKS==null && encryptionJWKSet==null) {
  432.                         throw new SecurityException(JOSECostanti.JOSE_ENGINE_DECRYPT_DESCRIPTION+" require keystore");
  433.                     }
  434.                     if(aliasEncryptUser==null) {
  435.                         if(encryptionSymmetric) {
  436.                             throw new SecurityException(JOSECostanti.JOSE_ENGINE_DECRYPT_DESCRIPTION+" require alias secret key");
  437.                         }
  438.                         else {
  439.                             throw new SecurityException(JOSECostanti.JOSE_ENGINE_DECRYPT_DESCRIPTION+" require alias private key");
  440.                         }
  441.                     }
  442.                     if(encryptionKS!=null && aliasEncryptPassword==null) {
  443.                         if(encryptionSymmetric) {
  444.                             throw new SecurityException(JOSECostanti.JOSE_ENGINE_DECRYPT_DESCRIPTION+" require password secret key");
  445.                         }
  446.                         else {
  447.                             boolean required = true;
  448.                             if(KeystoreType.JKS.isType(encryptionKS.getKeystoreType())) {
  449.                                 required = DBUtils.isKeystoreJksKeyPasswordRequired();
  450.                             }
  451.                             else if(KeystoreType.PKCS12.isType(encryptionKS.getKeystoreType())) {
  452.                                 required = DBUtils.isKeystorePkcs12KeyPasswordRequired();
  453.                             }
  454.                             if(required) {
  455.                                 throw new SecurityException(JOSECostanti.JOSE_ENGINE_DECRYPT_DESCRIPTION+" require password private key");
  456.                             }
  457.                         }
  458.                     }

  459.                     String encryptionKeyAlgorithm = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.ENCRYPTION_KEY_ALGORITHM);
  460.                     if(encryptionKeyAlgorithm==null || "".equals(encryptionKeyAlgorithm.trim())){
  461.                         throw new SecurityException(JOSECostanti.JOSE_ENGINE_DECRYPT_DESCRIPTION+" require '"+SecurityConstants.ENCRYPTION_KEY_ALGORITHM+"' property");
  462.                     }
  463.                    
  464.                     String encryptionContentAlgorithm = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.ENCRYPTION_CONTENT_ALGORITHM);
  465.                     if(encryptionContentAlgorithm==null || "".equals(encryptionContentAlgorithm.trim())){
  466.                         throw new SecurityException(JOSECostanti.JOSE_ENGINE_DECRYPT_DESCRIPTION+" require '"+SecurityConstants.ENCRYPTION_CONTENT_ALGORITHM+"' property");
  467.                     }
  468.                    
  469.                     if(encryptionKS!=null) {
  470.                         this.jsonDecrypt = new JsonDecrypt(encryptionKS, encryptionSymmetric, aliasEncryptUser, aliasEncryptPassword,
  471.                                 encryptionKeyAlgorithm, encryptionContentAlgorithm, options);  
  472.                     }
  473.                     else {
  474.                         this.jsonDecrypt = new JsonDecrypt(encryptionJWKSet.getJsonWebKeys(), encryptionSymmetric, aliasEncryptUser,
  475.                                 encryptionKeyAlgorithm, encryptionContentAlgorithm, options);  
  476.                     }

  477.                 }
  478.                
  479.                 String encryptionValidityCheck = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_VALIDITY_CHECK);
  480.                 if(encryptionValidityCheck!=null && StringUtils.isNotEmpty(encryptionValidityCheck)) {
  481.                     CertificateValidityCheck c = CertificateValidityCheck.parseCertificateValidityCheck(encryptionValidityCheck);
  482.                     if(c!=null) {
  483.                         this.jsonDecrypt.setValidityCheck(c);
  484.                     }
  485.                 }
  486.                
  487.                 String encryptionCRL = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_CRL);
  488.                 String encryptionOCSP = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_OCSP);
  489.                
  490.                 boolean crlByOcsp = false;
  491.                 if(this.jsonDecrypt.getTrustStoreVerificaCertificatiX509()!=null && encryptionOCSP!=null && !"".equals(encryptionOCSP)) {
  492.                     LoggerBuffer lb = new LoggerBuffer();
  493.                     lb.setLogDebug(messageSecurityContext.getLog());
  494.                     lb.setLogError(messageSecurityContext.getLog());
  495.                     GestoreOCSPResource ocspResourceReader = new GestoreOCSPResource(requestInfo);
  496.                     IOCSPValidator ocspValidator = null;
  497.                     try {
  498.                         ocspValidator = new GestoreOCSPValidator(requestInfo, lb,
  499.                                 this.jsonDecrypt.getTrustStoreVerificaCertificatiX509(),
  500.                                 encryptionCRL,
  501.                                 encryptionOCSP,
  502.                                 ocspResourceReader);
  503.                     }catch(Exception e){
  504.                         throw new SecurityException(JOSECostanti.JOSE_ENGINE_DECRYPT_DESCRIPTION+"; ocsp initialization (policy:'"+encryptionOCSP+"') failed: "+e.getMessage(),e);
  505.                     }
  506.                     if(ocspValidator!=null) {
  507.                         this.jsonDecrypt.setOcspValidatorX509(ocspValidator);
  508.                         GestoreOCSPValidator gOcspValidator = (GestoreOCSPValidator) ocspValidator;
  509.                         if(gOcspValidator.getOcspConfig()!=null) {
  510.                             crlByOcsp = gOcspValidator.getOcspConfig().isCrl();
  511.                         }
  512.                     }
  513.                 }
  514.                
  515.                 if(encryptionCRL!=null && !"".equals(encryptionCRL) && !crlByOcsp) {
  516.                     CRLCertstore crlCertstore = GestoreKeystoreCache.getCRLCertstore(requestInfo, encryptionCRL);
  517.                     if(crlCertstore==null) {
  518.                         throw new SecurityException("Process CRL '"+encryptionCRL+"' failed");
  519.                     }
  520.                     this.jsonDecrypt.setCrlX509(crlCertstore.getCertStore());
  521.                 }
  522.                
  523.                 String httpsCRL = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_CRL);
  524.                 String httpsOCSP = (String) messageSecurityContext.getIncomingProperties().get(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_OCSP);
  525.                
  526.                 boolean httpsCrlByOcsp = false;
  527.                 if(this.jsonDecrypt.getTrustStoreHttps()!=null && httpsOCSP!=null && !"".equals(httpsOCSP)) {
  528.                     LoggerBuffer lb = new LoggerBuffer();
  529.                     lb.setLogDebug(messageSecurityContext.getLog());
  530.                     lb.setLogError(messageSecurityContext.getLog());
  531.                     GestoreOCSPResource ocspResourceReader = new GestoreOCSPResource(requestInfo);
  532.                     IOCSPValidator ocspValidator = null;
  533.                     try {
  534.                         ocspValidator = new GestoreOCSPValidator(requestInfo, lb,
  535.                                 this.jsonDecrypt.getTrustStoreHttps(),
  536.                                 httpsCRL,
  537.                                 httpsOCSP,
  538.                                 ocspResourceReader);
  539.                     }catch(Exception e){
  540.                         throw new SecurityException(JOSECostanti.JOSE_ENGINE_DECRYPT_DESCRIPTION+"; ocsp initialization for https (policy:'"+httpsOCSP+"') failed: "+e.getMessage(),e);
  541.                     }
  542.                     if(ocspValidator!=null) {
  543.                         this.jsonDecrypt.setOcspValidatorHttps(ocspValidator);
  544.                         GestoreOCSPValidator gOcspValidator = (GestoreOCSPValidator) ocspValidator;
  545.                         if(gOcspValidator.getOcspConfig()!=null) {
  546.                             httpsCrlByOcsp = gOcspValidator.getOcspConfig().isCrl();
  547.                         }
  548.                     }
  549.                 }
  550.                
  551.                 if(httpsCRL!=null && !"".equals(httpsCRL) && !httpsCrlByOcsp) {
  552.                     CRLCertstore crlCertstore = GestoreKeystoreCache.getCRLCertstore(requestInfo, httpsCRL);
  553.                     if(crlCertstore==null) {
  554.                         throw new SecurityException("Process CRL '"+httpsCRL+"' failed");
  555.                     }
  556.                     this.jsonDecrypt.setCrlHttps(crlCertstore.getCertStore());
  557.                 }
  558.    
  559.                
  560.                 // **************** Process **************************
  561.                            
  562.                 encryptProcess = true; // le eccezioni lanciate da adesso sono registrato con codice relative alla verifica
  563.                 try {
  564.                     this.jsonDecrypt.decrypt(restJsonMessage.getContent(bufferMessageReadOnly, idTransazione));
  565.                 }catch(Exception e) {
  566.                     throw new SecurityException("Decrypt failed: "+e.getMessage(),e);
  567.                 }
  568.        
  569.            
  570.             } // fine encrypt
  571.            
  572.            
  573.            
  574.                        
  575.         } catch (Exception e) {
  576.            
  577.             SecurityException secException = new SecurityException(e.getMessage(), e);
  578.            
  579.            
  580.             /* **** MESSAGGIO ***** */
  581.             String msg = Utilities.getInnerNotEmptyMessageException(e).getMessage();
  582.            
  583.             Throwable innerExc = Utilities.getLastInnerException(e);
  584.             String innerMsg = null;
  585.             if(innerExc!=null){
  586.                 innerMsg = innerExc.getMessage();
  587.             }
  588.            
  589.             String messaggio = null;
  590.             if(msg!=null){
  591.                 messaggio = msg + "";
  592.                 if(innerMsg!=null && !innerMsg.equals(msg)){
  593.                     messaggio = messaggio + " ; " + innerMsg;
  594.                 }
  595.             }
  596.             else{
  597.                 if(innerMsg!=null){
  598.                     messaggio = innerMsg;
  599.                 }
  600.             }
  601.            
  602.             secException.setMsgErrore(messaggio);
  603.            
  604.            
  605.             /* ***** CODICE **** */
  606.            
  607.             if(signatureProcess){
  608.                 secException.setCodiceErrore(CodiceErroreCooperazione.SICUREZZA_FIRMA_NON_VALIDA);
  609.             }
  610.             else if(encryptProcess){
  611.                 secException.setCodiceErrore(CodiceErroreCooperazione.SICUREZZA_CIFRATURA_NON_VALIDA);
  612.             }
  613.             else {
  614.                 secException.setCodiceErrore(CodiceErroreCooperazione.SICUREZZA);
  615.             }
  616.            
  617.            
  618.             throw secException;
  619.         }

  620.     }

  621.     @Override
  622.     public void detachSecurity(MessageSecurityContext messageSecurityContext, OpenSPCoop2RestMessage<?> messageParam)
  623.             throws SecurityException {
  624.        
  625.         try {
  626.        
  627.             if(!ServiceBinding.REST.equals(messageParam.getServiceBinding())){
  628.                 throw new SecurityException(JOSECostanti.JOSE_ENGINE_DESCRIPTION+" usable only with REST Binding");
  629.             }
  630.             if(!MessageType.JSON.equals(messageParam.getMessageType())) {
  631.                 throw new SecurityException(JOSECostanti.JOSE_ENGINE_DESCRIPTION+" usable only with REST Binding and a json message, found: "+messageParam.getMessageType());
  632.             }
  633.             OpenSPCoop2RestJsonMessage restJsonMessage = messageParam.castAsRestJson();
  634.                    
  635.             if(this.jsonVerifierSignature!=null) {
  636.                 if(this.detached) {
  637.                     this.deleteDetachedSignatureFromMessage(restJsonMessage, JOSECostanti.JOSE_ENGINE_VERIFIER_SIGNATURE_DESCRIPTION);
  638.                 }  
  639.                 else {
  640.                     restJsonMessage.updateContent(this.jsonVerifierSignature.getDecodedPayload());
  641.                 }
  642.             }
  643.             else if(this.jsonDecrypt!=null) {
  644.                 restJsonMessage.updateContent(this.jsonDecrypt.getDecodedPayload());
  645.             }
  646.             else {
  647.                 throw new SecurityException(JOSECostanti.JOSE_ENGINE_DESCRIPTION+" (detach method) usable only after one function beetwen encrypt or signature");
  648.             }
  649.            
  650.         }catch(Exception e) {
  651.             throw new SecurityException(e.getMessage(), e);
  652.         }
  653.     }

  654.     public JOSESerialization getJoseSerialization() {
  655.         return this.joseSerialization;
  656.     }
  657.    
  658.     @Override
  659.     public String getCertificate() throws SecurityException {
  660.         if(this.jsonVerifierSignature!=null && this.jsonVerifierSignature.getX509Certificate()!=null) {
  661.             return this.jsonVerifierSignature.getX509Certificate().getSubjectX500Principal().toString();
  662.         }
  663.         else if(this.jsonDecrypt!=null && this.jsonDecrypt.getX509Certificate()!=null) {
  664.             return this.jsonDecrypt.getX509Certificate().getSubjectX500Principal().toString();
  665.         }
  666.         return null;
  667.     }

  668.     @Override
  669.     public X509Certificate getX509Certificate() throws SecurityException {
  670.         if(this.jsonVerifierSignature!=null) {
  671.             return this.jsonVerifierSignature.getX509Certificate();
  672.         }
  673.         else if(this.jsonDecrypt!=null) {
  674.             return this.jsonDecrypt.getX509Certificate();
  675.         }
  676.         return null;
  677.     }

  678.     @Override
  679.     public PublicKey getPublicKey() {
  680.         if(this.jsonVerifierSignature!=null) {
  681.             return this.jsonVerifierSignature.getRsaPublicKey();
  682.         }
  683.         else if(this.jsonDecrypt!=null) {
  684.             return this.jsonDecrypt.getRsaPublicKey();
  685.         }
  686.         return null;
  687.     }

  688.     @Override
  689.     public String getCertificateId() {
  690.         if(this.jsonVerifierSignature!=null) {
  691.             return this.jsonVerifierSignature.getKid();
  692.         }
  693.         else if(this.jsonDecrypt!=null) {
  694.             return this.jsonDecrypt.getKid();
  695.         }
  696.         return null;
  697.     }
  698.    
  699. }