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,6 @@
@echo off
set ANT_HOME=../build/apache-ant-1.9.2
set JAVA_HOME=C:\NTTDATA\JAVA\jdk1.6.0_45
set ANT_OPTS=-Xms512m -Xmx512m
set PATH=%ANT_HOME%/bin;%JAVA_HOME%/bin
ant -Dplatforms.JDK_1.6.home=C:\NTTDATA\JAVA\jdk1.6.0_45 -lib "%JAVA_HOME%\lib\tools.jar" -buildfile build.xml %1

View File

@@ -0,0 +1,73 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See commented blocks below for -->
<!-- some examples of how to customize the build. -->
<!-- (If you delete it and reopen the project it will be recreated.) -->
<!-- By default, only the Clean and Build commands use this build script. -->
<!-- Commands such as Run, Debug, and Test only use this build script if -->
<!-- the Compile on Save feature is turned off for the project. -->
<!-- You can turn off the Compile on Save (or Deploy on Save) setting -->
<!-- in the project's Project Properties dialog box.-->
<project name="SecurityUtility" default="default" basedir=".">
<description>Builds, tests, and runs the project SecurityUtility.</description>
<import file="nbproject/build-impl.xml"/>
<!--
There exist several targets which are by default empty and which can be
used for execution of your tasks. These targets are usually executed
before and after some main targets. They are:
-pre-init: called before initialization of project properties
-post-init: called after initialization of project properties
-pre-compile: called before javac compilation
-post-compile: called after javac compilation
-pre-compile-single: called before javac compilation of single file
-post-compile-single: called after javac compilation of single file
-pre-compile-test: called before javac compilation of JUnit tests
-post-compile-test: called after javac compilation of JUnit tests
-pre-compile-test-single: called before javac compilation of single JUnit test
-post-compile-test-single: called after javac compilation of single JUunit test
-pre-jar: called before JAR building
-post-jar: called after JAR building
-post-clean: called after cleaning build products
(Targets beginning with '-' are not intended to be called on their own.)
Example of inserting an obfuscator after compilation could look like this:
<target name="-post-compile">
<obfuscate>
<fileset dir="${build.classes.dir}"/>
</obfuscate>
</target>
For list of available properties check the imported
nbproject/build-impl.xml file.
Another way to customize the build is by overriding existing main targets.
The targets of interest are:
-init-macrodef-javac: defines macro for javac compilation
-init-macrodef-junit: defines macro for junit execution
-init-macrodef-debug: defines macro for class debugging
-init-macrodef-java: defines macro for class execution
-do-jar: JAR building
run: execution of project
-javadoc-build: Javadoc generation
test-report: JUnit report generation
An example of overriding the target for project execution could look like this:
<target name="run" depends="SecurityUtility-impl.jar">
<exec dir="bin" executable="launcher.exe">
<arg file="${dist.jar}"/>
</exec>
</target>
Notice that the overridden target depends on the jar target and not only on
the compile target as the regular run target does. Again, for a list of available
properties which you can use, check the target you are overriding in the
nbproject/build-impl.xml file.
-->
</project>

View File

@@ -0,0 +1,3 @@
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,8 @@
build.xml.data.CRC32=c40b9185
build.xml.script.CRC32=1f3acd4b
build.xml.stylesheet.CRC32=8064a381@1.75.2.48
# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml.
# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you.
nbproject/build-impl.xml.data.CRC32=c40b9185
nbproject/build-impl.xml.script.CRC32=f70519d2
nbproject/build-impl.xml.stylesheet.CRC32=876e7a8f@1.75.2.48

View File

@@ -0,0 +1,73 @@
annotation.processing.enabled=true
annotation.processing.enabled.in.editor=false
annotation.processing.processors.list=
annotation.processing.run.all.processors=true
annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output
application.title=SecurityUtility
application.vendor=giuseppe
build.classes.dir=${build.dir}/classes
build.classes.excludes=**/*.java,**/*.form
# This directory is removed when the project is cleaned:
build.dir=build
build.generated.dir=${build.dir}/generated
build.generated.sources.dir=${build.dir}/generated-sources
# Only compile against the classpath explicitly listed here:
build.sysclasspath=ignore
build.test.classes.dir=${build.dir}/test/classes
build.test.results.dir=${build.dir}/test/results
# Uncomment to specify the preferred debugger connection transport:
#debug.transport=dt_socket
debug.classpath=\
${run.classpath}
debug.test.classpath=\
${run.test.classpath}
# This directory is removed when the project is cleaned:
dist.dir=dist
dist.jar=${dist.dir}/SecurityUtility.jar
dist.javadoc.dir=${dist.dir}/javadoc
endorsed.classpath=
excludes=
file.reference.SecurityUtility-src=src
includes=**
jar.compress=false
javac.classpath=
# Space-separated list of extra javac options
javac.compilerargs=
javac.deprecation=false
javac.processorpath=\
${javac.classpath}
javac.source=1.6
javac.target=1.6
javac.test.classpath=\
${javac.classpath}:\
${build.classes.dir}
javac.test.processorpath=\
${javac.test.classpath}
javadoc.additionalparam=
javadoc.author=false
javadoc.encoding=${source.encoding}
javadoc.noindex=false
javadoc.nonavbar=false
javadoc.notree=false
javadoc.private=false
javadoc.splitindex=true
javadoc.use=true
javadoc.version=false
javadoc.windowtitle=
main.class=
manifest.file=manifest.mf
meta.inf.dir=${src.dir}/META-INF
mkdist.disabled=false
platform.active=JDK_1.6
run.classpath=\
${javac.classpath}:\
${build.classes.dir}
# Space-separated list of JVM arguments used when running the project
# (you may also define separate properties like run-sys-prop.name=value instead of -Dname=value
# or test-sys-prop.name=value to set system properties for unit tests):
run.jvmargs=
run.test.classpath=\
${javac.test.classpath}:\
${build.test.classes.dir}
source.encoding=UTF-8
src.dir=${file.reference.SecurityUtility-src}

View File

@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://www.netbeans.org/ns/project/1">
<type>org.netbeans.modules.java.j2seproject</type>
<configuration>
<data xmlns="http://www.netbeans.org/ns/j2se-project/3">
<name>SecurityUtility</name>
<explicit-platform explicit-source-supported="true"/>
<source-roots>
<root id="src.dir"/>
</source-roots>
<test-roots/>
</data>
</configuration>
</project>

View File

@@ -0,0 +1,132 @@
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <string.h>
#define SHMSZ 27
#define KEY 5625
#define PERM 0600
void scrivi(void) {
int indirizzo = 0;
char c;
int shmid;
key_t key;
char * shm, * s, * res;
char str[80];
int i;
printf("Inserisci indirizzo.\n");
scanf("%d",&indirizzo);
printf("Indirizzo: %d \n",indirizzo);
//key = KEY;
key = (key_t)indirizzo;
/*
* Create the segment.
*/
if ((shmid = shmget(key, SHMSZ, IPC_CREAT | PERM)) < 0) {
perror("shmget");
exit(1);
}
/*
* Now we attach the segment to our data space.
*/
if ((shm = shmat(shmid, NULL, 0)) == (char * ) - 1) {
perror("shmat");
exit(1);
}
res = getpass("password:");
s = shm;
int j = strlen(res);
for (i = 0; i <= j; i++)
* s++ = * res++;
* s = NULL;
printf("Scrittura terminata.\n");
exit(0);
}
void cancella(void) {
int indirizzo = 0;
int shmid;
key_t key;
char *shm, *s;
struct shmid_ds * shmid_ds;
int rtrn;
printf("Inserisci indirizzo (x per usare il default).\n");
rtrn = scanf("%d",&indirizzo);
if(rtrn!=0) {
printf("Indirizzo: %d \n",indirizzo);
key = (key_t)indirizzo;
}
else {
printf("Indirizzo: %d \n",KEY);
key = KEY;
}
/*
* Locate the segment.
*/
if ((shmid = shmget(key, SHMSZ, PERM)) < 0) {
perror("shmget");
exit(1);
}
/*
* Now we attach the segment to our data space.
*/
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
exit(1);
}
if ((rtrn = shmctl(shmid, IPC_RMID, shmid_ds)) == -1) {
perror("shmctl");
exit(1);
}
printf("Dati cancellati.\n");
exit(0);
}
main(int argc, char * argv[]) {
// int i;
//
// printf("argc = %d\n", argc);
//
// for (i = 0; i < argc; i++)
// printf("argv[%d] = \"%s\"\n", i, argv[i]);
//
// if ((argc!=2) ||
// ((argc==2) && (argv[1][0]!='s') && (argv[1][0]!='c'))) {
// printf("Usage: shm_server [s|c]\n");
// }
// else {
// printf("1\n");
// if (argv[1][0] == 's')
// scrivi();
// else {
// printf("2\n");
// cancella();
// }
// }
cancella();
}

View File

@@ -0,0 +1,4 @@
gcc -fPIC -o libSecUtility.so -shared -I/usr/java14/include -static-libgcc it_valueteam_securityutility_KeyJNIBridge.c

View File

@@ -0,0 +1,4 @@
gcc -o pswd.so pswd.c

View File

@@ -0,0 +1,87 @@
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <jni.h>
#include "it_valueteam_securityutility_KeyJNIBridge.h"
#define SHMSZ 27
//#define KEY 5678
#define KEY 5650
#define PERM 0600
JNIEXPORT jbyteArray JNICALL Java_it_valueteam_securityutility_KeyJNIBridge_readKey
(JNIEnv * env, jobject obj, jint indirizzo){
int shmid;
int i = 0;
key_t key;
char *shm, *s;
jbyteArray result;
char buffer[24] = "12345123451234512345123";
//key = KEY;
key = (key_t)indirizzo;
result = (*env)->NewByteArray(env,24);
if(result==NULL) {
printf("Allocazione fallita.\n");
}
if ((shmid = shmget(key, SHMSZ, PERM)) < 0) {
perror("shmget");
return NULL;
}
if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) {
perror("shmat");
return NULL;
}
for(s = shm; i<24; s++) {
buffer[i++] = *s;
}
(*env)->SetByteArrayRegion(env,result,0,24,buffer);
return result;
}
JNIEXPORT void JNICALL Java_it_valueteam_securityutility_KeyJNIBridge_writeKey
(JNIEnv * env, jobject obj, jint indirizzo, jbyteArray chiave) {
int shmid;
key_t key;
char * shm, *s;
int i;
jbyte *start;
//key = KEY;
key = (key_t)indirizzo;
printf("Inizio scrittura.\n");
/*
* Create the segment.
*/
if ((shmid = shmget(key, SHMSZ, IPC_CREAT | PERM)) < 0) {
perror("shmget");
exit(1);
}
/*
* Now we attach the segment to our data space.
*/
if ((shm = shmat(shmid, NULL, 0)) == (char * ) - 1) {
perror("shmat");
exit(1);
}
start = (*env)->GetByteArrayElements(env,chiave,NULL);
s = shm;
for(i=0;i<24;i++) {
* s++ = start[i];
}
(*env)->ReleaseByteArrayElements(env, chiave, start, 0);
}

View File

@@ -0,0 +1,29 @@
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class itm_valueteam_securityutility_KeyJNIBridge */
#ifndef _Included_it_valueteam_securityutility_KeyJNIBridge
#define _Included_it_valueteam_securityutility_KeyJNIBridge
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: it_valueteam_securityutility_KeyJNIBridge
* Method: readKey
* Signature: (I)[B
*/
JNIEXPORT jbyteArray JNICALL Java_it_valueteam_securityutility_KeyJNIBridge_readKey
(JNIEnv *, jobject, jint);
/*
* Class: it_valueteam_securityutility_KeyJNIBridge
* Method: writeKey
* Signature: (I[B)V
*/
JNIEXPORT void JNICALL Java_it_valueteam_securityutility_KeyJNIBridge_writeKey
(JNIEnv *, jobject, jint, jbyteArray);
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -0,0 +1,13 @@
#include <stdio.h>
#include <string.h>
main(int argc, char * argv[]) {
char * res;
res = getpass("Inserire valore: \n");
printf("%s",res);
}

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;
}
}