DriverRegistroServiziDB_soggettiCredenzialiDriver.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.core.registry.driver.db;

  21. import java.sql.Connection;
  22. import java.sql.PreparedStatement;
  23. import java.sql.ResultSet;
  24. import java.sql.SQLException;
  25. import java.util.ArrayList;
  26. import java.util.List;
  27. import java.util.Map;

  28. import org.apache.commons.lang.StringUtils;
  29. import org.openspcoop2.core.constants.CostantiDB;
  30. import org.openspcoop2.core.id.IDSoggetto;
  31. import org.openspcoop2.core.registry.Soggetto;
  32. import org.openspcoop2.core.registry.constants.CredenzialeTipo;
  33. import org.openspcoop2.core.registry.constants.PddTipologia;
  34. import org.openspcoop2.core.registry.driver.DriverRegistroServiziException;
  35. import org.openspcoop2.core.registry.driver.DriverRegistroServiziNotFound;
  36. import org.openspcoop2.utils.certificate.ArchiveLoader;
  37. import org.openspcoop2.utils.certificate.ArchiveType;
  38. import org.openspcoop2.utils.certificate.Certificate;
  39. import org.openspcoop2.utils.certificate.CertificateInfo;
  40. import org.openspcoop2.utils.certificate.CertificateUtils;
  41. import org.openspcoop2.utils.certificate.PrincipalType;
  42. import org.openspcoop2.utils.crypt.CryptConfig;
  43. import org.openspcoop2.utils.crypt.CryptFactory;
  44. import org.openspcoop2.utils.crypt.ICrypt;
  45. import org.openspcoop2.utils.jdbc.IJDBCAdapter;
  46. import org.openspcoop2.utils.jdbc.JDBCAdapterFactory;
  47. import org.openspcoop2.utils.jdbc.JDBCUtilities;
  48. import org.openspcoop2.utils.sql.ISQLQueryObject;
  49. import org.openspcoop2.utils.sql.SQLObjectFactory;

  50. /**
  51.  * DriverRegistroServiziDB_soggettiDriver
  52.  *
  53.  *
  54.  * @author Sandra Giangrandi (sandra@link.it)
  55.  * @author Stefano Corallo (corallo@link.it)
  56.  * @author $Author$
  57.  * @version $Rev$, $Date$
  58.  */
  59. public class DriverRegistroServiziDB_soggettiCredenzialiDriver {

  60.     private DriverRegistroServiziDB driver = null;
  61.     private DriverRegistroServiziDB_soggettiDriver soggettiDriver = null;
  62.    
  63.     protected DriverRegistroServiziDB_soggettiCredenzialiDriver(DriverRegistroServiziDB driver) {
  64.         this.driver = driver;
  65.         this.soggettiDriver = new DriverRegistroServiziDB_soggettiDriver(driver);
  66.     }
  67.    
  68.    
  69.     protected Soggetto soggettoWithCredenzialiBasic(String utente, String password, boolean checkPassword) throws DriverRegistroServiziException {
  70.         String nomeMetodo = "soggettoWithCredenzialiBasic";
  71.         String queryString;

  72.         Connection con = null;
  73.         PreparedStatement stmt=null;
  74.         ResultSet risultato=null;
  75.        
  76.         Soggetto sogg = null;
  77.        
  78.         if (this.driver.atomica) {
  79.             try {
  80.                 con = this.driver.getConnectionFromDatasource(nomeMetodo);
  81.             } catch (Exception e) {
  82.                 throw new DriverRegistroServiziException("[DriverRegistroServiziDB::" + nomeMetodo + "] Exception accedendo al datasource :" + e.getMessage(),e);

  83.             }

  84.         } else
  85.             con = this.driver.globalConnection;

  86.         this.driver.logDebug("operazione this.driver.atomica = " + this.driver.atomica);

  87.         try {

  88.             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(this.driver.tipoDB);
  89.             sqlQueryObject.addFromTable(CostantiDB.SOGGETTI);
  90.             sqlQueryObject.addSelectField("id");
  91.             sqlQueryObject.addWhereCondition("tipoauth = ?");
  92.             sqlQueryObject.addWhereCondition("utente = ?");
  93.             if(checkPassword) {
  94.                 sqlQueryObject.addWhereCondition("password = ?");
  95.             }
  96.             sqlQueryObject.setANDLogicOperator(true);
  97.             queryString = sqlQueryObject.createSQLQuery();
  98.             stmt = con.prepareStatement(queryString);
  99.             int index = 1;
  100.             stmt.setString(index++, CredenzialeTipo.BASIC.getValue());
  101.             stmt.setString(index++, utente);
  102.             if(checkPassword) {
  103.                 stmt.setString(index++, password);
  104.             }
  105.             risultato = stmt.executeQuery();

  106.             if (risultato.next()) {

  107.                 sogg=this.soggettiDriver.getSoggetto(risultato.getLong("id"));

  108.             }

  109.             return sogg;

  110.         } catch (Exception qe) {
  111.             throw new DriverRegistroServiziException("[DriverRegistroServiziDB::" + nomeMetodo + "] Errore : " + qe.getMessage(),qe);
  112.         } finally {

  113.             //Chiudo statement and resultset
  114.             JDBCUtilities.closeResources(risultato, stmt);

  115.             this.driver.closeConnection(con);
  116.         }
  117.     }
  118.    
  119.     protected Soggetto soggettoWithCredenzialiApiKey(String utente, boolean appId) throws DriverRegistroServiziException {
  120.         String nomeMetodo = "soggettoWithCredenzialiApiKey";
  121.         String queryString;

  122.         Connection con = null;
  123.         PreparedStatement stmt=null;
  124.         ResultSet risultato=null;
  125.        
  126.         Soggetto sogg = null;
  127.        
  128.         if (this.driver.atomica) {
  129.             try {
  130.                 con = this.driver.getConnectionFromDatasource(nomeMetodo);
  131.             } catch (Exception e) {
  132.                 throw new DriverRegistroServiziException("[DriverRegistroServiziDB::" + nomeMetodo + "] Exception accedendo al datasource :" + e.getMessage(),e);

  133.             }

  134.         } else
  135.             con = this.driver.globalConnection;

  136.         this.driver.logDebug("operazione this.driver.atomica = " + this.driver.atomica);

  137.         try {

  138.             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(this.driver.tipoDB);
  139.             sqlQueryObject.addFromTable(CostantiDB.SOGGETTI);
  140.             sqlQueryObject.addSelectField("id");
  141.             sqlQueryObject.addWhereCondition("tipoauth = ?");
  142.             sqlQueryObject.addWhereCondition("utente = ?");
  143.             sqlQueryObject.addWhereCondition("issuer = ?");
  144.             sqlQueryObject.setANDLogicOperator(true);
  145.             queryString = sqlQueryObject.createSQLQuery();
  146.             stmt = con.prepareStatement(queryString);
  147.             int index = 1;
  148.             stmt.setString(index++, CredenzialeTipo.APIKEY.getValue());
  149.             stmt.setString(index++, utente);
  150.             stmt.setString(index++, CostantiDB.getIssuerApiKey(appId));
  151.             risultato = stmt.executeQuery();

  152.             if (risultato.next()) {

  153.                 sogg=this.soggettiDriver.getSoggetto(risultato.getLong("id"));

  154.             }

  155.             return sogg;

  156.         } catch (Exception qe) {
  157.             throw new DriverRegistroServiziException("[DriverRegistroServiziDB::" + nomeMetodo + "] Errore : " + qe.getMessage(),qe);
  158.         } finally {

  159.             //Chiudo statement and resultset
  160.             JDBCUtilities.closeResources(risultato, stmt);

  161.             this.driver.closeConnection(con);
  162.         }
  163.     }
  164.    
  165.    
  166.     protected Soggetto getSoggettoByCredenzialiBasic(
  167.             String user,String password, CryptConfig config) throws DriverRegistroServiziException, DriverRegistroServiziNotFound{
  168.         return this.getEngineSoggettoAutenticato(CredenzialeTipo.BASIC, user, password,
  169.                 null, null, null, false,
  170.                 null,
  171.                 config,
  172.                 false,
  173.                 false);
  174.     }
  175.    
  176.     protected Soggetto getSoggettoByCredenzialiApiKey(
  177.             String user,String password, boolean appId, CryptConfig config) throws DriverRegistroServiziException, DriverRegistroServiziNotFound{
  178.         return this.getEngineSoggettoAutenticato(CredenzialeTipo.APIKEY, user, password,
  179.                 null, null, null, false,
  180.                 null,
  181.                 config,
  182.                 appId,
  183.                 false);
  184.     }
  185.    
  186.     protected Soggetto getSoggettoByCredenzialiSsl(
  187.             String subject, String issuer) throws DriverRegistroServiziException, DriverRegistroServiziNotFound{
  188.         try {
  189.             return this.getEngineSoggettoAutenticato(CredenzialeTipo.SSL, null, null,
  190.                     subject, issuer, null, false,
  191.                     null,
  192.                     null,
  193.                     false,
  194.                     false);
  195.         }catch(DriverRegistroServiziNotFound notFound) {
  196.             // provo a cercare in credenziali ulteriori
  197.             return this.getEngineSoggettoAutenticato(CredenzialeTipo.SSL, null, null,
  198.                     subject, issuer, null, false,
  199.                     null,
  200.                     null,
  201.                     false,
  202.                     true);
  203.         }
  204.     }
  205.    
  206.     protected Soggetto getSoggettoByCredenzialiSsl(CertificateInfo certificate, boolean strictVerifier) throws DriverRegistroServiziException,DriverRegistroServiziNotFound{
  207.         try {
  208.             return this.getEngineSoggettoAutenticato(CredenzialeTipo.SSL, null, null,
  209.                     null, null, certificate, strictVerifier,
  210.                     null,
  211.                     null,
  212.                     false,
  213.                     false);
  214.         }catch(DriverRegistroServiziNotFound notFound) {
  215.             // provo a cercare in credenziali ulteriori
  216.             return this.getEngineSoggettoAutenticato(CredenzialeTipo.SSL, null, null,
  217.                     null, null, certificate, strictVerifier,
  218.                     null,
  219.                     null,
  220.                     false,
  221.                     true);
  222.         }
  223.     }
  224.    
  225.     protected Soggetto getSoggettoByCredenzialiPrincipal(
  226.             String principal) throws DriverRegistroServiziException, DriverRegistroServiziNotFound{
  227.         return this.getEngineSoggettoAutenticato(CredenzialeTipo.PRINCIPAL, null, null,
  228.                 null, null, null, false,
  229.                 principal,
  230.                 null,
  231.                 false,
  232.                 false);
  233.     }
  234.    
  235.     private Soggetto getEngineSoggettoAutenticato(
  236.             CredenzialeTipo tipoCredenziale, String user,String password,
  237.             String aSubject, String aIssuer, CertificateInfo aCertificate, boolean aStrictVerifier,
  238.             String principal,
  239.             CryptConfig config,
  240.             boolean appId,
  241.             boolean searchInCredenzialiUlteriori) throws DriverRegistroServiziException, DriverRegistroServiziNotFound{
  242.        
  243.         // conrollo consistenza
  244.         if (tipoCredenziale == null)
  245.             throw new DriverRegistroServiziException("[getSoggettoAutenticato] Parametro tipoCredenziale is null");

  246.         switch (tipoCredenziale) {
  247.         case BASIC:
  248.             if (user == null || "".equalsIgnoreCase(user))
  249.                 throw new DriverRegistroServiziException("[getSoggettoAutenticato] Parametro user is null (required for basic auth)");
  250.             if (password == null || "".equalsIgnoreCase(password))
  251.                 throw new DriverRegistroServiziException("[getSoggettoAutenticato] Parametro password is null (required for basic auth)");
  252.             break;
  253.         case APIKEY:
  254.             if (user == null || "".equalsIgnoreCase(user))
  255.                 throw new DriverRegistroServiziException("[getSoggettoAutenticato] Parametro user is null (required for apikey auth)");
  256.             if (password == null || "".equalsIgnoreCase(password))
  257.                 throw new DriverRegistroServiziException("[getSoggettoAutenticato] Parametro password is null (required for apikey auth)");
  258.             break;
  259.         case SSL:
  260.             if ( (aSubject == null || "".equalsIgnoreCase(aSubject)) && (aCertificate==null))
  261.                 throw new DriverRegistroServiziException("[getSoggettoAutenticato] Parametro subject/certificate is null (required for ssl auth)");
  262.             break;
  263.         case PRINCIPAL:
  264.             if (principal == null || "".equalsIgnoreCase(principal))
  265.                 throw new DriverRegistroServiziException("[getSoggettoAutenticato] Parametro principal is null (required for principal auth)");
  266.             break;
  267.         }

  268.         Connection con = null;
  269.         PreparedStatement stm = null;
  270.         ResultSet rs = null;

  271.         if (this.driver.atomica) {
  272.             try {
  273.                 con = this.driver.getConnectionFromDatasource("getSoggettoAutenticato");

  274.             } catch (Exception e) {
  275.                 throw new DriverRegistroServiziException("DriverRegistroServiziDB::getSoggettoAutenticato] Exception accedendo al datasource :" + e.getMessage(),e);

  276.             }

  277.         } else
  278.             con = this.driver.globalConnection;

  279.         this.driver.logDebug("operazione atomica = " + this.driver.atomica);

  280.         IDSoggetto idSoggetto = null;
  281.         try {
  282.             String tabella = CostantiDB.SOGGETTI;
  283.             if(searchInCredenzialiUlteriori) {
  284.                 tabella = CostantiDB.SOGGETTI_CREDENZIALI;
  285.             }
  286.            
  287.             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(this.driver.tipoDB);
  288.             sqlQueryObject.addFromTable(CostantiDB.SOGGETTI);
  289.             if(searchInCredenzialiUlteriori) {
  290.                 sqlQueryObject.addFromTable(CostantiDB.SOGGETTI_CREDENZIALI);
  291.             }
  292.             sqlQueryObject.addSelectField("tipo_soggetto");
  293.             sqlQueryObject.addSelectField("nome_soggetto");
  294.             if(searchInCredenzialiUlteriori) {
  295.                 sqlQueryObject.addWhereCondition(CostantiDB.SOGGETTI_CREDENZIALI+".id_soggetto="+CostantiDB.SOGGETTI+".id");
  296.             }
  297.             sqlQueryObject.addWhereCondition("tipoauth = ?");
  298.             switch (tipoCredenziale) {
  299.             case BASIC:
  300.                 sqlQueryObject.addSelectField("password");
  301.                
  302.                 sqlQueryObject.addWhereCondition("utente = ?");
  303.                 //sqlQueryObject.addWhereCondition("password = ?");
  304.                 break;
  305.             case APIKEY:
  306.                 sqlQueryObject.addSelectField("password");
  307.                
  308.                 sqlQueryObject.addWhereCondition("utente = ?");
  309.                 //sqlQueryObject.addWhereCondition("password = ?");
  310.                 sqlQueryObject.addWhereCondition("issuer = ?");
  311.                 break;
  312.             case SSL:
  313.                 if(aSubject!=null && !"".equals(aSubject)) {
  314.                    
  315.                     sqlQueryObject.addSelectAliasField(tabella, "subject", "soggettoSubject");
  316.                     sqlQueryObject.addSelectAliasField(tabella, "issuer", "soggettoIssuer");                
  317.                    
  318.                     // Autenticazione SSL deve essere LIKE
  319.                     Map<String, List<String>> hashSubject = CertificateUtils.getPrincipalIntoMap(aSubject, PrincipalType.SUBJECT);
  320.                     Map<String, List<String>> hashIssuer = null;
  321.                     if(StringUtils.isNotEmpty(aIssuer)) {
  322.                         hashIssuer = CertificateUtils.getPrincipalIntoMap(aIssuer, PrincipalType.ISSUER);
  323.                     }
  324.                    
  325.                     for (String key : hashSubject.keySet()) {
  326.                         List<String> listValues = hashSubject.get(key);
  327.                         for (String value : listValues) {
  328.                             sqlQueryObject.addWhereLikeCondition(tabella+".subject", "/"+CertificateUtils.formatKeyPrincipal(key)+"="+CertificateUtils.formatValuePrincipal(value)+"/", true, true, false);
  329.                         }
  330.                     }
  331.                    
  332.                     if(hashIssuer!=null) {
  333.                         for (String key : hashIssuer.keySet()) {
  334.                             List<String> listValues = hashIssuer.get(key);
  335.                             for (String value : listValues) {
  336.                                 sqlQueryObject.addWhereLikeCondition(tabella+".issuer", "/"+CertificateUtils.formatKeyPrincipal(key)+"="+CertificateUtils.formatValuePrincipal(value)+"/", true, true, false);
  337.                             }
  338.                         }
  339.                     }
  340.                     else {
  341.                         sqlQueryObject.addWhereIsNullCondition(tabella+".issuer");
  342.                     }
  343.                 }
  344.                 else {
  345.                
  346.                     sqlQueryObject.addSelectAliasField(tabella, "cn_subject", "soggettoCNSubject");
  347.                     sqlQueryObject.addSelectAliasField(tabella, "cn_issuer", "soggettoCNIssuer");
  348.                     sqlQueryObject.addSelectAliasField(tabella, "cert_strict_verification", "soggettoCertStrictVerification");
  349.                     sqlQueryObject.addSelectAliasField(tabella, "certificate", "soggettoCertificate");
  350.                    
  351.                     // ricerca per certificato
  352.                     sqlQueryObject.addWhereCondition(tabella+".cn_subject = ?");
  353.                     sqlQueryObject.addWhereCondition(tabella+".cn_issuer = ?");
  354.                     sqlQueryObject.addWhereCondition(tabella+".cert_strict_verification = ?");
  355.                    
  356.                 }
  357.                 break;
  358.             case PRINCIPAL:
  359.                 sqlQueryObject.addWhereCondition("utente = ?");
  360.                 break;
  361.             }
  362.             sqlQueryObject.setANDLogicOperator(true);
  363.             String sqlQuery = sqlQueryObject.createSQLQuery();

  364.             stm = con.prepareStatement(sqlQuery);
  365.             int index = 1;
  366.             stm.setString(index++, tipoCredenziale.toString());
  367.             switch (tipoCredenziale) {
  368.             case BASIC:
  369.                 stm.setString(index++, user);
  370.                 //stm.setString(index++, password);
  371.                 this.driver.logDebug("eseguo query : " + DriverRegistroServiziDB_LIB.formatSQLString(sqlQuery, tipoCredenziale.toString(), user));
  372.                 break;
  373.             case APIKEY:
  374.                 stm.setString(index++, user);
  375.                 //stm.setString(index++, password);
  376.                 stm.setString(index++, CostantiDB.getIssuerApiKey(appId));
  377.                 this.driver.logDebug("eseguo query : " + DriverRegistroServiziDB_LIB.formatSQLString(sqlQuery, tipoCredenziale.toString(), user, CostantiDB.getIssuerApiKey(appId)));
  378.                 break;
  379.             case SSL:
  380.                 if(aSubject!=null && !"".equals(aSubject)) {
  381.                     this.driver.logDebug("eseguo query : " + DriverRegistroServiziDB_LIB.formatSQLString(sqlQuery, tipoCredenziale.toString()));
  382.                 }
  383.                 else {
  384.                     String cnSubject = aCertificate.getSubject().getCN();
  385.                     String cnIssuer = aCertificate.getIssuer().getCN();
  386.                    
  387.                     stm.setString(index++, cnSubject);
  388.                     stm.setString(index++, cnIssuer);
  389.                     if(aStrictVerifier) {
  390.                         stm.setInt(index++, CostantiDB.TRUE);
  391.                     }
  392.                     else {
  393.                         stm.setInt(index++, CostantiDB.FALSE);
  394.                     }
  395.                     this.driver.logDebug("eseguo query : " + DriverRegistroServiziDB_LIB.formatSQLString(sqlQuery, tipoCredenziale.toString(), cnSubject, cnIssuer,
  396.                             (aStrictVerifier? CostantiDB.TRUE : CostantiDB.FALSE)));
  397.                 }
  398.                 break;
  399.             case PRINCIPAL:
  400.                 stm.setString(index++, principal);
  401.                 this.driver.logDebug("eseguo query : " + DriverRegistroServiziDB_LIB.formatSQLString(sqlQuery, tipoCredenziale.toString(), principal));
  402.                 break;
  403.             }

  404.             rs = stm.executeQuery();

  405.             if(CredenzialeTipo.BASIC.equals(tipoCredenziale) || CredenzialeTipo.APIKEY.equals(tipoCredenziale)) {
  406.                
  407.                 boolean testInChiaro = false;
  408.                 ICrypt crypt = null;
  409.                 if(CredenzialeTipo.BASIC.equals(tipoCredenziale)) {
  410.                     if(config==null || config.isBackwardCompatibility()) {
  411.                         testInChiaro = true;
  412.                     }
  413.                     if(config!=null) {
  414.                         crypt = CryptFactory.getCrypt(this.driver.log, config);
  415.                     }
  416.                 }
  417.                 else {
  418.                     if(config!=null) {
  419.                         crypt = CryptFactory.getCrypt(this.driver.log, config);
  420.                     }
  421.                     else {
  422.                         testInChiaro = true;
  423.                     }
  424.                 }
  425.                
  426.                 while(rs.next()){
  427.                     String passwordDB =  rs.getString("password");
  428.                    
  429.                     boolean found = false;
  430.                     if(testInChiaro) {
  431.                         found = password.equals(passwordDB);
  432.                     }
  433.                     if(!found && crypt!=null) {
  434.                         found = crypt.check(password, passwordDB);
  435.                     }
  436.                    
  437.                     if( found ) {
  438.                         idSoggetto = new IDSoggetto();
  439.                         idSoggetto.setTipo(rs.getString("tipo_soggetto"));
  440.                         idSoggetto.setNome(rs.getString("nome_soggetto"));
  441.                         break;
  442.                     }
  443.                 }
  444.                
  445.             }
  446.             else if(CredenzialeTipo.SSL.equals(tipoCredenziale)) {
  447.                
  448.                 IJDBCAdapter jdbcAdapter = JDBCAdapterFactory.createJDBCAdapter(this.driver.tipoDB);
  449.                
  450.                 while(rs.next()){
  451.                    
  452.                     if(aSubject!=null && !"".equals(aSubject)) {
  453.                    
  454.                         // Possono esistere piu' soggetti che hanno una porzione di subject uguale, devo quindi verificare che sia proprio quello che cerco
  455.                                            
  456.                         String subjectPotenziale =  rs.getString("soggettoSubject");
  457.                         boolean subjectValid = CertificateUtils.sslVerify(subjectPotenziale, aSubject, PrincipalType.SUBJECT, this.driver.log);
  458.                        
  459.                         boolean issuerValid = true;
  460.                         if(StringUtils.isNotEmpty(aIssuer)) {
  461.                             String issuerPotenziale =  rs.getString("soggettoIssuer");
  462.                             if(StringUtils.isNotEmpty(issuerPotenziale)) {
  463.                                 issuerValid = CertificateUtils.sslVerify(issuerPotenziale, aIssuer, PrincipalType.ISSUER, this.driver.log);
  464.                             }
  465.                             else {
  466.                                 issuerValid = false;
  467.                             }
  468.                         }
  469.                        
  470.                        
  471.                         if( subjectValid && issuerValid ) {
  472.                             idSoggetto = new IDSoggetto();
  473.                             idSoggetto.setTipo(rs.getString("tipo_soggetto"));
  474.                             idSoggetto.setNome(rs.getString("nome_soggetto"));
  475.                             break;
  476.                         }
  477.                     }
  478.                     else {
  479.                        
  480.                         // ricerca per certificato
  481.                         // Possono esistere piu' soggetti che hanno un CN con subject e issuer diverso.
  482.                        
  483.                         byte[] certificatoBytes = jdbcAdapter.getBinaryData(rs, "soggettoCertificate");
  484.                         Certificate certificato = ArchiveLoader.load(ArchiveType.CER, certificatoBytes, 0, null);
  485.                         //int tmpStrict = rs.getInt("cert_strict_verification");
  486.                         //boolean strict = tmpStrict == CostantiDB.TRUE;
  487.                        
  488.                         if(aCertificate.equals(certificato.getCertificate(),aStrictVerifier)) {
  489.                             idSoggetto = new IDSoggetto();
  490.                             idSoggetto.setTipo(rs.getString("tipo_soggetto"));
  491.                             idSoggetto.setNome(rs.getString("nome_soggetto"));
  492.                             break;
  493.                         }
  494.                     }
  495.                 }
  496.                
  497.             }
  498.             else {
  499.                 if (rs.next()) {
  500.                     idSoggetto = new IDSoggetto();
  501.                     idSoggetto.setTipo(rs.getString("tipo_soggetto"));
  502.                     idSoggetto.setNome(rs.getString("nome_soggetto"));
  503.                 }
  504.             }

  505.         }catch (SQLException se) {

  506.             throw new DriverRegistroServiziException("[DriverRegistroServiziDB::getSoggettoAutenticato] SqlException: " + se.getMessage(),se);
  507.         }catch (Exception se) {

  508.             throw new DriverRegistroServiziException("[DriverRegistroServiziDB::getSoggettoAutenticato] Exception: " + se.getMessage(),se);
  509.         } finally {
  510.             JDBCUtilities.closeResources(rs, stm);
  511.             this.driver.closeConnection(con);
  512.         }
  513.        
  514.         if(idSoggetto!=null){
  515.             return this.soggettiDriver.getSoggetto(idSoggetto);
  516.         }
  517.         else{
  518.             throw new DriverRegistroServiziNotFound("Nessun soggetto trovato che possiede le credenziali '"+tipoCredenziale.toString()+"' fornite");
  519.         }
  520.     }
  521.    
  522.     protected List<Soggetto> soggettoWithCredenzialiSslList(CertificateInfo certificate, boolean strictVerifier) throws DriverRegistroServiziException {
  523.         String nomeMetodo = "soggettoWithCredenzialiSslList";
  524.         String queryString;

  525.         Connection con = null;
  526.         PreparedStatement stmt=null;
  527.         ResultSet risultato=null;
  528.         ArrayList<Soggetto> lista = new ArrayList<>();

  529.         if (this.driver.atomica) {
  530.             try {
  531.                 con = this.driver.getConnectionFromDatasource(nomeMetodo);
  532.             } catch (Exception e) {
  533.                 throw new DriverRegistroServiziException("[DriverRegistroServiziDB::" + nomeMetodo + "] Exception accedendo al datasource :" + e.getMessage(),e);

  534.             }

  535.         } else
  536.             con = this.driver.globalConnection;

  537.         this.driver.logDebug("operazione this.driver.atomica = " + this.driver.atomica);

  538.         try {

  539.             for (int i = 0; i < 2; i++) {
  540.                
  541.                 String tabella = null;
  542.                 if(i==0) {
  543.                     tabella = CostantiDB.SOGGETTI;
  544.                 }
  545.                 else {
  546.                     tabella = CostantiDB.SOGGETTI_CREDENZIALI;
  547.                 }
  548.            
  549.                 ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(this.driver.tipoDB);
  550.                 sqlQueryObject.addFromTable(CostantiDB.SOGGETTI);
  551.                 if(i>0) {
  552.                     sqlQueryObject.addFromTable(CostantiDB.SOGGETTI_CREDENZIALI);
  553.                 }
  554.                 sqlQueryObject.addSelectAliasField(CostantiDB.SOGGETTI, "id", "soggettoIdentificativo");
  555.                 sqlQueryObject.addSelectAliasField(tabella, "cn_subject", "soggettoCNSubject");
  556.                 sqlQueryObject.addSelectAliasField(tabella, "cn_issuer", "soggettoCNIssuer");
  557.                 sqlQueryObject.addSelectAliasField(tabella, "cert_strict_verification", "soggettoCertStrictVerification");
  558.                 sqlQueryObject.addSelectAliasField(tabella, "certificate", "soggettoCertificate");
  559.                
  560.                 if(i>0) {
  561.                     sqlQueryObject.addWhereCondition(CostantiDB.SOGGETTI_CREDENZIALI+".id_soggetto="+CostantiDB.SOGGETTI+".id");
  562.                 }
  563.                 sqlQueryObject.addWhereCondition(CostantiDB.SOGGETTI+".tipoauth = ?");
  564.                
  565.                 sqlQueryObject.addWhereCondition(tabella+".cn_subject = ?");
  566.                 sqlQueryObject.addWhereCondition(tabella+".cn_issuer = ?");
  567.                 //sqlQueryObject.addWhereCondition(tabella+".cert_strict_verification = ?");
  568.                
  569.                 sqlQueryObject.setANDLogicOperator(true);
  570.                 queryString = sqlQueryObject.createSQLQuery();
  571.                 String cnSubject = certificate.getSubject().getCN();
  572.                 String cnIssuer = certificate.getIssuer().getCN();
  573.                 stmt = con.prepareStatement(queryString);
  574.                 int indexStmt = 1;
  575.                 stmt.setString(indexStmt++, CredenzialeTipo.SSL.getValue());
  576.                 stmt.setString(indexStmt++, cnSubject);
  577.                 stmt.setString(indexStmt++, cnIssuer);
  578.                 // Il controllo serve ad evitare di caricare piu' applicativi con stesso certificato medesimo (indipendentemente dallo strict)
  579.                 // Se quindi sto creando un entita con strict abilitato, verifichero sotto tra i vari certificati la corrispondenza esatta, altrimenti una corrispondenza non esatta
  580.     //          if(strictVerifier) {
  581.     //              stmt.setInt(indexStmt++, CostantiDB.TRUE);
  582.     //          }
  583.     //          else {
  584.     //              stmt.setInt(indexStmt++, CostantiDB.FALSE);
  585.     //          }
  586.                 risultato = stmt.executeQuery();
  587.    
  588.                 Soggetto soggetto;
  589.                 IJDBCAdapter jdbcAdapter = JDBCAdapterFactory.createJDBCAdapter(this.driver.tipoDB);
  590.                 while (risultato.next()) {
  591.    
  592.                     // Possono esistere piu' servizi applicativi che hanno un CN con subject e issuer diverso.
  593.                    
  594.                     byte[] certificatoBytes = jdbcAdapter.getBinaryData(risultato, "soggettoCertificate");
  595.                     Certificate certificato = ArchiveLoader.load(ArchiveType.CER, certificatoBytes, 0, null);
  596.                     //int tmpStrict = rs.getInt("cert_strict_verification");
  597.                     //boolean strict = tmpStrict == CostantiDB.TRUE;
  598.                    
  599.                     if(!certificate.equals(certificato.getCertificate(),strictVerifier)) {
  600.                         continue;
  601.                     }
  602.                    
  603.                     soggetto=this.soggettiDriver.getSoggetto(risultato.getLong("soggettoIdentificativo"));
  604.                     lista.add(soggetto);
  605.                 }
  606.                 risultato.close(); risultato=null;
  607.                 stmt.close(); stmt=null;
  608.                
  609.             }

  610.             return lista;

  611.         } catch (Exception qe) {
  612.             throw new DriverRegistroServiziException("[DriverRegistroServiziDB::" + nomeMetodo + "] Errore : " + qe.getMessage(),qe);
  613.         } finally {

  614.             //Chiudo statement and resultset
  615.             JDBCUtilities.closeResources(risultato, stmt);
  616.            
  617.             this.driver.closeConnection(con);
  618.         }
  619.     }
  620.    
  621.     protected List<IDSoggettoDB> getSoggettiFromTipoAutenticazione(List<String> tipiSoggetto, String superuser, CredenzialeTipo credenziale, Boolean appId, PddTipologia pddTipologia) throws DriverRegistroServiziException {
  622.         Connection con = null;
  623.         PreparedStatement stmt = null;
  624.         ResultSet risultato = null;
  625.         String queryString;
  626.         int offset = 0;
  627.         int limit = ISQLQueryObject.LIMIT_DEFAULT_VALUE;
  628.        
  629.         this.driver.logDebug("getSoggettiFromTipoAutenticazione...");
  630.        
  631.         List<IDSoggettoDB> soggetti= null;
  632.        
  633.         try {
  634.             this.driver.logDebug("operazione atomica = " + this.driver.atomica);
  635.             // prendo la connessione dal pool
  636.             if (this.driver.atomica)
  637.                 con = this.driver.getConnectionFromDatasource("getSoggettiFromTipoAutenticazione");
  638.             else
  639.                 con = this.driver.globalConnection;
  640.        
  641.             ISQLQueryObject sqlQueryObjectPdd = null;
  642.             if(pddTipologia!=null && PddTipologia.ESTERNO.equals(pddTipologia)) {
  643.                 ISQLQueryObject sqlQueryObjectExistsPdd = SQLObjectFactory.createSQLQueryObject(this.driver.tipoDB);
  644.                 sqlQueryObjectExistsPdd.addSelectField(CostantiDB.PDD+".nome");
  645.                 sqlQueryObjectExistsPdd.addFromTable(CostantiDB.PDD);
  646.                 sqlQueryObjectExistsPdd.setANDLogicOperator(true);
  647.                 sqlQueryObjectExistsPdd.addWhereCondition(CostantiDB.PDD+".nome="+CostantiDB.SOGGETTI+".server");
  648.                 sqlQueryObjectExistsPdd.addWhereCondition(CostantiDB.PDD+".tipo=?");
  649.                
  650.                 sqlQueryObjectPdd = SQLObjectFactory.createSQLQueryObject(this.driver.tipoDB);
  651.                 sqlQueryObjectPdd.setANDLogicOperator(false);
  652.                 sqlQueryObjectPdd.addWhereIsNullCondition(CostantiDB.SOGGETTI+".server");
  653.                 sqlQueryObjectPdd.addWhereExistsCondition(false, sqlQueryObjectExistsPdd);
  654.             }
  655.            
  656.             ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(this.driver.tipoDB);
  657.             sqlQueryObject.addFromTable(CostantiDB.SOGGETTI);
  658.             sqlQueryObject.setSelectDistinct(true);
  659.             sqlQueryObject.addSelectAliasField(CostantiDB.SOGGETTI,"id", "idTableSoggetto");
  660.             sqlQueryObject.addSelectField("tipo_soggetto");
  661.             sqlQueryObject.addSelectField("nome_soggetto");
  662.             sqlQueryObject.setANDLogicOperator(true);
  663.             if(tipiSoggetto!=null && tipiSoggetto.size()>0) {
  664.                 sqlQueryObject.addWhereINCondition("tipo_soggetto", true, tipiSoggetto.toArray(new String[1]));
  665.             }
  666.             if(this.driver.useSuperUser && superuser!=null && !superuser.equals(""))
  667.                 sqlQueryObject.addWhereCondition(CostantiDB.SOGGETTI+".superuser = ?");
  668.             if(credenziale != null) {
  669.                 sqlQueryObject.addWhereCondition("tipoauth = ?");
  670.                 if(CredenzialeTipo.APIKEY.equals(credenziale) && appId!=null) {
  671.                     sqlQueryObject.addWhereCondition("issuer = ?");
  672.                 }
  673.             }
  674.             if(pddTipologia!=null) {
  675.                 if(PddTipologia.ESTERNO.equals(pddTipologia)) {
  676.                     sqlQueryObject.addWhereCondition(sqlQueryObjectPdd.createSQLConditions());                                  
  677.                 }
  678.                 else {
  679.                     sqlQueryObject.addFromTable(CostantiDB.PDD);
  680.                     sqlQueryObject.addWhereCondition(true,CostantiDB.PDD+".nome="+CostantiDB.SOGGETTI+".server",CostantiDB.PDD+".tipo=?");
  681.                 }
  682.             }
  683.            
  684.             sqlQueryObject.addOrderBy("nome_soggetto");
  685.             sqlQueryObject.addOrderBy("tipo_soggetto");
  686.             sqlQueryObject.setSortType(true);
  687.             sqlQueryObject.setLimit(limit);
  688.             sqlQueryObject.setOffset(offset);
  689.             queryString = sqlQueryObject.createSQLQuery();
  690.            
  691.             stmt = con.prepareStatement(queryString);
  692.             int index = 1;
  693.             if(this.driver.useSuperUser && superuser!=null && !superuser.equals(""))
  694.                 stmt.setString(index++, superuser);
  695.             if(credenziale != null) {
  696.                 stmt.setString(index++, credenziale.toString());
  697.                 if(CredenzialeTipo.APIKEY.equals(credenziale) && appId!=null) {
  698.                     stmt.setString(index++, CostantiDB.getIssuerApiKey(appId));
  699.                 }
  700.             }
  701.             if(pddTipologia!=null) {
  702.                 stmt.setString(index++, pddTipologia.toString());
  703.             }
  704.            
  705.             risultato = stmt.executeQuery();
  706.            
  707.             soggetti = new ArrayList<IDSoggettoDB>();
  708.             while (risultato.next()) {

  709.                 IDSoggettoDB sog = new IDSoggettoDB();
  710.                 sog.setId(risultato.getLong("idTableSoggetto"));
  711.                 sog.setNome(risultato.getString("nome_soggetto"));
  712.                 sog.setTipo(risultato.getString("tipo_soggetto"));
  713.                 soggetti.add(sog);
  714.             }

  715.             return soggetti;
  716.         } catch (Exception qe) {
  717.             throw new DriverRegistroServiziException("[DriverRegistroServiziDB::getSoggettiFromTipoAutenticazione] Exception: " + qe.getMessage(),qe);
  718.         } finally {
  719.             JDBCUtilities.closeResources(risultato, stmt);
  720.             this.driver.closeConnection(con);
  721.         }
  722.     }
  723.    
  724. }