VaultTools.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.pdd.config.vault.cli;

  21. import java.io.File;
  22. import java.io.InputStream;
  23. import java.util.HashMap;
  24. import java.util.Map;
  25. import java.util.Properties;

  26. import org.apache.commons.lang.StringUtils;
  27. import org.openspcoop2.core.commons.CoreException;
  28. import org.openspcoop2.core.config.driver.ExtendedInfoManager;
  29. import org.openspcoop2.pdd.core.byok.BYOKMapProperties;
  30. import org.openspcoop2.pdd.core.dynamic.DynamicInfo;
  31. import org.openspcoop2.pdd.core.dynamic.DynamicUtils;
  32. import org.openspcoop2.pdd.services.ServicesUtils;
  33. import org.openspcoop2.protocol.engine.ProtocolFactoryManager;
  34. import org.openspcoop2.protocol.sdk.ConfigurazionePdD;
  35. import org.openspcoop2.utils.LoggerWrapperFactory;
  36. import org.openspcoop2.utils.certificate.byok.BYOKManager;
  37. import org.openspcoop2.utils.certificate.hsm.HSMManager;
  38. import org.openspcoop2.utils.certificate.hsm.HSMUtils;
  39. import org.openspcoop2.utils.properties.MapProperties;
  40. import org.openspcoop2.utils.security.ProviderUtils;
  41. import org.slf4j.Logger;

  42. /**
  43.  *  VaultTools
  44.  *
  45.  * @author Poli Andrea (apoli@link.it)
  46.  * @author $Author$
  47.  * @version $Rev$, $Date$
  48.  */
  49. public class VaultTools {

  50.     private static Logger logCore = LoggerWrapperFactory.getLogger(VaultTools.class);
  51.     public static Logger getLogCore() {
  52.         return logCore;
  53.     }
  54.     public static void logCoreDebug(String msg) {
  55.         logCore.debug(msg);
  56.     }
  57.     public static void logCoreInfo(String msg) {
  58.         logCore.info(msg);
  59.     }
  60.     public static void logCoreError(String msg, Exception e) {
  61.         logCore.error(msg,e);
  62.     }
  63.     private static Logger logOutput = LoggerWrapperFactory.getLogger(VaultTools.class);
  64.     public static void logOutput(String msg) {
  65.         logOutput.info(msg);
  66.     }
  67.    
  68.     public static void main(String[] args) throws CoreException {
  69.        
  70.         VaultOperationType opType = null;
  71.         VaultUpdateConfig updateConfig = null;
  72.         VaultEncDecConfig encDecConfig = null;
  73.         String[] argsConfig = null;
  74.         String utilizzoErrato = null;
  75.         try {
  76.        
  77.             // Logger
  78.             initLogger();
  79.             logCore=LoggerWrapperFactory.getLogger("govway_vault.core");    
  80.             logOutput=LoggerWrapperFactory.getLogger("govway_vault.output");    
  81.            
  82.            
  83.             logCoreDebug("Raccolta parametri in corso...");
  84.                                    
  85.             // args
  86.             utilizzoErrato = "Usage error: VaultTools <operationType> <options>\n"+
  87.                     "- <operationType>: "+VaultOperationType.UPDATE_CONFIG.getValue()+","+VaultOperationType.ENCRYPT.getValue()+","+VaultOperationType.DECRYPT.getValue()+"\n"+
  88.                     "- <options>: \n"+
  89.                     "\t- "+VaultOperationType.UPDATE_CONFIG.getValue()+": "+VaultUpdateConfig.getUsage()+"\n"+
  90.                     "\t- "+VaultOperationType.ENCRYPT.getValue()+": "+VaultEncDecConfig.getUsage()+"\n"+
  91.                     "\t- "+VaultOperationType.DECRYPT.getValue()+": "+VaultEncDecConfig.getUsage()+"";
  92.            
  93.         }
  94.         catch(Exception t) {
  95.             if(logCore!=null) {
  96.                 logCore.error(t.getMessage(),t);
  97.             }
  98.             throw new CoreException(t.getMessage(),t);
  99.         }
  100.            
  101.         if(args.length<1 || args[0]==null) {
  102.             throw new CoreException(utilizzoErrato);
  103.         }
  104.        
  105.         try {
  106.             opType = parseOperationType(utilizzoErrato, args);
  107.             argsConfig = new String[args.length - 1];
  108.             System.arraycopy(args, 1, argsConfig, 0, args.length - 1);
  109.         }
  110.         catch(Exception t) {
  111.             if(logCore!=null) {
  112.                 logCore.error(t.getMessage(),t);
  113.             }
  114.             throw new CoreException(t.getMessage(),t);
  115.         }
  116.        
  117.         switch (opType) {
  118.         case UPDATE_CONFIG:
  119.             utilizzoErrato = "Usage error: update "+VaultUpdateConfig.getUsage();          
  120.             updateConfig = new VaultUpdateConfig(argsConfig, utilizzoErrato);
  121.             break;
  122.         case ENCRYPT:
  123.             utilizzoErrato = "Usage error: encrypt "+VaultEncDecConfig.getUsage();          
  124.             encDecConfig = new VaultEncDecConfig(argsConfig, utilizzoErrato, true);
  125.             break;
  126.         case DECRYPT:
  127.             utilizzoErrato = "Usage error: decrypt "+VaultEncDecConfig.getUsage();          
  128.             encDecConfig = new VaultEncDecConfig(argsConfig, utilizzoErrato, false);
  129.             break;
  130.         }
  131.        
  132.         try {
  133.             process(updateConfig, encDecConfig);
  134.         }
  135.         catch(Exception t) {
  136.             if(logCore!=null) {
  137.                 logCore.error(t.getMessage(),t);
  138.             }
  139.             throw new CoreException(t.getMessage(),t);
  140.         }

  141.     }
  142.    
  143.     private static void process(VaultUpdateConfig updateConfig, VaultEncDecConfig encDecConfig) throws CoreException {
  144.         logCoreDebug("Raccolta parametri terminata");
  145.        
  146.         // properties
  147.         VaultProperties vaultProperties = VaultProperties.getInstance();
  148.         /**String confDir = null;*/ // non sembra servire
  149.         String protocolloDefault = vaultProperties.getProtocolloDefault();
  150.        
  151.         // Inizializzo Controlli connessioni
  152.         disableCheckSingleConnectionDataSource();
  153.        
  154.         // Map (environment)
  155.         initMap(vaultProperties);
  156.        
  157.         // Load Security Provider
  158.         if(vaultProperties.isSecurityLoadBouncyCastleProvider()) {
  159.             initBouncyCastle();
  160.         }
  161.        
  162.         // inizializzo HSM Manager
  163.         initHsm(vaultProperties);
  164.        
  165.         // inizializzo BYOK Manager
  166.         BYOKManager byokManager = initBYOK(vaultProperties);
  167.        
  168.         // Secrets (environment)
  169.         initSecrets(vaultProperties, byokManager);
  170.        
  171.         // Init GovWay
  172.         logCoreDebug("Inizializzazione risorse libreria in corso...");
  173.        
  174.         initProtocolFactory(protocolloDefault);
  175.        
  176.         initExtendedInfoManager();
  177.        
  178.         logCoreDebug("Inizializzazione risorse libreria terminata");
  179.        
  180.         // Validazione configurazioni
  181.         if(updateConfig!=null) {
  182.            
  183.             logCoreInfo("Aggiornamento informazioni sensibili in corso ...");
  184.            
  185.             updateConfig.validate(byokManager);
  186.             VaultUpdateConfigUtilities utils = new VaultUpdateConfigUtilities(updateConfig);
  187.             utils.process();
  188.            
  189.             logCoreInfo("Aggiornamento informazioni sensibili completato");
  190.         }
  191.         else if(encDecConfig!=null) {
  192.            
  193.             String op = encDecConfig.isEncode() ? "Cifratura" : "Decrifratura";
  194.             logCoreInfo(op+" in corso ...");
  195.            
  196.             encDecConfig.validate(byokManager);
  197.             VaultEncDecUtilities utils = new VaultEncDecUtilities(encDecConfig);
  198.             utils.process();
  199.            
  200.             logCoreInfo(op+" completata");
  201.         }
  202.     }

  203.     private static void initLogger() throws CoreException {
  204.         Properties propertiesLog4j = new Properties();
  205.         try (InputStream inPropLog4j = VaultTools.class.getResourceAsStream("/govway_vault.cli.log4j2.properties");){
  206.             propertiesLog4j.load(inPropLog4j);
  207.             LoggerWrapperFactory.setLogConfiguration(propertiesLog4j);
  208.         } catch(java.lang.Exception e) {
  209.             throw new CoreException("Impossibile leggere i dati dal file 'govway_vault.cli.log4j2.properties': "+e.getMessage());
  210.         }
  211.     }
  212.     private static VaultOperationType parseOperationType(String utilizzoErrato,String [] args) throws CoreException{
  213.         VaultOperationType opType = null;
  214.         try {
  215.             opType = VaultOperationType.toEnumConstant(args[0].trim(), true);
  216.         }catch(Exception e) {
  217.             throw new CoreException(utilizzoErrato+"\nIl tipo di operazione indicato ("+args[0].trim()+") non รจ gestito, valori ammessi: "+
  218.                     VaultOperationType.UPDATE_CONFIG.getValue()+","+VaultOperationType.ENCRYPT.getValue()+","+VaultOperationType.DECRYPT.getValue());
  219.         }
  220.         return opType;
  221.     }
  222.     private static void initBouncyCastle() throws CoreException {
  223.         try{
  224.             ProviderUtils.addBouncyCastleAfterSun(true);
  225.             logCoreInfo("Aggiunto Security Provider org.bouncycastle.jce.provider.BouncyCastleProvider");
  226.         }catch(Exception e){
  227.             throw new CoreException(e.getMessage(),e);
  228.         }
  229.     }
  230.     private static void disableCheckSingleConnectionDataSource() throws CoreException {
  231.         // Inizializzo Controlli connessioni
  232.         try {
  233.             Logger logR = logCore;
  234.             ServicesUtils.initCheckConnectionDB(logR, false, false);
  235.         } catch (Exception e) {
  236.             doError("Inizializzazione controlli connessione non riuscita",e);
  237.         }
  238.     }
  239.     private static void initMap(VaultProperties loaderProperties) throws CoreException {
  240.         try {
  241.             String mapConfig = loaderProperties.getEnvMapConfig();
  242.             if(StringUtils.isNotEmpty(mapConfig)) {
  243.                 logCoreInfo("Inizializzazione environment in corso...");
  244.                 MapProperties.initialize(logCore, mapConfig, loaderProperties.isEnvMapConfigRequired());
  245.                 MapProperties mapProperties = MapProperties.getInstance();
  246.                 mapProperties.initEnvironment();
  247.                 String msgInit = "Environment inizializzato con le variabili definite nel file '"+mapConfig+"'"+
  248.                         "\n\tJavaProperties: "+mapProperties.getJavaMap().keys()+
  249.                         "\n\tEnvProperties: "+mapProperties.getEnvMap().keys()+
  250.                         "\n\tObfuscateMode: "+mapProperties.getObfuscateModeDescription()+
  251.                         "\n\tObfuscatedJavaKeys: "+mapProperties.getObfuscatedJavaKeys()+
  252.                         "\n\tObfuscatedEnvKeys: "+mapProperties.getObfuscatedEnvKeys();
  253.                 logCoreInfo(msgInit);
  254.             }
  255.         } catch (Exception e) {
  256.             doError("Errore durante l'inizializzazione dell'ambiente",e);
  257.         }
  258.     }
  259.     private static void initHsm(VaultProperties loaderProperties) throws CoreException {
  260.         // inizializzo HSM Manager
  261.         try {
  262.             String hsmConfig = loaderProperties.getHSMConfigurazione();
  263.             if(StringUtils.isNotEmpty(hsmConfig)) {
  264.                 logCoreInfo("Inizializzazione HSM in corso...");
  265.                 File f = new File(hsmConfig);
  266.                 HSMManager.init(f, loaderProperties.isHSMRequired(), logCore, false);
  267.                 HSMUtils.setHsmConfigurableKeyPassword(loaderProperties.isHSMKeyPasswordConfigurable());
  268.                 logCoreInfo("Inizializzazione HSM effettuata con successo");
  269.             }
  270.         } catch (Exception e) {
  271.             doError("Errore durante l'inizializzazione del manager HSM",e);
  272.         }
  273.     }
  274.     private static BYOKManager initBYOK(VaultProperties loaderProperties) throws CoreException {
  275.         BYOKManager byokManager = null;
  276.         try {
  277.             String byokConfig = loaderProperties.getBYOKConfigurazione();
  278.             if(StringUtils.isNotEmpty(byokConfig)) {
  279.                 logCoreInfo("Inizializzazione BYOK in corso...");
  280.                 File f = new File(byokConfig);
  281.                 BYOKManager.init(f, loaderProperties.isBYOKRequired(), logCore);
  282.                 byokManager = BYOKManager.getInstance();
  283.                 String msgInit = "Gestore BYOK inizializzato;"+
  284.                         "\n\tHSM registrati: "+byokManager.getKeystoreTypes()+
  285.                         "\n\tSecurityEngine registrati: "+byokManager.getSecurityEngineTypes()+
  286.                         "\n\tGovWaySecurityEngine: "+byokManager.getSecurityEngineGovWayDescription();
  287.                 logCoreInfo(msgInit);
  288.             }
  289.         } catch (Exception e) {
  290.             doError("Errore durante l'inizializzazione del manager BYOK",e);
  291.         }
  292.         return byokManager;
  293.     }
  294.     private static void initSecrets(VaultProperties loaderProperties, BYOKManager byokManager) throws CoreException {
  295.         try {
  296.             String secretsConfig = loaderProperties.getBYOKEnvSecretsConfig();
  297.             if(byokManager!=null && StringUtils.isNotEmpty(secretsConfig)) {
  298.                 logCoreInfo("Inizializzazione secrets in corso...");
  299.                
  300.                 Map<String, Object> dynamicMap = new HashMap<>();
  301.                 DynamicInfo dynamicInfo = new  DynamicInfo();
  302.                 DynamicUtils.fillDynamicMap(logCore, dynamicMap, dynamicInfo);
  303.                
  304.                 BYOKMapProperties.initialize(logCore, secretsConfig, loaderProperties.isBYOKEnvSecretsConfigRequired(),
  305.                         true,
  306.                         dynamicMap, true);
  307.                 BYOKMapProperties secretsProperties = BYOKMapProperties.getInstance();
  308.                 secretsProperties.initEnvironment();
  309.                 String msgInit = "Environment inizializzato con i secrets definiti nel file '"+secretsConfig+"'"+
  310.                         "\n\tJavaProperties: "+secretsProperties.getJavaMap().keys()+
  311.                         "\n\tEnvProperties: "+secretsProperties.getEnvMap().keys()+
  312.                         "\n\tObfuscateMode: "+secretsProperties.getObfuscateModeDescription();
  313.                 logCoreInfo(msgInit);
  314.             }
  315.         } catch (Exception e) {
  316.             doError("Errore durante l'inizializzazione dell'ambiente (secrets)",e);
  317.         }  
  318.     }
  319.     private static ConfigurazionePdD initProtocolFactory(String protocolloDefault) throws CoreException {
  320.         ConfigurazionePdD configPdD = null;
  321.         try {
  322.             configPdD = new ConfigurazionePdD();
  323.             configPdD.setAttesaAttivaJDBC(-1);
  324.             configPdD.setCheckIntervalJDBC(-1);
  325.             configPdD.setLoader(new org.openspcoop2.utils.resources.Loader(VaultTools.class.getClassLoader()));
  326.             configPdD.setLog(logCore);
  327.             ProtocolFactoryManager.initialize(logCore, configPdD,
  328.                     protocolloDefault);
  329.         } catch (Exception e) {
  330.             throw new CoreException("Errore (InitConfigurazione - ProtocolFactoryManager): "+e.getMessage(),e);
  331.         }
  332.         return configPdD;
  333.     }
  334.     private static void initExtendedInfoManager() throws CoreException {
  335.         try{
  336.             ExtendedInfoManager.initialize(new org.openspcoop2.utils.resources.Loader(VaultTools.class.getClassLoader()), null, null, null);
  337.         }catch(Exception e){
  338.             throw new CoreException("Inizializzazione [ExtendedInfoManager] fallita",e);
  339.         }
  340.     }

  341.     private static void doError(String msg,Exception e) throws CoreException {
  342.         String msgErrore = msg+": " + e.getMessage();
  343.         logCoreError(msgErrore,e);
  344.         throw new CoreException(msgErrore,e);
  345.     }
  346.    
  347. }