ModIImbustamentoSoap.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.protocol.modipa.builder;

  21. import java.security.cert.Certificate;
  22. import java.security.cert.X509Certificate;
  23. import java.util.Date;
  24. import java.util.HashMap;
  25. import java.util.List;
  26. import java.util.Map;
  27. import java.util.Properties;

  28. import javax.xml.namespace.QName;
  29. import javax.xml.soap.SOAPBody;
  30. import javax.xml.soap.SOAPEnvelope;
  31. import javax.xml.soap.SOAPHeaderElement;

  32. import org.openspcoop2.core.constants.CostantiDB;
  33. import org.openspcoop2.core.constants.CostantiLabel;
  34. import org.openspcoop2.core.registry.AccordoServizioParteComune;
  35. import org.openspcoop2.message.OpenSPCoop2Message;
  36. import org.openspcoop2.message.OpenSPCoop2MessageFactory;
  37. import org.openspcoop2.message.OpenSPCoop2SoapMessage;
  38. import org.openspcoop2.message.constants.Costanti;
  39. import org.openspcoop2.message.soap.wsaddressing.WSAddressingHeader;
  40. import org.openspcoop2.message.soap.wsaddressing.WSAddressingUtilities;
  41. import org.openspcoop2.message.soap.wsaddressing.WSAddressingValue;
  42. import org.openspcoop2.message.xml.MessageDynamicNamespaceContextFactory;
  43. import org.openspcoop2.message.xml.XPathExpressionEngine;
  44. import org.openspcoop2.pdd.config.OpenSPCoop2Properties;
  45. import org.openspcoop2.pdd.core.byok.BYOKUnwrapPolicyUtilities;
  46. import org.openspcoop2.pdd.core.dynamic.DynamicMapBuilderUtils;
  47. import org.openspcoop2.protocol.modipa.config.ModIProperties;
  48. import org.openspcoop2.protocol.modipa.constants.ModICostanti;
  49. import org.openspcoop2.protocol.modipa.utils.ModIKeystoreConfig;
  50. import org.openspcoop2.protocol.modipa.utils.ModISecurityConfig;
  51. import org.openspcoop2.protocol.modipa.utils.ModIUtilities;
  52. import org.openspcoop2.protocol.modipa.utils.SOAPHeader;
  53. import org.openspcoop2.protocol.modipa.validator.ModISOAPSecurity;
  54. import org.openspcoop2.protocol.sdk.Busta;
  55. import org.openspcoop2.protocol.sdk.Context;
  56. import org.openspcoop2.protocol.sdk.ProtocolException;
  57. import org.openspcoop2.protocol.sdk.SecurityToken;
  58. import org.openspcoop2.protocol.sdk.SoapMessageSecurityToken;
  59. import org.openspcoop2.protocol.sdk.constants.RuoloMessaggio;
  60. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  61. import org.openspcoop2.security.keystore.KeystoreConstants;
  62. import org.openspcoop2.security.keystore.MerlinKeystore;
  63. import org.openspcoop2.security.keystore.cache.GestoreKeystoreCache;
  64. import org.openspcoop2.security.message.MessageSecurityContext;
  65. import org.openspcoop2.security.message.MessageSecurityContextParameters;
  66. import org.openspcoop2.security.message.constants.SecurityConstants;
  67. import org.openspcoop2.security.message.constants.SignatureDigestAlgorithm;
  68. import org.openspcoop2.security.message.engine.MessageSecurityContext_impl;
  69. import org.openspcoop2.security.message.saml.SAMLBuilderConfigConstants;
  70. import org.openspcoop2.security.message.wss4j.MessageSecuritySender_wss4j;
  71. import org.openspcoop2.utils.certificate.CertificateInfo;
  72. import org.openspcoop2.utils.certificate.KeyStore;
  73. import org.openspcoop2.utils.certificate.byok.BYOKRequestParams;
  74. import org.openspcoop2.utils.date.DateUtils;
  75. import org.openspcoop2.utils.xml.DynamicNamespaceContext;
  76. import org.openspcoop2.utils.xml.XPathNotFoundException;
  77. import org.slf4j.Logger;
  78. import org.w3c.dom.NodeList;

  79. /**
  80.  * ModIImbustamentoSoap
  81.  *
  82.  * @author Poli Andrea (apoli@link.it)
  83.  * @author $Author$
  84.  * @version $Rev$, $Date$
  85.  */
  86. public class ModIImbustamentoSoap {

  87.     private Logger log;
  88.     private ModIProperties modiProperties;
  89.     public ModIImbustamentoSoap(Logger log) throws ProtocolException {
  90.         this.log = log;
  91.         this.modiProperties = ModIProperties.getInstance();
  92.     }
  93.    
  94.     private static String getHeaderSoapPrefix(String hdr) {
  95.         return "Header SOAP '"+hdr+"'";
  96.     }
  97.    
  98.     public void addAsyncInteractionProfile(OpenSPCoop2Message msg, Busta busta, RuoloMessaggio ruoloMessaggio,
  99.             String asyncInteractionType, String asyncInteractionRole,
  100.             String replyTo,
  101.             AccordoServizioParteComune apiContenenteRisorsa, String azione) throws ProtocolException {
  102.        
  103.         if(apiContenenteRisorsa!=null && azione!=null) {
  104.             // nop
  105.         }
  106.        
  107.         OpenSPCoop2SoapMessage soapMessage = null;
  108.         try {
  109.             soapMessage = msg.castAsSoap();
  110.         }catch(Exception e) {
  111.             throw new ProtocolException(e.getMessage(),e);
  112.         }
  113.        
  114.         boolean bufferMessageReadOnly = true;
  115.         String idTransazione = soapMessage.getTransactionId();
  116.        
  117.         if(RuoloMessaggio.RICHIESTA.equals(ruoloMessaggio)) {
  118.            
  119.             // Flusso di Richiesta
  120.            
  121.             if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_VALUE_PUSH.equals(asyncInteractionType)) {
  122.            
  123.                 if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RICHIESTA.equals(asyncInteractionRole)) {
  124.                                    
  125.                     if(this.modiProperties.isSoapSecurityTokenPushReplyToUpdateOrCreateInFruizione()) {
  126.                        
  127.                         ModIUtilities.addSOAPHeaderReplyTo(soapMessage, !bufferMessageReadOnly, idTransazione, replyTo); // aggiorna il valore se giĆ  esistente
  128.                         busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_REPLY_TO, replyTo);
  129.                     }
  130.                     else {
  131.                         String replyToFound = ModIUtilities.getSOAPHeaderReplyToValue(soapMessage, bufferMessageReadOnly, idTransazione);
  132.                         if(replyToFound!=null && !"".equals(replyToFound)) {
  133.                             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_REPLY_TO, replyToFound);
  134.                         }
  135.                         else {
  136.                             ProtocolException pe = new ProtocolException(getHeaderSoapPrefix(this.modiProperties.getSoapReplyToName())+", richiesto dal profilo non bloccante PUSH, non trovato");
  137.                             pe.setInteroperabilityError(true);
  138.                             throw pe;
  139.                         }
  140.                     }
  141.                    
  142.                 }
  143.                 else if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RISPOSTA.equals(asyncInteractionRole)) {
  144.                    
  145.                     processCorrelationId(soapMessage, busta, true, asyncInteractionType, true);

  146.                 }
  147.                
  148.             }
  149.             else {
  150.                
  151.                 // pull
  152.                 if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RICHIESTA_STATO.equals(asyncInteractionRole) ||
  153.                         ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RISPOSTA.equals(asyncInteractionRole)) {
  154.                    
  155.                     processCorrelationId(soapMessage, busta, true, asyncInteractionType, true);
  156.                    
  157.                 }
  158.                
  159.             }
  160.         }
  161.         else {
  162.            
  163.             // Flusso di Risposta
  164.            
  165.             if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_VALUE_PUSH.equals(asyncInteractionType)) {
  166.                
  167.                 if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RICHIESTA.equals(asyncInteractionRole)) {
  168.                
  169.                     boolean foundCorrelationId = processCorrelationId(soapMessage, busta, false, asyncInteractionType, false);
  170.                    
  171.                     if(!foundCorrelationId) {
  172.                    
  173.                         if(this.modiProperties.isSoapSecurityTokenPushCorrelationIdUseTransactionIdIfNotExists()) {
  174.                             ModIUtilities.addSOAPHeaderCorrelationId(soapMessage, !bufferMessageReadOnly, idTransazione, idTransazione);
  175.                             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_ID_CORRELAZIONE, idTransazione);
  176.                             busta.setCollaborazione(idTransazione);
  177.                         }
  178.                         else {
  179.                             ProtocolException pe = new ProtocolException(getHeaderSoapPrefix(this.modiProperties.getSoapCorrelationIdName())+", richiesto dal profilo non bloccante PUSH, non trovato");
  180.                             pe.setInteroperabilityError(true);
  181.                             throw pe;
  182.                         }
  183.                     }
  184.                    
  185.                 }
  186.                
  187.             }
  188.             else {
  189.                
  190.                 // pull
  191.                
  192.                 if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RICHIESTA.equals(asyncInteractionRole) ) {
  193.                    
  194.                     boolean foundCorrelationId = processCorrelationId(soapMessage, busta, false, asyncInteractionType, false);
  195.                    
  196.                     if(!foundCorrelationId) {
  197.                    
  198.                         if(this.modiProperties.isSoapSecurityTokenPullCorrelationIdUseTransactionIdIfNotExists()) {
  199.                             ModIUtilities.addSOAPHeaderCorrelationId(soapMessage, !bufferMessageReadOnly, idTransazione, idTransazione);
  200.                             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_ID_CORRELAZIONE, idTransazione);
  201.                             busta.setCollaborazione(idTransazione);
  202.                         }
  203.                         else {
  204.                             ProtocolException pe = new ProtocolException(getHeaderSoapPrefix(this.modiProperties.getSoapCorrelationIdName())+", richiesto dal profilo non bloccante PULL, non trovato");
  205.                             pe.setInteroperabilityError(true);
  206.                             throw pe;
  207.                         }
  208.                     }
  209.                    
  210.                 }
  211.                
  212.             }
  213.         }
  214.        
  215.     }
  216.    
  217.     private boolean processCorrelationId(OpenSPCoop2SoapMessage soapMessage, Busta busta, boolean notFoundException, String profilo, boolean useAlternativeMethod) throws ProtocolException {
  218.        
  219.         boolean bufferMessageReadOnly = true;
  220.         String idTransazione = soapMessage.getTransactionId();
  221.        
  222.         String correlationIdFound = ModIUtilities.getSOAPHeaderCorrelationIdValue(soapMessage, bufferMessageReadOnly, idTransazione);
  223.         if(correlationIdFound!=null && !"".equals(correlationIdFound)) {
  224.             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_ID_CORRELAZIONE, correlationIdFound);
  225.             if(correlationIdFound.length()<=255) {
  226.                 busta.setCollaborazione(correlationIdFound);
  227.             }
  228.             return true;
  229.         }
  230.        
  231.         if(useAlternativeMethod) {
  232.        
  233.             String headerCorrelationIdHttp = this.modiProperties.getRestCorrelationIdHeader();
  234.             String correlationIdFoundHttp = null;
  235.             if(soapMessage.getTransportRequestContext()!=null) {
  236.                 correlationIdFoundHttp = soapMessage.getTransportRequestContext().getHeaderFirstValue(headerCorrelationIdHttp);
  237.             }
  238.             else if(soapMessage.getTransportResponseContext()!=null) {
  239.                 correlationIdFoundHttp = soapMessage.getTransportResponseContext().getHeaderFirstValue(headerCorrelationIdHttp);
  240.             }
  241.            
  242.             if(correlationIdFoundHttp!=null && !"".equals(correlationIdFoundHttp)) {
  243.                 busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_ID_CORRELAZIONE, correlationIdFoundHttp);
  244.                 if(correlationIdFoundHttp.length()<=255) {
  245.                     busta.setCollaborazione(correlationIdFoundHttp);
  246.                 }
  247.                 ModIUtilities.addSOAPHeaderCorrelationId(soapMessage, !bufferMessageReadOnly, idTransazione, correlationIdFoundHttp);
  248.                 return true;
  249.             }
  250.             else if(busta.getCollaborazione()!=null) {
  251.                 busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_ID_CORRELAZIONE, busta.getCollaborazione());
  252.                 ModIUtilities.addSOAPHeaderCorrelationId(soapMessage, !bufferMessageReadOnly, idTransazione, busta.getCollaborazione());
  253.                 return true;
  254.             }
  255.             else if(busta.getRiferimentoMessaggio()!=null) {
  256.                 busta.setCollaborazione(busta.getRiferimentoMessaggio());
  257.                 busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_ID_CORRELAZIONE, busta.getRiferimentoMessaggio());
  258.                 ModIUtilities.addSOAPHeaderCorrelationId(soapMessage, !bufferMessageReadOnly, idTransazione, busta.getRiferimentoMessaggio());
  259.                 return true;
  260.             }
  261.            
  262.         }
  263.        
  264.         if(notFoundException) {
  265.             ProtocolException pe = new ProtocolException(getHeaderSoapPrefix(this.modiProperties.getSoapCorrelationIdName())+", richiesto dal profilo non bloccante "+profilo+", non trovato");
  266.             pe.setInteroperabilityError(true);
  267.             throw pe;
  268.         }
  269.         else {
  270.             return false;
  271.         }
  272.        
  273.     }
  274.    
  275.     public SOAPEnvelope addSecurity(OpenSPCoop2Message msg, boolean request, Context context, ModIKeystoreConfig keystoreConfig, ModISecurityConfig securityConfig,
  276.             Busta busta, String securityMessageProfile, boolean corniceSicurezza, RuoloMessaggio ruoloMessaggio, boolean includiRequestDigest,
  277.             boolean signAttachments,
  278.             Map<String, Object> dynamicMap,
  279.             RequestInfo requestInfo) throws ProtocolException {
  280.    
  281.         ModIProperties modIProperties = ModIProperties.getInstance();
  282.    
  283.         OpenSPCoop2MessageFactory messageFactory = msg!=null ? msg.getFactory() : OpenSPCoop2MessageFactory.getDefaultMessageFactory();
  284.        
  285.         if(msg==null) {
  286.             throw new ProtocolException("Param msg is null");
  287.         }
  288.        
  289.         OpenSPCoop2SoapMessage soapMessage = null;
  290.         SOAPEnvelope soapEnvelope = null;
  291.         try {
  292.             soapMessage = msg.castAsSoap();
  293.             soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
  294.         }catch(Exception e) {
  295.             throw new ProtocolException(e.getMessage(),e);
  296.         }
  297.         boolean bufferMessageReadOnly = true;
  298.         String idTransazione = soapMessage.getTransactionId();
  299.        
  300.         boolean integritaX509 = ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0301.equals(securityMessageProfile) ||
  301.                 ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0302.equals(securityMessageProfile);
  302.         boolean integritaKid = ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0401.equals(securityMessageProfile) ||
  303.                 ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0402.equals(securityMessageProfile);
  304.         boolean integrita = integritaX509 || integritaKid;
  305.        
  306.         if(integritaKid) {
  307.             String labelPattern = ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0401.equals(securityMessageProfile) ?
  308.                     CostantiLabel.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_LABEL_IDAM0401_REST :
  309.                     CostantiLabel.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_LABEL_IDAM0402_REST;
  310.             throw new ProtocolException("Sicurezza Messaggio con pattern '"+labelPattern+"' non utilizzabile su API SOAP");
  311.         }

  312.         /*
  313.          * == request digest ==
  314.          */
  315.         SOAPHeaderElement requestDigest = null;
  316.         if(integrita && RuoloMessaggio.RISPOSTA.equals(ruoloMessaggio) && includiRequestDigest &&
  317.             context.containsKey(ModICostanti.MODIPA_CONTEXT_REQUEST_DIGEST)) {
  318.             Object o = context.getObject(ModICostanti.MODIPA_CONTEXT_REQUEST_DIGEST);
  319.             NodeList nodeList = (NodeList) o;
  320.             requestDigest = ModIUtilities.addSOAPHeaderRequestDigest(soapMessage, !bufferMessageReadOnly, idTransazione, nodeList);
  321.         }
  322.        
  323.        
  324.         /*
  325.          * == wsaddressing ==
  326.          */
  327.        
  328.         WSAddressingUtilities wsaddressingUtilities = new WSAddressingUtilities(this.log);
  329.         WSAddressingValue wsAddressingValue = new WSAddressingValue();
  330.        
  331.         if(busta.getID()!=null) {
  332.             wsAddressingValue.setId(busta.getID());
  333.             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_ID, busta.getID());
  334.         }
  335.        
  336.         if(securityConfig.getAudience()!=null) {
  337.             String audience = securityConfig.getAudience();
  338.             if(RuoloMessaggio.RICHIESTA.equals(ruoloMessaggio)) { // un valore dinamico e' consentito solo sulla richiesta
  339.                 try {
  340.                     audience = ModIUtilities.getDynamicValue(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_SOAP_WSA_TO,
  341.                             audience, dynamicMap, context);
  342.                 }catch(Exception e) {
  343.                     this.log.error(e.getMessage(),e);
  344.                     ProtocolException pe = new ProtocolException(e.getMessage());
  345.                     pe.setInteroperabilityError(true);
  346.                     throw pe;
  347.                 }
  348.             }
  349.             wsAddressingValue.setTo(audience);
  350.             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_SOAP_WSA_TO, audience);
  351.         }
  352.        
  353.         if(securityConfig.getClientId()!=null) {
  354.             wsAddressingValue.setFrom(securityConfig.getClientId());
  355.             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_SOAP_WSA_FROM, securityConfig.getClientId());
  356.         }
  357.        
  358.         if(busta.getRiferimentoMessaggio()!=null) {
  359.            
  360.             boolean add = true;
  361.             if(RuoloMessaggio.RISPOSTA.equals(ruoloMessaggio)) {
  362.                 boolean buildSecurityTokenInRequest = false;
  363.                 Object buildSecurityTokenInRequestObject = null;
  364.                 if(context!=null) {
  365.                     buildSecurityTokenInRequestObject = context.getObject(ModICostanti.MODIPA_OPENSPCOOP2_MSG_CONTEXT_BUILD_SECURITY_REQUEST_TOKEN);
  366.                     if(buildSecurityTokenInRequestObject instanceof Boolean) {
  367.                         buildSecurityTokenInRequest = (Boolean) buildSecurityTokenInRequestObject;
  368.                     }
  369.                 }
  370.                 add = buildSecurityTokenInRequest;
  371.             }
  372.             if(add) {
  373.                 wsAddressingValue.setRelatesTo(busta.getRiferimentoMessaggio());
  374.                 busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_RELATES_TO, busta.getRiferimentoMessaggio());
  375.             }
  376.            
  377.         }
  378.        
  379.         wsAddressingValue.setReplyToAnonymouys();
  380.        
  381.         if(this.modiProperties.isSoapSecurityTokenWsaToSoapAction()) {
  382.             try {
  383.                 if(soapMessage.getSoapAction()!=null) {
  384.                     String soapAction = soapMessage.getSoapAction();
  385.                     soapAction = soapAction.trim();
  386.                     if(soapAction.startsWith("\"") &&
  387.                         soapAction.length()>1) {
  388.                         soapAction = soapAction.substring(1);
  389.                     }
  390.                     if(soapAction.endsWith("\"") &&
  391.                         soapAction.length()>1) {
  392.                         soapAction = soapAction.substring(0,(soapAction.length()-1));
  393.                     }
  394.                     wsAddressingValue.setAction(soapAction);
  395.                 }
  396.             }catch(Exception e) {
  397.                 throw new ProtocolException(e.getMessage(),e);
  398.             }
  399.         }
  400.         else if(this.modiProperties.isSoapSecurityTokenWsaToOperation()) {
  401.             wsAddressingValue.setAction(busta.getAzione());
  402.         }
  403.        
  404.         WSAddressingHeader wsAddressingHeaders = null;
  405.         try {
  406.             wsAddressingHeaders = wsaddressingUtilities.build(soapMessage,
  407.                     modIProperties.getSoapWSAddressingActor(), modIProperties.isSoapWSAddressingMustUnderstand(),
  408.                     wsAddressingValue);
  409.             wsaddressingUtilities.addHeader(wsAddressingHeaders, soapMessage);
  410.         }catch(Exception e) {
  411.             throw new ProtocolException(e.getMessage(),e);
  412.         }
  413.        
  414.        
  415.        
  416.         /*
  417.          * == signature ==
  418.          */
  419.        
  420.         MessageSecuritySender_wss4j wss4jSignature = new MessageSecuritySender_wss4j();
  421.         MessageSecurityContextParameters messageSecurityContextParameters = new MessageSecurityContextParameters();
  422.         messageSecurityContextParameters.setFunctionAsClient(true);
  423.         messageSecurityContextParameters.setPrefixWsuId(OpenSPCoop2Properties.getInstance().getPrefixWsuId()); // NOTA: deve essere lo stesso di govway usato in altri profili
  424.         MessageSecurityContext messageSecurityContext = new MessageSecurityContext_impl(messageSecurityContextParameters);
  425.         Map<String,Object> secProperties = new HashMap<>();
  426.         secProperties.put(SecurityConstants.SECURITY_ENGINE, SecurityConstants.SECURITY_ENGINE_WSS4J);
  427.         if(modIProperties.getSoapSecurityTokenActor()!=null && !"".equals(modIProperties.getSoapSecurityTokenActor())) {
  428.             secProperties.put(SecurityConstants.ACTOR, modIProperties.getSoapSecurityTokenActor());
  429.         }
  430.         secProperties.put(SecurityConstants.MUST_UNDERSTAND, modIProperties.isSoapSecurityTokenMustUnderstand()+"");
  431.         secProperties.put(SecurityConstants.TIMESTAMP_TTL, securityConfig.getTtlSeconds()+"");
  432.         secProperties.put(SecurityConstants.IS_BSP_COMPLIANT, SecurityConstants.TRUE);
  433.        
  434.         // cornice sicurezza
  435.         if(RuoloMessaggio.RISPOSTA.equals(ruoloMessaggio)) {
  436.             corniceSicurezza = false; // permessa solo per i messaggi di richiesta
  437.         }
  438.         if(corniceSicurezza) {
  439.             addCorniceSicurezza(secProperties, context, busta, securityConfig, dynamicMap);
  440.         }
  441.        
  442.         // action
  443.         StringBuilder bfAction = new StringBuilder();
  444.         if(corniceSicurezza) {
  445.             bfAction.append(SecurityConstants.ACTION_SAML_TOKEN_UNSIGNED).append(" ");
  446.         }
  447.         bfAction.append(SecurityConstants.TIMESTAMP_ACTION).append(" ").append(SecurityConstants.SIGNATURE_ACTION);
  448.         secProperties.put(SecurityConstants.ACTION, bfAction.toString());
  449.        
  450.         // parti da firmare
  451.         List<SOAPHeader> soapHeaderAggiuntiviDaFirmare = securityConfig.getSoapHeaders();
  452.         StringBuilder bf = new StringBuilder();
  453.        
  454.         // -- Timestamp
  455.         addSignaturePart(soapHeaderAggiuntiviDaFirmare, busta, bf, SecurityConstants.WSS_HEADER_UTILITY_NAMESPACE, "Timestamp");
  456.        
  457.         // -- WSAddressing
  458.         if(wsAddressingHeaders.getTo()!=null) {
  459.             addSignaturePart(soapHeaderAggiuntiviDaFirmare, busta, bf, wsAddressingHeaders.getTo().getNamespaceURI(), wsAddressingHeaders.getTo().getLocalName());
  460.         }
  461.         if(wsAddressingHeaders.getFrom()!=null) {
  462.             addSignaturePart(soapHeaderAggiuntiviDaFirmare, busta, bf, wsAddressingHeaders.getFrom().getNamespaceURI(), wsAddressingHeaders.getFrom().getLocalName());
  463.         }
  464.         if(wsAddressingHeaders.getAction()!=null) {
  465.             addSignaturePart(soapHeaderAggiuntiviDaFirmare, busta, bf, wsAddressingHeaders.getAction().getNamespaceURI(), wsAddressingHeaders.getAction().getLocalName());
  466.         }
  467.         if(wsAddressingHeaders.getId()!=null) {
  468.             addSignaturePart(soapHeaderAggiuntiviDaFirmare, busta, bf, wsAddressingHeaders.getId().getNamespaceURI(), wsAddressingHeaders.getId().getLocalName());
  469.         }
  470.         if(wsAddressingHeaders.getRelatesTo()!=null) {
  471.             addSignaturePart(soapHeaderAggiuntiviDaFirmare, busta, bf, wsAddressingHeaders.getRelatesTo().getNamespaceURI(), wsAddressingHeaders.getRelatesTo().getLocalName());
  472.         }
  473.         if(wsAddressingHeaders.getReplyTo()!=null) {
  474.             addSignaturePart(soapHeaderAggiuntiviDaFirmare, busta, bf, wsAddressingHeaders.getReplyTo().getNamespaceURI(), wsAddressingHeaders.getReplyTo().getLocalName());
  475.         }
  476.         if(wsAddressingHeaders.getFaultTo()!=null) {
  477.             addSignaturePart(soapHeaderAggiuntiviDaFirmare, busta, bf, wsAddressingHeaders.getFaultTo().getNamespaceURI(), wsAddressingHeaders.getFaultTo().getLocalName());
  478.         }
  479.         if(integrita) {
  480.             addSignaturePart(soapHeaderAggiuntiviDaFirmare, busta, bf, soapEnvelope.getNamespaceURI(), "Body");
  481.             if(signAttachments) {
  482.                 if(bf.length()>0) {
  483.                     bf.append(";");
  484.                 }
  485.                 bf.append("{}"+SecurityConstants.CID_ATTACH_WSS4J);
  486.                 busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_SIGNED_SOAP_PREFIX+"Attachments", "tutti");
  487.             }
  488.         }
  489.         if(corniceSicurezza) {
  490.             addSignaturePart(soapHeaderAggiuntiviDaFirmare, busta, bf, Costanti.SAML_20_NAMESPACE, "Assertion");
  491.         }
  492.         if(requestDigest!=null) {
  493.             addSignaturePart(soapHeaderAggiuntiviDaFirmare, busta, bf, requestDigest.getNamespaceURI(), requestDigest.getLocalName());
  494.         }
  495.         if(soapHeaderAggiuntiviDaFirmare!=null) {
  496.             while(!soapHeaderAggiuntiviDaFirmare.isEmpty()) {
  497.                 SOAPHeader soapHeader = soapHeaderAggiuntiviDaFirmare.get(0); // non ĆØ un errore la get, nella lista viene rimosso dentro uno dei metodi usati da addSignaturePart
  498.                 addSignaturePart(soapHeaderAggiuntiviDaFirmare, busta, bf, soapHeader.getNamespace(), soapHeader.getLocalName());
  499.             }
  500.         }
  501.         secProperties.put(SecurityConstants.SIGNATURE_PARTS, bf.toString());
  502.        
  503.         // algoritmi
  504.         secProperties.put(SecurityConstants.SIGNATURE_ALGORITHM, securityConfig.getAlgorithm());
  505.         secProperties.put(SecurityConstants.SIGNATURE_C14N_ALGORITHM, securityConfig.getC14nAlgorithm());
  506.         secProperties.put(SecurityConstants.SIGNATURE_DIGEST_ALGORITHM, securityConfig.getDigestAlgorithm());
  507.        
  508.         // spedizione certificato
  509.         secProperties.put(SecurityConstants.SIGNATURE_KEY_IDENTIFIER, securityConfig.getKeyIdentifierMode());
  510.         if(ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_SOAP_RIFERIMENTO_X509_VALUE_BINARY_SECURITY_TOKEN.equals(securityConfig.getKeyIdentifierMode())) {
  511.             secProperties.put(SecurityConstants.KEY_IDENTIFIER_BST_DIRECT_REFERENCE_USE_SINGLE_CERTIFICATE, securityConfig.isUseSingleCertificate()+"");
  512.         }
  513.         else if(ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_SOAP_RIFERIMENTO_X509_VALUE_SECURITY_TOKEN_REFERENCE.equals(securityConfig.getKeyIdentifierMode())
  514.                 ||
  515.                 ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_SOAP_RIFERIMENTO_X509_VALUE_KEY_IDENTIFIER_THUMBPRINT.equals(securityConfig.getKeyIdentifierMode())
  516.                 ||
  517.                 ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_SOAP_RIFERIMENTO_X509_VALUE_KEY_IDENTIFIER_SKI.equals(securityConfig.getKeyIdentifierMode())) {
  518.             secProperties.put(SecurityConstants.KEY_IDENTIFIER_INCLUDE_SIGNATURE_TOKEN, securityConfig.isIncludeSignatureToken()+"");
  519.         }
  520.        
  521.         // keystore
  522.         Properties pKeystore = new Properties();
  523.         /**pKeystore.put(KeystoreConstants.PROPERTY_PROVIDER, KeystoreConstants.PROVIDER_DEFAULT);*/
  524.         pKeystore.put(KeystoreConstants.PROPERTY_PROVIDER, KeystoreConstants.PROVIDER_GOVWAY);
  525.         pKeystore.put(KeystoreConstants.PROPERTY_KEYSTORE_TYPE, keystoreConfig.getSecurityMessageKeystoreType());
  526.         if(keystoreConfig.getSecurityMessageKeystorePassword()!=null) {
  527.             pKeystore.put(KeystoreConstants.PROPERTY_KEYSTORE_PASSWORD, keystoreConfig.getSecurityMessageKeystorePassword());
  528.         }
  529.         if(keystoreConfig.getSecurityMessageKeystorePath()!=null || keystoreConfig.isSecurityMessageKeystoreHSM()) {
  530.             if(CostantiDB.KEYSTORE_TYPE_JWK.equalsIgnoreCase(keystoreConfig.getSecurityMessageKeystoreType())) {
  531.                 throw new ProtocolException("Keystore di tipo '"+CostantiLabel.KEYSTORE_TYPE_JWK+"' non utilizzabile su API SOAP");
  532.             }
  533.             else if(CostantiDB.KEYSTORE_TYPE_KEY_PAIR.equalsIgnoreCase(keystoreConfig.getSecurityMessageKeystoreType())) {
  534.                 throw new ProtocolException("Keystore di tipo '"+CostantiLabel.KEYSTORE_TYPE_KEY_PAIR+"' non utilizzabile su API SOAP");
  535.             }
  536.             pKeystore.put(KeystoreConstants.PROPERTY_KEYSTORE_PATH, keystoreConfig.getSecurityMessageKeystorePath());
  537.            
  538.             if(!keystoreConfig.isSecurityMessageKeystoreHSM() && keystoreConfig.getSecurityMessageKeystoreByokPolicy()!=null) {
  539.                 DynamicMapBuilderUtils.injectDynamicMap(busta, requestInfo, context, this.log);
  540.                 pKeystore.put(KeystoreConstants.PROPERTY_KEYSTORE_PATH_BYOK, keystoreConfig.getSecurityMessageKeystoreByokPolicy());
  541.             }
  542.         }
  543.         else {
  544.             pKeystore.put(KeystoreConstants.PROPERTY_KEYSTORE_ARCHIVE, keystoreConfig.getSecurityMessageKeystoreArchive());
  545.         }
  546.         pKeystore.put(KeystoreConstants.PROPERTY_REQUEST_INFO, requestInfo);
  547.         secProperties.put(SecurityConstants.SIGNATURE_PROPERTY_REF_ID, pKeystore);
  548.        
  549.         secProperties.put(SecurityConstants.SIGNATURE_USER, keystoreConfig.getSecurityMessageKeyAlias());
  550.         secProperties.put(SecurityConstants.SIGNATURE_PASSWORD, keystoreConfig.getSecurityMessageKeyPassword());
  551.         secProperties.put(SecurityConstants.PASSWORD_CALLBACK_REF, SecurityConstants.TRUE);
  552.        
  553.         // setProperties
  554.         try {
  555.             messageSecurityContext.setOutgoingProperties(secProperties, false);
  556.         }catch(Exception e) {
  557.             throw new ProtocolException(e.getMessage(),e);
  558.         }
  559.                
  560.         // firma
  561.         try {
  562.             wss4jSignature.process(messageSecurityContext, msg, context);
  563.         }catch(Exception e) {
  564.             throw new ProtocolException(e.getMessage(),e);
  565.         }
  566.        
  567.         // Aggiungo a traccia informazioni sul certificato utilizzato
  568.         KeyStore ks = null;
  569.         if(keystoreConfig.getSecurityMessageKeystorePath()!=null) {
  570.             try {
  571.                 String keystoreByokPolicy = keystoreConfig.getSecurityMessageKeystoreByokPolicy();
  572.                 BYOKRequestParams byokParams = null;
  573.                 try {
  574.                     byokParams = BYOKUnwrapPolicyUtilities.getBYOKRequestParams(keystoreByokPolicy, dynamicMap);
  575.                 }catch(Exception e) {
  576.                     throw new ProtocolException(e.getMessage(),e);
  577.                 }
  578.                
  579.                 MerlinKeystore merlinKs = GestoreKeystoreCache.getMerlinKeystore(requestInfo, keystoreConfig.getSecurityMessageKeystorePath(), keystoreConfig.getSecurityMessageKeystoreType(),
  580.                         keystoreConfig.getSecurityMessageKeystorePassword(),
  581.                         byokParams);
  582.                 if(merlinKs==null) {
  583.                     throw new ProtocolException("Accesso al keystore '"+keystoreConfig.getSecurityMessageKeystorePath()+"' non riuscito");
  584.                 }
  585.                 ks = merlinKs.getKeyStore();
  586.             }catch(Exception e) {
  587.                 throw new ProtocolException(e.getMessage(),e);
  588.             }
  589.         }
  590.         else {
  591.             try {
  592.                 MerlinKeystore merlinKs = GestoreKeystoreCache.getMerlinKeystore(requestInfo, keystoreConfig.getSecurityMessageKeystoreArchive(), keystoreConfig.getSecurityMessageKeystoreType(),
  593.                         keystoreConfig.getSecurityMessageKeystorePassword());
  594.                 if(merlinKs==null) {
  595.                     throw new ProtocolException("Accesso al keystore non riuscito");
  596.                 }
  597.                 ks = merlinKs.getKeyStore();
  598.             }catch(Exception e) {
  599.                 throw new ProtocolException(e.getMessage(),e);
  600.             }
  601.         }
  602.         Certificate certificate = null;
  603.         try {
  604.             certificate = ks.getCertificate(keystoreConfig.getSecurityMessageKeyAlias());
  605.         }catch(Exception e) {
  606.             throw new ProtocolException(e.getMessage(),e);
  607.         }
  608.         X509Certificate x509 = null;
  609.         if(certificate instanceof X509Certificate) {
  610.             x509 = (X509Certificate) certificate;
  611.             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_X509_SUBJECT, x509.getSubjectX500Principal().toString());
  612.             if(x509.getIssuerX500Principal()!=null) {
  613.                 busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_X509_ISSUER, x509.getIssuerX500Principal().toString());
  614.             }
  615.         }
  616.        
  617.        
  618.         /*
  619.          * == header per tracciatura ==
  620.          */
  621.        
  622.         SOAPHeaderElement securityHeader = messageSecurityContext.getSecurityHeader(msg, modIProperties.getSoapSecurityTokenActor());
  623.        
  624.         DynamicNamespaceContext dnc = MessageDynamicNamespaceContextFactory.getInstance(messageFactory).getNamespaceContext(securityHeader);
  625.         String wsuNamespace = SecurityConstants.WSS_HEADER_UTILITY_NAMESPACE;
  626.         XPathExpressionEngine xpathEngine = new XPathExpressionEngine(messageFactory);
  627.        
  628.         String patternCreated = "//{"+wsuNamespace+"}Timestamp/{"+wsuNamespace+"}Created/text()";
  629.         String created = null;
  630.         try {
  631.             created = xpathEngine.getStringMatchPattern(securityHeader, dnc, patternCreated);
  632.         }catch(XPathNotFoundException notFound) {
  633.             // ignore
  634.         }catch(Exception e) {
  635.             throw new ProtocolException(e.getMessage(),e);
  636.         }
  637.         if(created!=null) {
  638.             java.time.Instant iCreated = java.time.Instant.parse(created);
  639.             Date dCreated = new Date(iCreated.toEpochMilli());
  640.             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_IAT, DateUtils.getSimpleDateFormatMs().format(dCreated));
  641.         }
  642.        
  643.         String patternExpires = "//{"+wsuNamespace+"}Timestamp/{"+wsuNamespace+"}Expires/text()";
  644.         String expires = null;
  645.         try {
  646.             expires = xpathEngine.getStringMatchPattern(securityHeader, dnc, patternExpires);
  647.         }catch(XPathNotFoundException notFound) {
  648.             // ignore  
  649.         }catch(Exception e) {
  650.             throw new ProtocolException(e.getMessage(),e);
  651.         }
  652.         if(expires!=null) {
  653.             java.time.Instant iExpires = java.time.Instant.parse(expires);
  654.             Date dExpires = new Date(iExpires.toEpochMilli());
  655.             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_EXP, DateUtils.getSimpleDateFormatMs().format(dExpires));
  656.         }
  657.        
  658.        
  659.         ModISOAPSecurity soapSecurity = new ModISOAPSecurity();    
  660.         soapSecurity.setSecurityHeader(securityHeader);
  661.         soapSecurity.setWsAddressingHeader(wsAddressingHeaders);
  662.         soapSecurity.setRequestDigestHeader(requestDigest);
  663.         if(integrita) {
  664.             QName qname = new QName(SecurityConstants.WSS_HEADER_UTILITY_NAMESPACE, "Id");
  665.             SOAPBody soapBody = null;
  666.             try {
  667.                 soapBody = msg.castAsSoap().getSOAPBody();
  668.             }catch(Exception e) {
  669.                 throw new ProtocolException(e.getMessage(),e);
  670.             }
  671.             String wsuIdBodyRef = soapBody.getAttributeValue(qname);
  672.             soapSecurity.setWsuIdBodyRef(wsuIdBodyRef);
  673.            
  674.             if(wsuIdBodyRef!=null) {
  675.                 String digestNamespace = "http://www.w3.org/2000/09/xmldsig#";
  676.                 String digestReferencePattern = "//{"+digestNamespace+"}:Reference[@URI='#"+wsuIdBodyRef+"']";
  677.                 String digestValuePattern = digestReferencePattern+"/{"+digestNamespace+"}:DigestValue/text()";
  678.                 String digestAlgorithmPattern = digestReferencePattern+"/{"+digestNamespace+"}:DigestMethod/@Algorithm";

  679.                 String digestValue = null;
  680.                 try {
  681.                     digestValue = xpathEngine.getStringMatchPattern(securityHeader, dnc, digestValuePattern);
  682.                 }catch(XPathNotFoundException notFound) {
  683.                     // ignore
  684.                 }catch(Exception e) {
  685.                     throw new ProtocolException(e.getMessage(),e);
  686.                 }
  687.                 String digestAlgorithm = null;
  688.                 try {
  689.                     digestAlgorithm = xpathEngine.getStringMatchPattern(securityHeader, dnc, digestAlgorithmPattern);
  690.                 }catch(XPathNotFoundException notFound) {
  691.                     // ignore
  692.                 }catch(Exception e) {
  693.                     throw new ProtocolException(e.getMessage(),e);
  694.                 }
  695.                
  696.                 if(digestValue!=null && digestAlgorithm!=null) {
  697.                     SignatureDigestAlgorithm s = SignatureDigestAlgorithm.toEnumConstant(digestAlgorithm);
  698.                     String digestValueBusta = s!=null ? (s.name()+"=") : "";
  699.                     digestValueBusta = digestValueBusta + digestValue;
  700.                     busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_DIGEST, digestValueBusta);
  701.                 }
  702.             }
  703.         }
  704.        
  705.        
  706.         SOAPEnvelope soapEnvelopeTraccia = null;
  707.         try {
  708.             soapEnvelopeTraccia = soapSecurity.buildTraccia(msg.getMessageType());
  709.         }catch(Exception e) {
  710.             throw new ProtocolException(e.getMessage(),e);
  711.         }
  712.        
  713.        
  714.         SoapMessageSecurityToken soapSecurityToken = null;
  715.         if(request && context!=null) {
  716.            
  717.             SecurityToken securityTokenForContext = ModIUtilities.newSecurityToken(context);
  718.            
  719.             soapSecurityToken = new SoapMessageSecurityToken();
  720.             soapSecurityToken.setCertificate(new CertificateInfo(x509, "soapEnvelope"));
  721.             if(soapEnvelopeTraccia!=null) {
  722.                 soapSecurityToken.setToken(soapEnvelopeTraccia);
  723.             }
  724.             securityTokenForContext.setEnvelope(soapSecurityToken);
  725.            
  726.         }
  727.        
  728.        
  729.         return soapEnvelopeTraccia;
  730.     }
  731.    
  732.     private void addSignaturePart(List<SOAPHeader> soapHeaderAggiuntiviDaFirmare, Busta busta, StringBuilder bf, String namespace, String localName) {
  733.         if(bf.length()>0) {
  734.             bf.append(";");
  735.         }
  736.         bf.append("{Element}{").append(namespace).append("}").append(localName);
  737.         SOAPHeader.remove(soapHeaderAggiuntiviDaFirmare, namespace, localName);
  738.         busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_SIGNED_SOAP_PREFIX+localName, namespace);
  739.     }
  740.    
  741.     private static boolean senderVouche = true;
  742.     public static boolean isSenderVouche() {
  743.         return senderVouche;
  744.     }
  745.     public static void setSenderVouche(boolean senderVouche) {
  746.         ModIImbustamentoSoap.senderVouche = senderVouche;
  747.     }

  748.     private static final String ATTR_0 = "ATTR_0";
  749.     private static final String ATTR_1 = "ATTR_1";
  750.     private static final String ATTR_2 = "ATTR_2";
  751.    
  752.     private void addCorniceSicurezza(Map<String,Object> secProperties,
  753.             Context context, Busta busta,
  754.             ModISecurityConfig securityConfig,
  755.             Map<String, Object> dynamicMap) throws ProtocolException {
  756.        
  757.         String nomeSoggettoMittente = busta.getMittente();
  758.                
  759.         String attributeNameCodiceEnte = this.modiProperties.getSicurezzaMessaggioCorniceSicurezzaSoapCodiceEnte();
  760.         String codiceEnte = null;
  761.         try {
  762.             codiceEnte = ModIUtilities.getDynamicValue(ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_LABEL+" - "+ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_CODICE_ENTE_MODE_LABEL,
  763.                     securityConfig.getCorniceSicurezzaCodiceEnteRule(), dynamicMap, context);
  764.         }catch(Exception e) {
  765.             ProtocolException pe = new ProtocolException(e.getMessage());
  766.             pe.setInteroperabilityError(true);
  767.             throw pe;
  768.         }
  769.            
  770.         String attributeNameUser = this.modiProperties.getSicurezzaMessaggioCorniceSicurezzaSoapUser();
  771.         String utente = null;
  772.         try {
  773.             utente = ModIUtilities.getDynamicValue(ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_LABEL+" - "+ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_USER_MODE_LABEL,
  774.                     securityConfig.getCorniceSicurezzaUserRule(), dynamicMap, context);
  775.         }catch(Exception e) {
  776.             ProtocolException pe = new ProtocolException(e.getMessage());
  777.             pe.setInteroperabilityError(true);
  778.             throw pe;
  779.         }
  780.        
  781.         String attributeNameIpUser = this.modiProperties.getSicurezzaMessaggioCorniceSicurezzaSoapIpuser();
  782.         String indirizzoIpPostazione = null;
  783.         try {
  784.             indirizzoIpPostazione = ModIUtilities.getDynamicValue(ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_LABEL+" - "+ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_IP_USER_MODE_LABEL,
  785.                     securityConfig.getCorniceSicurezzaIpUserRule(), dynamicMap, context);
  786.         }catch(Exception e) {
  787.             ProtocolException pe = new ProtocolException(e.getMessage());
  788.             pe.setInteroperabilityError(true);
  789.             throw pe;
  790.         }
  791.        
  792.         Properties pSaml = new Properties();
  793.        
  794.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_SIGN_ASSERTION, SecurityConstants.FALSE); // lo faccio globalmente!
  795.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_SIGN_ASSERTION_SEND_KEY_VALUE, SecurityConstants.FALSE); // lo faccio globalmente!
  796.        
  797.         //       410 - signatureDigestAlgorithm                                                       - http://www.w3.org/2001/04/xmlenc#sha256           - 360
  798.         //       410 - signatureC14nAlgorithmExclusive                                                - http://www.w3.org/2001/10/xml-exc-c14n#           - 371
  799.         //      410 - signatureAlgorithm                                                             - http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 - 374

  800.        
  801.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_VERSION, SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_VERSION_20);
  802.        
  803.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ISSUER_VALUE, nomeSoggettoMittente);
  804.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ISSUER_FORMAT, SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_SUBJECT_NAMEID_FORMAT_VALUE_UNSPECIFIED);
  805.        
  806.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_SUBJECT_NAMEID_VALUE, codiceEnte);
  807.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_SUBJECT_NAMEID_FORMAT, SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_SUBJECT_NAMEID_FORMAT_VALUE_UNSPECIFIED);
  808.         busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_CORNICE_SICUREZZA_ENTE, codiceEnte);
  809.        
  810.         if(senderVouche) {
  811.             pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_SUBJECT_CONFIRMATION_METHOD, SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_SUBJECT_CONFIRMATION_METHOD_VALUE_SENDER_VOUCHES);
  812.         }
  813.         else {
  814.             pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_SUBJECT_CONFIRMATION_METHOD, SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_SUBJECT_CONFIRMATION_METHOD_VALUE_BEARER);
  815.         }
  816.        
  817.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_AUTHN_STATEMENT_ENABLED, SecurityConstants.TRUE);
  818.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_AUTHN, SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_AUTHN_VALUE_UNSPECIFIED);

  819.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_CONDITIONS_DATA_NOT_ON_OR_AFTER, "60");
  820.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_CONDITIONS_DATA_NOT_BEFORE, "0");
  821.        
  822.         /**pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_PREFIX+".enabled", SecurityConstants.TRUE);*/
  823.        
  824.         if(attributeNameCodiceEnte!=null && !"".equals(attributeNameCodiceEnte)) {
  825.             // se si desidera avere un attributo anche per il codice utente oltre al saml2:subject
  826.            
  827.             pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_PREFIX+ATTR_0+
  828.                     SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_SUFFIX_QUALIFIED_NAME, attributeNameCodiceEnte);
  829.             pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_PREFIX+ATTR_0+
  830.                     SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_SUFFIX_FORMAT_NAME,
  831.                     SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_SUFFIX_FORMAT_NAME_VALUE_UNSPECIFIED);
  832.             pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_PREFIX+ATTR_0+
  833.                     SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_SUFFIX_VALUE_SEPARATOR, ",");
  834.             pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_PREFIX+ATTR_0+
  835.                     SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_SUFFIX_VALUE, codiceEnte);
  836.            
  837.         }
  838.        
  839.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_PREFIX+ATTR_1+
  840.                 SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_SUFFIX_QUALIFIED_NAME, attributeNameUser);
  841.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_PREFIX+ATTR_1+
  842.                 SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_SUFFIX_FORMAT_NAME,
  843.                 SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_SUFFIX_FORMAT_NAME_VALUE_UNSPECIFIED);
  844.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_PREFIX+ATTR_1+
  845.                 SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_SUFFIX_VALUE_SEPARATOR, ",");
  846.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_PREFIX+ATTR_1+
  847.                 SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_SUFFIX_VALUE, utente);
  848.         busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_CORNICE_SICUREZZA_USER, utente);
  849.        
  850.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_PREFIX+ATTR_2+
  851.                 SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_SUFFIX_QUALIFIED_NAME, attributeNameIpUser);
  852.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_PREFIX+ATTR_2+
  853.                 SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_SUFFIX_FORMAT_NAME,
  854.                 SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_SUFFIX_FORMAT_NAME_VALUE_UNSPECIFIED);
  855.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_PREFIX+ATTR_2+
  856.                 SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_SUFFIX_VALUE_SEPARATOR, ",");
  857.         pSaml.put(SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_PREFIX+ATTR_2+
  858.                 SAMLBuilderConfigConstants.SAML_CONFIG_BUILDER_ATTRIBUTE_SUFFIX_VALUE, indirizzoIpPostazione);
  859.         busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_CORNICE_SICUREZZA_USER_IP, indirizzoIpPostazione);
  860.        
  861.         secProperties.put(SecurityConstants.SAML_PROF_REF_ID, pSaml);

  862.     }
  863. }