First Commit from Source Code Reply

This commit is contained in:
vincenzofariello
2024-05-09 17:40:24 +02:00
parent 11e3b57c5b
commit 107a016cb9
35225 changed files with 1111346 additions and 1 deletions

View File

@@ -0,0 +1,59 @@
package it.valueteam.securityutility;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* <p>
* Title: ChangePassword</p>
* <p>
* Description: permette di modificare una password criptata in un file di
* properties</p>
* <p>
* Copyright: Copyright (c) 2006</p>
* <p>
* Company: </p>
*
* @author not attributable
* @version 1.0
*/
public class ChangePassword {
public ChangePassword(String[] args) {
String fileProp;
String propName;
try {
if (args.length == 2) {
fileProp = args[0];
propName = args[1];
//read password
String pwd;
//Process proc = Runtime.getRuntime().exec("pswd.so");
//BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
System.out.print("Cambio valore per la proprieta' [" + propName + "]. Inserire il valore in chiaro:");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
pwd = reader.readLine();
if (pwd != null && pwd.length() > 0) {
//cripto
CryptoUtility.getInstance().criptaFileEntry(fileProp, propName, pwd);
} else {
System.out.println("Password vuota!!! ");
}
} else {
System.out.println("Sintassi: ChangePassword <file di properties> <proprieta'>");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* MAIN*
*/
public static void main(String[] args) {
ChangePassword changePassword = new ChangePassword(args);
}
}

View File

@@ -0,0 +1,359 @@
package it.valueteam.securityutility;
import java.io.*;
import java.security.*;
import java.util.*;
import javax.crypto.*;
import javax.crypto.spec.DESedeKeySpec;
import sun.misc.*;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2005</p>
* <p>Company: </p>
* @author Paolo Marini
* @version 1.0
*/
public class CryptoUtility {
public static final String TRIPLE_DES_CHIPER = "DESede/ECB/PKCS5Padding";
public static final String TRIPLE_DES_PREFIX = "{3DES}";
public static final String TRIPLE_DES_KEY = "DESede";
public static final int TRIPLE_DES_KEY_SIZE = 168;
public static final String KEY_MISSING = "Symmetric Key Missing";
public static final String MEMORY_ADDRESS = "INDIRIZZO_KEY";
public static final String FLAG_SHARED_KEY = "USE_CRYPTO_SHARED";
public static final String FILE_KEY = "PATH_KEY";
public static final String INDIRIZZO_DINAMICO = "USE_DYNAMIC_ADDRESS";
public static final int INDIRIZZO_STATICO = 5625;
private Key chiave3DES = null;
private static CryptoUtility onlyInstance = null;
/**
* Costruttore
* @throws Exception
*/
private CryptoUtility() throws Exception{
String fileChiave=null;
int indirizzo;
String confFile = System.getProperty("security_conf_file");
IniFile iniFile = new IniFile(confFile);
Properties p = iniFile.getSection("main.properties");
if("true".equalsIgnoreCase(p.getProperty(FLAG_SHARED_KEY))) {
indirizzo = "true".equalsIgnoreCase(p.getProperty(INDIRIZZO_DINAMICO))?
Integer.parseInt(p.getProperty(MEMORY_ADDRESS)):
INDIRIZZO_STATICO;
try {
readKey(indirizzo);
}
catch (Exception ex) {
System.out.println("Impossibile caricare la chiave dalla ram: verificare che la chiave sia presente.");
throw new Exception("Impossibile caricare la chiave dalla ram.");
}
}
else {
fileChiave = (String) p.get(FILE_KEY);
loadKey(fileChiave);
}
}
/**
* Utilizzato da applicazioni che inizializzano esplicitamente l'api
* di cifratura con init(). Il Properties e' letto autonomamente prima dell'init.
* @param config Le properties contenute nel file security.properties.
* @throws Exception
*/
private CryptoUtility(Properties config) throws Exception {
String fileChiave = null;
int indirizzo;
if("true".equalsIgnoreCase(config.getProperty(FLAG_SHARED_KEY))) {
indirizzo = "true".equalsIgnoreCase(config.getProperty(INDIRIZZO_DINAMICO))?
Integer.parseInt(config.getProperty(MEMORY_ADDRESS)):
INDIRIZZO_STATICO;
try {
readKey(indirizzo);
}
catch (Exception ex) {
System.out.println("Impossibile caricare la chiave dalla ram: verificare che la chiave sia presente.");
throw new Exception("Impossibile caricare la chiave dalla ram.");
}
}
else {
fileChiave = (String) config.get(FILE_KEY);
loadKey(fileChiave);
}
}
/**
* Inizializzazione del framework di security
* @param fileChiave String
* @throws Exception
* @return CryptoUtility
*/
public static CryptoUtility getInstance() throws Exception{
if (onlyInstance==null) {
synchronized(CryptoUtility.class) {
if (onlyInstance==null) {
onlyInstance = new CryptoUtility();
}
}
}
return onlyInstance;
}
/**
* Utilizzato per inizializzare la classe prima delle operazioni di cifratura.
* @param secConfig Le properties del file security.properties
* @throws Exception
*/
public static void init(Properties secConfig) throws Exception{
onlyInstance = new CryptoUtility(secConfig);
}
/**
* carica la chiave simmetrica di cifratura/decifratura
* @param fileChiave String
* @throws Exception
*/
private void loadKey(String fileChiave) throws Exception{
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(fileChiave));
chiave3DES = (Key)in.readObject();
}
finally {
if(in!=null) {
try {
in.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
/**
* Legge la chiave (raw byte) dalla shared memory attraverso il bridge JNI
* @param indirizzo L'indirizzo della chiave nella memoria
* @throws Exception
*/
private void readKey(int indirizzo) throws Exception{
DESedeKeySpec spec = null;
KeyJNIBridge bridge = new KeyJNIBridge();
spec = new DESedeKeySpec(bridge.readKey(indirizzo));
chiave3DES = SecretKeyFactory.getInstance(CryptoUtility.TRIPLE_DES_KEY).generateSecret(spec);
}
/**
* funzione di criptazione
* @param value String
* @throws Exception
* @return String
*/
public String cripta3DES(String value) throws Exception{
byte[] res = null;
Cipher cipher = Cipher.getInstance(TRIPLE_DES_CHIPER);
cipher.init(Cipher.ENCRYPT_MODE, chiave3DES);
byte[] val = value.getBytes();
res = new byte[cipher.getOutputSize(val.length)];
int size = cipher.update(val, 0, val.length, res, 0);
size += cipher.doFinal(res,size);
return toString(res,res.length);
}
/**
* funzione di decriptazione
* @param value String
* @throws Exception
* @return String
*/
public String decripta3DES(String value) throws Exception{
Cipher cipher = Cipher.getInstance(TRIPLE_DES_CHIPER);
cipher.init(Cipher.DECRYPT_MODE, chiave3DES);
return new String(cipher.doFinal(toByteArray(value)));
}
/**
* funzione di decriptazione che automaticamte elimina il prefisso 3DES
* @param value String
* @throws Exception
* @return String
*/
public String decripta3DESWithPrefix(String value) throws Exception{
return decripta3DES(value.substring(TRIPLE_DES_PREFIX.length()));
}
private static final String toString(byte[] bytes,int length) {
BASE64Encoder encoder = new BASE64Encoder();
String base64 = encoder.encode(bytes);
return base64;
}
private static final byte[] toByteArray(String string) throws Exception{
BASE64Decoder decoder = new BASE64Decoder();
byte[] raw = decoder.decodeBuffer(string);
return raw;
}
/**
* decripta un inputstream ritornandone un inputstream uno con tutte le key in chiaro
* @param filename String
* @throws Exception
* @return InputStream
*/
public InputStream getCleanFile(InputStream in) throws Exception {
ByteArrayInputStream bin = null;
String read = null;
BufferedReader input = new BufferedReader(new InputStreamReader(in));
String key = null;
String value = null;
String cleanValue = null;
StringBuffer stringOutput = new StringBuffer();
byte[] b = null;
int idx = -1;
while ( (read = input.readLine()) != null) {
if ( (read.startsWith(";") || read.startsWith("#")))
stringOutput.append(read + "\n");
else {
idx = read.indexOf("=");
if (idx == -1)
stringOutput.append(read + "\n");
else {
cleanValue = "";
key = read.substring(0, idx);
if (idx < read.length())
value = read.substring(idx + 1, read.length());
else
value = "";
cleanValue = value;
if ( (key.startsWith(TRIPLE_DES_PREFIX)) && value != null &&
value.length() > 0) {
try {
if (value.startsWith(TRIPLE_DES_PREFIX)) {
cleanValue = decripta3DES(value.substring(TRIPLE_DES_PREFIX.
length()));
// System.out.println("decripta3DES:" + key);
}
// else
// System.out.println("NOT decripta3DES:" + key);
}
catch (Exception ex) {
System.out.println("Errore durante il decript della chiave:"+key);
ex.printStackTrace();
throw ex;
}
}
stringOutput.append(key + "=" + cleanValue + "\n");
}
}
}
b = stringOutput.toString().getBytes();
bin = new ByteArrayInputStream(b);
return bin;
}
/**
* decripta un properties ritornandone uno con tutte le key in chiaro
* @param inProperties Properties
* @throws Exception
* @return Properties
*/
public Properties getCleanProperties(Properties inProperties) throws Exception{
String key=null;
String value=null;
String cleanValue=null;
Properties outProperties = new Properties();
if ((inProperties!=null) && (inProperties.size()!=0)) {
Enumeration e = inProperties.keys();
while (e.hasMoreElements()) {
key = (String) e.nextElement();
value = (String)inProperties.get(key);
cleanValue = value;
if ((key.startsWith(TRIPLE_DES_PREFIX)) && value!=null && value.length()>0) {
try {
if (value.startsWith(TRIPLE_DES_PREFIX)) {
cleanValue = decripta3DES(value.substring(TRIPLE_DES_PREFIX.length()));
//System.out.println("decripta3DES: ["+key+"] value crypt ["+value+"] clean value ["+cleanValue+"]");
}
// else
// System.out.println("NOT decripta3DES:"+key);
}
catch (Exception ex) {
System.out.println("Errore durante il decript della chiave:"+key);
ex.printStackTrace();
throw ex;
}
}
outProperties.put(key,cleanValue);
}
}
return outProperties;
}
/**
* Chipta una pwd della proprieta' in ingresso del relativo file
* @param file String
* @param key String
* @param value String
* @throws Exception
*/
public void criptaFileEntry(String file, String key, String value) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteArrayInputStream bin = new ByteArrayInputStream(baos.toByteArray());
baos = new ByteArrayOutputStream();
PrintWriter writer = new PrintWriter(baos);
BufferedReader reader = null;
FileOutputStream out = null;
String pwd = TRIPLE_DES_PREFIX + cripta3DES(value);
try {
reader = new BufferedReader(new FileReader(file));
String linea = null;
while ( (linea = reader.readLine()) != null) {
if (linea.startsWith(key)) {
writer.println(key + "=" + pwd);
}
else {
writer.println(linea);
}
}
writer.close();
reader.close();
reader = null;
baos.flush();
out = new FileOutputStream(file);
baos.writeTo(out);
out.close();
out = null;
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException ex) {
}
}
if (out != null) {
out.close();
}
}
}
}

View File

@@ -0,0 +1,336 @@
/* ====================================================================
*
* @PROJECT.FULLNAME@ @VERSION@ License.
*
* Copyright (c) @YEAR@ L2FProd.com. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by L2FProd.com
* (http://www.L2FProd.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "@PROJECT.FULLNAME@", "SkinLF" and "L2FProd.com" must not
* be used to endorse or promote products derived from this software
* without prior written permission. For written permission, please
* contact info@L2FProd.com.
*
* 5. Products derived from this software may not be called "SkinLF"
* nor may "SkinLF" appear in their names without prior written
* permission of L2FProd.com.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL L2FPROD.COM OR ITS CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*/
package it.valueteam.securityutility;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
/**
* @author $Author: valueteam\salvalaggiom $
* @created 27 avril 2002
* @version $Revision: 1.1 $, $Date: 2009/11/27 10:19:05 $
*/
public class IniFile {
Properties sections;
/**
* Constructor for the IniFile object
*/
public IniFile() {
sections = new Properties();
}
/**
* Constructor for the IniFile object
*
* @param filename Description of Parameter
* @exception FileNotFoundException Description of Exception
*/
public IniFile(String filename) throws FileNotFoundException {
this();
load(filename);
}
/**
* Constructor for the IniFile object
*
* @param url Description of Parameter
* @exception IOException Description of Exception
*/
public IniFile(URL url) throws IOException {
this();
load(url.openStream());
}
/**
* Constructor for the IniFile object
*
* @param input Description of Parameter
* @exception IOException Description of Exception
*/
public IniFile(InputStream input) throws IOException {
this();
load(input);
}
/**
* Sets the KeyValue attribute of the IniFile object
*
* @param section The new KeyValue value
* @param key The new KeyValue value
* @param value The new KeyValue value
*/
public void setKeyValue(String section, String key, String value) {
try {
getSection(section).put(key, value);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Gets the Sections attribute of the IniFile object
*
* @return The Sections value
*/
public Properties getSections() {
return sections;
}
/**
* Gets the Section attribute of the IniFile object
*
* @param section Description of Parameter
* @return The Section value
*/
public Properties getSection(String section) {
return (Properties) (sections.get(section));
}
/**
* Gets the NullOrEmpty attribute of the IniFile object
*
* @param section Description of Parameter
* @param key Description of Parameter
* @return The NullOrEmpty value
*/
public boolean isNullOrEmpty(String section, String key) {
String value = getKeyValue(section, key);
return (value == null || value.length() == 0);
}
/**
* Gets the KeyValue attribute of the IniFile object
*
* @param section Description of Parameter
* @param key Description of Parameter
* @return The KeyValue value
*/
public String getKeyValue(String section, String key) {
try {
return (String) getSection(section).get(key);
} catch (NullPointerException e) {
return null;
}
}
/**
* Gets the KeyIntValue attribute of the IniFile object
*
* @param section Description of Parameter
* @param key Description of Parameter
* @return The KeyIntValue value
*/
public int getKeyIntValue(String section, String key) {
return getKeyIntValue(section, key, 0);
}
/**
* Gets the KeyIntValue attribute of the IniFile object
*
* @param section Description of Parameter
* @param key Description of Parameter
* @param defaultValue Description of Parameter
* @return The KeyIntValue value
*/
public int getKeyIntValue(String section, String key, int defaultValue) {
String value = getKeyValue(section, key);
if (value == null) {
return defaultValue;
}
else {
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
return 0;
}
}
}
/**
* Gets the KeysAndValues attribute of the IniFile object
*
* @param aSection Description of Parameter
* @return The KeysAndValues value
*/
public String[][] getKeysAndValues(String aSection) {
Properties section = getSection(aSection);
if (section == null) {
return null;
}
String[][] results = new String[section.size()][2];
int i = 0;
for (Enumeration f = section.keys(), g = section.elements(); f.hasMoreElements(); i++) {
results[i][0] = (String) f.nextElement();
results[i][1] = (String) g.nextElement();
}
return results;
}
/**
* Description of the Method
*
* @param filename Description of Parameter
* @exception FileNotFoundException Description of Exception
*/
public void load(String filename) throws FileNotFoundException {
load(new FileInputStream(filename));
}
/**
* Description of the Method
*
* @param filename Description of Parameter
* @exception IOException Description of Exception
*/
public void save(String filename) throws IOException {
save(new FileOutputStream(filename));
}
/**
* Description of the Method
*
* @param in Description of Parameter
*/
public void load(InputStream in) {
try {
BufferedReader input = new BufferedReader(new InputStreamReader(in));
String read;
Properties section = null;
String section_name;
while ((read = input.readLine()) != null) {
if (read.startsWith(";") || read.startsWith("#")) {
continue;
}
else if (read.startsWith("[")) {
// new section
section_name = read.substring(1, read.indexOf("]"));
section = (Properties) sections.get(section_name);
if (section == null) {
section = new Properties();
sections.put(section_name, section);
}
}
else if (read.indexOf("=") != -1 && section != null) {
// new key
String key = read.substring(0, read.indexOf("=")).trim();
String value = read.substring(read.indexOf("=") + 1).trim();
section.put(key, value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Description of the Method
*
* @param out Description of Parameter
*/
public void save(OutputStream out) {
try {
PrintWriter output = new PrintWriter(out);
String section;
for (Enumeration e = sections.keys(); e.hasMoreElements(); ) {
section = (String) e.nextElement();
output.println("[" + section + "]");
for (Enumeration f = getSection(section).keys(), g = getSection(section).elements();
f.hasMoreElements(); ) {
output.println(f.nextElement() + "=" + g.nextElement());
}
}
output.flush();
output.close();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Adds a feature to the Section attribute of the IniFile object
*
* @param section The feature to be added to the Section attribute
*/
public void addSection(String section) {
sections.put(section, new Properties());
}
/**
* Description of the Method
*
* @param section Description of Parameter
*/
public void removeSection(String section) {
}
/**
* Simple test function
*
* @param args The command line arguments
* @exception Exception Description of Exception
*/
public static void main(String[] args) throws Exception {
(new IniFile()).load(new FileInputStream(args[0]));
}
}

View File

@@ -0,0 +1,25 @@
package it.valueteam.securityutility;
/**
* <p>Title: </p>
* <p>Description: Interfaccia per la libreria C per l'accesso alla shared memory</p>
* <p>Copyright: Copyright (c) 2006</p>
* <p>Company: </p>
* @author Paolo Marini
* @version 1.0
*/
public class KeyJNIBridge {
static {
System.loadLibrary("SecUtility");
}
public KeyJNIBridge() {
}
public native void writeKey(int indirizzo,byte[] chiaveInChiaro);
public native byte[] readKey(int indirizzo);
}

View File

@@ -0,0 +1,78 @@
package it.valueteam.securityutility;
import java.io.*;
import java.util.Properties;
import java.security.*;
/**
* <p>Title: </p>
* <p>Description: Classe per il caricamento nella shared memory della
* chiave simmetrica dle sistema</p>
* <p>Copyright: Copyright (c) 2006</p>
* <p>Company: </p>
* @author Paolo Marini
* @version 1.0
*/
public class KeyManager {
public KeyManager() {
}
public static void main(String[] args) {
FileInputStream in = null;
Properties config = null;
int indirizzo;
KeyStore store = null;
Key encryptionKey = null;
String passphrase = null;
String confFile = System.getProperty("security_conf_file");
try {
System.out.println("Inizio caricamento chiave.");
in = new FileInputStream(confFile);
config = new Properties();
config.load(in);
in.close();
passphrase = "";
Process proc = Runtime.getRuntime().exec("pswd.so");
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.
getInputStream()));
passphrase = reader.readLine();
if (passphrase==null || passphrase.length()== 0) {
System.out.println("Specificare la passphrase");
System.exit(1);
}
in = new FileInputStream(config.getProperty(CryptoUtility.FILE_KEY));
store = KeyStore.getInstance("JCEKS");
store.load(in,passphrase.toCharArray());
encryptionKey = store.getKey("alias",passphrase.toCharArray());
indirizzo = "true".equalsIgnoreCase(config.getProperty(CryptoUtility.INDIRIZZO_DINAMICO))?
Integer.parseInt(config.getProperty(CryptoUtility.MEMORY_ADDRESS)):
CryptoUtility.INDIRIZZO_STATICO;
KeyJNIBridge bridge = new KeyJNIBridge();
bridge.writeKey(indirizzo,encryptionKey.getEncoded());
System.out.println("Caricamento chiave terminato con successo.");
}
catch (Exception ex) {
ex.printStackTrace();
}
finally {
if(in!=null) {
try {
in.close();
}
catch (IOException ex1) {
}
}
}
}
}

View File

@@ -0,0 +1,253 @@
package it.valueteam.securityutility;
import java.io.*;
import java.util.*;
/**
* <p>Title: SqlExecutor</p>
* <p>Description: Esegui gli script sql richiamando sqlplus e leggendo la pwd criptata da file di properties</p>
* <p> ES:java it.valueteam.securityutility.SqlExecutor -sqlplus test.sql -sqlplusOption -s</p>
* <p> ES:java it.valueteam.securityutility.SqlExecutor -sqlldr control=test.ctl log=test.log bad=test.bad data=test.dat rows=100 errors=99999</p>
* <p>Copyright: Copyright (c) 2006</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
public class SqlExecutor {
public static final String OUTPUT_STREAM_TYPE = "Output";
public static final String ERROR_STREAM_TYPE = "Error";
public static final int NORETVALUE = -1000;
public SqlExecutor(String[] args) {
String sqlPlusPathSh = null;
String sqlLrdPathSh = null;
String dbUser = null;
String dbPwdEncrypted = null;
String dbAlias = null;
String dbPwd = null;
String commandLine=null;
try {
if ((args.length < 2 ) ||
((!args[0].equals("-sqlplus")) &&
(!args[0].equals("-sqlldr")))
) {
System.out.println("Sintassi: SqlExecutor -sqlplus <script sql> [<param>] [-sqlplusOption <option>]");
System.out.println(" SqlExecutor -sqlldr <param>");
}
else {
String confFile = System.getProperty("security_conf_file");
IniFile iniFile = new IniFile(confFile);
Properties p = iniFile.getSection("sqlexecutor.properties");
sqlPlusPathSh = (String) p.get("PATH_SQLPLUS_SH");
sqlLrdPathSh = (String) p.get("PATH_SQLLRD_SH");
dbUser = (String) p.get("DB_USER");
dbPwdEncrypted = (String) p.get("{3DES}DB_PWD");
dbAlias = (String) p.get("DB_INSTANCE");
//decripto la pwd
dbPwd = CryptoUtility.getInstance().decripta3DESWithPrefix(dbPwdEncrypted);
if (args[0].equals("-sqlplus"))
commandLine = getSqlPlusLine(sqlPlusPathSh, dbUser, dbPwd, dbAlias, args);
else
commandLine = getSqlLdrLine(sqlLrdPathSh, dbUser, dbPwd, dbAlias, args);
//eseguo sqlplus
int exitVal = execCommand(commandLine,dbPwd);
if (exitVal!=0)
System.out.println("Errore nell'esecuzione dello script");
}
}
catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Costruisce la string di esecuzione per SqlPlus
* @param sqlPlusPath String
* @param dbUser String
* @param dbPwd String
* @param dbAlias String
* @param param String[]
* @return String
*/
private String getSqlPlusLine(String path, String dbUser, String dbPwd,
String dbAlias,String[] param) {
StringBuffer line = new StringBuffer();
//$ORACLE_HOME/bin/sqlplus $DB_USER/$DB_PWD@$DB_ALIAS
line.append(path).append(" ");
//opzioni sqlplus
boolean trovato=false;
for (int i = 1; i < param.length; i++) {
if (param[i].equals("-sqlplusOption"))
trovato=true;
else {
if (trovato)
line.append(param[i]).append(" ");
}
}
line.append(dbUser);
// line.append("/");
// line.append(dbPwd);
line.append("@");
line.append(dbAlias).append(" ");
line.append("@");
trovato=false;
for (int i = 1; i < param.length; i++) {
if (param[i].equals("-sqlplusOption"))
trovato=true;
else {
if (!trovato)
line.append(param[i]).append(" ");
}
}
return line.toString();
}
/**
* Costruisce la string di esecuzione per sqlldr
* @param sqlPlusPath String
* @param dbUser String
* @param dbPwd String
* @param dbAlias String
* @param param String[]
* @return String
*/
private String getSqlLdrLine(String path, String dbUser, String dbPwd,
String dbAlias,String[] param) {
//$ORACLE_HOME/bin/sqlldr userid=$DB_USER/$DB_PWD@$DB_ALIAS control=$CMD/CRMB_MNP.ctl log=$LOG/CRMB_MNP.log bad=$TMP/CRMB_MNP.bad data=$DAT/$FileFtp rows=100 errors=99999 >/dev/null 2>&1
StringBuffer line = new StringBuffer();
line.append(path).append(" ");
line.append("userid=");
line.append(dbUser);
// line.append("/");
// line.append(dbPwd);
line.append("@");
line.append(dbAlias).append(" ");
for (int i = 1; i < param.length; i++) {
line.append(param[i]).append(" ");
}
return line.toString();
}
/**
* Esegue un processo e rimane in attesa del suo completamento.
* @param procInfo Processo da eseguire.
* @return valore di ritorno del processo.
*/
private int execCommand(String line,String pwd) throws Exception {
Process curProc = null;
OutputReader r1 = null;
OutputReader r2 = null;
int exitVal = NORETVALUE;
try {
// System.out.println("debug----" + line);
//imposta la pwd come var di ambiente
String[] env1 = new String[1];
env1[0]="env1="+pwd;
//eseguo il processo
curProc = Runtime.getRuntime().exec(line.toString(),env1);
if (curProc != null) {
r1 = new OutputReader(OUTPUT_STREAM_TYPE, curProc.getInputStream());
r2 = new OutputReader(ERROR_STREAM_TYPE, curProc.getErrorStream());
r1.start();
r2.start();
exitVal = curProc.waitFor();
}
else
System.out.println("Processo figlio nullo");
}
catch (Exception ex) {
ex.printStackTrace();
throw ex;
}
finally {
OutputReader.stopReader(r1);
OutputReader.stopReader(r2);
curProc = null;
}
return exitVal;
}
/**MAIN**/
public static void main(String[] args) {
SqlExecutor sqlExecutor1 = new SqlExecutor(args);
}
/**
* Inner Class che gestisce la ridirezione dell'output del processo figlio
* sullo standard Output
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2006</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
protected static class OutputReader extends Thread {
BufferedReader bi;
String line;
String inputType;
boolean keepReading = true;
public OutputReader(String type, InputStream i) {
super("SqlExecutor-" + type);
inputType = type;
bi = new BufferedReader(new InputStreamReader(i));
}
public void interrupt() {
keepReading = false;
}
public void run() {
try {
while (keepReading) {
line = bi.readLine();
if (line != null) {
System.out.println(line);
line = null;
}
yield();
}
}
catch (Exception io) {
io.printStackTrace();
}
finally {
try {
if (bi != null) {
bi.close();
}
}
catch (Exception ex2) {
ex2.printStackTrace();
}
}
}
/**
* Esegue lo stop dell'OutputReader
* @param r OutputReader
*/
public static final void stopReader(OutputReader r) {
try {
if (r != null)
r.interrupt();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
//end OutputReader
}

View File

@@ -0,0 +1,134 @@
package it.valueteam.securityutility;
import java.io.*;
import java.security.*;
import java.util.*;
/**
* <p>Title: Utility per la lettura della chiave di cifratura serializzata dal file dove risiede
* e la memorizza in un keystore protetta da passprase</p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2006</p>
*
* <p>Company: ValueTeam</p>
*
* @author Mario Giurlanda
*
* @version 1.0
*/
public class TripleDesKeyCipher {
public TripleDesKeyCipher() {
}
public static void main(String[] args) {
Key encryptionKey = null;
boolean backup=false;
//Recupero degli eventuali args
if( args.length == 0 )
backup = false;
else if ( args[0].equalsIgnoreCase("-b") )
backup = true;
else {
System.out.println("Sintassi: TripleDesKeyCipher [-b] ");
System.out.println(" -b Backup dei file");
System.exit(1);
}
//Load delle property
Properties p = TripleDesKeyGenerator.initProperties();
String filekey = (String)p.get("PATH_KEY");
try {
File file = new File(filekey);
//Controllo sull'esistenza del file
System.out.println("Leggo il file" + file);
if (file.exists()) {
encryptionKey = loadTripleDesKey(file);
//Se richiesto backup provo ad eseguirlo altrimenti termino esecuzione con messaggio di errore
if (backup) {
System.out.println("Backup del file " + file);
if (backupFile(file)) {
System.out.println("Backup eseguito con successo");
}
else {
System.out.println("Impossibile eseguire il backup del file");
System.exit(1);
}
}
//Generazione del keystore
System.out.println("Genero il file: " + filekey);
TripleDesKeyGenerator.storeTripleDesKey(file, encryptionKey, true);
System.out.println("File generato con successo.");
}
else
System.out.println("Impossibile cifrare la chiave, file non presente.");
}
catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* loadTripleDesKey
*
* @return Key
*/
private static Key loadTripleDesKey(File fileChiave) throws Exception {
ObjectInputStream in = null;
Key chiave3DES = null;
try {
in = new ObjectInputStream(new FileInputStream(fileChiave));
chiave3DES = (Key)in.readObject();
} catch (Exception e) {
System.out.println("Impossibile caricare la chiave dal file " + fileChiave);
e.printStackTrace();
throw e;
}
finally {
if(in!=null) {
try {
in.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
return chiave3DES;
}
private static boolean backupFile(File oldFile){
File newFile = null;
boolean ret;
try{
newFile = new File(oldFile.getAbsolutePath() + ".bak");
ret = oldFile.renameTo(newFile);
ret = true;
}
catch(Exception e){
e.printStackTrace();
ret = false;
}
return ret;
}
}

View File

@@ -0,0 +1,150 @@
package it.valueteam.securityutility;
import java.io.*;
import java.security.*;
import java.util.*;
import javax.crypto.*;
/**
* <p>Title: </p>
* <p>Description: Generatore della chiave simmetrica di cifratura/decifratura </p>
* <p>Copyright: Copyright (c) 2006</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
public class TripleDesKeyGenerator {
public TripleDesKeyGenerator() {
}
public static void main(String[] args) {
Key encryptionKey = null;
String filename = null;
boolean useShared = false;
Properties p = initProperties();
filename = (String)p.get("PATH_KEY");
useShared = "true".equalsIgnoreCase(p.getProperty(CryptoUtility.FLAG_SHARED_KEY));
try {
File file = new File(filename);
if (!file.exists()) {
encryptionKey = generateTripleDesKey();
System.out.println("Genero il file: " + file);
storeTripleDesKey(file, encryptionKey, useShared);
System.out.println("File generato con successo.");
}
else
System.out.println("Impossibile generare file, file gia' presente.");
}
catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* initProperties
*
* @return Properties
*/
public static Properties initProperties() {
String confFile = System.getProperty("security_conf_file");
System.out.println("FILE SEC: "+confFile);
IniFile iniFile = null;
try {
iniFile = new IniFile(confFile);
}
catch (FileNotFoundException ex2) {
System.out.println("File security properties non trovato");
System.exit(1);
}
return iniFile.getSection("main.properties");
}
/**
*
* @param file File
* @param encryptionKey Key
* @param useShared boolean
* @throws Exception
*/
public static void storeTripleDesKey(File file, Key encryptionKey, boolean useShared) throws Exception {
ObjectOutput objOut = null;
FileOutputStream out = null;
KeyStore store = null;
String passphrase = null;
try {
if(useShared) {
passphrase = "";
Process proc = Runtime.getRuntime().exec("pswd.so");
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.
getInputStream()));
passphrase = reader.readLine();
if((passphrase==null)||(passphrase.length()<8) || (passphrase.length()>16)) {
System.out.println("Specificare la passphrase di MIN. 8, MAX. 16 caratteri");
System.exit(1);
}
store = KeyStore.getInstance("JCEKS");
store.load(null, null);
store.setKeyEntry("alias", encryptionKey, passphrase.toCharArray(), null);
out = new FileOutputStream(file);
store.store(out, passphrase.toCharArray());
}
else {
objOut = new ObjectOutputStream(new FileOutputStream(file));
objOut.writeObject(encryptionKey);
}
}
catch (Exception ex) {
throw ex;
}
finally {
if(out!=null) {
try {
out.close();
}
catch (IOException ex3) {
}
}
if(objOut!=null) {
try {
objOut.close();
}
catch (IOException ex1) {
}
}
}
}
/**
* Genera la chiave di cifratura con algoritmo 3DES
*
* @return Key
*/
private static Key generateTripleDesKey() throws NoSuchAlgorithmException {
Key encryptionKey;
KeyGenerator generator = KeyGenerator.getInstance(CryptoUtility.TRIPLE_DES_KEY);
generator.init(CryptoUtility.TRIPLE_DES_KEY_SIZE);
encryptionKey = generator.generateKey();
return encryptionKey;
}
}