MessageSecurityReceiver_wss4j.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.wss4j;

  21. import java.io.ByteArrayOutputStream;
  22. import java.io.FileNotFoundException;
  23. import java.io.PrintStream;
  24. import java.net.URISyntaxException;
  25. import java.security.KeyStore;
  26. import java.security.Principal;
  27. import java.security.PublicKey;
  28. import java.security.cert.Certificate;
  29. import java.security.cert.X509Certificate;
  30. import java.util.ArrayList;
  31. import java.util.HashMap;
  32. import java.util.List;
  33. import java.util.Map;
  34. import java.util.Properties;

  35. import javax.security.auth.callback.CallbackHandler;
  36. import javax.xml.namespace.QName;
  37. import javax.xml.soap.SOAPMessage;

  38. import org.apache.cxf.binding.soap.SoapMessage;
  39. import org.apache.cxf.message.Attachment;
  40. import org.apache.cxf.message.Exchange;
  41. import org.apache.cxf.message.ExchangeImpl;
  42. import org.apache.cxf.message.MessageImpl;
  43. import org.apache.cxf.ws.security.wss4j.WSS4JInInterceptor;
  44. import org.apache.wss4j.common.crypto.Merlin;
  45. import org.apache.wss4j.common.ext.WSSecurityException;
  46. import org.apache.wss4j.dom.WSConstants;
  47. import org.apache.wss4j.dom.WSDataRef;
  48. import org.apache.wss4j.dom.engine.WSSecurityEngineResult;
  49. import org.apache.wss4j.dom.handler.WSHandlerConstants;
  50. import org.apache.wss4j.dom.handler.WSHandlerResult;
  51. import org.apache.wss4j.dom.message.token.Timestamp;
  52. import org.apache.wss4j.dom.str.STRParser;
  53. import org.openspcoop2.core.constants.Costanti;
  54. import org.openspcoop2.message.MessageUtils;
  55. import org.openspcoop2.message.OpenSPCoop2Message;
  56. import org.openspcoop2.message.OpenSPCoop2SoapMessage;
  57. import org.openspcoop2.message.constants.MessageType;
  58. import org.openspcoop2.message.constants.ServiceBinding;
  59. import org.openspcoop2.message.soap.reference.Reference;
  60. import org.openspcoop2.protocol.sdk.Busta;
  61. import org.openspcoop2.protocol.sdk.constants.CodiceErroreCooperazione;
  62. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  63. import org.openspcoop2.security.SecurityException;
  64. import org.openspcoop2.security.keystore.CRLCertstore;
  65. import org.openspcoop2.security.keystore.KeystoreConstants;
  66. import org.openspcoop2.security.keystore.MerlinTruststore;
  67. import org.openspcoop2.security.keystore.cache.GestoreKeystoreCache;
  68. import org.openspcoop2.security.keystore.cache.GestoreOCSPResource;
  69. import org.openspcoop2.security.keystore.cache.GestoreOCSPValidator;
  70. import org.openspcoop2.security.message.AbstractSOAPMessageSecurityReceiver;
  71. import org.openspcoop2.security.message.MessageSecurityContext;
  72. import org.openspcoop2.security.message.SubErrorCodeSecurity;
  73. import org.openspcoop2.security.message.constants.SecurityConstants;
  74. import org.openspcoop2.security.message.engine.MessageUtilities;
  75. import org.openspcoop2.security.message.engine.WSSUtilities;
  76. import org.openspcoop2.security.message.utils.AttachmentProcessingPart;
  77. import org.openspcoop2.security.message.utils.AttachmentsConfigReaderUtils;
  78. import org.openspcoop2.security.message.utils.EncryptionBean;
  79. import org.openspcoop2.security.message.utils.KeystoreUtils;
  80. import org.openspcoop2.utils.LoggerBuffer;
  81. import org.openspcoop2.utils.Utilities;
  82. import org.openspcoop2.utils.UtilsException;
  83. import org.openspcoop2.utils.certificate.CertificateInfo;
  84. import org.openspcoop2.utils.id.IDUtilities;
  85. import org.openspcoop2.utils.transport.http.IOCSPValidator;



  86. /**
  87.  * Classe per la gestione della WS-Security (WSDoAllReceiver).
  88.  *
  89.  * @author Lorenzo Nardi (nardi@link.it)
  90.  * @author Tommaso Burlon (tommaso.burlon@link.it)
  91.  * @author $Author$
  92.  * @version $Rev$, $Date$
  93.  *
  94.  */
  95. public class MessageSecurityReceiver_wss4j extends AbstractSOAPMessageSecurityReceiver{


  96.     @Override
  97.     public void process(MessageSecurityContext wssContext,OpenSPCoop2Message messageParam,Busta busta, org.openspcoop2.utils.Map<Object> ctx) throws SecurityException{
  98.         process(wssContext, messageParam, busta,
  99.                 false, null, ctx);
  100.     }
  101.     public void process(MessageSecurityContext wssContext,OpenSPCoop2Message messageParam,Busta busta,
  102.             boolean bufferMessage_readOnly, String idTransazione, org.openspcoop2.utils.Map<Object> ctx) throws SecurityException{
  103.         boolean certError = false;
  104.         boolean ocspError = false;
  105.         try{
  106.            
  107.             if(ServiceBinding.SOAP.equals(messageParam.getServiceBinding())==false){
  108.                 throw new SecurityException("WSS4J Engine usable only with SOAP Binding");
  109.             }
  110.             OpenSPCoop2SoapMessage message = messageParam.castAsSoap();
  111.             SOAPMessage soapMessage = MessageUtils.getSOAPMessage(message, bufferMessage_readOnly, idTransazione);
  112.            
  113.             RequestInfo requestInfo = null;
  114.             if(ctx!=null && ctx.containsKey(Costanti.REQUEST_INFO)) {
  115.                 requestInfo = (RequestInfo) ctx.get(Costanti.REQUEST_INFO);
  116.             }
  117.            
  118.            
  119.             // ** Inizializzo handler CXF **/
  120.            
  121.             WSS4JInInterceptor inHandler = new WSS4JInInterceptor();
  122.             SoapMessage msgCtx = new SoapMessage(new MessageImpl());
  123.             msgCtx.setVersion(MessageType.SOAP_12.equals(message.getMessageType()) ? org.apache.cxf.binding.soap.Soap12.getInstance() : org.apache.cxf.binding.soap.Soap11.getInstance());
  124.             Exchange ex = new ExchangeImpl();
  125.             ex.setInMessage(msgCtx);
  126.             msgCtx.setContent(SOAPMessage.class, soapMessage);
  127.             setIncomingProperties(wssContext,inHandler,msgCtx,requestInfo,ctx);
  128.            
  129.            
  130.             // ** Registro attachments da trattare **/
  131.            
  132.             AttachmentProcessingPart app = AttachmentsConfigReaderUtils.getSecurityOnAttachments(wssContext);
  133.             List<Attachment> listAttachments = null;
  134.             if(app!=null){
  135.                 // Non è possibile effettuare il controllo della posizione puntuale sulla ricezione.
  136.                 // Può essere usato solo per specificare quale attach firmare/cifrare in spedizione
  137.                 // Alcune implementazioni modificano l'ordine degli attachments una volta applicata la sicurezza
  138.                 if(app.isAllAttachments()==false){
  139.                     List<String> cidAttachmentsForSecurity = AttachmentsConfigReaderUtils.getListCIDAttachmentsForSecurity(wssContext);
  140.                     listAttachments = org.openspcoop2.security.message.wss4j.WSSUtilities.readAttachments(cidAttachmentsForSecurity, message, msgCtx);
  141.                 }
  142.                 else{
  143.                     listAttachments = org.openspcoop2.security.message.wss4j.WSSUtilities.readAttachments(app, message, msgCtx);
  144.                 }
  145.                 if(listAttachments!=null && listAttachments.size()>0){
  146.                     msgCtx.setAttachments(listAttachments);
  147.                 }
  148.             }
  149.            
  150.            
  151.             // ** Applico sicurezza tramite CXF **/
  152.            
  153.             inHandler.handleMessage(msgCtx);
  154.             List<?> results = (List<?>) msgCtx.getContextualProperty(WSHandlerConstants.RECV_RESULTS);
  155.             wssContext.getLog().debug("Print wssRecever results...");
  156.             org.openspcoop2.security.message.wss4j.WSSUtilities.printWSResult(wssContext.getLog(), results);
  157.            
  158.            
  159.             // ** Riporto modifica degli attachments **/
  160.            
  161.             org.openspcoop2.security.message.wss4j.WSSUtilities.updateAttachments(listAttachments, message, msgCtx);
  162.            
  163.            
  164.             // ** Lettura Subject Certificato e informazioni relative al processamento effettuato **/
  165.            
  166.             boolean validateX509 = this.examineResults(msgCtx, wssContext.getActor());
  167.            
  168.            
  169.             // ** Validazione CRL se non effettuata dall'handler (indicazione arriva dal metodo examineResults) **
  170.            
  171.             if(validateX509) {
  172.                 if(this.x509Certificate!=null && this.crlX509!=null) {
  173.                     try {
  174.                         CertificateInfo certificatoInfo = new CertificateInfo(this.x509Certificate, "x509");
  175.                         certificatoInfo.checkValid(this.crlX509.getCertStore(), this.trustStore);
  176.                     }catch(Throwable e) {
  177.                         certError = true;
  178.                         throw new Exception(e.getMessage(),e);
  179.                     }
  180.                 }  
  181.             }
  182.            
  183.             // ** Lettura Subject Certificato e informazioni relative al processamento effettuato **/
  184.            
  185.             if(this.ocspValidator!=null) {
  186.                 X509Certificate cert = this.x509Certificate;
  187.                 if(cert==null && this.x509Certificates!=null && this.x509Certificates.length>0) {
  188.                     cert = this.x509Certificates[0];
  189.                 }
  190.                 if(cert!=null) {
  191.                     try {
  192.                         this.ocspValidator.valid(cert);
  193.                     }catch(Throwable e) {
  194.                         ocspError = true;
  195.                         throw e;
  196.                     }
  197.                 }
  198.             }          
  199.            
  200.         } catch (Throwable e) {
  201.            
  202.             SecurityException wssException = null;
  203.            
  204.            
  205.             /* **** MESSAGGIO ***** */
  206.             String msg = Utilities.getInnerNotEmptyMessageException(e).getMessage();
  207.            
  208.             Throwable innerExc = Utilities.getLastInnerException(e);
  209.             String innerMsg = null;
  210.             if(innerExc!=null){
  211.                 innerMsg = innerExc.getMessage();
  212.             }
  213.            
  214.             String messaggio = null;
  215.             if(msg!=null){
  216.                 messaggio = new String(msg);
  217.                 if(innerMsg!=null && !innerMsg.equals(msg)){
  218.                     messaggio = messaggio + " ; " + innerMsg;
  219.                 }
  220.             }
  221.             else{
  222.                 if(innerMsg!=null){
  223.                     messaggio = innerMsg;
  224.                 }
  225.             }
  226.            
  227.             // L'if scopre l'eventuale motivo preciso riguardo al fallimento della cifratura/firma.
  228.             if(Utilities.existsInnerException(e, WSSecurityException.class)){
  229.                 Throwable t = Utilities.getLastInnerException(e);
  230.                 if(t instanceof WSSecurityException){
  231.                     if(messaggio!=null){
  232.                         messaggio = messaggio + " ; " + t.getMessage();
  233.                     }
  234.                     else{
  235.                         messaggio = t.getMessage();
  236.                     }
  237.                 }
  238.             }
  239.            
  240.             wssException = new SecurityException(messaggio, e);
  241.             wssException.setMsgErrore(messaggio);
  242.            
  243.            
  244.             /* ***** CODICE **** */
  245.            
  246.             boolean signature = false;
  247.             boolean encrypt = false;
  248.             try{
  249.                 ByteArrayOutputStream bout = new ByteArrayOutputStream();
  250.                 PrintStream printStream = new PrintStream(bout);
  251.                 e.printStackTrace(printStream);
  252.                 bout.flush();
  253.                 printStream.flush();
  254.                 bout.close();
  255.                 printStream.close();
  256.                
  257.                 if(certError) {
  258.                     signature = true; // per adesso avviene solo con SAML
  259.                 }
  260.                 else if(ocspError) {
  261.                     signature = true;
  262.                 }
  263.                 else if(bout.toString().contains(".processor.SignatureProcessor")){
  264.                     signature = true;
  265.                 }
  266.                 else if(bout.toString().contains(".processor.SignatureConfirmationProcessor")){
  267.                     signature = true;
  268.                 }
  269.                 else if(bout.toString().contains(".processor.EncryptedKeyProcessor")){
  270.                     encrypt = true;
  271.                 }
  272.                 else if(bout.toString().contains(".processor.EncryptedDataProcessor")){
  273.                     encrypt = true;
  274.                 }
  275.                
  276.             }catch(Exception eClose){}
  277.            
  278.             if(signature){
  279.                 wssException.setCodiceErrore(CodiceErroreCooperazione.SICUREZZA_FIRMA_NON_VALIDA);
  280.             }
  281.             else if(encrypt){
  282.                 wssException.setCodiceErrore(CodiceErroreCooperazione.SICUREZZA_CIFRATURA_NON_VALIDA);
  283.             }
  284.             else if(Utilities.existsInnerMessageException(e, "The signature or decryption was invalid", true)){
  285.                 wssException.setCodiceErrore(CodiceErroreCooperazione.SICUREZZA_FIRMA_NON_VALIDA);
  286.             } else {
  287.                 wssException.setCodiceErrore(CodiceErroreCooperazione.SICUREZZA);
  288.             }
  289.            
  290.            
  291.             throw wssException;
  292.         }

  293.     }

  294.     private Timestamp timestamp;
  295.     public Timestamp getTimestamp() {
  296.         return this.timestamp;
  297.     }
  298.    
  299.     private List<WSDataRef> signatureRefs;
  300.     public List<WSDataRef> getSignatureRefs() {
  301.         return this.signatureRefs;
  302.     }

  303.     private List<WSDataRef> encryptionRefs;
  304.     public List<WSDataRef> getEncryptionRefs() {
  305.         return this.encryptionRefs;
  306.     }
  307.    
  308.     private String certificate;
  309.     private STRParser.REFERENCE_TYPE x509ReferenceType;
  310.     private X509Certificate x509Certificate;
  311.     private X509Certificate [] x509Certificates;
  312.     private PublicKey publicKey;
  313.     @Override
  314.     public String getCertificate() throws SecurityException{
  315.         return this.certificate;
  316.     }
  317.     public STRParser.REFERENCE_TYPE getX509ReferenceType() {
  318.         return this.x509ReferenceType;
  319.     }
  320.     @Override
  321.     public X509Certificate getX509Certificate() throws SecurityException {
  322.         return this.x509Certificate;
  323.     }
  324.     public X509Certificate[] getX509Certificates() {
  325.         return this.x509Certificates;
  326.     }
  327.     @Override
  328.     public PublicKey getPublicKey() {
  329.         return this.publicKey;
  330.     }
  331.     @Override
  332.     public String getCertificateId() throws SecurityException{
  333.         return null;
  334.     }

  335.     private IOCSPValidator ocspValidator;
  336.     private org.openspcoop2.utils.certificate.KeyStore trustStore = null;
  337.     private CRLCertstore crlX509 = null;
  338.     private void setIncomingProperties(MessageSecurityContext wssContext,WSS4JInInterceptor interceptor, SoapMessage msgCtx, RequestInfo requestInfo,
  339.             org.openspcoop2.utils.Map<Object> ctx) throws SecurityException {
  340.         Map<String,Object> wssIncomingProperties =  wssContext.getIncomingProperties();
  341.         String ocspPolicy = null;
  342.         String crls = null;
  343.         Properties pTrustStore = null;
  344.         boolean samlSigned = false;
  345.         if (wssIncomingProperties != null && wssIncomingProperties.size() > 0) {
  346.            
  347.             // preprocess per multipropfile
  348.             try {
  349.                 preprocessMultipropFile(wssContext, msgCtx, wssIncomingProperties, requestInfo, ctx);
  350.             }catch(Exception e) {
  351.                 throw new SecurityException(e.getMessage(),e);
  352.             }
  353.            
  354.             for (String key : wssIncomingProperties.keySet()) {
  355.                 Object oValue = wssIncomingProperties.get(key);
  356.                 String value = null;
  357.                 if(oValue!=null && oValue instanceof String) {
  358.                     value = (String) oValue;
  359.                 }
  360.                 if(SecurityConstants.ACTION.equals(key)) {
  361.                     msgCtx.put(key, value);
  362.                     interceptor.setProperty(key, value);
  363.                     if(value!=null && value.contains(SecurityConstants.ACTION_SAML_TOKEN_SIGNED)) {
  364.                         samlSigned = true;
  365.                     }
  366.                 }
  367.                 else if(SecurityConstants.PASSWORD_CALLBACK_REF.equals(key)) {
  368.                     msgCtx.put(key, oValue);
  369.                 }
  370.                 else if(SecurityConstants.SIGNATURE_PROPERTY_REF_ID.equals(key) ||
  371.                         SecurityConstants.SIGNATURE_VERIFICATION_PROPERTY_REF_ID.equals(key) ||
  372.                         SecurityConstants.SIGNATURE_TRUSTSTORE_PROPERTY_REF_ID.equals(key) ||
  373.                         SecurityConstants.ENCRYPTION_PROPERTY_REF_ID.equals(key) ||
  374.                         SecurityConstants.DECRYPTION_PROPERTY_REF_ID.equals(key) ) {
  375.                     if(value!=null) {
  376.                         msgCtx.put(key, value);
  377.                     }
  378.                     else {
  379.                         String id = key+"_"+IDUtilities.getUniqueSerialNumber("wssSecurity.setIncomingProperties");
  380.                         msgCtx.put(key, id);
  381.                         msgCtx.put(id, oValue);
  382.                         if(oValue!=null && oValue instanceof Properties) {
  383.                             Properties p = (Properties) oValue;
  384.                             p.put(KeystoreConstants.PROPERTY_REQUEST_INFO, requestInfo);
  385.                             if(SecurityConstants.SIGNATURE_PROPERTY_REF_ID.equals(key) ||
  386.                                     SecurityConstants.SIGNATURE_VERIFICATION_PROPERTY_REF_ID.equals(key) ||
  387.                                     SecurityConstants.SIGNATURE_TRUSTSTORE_PROPERTY_REF_ID.equals(key) ) {
  388.                                 pTrustStore = p;
  389.                             }
  390.                         }
  391.                     }
  392.                 }
  393.                 else if(SecurityConstants.ENCRYPT_ACTION_OLD.equals(key)) {
  394.                     // backward compatibility per adeguamento costante rispetto a wss4j 2.3.x
  395.                     msgCtx.put(SecurityConstants.ENCRYPTION_ACTION, value);
  396.                     interceptor.setProperty(SecurityConstants.ENCRYPTION_ACTION, value);
  397.                 }
  398.                 else if(SecurityConstants.SIGNATURE_OCSP.equals(key)) {
  399.                     ocspPolicy = value;
  400.                 }
  401.                 else if(SecurityConstants.SIGNATURE_CRL.equals(key)) {
  402.                     crls = value;
  403.                 }
  404.                 else{
  405.                     msgCtx.put(key, value);
  406.                     interceptor.setProperty(key, value);
  407.                 }
  408.             }
  409.         }
  410.         if(wssContext.getActor()!=null){
  411.             interceptor.setProperty(SecurityConstants.ACTOR, wssContext.getActor());
  412.             msgCtx.put(SecurityConstants.ACTOR, wssContext.getActor());
  413.         }
  414.        
  415.         String prefixTrustStore = null;
  416.         if(pTrustStore!=null && !pTrustStore.isEmpty()) {
  417.             String trustStoreLocation = null;
  418.             try {
  419.                 //
  420.                 // Load the TrustStore (serve ad avere x509 in alcuni casi durante l'esamina della risposta)
  421.                 //
  422.                 prefixTrustStore = org.openspcoop2.security.keystore.MerlinProvider.readPrefix(pTrustStore);
  423.                
  424.                 trustStoreLocation = pTrustStore.getProperty(prefixTrustStore + Merlin.TRUSTSTORE_FILE);
  425.                 String trustStorePassword = null;
  426.                 String trustStoreType = null;
  427.                 if (trustStoreLocation == null) {
  428.                     trustStoreLocation = pTrustStore.getProperty(prefixTrustStore + Merlin.KEYSTORE_FILE);
  429.                     if (trustStoreLocation == null) {
  430.                         trustStoreLocation = pTrustStore.getProperty(prefixTrustStore + Merlin.OLD_KEYSTORE_FILE);
  431.                     }
  432.                     if (trustStoreLocation != null) {
  433.                         trustStorePassword = pTrustStore.getProperty(prefixTrustStore + Merlin.KEYSTORE_PASSWORD);
  434.                         if (trustStorePassword != null) {
  435.                             trustStorePassword = trustStorePassword.trim();
  436.                         }
  437.                         trustStoreType = pTrustStore.getProperty(prefixTrustStore + Merlin.KEYSTORE_TYPE, KeyStore.getDefaultType());
  438.                         if (trustStoreType != null) {
  439.                             trustStoreType = trustStoreType.trim();
  440.                         }
  441.                     }
  442.                 }
  443.                 else {
  444.                     trustStorePassword = pTrustStore.getProperty(prefixTrustStore + Merlin.TRUSTSTORE_PASSWORD);
  445.                     if (trustStorePassword != null) {
  446.                         trustStorePassword = trustStorePassword.trim();
  447.                     }
  448.                     trustStoreType = pTrustStore.getProperty(prefixTrustStore + Merlin.TRUSTSTORE_TYPE, KeyStore.getDefaultType());
  449.                     if (trustStoreType != null) {
  450.                         trustStoreType = trustStoreType.trim();
  451.                     }
  452.                 }
  453.                 if (trustStoreLocation != null) {
  454.                     trustStoreLocation = trustStoreLocation.trim();
  455.                     MerlinTruststore merlinTs = GestoreKeystoreCache.getMerlinTruststore(requestInfo, trustStoreLocation, trustStoreType,
  456.                             trustStorePassword);
  457.                     if(merlinTs==null) {
  458.                         throw new Exception("Accesso al truststore '"+trustStoreLocation+"' non riuscito");
  459.                     }
  460.                     if(merlinTs.getTrustStore()==null) {
  461.                         throw new Exception("Accesso al truststore '"+trustStoreLocation+"' non riuscito");
  462.                     }
  463.                     this.trustStore = merlinTs.getTrustStore();
  464.                 }
  465.             }catch(Exception e) {
  466.                 throw new SecurityException("[Truststore-File] '"+trustStoreLocation+"': "+e.getMessage(),e);
  467.             }
  468.         }
  469.        
  470.         boolean crlByOcsp = false;
  471.         if(ocspPolicy!=null&& !"".equals(ocspPolicy)) {
  472.            
  473.             if(this.trustStore!=null) {
  474.                 LoggerBuffer lb = new LoggerBuffer();
  475.                 lb.setLogDebug(wssContext.getLog());
  476.                 lb.setLogError(wssContext.getLog());
  477.                 GestoreOCSPResource ocspResourceReader = new GestoreOCSPResource(requestInfo);
  478.                 IOCSPValidator ocspValidator = null;
  479.                 try {
  480.                     ocspValidator = new GestoreOCSPValidator(requestInfo, lb,
  481.                             this.trustStore,
  482.                             crls,
  483.                             ocspPolicy,
  484.                             ocspResourceReader);
  485.                 }catch(Exception e){
  486.                     throw new SecurityException("SignatureVerifier; ocsp initialization (policy:'"+ocspPolicy+"') failed: "+e.getMessage(),e);
  487.                 }
  488.                 if(ocspValidator!=null) {
  489.                     this.ocspValidator = ocspValidator;
  490.                     GestoreOCSPValidator gOcspValidator = (GestoreOCSPValidator) ocspValidator;
  491.                     if(gOcspValidator.getOcspConfig()!=null) {
  492.                         crlByOcsp = gOcspValidator.getOcspConfig().isCrl();
  493.                     }
  494.                 }
  495.             }
  496.            
  497.             if(crlByOcsp) {
  498.                 // la validazione crl viene fatta tramite tool ocsp
  499.                 msgCtx.put(SecurityConstants.ENABLE_REVOCATION, SecurityConstants.FALSE);
  500.                 interceptor.setProperty(SecurityConstants.ENABLE_REVOCATION, SecurityConstants.FALSE);
  501.             }
  502.         }
  503.        
  504.         if(samlSigned && !crlByOcsp && this.trustStore!=null && pTrustStore!=null) {
  505.             String trustStoreCRLs = null;
  506.             try {
  507.                 trustStoreCRLs = pTrustStore.getProperty(prefixTrustStore + Merlin.X509_CRL_FILE);
  508.                 if(trustStoreCRLs!=null) {
  509.                     trustStoreCRLs = trustStoreCRLs.trim();
  510.                     this.crlX509 = GestoreKeystoreCache.getCRLCertstore(requestInfo, trustStoreCRLs);
  511.                 }
  512.             }catch(Exception e) {
  513.                 throw new SecurityException("[Truststore-CRLs] '"+trustStoreCRLs+"': "+e.getMessage(),e);
  514.             }
  515.         }
  516.     }

  517.     private void preprocessMultipropFile(MessageSecurityContext wssContext,SoapMessage msgCtx,Map<String,Object> wssIncomingProperties, RequestInfo requestInfo,org.openspcoop2.utils.Map<Object> ctx) throws FileNotFoundException, UtilsException, SecurityException, URISyntaxException {

  518.         Properties pTrustStoreSignatureVerification = null;
  519.        
  520.         String signatureCrls = null;
  521.         for (Map.Entry<String,Object> entry : wssIncomingProperties.entrySet()) {
  522.             if(SecurityConstants.SIGNATURE_CRL.equals(entry.getKey())) {
  523.                 signatureCrls = (String) entry.getValue();
  524.                 break;
  525.             }
  526.         }
  527.         String signatureCrlsValidateOnlyEndEntity = null;
  528.         if(signatureCrls!=null) {
  529.             for (Map.Entry<String,Object> entry : wssIncomingProperties.entrySet()) {
  530.                 if(SecurityConstants.SIGNATURE_CRL_VALIDATE_ONLY_END_ENTITY.equals(entry.getKey())) {
  531.                     signatureCrlsValidateOnlyEndEntity = (String) entry.getValue();
  532.                     break;
  533.                 }
  534.             }
  535.         }
  536.        
  537.         String forceDecryptionUser = null;
  538.        
  539.         for (Map.Entry<String,Object> entry : wssIncomingProperties.entrySet()) {
  540.             String key = entry.getKey();
  541.             if(SecurityConstants.SIGNATURE_TRUSTSTORE_PROPERTY_FILE.equals(key)) {
  542.                 Object o = wssIncomingProperties.get(key);
  543.                 if(o instanceof String) {
  544.                     String path = (String) o;
  545.                     MerlinTruststore merlinTruststore = GestoreKeystoreCache.getMerlinTruststore(requestInfo, path);
  546.                    
  547.                     pTrustStoreSignatureVerification = new Properties();
  548.                     pTrustStoreSignatureVerification.put(KeystoreConstants.PROPERTY_TRUSTSTORE_PATH, merlinTruststore.getPathStore());
  549.                     pTrustStoreSignatureVerification.put(KeystoreConstants.PROPERTY_TRUSTSTORE_PASSWORD, merlinTruststore.getPasswordStore());
  550.                     pTrustStoreSignatureVerification.put(KeystoreConstants.PROPERTY_TRUSTSTORE_TYPE, merlinTruststore.getTipoStore());
  551.                     pTrustStoreSignatureVerification.put(KeystoreConstants.PROPERTY_PROVIDER, KeystoreConstants.PROVIDER_GOVWAY);
  552.                     if(signatureCrls!=null) {
  553.                         pTrustStoreSignatureVerification.put(KeystoreConstants.PROPERTY_CRL, signatureCrls);
  554.                         if(signatureCrlsValidateOnlyEndEntity!=null) {
  555.                             pTrustStoreSignatureVerification.put(KeystoreConstants.PROPERTY_CRL_VALIDATE_ONLY_END_ENTITY, signatureCrlsValidateOnlyEndEntity);
  556.                         }
  557.                     }
  558.                 }
  559.             }
  560.             else if(SecurityConstants.DECRYPTION_MULTI_PROPERTY_FILE.equals(key)) {
  561.                 EncryptionBean bean = KeystoreUtils.getReceiverEncryptionBean(wssContext, ctx);
  562.                 if(bean.getMultiKeystore()==null) {
  563.                     throw new SecurityException("Multiproperty config not exists");
  564.                 }
  565.                 String keyAlias = bean.getUser();
  566.                 String internalAlias = bean.getMultiKeystore().getInternalConfigAlias(keyAlias);
  567.                 Properties p = new Properties();
  568.                 p.put(KeystoreConstants.PROPERTY_KEYSTORE_PATH, bean.getMultiKeystore().getKeystorePath(internalAlias));
  569.                 p.put(KeystoreConstants.PROPERTY_KEYSTORE_PASSWORD, bean.getMultiKeystore().getKeystorePassword(internalAlias));
  570.                 p.put(KeystoreConstants.PROPERTY_KEYSTORE_TYPE, bean.getMultiKeystore().getKeystoreType(internalAlias));
  571.                 p.put(KeystoreConstants.PROPERTY_PROVIDER, KeystoreConstants.PROVIDER_GOVWAY);
  572.                 p.put(KeystoreConstants.PROPERTY_REQUEST_INFO, requestInfo);
  573.                 String id = SecurityConstants.DECRYPTION_PROPERTY_REF_ID +"_"+IDUtilities.getUniqueSerialNumber("wssSecurity.setOutgoingProperties");
  574.                 msgCtx.put(SecurityConstants.DECRYPTION_PROPERTY_REF_ID , id);
  575.                 msgCtx.put(id, p);
  576.                
  577.                 HashMap<String, String> mapAliasToPassword = new HashMap<>();
  578.                 String password = bean.getPassword();
  579.                 msgCtx.put(SecurityConstants.DECRYPTION_PASSWORD, bean.getPassword());
  580.                 mapAliasToPassword.put(keyAlias, password);
  581.                 CallbackHandler pwCallbackHandler = MessageSecurityContext.newCallbackHandler(mapAliasToPassword);
  582.                 msgCtx.put(SecurityConstants.PASSWORD_CALLBACK_REF, pwCallbackHandler);
  583.                
  584.                 forceDecryptionUser = keyAlias;
  585.             }
  586.         }
  587.        
  588.         if(pTrustStoreSignatureVerification!=null) {
  589.             wssIncomingProperties.put(SecurityConstants.SIGNATURE_VERIFICATION_PROPERTY_REF_ID, pTrustStoreSignatureVerification);
  590.             if(signatureCrls!=null) {
  591.                 wssIncomingProperties.put(SecurityConstants.ENABLE_REVOCATION, SecurityConstants.TRUE);
  592.             }
  593.         }
  594.        
  595.         if(forceDecryptionUser!=null) {
  596.             wssIncomingProperties.remove(SecurityConstants.DECRYPTION_USER);
  597.             wssIncomingProperties.put(SecurityConstants.DECRYPTION_USER, forceDecryptionUser);
  598.         }
  599.        
  600.     }
  601.    
  602.     private boolean examineResults(SoapMessage msgCtx, String actor) {
  603.                
  604.         boolean validateX509 = false;
  605.        
  606.         List<?> results = (List<?>) msgCtx.get(WSHandlerConstants.RECV_RESULTS);
  607.         //System.out.println("Potential number of usernames: " + results.size());
  608.         for (int i = 0; results != null && i < results.size(); i++) {
  609.             //System.out.println("RESULT["+i+"]: "+results.get(i).getClass().getName());
  610.             WSHandlerResult hResult = (WSHandlerResult)results.get(i);
  611.             //System.out.println("RESULT["+i+"] actor: "+hResult.getActor());
  612.            
  613.             boolean actorCompatibile = false;
  614.             if(actor==null) {
  615.                 actorCompatibile = hResult.getActor()==null;
  616.             }
  617.             else {
  618.                 actorCompatibile = actor.equals(hResult.getActor());
  619.             }
  620.            
  621.             if(actorCompatibile) {
  622.                
  623.                 //System.out.println("RESULT["+i+"] ESAMINO SENZA ["+actor+"]");
  624.                
  625.                 List<WSSecurityEngineResult> hResults = hResult.getResults();
  626.                 for (int j = 0; j < hResults.size(); j++) {
  627.                     WSSecurityEngineResult eResult = hResults.get(j);
  628.                    
  629.                     /*
  630.                     Iterator<String> resultIt = eResult.keySet().iterator();
  631.                     while (resultIt.hasNext()) {
  632.                         String resultItKey = (String) resultIt.next();
  633.                         Object resultItObject = eResult.get(resultItKey);
  634.                         System.out.println("RESULT-INTERNAL ["+i+"]["+j+"] ["+resultItKey+"]["+resultItObject+"]["+(resultItObject!=null ? resultItObject.getClass().getName() : "n.d.")+"]");
  635.                     }*/
  636.                    
  637.                     int actionGet = ((java.lang.Integer)  eResult.get(WSSecurityEngineResult.TAG_ACTION)).intValue();
  638.                    
  639.                     // An encryption or timestamp action does not have an associated principal,
  640.                     // only Signature and UsernameToken actions return a principal
  641.                     if ((actionGet == WSConstants.SIGN) ||
  642.                             (actionGet == WSConstants.UT) ||
  643.                             (actionGet == WSConstants.UT_SIGN) ||
  644.                             (actionGet == WSConstants.ST_SIGNED)) {
  645.                        
  646.                         Object oPrincipal = eResult.get(WSSecurityEngineResult.TAG_PRINCIPAL);
  647.                         if(oPrincipal!=null && oPrincipal instanceof Principal) {
  648.                             Principal principal =  (Principal) oPrincipal;
  649.                             if(principal!=null) {
  650.                                 this.certificate = principal.getName();
  651.                             }
  652.                             if(oPrincipal instanceof org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl) {
  653.                                 org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl samlPrincipal = (org.apache.wss4j.common.principal.SAMLTokenPrincipalImpl) oPrincipal;
  654.                                 if(samlPrincipal.getToken()!=null) {
  655.                                     if(samlPrincipal.getToken().getSignatureKeyInfo()!=null) {
  656.                                         if(samlPrincipal.getToken().getSignatureKeyInfo().getCerts()!=null) {
  657.                                             if(this.x509Certificates==null) {
  658.                                                 this.x509Certificates = samlPrincipal.getToken().getSignatureKeyInfo().getCerts();
  659.                                             }
  660.                                         }
  661.                                         else if(samlPrincipal.getToken().getSignatureKeyInfo().getPublicKey()!=null) {
  662.                                             if(this.x509Certificate==null && this.trustStore!=null) {
  663.                                                 try {
  664.                                                     Certificate c = this.trustStore.getCertificateByPublicKey(samlPrincipal.getToken().getSignatureKeyInfo().getPublicKey());
  665.                                                     if(c!=null && (c instanceof X509Certificate)) {
  666.                                                         this.x509Certificate = (X509Certificate) c;
  667.                                                         validateX509 = true; // in saml handler non viene validato il certificato rispetto alla crl
  668.                                                     }
  669.                                                 }catch(Throwable t) {
  670.                                                     // ignore
  671.                                                 }
  672.                                             }
  673.                                         }
  674.                                     }
  675.                                 }
  676.                             }
  677.                         }
  678.    
  679.                         Object oX509Certificate = eResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATE);
  680.                         if(oX509Certificate!=null && oX509Certificate instanceof X509Certificate) {
  681.                             this.x509Certificate = (X509Certificate) oX509Certificate;
  682.                             if(this.x509Certificate!=null) {
  683.                                 this.publicKey = this.x509Certificate.getPublicKey();
  684.                             }
  685.                         }
  686.                            
  687.                         Object oListX509Certificates = eResult.get(WSSecurityEngineResult.TAG_X509_CERTIFICATES);
  688.                         if(oListX509Certificates!=null && oListX509Certificates instanceof X509Certificate []){
  689.                             this.x509Certificates = (X509Certificate []) oListX509Certificates;
  690.                            
  691.                             /*
  692.                             if(this.x509Certificates!=null && this.x509Certificates.length>0) {
  693.                                 System.out.println("CERTS: "+this.x509Certificates.length);
  694.                                 int index = 0;
  695.                                 for (X509Certificate X509Certificate : this.x509Certificates) {
  696.                                     System.out.println("CERT["+index+"]: "+X509Certificate.getSubjectX500Principal().toString());  
  697.                                     index ++;
  698.                                 }
  699.                             }
  700.                             */
  701.                            
  702.                         }
  703.                        
  704.                         Object oX509ReferenceType = eResult.get(WSSecurityEngineResult.TAG_X509_REFERENCE_TYPE);
  705.                         if(oX509ReferenceType!=null && oX509ReferenceType instanceof STRParser.REFERENCE_TYPE) {
  706.                             this.x509ReferenceType = (STRParser.REFERENCE_TYPE) oX509ReferenceType;
  707.                            
  708.                             //System.out.println("REFERENCE TYPE: "+this.x509ReferenceType);
  709.                         }
  710.                        
  711.                         Object oSignatureRefs = eResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS);
  712.                         if(oSignatureRefs!=null && oSignatureRefs instanceof List<?>) {
  713.                             List<WSDataRef> l = new ArrayList<WSDataRef>();
  714.                             List<?> lRefs = (List<?>) oSignatureRefs;
  715.                             for (Object oRef : lRefs) {
  716.                                 if(oRef!=null && oRef instanceof WSDataRef) {
  717.                                     l.add((WSDataRef)oRef);
  718.                                 }
  719.                             }
  720.                             if(!l.isEmpty()) {
  721.                                 this.signatureRefs = l;
  722.                             }
  723.                         }
  724.                     }
  725.                    
  726.                     if( actionGet == WSConstants.ENCR ) {
  727.                        
  728.                         Object oEncryptionRefs = eResult.get(WSSecurityEngineResult.TAG_DATA_REF_URIS);
  729.                         if(oEncryptionRefs!=null && oEncryptionRefs instanceof List<?>) {
  730.                             List<WSDataRef> l = new ArrayList<WSDataRef>();
  731.                             List<?> lRefs = (List<?>) oEncryptionRefs;
  732.                             for (Object oRef : lRefs) {
  733.                                 if(oRef!=null && oRef instanceof WSDataRef) {
  734.                                     l.add((WSDataRef)oRef);
  735.                                 }
  736.                             }
  737.                             if(!l.isEmpty()) {
  738.                                 this.encryptionRefs = l;
  739.                             }
  740.                         }
  741.                        
  742.                     }
  743.                    
  744.                     if( actionGet == WSConstants.TS ) {
  745.                        
  746.                         Object oTimestamp = eResult.get(WSSecurityEngineResult.TAG_TIMESTAMP);
  747.                         if(oTimestamp!=null && oTimestamp instanceof Timestamp) {
  748.                             this.timestamp =  (Timestamp) oTimestamp;
  749.                         }
  750.                        
  751.                     }
  752.                    
  753.                     if( actionGet == WSConstants.ST_SIGNED ) {
  754.                        
  755.                     }
  756.                    
  757.                 }
  758.                
  759.             }

  760.         }

  761.         /*
  762.         String key = "org.apache.cxf.headers.Header.list";
  763.         if(msgCtx.containsKey(key)) {
  764.             Object o = msgCtx.get(key);
  765.             if(o instanceof List<?> ) {
  766.                 List<?> l = (List<?>) o;
  767.                 System.out.println("SIZE ["+l.size()+"]");
  768.                 if(!l.isEmpty()) {
  769.                     int index = 0;
  770.                     for (Object entry : l) {
  771.                         if(entry!=null) {
  772.                             System.out.println("ENTRY ["+index+"]: "+entry.getClass().getName());
  773.                             if(entry instanceof org.apache.cxf.binding.soap.SoapHeader) {
  774.                                 org.apache.cxf.binding.soap.SoapHeader soapHdr = (org.apache.cxf.binding.soap.SoapHeader) entry;
  775.                                 System.out.println("HDR ("+soapHdr.getActor()+") ("+soapHdr.getObject().getClass().getName()+"): "+soapHdr.getName());
  776.                             }
  777.                            
  778.                         }
  779.                         index++;
  780.                     }
  781.                 }
  782.             }
  783.         }
  784.         */
  785.        
  786.         return validateX509;
  787.     }
  788.    

  789.     @Override
  790.     public List<Reference> getDirtyElements(
  791.             org.openspcoop2.security.message.MessageSecurityContext messageSecurityContext,
  792.             OpenSPCoop2SoapMessage message) throws SecurityException {
  793.         return WSSUtilities.getDirtyElements(messageSecurityContext, message);
  794.     }

  795.     @Override
  796.     public Map<QName, QName> checkEncryptSignatureParts(
  797.             org.openspcoop2.security.message.MessageSecurityContext messageSecurityContext,
  798.             List<Reference> elementsToClean, OpenSPCoop2SoapMessage message,
  799.             List<SubErrorCodeSecurity> codiciErrore) throws SecurityException {
  800.         return MessageUtilities.checkEncryptSignatureParts(messageSecurityContext, elementsToClean, message, codiciErrore, SecurityConstants.QNAME_WSS_ELEMENT_SECURITY);
  801.     }

  802.     @Override
  803.     public void checkEncryptionPartElements(Map<QName, QName> notResolved,
  804.             OpenSPCoop2SoapMessage message,
  805.             List<SubErrorCodeSecurity> erroriRilevati) throws SecurityException {
  806.         MessageUtilities.checkEncryptionPartElements(notResolved, message, erroriRilevati);
  807.     }

  808.     @Override
  809.     public void cleanDirtyElements(
  810.             org.openspcoop2.security.message.MessageSecurityContext messageSecurityContext,
  811.             OpenSPCoop2SoapMessage message, List<Reference> elementsToClean,
  812.             boolean detachHeaderWSSecurity, boolean removeAllIdRef)
  813.             throws SecurityException {
  814.         WSSUtilities.cleanDirtyElements(messageSecurityContext, message, elementsToClean,detachHeaderWSSecurity,removeAllIdRef);
  815.        
  816.     }
  817. }