ModIValidazioneSintatticaRest.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.validator;

  21. import java.io.ByteArrayOutputStream;
  22. import java.security.cert.X509Certificate;
  23. import java.util.Date;
  24. import java.util.HashMap;
  25. import java.util.Iterator;
  26. import java.util.List;
  27. import java.util.Map;

  28. import org.apache.commons.lang.StringUtils;
  29. import org.openspcoop2.core.config.PortaApplicativa;
  30. import org.openspcoop2.core.constants.CostantiDB;
  31. import org.openspcoop2.core.id.IDPortaApplicativa;
  32. import org.openspcoop2.core.id.IDSoggetto;
  33. import org.openspcoop2.core.registry.AccordoServizioParteComune;
  34. import org.openspcoop2.core.registry.Resource;
  35. import org.openspcoop2.message.OpenSPCoop2Message;
  36. import org.openspcoop2.message.constants.MessageRole;
  37. import org.openspcoop2.message.constants.MessageType;
  38. import org.openspcoop2.message.constants.ServiceBinding;
  39. import org.openspcoop2.pdd.core.dynamic.DynamicMapBuilderUtils;
  40. import org.openspcoop2.pdd.core.dynamic.DynamicUtils;
  41. import org.openspcoop2.pdd.core.keystore.RemoteStoreProvider;
  42. import org.openspcoop2.pdd.core.token.Costanti;
  43. import org.openspcoop2.pdd.core.token.parser.Claims;
  44. import org.openspcoop2.pdd.core.token.parser.TokenUtils;
  45. import org.openspcoop2.pdd.logger.MsgDiagnostico;
  46. import org.openspcoop2.protocol.modipa.config.ModIAuditClaimConfig;
  47. import org.openspcoop2.protocol.modipa.config.ModIAuditConfig;
  48. import org.openspcoop2.protocol.modipa.config.ModIProperties;
  49. import org.openspcoop2.protocol.modipa.constants.ModICostanti;
  50. import org.openspcoop2.protocol.modipa.constants.ModIHeaderType;
  51. import org.openspcoop2.protocol.modipa.utils.ModISecurityConfig;
  52. import org.openspcoop2.protocol.modipa.utils.ModITruststoreConfig;
  53. import org.openspcoop2.protocol.modipa.utils.ModIUtilities;
  54. import org.openspcoop2.protocol.sdk.Busta;
  55. import org.openspcoop2.protocol.sdk.Context;
  56. import org.openspcoop2.protocol.sdk.Eccezione;
  57. import org.openspcoop2.protocol.sdk.IProtocolFactory;
  58. import org.openspcoop2.protocol.sdk.ProtocolException;
  59. import org.openspcoop2.protocol.sdk.RestMessageSecurityToken;
  60. import org.openspcoop2.protocol.sdk.SecurityToken;
  61. import org.openspcoop2.protocol.sdk.constants.CodiceErroreCooperazione;
  62. import org.openspcoop2.protocol.sdk.state.IState;
  63. import org.openspcoop2.protocol.sdk.state.RequestInfo;
  64. import org.openspcoop2.protocol.sdk.validator.ValidazioneUtils;
  65. import org.openspcoop2.security.message.MessageSecurityContext;
  66. import org.openspcoop2.security.message.MessageSecurityContextParameters;
  67. import org.openspcoop2.security.message.constants.SecurityConstants;
  68. import org.openspcoop2.security.message.engine.MessageSecurityContext_impl;
  69. import org.openspcoop2.security.message.jose.MessageSecurityReceiver_jose;
  70. import org.openspcoop2.utils.certificate.CertificateInfo;
  71. import org.openspcoop2.utils.certificate.remote.RemoteKeyType;
  72. import org.openspcoop2.utils.date.DateUtils;
  73. import org.openspcoop2.utils.digest.DigestEncoding;
  74. import org.openspcoop2.utils.json.JSONUtils;
  75. import org.openspcoop2.utils.transport.TransportUtils;
  76. import org.openspcoop2.utils.transport.http.HttpConstants;
  77. import org.openspcoop2.utils.transport.http.HttpUtilities;
  78. import org.slf4j.Logger;

  79. import com.fasterxml.jackson.databind.JsonNode;
  80. import com.fasterxml.jackson.databind.node.ArrayNode;
  81. import com.fasterxml.jackson.databind.node.ObjectNode;
  82. import com.fasterxml.jackson.databind.node.TextNode;

  83. /**
  84.  * ModIValidazioneSintatticaRest
  85.  *
  86.  * @author Poli Andrea (apoli@link.it)
  87.  * @author $Author$
  88.  * @version $Rev$, $Date$
  89.  */
  90. public class ModIValidazioneSintatticaRest extends AbstractModIValidazioneSintatticaCommons{

  91.     public ModIValidazioneSintatticaRest(Logger log, IState state, Context context, IProtocolFactory<?> factory, RequestInfo requestInfo,
  92.             ModIProperties modiProperties, ValidazioneUtils validazioneUtils) {
  93.         super(log, state, context, factory, requestInfo, modiProperties, validazioneUtils);
  94.     }
  95.    
  96.     private void logError(String msg) {
  97.         this.log.error(msg);
  98.     }
  99.     private void logError(String msg, Exception e) {
  100.         this.log.error(msg,e);
  101.     }
  102.    
  103.     public void validateSyncInteractionProfile(OpenSPCoop2Message msg, boolean request,
  104.             List<Eccezione> erroriValidazione) throws ProtocolException {
  105.        
  106.         if(!request) {
  107.            
  108.             String returnCode = null;
  109.             int returnCodeInt = -1;
  110.             if(!request && msg.getTransportResponseContext()!=null) {
  111.                 returnCode = msg.getTransportResponseContext().getCodiceTrasporto();
  112.                 if(returnCode!=null) {
  113.                     try {
  114.                         returnCodeInt = Integer.valueOf(returnCode);
  115.                     }catch(Exception e) {
  116.                         // ignore
  117.                     }
  118.                 }
  119.             }
  120.            
  121.             Integer [] returnCodeAttesi = this.modiProperties.getRestBloccanteHttpStatus();
  122.            
  123.             // Fix: il controllo deve essere fatto solo per i codici che non rientrano in 4xx e 5xx
  124.             boolean is4xx5xx = (returnCodeInt>=400) && (returnCodeInt<=599);
  125.            
  126.             if(!is4xx5xx && returnCodeAttesi!=null) {
  127.                 boolean found = false;
  128.                 for (Integer integer : returnCodeAttesi) {
  129.                     if(integer.intValue() == ModICostanti.MODIPA_PROFILO_INTERAZIONE_HTTP_CODE_2XX_INT_VALUE) {
  130.                         if((returnCodeInt >= 200) && (returnCodeInt<=299) ) {
  131.                             found = true;
  132.                         }
  133.                     }
  134.                     else if(integer.intValue() == returnCodeInt) {
  135.                         found = true;
  136.                     }
  137.                     if(found) {
  138.                         break;
  139.                     }
  140.                 }
  141.                 if(!found) {
  142.                     StringBuilder sb = new StringBuilder();
  143.                     for (Integer integer : returnCodeAttesi) {
  144.                        
  145.                         if(integer.intValue() == ModICostanti.MODIPA_PROFILO_INTERAZIONE_HTTP_CODE_2XX_INT_VALUE) {
  146.                             sb = new StringBuilder();
  147.                             sb.append("2xx");
  148.                             break;
  149.                         }
  150.                        
  151.                         if(sb.length()>0) {
  152.                             sb.append(",");
  153.                         }
  154.                         sb.append(integer.intValue());
  155.                     }
  156.                     erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.PROFILO_TRASMISSIONE,
  157.                             "HTTP Status '"+returnCodeInt+"' differente da quello atteso per il profilo bloccante (atteso: "+sb.toString()+")"));
  158.                 }
  159.             }
  160.         }
  161.        
  162.     }
  163.    
  164.     private String getErrorHeaderHttpPrefix(String hdr) {
  165.         return "Header HTTP '"+hdr+"'";
  166.     }
  167.     private String getErrorHeaderHttpNonPresente(String hdr) {
  168.         return getErrorHeaderHttpPrefix(hdr)+" non presente";
  169.     }
  170.     private String getErrorHeaderHttpPresentePiuVolte(String hdr) {
  171.         return getErrorHeaderHttpPrefix(hdr)+" presente più volte";
  172.     }
  173.    
  174.     static String getErroreTokenSenzaClaim(String c) {
  175.         return "Token senza claim '"+c+"'";
  176.     }
  177.     static String getErroreTokenClaimNonValido(String c, Exception e) {
  178.         return "Token con claim '"+c+"' non valido: "+e.getMessage();
  179.     }
  180.    
  181.     public void validateAsyncInteractionProfile(OpenSPCoop2Message msg, boolean request, String asyncInteractionType, String asyncInteractionRole,
  182.             AccordoServizioParteComune apiContenenteRisorsa, String azione,
  183.             Busta busta, List<Eccezione> erroriValidazione,
  184.             String replyTo) throws ProtocolException {
  185.                
  186.         String correlationIdHeader = this.modiProperties.getRestCorrelationIdHeader();
  187.         String correlationId = null;
  188.         if(msg!=null) {
  189.             if(request && msg.getTransportRequestContext()!=null) {
  190.                 correlationId = msg.getTransportRequestContext().getHeaderFirstValue(correlationIdHeader);
  191.             }
  192.             else if(!request && msg.getTransportResponseContext()!=null) {
  193.                 correlationId = msg.getTransportResponseContext().getHeaderFirstValue(correlationIdHeader);
  194.             }
  195.         }
  196.        
  197.         String replyToHeader = this.modiProperties.getRestReplyToHeader();
  198.         String replyToAddress = null;
  199.         if(msg!=null) {
  200.             if(request && msg.getTransportRequestContext()!=null) {
  201.                 replyToAddress = msg.getTransportRequestContext().getHeaderFirstValue(replyToHeader);
  202.             }
  203.             else if(!request && msg.getTransportResponseContext()!=null) {
  204.                 replyToAddress = msg.getTransportResponseContext().getHeaderFirstValue(replyToHeader);
  205.             }
  206.         }
  207.        
  208.         String locationHeader = this.modiProperties.getRestLocationHeader();
  209.         String location = null;
  210.         if(msg!=null) {
  211.             if(request && msg.getTransportRequestContext()!=null) {
  212.                 location = msg.getTransportRequestContext().getHeaderFirstValue(locationHeader);
  213.             }
  214.             else if(!request && msg.getTransportResponseContext()!=null) {
  215.                 location = msg.getTransportResponseContext().getHeaderFirstValue(locationHeader);
  216.             }
  217.         }
  218.        
  219.         if(replyToAddress!=null) {
  220.             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_REPLY_TO, replyToAddress);
  221.         }
  222.         if(correlationId!=null) {
  223.             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_ID_CORRELAZIONE, correlationId);
  224.             if(correlationId.length()<=255) {
  225.                 busta.setCollaborazione(correlationId);
  226.             }
  227.         }
  228.        
  229.         String returnCode = null;
  230.         int returnCodeInt = -1;
  231.         if(!request && msg.getTransportResponseContext()!=null) {
  232.             returnCode = msg.getTransportResponseContext().getCodiceTrasporto();
  233.             if(returnCode!=null) {
  234.                 try {
  235.                     returnCodeInt = Integer.valueOf(returnCode);
  236.                 }catch(Exception e) {
  237.                     // ignore
  238.                 }
  239.             }
  240.         }
  241.        
  242.         // Fix: il controllo deve essere fatto solo per i codici che non rientrano in 4xx e 5xx
  243.         boolean is4xx5xx = false;
  244.         if(!request) {
  245.             is4xx5xx = (returnCodeInt>=400) && (returnCodeInt<=599);
  246.         }
  247.        
  248.         Integer [] returnCodeAttesi = null;
  249.        
  250.         if(!is4xx5xx && asyncInteractionType!=null) {
  251.             if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_VALUE_PUSH.equals(asyncInteractionType)) {
  252.                 if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RICHIESTA.equals(asyncInteractionRole)) {
  253.                     if(request) {
  254.                         if(replyToAddress==null || "".equals(replyToAddress)) {
  255.                             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SERVIZIO_CORRELATO_NON_PRESENTE,
  256.                                     getErrorHeaderHttpNonPresente(replyToHeader)));
  257.                             return;
  258.                         }
  259.                         if(this.modiProperties.isRestSecurityTokenPushReplyToUpdateInErogazione()) {
  260.                             if(msg.getTransportRequestContext()!=null) {
  261.                                 msg.getTransportRequestContext().removeHeader(replyToHeader); // rimuovo se giĆ  esiste
  262.                             }
  263.                             msg.forceTransportHeader(replyToHeader, replyTo);
  264.                         }
  265.                     }
  266.                     else {
  267.                         if(correlationId==null || "".equals(correlationId)) {
  268.                             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.COLLABORAZIONE_NON_PRESENTE,
  269.                                     getErrorHeaderHttpNonPresente(correlationIdHeader)));
  270.                             return;
  271.                         }
  272.                         returnCodeAttesi = this.modiProperties.getRestNonBloccantePushRequestHttpStatus();
  273.                     }
  274.                 }
  275.                 else {
  276.                     if(request) {
  277.                         if(correlationId==null || "".equals(correlationId)) {
  278.                             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.COLLABORAZIONE_NON_PRESENTE,
  279.                                     getErrorHeaderHttpNonPresente(correlationIdHeader)));
  280.                             return;
  281.                         }
  282.                     }
  283.                     else {
  284.                         returnCodeAttesi = this.modiProperties.getRestNonBloccantePushResponseHttpStatus();
  285.                     }
  286.                 }
  287.             }
  288.             else {
  289.                 // pull
  290.                 if(request) {
  291.                    
  292.                     // Flusso di richiesta
  293.                    
  294.                     if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RICHIESTA_STATO.equals(asyncInteractionRole) ||
  295.                             ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RISPOSTA.equals(asyncInteractionRole)) {
  296.                    
  297.                         String urlInvocata = msg.getTransportRequestContext().getFunctionParameters();
  298.                         if(urlInvocata!=null && !"".equals(urlInvocata)) {
  299.                            
  300.                             String resourcePathAzione = null;
  301.                             for (Resource r : apiContenenteRisorsa.getResourceList()) {
  302.                                 if(r.getNome().equals(azione)) {
  303.                                     resourcePathAzione = r.getPath();
  304.                                     break;
  305.                                 }
  306.                             }
  307.                            
  308.                             if(!urlInvocata.startsWith("/")) {
  309.                                 urlInvocata = "/" + urlInvocata;
  310.                             }
  311.                             String correlationIdExtracted = ModIUtilities.extractCorrelationIdFromLocation(resourcePathAzione, urlInvocata, false, this.log);
  312.                             if(correlationIdExtracted!=null && correlationIdExtracted.length()<=255) {
  313.                                 busta.setCollaborazione(correlationIdExtracted);
  314.                             }
  315.                         }
  316.                        
  317.                     }
  318.                    
  319.                    
  320.                 }
  321.                 else {
  322.                    
  323.                     // Flusso di risposta
  324.                    
  325.                     if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RICHIESTA.equals(asyncInteractionRole)) {
  326.                         if(location==null || "".equals(location)) {
  327.                             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SERVIZIO_CORRELATO_NON_PRESENTE,
  328.                                     getErrorHeaderHttpNonPresente(locationHeader)));
  329.                             return;
  330.                         }
  331.                         busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_LOCATION, location);
  332.                        
  333.                         String correlationIdExtracted = ModIUtilities.extractCorrelationId(location, apiContenenteRisorsa, azione, asyncInteractionRole, this.log);
  334.                         if(correlationIdExtracted!=null && correlationIdExtracted.length()<=255) {
  335.                             busta.setCollaborazione(correlationIdExtracted);
  336.                         }
  337.                        
  338.                         returnCodeAttesi = this.modiProperties.getRestNonBloccantePullRequestHttpStatus();
  339.                     }
  340.                     else if(ModICostanti.MODIPA_PROFILO_INTERAZIONE_ASINCRONA_RUOLO_VALUE_RICHIESTA_STATO.equals(asyncInteractionRole)) {
  341.                        
  342.                         Integer [] returnCodeResourceReady = this.modiProperties.getRestNonBloccantePullRequestStateOkHttpStatus();
  343.                         boolean isReady = false;
  344.                         for (Integer integer : returnCodeResourceReady) {
  345.                             if(integer.intValue() == returnCodeInt) {
  346.                                 isReady = true;
  347.                                 break;
  348.                             }
  349.                         }
  350.                        
  351.                         if(isReady) {
  352.                             if(location==null || "".equals(location)) {
  353.                                 erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SERVIZIO_CORRELATO_NON_PRESENTE,
  354.                                         getErrorHeaderHttpNonPresente(locationHeader)));
  355.                                 return;
  356.                             }
  357.                             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_INTERAZIONE_ASINCRONA_LOCATION, location);
  358.                            
  359.                             String correlationIdExtracted = ModIUtilities.extractCorrelationId(location, apiContenenteRisorsa, azione, asyncInteractionRole, this.log);
  360.                             if(correlationIdExtracted!=null && correlationIdExtracted.length()<=255) {
  361.                                 busta.setCollaborazione(correlationIdExtracted);
  362.                             }
  363.                            
  364.                             returnCodeAttesi = returnCodeResourceReady;
  365.                         }
  366.                         else {
  367.                             Integer [] returnCodeAttesiNotReady = this.modiProperties.getRestNonBloccantePullRequestStateNotReadyHttpStatus();
  368.                             returnCodeAttesi = new Integer[returnCodeResourceReady.length+returnCodeAttesiNotReady.length];
  369.                             int i = 0;
  370.                             for (int j=0; j < returnCodeAttesiNotReady.length; j++) {
  371.                                 returnCodeAttesi[i] = returnCodeAttesiNotReady[j];
  372.                                 i++;
  373.                             }
  374.                             for (int j=0; j < returnCodeResourceReady.length; j++) {
  375.                                 returnCodeAttesi[i] = returnCodeResourceReady[j];
  376.                                 i++;
  377.                             }
  378.                         }
  379.                        
  380.                     }
  381.                     else {
  382.                         returnCodeAttesi = this.modiProperties.getRestNonBloccantePullResponseHttpStatus();
  383.                     }
  384.                 }
  385.             }
  386.         }
  387.        
  388.         if(returnCodeAttesi!=null) {
  389.             boolean found = false;
  390.             for (Integer integer : returnCodeAttesi) {
  391.                 if(integer.intValue() == returnCodeInt) {
  392.                     found = true;
  393.                     break;
  394.                 }
  395.             }
  396.             if(!found) {
  397.                 StringBuilder sb = new StringBuilder();
  398.                 for (Integer integer : returnCodeAttesi) {
  399.                     if(sb.length()>0) {
  400.                         sb.append(",");
  401.                     }
  402.                     sb.append(integer.intValue());
  403.                 }
  404.                 erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.PROFILO_TRASMISSIONE,
  405.                         "HTTP Status '"+returnCodeInt+"' differente da quello atteso per il profilo non bloccante '"+asyncInteractionType+"' con ruolo '"+asyncInteractionRole+"' (atteso: "+sb.toString()+")"));
  406.             }
  407.         }
  408.     }
  409.    
  410.     public String validateSecurityProfile(OpenSPCoop2Message msg, boolean request, String securityMessageProfile, boolean useKIDtokenHeader, String headerTokenRest,
  411.             boolean corniceSicurezza, String patternCorniceSicurezza, String schemaCorniceSicurezza,
  412.             boolean includiRequestDigest,
  413.             Busta busta, List<Eccezione> erroriValidazione,
  414.             ModITruststoreConfig trustStoreCertificati, ModITruststoreConfig trustStoreSsl, ModISecurityConfig securityConfig,
  415.             boolean buildSecurityTokenInRequest, ModIHeaderType headerType, boolean integritaCustom, boolean securityHeaderObbligatorio,
  416.             Map<String, Object> dynamicMapParameter, Busta datiRichiesta,
  417.             IDSoggetto idSoggetto, MsgDiagnostico msgDiag) throws ProtocolException {
  418.        
  419.         if(msg==null) {
  420.             throw new ProtocolException("Param msg is null");
  421.         }
  422.                
  423.         boolean bufferMessageReadOnly = this.modiProperties.isReadByPathBufferEnabled();
  424.         String idTransazione = null;
  425.         if(this.context!=null) {
  426.             idTransazione = (String)this.context.getObject(org.openspcoop2.core.constants.Costanti.ID_TRANSAZIONE);
  427.         }
  428.        
  429.         String securityTokenHeader = headerTokenRest;
  430.         List<String> securityTokens = null;
  431.         if(request && msg.getTransportRequestContext()!=null) {
  432.             securityTokens = msg.getTransportRequestContext().getHeaderValues(securityTokenHeader);
  433.         }
  434.         else if(!request && msg.getTransportResponseContext()!=null) {
  435.             securityTokens = msg.getTransportResponseContext().getHeaderValues(securityTokenHeader);
  436.         }
  437.         String securityToken = null;
  438.         if(securityTokens!=null && !securityTokens.isEmpty()) {
  439.             securityToken = securityTokens.get(0);
  440.         }
  441.        
  442.        
  443.         boolean attesoSecurityHeader = securityHeaderObbligatorio;
  444.         if(!request) {
  445.             try {
  446.                 if(msg.isFault()) {
  447.                     attesoSecurityHeader = false;
  448.                 }
  449.             }catch(Exception e) {
  450.                 throw new ProtocolException(e.getMessage(),e);
  451.             }
  452.         }
  453.        
  454.         if(securityToken==null || "".equals(securityToken)) {
  455.             if(attesoSecurityHeader) {
  456.                 erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_TOKEN_NON_PRESENTE,
  457.                         getErrorHeaderHttpNonPresente(securityTokenHeader)));
  458.             }
  459.             return null;
  460.         }
  461.         if(securityTokens.size()>1) {
  462.             if(attesoSecurityHeader) {
  463.                 erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_TOKEN_PRESENTE_PIU_VOLTE,
  464.                         getErrorHeaderHttpPresentePiuVolte(securityTokenHeader)));
  465.             }
  466.             return null;
  467.         }
  468.        
  469.         if(busta!=null && integritaCustom) {
  470.             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CUSTOM_HEADER,headerTokenRest);
  471.         }
  472.        
  473.         String token = securityToken;
  474.         if(HttpConstants.AUTHORIZATION.equalsIgnoreCase(securityTokenHeader)) {
  475.             if(request) {
  476.                 if(msg.getTransportRequestContext()==null || msg.getTransportRequestContext().getCredential()==null) {
  477.                     erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_TOKEN_NON_PRESENTE,
  478.                             getErrorHeaderHttpNonPresente(HttpConstants.AUTHORIZATION)));
  479.                     return null;
  480.                 }
  481.                 if(msg.getTransportRequestContext().getCredential().getBearerToken()==null) {
  482.                     if(msg.getTransportRequestContext().getCredential().getUsername()!=null) {
  483.                         erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_TOKEN_NON_PRESENTE,
  484.                                 getErrorHeaderHttpPrefix(HttpConstants.AUTHORIZATION)+" non presente con prefisso '"+HttpConstants.AUTHORIZATION_PREFIX_BEARER+"'"));
  485.                         return null;
  486.                     }
  487.                     else {
  488.                         erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_TOKEN_NON_PRESENTE,
  489.                                 getErrorHeaderHttpNonPresente(HttpConstants.AUTHORIZATION)));
  490.                         return null;
  491.                     }
  492.                 }
  493.                 token = msg.getTransportRequestContext().getCredential().getBearerToken();
  494.             }
  495.             else {
  496.                 if(token.toLowerCase().startsWith(HttpConstants.AUTHORIZATION_PREFIX_BEARER.toLowerCase())){
  497.                     token = token.substring(HttpConstants.AUTHORIZATION_PREFIX_BEARER.length());
  498.                 }
  499.                 else {
  500.                     if(token.toLowerCase().startsWith(HttpConstants.AUTHORIZATION_PREFIX_BASIC.toLowerCase())){
  501.                         if(attesoSecurityHeader) {
  502.                             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_TOKEN_NON_PRESENTE,
  503.                                     getErrorHeaderHttpPrefix(HttpConstants.AUTHORIZATION)+" non presente con prefisso '"+HttpConstants.AUTHORIZATION_PREFIX_BEARER+"'"));
  504.                         }
  505.                         return null;
  506.                     }
  507.                     else {
  508.                         if(attesoSecurityHeader) {
  509.                             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_TOKEN_NON_PRESENTE,
  510.                                     getErrorHeaderHttpNonPresente(HttpConstants.AUTHORIZATION)));
  511.                         }
  512.                         return null;
  513.                     }
  514.                 }
  515.             }
  516.         }
  517.        
  518.        
  519.         boolean integritaX509 = false;
  520.         if(ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0301.equals(securityMessageProfile) ||
  521.                 ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0302.equals(securityMessageProfile)) {
  522.             integritaX509 = true;
  523.         }
  524.         boolean integritaKid = false;
  525.         if(ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0401.equals(securityMessageProfile) ||
  526.                 ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0402.equals(securityMessageProfile)) {
  527.             integritaKid = true;
  528.         }
  529.         boolean integrita = integritaX509 || integritaKid;
  530.        
  531.        
  532.         boolean tokenAudit = corniceSicurezza && !CostantiDB.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_PATTERN_OLD.equals(patternCorniceSicurezza) && schemaCorniceSicurezza!=null;
  533.                
  534.         boolean apiSoap = ServiceBinding.SOAP.equals(msg.getServiceBinding());
  535.        

  536.         String prefix = "";
  537.         boolean headerDuplicati = headerType.isHeaderDuplicati();
  538.         boolean headerAuthentication = headerType.isUsabledForAuthentication();
  539.         if(headerDuplicati || tokenAudit) {
  540.             prefix = "[Header '"+headerTokenRest+"'] ";
  541.         }
  542.        
  543.         /*
  544.          * == signature ==
  545.          */
  546.        
  547.         OpenSPCoop2Message msgToken = null;
  548.         try {
  549.             msgToken = msg.getFactory().createMessage(MessageType.JSON, MessageRole.NONE,
  550.                 HttpConstants.CONTENT_TYPE_JSON, token.getBytes(), null, null).getMessage_throwParseException();
  551.         }catch(Exception e) {
  552.             throw new ProtocolException(e.getMessage(),e);
  553.         }
  554.         String payloadToken = null;
  555.         X509Certificate x509 = null;
  556.         String kid = null;
  557.         try {
  558.        
  559.             //  ** Timestamp **
  560.             Long timeToLive = this.modiProperties.getRestSecurityTokenClaimsIatTimeCheckMilliseconds();
  561.             if(securityConfig.getCheckTtlIatMilliseconds()!=null) {
  562.                 timeToLive = securityConfig.getCheckTtlIatMilliseconds();
  563.             }
  564.             if(timeToLive!=null && msg!=null) {
  565.                 msg.addContextProperty(ModICostanti.MODIPA_OPENSPCOOP2_MSG_CONTEXT_IAT_TTL_CHECK, timeToLive);
  566.             }
  567.            
  568.             MessageSecurityReceiver_jose joseSignature = new MessageSecurityReceiver_jose();
  569.             MessageSecurityContextParameters messageSecurityContextParameters = new MessageSecurityContextParameters();
  570.             MessageSecurityContext messageSecurityContext = new MessageSecurityContext_impl(messageSecurityContextParameters);
  571.             Map<String,Object> secProperties = new HashMap<>();
  572.             secProperties.put(SecurityConstants.SECURITY_ENGINE, SecurityConstants.SECURITY_ENGINE_JOSE);
  573.             secProperties.put(SecurityConstants.ACTION, SecurityConstants.SIGNATURE_ACTION);
  574.             secProperties.put(SecurityConstants.SIGNATURE_MODE, SecurityConstants.SIGNATURE_MODE_COMPACT);
  575.             secProperties.put(SecurityConstants.SIGNATURE_DETACHED, SecurityConstants.SIGNATURE_DETACHED_FALSE);
  576.             secProperties.put(SecurityConstants.DETACH_SECURITY_INFO, SecurityConstants.TRUE);
  577.             secProperties.put(SecurityConstants.JOSE_USE_HEADERS, SecurityConstants.JOSE_USE_HEADERS_TRUE);
  578.             secProperties.put(SecurityConstants.JOSE_USE_HEADERS_JWK, SecurityConstants.JOSE_USE_HEADERS_FALSE);
  579.             secProperties.put(SecurityConstants.JOSE_USE_HEADERS_JKU, SecurityConstants.JOSE_USE_HEADERS_FALSE);
  580.             secProperties.put(SecurityConstants.JOSE_USE_HEADERS_X5T, SecurityConstants.JOSE_USE_HEADERS_FALSE);
  581.             if(integritaKid || useKIDtokenHeader) {
  582.                 secProperties.put(SecurityConstants.JOSE_USE_HEADERS_KID, SecurityConstants.JOSE_USE_HEADERS_TRUE);
  583.                 secProperties.put(SecurityConstants.JOSE_USE_HEADERS_X5C, SecurityConstants.JOSE_USE_HEADERS_FALSE);
  584.                 secProperties.put(SecurityConstants.JOSE_USE_HEADERS_X5U, SecurityConstants.JOSE_USE_HEADERS_FALSE);
  585.                 secProperties.put(SecurityConstants.JOSE_USE_HEADERS_X5T_256, SecurityConstants.JOSE_USE_HEADERS_FALSE);
  586.             }
  587.             else {
  588.                 secProperties.put(SecurityConstants.JOSE_USE_HEADERS_KID, SecurityConstants.JOSE_USE_HEADERS_FALSE);
  589.                
  590.                 boolean x5c = tokenAudit && apiSoap ? this.modiProperties.isSecurityTokenAuditApiSoapX509RiferimentoX5c() : securityConfig.isX5c();
  591.                 secProperties.put(SecurityConstants.JOSE_USE_HEADERS_X5C, x5c ? SecurityConstants.JOSE_USE_HEADERS_TRUE: SecurityConstants.JOSE_USE_HEADERS_FALSE);
  592.                
  593.                 boolean x5u = tokenAudit && apiSoap ? this.modiProperties.isSecurityTokenAuditApiSoapX509RiferimentoX5u() : securityConfig.isX5u();
  594.                 secProperties.put(SecurityConstants.JOSE_USE_HEADERS_X5U, x5u ? SecurityConstants.JOSE_USE_HEADERS_TRUE: SecurityConstants.JOSE_USE_HEADERS_FALSE);
  595.                
  596.                 boolean x5t = tokenAudit && apiSoap ? this.modiProperties.isSecurityTokenAuditApiSoapX509RiferimentoX5t() : securityConfig.isX5t();
  597.                 secProperties.put(SecurityConstants.JOSE_USE_HEADERS_X5T_256, x5t ? SecurityConstants.JOSE_USE_HEADERS_TRUE: SecurityConstants.JOSE_USE_HEADERS_FALSE);
  598.             }
  599.             secProperties.put(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_TYPE, trustStoreCertificati.getSecurityMessageTruststoreType());
  600.             if(!trustStoreCertificati.isSecurityMessageTruststoreRemote()) {
  601.                 secProperties.put(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_FILE, trustStoreCertificati.getSecurityMessageTruststorePath());
  602.             }
  603.             if(!trustStoreCertificati.isSecurityMessageTruststoreJWK() && !trustStoreCertificati.isSecurityMessageTruststoreRemote() &&
  604.                 trustStoreCertificati.getSecurityMessageTruststorePassword()!=null) {
  605.                 secProperties.put(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_PASSWORD, trustStoreCertificati.getSecurityMessageTruststorePassword());
  606.             }
  607.             if(trustStoreCertificati.getSecurityMessageTruststoreCRLs()!=null) {
  608.                 secProperties.put(SecurityConstants.SIGNATURE_CRL, trustStoreCertificati.getSecurityMessageTruststoreCRLs());
  609.             }
  610.             if(trustStoreCertificati.getSecurityMessageTruststoreOCSPPolicy()!=null) {
  611.                 secProperties.put(SecurityConstants.SIGNATURE_OCSP, trustStoreCertificati.getSecurityMessageTruststoreOCSPPolicy());
  612.             }
  613.             if(trustStoreCertificati.isSecurityMessageTruststoreRemote()) {
  614.                 RemoteKeyType keyType = this.modiProperties.getRemoteKeyType(trustStoreCertificati.getSecurityMessageTruststoreType());
  615.                 secProperties.put(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_REMOTE_STORE_PROVIDER, new RemoteStoreProvider(this.requestInfo, keyType));
  616.                 secProperties.put(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_REMOTE_STORE_KEY_TYPE, keyType);
  617.                 secProperties.put(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_REMOTE_STORE_CONFIG, this.modiProperties.getRemoteStoreConfig(trustStoreCertificati.getSecurityMessageTruststoreType(), idSoggetto));
  618.             }
  619.             if(securityConfig.isX5u() &&
  620.                 trustStoreSsl!=null && trustStoreSsl.getSecurityMessageTruststorePath()!=null) {
  621.                 secProperties.put(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_FILE, trustStoreSsl.getSecurityMessageTruststorePath());
  622.                 secProperties.put(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_TYPE, trustStoreSsl.getSecurityMessageTruststoreType());
  623.                 if(trustStoreSsl.getSecurityMessageTruststorePassword()!=null) {
  624.                     secProperties.put(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_PASSWORD, trustStoreSsl.getSecurityMessageTruststorePassword());
  625.                 }
  626.                 if(trustStoreSsl.getSecurityMessageTruststoreCRLs()!=null) {
  627.                     secProperties.put(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_CRL, trustStoreSsl.getSecurityMessageTruststoreCRLs());
  628.                 }
  629.                 if(trustStoreSsl.getSecurityMessageTruststoreOCSPPolicy()!=null) {
  630.                     secProperties.put(SecurityConstants.JOSE_USE_HEADERS_TRUSTSTORE_SSL_OCSP, trustStoreSsl.getSecurityMessageTruststoreOCSPPolicy());
  631.                 }
  632.             }
  633.             messageSecurityContext.setIncomingProperties(secProperties, false);
  634.             DynamicMapBuilderUtils.injectDynamicMap(busta, this.requestInfo, this.context, this.log);
  635.             joseSignature.process(messageSecurityContext, msgToken, busta, this.context);
  636.             joseSignature.detachSecurity(messageSecurityContext, msgToken.castAsRest());
  637.            
  638.             ModIRESTSecurity restSecurity = (ModIRESTSecurity) msg.getContextProperty(ModICostanti.MODIPA_OPENSPCOOP2_MSG_CONTEXT_SBUSTAMENTO_REST);
  639.             if(restSecurity==null) {
  640.                 restSecurity = new ModIRESTSecurity(securityTokenHeader, request);
  641.                 msg.addContextProperty(ModICostanti.MODIPA_OPENSPCOOP2_MSG_CONTEXT_SBUSTAMENTO_REST, restSecurity);
  642.             }
  643.             else {
  644.                 restSecurity.getTokenHeaderNames().add(securityTokenHeader);
  645.             }

  646.             ByteArrayOutputStream bout = new ByteArrayOutputStream();
  647.             msgToken.writeTo(bout, true);
  648.             bout.flush();
  649.             bout.close();
  650.            
  651.             payloadToken = bout.toString();
  652.             /** System.out.println("PAYLOAD TOKEN ["+payloadToken+"]"); */  
  653.            
  654.             x509 = joseSignature.getX509Certificate();
  655.             /** System.out.println("CERTIFICATE ["+x509.getSubjectX500Principal().toString()+"]"); */
  656.            
  657.             kid = joseSignature.getCertificateId();
  658.            
  659.         }catch(Exception e) {
  660.             logError("Errore durante la validazione del token di sicurezza: "+e.getMessage(),e);
  661.             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_FIRMA_NON_VALIDA,
  662.                     prefix+e.getMessage(),e));
  663.             return token;
  664.         }
  665.        
  666.         if(integritaKid || useKIDtokenHeader) {
  667.             if(kid==null) {
  668.                 erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(
  669.                         request ? CodiceErroreCooperazione.SERVIZIO_APPLICATIVO_FRUITORE_NON_PRESENTE :
  670.                             CodiceErroreCooperazione.SERVIZIO_APPLICATIVO_EROGATORE_NON_PRESENTE,
  671.                         prefix+"Riferimento alla chiave (kid) non presente"));
  672.             }
  673.             else {
  674.                
  675.                 if(!headerDuplicati || headerAuthentication) {
  676.                     busta.addProperty(tokenAudit ? ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_AUDIT_KID : ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_KID,
  677.                             kid);
  678.                    
  679.                     if(headerDuplicati) {
  680.                         this.context.addObject(ModICostanti.MODIPA_CONTEXT_KID_AUTHORIZATION, x509);
  681.                     }
  682.                 }
  683.                 else {
  684.                     String kidAuthorization = null;
  685.                     Object oKidAuthorization = this.context.removeObject(ModICostanti.MODIPA_CONTEXT_KID_AUTHORIZATION);
  686.                     if(oKidAuthorization instanceof String) {
  687.                         kidAuthorization = (String) oKidAuthorization;
  688.                     }
  689.                     if(kidAuthorization!=null) {
  690.                         if(!kidAuthorization.equals(kid)) {
  691.                             StringBuilder sb = new StringBuilder();
  692.                             sb.append(HttpConstants.AUTHORIZATION).append(" ");
  693.                             sb.append("kid=\"").append(kidAuthorization).append("\"");
  694.                             sb.append("\n");
  695.                             sb.append(headerTokenRest).append(" ");
  696.                             sb.append("kid=\"").append(kid).append("\"");
  697.                             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(
  698.                                     request ? CodiceErroreCooperazione.SERVIZIO_APPLICATIVO_FRUITORE_NON_VALIDO :
  699.                                         CodiceErroreCooperazione.SERVIZIO_APPLICATIVO_EROGATORE_NON_VALIDO,
  700.                                     "I token '"+HttpConstants.AUTHORIZATION+"' e '"+headerTokenRest+"' risultano firmati da certificati differenti\n"+sb.toString()));
  701.                         }
  702.                     }
  703.                     else {
  704.                         if(erroriValidazione.isEmpty()) {
  705.                             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_TOKEN_NON_PRESENTE,
  706.                                     "Riferimento alla chiave (kid) nell'header '"+HttpConstants.AUTHORIZATION+"' non presente"));
  707.                         }
  708.                     }
  709.                 }
  710.                
  711.                 if(request &&
  712.                         (!headerDuplicati || headerAuthentication)
  713.                         ){
  714.                            
  715.                         if(msg==null || msg.getTransportRequestContext()==null || msg.getTransportRequestContext().getInterfaceName()==null) {
  716.                             throw new ProtocolException("ID Porta non presente");
  717.                         }
  718.                         IDPortaApplicativa idPA = new IDPortaApplicativa();
  719.                         idPA.setNome(msg.getTransportRequestContext().getInterfaceName());
  720.                         PortaApplicativa pa = null;
  721.                         try {
  722.                             pa = this.factory.getCachedConfigIntegrationReader(this.state, this.requestInfo).getPortaApplicativa(idPA);
  723.                         }catch(Exception e) {
  724.                             throw new ProtocolException(e.getMessage(),e);
  725.                         }
  726.                         boolean autenticazioneToken = pa!=null && pa.getGestioneToken()!=null && pa.getGestioneToken().getPolicy()!=null && StringUtils.isNotEmpty(pa.getGestioneToken().getPolicy());
  727.                         if(autenticazioneToken) {
  728.                             // l'autenticazione dell'applicativo mittente avviene per token
  729.                             // Il token rappresenta:
  730.                             // - un integrity nel caso PDND + Integrity
  731.                             // - una configurazione errata. In questo caso l'header Authorization non verrĆ  validato con successo (es. certificato x509 non presente nel token).
  732.                             //   Se per caso risultasse corretto non ĆØ un problema
  733.                         }
  734.                         else {
  735.                            
  736.                             String clientId = readClientIdSafe(payloadToken);
  737.                             if(clientId!=null) {
  738.                                 /** PER ADESSO NON SUPPORTATO
  739.                                 identificazioneApplicativoMittente(kid,msg,busta);
  740.                                  */
  741.                             }
  742.                            
  743.                         }
  744.                     }
  745.             }
  746.         }
  747.         else {
  748.             if(x509==null || x509.getSubjectX500Principal()==null) {
  749.                 erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(
  750.                         request ? CodiceErroreCooperazione.SERVIZIO_APPLICATIVO_FRUITORE_NON_PRESENTE :
  751.                             CodiceErroreCooperazione.SERVIZIO_APPLICATIVO_EROGATORE_NON_PRESENTE,
  752.                         prefix+"Certificato X509 mittente non presente"));
  753.             }
  754.             else {
  755.                
  756.                 if(!headerDuplicati || headerAuthentication) {
  757.                     busta.addProperty(tokenAudit ? ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_AUDIT_X509_SUBJECT : ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_X509_SUBJECT,
  758.                             x509.getSubjectX500Principal().toString());
  759.                     if(x509.getIssuerX500Principal()!=null) {
  760.                         busta.addProperty(tokenAudit ? ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_AUDIT_X509_ISSUER : ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_X509_ISSUER,
  761.                                 x509.getIssuerX500Principal().toString());
  762.                     }
  763.                    
  764.                     if(headerDuplicati) {
  765.                         this.context.addObject(ModICostanti.MODIPA_CONTEXT_X509_AUTHORIZATION, x509);
  766.                     }
  767.                 }
  768.                 else {
  769.                     /**
  770.                     String subjectAuthorization = busta.getProperty(busta.getProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_X509_SUBJECT));
  771.                     String issuerAuthorization = busta.getProperty(busta.getProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_X509_ISSUER));
  772.                     String subjectIntegrity = x509.getSubjectX500Principal().toString();
  773.                     String issuerIntegrity = x509.getIssuerX500Principal().toString();
  774.                     boolean subjectValid = false;
  775.                     if(subjectIntegrity!=null && subjectAuthorization!=null) {
  776.                         subjectValid = CertificateUtils.sslVerify(subjectAuthorization, subjectIntegrity, PrincipalType.subject, this.log);
  777.                     }
  778.                     boolean issuerValid = true;
  779.                     if(issuerAuthorization!=null && !"".equals(issuerAuthorization)) {
  780.                         if(issuerIntegrity==null) {
  781.                             issuerValid = false;
  782.                         }
  783.                         else {
  784.                             issuerValid = CertificateUtils.sslVerify(issuerAuthorization, issuerIntegrity, PrincipalType.issuer, this.log);
  785.                         }
  786.                     }
  787.                     else {
  788.                         issuerValid = (issuerIntegrity == null);
  789.                     }
  790.                    
  791.                     if(!subjectValid || !issuerValid){
  792.                         erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(
  793.                                 request ? CodiceErroreCooperazione.SERVIZIO_APPLICATIVO_FRUITORE_NON_VALIDO :
  794.                                     CodiceErroreCooperazione.SERVIZIO_APPLICATIVO_EROGATORE_NON_VALIDO,
  795.                                 "I token '"+HttpConstants.AUTHORIZATION+"' e '"+headerTokenRest+"' risultano firmati da certificati differenti"));
  796.                     }*/
  797.                     X509Certificate x509Authorization = null;
  798.                     Object oX509Authorization = this.context.removeObject(ModICostanti.MODIPA_CONTEXT_X509_AUTHORIZATION);
  799.                     if(oX509Authorization instanceof X509Certificate) {
  800.                         x509Authorization = (X509Certificate) oX509Authorization;
  801.                     }
  802.                     if(x509Authorization!=null) {
  803.                         if(!x509Authorization.equals(x509)) {
  804.                             StringBuilder sb = new StringBuilder();
  805.                             sb.append(HttpConstants.AUTHORIZATION).append(" ");
  806.                             sb.append("subject=\"").append(x509Authorization.getSubjectX500Principal().toString()).append("\"");
  807.                             if(x509Authorization.getIssuerX500Principal()!=null) {
  808.                                 sb.append(" issuer=\"").append(x509Authorization.getIssuerX500Principal().toString()).append("\"");
  809.                             }
  810.                             sb.append("\n");
  811.                             sb.append(headerTokenRest).append(" ");
  812.                             sb.append("subject=\"").append(x509.getSubjectX500Principal().toString()).append("\"");
  813.                             if(x509.getIssuerX500Principal()!=null) {
  814.                                 sb.append(" issuer=\"").append(x509.getIssuerX500Principal().toString()).append("\"");
  815.                             }
  816.                             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(
  817.                                     request ? CodiceErroreCooperazione.SERVIZIO_APPLICATIVO_FRUITORE_NON_VALIDO :
  818.                                         CodiceErroreCooperazione.SERVIZIO_APPLICATIVO_EROGATORE_NON_VALIDO,
  819.                                     "I token '"+HttpConstants.AUTHORIZATION+"' e '"+headerTokenRest+"' risultano firmati da certificati differenti\n"+sb.toString()));
  820.                         }
  821.                     }
  822.                     else {
  823.                         if(erroriValidazione.isEmpty()) {
  824.                             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_TOKEN_NON_PRESENTE,
  825.                                     "Certificato x509 nell'header '"+HttpConstants.AUTHORIZATION+"' non presente"));
  826.                         }
  827.                     }
  828.                 }
  829.                
  830.                 if(request &&
  831.                     (!headerDuplicati || headerAuthentication)
  832.                     ){
  833.                        
  834.                     if(msg==null || msg.getTransportRequestContext()==null || msg.getTransportRequestContext().getInterfaceName()==null) {
  835.                         throw new ProtocolException("ID Porta non presente");
  836.                     }
  837.                     IDPortaApplicativa idPA = new IDPortaApplicativa();
  838.                     idPA.setNome(msg.getTransportRequestContext().getInterfaceName());
  839.                     PortaApplicativa pa = null;
  840.                     try {
  841.                         pa = this.factory.getCachedConfigIntegrationReader(this.state, this.requestInfo).getPortaApplicativa(idPA);
  842.                     }catch(Exception e) {
  843.                         throw new ProtocolException(e.getMessage(),e);
  844.                     }
  845.                     boolean autenticazioneToken = pa!=null && pa.getGestioneToken()!=null && pa.getGestioneToken().getPolicy()!=null && StringUtils.isNotEmpty(pa.getGestioneToken().getPolicy());
  846.                     if(autenticazioneToken) {
  847.                         // l'autenticazione dell'applicativo mittente avviene per token
  848.                         // Il token rappresenta:
  849.                         // - un integrity nel caso PDND + Integrity
  850.                         // - una configurazione errata. In questo caso l'header Authorization non verrĆ  validato con successo (es. certificato x509 non presente nel token).
  851.                         //   Se per caso risultasse corretto non ĆØ un problema
  852.                     }
  853.                     else {
  854.                         identificazioneApplicativoMittente(x509,msg,busta,msgDiag);
  855.                     }
  856.                 }
  857.             }
  858.         }
  859.        
  860.         if(request && this.context!=null) {
  861.            
  862.             SecurityToken securityTokenForContext = ModIUtilities.newSecurityToken(this.context);
  863.            
  864.             RestMessageSecurityToken restSecurityToken = new RestMessageSecurityToken();
  865.            
  866.             if(x509!=null) {
  867.                 restSecurityToken.setCertificate(new CertificateInfo(x509, securityTokenHeader));
  868.             }
  869.             if(kid!=null) {
  870.                 restSecurityToken.setKid(kid);
  871.             }
  872.             restSecurityToken.setToken(token);
  873.             restSecurityToken.setHttpHeaderName(securityTokenHeader);
  874.             if(tokenAudit) {
  875.                 securityTokenForContext.setAudit(restSecurityToken);
  876.             }
  877.             else if(headerDuplicati) {
  878.                 if(headerAuthentication) {
  879.                     securityTokenForContext.setAuthorization(restSecurityToken);
  880.                 }
  881.                 else {
  882.                     securityTokenForContext.setIntegrity(restSecurityToken);    
  883.                 }
  884.             }
  885.             else {
  886.                 if(HttpConstants.AUTHORIZATION.equalsIgnoreCase(securityTokenHeader)) {
  887.                     securityTokenForContext.setAuthorization(restSecurityToken);
  888.                 }
  889.                 else {
  890.                     securityTokenForContext.setIntegrity(restSecurityToken);
  891.                 }
  892.             }
  893.            
  894.         }
  895.        
  896.         // NOTA: Inizializzare da qua il dynamicMap altrimenti non ci finisce l'identificazione del mittente effettuata dal metodo sopra 'identificazioneApplicativoMittente'
  897.         Map<String, Object> dynamicMap = null;
  898.         Map<String, Object> dynamicMapRequest = null;
  899.         if(!request) {
  900.             dynamicMapRequest = ModIUtilities.removeDynamicMapRequest(this.context);
  901.         }
  902.         try {
  903.             if(dynamicMapRequest!=null) {
  904.                 dynamicMap = DynamicUtils.buildDynamicMapResponse(msg, this.context, null, this.log, bufferMessageReadOnly, dynamicMapRequest);
  905.             }
  906.             else {
  907.                 dynamicMap = DynamicUtils.buildDynamicMap(msg, this.context, datiRichiesta, this.log, bufferMessageReadOnly);
  908.                 ModIUtilities.saveDynamicMapRequest(this.context, dynamicMap);
  909.             }
  910.         }catch(Exception e) {
  911.             throw new ProtocolException(e.getMessage(),e);
  912.         }
  913.         if(dynamicMapParameter!=null && dynamicMap!=null) {
  914.             dynamicMapParameter.putAll(dynamicMap);
  915.         }
  916.        
  917.        
  918.         try {
  919.             JsonNode jsonNode = JSONUtils.getInstance().getAsNode(payloadToken);
  920.             if(!(jsonNode instanceof ObjectNode)) {
  921.                 throw new ProtocolException("Payload del token possiede una struttura non valida");
  922.             }
  923.             ObjectNode objectNode = (ObjectNode) jsonNode;
  924.            
  925.             if(objectNode.has(Claims.JSON_WEB_TOKEN_RFC_7519_ISSUED_AT)) {
  926.                 Object iat = objectNode.get(Claims.JSON_WEB_TOKEN_RFC_7519_ISSUED_AT);
  927.                 if(iat==null) {
  928.                     erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.ORA_REGISTRAZIONE_NON_PRESENTE,
  929.                             prefix+getErroreTokenSenzaClaim(Claims.JSON_WEB_TOKEN_RFC_7519_ISSUED_AT)));
  930.                 }
  931.                 Date iatDate = toDate(iat, erroriValidazione, CodiceErroreCooperazione.ORA_REGISTRAZIONE_NON_VALIDA, prefix, Claims.JSON_WEB_TOKEN_RFC_7519_ISSUED_AT);
  932.                 if(iatDate!=null) { // altrimenti viene segnalato errore in erroriValidazione
  933.                     String iatValue = DateUtils.getSimpleDateFormatMs().format(iatDate);
  934.                     if(!headerDuplicati || headerAuthentication) {
  935.                         busta.addProperty(tokenAudit ? ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_AUDIT_IAT : ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_IAT,
  936.                                 iatValue);
  937.                     }
  938.                     else {
  939.                         String iatAuthorization = busta.getProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_IAT);
  940.                         if(!iatValue.equals(iatAuthorization)) {
  941.                             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_INTEGRITY_IAT, iatValue);
  942.                         }
  943.                     }
  944.                 }
  945.             }
  946.             else {
  947.                 erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.ORA_REGISTRAZIONE_NON_PRESENTE,
  948.                         prefix+getErroreTokenSenzaClaim(Claims.JSON_WEB_TOKEN_RFC_7519_ISSUED_AT)));
  949.             }
  950.            
  951.             if(objectNode.has(Claims.JSON_WEB_TOKEN_RFC_7519_EXPIRED)) {
  952.                 Object exp = objectNode.get(Claims.JSON_WEB_TOKEN_RFC_7519_EXPIRED);
  953.                 if(exp==null) {
  954.                     erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SCADENZA_NON_PRESENTE,
  955.                             prefix+getErroreTokenSenzaClaim(Claims.JSON_WEB_TOKEN_RFC_7519_EXPIRED)));
  956.                 }
  957.                 Date expDate = toDate(exp, erroriValidazione, CodiceErroreCooperazione.SCADENZA_NON_VALIDA, prefix, Claims.JSON_WEB_TOKEN_RFC_7519_EXPIRED);
  958.                 if(expDate!=null) { // altrimenti viene segnalato errore in erroriValidazione
  959.                     String expValue = DateUtils.getSimpleDateFormatMs().format(expDate);
  960.                     if(!headerDuplicati || headerAuthentication) {
  961.                         busta.addProperty(tokenAudit ? ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_AUDIT_EXP : ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_EXP,
  962.                                 expValue);
  963.                     }
  964.                     else {
  965.                         String expAuthorization = busta.getProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_EXP);
  966.                         if(!expValue.equals(expAuthorization)) {
  967.                             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_INTEGRITY_EXP, expValue);
  968.                         }
  969.                     }
  970.                 }
  971.             }
  972.             else {
  973.                 erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SCADENZA_NON_PRESENTE,
  974.                         prefix+getErroreTokenSenzaClaim(Claims.JSON_WEB_TOKEN_RFC_7519_EXPIRED)));
  975.             }
  976.            
  977.             if(objectNode.has(Claims.JSON_WEB_TOKEN_RFC_7519_NOT_TO_BE_USED_BEFORE)) {
  978.                 Object nbf = objectNode.get(Claims.JSON_WEB_TOKEN_RFC_7519_NOT_TO_BE_USED_BEFORE);
  979.                 if(nbf!=null) {
  980.                     Date nbfDate = toDate(nbf, erroriValidazione, CodiceErroreCooperazione.SCADENZA_NON_VALIDA, prefix, Claims.JSON_WEB_TOKEN_RFC_7519_NOT_TO_BE_USED_BEFORE);
  981.                     if(nbfDate!=null) { // altrimenti viene segnalato errore in erroriValidazione
  982.                         String nbfValue = DateUtils.getSimpleDateFormatMs().format(nbfDate);
  983.                         if(!headerDuplicati || headerAuthentication) {
  984.                             busta.addProperty(tokenAudit ? ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_AUDIT_NBF : ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_NBF,
  985.                                     nbfValue);
  986.                         }
  987.                         else {
  988.                             String nbfAuthorization = busta.getProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_NBF);
  989.                             if(!nbfValue.equals(nbfAuthorization)) {
  990.                                 busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_INTEGRITY_NBF, nbfValue);
  991.                             }
  992.                         }
  993.                     }
  994.                 }
  995.             }
  996.            
  997.             if(objectNode.has(Claims.JSON_WEB_TOKEN_RFC_7519_AUDIENCE)) {
  998.                 Object aud = objectNode.get(Claims.JSON_WEB_TOKEN_RFC_7519_AUDIENCE);
  999.                 if(aud==null) {
  1000.                     erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(
  1001.                             request ? CodiceErroreCooperazione.SERVIZIO_APPLICATIVO_EROGATORE_NON_PRESENTE :
  1002.                                 CodiceErroreCooperazione.SERVIZIO_APPLICATIVO_FRUITORE_NON_PRESENTE,
  1003.                         prefix+getErroreTokenSenzaClaim(Claims.JSON_WEB_TOKEN_RFC_7519_AUDIENCE)));
  1004.                 }
  1005.                 else {
  1006.                     String audValue = toString(aud);
  1007.                     if(tokenAudit) {
  1008.                         String audAuthorization = busta.getProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_AUDIENCE);
  1009.                         if(audAuthorization==null || !audValue.equals(audAuthorization)) {
  1010.                             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_AUDIT_AUDIENCE, audValue);
  1011.                         }
  1012.                     }
  1013.                     else {
  1014.                         if(!headerDuplicati || headerAuthentication) {
  1015.                             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_AUDIENCE, audValue);
  1016.                         }
  1017.                         else {
  1018.                             String audAuthorization = busta.getProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_AUDIENCE);
  1019.                             if(!audValue.equals(audAuthorization)) {
  1020.                                 busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_INTEGRITY_AUDIENCE, audValue);
  1021.                             }
  1022.                         }
  1023.                     }
  1024.                 }
  1025.             }
  1026.             else {
  1027.                 if(request || buildSecurityTokenInRequest) {
  1028.                     erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(
  1029.                             request ? CodiceErroreCooperazione.SERVIZIO_APPLICATIVO_EROGATORE_NON_PRESENTE :
  1030.                                 CodiceErroreCooperazione.SERVIZIO_APPLICATIVO_FRUITORE_NON_PRESENTE,
  1031.                         prefix+getErroreTokenSenzaClaim(Claims.JSON_WEB_TOKEN_RFC_7519_AUDIENCE)));
  1032.                 }
  1033.             }
  1034.            
  1035.             boolean jtiRequired = false;
  1036.             if(ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM02.equals(securityMessageProfile) ||
  1037.                     ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0302.equals(securityMessageProfile) ||
  1038.                     ModICostanti.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_VALUE_IDAM0402.equals(securityMessageProfile)) {
  1039.                 jtiRequired = true;
  1040.             }
  1041.             if(objectNode.has(Claims.JSON_WEB_TOKEN_RFC_7519_JWT_ID)) {
  1042.                 Object jti = objectNode.get(Claims.JSON_WEB_TOKEN_RFC_7519_JWT_ID);
  1043.                 if(jti==null) {
  1044.                     if(jtiRequired) {
  1045.                         erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.IDENTIFICATIVO_MESSAGGIO_NON_PRESENTE,
  1046.                                 prefix+getErroreTokenSenzaClaim(Claims.JSON_WEB_TOKEN_RFC_7519_JWT_ID)));
  1047.                     }
  1048.                 }
  1049.                 else {
  1050.                     String id = toString(jti);
  1051.                     if(tokenAudit) {
  1052.                         busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_AUDIT_ID, id);
  1053.                     }
  1054.                     else {
  1055.                         boolean addAsIdBusta = true;
  1056.                         if(headerDuplicati) {
  1057.                             if(headerAuthentication) {
  1058.                                 if(!securityConfig.isMultipleHeaderUseJtiAuthorizationAsIdMessaggio()) {
  1059.                                     String idActual = busta.getProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_ID);
  1060.                                     if(idActual==null || !idActual.equals(id)) {
  1061.                                         busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_AUTHORIZATION_ID, id);
  1062.                                     }
  1063.                                     addAsIdBusta = false;
  1064.                                 }
  1065.                             }
  1066.                             else {
  1067.                                 if(securityConfig.isMultipleHeaderUseJtiAuthorizationAsIdMessaggio()) {
  1068.                                     String idActual = busta.getProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_ID);
  1069.                                     if(idActual==null || !idActual.equals(id)) {
  1070.                                         busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_INTEGRITY_ID, id);
  1071.                                     }
  1072.                                     addAsIdBusta = false;
  1073.                                 }
  1074.                                 else {
  1075.                                     // verifico se ho gia' impostato authorization
  1076.                                     String idActualAuthorization = busta.getProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_AUTHORIZATION_ID);
  1077.                                     if(idActualAuthorization!=null && idActualAuthorization.equals(id)) {
  1078.                                         busta.removeProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_AUTHORIZATION_ID);
  1079.                                     }
  1080.                                 }
  1081.                             }
  1082.                         }
  1083.                         if(addAsIdBusta) {
  1084.                             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_ID, id);
  1085.                             if(id.length()<=255) {
  1086.                                 busta.setID(id);
  1087.                             }
  1088.                         }
  1089.                     }
  1090.                 }
  1091.             }
  1092.             else {
  1093.                 if(jtiRequired) {
  1094.                     erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.IDENTIFICATIVO_MESSAGGIO_NON_PRESENTE,
  1095.                             prefix+getErroreTokenSenzaClaim(Claims.JSON_WEB_TOKEN_RFC_7519_JWT_ID)));
  1096.                 }
  1097.             }

  1098.             if(!request) {
  1099.                 corniceSicurezza = false; // permessa solo per i messaggi di richiesta
  1100.             }
  1101.            
  1102.             boolean readIss = true;
  1103.             boolean readSub = true;
  1104.            
  1105.             if(corniceSicurezza) {
  1106.                
  1107.                 if(CostantiDB.MODIPA_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_PATTERN_OLD.equals(patternCorniceSicurezza)) {
  1108.                     readIss = readCorniceSicurezzaCodiceEnteLegacy(objectNode, busta,
  1109.                             erroriValidazione, prefix);
  1110.                     readSub = readCorniceSicurezzaUserLegacy(objectNode, busta,
  1111.                             erroriValidazione, prefix);
  1112.                     readCorniceSicurezzaIpUserLegacy(objectNode, busta,
  1113.                             erroriValidazione, prefix);
  1114.                 }
  1115.                 else {
  1116.                     readCorniceSicurezzaSchema(objectNode, msg, busta,
  1117.                             erroriValidazione, prefix,
  1118.                             schemaCorniceSicurezza, securityConfig.getCorniceSicurezzaSchemaConfig());
  1119.                 }
  1120.                
  1121.             }
  1122.            
  1123.             if(readIss &&
  1124.                 objectNode.has(Claims.JSON_WEB_TOKEN_RFC_7519_ISSUER)) {
  1125.                 Object iss = objectNode.get(Claims.JSON_WEB_TOKEN_RFC_7519_ISSUER);
  1126.                 if(iss!=null) {
  1127.                     busta.addProperty(tokenAudit ? ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_AUDIT_ISSUER : ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_ISSUER,
  1128.                             toString(iss));
  1129.                 }
  1130.             }
  1131.             if(readSub &&
  1132.                 objectNode.has(Claims.JSON_WEB_TOKEN_RFC_7519_SUBJECT)) {
  1133.                 Object sub = objectNode.get(Claims.JSON_WEB_TOKEN_RFC_7519_SUBJECT);
  1134.                 if(sub!=null) {
  1135.                     busta.addProperty(tokenAudit ? ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_AUDIT_SUBJECT : ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_SUBJECT,
  1136.                             toString(sub));
  1137.                 }
  1138.             }
  1139.            
  1140.             Object clientId = readObjectClientId(objectNode);
  1141.             if(clientId!=null) {
  1142.                 String clientIdValue = toString(clientId);
  1143.                 busta.addProperty(tokenAudit ? ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_AUDIT_CLIENT_ID : ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_CLIENT_ID,clientIdValue);
  1144.             }
  1145.            
  1146.            
  1147.             if( (tokenAudit || integritaX509 || integritaKid)
  1148.                     &&
  1149.                 objectNode.has(Costanti.PDND_PURPOSE_ID)
  1150.                 ) {
  1151.                 Object purposeId = objectNode.get(Costanti.PDND_PURPOSE_ID);
  1152.                 if(purposeId!=null) {
  1153.                     busta.addProperty(tokenAudit ? ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_AUDIT_PURPOSE_ID : ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_REST_INTEGRITY_PURPOSE_ID,
  1154.                             toString(purposeId));
  1155.                 }
  1156.             }
  1157.            
  1158.             String digestHeader = HttpConstants.DIGEST;
  1159.             String digestValueInHeaderHTTP = null;
  1160.             if(integrita && !integritaCustom) {
  1161.                
  1162.                 List<String> digests = null;
  1163.                 if(msg!=null) {
  1164.                     if(request && msg.getTransportRequestContext()!=null) {
  1165.                         digests = msg.getTransportRequestContext().getHeaderValues(digestHeader);
  1166.                     }
  1167.                     else if(!request && msg.getTransportResponseContext()!=null) {
  1168.                         digests = msg.getTransportResponseContext().getHeaderValues(digestHeader);
  1169.                     }
  1170.                 }  
  1171.                 String digest = null;
  1172.                 if(digests!=null && !digests.isEmpty()) {
  1173.                     digest = digests.get(0);
  1174.                 }
  1175.                 if(digest==null) {
  1176.                     if(msg.castAsRest().hasContent()) {
  1177.                         erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.PROFILO_TRASMISSIONE_NON_PRESENTE,
  1178.                                 getErrorHeaderHttpNonPresente(digestHeader)));
  1179.                     }
  1180.                 }
  1181.                 else if(digests.size()>1) {
  1182.                     erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.PROFILO_TRASMISSIONE_PRESENTE_PIU_VOLTE,
  1183.                             getErrorHeaderHttpPresentePiuVolte(digestHeader)));
  1184.                 }
  1185.                 else {
  1186.                     digestValueInHeaderHTTP = toString(digest);
  1187.                     busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_DIGEST, digestValueInHeaderHTTP);
  1188.                     if(request && includiRequestDigest && this.context!=null) {
  1189.                         this.context.addObject(ModICostanti.MODIPA_CONTEXT_REQUEST_DIGEST, digestValueInHeaderHTTP);
  1190.                     }
  1191.                    
  1192.                     if(!msg.castAsRest().hasContent()) {
  1193.                         String role = MessageRole.REQUEST.equals(msg.getMessageRole()) ? "richiesta" : "risposta";
  1194.                         erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_FIRMA_INTESTAZIONE_NON_VALIDA,
  1195.                                 getErrorHeaderHttpPrefix(digestHeader)+" presente in una "+role+" con http payload vuoto"));
  1196.                     }
  1197.                 }
  1198.             }
  1199.            
  1200.             if(digestValueInHeaderHTTP!=null) {
  1201.                
  1202.                 // Produco Digest Headers
  1203.                 ByteArrayOutputStream bout = new ByteArrayOutputStream();
  1204.                 msg.castAsRest().writeTo(bout, false, bufferMessageReadOnly, idTransazione);
  1205.                 bout.flush();
  1206.                 bout.close();
  1207.                
  1208.                 List<DigestEncoding> digestEncoding = securityConfig.getDigestEncodingAccepted();
  1209.                 Map<DigestEncoding, String> newDigestValue = null;
  1210.                 boolean formatoSupportato = true;
  1211.                 if(digestValueInHeaderHTTP.startsWith(HttpConstants.DIGEST_ALGO_SHA_256+"=")) {
  1212.                     newDigestValue = HttpUtilities.getDigestHeaderValues(bout.toByteArray(), HttpConstants.DIGEST_ALGO_SHA_256,
  1213.                             digestEncoding.toArray(new DigestEncoding[1]));
  1214.                 }
  1215.                 else if(digestValueInHeaderHTTP.startsWith(HttpConstants.DIGEST_ALGO_SHA_384+"=")) {
  1216.                     newDigestValue = HttpUtilities.getDigestHeaderValues(bout.toByteArray(), HttpConstants.DIGEST_ALGO_SHA_384,
  1217.                             digestEncoding.toArray(new DigestEncoding[1]));
  1218.                 }
  1219.                 else if(digestValueInHeaderHTTP.startsWith(HttpConstants.DIGEST_ALGO_SHA_512+"=")) {
  1220.                     newDigestValue = HttpUtilities.getDigestHeaderValues(bout.toByteArray(), HttpConstants.DIGEST_ALGO_SHA_512,
  1221.                             digestEncoding.toArray(new DigestEncoding[1]));
  1222.                 }
  1223.                 else {
  1224.                     formatoSupportato = false;
  1225.                     erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_FIRMA_INTESTAZIONE_NON_VALIDA,
  1226.                             getErrorHeaderHttpPrefix(digestHeader)+" con un formato non supportato"));
  1227.                 }
  1228.                
  1229.                 if(formatoSupportato) {
  1230.                     if(newDigestValue==null || newDigestValue.isEmpty()) {
  1231.                         erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_FIRMA_INTESTAZIONE_NON_VALIDA,
  1232.                                 "Calcolo Digest fallito"));
  1233.                     }
  1234.                     else {
  1235.                         boolean valido = false;
  1236.                         for (DigestEncoding de : digestEncoding) {
  1237.                             String check = newDigestValue.get(de);
  1238.                             if(check==null) { // non deve succedere
  1239.                                 erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_FIRMA_INTESTAZIONE_NON_VALIDA,
  1240.                                         "Encoding Digest '"+de+"' fallito"));
  1241.                             }
  1242.                             else if(check.equals(digestValueInHeaderHTTP)){
  1243.                                 valido=true;
  1244.                                 break;
  1245.                             }
  1246.                         }
  1247.                         if(!valido) {
  1248.                             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_FIRMA_NON_VALIDA,
  1249.                                     getErrorHeaderHttpPrefix(digestHeader)+" possiede un valore non corrispondente al messaggio"));
  1250.                         }
  1251. /**                     else {
  1252. //                          System.out.println("VERIFICATO DIGEST HTTP");
  1253. //                      }*/
  1254.                     }
  1255.                 }
  1256.                
  1257.             }
  1258.            
  1259.             String claimSignedHeader = this.modiProperties.getRestSecurityTokenClaimSignedHeaders();
  1260.             if(integrita && !integritaCustom && objectNode.has(claimSignedHeader)) {
  1261.                
  1262.                 boolean findDigestInClaimSignedHeader = false;
  1263.                
  1264.                 Map<String, List<String>> headerHttpAttesi = new HashMap<>();
  1265.                
  1266.                 Object signedHeaders = objectNode.get(claimSignedHeader);
  1267.                 if(signedHeaders==null) {
  1268.                     if(integrita && msg.castAsRest().hasContent()) {
  1269.                         erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_FIRMA_INTESTAZIONE_NON_PRESENTE,
  1270.                                 prefix+getErroreTokenSenzaClaim(claimSignedHeader)));
  1271.                     }
  1272.                 }
  1273.                 else {
  1274.                     readSignedHeaders(signedHeaders, erroriValidazione, prefix, headerDuplicati,
  1275.                             busta, headerHttpAttesi,
  1276.                             claimSignedHeader);
  1277.                 }
  1278.                
  1279.                 if(headerHttpAttesi!=null && !headerHttpAttesi.isEmpty()) {
  1280.                     Iterator<String> headers = headerHttpAttesi.keySet().iterator();
  1281.                     while (headers.hasNext()) {
  1282.                         String hdrName = headers.next();
  1283.                         List<String> hrdAttesiValues = headerHttpAttesi.get(hdrName);
  1284.                         boolean checkHdrAttesiSize = true;
  1285.                         List<String> hdrFound = null;
  1286.                         for (String hdrAttesoValue : hrdAttesiValues) {
  1287.                             boolean valid = false;
  1288.                             String valueInHttpHeader = null;
  1289.                             boolean multiHeader = false;
  1290.                             if(digestHeader.toLowerCase().equalsIgnoreCase(hdrName)) {
  1291.                                 checkHdrAttesiSize = false; // il controllo che non esista piu' di un header digest e' stato fatto in precedenza
  1292.                                 findDigestInClaimSignedHeader = true;
  1293.                                 if(digestValueInHeaderHTTP==null) {
  1294.                                     erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_FIRMA_NON_VALIDA,
  1295.                                             getErrorHeaderHttpPrefix(hdrName)+", dichiarato tra gli header firmati, non trovato"));
  1296.                                     valid = true; // per non far segnalare l'eccezione, che e' stata personalizzata sopra
  1297.                                 }
  1298.                                 else {
  1299.                                     valueInHttpHeader = digestValueInHeaderHTTP;
  1300.                                     valid = hdrAttesoValue.equals(digestValueInHeaderHTTP);
  1301.                                     /**System.out.println("VALID DIGEST: "+valid);*/
  1302.                                 }
  1303.                             }
  1304.                             else {
  1305.                                 if(request && msg.getTransportRequestContext()!=null) {
  1306.                                     hdrFound = msg.getTransportRequestContext().getHeaderValues(hdrName);
  1307.                                 }
  1308.                                 else if(!request && msg.getTransportResponseContext()!=null) {
  1309.                                     hdrFound = msg.getTransportResponseContext().getHeaderValues(hdrName);
  1310.                                 }
  1311.                                
  1312.                                 if(checkHdrAttesiSize && hdrFound!=null) {
  1313.                                     // Fix: per verificare che non esistano altri copie dell'header, oltre a quelli attesi, con valori differenti
  1314.                                     if(hrdAttesiValues.size()!=hdrFound.size()) {
  1315.                                         logError(getErrorHeaderHttpPrefix(hdrName)+" possiede "+(hdrFound!=null ? hdrFound.size() : 0)+" valori '"+(hdrFound!=null ? hdrFound.toString() : "non presente")+
  1316.                                                 "' mentre negli header firmati sono presenti "+hrdAttesiValues.size()+" valori '"+hrdAttesiValues.toString()+"'");
  1317.                                         erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_FIRMA_NON_VALIDA,
  1318.                                                 getErrorHeaderHttpPrefix(hdrName)+" possiede un numero di valori ("+(hdrFound!=null ? hdrFound.size() : 0)
  1319.                                                     +") differente rispetto al numero di valori ("+hrdAttesiValues.size()+") definiti negli header firmati"));
  1320.                                         valid = true; // per non far segnalare l'eccezione, che e' stata personalizzata sopra
  1321.                                         if(valid) {
  1322.                                             break; // e' inutile continuare a controllare i valori degli header
  1323.                                         }
  1324.                                     }
  1325.                                     checkHdrAttesiSize=false; // questo controllo per ogni header basta 1 volta, non serve farlo per ogni valore
  1326.                                 }
  1327.                                
  1328.                                 if(hdrFound==null || hdrFound.isEmpty()) {
  1329.                                     erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_FIRMA_NON_VALIDA,
  1330.                                             getErrorHeaderHttpPrefix(hdrName)+", dichiarato tra gli header firmati, non trovato"));
  1331.                                     valid = true; // per non far segnalare l'eccezione, che e' stata personalizzata sopra
  1332.                                     if(valid) {
  1333.                                         break; // e' inutile continuare a controllare i valori degli header
  1334.                                     }
  1335.                                 }
  1336.                                 else if(hdrFound.size()==1) {
  1337.                                     valueInHttpHeader = hdrFound.get(0);
  1338.                                     valid = hdrAttesoValue.equals(valueInHttpHeader);
  1339.                                 }
  1340.                                 else {
  1341.                                     multiHeader = true;
  1342.                                     valueInHttpHeader = hdrFound.toString();
  1343.                                     valid = hdrFound.contains(hdrAttesoValue);
  1344.                                 }
  1345.                                                                
  1346.                                 /**System.out.println("VALID HDR '"+hdrName+"': "+valid);*/
  1347.                             }
  1348.                             if(!valid) {
  1349.                                 String errorMsg = "possiede un valore '"+valueInHttpHeader+"' differente";
  1350.                                 String errorExc = "possiede un valore differente";
  1351.                                 if(multiHeader) {
  1352.                                     errorMsg = "possiede dei valori '"+valueInHttpHeader+"' differenti";
  1353.                                     errorExc = "possiede dei valori differenti";
  1354.                                 }
  1355.                                 logError(getErrorHeaderHttpPrefix(hdrName)+" "+errorMsg+" rispetto a quello presente negli header firmati '"+hdrAttesoValue+"'");
  1356.                                 erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_FIRMA_NON_VALIDA,
  1357.                                         getErrorHeaderHttpPrefix(hdrName)+" "+errorExc+" rispetto a quello presente negli header firmati"));
  1358.                             }
  1359.                         }
  1360.                     }
  1361.                 }
  1362.                
  1363.                 if(integrita && msg.castAsRest().hasContent() &&
  1364.                     !findDigestInClaimSignedHeader) {
  1365.                     erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_FIRMA_INTESTAZIONE_NON_PRESENTE,
  1366.                             getErrorHeaderHttpPrefix(digestHeader)+" non presente nella lista degli header firmati (token claim '"+claimSignedHeader+"')"));
  1367.                 }
  1368.             }
  1369.             else {
  1370.                 if(integrita && !integritaCustom && msg.castAsRest().hasContent()) {
  1371.                     erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_FIRMA_INTESTAZIONE_NON_PRESENTE,
  1372.                             prefix+getErroreTokenSenzaClaim(claimSignedHeader)));
  1373.                 }
  1374.             }
  1375.            
  1376.            
  1377.         }catch(Exception e) {
  1378.             logError("Errore durante il processamento del payload del token di sicurezza: "+e.getMessage(),e);
  1379.             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_TOKEN_NON_VALIDO,
  1380.                     prefix+e.getMessage()));
  1381.         }
  1382.        
  1383.         return token;
  1384.     }
  1385.    
  1386.     private void readSignedHeaders(Object signedHeaders, List<Eccezione> erroriValidazione, String prefix, boolean headerDuplicati,
  1387.             Busta busta, Map<String, List<String>> headerHttpAttesi,
  1388.             String claimSignedHeader) throws ProtocolException {
  1389.         try {
  1390.             if(signedHeaders instanceof ArrayNode) {
  1391.                 ArrayNode arrayNode = (ArrayNode) signedHeaders;
  1392.                 if(arrayNode.size()<=0) {
  1393.                     throw new ProtocolException("atteso un array con almeno un valore");
  1394.                 }
  1395.                 for (int i = 0; i < arrayNode.size(); i++) {
  1396.                     JsonNode hdrNode = arrayNode.get(i);
  1397.                     String prefixArray = "array["+i+"]";
  1398.                     if(hdrNode==null) {
  1399.                         throw new ProtocolException(prefixArray+" non possiede un valore");
  1400.                     }
  1401.                     if(!(hdrNode instanceof ObjectNode)) {
  1402.                         throw new ProtocolException(prefixArray+" possiede una struttura errata");
  1403.                     }
  1404.                     ObjectNode oNode = (ObjectNode) hdrNode;
  1405.                     if(oNode.size()<=0) {
  1406.                         throw new ProtocolException(prefixArray+" possiede una struttura senza elementi");
  1407.                     }
  1408.                     Iterator<String> fieldNames = oNode.fieldNames();
  1409.                     while (fieldNames.hasNext()) {
  1410.                         String hdrName = fieldNames.next();
  1411.                         addSignedHeader(oNode, hdrName, headerDuplicati,
  1412.                                 busta, headerHttpAttesi, prefixArray);
  1413.                     }
  1414.                 }
  1415.             }
  1416.             else {
  1417.                 throw new ProtocolException("atteso un array");
  1418.             }
  1419.         }catch(Exception e) {
  1420.             logError("Errore durante il processamento del claim che definisce gli header HTTP firmati '"+claimSignedHeader+"': "+e.getMessage(),e);
  1421.             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.SICUREZZA_FIRMA_INTESTAZIONE_NON_VALIDA,
  1422.                     prefix+"Claim '"+claimSignedHeader+"' con un formato non valido; "+ e.getMessage()));
  1423.         }
  1424.     }
  1425.     private void addSignedHeader(ObjectNode oNode, String hdrName, boolean headerDuplicati,
  1426.             Busta busta, Map<String, List<String>> headerHttpAttesi, String prefixArray) throws ProtocolException {
  1427.         try {
  1428.             String hdrValue = toString(oNode.get(hdrName));
  1429.             if(HttpConstants.AUTHORIZATION.equalsIgnoreCase(hdrName) && headerDuplicati) {
  1430.                 ModIUtilities.addHeaderProperty(busta, hdrName, HttpConstants.AUTHORIZATION_PREFIX_BEARER +"...TOKEN...");  
  1431.             }
  1432.             else {
  1433.                 ModIUtilities.addHeaderProperty(busta, hdrName, hdrValue);
  1434.             }
  1435.             TransportUtils.addHeader(headerHttpAttesi, hdrName, hdrValue);
  1436.         }catch(Exception e) {
  1437.             throw new ProtocolException(prefixArray+" possiede header '"+hdrName+"' con un valore non valido: "+e.getMessage(),e);
  1438.         }
  1439.     }
  1440.    
  1441.     private String readClientIdSafe(String payloadToken) {
  1442.         try {
  1443.             JsonNode jsonNode = JSONUtils.getInstance().getAsNode(payloadToken);
  1444.             if(!(jsonNode instanceof ObjectNode)) {
  1445.                 throw new ProtocolException("Payload del token possiede una struttura non valida");
  1446.             }
  1447.             ObjectNode objectNode = (ObjectNode) jsonNode;
  1448.            
  1449.             Object clientIdO = readObjectClientId(objectNode);
  1450.             if(clientIdO!=null) {
  1451.                 return toString(clientIdO);
  1452.             }
  1453.             return null;
  1454.            
  1455.         }catch(Exception e) {
  1456.             // ignore
  1457.             return null;
  1458.         }  
  1459.     }
  1460.     private Object readObjectClientId(ObjectNode objectNode) throws ProtocolException {
  1461.         Object clientId = null;
  1462.         String claimName = this.modiProperties.getRestSecurityTokenClaimsClientIdHeader();
  1463.         if(objectNode.has(Claims.INTROSPECTION_RESPONSE_RFC_7662_CLIENT_ID)) {
  1464.             clientId = objectNode.get(Claims.INTROSPECTION_RESPONSE_RFC_7662_CLIENT_ID);
  1465.         }
  1466.         else if(objectNode.has(Claims.OIDC_ID_TOKEN_AZP)) {
  1467.             clientId = objectNode.get(Claims.OIDC_ID_TOKEN_AZP);
  1468.         }
  1469.         else if(objectNode.has(claimName)) {
  1470.             clientId = objectNode.get(claimName);
  1471.         }
  1472.         return clientId;
  1473.     }  
  1474.    
  1475.     private void readCorniceSicurezzaSchema(ObjectNode objectNode, OpenSPCoop2Message msg, Busta busta,
  1476.             List<Eccezione> erroriValidazione, String prefix,
  1477.             String schemaCorniceSicurezza, ModIAuditConfig auditConfig) throws ProtocolException {
  1478.        
  1479.         if(schemaCorniceSicurezza!=null && StringUtils.isNotEmpty(schemaCorniceSicurezza) && auditConfig!=null) {
  1480.             readCorniceSicurezzaSchema(objectNode, msg, busta,
  1481.                     erroriValidazione, prefix, auditConfig.getClaims());
  1482.         }
  1483.        
  1484.     }
  1485.     private void readCorniceSicurezzaSchema(ObjectNode objectNode, OpenSPCoop2Message msg, Busta busta,
  1486.             List<Eccezione> erroriValidazione, String prefix,
  1487.             List<ModIAuditClaimConfig> claims) throws ProtocolException {
  1488.        
  1489.         if(claims!=null && !claims.isEmpty()) {
  1490.             for (ModIAuditClaimConfig modIAuditClaimConfig : claims) {
  1491.                 String claimName = modIAuditClaimConfig.getNome();
  1492.                 if(objectNode.has(claimName)) {
  1493.                     Object o = objectNode.get(claimName);
  1494.                     if(o!=null) {
  1495.                         processCorniceSicurezzaSchemaClaimValue(msg, modIAuditClaimConfig, busta,
  1496.                                 erroriValidazione, prefix,
  1497.                                 claimName, o);
  1498.                     }
  1499.                 }
  1500.                 else if(modIAuditClaimConfig.isRequired()){
  1501.                     erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.MITTENTE_NON_PRESENTE,
  1502.                             prefix+getErroreTokenSenzaClaim(claimName)));
  1503.                 }
  1504.             }
  1505.         }
  1506.        
  1507.     }
  1508.     private void processCorniceSicurezzaSchemaClaimValue(OpenSPCoop2Message msg, ModIAuditClaimConfig modIAuditClaimConfig, Busta busta,
  1509.             List<Eccezione> erroriValidazione, String prefix,
  1510.             String claimName, Object o) throws ProtocolException {
  1511.        
  1512.         String v = toString(o);
  1513.        
  1514.        
  1515.         // Trace
  1516.         if(modIAuditClaimConfig.isTrace()) {
  1517.             busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_AUDIT_PREFIX+claimName, v);
  1518.         }
  1519.        
  1520.         // Validazione
  1521.         ModIValidazioneAuditClaimValue validator = new ModIValidazioneAuditClaimValue(claimName, v, o, modIAuditClaimConfig);
  1522.         validator.validate(this.validazioneUtils, erroriValidazione, prefix);
  1523.        
  1524.         // Forward
  1525.         String header = modIAuditClaimConfig.getForwardBackend();
  1526.         if(header!=null && StringUtils.isNotEmpty(header)) {
  1527.             msg.forceTransportHeader(header, v);
  1528.         }
  1529.     }  
  1530.    
  1531.     private boolean readCorniceSicurezzaCodiceEnteLegacy(ObjectNode objectNode, Busta busta,
  1532.             List<Eccezione> erroriValidazione, String prefix) throws ProtocolException {
  1533.        
  1534.         boolean readIss = true;
  1535.        
  1536.         String claimNameCodiceEnte = this.modiProperties.getSicurezzaMessaggioCorniceSicurezzaRestCodiceEnte();
  1537.         if(Claims.JSON_WEB_TOKEN_RFC_7519_ISSUER.equals(claimNameCodiceEnte)) {
  1538.             readIss = false;
  1539.         }
  1540.         if(objectNode.has(claimNameCodiceEnte)) {
  1541.             Object codiceEnte = objectNode.get(claimNameCodiceEnte);
  1542.             if(codiceEnte!=null) {
  1543.                 busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_CORNICE_SICUREZZA_ENTE, toString(codiceEnte));
  1544.             }
  1545.         }
  1546.         else {
  1547.             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.MITTENTE_NON_PRESENTE,
  1548.                     prefix+getErroreTokenSenzaClaim(claimNameCodiceEnte)));
  1549.         }
  1550.        
  1551.         return readIss;
  1552.     }
  1553.    
  1554.     private boolean readCorniceSicurezzaUserLegacy(ObjectNode objectNode, Busta busta,
  1555.             List<Eccezione> erroriValidazione, String prefix) throws ProtocolException {
  1556.        
  1557.         boolean readSub = true;
  1558.        
  1559.         String claimNameUser = this.modiProperties.getSicurezzaMessaggioCorniceSicurezzaRestUser();
  1560.         if(Claims.JSON_WEB_TOKEN_RFC_7519_SUBJECT.equals(claimNameUser)) {
  1561.             readSub = false;
  1562.         }
  1563.         if(objectNode.has(claimNameUser)) {
  1564.             Object user = objectNode.get(claimNameUser);
  1565.             if(user!=null) {
  1566.                 busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_CORNICE_SICUREZZA_USER, toString(user));
  1567.             }
  1568.         }
  1569.         else {
  1570.             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.MITTENTE_NON_PRESENTE,
  1571.                     prefix+getErroreTokenSenzaClaim(claimNameUser)));
  1572.         }
  1573.        
  1574.         return readSub;
  1575.        
  1576.     }
  1577.    
  1578.     private void readCorniceSicurezzaIpUserLegacy(ObjectNode objectNode, Busta busta,
  1579.             List<Eccezione> erroriValidazione, String prefix) throws ProtocolException {
  1580.        
  1581.         String claimNameIpUser = this.modiProperties.getSicurezzaMessaggioCorniceSicurezzaRestIpuser();
  1582.         if(objectNode.has(claimNameIpUser)) {
  1583.             Object userIp = objectNode.get(claimNameIpUser);
  1584.             if(userIp!=null) {
  1585.                 busta.addProperty(ModICostanti.MODIPA_BUSTA_EXT_PROFILO_SICUREZZA_MESSAGGIO_CORNICE_SICUREZZA_CORNICE_SICUREZZA_USER_IP, toString(userIp));
  1586.             }
  1587.         }
  1588.         else {
  1589.             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(CodiceErroreCooperazione.MITTENTE_NON_PRESENTE,
  1590.                     prefix+getErroreTokenSenzaClaim(claimNameIpUser)));
  1591.         }
  1592.     }
  1593.    
  1594.    
  1595.     private Date toDate(Object tmp, List<Eccezione> erroriValidazione, CodiceErroreCooperazione codiceErroreCooperazione,String prefix,String claim) throws ProtocolException {
  1596.         try {
  1597.             return toDate(tmp);
  1598.         }catch(Exception e) {
  1599.             erroriValidazione.add(this.validazioneUtils.newEccezioneValidazione(codiceErroreCooperazione,
  1600.                     prefix+getErroreTokenClaimNonValido(claim,e),e));
  1601.             return null;
  1602.         }
  1603.     }
  1604.     private Date toDate(Object tmp) throws ProtocolException {
  1605.        
  1606.         String tmpV = null;
  1607.         if(tmp==null) {
  1608.             throw new ProtocolException("Value undefined");
  1609.         }
  1610.         if(tmp instanceof String) {
  1611.             tmpV = (String) tmp;
  1612.         }
  1613.         else {
  1614.             tmpV = toString(tmp);
  1615.         }
  1616.        
  1617.         Date d = TokenUtils.parseTimeInSecond(tmpV);
  1618.         if(d!=null) {
  1619.             return d;
  1620.         }
  1621.        
  1622.         throw new ProtocolException("Value '"+tmpV+"' not valid");
  1623.     }
  1624.    
  1625.     private String toString(Object tmp) {
  1626.         if(tmp instanceof TextNode) {
  1627.             TextNode text = (TextNode) tmp;
  1628.             return text.asText();
  1629.         }
  1630.         return tmp.toString();
  1631.     }
  1632. }