diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..474a868 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +*~ +*.class +*.pyc +*.o diff --git a/0001-HisAppraiser-Fixed-reading-of-host-name-from-the-rep.patch b/0001-HisAppraiser-Fixed-reading-of-host-name-from-the-rep.patch new file mode 100644 index 0000000..77e4e50 --- /dev/null +++ b/0001-HisAppraiser-Fixed-reading-of-host-name-from-the-rep.patch @@ -0,0 +1,28 @@ +From 0a317e92fc67fd6171ea1de011b72c77b0074680 Mon Sep 17 00:00:00 2001 +From: Nicola Barresi +Date: Fri, 4 Apr 2014 12:29:45 +0200 +Subject: [PATCH] HisAppraiser: Fixed reading of host name from the report ID + +This patch fixes a bug in the reading of the host name from the report +ID; it was executed not considering host names containing the character +"-". +--- + .../integrityReport/HisReportValidator.java | 2 +- + 1 file changed, 1 insertion(+), 1 deletion(-) + +diff --git a/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportValidator.java b/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportValidator.java +index 62696b3..16202cb 100755 +--- a/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportValidator.java ++++ b/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportValidator.java +@@ -341,7 +341,7 @@ public class HisReportValidator { + return; + } + +- String hostName = splittedReportId[0]; ++ String hostName = report.getID().split("-[^-]*-[^-]*$")[0]; + AuditLog lastAuditLog = new HisAuditDao().getLastAuditLog(hostName); + + if (!FIRST_IR && !lastAuditLog.getPcrIMLMask().equals(this.currentPcrIMLMask)) { +-- +1.7.9.5 + diff --git a/OAT-Appraiser-Base.spec b/OAT-Appraiser-Base.spec new file mode 100644 index 0000000..322f8c0 --- /dev/null +++ b/OAT-Appraiser-Base.spec @@ -0,0 +1,509 @@ +Name: OAT-Appraiser-Base +Summary: [OAT Crossbow] Host Integrity at Startup Installation of Appraiser Server +Version: 1.0.0 +Release: 2%{?dist} +License: DoD +Group: Department of Defense +Vendor: Department of Defense +Source0: OAT-Appraiser-Configure.tar.gz +BuildRoot: /var/tmp/OAT-Appraiser-Configure-%{PACKAGE_VERSION} + +%description +Host Integrity at Startup (OAT) is a project that explores how software and processes on standard desktop computers can be measured to detect and report important and specific changes which highlight potential compromise of the host platform. OAT provides the first examples of effective Measurement and Attestation on the path toward trusted platforms. + +%package OATapp +Summary: The OAT Appraiser Base Install +Group: Department of Defense +#we use mysql for OAT Appraiser, and php is needed for the web portal +#Requires: mysql, mysql-server, php, php-mysql +Requires: mariadb, mariadb-server, php, php-mysql +%description OATapp +The Host Integrity at Startup Installation +of the OAT Appraiser Server Base Install +%prep +%setup -n OAT-Appraiser-Configure +rm -rf $RPM_BUILD_ROOT +mkdir $RPM_BUILD_ROOT/ +cp -R $RPM_BUILD_DIR/OAT-Appraiser-Configure $RPM_BUILD_ROOT + +%post OATapp +echo -n "Making OAT Appraiser\n" + +#######Install script########################################################### + +service mysqld start +#TOMCAT_INSTALL_DIR=/usr/lib +#TOMCAT_INSTALL_DIR=$TOMCAT_DIR +#TOMCAT_DIR_COFNIG_TYPE=${TOMCAT_INSTALL_DIR//\//\\/} +##TOMCAT_NAME=apache-tomcat-6.0.35 +#TOMCAT_NAME=apache-tomcat-6.0.29 +#echo $TOMCAT_INSTALL_DIR > ~/rpm.log +#echo $TOMCAT_DIR_COFNIG_TYPE >> ~/rpm.log +TOMCAT_INSTALL_DIR=/usr/lib +TOMCAT_NAME=apache-tomcat-6.0.29 + +if [ -d /var/lib/oat-appraiser ] +then + rm -rf /var/lib/oat-appraiser + mkdir /var/lib/oat-appraiser + mkdir /var/lib/oat-appraiser/CaCerts + mkdir /var/lib/oat-appraiser/ClientFiles +else + mkdir /var/lib/oat-appraiser + mkdir /var/lib/oat-appraiser/CaCerts + mkdir /var/lib/oat-appraiser/ClientFiles +fi + +if [ -d /etc/oat-appraiser ] +then + rm -rf /etc/oat-appraiser + mkdir /etc/oat-appraiser +else + mkdir /etc/oat-appraiser +fi + +if [ $TOMCAT_DIR -a -d $TOMCAT_DIR ];then + if [[ ${TOMCAT_DIR:$((${#TOMCAT_DIR}-1)):1} == / ]];then + TOMCAT_DIR_TMP=${TOMCAT_DIR:0:$((${#TOMCAT_DIR}-1))} + else + TOMCAT_DIR_TMP=$TOMCAT_DIR + fi + + TOMCAT_INSTALL_DIR=${TOMCAT_DIR_TMP%/*} + TOMCAT_NAME=${TOMCAT_DIR_TMP##*/} +fi +TOMCAT_DIR_COFNIG_TYPE=${TOMCAT_INSTALL_DIR//\//\\/} +echo $TOMCAT_INSTALL_DIR > ~/rpm.log +echo $TOMCAT_DIR_COFNIG_TYPE >> ~/rpm.log + +###Random generation /dev/urandom is good but just in case... +# Creating randoms for the p12 files and setting up truststore and keystore +ip12="internal.p12" +ipassfile="internal.pass" +idomfile="internal.domain" +iloc="/OAT-Appraiser-Configure/" +p12file="$loc$ip12" +RAND1=$(dd if=/dev/urandom bs=1 count=1024) +RAND2=$(dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}') +RAND3=$(dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}') +randbits="$(echo "$( echo "`clock`" | md5sum | md5sum )$( echo "`dd if=/dev/urandom bs=1 count=1024`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum )$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum)$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum )" | md5sum | md5sum )" +randpass="${randbits:0:30}" +randbits2="$(echo "$( echo "`clock`" | md5sum | md5sum )$( echo "`dd if=/dev/urandom bs=1 count=1024`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum )$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum)$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum )" | md5sum | md5sum )" +randpass2="${randbits2:0:30}" +randbits3="$(echo "$( echo "`clock`" | md5sum | md5sum )$( echo "`dd if=/dev/urandom bs=1 count=1024`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum )$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum)$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum )" | md5sum | md5sum )" +randpass3="${randbits3:0:30}" +p12pass="$randpass" +mysqlPass="$randpass2" +keystore="keystore.jks" +truststore="TrustStore.jks" +if [ "`ls $iloc | grep $ip12`" ] && [ "`ls $iloc | grep $ipassfile`" ] ; then + p12pass="`cat $loc$ipassfile`" +fi +if [ "`ls $iloc | grep $idomfile`" ] ; then + domain="`cat $loc$idomfile`" +fi + + +service mysqld stop +service tomcat6 stop + +sleep 10 + +#Configuring mysqld so we can set up database and hisAppraiser profile + +#sed -i 's/--datadir="$datadir" --socket="$socketfile"/--datadir="$datadir" --skip-grant-tables --socket="$socketfile"/g' /etc/rc.d/init.d/mysqld + +service mysqld start + +#Sets up database and user +ISSKIPGRANTEXIT=`grep skip-grant-tables /etc/my.cnf` +if [ ! "$ISSKIPGRANTEXIT" ]; then + sed -i 's/\[mysqld\]/\[mysqld\]\nskip-grant-tables/g' /etc/my.cnf +fi + + +mysql -u root --execute="CREATE DATABASE oat_db; FLUSH PRIVILEGES; GRANT ALL ON oat_db.* TO 'oatAppraiser'@'localhost' IDENTIFIED BY '$randpass3';" + +service mysqld stop + +#sed -i 's/--datadir="$datadir" --socket="$socketfile"/--datadir="$datadir" --skip-grant-tables --socket="$socketfile"/g' /etc/rc.d/init.d/mysqld + + +#setting up tomcat at $TOMCAT_INSTALL_DIR/ +if [ $TOMCAT_NAME == apache-tomcat-6.0.29 ];then +rm -f $TOMCAT_INSTALL_DIR/apache-tomcat-6.0.29.tar.gz +mv /OAT-Appraiser-Configure/apache-tomcat-6.0.29.tar.gz $TOMCAT_INSTALL_DIR/. +fi + +unzip /OAT-Appraiser-Configure/service.zip -d /OAT-Appraiser-Configure/ +rm -f /OAT-Appraiser-Configure/service.zip + +#mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME $TOMCAT_INSTALL_DIR/apache-tomcat-old +if [ $TOMCAT_NAME == apache-tomcat-6.0.29 ];then +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME +tar -zxf $TOMCAT_INSTALL_DIR/apache-tomcat-6.0.29.tar.gz -C $TOMCAT_INSTALL_DIR/ +fi + +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/service +mv -f /OAT-Appraiser-Configure/service $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/service +#rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/Certificate +#mkdir $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/Certificate +rm -rf /var/lib/oat-appraiser/Certificate +mkdir /var/lib/oat-appraiser/Certificate +unzip /OAT-Appraiser-Configure/setupProperties.zip -d /OAT-Appraiser-Configure/ +mv /OAT-Appraiser-Configure/setup.properties /etc/oat-appraiser/ + +rm -R -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/* + +#chkconfig --del NetworkManager +chkconfig network on +chkconfig httpd --add +chkconfig httpd on +service httpd start +chkconfig mysqld on +service mysqld start + +#running OAT database full setup +#rm -rf /OAT-Appraiser-Configure/MySQLdrop.txt +#unzip /OAT-Appraiser-Configure/MySQLdrop.zip -d /OAT-Appraiser-Configure/ +#mysql -u root < /OAT-Appraiser-Configure/MySQLdrop.txt +rm -rf /OAT-Appraiser-Configure/OAT_Server_Install +unzip /OAT-Appraiser-Configure/OAT_Server_Install.zip -d /OAT-Appraiser-Configure/ +rm -rf /tmp/OAT_Server_Install +mv -f /OAT-Appraiser-Configure/OAT_Server_Install /tmp/OAT_Server_Install +mysql -u root --execute="DROP DATABASE IF EXISTS oat_db;" +mysql -u root < /tmp/OAT_Server_Install/oat_db.MySQL +mysql -u root < /tmp/OAT_Server_Install/init.sql +#setting up access control in tomcat context.xml +#sed -i "/<\/Context>/i\\ " $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/conf/context.xml + +sed -i "/<\/Context>/i\\ " $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/conf/context.xml + +#setting up port 8443 in tomcat server.xml +sed -i "s/ <\/Service>/<\/Service>/g" $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/conf/server.xml + + + +cp -R /tmp/OAT_Server_Install/HisWebServices $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/ +# +#if [ -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationAdminConsole.war ];then +# rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationAdminConsole.war +#fi +# +#if [ -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationManifestWebServices.war ];then +# rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationManifestWebServices.war +#fi +# +#if [ -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationWebServices.war ];then +# rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationWebServices.war +#fi + +cp /tmp/OAT_Server_Install/WLMService.war $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/ +cp /tmp/OAT_Server_Install/AttestationService.war $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/ +unzip $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/WLMService.war -d $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/WLMService +unzip $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/AttestationService.war -d $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/AttestationService +#delete the OpenAttestation war package +rm -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/WLMService.war +rm -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/AttestationService.war +mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/AttestationService/WEB-INF/classes/OpenAttestationWebServices.properties /etc/oat-appraiser/OpenAttestationWebServices.properties +sed -i "s//$(hostname)/g" /etc/oat-appraiser/OpenAttestationWebServices.properties +#configuring hibernateHis for OAT appraiser setup +cp /tmp/OAT_Server_Install/hibernateOat.cfg.xml /tmp/ +sed -i 's/root<\/property>/oatAppraiser<\/property>/' /tmp/hibernateOat.cfg.xml +sed -i "s/oat-password<\/property>/$randpass3<\/property>/" /tmp/hibernateOat.cfg.xml +cp /tmp/hibernateOat.cfg.xml $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisWebServices/WEB-INF/classes/ +cp /tmp/OAT_Server_Install/OAT.properties /etc/oat-appraiser/ +mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisWebServices/WEB-INF/classes/OpenAttestation.properties /etc/oat-appraiser/ +sed -i "s//$(hostname)/g" /etc/oat-appraiser/OpenAttestation.properties +sed -i "s/^truststore_path.*$/truststore_path=\/var\/lib\/oat-appraiser\/Certificate\/TrustStore.jks/g" /etc/oat-appraiser/OpenAttestation.properties + +sed -i "s/^TrustStore.*$/TrustStore=\/var\/lib\/oat-appraiser\/Certificate\/TrustStore.jks/g" /etc/oat-appraiser/OpenAttestation.properties + +mkdir -p /var/log/oat_ir +#placing OAT web portal in correct folder to be seen by tomcat6 +rm -rf /OAT-Appraiser-Configure/OAT +unzip /OAT-Appraiser-Configure/OAT.zip -d /OAT-Appraiser-Configure/ +rm -rf /var/www/html/OAT +mv -f /OAT-Appraiser-Configure/OAT /var/www/html/OAT + +#setting all files in the OAT portal to be compiant to selinux +/sbin/restorecon -R '/var/www/html/OAT' + +#setting the user and password in the OAT appraiser that will be used to access the mysql database. +sed -i 's/user = "root"/user = "oatAppraiser"/g' /var/www/html/OAT/includes/dbconnect.php +sed -i "s/pass = \"newpwd\"/pass = \"$randpass3\"/g" /var/www/html/OAT/includes/dbconnect.php + +#setting up OAT database to talk with the web portal correctly +rm -f /OAT-Appraiser-Configure/oatSetup.txt +unzip /OAT-Appraiser-Configure/oatSetup.zip -d /OAT-Appraiser-Configure/ +mysql -u root --database=oat_db < /OAT-Appraiser-Configure/oatSetup.txt + + +# This is setting the OAT mysql user to the password given to the Appraiser +#mysql -u root --database=mysql --execute="UPDATE user SET password=PASSWORD('newpwd') WHERE user='hisAppraiser';" +service mysqld stop + +#sets configuration of mysql back to normal +#sed -i 's/--datadir="$datadir" --skip-grant-tables --socket="$socketfile"/--datadir="$datadir" --socket="$socketfile"/g' /etc/rc.d/init.d/mysqld +ISSKIPGRANTEXIT=`grep nskip-grant-tables /etc/my.cnf` +if [ "$ISSKIPGRANTEXIT" ]; then + sed -i 's/\[mysqld\]\nskip-grant-tables/\[mysqld\]g' /etc/my.cnf +fi + + +service mysqld start + + +#this code sets up the certificate attached to this computers hostname +cd /var/lib/oat-appraiser/Certificate/ +echo "127.0.0.1 `hostname`" >> /etc/hosts +if [ "`echo $p12pass | grep $randpass`" ] ; then + openssl req -x509 -nodes -days 730 -newkey rsa:2048 -keyout hostname.pem -out hostname.cer -subj "/C=US/O=U.S. Government/OU=DoD/CN=`hostname`" + openssl pkcs12 -export -in hostname.cer -inkey hostname.pem -out $p12file -passout pass:$p12pass +fi + +keytool -importkeystore -srckeystore $p12file -destkeystore $keystore -srcstoretype pkcs12 -srcstorepass $p12pass -deststoretype jks -deststorepass $p12pass -noprompt + +myalias=`keytool -list -v -keystore $keystore -storepass $p12pass | grep -B2 'PrivateKeyEntry' | grep 'Alias name:'` + +keytool -changealias -alias ${myalias#*:} -destalias tomcat -v -keystore $keystore -storepass $p12pass + +rm -f $truststore +keytool -import -keystore $truststore -storepass password -file hostname.cer -noprompt + +#sets up the tomcat6 service +chmod -R 755 $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/service/* +cp $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/service/tomcat6 /etc/rc.d/init.d/ +sed -i "s/killproc \$PROC/daemon \$CATALINA_BIN stop/g" /etc/rc.d/init.d/tomcat6 +chkconfig tomcat6 --add +chkconfig tomcat6 on + +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2.war + +# TOAT IS THE BEGINNING OF THE PCA PORTION +#rm -rf /OAT-Appraiser-Configure/OAT_PrivacyCA_Install +#unzip /OAT-Appraiser-Configure/OAT_PrivacyCA_Install.zip -d /OAT-Appraiser-Configure/ +#rm -rf /tmp/OAT_PrivacyCA_Install +#mv /OAT-Appraiser-Configure/OAT_PrivacyCA_Install /tmp/OAT_PrivacyCA_Install + +chmod 777 /tmp +sleep 10 +#catalina.sh +sed -i "/^#CATALINA_BIN/d" /etc/init.d/tomcat6 +sed -i "s/^CATALINA_BIN/#CATALINA_BIN/g" /etc/init.d/tomcat6 +sed -i "/^#CATALINA_BIN/i\\CATALINA_BIN=\'$TOMCAT_INSTALL_DIR/$TOMCAT_NAME/bin/catalina.sh 1> /dev/null\';" /etc/init.d/tomcat6 + +service tomcat6 start + +# TOAT FOR LOOP IS NEEDED TO MAKE SURE THAT TOMCAT6 IS STARTED WELL BEFORE THE .WAR FILE IS MOVED +for((i = 1; i < 60; i++)) +do + + rm -f ./serviceLog + + service tomcat6 status | grep "is running" >> ./serviceLog + + if [ -s ./serviceLog ]; then + + echo tomcat6 has started! + rm -f ./serviceLog + sleep 10 + break + fi + + sleep 1 + + echo If this file is present after install then starting tomcat6 timed-out >> serviceLog + +done + +#moves the war file to webapps folder to unpack it +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2.war +cp /OAT-Appraiser-Configure/HisPrivacyCAWebServices2.war $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/ + +# This for loop makes the rpm wait until the .war file has unpacked before attempting to access the files that will be created +for((i = 1; i < 60; i++)) +do + + rm -f ./warLog + if [ -e /var/lib/oat-appraiser -a -e /var/lib/oat-appraiser/ClientFiles/OATprovisioner.properties ]; then +# if [ -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2 -a -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/OATprovisioner.properties ]; then + + + echo the Privacy CA was unpacked! + rm -f ./warLog + sleep 5 + break + fi + + sleep 1 + + echo If this file is present after install then unpacking the Privacy CA war file timed-out >> warLog + +done + +#this is a script to re-run certificate creation using new p12 files after installation +rm -rf /OAT-Appraiser-Configure/clientInstallRefresh.sh +rm -rf /OAT-Appraiser-Configure/linuxClientInstallRefresh.sh +cur_dir=$(pwd) +unzip /OAT-Appraiser-Configure/clientInstallRefresh.zip -d /OAT-Appraiser-Configure/ +unzip /OAT-Appraiser-Configure/linuxClientInstallRefresh.zip -d /OAT-Appraiser-Configure/ +cd /OAT-Appraiser-Configure/ +sed -i "s/\/usr\/lib\/apache-tomcat-6.0.29/$TOMCAT_DIR_COFNIG_TYPE\/$TOMCAT_NAME/g" clientInstallRefresh.sh +sed -i "s/\/usr\/lib\/apache-tomcat-6.0.29/$TOMCAT_DIR_COFNIG_TYPE\/$TOMCAT_NAME/g" linuxClientInstallRefresh.sh + +mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/lib /var/lib/oat-appraiser/ClientFiles/ +mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/TPMModule.properties /var/lib/oat-appraiser/ClientFiles/ +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/ +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/CaCerts +rm -rf clientInstallRefresh.zip +rm -rf linuxClientInstallRefresh.zip + +zip -9 linuxClientInstallRefresh.zip linuxClientInstallRefresh.sh +zip -9 clientInstallRefresh.zip clientInstallRefresh.sh +cp -rf linuxClientInstallRefresh.zip /tmp +cd $cur_dir + +rm -rf /OAT-Appraiser-Configure/installers +#unzip /OAT-Appraiser-Configure/ClientInstall.zip -d /OAT-Appraiser-Configure/ +unzip /OAT-Appraiser-Configure/ClientInstallForLinux.zip -d /OAT-Appraiser-Configure/ + +sleep 5 + +mv /OAT-Appraiser-Configure/ClientInstallForLinux.zip /OAT-Appraiser-Configure/ClientInstallForLinuxOld.zip + +rm -rf /OAT-Appraiser-Configure/ClientInstallForLinux + +cp -r -f /OAT-Appraiser-Configure/linuxOatInstall /OAT-Appraiser-Configure/ClientInstallForLinux + + +cp -rf /OAT-Appraiser-Configure/OAT_Standalone.jar /OAT-Appraiser-Configure/ClientInstallForLinux/ +cp -rf /OAT-Appraiser-Configure/lib /OAT-Appraiser-Configure/ClientInstallForLinux/ +cp -r -f /var/lib/oat-appraiser/ClientFiles/PrivacyCA.cer /OAT-Appraiser-Configure/ClientInstallForLinux/ +cp -r -f /var/lib/oat-appraiser/ClientFiles/TrustStore.jks /OAT-Appraiser-Configure/ClientInstallForLinux/ +cp -r -f /var/lib/oat-appraiser/ClientFiles/OATprovisioner.properties /OAT-Appraiser-Configure/ClientInstallForLinux/ +cp -r -f /var/lib/oat-appraiser/ClientFiles/OAT.properties /OAT-Appraiser-Configure/ClientInstallForLinux/ +sed -i '/ClientPath/s/C:.*/\/OAT/' /OAT-Appraiser-Configure/ClientInstallForLinux/OATprovisioner.properties +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/OAT.properties /OAT-Appraiser-Configure/ClientInstallForLinux/ +sed -i 's/NIARL_TPM_Module\.exe/NIARL_TPM_Module/g' /OAT-Appraiser-Configure/ClientInstallForLinux/OAT.properties +sed -i 's/HIS07\.jpg/OAT07\.jpg/g' /OAT-Appraiser-Configure/ClientInstallForLinux/OAT.properties +cd /OAT-Appraiser-Configure/; zip -9 -r ClientInstallForLinux.zip ClientInstallForLinux + +#places the client installation folder up for tomcat6 to display +cp -f /OAT-Appraiser-Configure/ClientInstallForLinux.zip /var/www/html/ + + +#creates the web page that allows access for the download of the client files folder +echo "" >> /var/www/html/ClientInstaller.html +echo "" >> /var/www/html/ClientInstaller.html +#echo "

Client Installation Files

" >> /var/www/html/ClientInstaller.html +echo "

Client Installation Files For Linux

" >> /var/www/html/ClientInstaller.html +echo "" >> /var/www/html/ClientInstaller.html +echo "" >> /var/www/html/ClientInstaller.html + +chmod 755 /var/www/html/Client* + + +#closes some known security holes in tomcat6 +sed -i "s/AllowOverride None/AllowOverride All/" /etc/httpd/conf/httpd.conf +echo "TraceEnable Off" >> /etc/httpd/conf/httpd.conf +sed -i "s/ServerTokens OS/ServerTokens Prod/" /etc/httpd/conf/httpd.conf +sed -i "s/Options Indexes/Options/" /etc/httpd/conf/httpd.conf +sed -i "s/expose_php = On/expose_php = Off/" /etc/php.ini + +rm -f /etc/httpd/conf.d/welcome.conf +echo "" >> /etc/httpd/conf.d/welcome.conf + +/sbin/restorecon -R '/var/www/html/OAT' + +service tomcat6 restart +####################################################################### +printf "done\n" + +%postun OATapp +#HAPCrpmremoval.sh script********************************************** +TOMCAT_INSTALL_DIR2=/usr/lib +TOMCAT_NAME2=apache-tomcat-6.0.29 + +if [ $TOMCAT_DIR -a -d $TOMCAT_DIR ];then + if [[ ${TOMCAT_DIR:$((${#TOMCAT_DIR}-1)):1} == / ]];then + TOMCAT_DIR_TMP=${TOMCAT_DIR:0:$((${#TOMCAT_DIR}-1))} + else + TOMCAT_DIR_TMP=$TOMCAT_DIR + fi + + TOMCAT_INSTALL_DIR2=${TOMCAT_DIR_TMP%/*} + TOMCAT_NAME2=${TOMCAT_DIR_TMP##*/} +fi + +sed -i "/<\/Service>/d" $TOMCAT_INSTALL_DIR2/$TOMCAT_NAME2/conf/server.xml +sed -i "/<\/Server>/i\\ <\/Service>" $TOMCAT_INSTALL_DIR2/$TOMCAT_NAME2/conf/server.xml +rm -rf /OAT-Appraiser-Configure/ +#stop tomcat service and remove apache-tomcat +kill -9 `ps -ef | grep tomcat | grep -v grep | awk '{print $2}'` +if [ -d $TOMCAT_INSTALL_DIR2/apache-tomcat-6.0.29 ];then +rm -f -r $TOMCAT_INSTALL_DIR2/apache-tomcat-6.0.29.tar.gz +rm -rf $TOMCAT_INSTALL_DIR2/apache-tomcat-6.0.29 +fi + +if [ -d /etc/oat-appraiser ] +then +rm -rf /etc/oat-appraiser +fi + +if [ -d /var/lib/oat-appraiser ] +then +rm -rf /var/lib/oat-appraiser +fi + +#OAT_Server +rm -f -r /tmp/OAT_Server_Install +rm -f -r /var/www/html/OAT + +#OAT_PrivacyCA +#rm -f -r /tmp/OAT_PrivacyCA_Install +#rm -f -r /var/www/html/ClientInstall.zip +rm -f -r /var/www/html/ClientInstallForLinux.zip +rm -f -r /var/www/html/ClientInstaller.html + +#removes both the OAT mysql database and the hisAppraiser mysql user + +service mysqld stop +#sed -i 's/--datadir="$datadir" --socket="$socketfile"/--datadir="$datadir" --skip-grant-tables --socket="$socketfile"/g' /etc/rc.d/init.d/mysqld + +service mysqld start +mysql -u root --execute="FLUSH PRIVILEGES; DROP DATABASE IF EXISTS oat_db; DELETE FROM mysql.user WHERE User='oatAppraiser' and Host='localhost';" + +printf "OAT database removed\n" + +service mysqld stop + +#sed -i 's/--datadir="$datadir" --skip-grant-tables --socket="$socketfile"/--datadir="$datadir" --socket="$socketfile"/g' /etc/rc.d/init.d/mysqld + +service mysqld start + + +#********************************************************************** + +%clean +rm -rf $RPM_BUILD_ROOT + + +%files OATapp +/OAT-Appraiser-Configure/apache-tomcat-6.0.29.tar.gz +/OAT-Appraiser-Configure/clientInstallRefresh.zip +/OAT-Appraiser-Configure/linuxClientInstallRefresh.zip +/OAT-Appraiser-Configure/ClientInstallForLinux.zip +/OAT-Appraiser-Configure/HisPrivacyCAWebServices2.war +/OAT-Appraiser-Configure/OAT_Server_Install.zip +/OAT-Appraiser-Configure/oatSetup.zip +/OAT-Appraiser-Configure/OAT.zip +/OAT-Appraiser-Configure/MySQLdrop.zip +/OAT-Appraiser-Configure/service.zip +/OAT-Appraiser-Configure/setupProperties.zip +/OAT-Appraiser-Configure/OAT.sh +/OAT-Appraiser-Configure/OAT_Standalone.jar +/OAT-Appraiser-Configure/lib +/OAT-Appraiser-Configure/log4j.properties diff --git a/OpenAttestation/CommandTool/README b/OpenAttestation/CommandTool/README new file mode 100644 index 0000000..f598735 --- /dev/null +++ b/OpenAttestation/CommandTool/README @@ -0,0 +1,79 @@ + +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* +^* CERT ^* +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* +bash oat_cert -h his8 + +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* +^* OEM ^* +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* +bash oat_oem -a -h his8 '{"Name":"OEM1","Description":"Newdescription"}' + +bash oat_oem -e -h his8 '{"Name":"OEM1","Description":"Mooooooooodify"}' + +bash oat_oem -d -h his8 '{"Name":"OEM1"}' + +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* +^* OS ^* +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* +bash oat_os -a -h his8 '{"Name":"OS1","Version":"v1","Description":"Test1"}' + +bash oat_os -e -h his8 '{"Name":"OS1","Version":"v1","Description":"Mooooooooodify"}' + +bash oat_os -d -h his8 '{"Name":"OS1","Version":"v1"}' + +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* +^* MLE ^* +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* +#VMM +bash oat_mle -a -h his8 '{"Name":"NewMLE2","Version":"v123","OsName":"OS1","OsVersion":"v1","Attestation_Type": "PCR","MLE_Type":"VMM","Description":"Test","MLE_Manifests": [{"Name": "18", "Value": "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"}]}' + +#BIOS +bash oat_mle -a -h his8 '{"Name":"NewMLE1","Version":"v123","OemName":"OEM1","Attestation_Type": "PCR","MLE_Type":"BIOS","Description":"MLETest1111","MLE_Manifests": [{"Name": "0", "Value": "31B97D97B4679917EC3C1D943635693FFBAB4143"}]}' + +bash oat_mle -e -h his8 '{"Name":"NewMLE1","Version":"v123","OemName":"OEM1","Attestation_Type": "PCR","MLE_Type":"BIOS","Description":"03JR84","MLE_Manifests": [{"Name": "0", "Value": "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"}]}' + +bash oat_mle -d -h his8 '{"mleName":"NewMLE1","mleVersion":"v123","oemName":"OEM1"}' + +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* +^* HOST ^* +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* +bash oat_host -a -h his8 '{"HostName":"his8","IPAddress":"192.168.1.1","Port":"9999","BIOS_Name":"NewMLE1","BIOS_Version":"v123","BIOS_Oem":"OEM1","VMM_Name":"NewMLE2","VMM_Version":"v123","VMM_OSName":"OS1","VMM_OSVersion":"v1","Email":"","AddOn_Connection_String":"","Description":""}' + +bash oat_host -e -h his8 '{"HostName":"his8","IPAddress":"192.168.1.1","Port":"9999","BIOS_Name":"NewMLE1","BIOS_Version":"v123","BIOS_Oem":"OEM1","VMM_Name":"NewMLE2","VMM_Version":"v123","VMM_OSName":"OS1","VMM_OSVersion":"v1","Email":"quan.xu@intel.com","AddOn_Connection_String":"Moooooodify","Description":"Y"}' + +bash oat_host -d -h his8 '{"hostName":"his8"}' + +bash oat_host -s -h his8 '{rhel}' + +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* +^* POLLHOSTS ^* +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* +bash oat_pollhosts -h his8 '{"hosts":["his8"]}' + +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* +^* PCR_WHITE_LIST ^* +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* +#oem +bash oat_pcrwhitelist -a -h his8 '{"pcrName":"8","pcrDigest":"DE1343582097C9BC739C9311D60B5B5F5603A", "mleName":"NewMLE1","mleVersion":"v123", "oemName": "OEM1"}' +bash oat_pcrwhitelist -e -h his8 '{"pcrName":"8","pcrDigest":"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "mleName":"NewMLE1","mleVersion":"v123", "oemName": "OEM1"}' +bash oat_pcrwhitelist -d -h his8 '{"pcrName":"8","mleName":"NewMLE1","mleVersion":"v123","oemName":"OEM1"}' + +#os +bash oat_pcrwhitelist -a -h his8 '{"pcrName":"5","pcrDigest":"DE1343582097C9BC739C9311D60B5B5F5603A","mleName":"NewMLE2","mleVersion":"v123","osName":"OS1","osVersion":"v1"}' +bash oat_pcrwhitelist -e -h his8 '{"pcrName":"5","pcrDigest":"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", "mleName":"NewMLE2","mleVersion":"v123","osName":"OS1","osVersion":"v1"}' +bash oat_pcrwhitelist -d -h his8 '{"pcrName":"5","mleName":"NewMLE2","mleVersion":"v123","osName":"OS1","osVersion":"v1"}' + +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* +^* VIEW ^* +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* + +bash oat_view_os -h his8 +bash oat_view_oem -h his8 +bash oat_view_mle -h his8 '{"mleName":"NewMLE1","mleVersion":"v123","oemName":"OEM1"}' + +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* +^* MLE_SEARCH ^* +^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^*^* + +bash oat_mle_search -h his8 '{OEM1}' diff --git a/OpenAttestation/CommandTool/add_NED.sh b/OpenAttestation/CommandTool/add_NED.sh new file mode 100644 index 0000000..ceb8c5b --- /dev/null +++ b/OpenAttestation/CommandTool/add_NED.sh @@ -0,0 +1,22 @@ +#! /bin/bash + +OAT=$1 +HOST=$2 +HOSTIP=$3 +HOSTPCR0=$4 +HOSTDISTRO=$5 +HOSTCERTDGST=$6 + +if [ -z "$OAT" ] || [ -z "$HOST" ] || [ -z "$HOSTIP" ] || [ -z "$HOSTPCR0" ] || [ -z "$HOSTDISTRO" ] || [ -z "$HOSTCERTDGST" ]; then + echo "Missing parameters" + exit 1 +fi + +set -x + +bash oat_mle -a -h $OAT '{"Name":"'$HOST'-'$HOSTDISTRO'","Version":"123","OsName":"'$HOSTDISTRO'","OsVersion":"v1234","Attestation_Type": "PCR","MLE_Type":"VMM","Description":"Test ad"}' +bash oat_host -a -h $OAT '{"HostName":"'$HOST'","IPAddress":"'$HOSTIP'","Port":"9999","VMM_Name":"'$HOST'-'$HOSTDISTRO'","VMM_Version":"123","VMM_OSName":"'$HOSTDISTRO'","VMM_OSVersion":"v1234","Email":"","AddOn_Connection_String":"","Description":"'$HOSTCERTDGST'"}' +bash oat_pcrwhitelist -a -h $OAT '{"pcrName":"0","pcrDigest":"'$HOSTPCR0'","mleName":"'$HOST'-'$HOSTDISTRO'","mleVersion":"123", "osName":"'$HOSTDISTRO'", "osVersion":"v1234"}' + + +set +x diff --git a/OpenAttestation/CommandTool/configure_oat.sh b/OpenAttestation/CommandTool/configure_oat.sh new file mode 100644 index 0000000..d950c36 --- /dev/null +++ b/OpenAttestation/CommandTool/configure_oat.sh @@ -0,0 +1,30 @@ +#! /bin/bash + +OAT=$1 +HOST=$2 +HOSTIP=$3 +HOSTPCR0=$4 +HOSTDISTRO=$5 +RAPATH=$6 +DBIP=$7 +HOSTCERTDGST=$8 + +if [ -z "$OAT" ] || [ -z "$HOST" ] || [ -z "$HOSTIP" ] || [ -z "$HOSTPCR0" ] || [ -z "$HOSTDISTRO" ] || [ -z "$RAPATH" ] || [ -z "$DBIP" ] || [ -z "$HOSTCERTDGST" ]; then + echo "Missing parameters" + exit 1 +fi + +set -x + +#bash oat_cert -h $OAT +bash oat_oem -a -h $OAT '{"Name":"OEM1","Description":"Test id"}' +bash oat_os -a -h $OAT '{"Name":"'$HOSTDISTRO'","Version":"v1234","Description":"Test1"}' +bash oat_mle -a -h $OAT '{"Name":"'$HOST'-'$HOSTDISTRO'","Version":"123","OsName":"'$HOSTDISTRO'","OsVersion":"v1234","Attestation_Type": "PCR","MLE_Type":"VMM","Description":"Test ad"}' +bash oat_host -a -h $OAT '{"HostName":"'$HOST'","IPAddress":"'$HOSTIP'","Port":"9999","VMM_Name":"'$HOST'-'$HOSTDISTRO'","VMM_Version":"123","VMM_OSName":"'$HOSTDISTRO'","VMM_OSVersion":"v1234","Email":"","AddOn_Connection_String":"","Description":"'$HOSTCERTDGST'"}' +bash oat_pcrwhitelist -a -h $OAT '{"pcrName":"0","pcrDigest":"'$HOSTPCR0'","mleName":"'$HOST'-'$HOSTDISTRO'","mleVersion":"123", "osName":"'$HOSTDISTRO'", "osVersion":"v1234"}' +bash oat_analysisType -a -h $OAT '{"name":"load-time+check-cert","module":"RAVerifier","version":2,"url":"'$RAPATH' -H '$DBIP'"}' +bash oat_analysisType -a -h $OAT '{"name":"VALIDATE_PCR;load-time+check-cert","module":"RAVerifier","version":2,"url":"'$RAPATH' -H '$DBIP'"}' +bash oat_analysisType -a -h $OAT '{"name":"load-time","module":"RAVerifier","version":2,"url":"'$RAPATH' -H '$DBIP'"}' + + +set +x diff --git a/OpenAttestation/CommandTool/oat_analysisType b/OpenAttestation/CommandTool/oat_analysisType new file mode 100644 index 0000000..191c3f2 --- /dev/null +++ b/OpenAttestation/CommandTool/oat_analysisType @@ -0,0 +1,82 @@ +#!/bin/bash +#create mles script + +ADD_PARM="-a" +DEL_PARM="-d" +GET_PARM="-g" +HOST_PARM="-h" +HOST_NAME="" +INFO="" +PORT=8443 +ShowAnalysisTypeExample() +{ + echo "AnalysisType Example:" + echo -e "Add AnalysisType example:\n\033[31;49;5;1m bash oat_analysisType -a -h HOSTNAME_OF_OAT-APPRAISER '{\"name\":\"ANALYSIS_NAME\",\"module\":\"MODULE_NAME\",\"version\":VERSION_NUMBER,\"url\":\"SCRIPT_URL\",\"requiredPcrMask\":\"HEX_PCR_MASK\"}' \033[0m" + echo -e "Del AnalysisType example:\n\033[31;49;5;1m bash oat_analysisType -d -h HOSTNAME_OF_OAT-APPRAISER '{\"name\":\"ANALYSIS_NAME\"}'\033[0m" + echo -e "Get AnalysisType example:\n\033[31;49;5;1m bash oat_analysisType -g -h HOSTNAME_OF_OAT-APPRAISER\033[0m" +} + +if [ $# -lt 3 ];then + echo "parm num error!" + ShowAnalysisTypeExample + exit 0 +fi + +if [ ! -z $OAT_CERTFILE ] && [ -e $OAT_CERTFILE ];then + echo " " +else + OAT_CERTFILE="certfile.cer" +fi + +if [ $2 != $HOST_PARM ];then + echo "-h parm error!" + ShowAnalysisTypeExample + exit 1 +else + HOST_NAME="$3" +fi + +if [ $1 == $DEL_PARM ];then + INFO="`echo "$4" | awk -F{ '{print $2}'| awk -F} '{print $1}'\ + | sed 's/\"//g' | sed 's/:/=/g' | sed 's/,/\&/g'| sed 's/ /%20/g' | sed 's/\+/%2B/g'`" +else + INFO="$4" +fi + +addAnalysisType() +{ + curl --cacert $OAT_CERTFILE -H "Content-Type: application/json" \ + -X POST -d "$INFO" "https://$HOST_NAME:$PORT/WLMService/resources/analysisTypes" +} + +delAnalysisType() +{ + curl --cacert $OAT_CERTFILE \ + -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/analysisTypes?$INFO" +} + +getAnalysisType() +{ + curl --cacert $OAT_CERTFILE \ + -X GET "https://$HOST_NAME:$PORT/WLMService/resources/analysisTypes" | python -mjson.tool +} + +case $1 in + $ADD_PARM) + echo "add AnalysisType:" + addAnalysisType + ;; + $DEL_PARM) + echo "del AnalysisType:" + delAnalysisType + ;; + $GET_PARM) + echo "get AnalysisType:" + getAnalysisType + ;; + *) + echo "Usage oat_AnalysisTypes {-a|-d|-g}" + ShowAnalysisTypeExample + exit 3 +esac +echo -e "\n" diff --git a/OpenAttestation/CommandTool/oat_cert b/OpenAttestation/CommandTool/oat_cert new file mode 100644 index 0000000..43f3163 --- /dev/null +++ b/OpenAttestation/CommandTool/oat_cert @@ -0,0 +1,32 @@ +#!/bin/bash +#create oat cert +PARM="-h" +PORT="8443" +ShowExample() +{ + echo -e "Create cert example:\033[31;49;5;1m$1\033[0m" +} + +if [ $# -lt 2 ];then + echo "parm num error!" + ShowExample "bash oat_cert -h HOSTNAME_OF_OAT-APPRAISER" + exit 0 +fi + +if [ ! -z $OAT_CERTFILE ];then + echo " " +else + OAT_CERTFILE="certfile.cer" +fi + +if [ $1 != $PARM ];then + echo "parm error!" + ShowExample "bash oat_cert -h HOSTNAME_OF_OAT-APPRAISER" + exit 0 +fi +if [ -e ./$OAT_CERTFILE ];then + rm -f $OAT_CERTFILE +fi + +HOST_NAME="$2" +openssl s_client -connect "$HOST_NAME":$PORT -cipher DHE-RSA-AES256-SHA|tee $OAT_CERTFILE diff --git a/OpenAttestation/CommandTool/oat_host b/OpenAttestation/CommandTool/oat_host new file mode 100644 index 0000000..bc7c004 --- /dev/null +++ b/OpenAttestation/CommandTool/oat_host @@ -0,0 +1,100 @@ +#!/bin/bash +#create mles/whitelist/pcr script +ADD_PARM="-a" +EDIT_PARM="-e" +DEL_PARM="-d" +HOST_PARM="-h" +SEARCH_PARM="-s" +HOST_NAME="" +INFO="" +PORT=8443 + +ShowHostExample() +{ + echo "Host Example:" + echo -e "Add Host example:\n\033[31;49;5;1m bash oat_host -a -h HOSTNAME_OF_OAT-APPRAISER '{\"HostName\":\"HOSTNAME-CLIENT\",\"IPAddress\":\"IP_ADDRESS\",\"Port\":\"PORT\",\"BIOS_Name\":\"MLE_NAME_OF_BIOS_TYPE\",\"BIOS_Version\":\"MLE_VERSION\",\"BIOS_Oem\":\"OEM_NAME\",\"VMM_Name\":\"MLE_NAME_OF_VMM_TYPE\",\"VMM_Version\":\"MLE_VERSION\",\"VMM_OSName\":\"OS_NAME\",\"VMM_OSVersion\":\"OS_VERSION\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}'\033[0m" + + echo -e "Edit Host example:\n\033[31;49;5;1m bash oat_host -e -h HOSTNAME_OF_OAT-APPRAISER '{\"HostName\":\"HOSTNAME-CLIENT\",\"IPAddress\":\"IP_ADDRESS\",\"Port\":\"PORT\",\"BIOS_Name\":\"MLE_NAME_OF_BIOS_TYPE\",\"BIOS_Version\":\"MLE_VERSION\",\"BIOS_Oem\":\"OEM_NAME\",\"VMM_Name\":\"MLE_NAME_OF_VMM_TYPE\",\"VMM_Version\":\"MLE_VERSION\",\"VMM_OSName\":\"OS_NAME\",\"VMM_OSVersion\":\"OS_VERSION\",\"Email\":\"E-MAIL\",\"AddOn_Connection_String\":\"Moooooodify\",\"Description\":\"Moooooodify\"}'\033[0m" + + echo -e "Del Host example:\n\033[31;49;5;1m bash oat_host -d -h HOSTNAME_OF_OAT-APPRAISER '{\"hostName\":\"HOSTNAME-CLIENT\"}'\033[0m" + echo -e "Host Search example:\n\033[31;49;5;1m bash oat_host -s -h HOSTNAME_OF_OAT-APPRAISER '{KEY}' \033[0m" +} + +if [ $# -lt 4 ];then + echo "parm num error!" + ShowHostExample + exit 0 +fi + +if [ ! -z $OAT_CERTFILE ] && [ -e $OAT_CERTFILE ];then + echo " " +else + OAT_CERTFILE="certfile.cer" +fi + +if [ $2 != $HOST_PARM ];then + echo "-h parm error!" + ShowHostExample + exit 1 +else + HOST_NAME="$3" +fi + +if [ $1 == $DEL_PARM ];then + INFO="`echo $4 | awk -F{ '{print $2}' | awk -F} '{print $1}' | sed 's/\"//g' | \ + sed 's/:/=/g' | sed 's/,/\&/g' | sed 's/ /%20/g'`" +elif [ $1 == $SEARCH_PARM ]; then + INFO="`echo $4 | awk -F{ '{print $2}' | awk -F} '{print $1}' | sed 's/ /%20/g'`" +else + INFO="$4" +fi + +echo $INFO + +addHOST() +{ + curl --cacert $OAT_CERTFILE -H "Content-Type: application/json" \ + -X POST -d "$INFO" "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" +} + +editHOST() +{ + curl --cacert $OAT_CERTFILE -H "Content-Type: application/json" \ + -X PUT -d "$INFO" "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" +} + +delHOST() +{ + curl --cacert $OAT_CERTFILE \ + -X DELETE "https://$HOST_NAME:$PORT/AttestationService/resources/hosts?$INFO" +} + +searchHOST() +{ + curl --cacert $OAT_CERTFILE -H "Content-Type: application/json" \ + -X GET "https://$HOST_NAME:$PORT/AttestationService/resources/hosts?searchCriteria=$INFO" +} + +case $1 in + $ADD_PARM) + echo "add HOST:" + addHOST + ;; + $EDIT_PARM) + echo "edit HOST:" + editHOST + ;; + $DEL_PARM) + echo "del HOST:" + delHOST + ;; + $SEARCH_PARM) + echo "search HOST:" + searchHOST + ;; + *) + echo "Usage oat_host {-a|-e|-d|-s}" + ShowHostExample + exit 3 +esac +echo -e "\n" diff --git a/OpenAttestation/CommandTool/oat_mle b/OpenAttestation/CommandTool/oat_mle new file mode 100644 index 0000000..4e25499 --- /dev/null +++ b/OpenAttestation/CommandTool/oat_mle @@ -0,0 +1,86 @@ +#!/bin/bash +#create mles script + +ADD_PARM="-a" +EDIT_PARM="-e" +DEL_PARM="-d" +HOST_PARM="-h" +HOST_NAME="" +INFO="" +PORT=8443 +ShowMleExample() +{ + echo "MLE with VMM:" + echo -e "Add MLE example:\n\033[31;49;5;1m bash oat_mle -a -h HOSTNAME_OF_OAT-APPRAISER '{\"Name\":\"MLE_NAME\",\"Version\":\"MLE_VERSION\",\"OsName\":\"OS_NAME\",\"OsVersion\":\"OS_VERSION\",\"Attestation_Type\": \"PCR\",\"MLE_Type\":\"VMM\",\"Description\":\"DESCRIPTION\",\"MLE_Manifests\": [{\"Name\": \"PCR_NUM\", \"Value\": \"PCR_VALUE\"}],\"pcrIMLMask\":\"HEX_PCR_MASK\"}' \033[0m" + echo -e "Edit MLE example:\n\033[31;49;5;1m bash oat_mle -e -h HOSTNAME_OF_OAT-APPRAISER '{\"Name\":\"MLE_NAME\",\"Version\":\"MLE_VERSION\",\"OsName\":\"OS_NAME\",\"OsVersion\":\"OS_VERSION\",\"Attestation_Type\": \"PCR\",\"MLE_Type\":\"VMM\",\"Description\":\"DESCRIPTION\",\"MLE_Manifests\": [{\"Name\": \"PCR_NUM\", \"Value\": \"PCR_VALUE\"}],\"pcrIMLMask\":\"HEX_PCR_MASK\"}' \033[0m" + echo -e "Del MLE example:\n\033[31;49;5;1m bash oat_mle -d -h HOSTNAME_OF_OAT-APPRAISER '{\"mleName\":\"MLE_NAME\",\"mleVersion\":\"MLE_VERSION\",\"osName\":\"OS_NAME\",\"osVersion\":\"OS_VERSION\"}'\033[0m" + echo "MLE with BIOS:" + echo -e "Add MLE example:\n\033[31;49;5;1m bash oat_mle -a -h HOSTNAME_OF_OAT-APPRAISER '{\"Name\":\"MLE_NAME\",\"Version\":\"MLE_VERSION\",\"OemName\":\"OEM1\",\"Attestation_Type\": \"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"MLEDESCRIPTION1111\",\"MLE_Manifests\": [{\"Name\": \"PCR_NUM\", \"Value\": \"PCR_VALUE\"}],\"pcrIMLMask\":\"HEX_PCR_MASK\"}' \033[0m" + echo -e "Edit MLE example:\n\033[31;49;5;1m bash oat_mle -e -h HOSTNAME_OF_OAT-APPRAISER '{\"Name\":\"MLE_NAME\",\"Version\":\"MLE_VERSION\",\"OemName\":\"OEM1\",\"Attestation_Type\": \"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"DESCRIPTION\",\"MLE_Manifests\": [{\"Name\": \"PCR_NUM\", \"Value\": \"PCR_VALUE\"}],\"pcrIMLMask\":\"HEX_PCR_MASK\"}'\033[0m" + echo -e "Del MLE example:\n\033[31;49;5;1m bash oat_mle -d -h HOSTNAME_OF_OAT-APPRAISER '{\"mleName\":\"MLE_NAME\",\"mleVersion\":\"MLE_VERSION\",\"oemName\":\"OEM1\"}'\033[0m" +} + +if [ $# -lt 4 ];then + echo "parm num error!" + ShowMleExample + exit 0 +fi + +if [ ! -z $OAT_CERTFILE ] && [ -e $OAT_CERTFILE ];then + echo " " +else + OAT_CERTFILE="certfile.cer" +fi + +if [ $2 != $HOST_PARM ];then + echo "-h parm error!" + ShowMleExample + exit 1 +else + HOST_NAME="$3" +fi + +if [ $1 == $DEL_PARM ];then + INFO="`echo "$4" | awk -F{ '{print $2}'| awk -F} '{print $1}'\ + | sed 's/\"//g' | sed 's/:/=/g' | sed 's/,/\&/g'| sed 's/ /%20/g'`" +else + INFO="$4" +fi + +addMLE() +{ + curl --cacert $OAT_CERTFILE -H "Content-Type: application/json" \ + -X POST -d "$INFO" "https://$HOST_NAME:$PORT/WLMService/resources/mles" +} + +editMLE() +{ + curl --cacert $OAT_CERTFILE -H "Content-Type: application/json" \ + -X PUT -d "$INFO" "https://$HOST_NAME:$PORT/WLMService/resources/mles" +} + +delMLE() +{ + curl --cacert $OAT_CERTFILE \ + -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/mles?$INFO" +} + +case $1 in + $ADD_PARM) + echo "add MLE:" + addMLE + ;; + $EDIT_PARM) + echo "edit MLE:" + editMLE + ;; + $DEL_PARM) + echo "del MLE:" + delMLE + ;; + *) + echo "Usage oat_mles {-a|-e|-d}" + ShowMleExample + exit 3 +esac +echo -e "\n" diff --git a/OpenAttestation/CommandTool/oat_mle_search b/OpenAttestation/CommandTool/oat_mle_search new file mode 100644 index 0000000..09ba9a2 --- /dev/null +++ b/OpenAttestation/CommandTool/oat_mle_search @@ -0,0 +1,45 @@ +#!/bin/bash +#MLE search + +HOST_PARM="-h" +HOST_NAME="" +INFO="" +PORT=8443 +ShowMleSearchExample() +{ + echo -e "Mle Search example:\n\033[31;49;5;1m bash oat_mle_search -h HOSTNAME_OF_OAT-APPRAISER '{KEY}' \033[0m" +} + +if [ $# -lt 3 ];then + echo "parm num error!" + ShowMleSearchExample + exit 0 +fi + +if [ ! -z $OAT_CERTFILE ] && [ -e $OAT_CERTFILE ];then + echo " " +else + OAT_CERTFILE="certfile.cer" +fi + +if [ $1 != $HOST_PARM ];then + echo "-h parm error!" + ShowMleSearchExample + exit 1 +else + HOST_NAME="$2" +fi + +INFO="`echo "$3" | awk -F{ '{print $2}'| awk -F} '{print $1}'\ + | sed 's/\"//g' | sed 's/:/=/g' | sed 's/,/\&/g'| sed 's/ /%20/g'`" + + +oat_mle_search() +{ + curl --cacert ./$OAT_CERTFILE -H "Content-Type: application/json" \ + -X GET "https://$HOST_NAME:$PORT/WLMService/resources/mles?searchCriteria=$INFO" +} + + +oat_mle_search +echo -e "\n" diff --git a/OpenAttestation/CommandTool/oat_oem b/OpenAttestation/CommandTool/oat_oem new file mode 100644 index 0000000..d0b61f3 --- /dev/null +++ b/OpenAttestation/CommandTool/oat_oem @@ -0,0 +1,80 @@ +#!/bin/bash +#create oem script +ADD_PARM="-a" +EDIT_PARM="-e" +DEL_PARM="-d" +HOST_PARM="-h" +HOST_NAME="" +INFO="" +PORT=8443 +ShowExample() +{ + echo -e "Add oem example:\033[31;49;5;1m bash oat_oem -a -h HOSTNAME_OF_OAT-APPRAISER '{\"Name\":\"OEM_NAME\",\"Description\":\"DESCRIPTION\"}'\033[0m" + echo -e "Edit oem example:\033[31;49;5;1m bash oat_oem -e -h HOSTNAME_OF_OAT-APPRAISER '{\"Name\":\"OEM_NAME\",\"Description\":\"DESCRIPTION\"}'\033[0m" + echo -e "Del oem example:\033[31;49;5;1m bash oat_oem -d -h HOSTNAME_OF_OAT-APPRAISER '{\"Name\":\"OEM_NAME\"}'\033[0m" +} + +if [ $# -lt 4 ];then + echo "parm num error!" + ShowExample + exit 0 +fi + +if [ ! -z $OAT_CERTFILE ] && [ -e $OAT_CERTFILE ];then + echo " " +else + OAT_CERTFILE="certfile.cer" +fi + +if [ $2 != $HOST_PARM ];then + echo "-h parm error!" + ShowExample + exit 1 +else + HOST_NAME="$3" +fi + +if [ $1 == $DEL_PARM ];then + INFO="`echo "$4" | awk -F{ '{print $2}'| awk -F} '{print $1}'\ + | sed 's/\"//g' | sed 's/:/=/g' | sed 's/ /%20/g'`" +else + INFO="$4" +fi + +addOEM() +{ + curl --cacert $OAT_CERTFILE -H "Content-Type: application/json" \ + -X POST -d "$INFO" "https://$HOST_NAME:$PORT/WLMService/resources/oem" +} + +editOEM() +{ + curl --cacert $OAT_CERTFILE -H "Content-Type: application/json" \ + -X PUT -d "$INFO" "https://$HOST_NAME:$PORT/WLMService/resources/oem" +} + +delOEM() +{ + curl --cacert $OAT_CERTFILE \ + -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/oem?$INFO" +} + +case $1 in + $ADD_PARM) + echo "add OEM:" + addOEM + ;; + $EDIT_PARM) + echo "edit OEM:" + editOEM + ;; + $DEL_PARM) + echo "del OEM:" + delOEM + ;; + *) + echo "Usage oat_oem {-a|-e|-d}" + ShowExample + exit 3 +esac +echo -e "\n" diff --git a/OpenAttestation/CommandTool/oat_os b/OpenAttestation/CommandTool/oat_os new file mode 100644 index 0000000..4a9ddbe --- /dev/null +++ b/OpenAttestation/CommandTool/oat_os @@ -0,0 +1,81 @@ +#!/bin/bash +#create os script +ADD_PARM="-a" +EDIT_PARM="-e" +DEL_PARM="-d" +HOST_PARM="-h" +HOST_NAME="" +INFO="" +PORT=8443 + +ShowExample() +{ + echo -e "Add OS example:\033[31;49;5;1m bash oat_os -a -h HOSTNAME_OF_OAT-APPRAISER '{\"Name\":\"OS_NAME\",\"Version\":\"OS_VERSION\",\"Description\":\"DESCRIPTION\"}'\033[0m" + echo -e "Edit OS example:\033[31;49;5;1m bash oat_os -e -h HOSTNAME_OF_OAT-APPRAISER '{\"Name\":\"OS_NAME\",\"Version\":\"OS_VERSION\",\"Description\":\"Mooooooooodify\"}'\033[0m" + echo -e "Del OS example:\033[31;49;5;1m bash oat_os -d -h HOSTNAME_OF_OAT-APPRAISER '{\"Name\":\"OS_NAME\",\"Version\":\"OS_VERSION\"}'\033[0m" +} + +if [ $# -lt 4 ];then + echo "parm num error!" + ShowExample + exit 0 +fi + +if [ ! -z $OAT_CERTFILE ] && [ -e $OAT_CERTFILE ];then + echo " " +else + OAT_CERTFILE="certfile.cer" +fi + +if [ $2 != $HOST_PARM ];then + echo "-h parm error!" + ShowExample + exit 1 +else + HOST_NAME="$3" +fi + +if [ $1 == $DEL_PARM ];then + INFO="`echo "$4" | awk -F{ '{print $2}' | awk -F} '{print $1}' | awk -F, '{print $1$2}' | \ + sed 's/\":\"/=/g' | sed 's/\"\"/\&/g' | sed 's/\"//g' | sed 's/ /%20/g'`" +else + INFO="$4" +fi + +addOS() +{ + curl --cacert $OAT_CERTFILE -H "Content-Type: application/json" \ + -X POST -d "$INFO" "https://$HOST_NAME:$PORT/WLMService/resources/os" +} + +editOS() +{ + curl --cacert $OAT_CERTFILE -H "Content-Type: application/json" \ + -X PUT -d "$INFO" "https://$HOST_NAME:$PORT/WLMService/resources/os" +} + +delOS() +{ + curl --cacert $OAT_CERTFILE \ + -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/os?$INFO" +} + +case $1 in + $ADD_PARM) + echo "add OS:" + addOS + ;; + $EDIT_PARM) + echo "edit OS:" + editOS + ;; + $DEL_PARM) + echo "del OS:" + delOS + ;; + *) + echo "Usage oat_os {-a|-e|-d}" + ShowExample + exit 3 +esac +echo -e "\n" diff --git a/OpenAttestation/CommandTool/oat_pcrListToMask b/OpenAttestation/CommandTool/oat_pcrListToMask new file mode 100644 index 0000000..65312d6 --- /dev/null +++ b/OpenAttestation/CommandTool/oat_pcrListToMask @@ -0,0 +1,31 @@ +#!/bin/bash + +ShowPcrListToMaskExample() +{ + echo "PcrListToMask Example:\n\033[31;49;5;1m bash oat_pcrListToMask \"#|#|#|#|#|#\"\033[0m" +} + +if [ $# -ne 1 ];then + echo "parm num error!" + ShowPcrListToMaskExample + exit 0 +fi + +PCR_LIST="$1" +BIT_MASK=0x00000 + +OIFS=$IFS +IFS='|' + +for PCR_NUM in $PCR_LIST +do + PCR_NUM=${PCR_NUM//[[:blank:]]/} + if [ -n "$PCR_NUM" ]; then + SHIFTED_BIT=$(( 0x800000>>$PCR_NUM )) + BIT_MASK=$(($BIT_MASK | $SHIFTED_BIT)) + fi +done + +printf "%X\n" $BIT_MASK + +IFS=$OIFS diff --git a/OpenAttestation/CommandTool/oat_pcrwhitelist b/OpenAttestation/CommandTool/oat_pcrwhitelist new file mode 100644 index 0000000..563ae53 --- /dev/null +++ b/OpenAttestation/CommandTool/oat_pcrwhitelist @@ -0,0 +1,85 @@ +#!/bin/bash +#create mles/whitelist/pcr script +ADD_PARM="-a" +EDIT_PARM="-e" +DEL_PARM="-d" +HOST_PARM="-h" +HOST_NAME="" +INFO="" +PORT=8443 +ShowPcrExample() +{ + echo "Pcr bios Example:" + echo -e "Add Pcr example:\n\033[31;49;5;1m bash oat_pcrwhitelist -a -h HOSTNAME_OF_OAT-APPRAISER '{\"pcrName\":\"PCR_NUM\",\"pcrDigest\":\"PCR_VALUE\", \"mleName\":\"MLE_NAME_OF_BIOS_TYPE\",\"mleVersion\":\"MLE_VERSION\", \"oemName\": \"OEM_NAME\"}'\033[0m" + echo -e "Edit Pcr example:\n\033[31;49;5;1m bash oat_pcrwhitelist -e -h HOSTNAME_OF_OAT-APPRAISER '{\"pcrName\":\"PCR_NUM\",\"pcrDigest\":\"PCR_VALUE\", \"mleName\":\"MLE_NAME_OF_BIOS_TYPE\",\"mleVersion\":\"MLE_VERSION\", \"oemName\": \"OEM_NAME\"}'\033[0m" + echo -e "Del Pcr example:\n\033[31;49;5;1m bash oat_pcrwhitelist -d -h HOSTNAME_OF_OAT-APPRAISER '{\"pcrName\":\"PCR_NUM\",\"mleName\":\"MLE_NAME_OF_BIOS_TYPE\",\"mleVersion\":\"MLE_VERSION\",\"oemName\":\"OEM_NAME\"}'\033[0m" + echo "Pcr vmm Example:" + echo -e "Add Pcr example:\n\033[31;49;5;1m bash oat_pcrwhitelist -a -h HOSTNAME_OF_OAT-APPRAISER '{\"pcrName\":\"PCR_NUM\",\"pcrDigest\":\"PCR_VALUE\",\"mleName\":\"MLE_NAME_OF_VMM_TYPE\",\"mleVersion\":\"MLE_VERSION\",\"osName\":\"OS_NAME\",\"osVersion\":\"OS_VERSION\"}'\033[0m" + echo -e "Edit Pcr example:\n\033[31;49;5;1m bash oat_pcrwhitelist -e -h HOSTNAME_OF_OAT-APPRAISER '{\"pcrName\":\"PCR_NUM\",\"pcrDigest\":\"PCR_VALUE\", \"mleName\":\"MLE_NAME_OF_VMM_TYPE\",\"mleVersion\":\"MLE_VERSION\",\"osName\":\"OS_NAME\",\"osVersion\":\"OS_VERSION\"}'\033[0m" + echo -e "Del Pcr example:\n\033[31;49;5;1m bash oat_pcrwhitelist -d -h HOSTNAME_OF_OAT-APPRAISER '{\"pcrName\":\"PCR_NUM\",\"mleName\":\"MLE_NAME_OF_VMM_TYPE\",\"mleVersion\":\"MLE_VERSION\",\"osName\":\"OS_NAME\",\"osVersion\":\"OS_VERSION\"}'\033[0m" +} + +if [ $# -lt 4 ];then + echo "parm num error!" + ShowPcrExample + exit 0 +fi + +if [ ! -z $OAT_CERTFILE ] && [ -e $OAT_CERTFILE ];then + echo " " +else + OAT_CERTFILE="certfile.cer" +fi + +if [ $2 != $HOST_PARM ];then + echo "-h parm error!" + ShowPcrExample + exit 1 +else + HOST_NAME="$3" +fi + +if [ $1 == $DEL_PARM ];then + INFO="`echo $4 | awk -F{ '{print $2}' | awk -F} '{print $1}' | sed 's/\"//g' | \ + sed 's/:/=/g' | sed 's/,/\&/g' | sed 's/ /%20/g'`" +else + INFO="$4" +fi + +addOS() +{ + curl --cacert $OAT_CERTFILE -H "Content-Type: application/json" \ + -X POST -d "$INFO" "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr" +} + +editOS() +{ + curl --cacert $OAT_CERTFILE -H "Content-Type: application/json" \ + -X PUT -d "$INFO" "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr" +} + +delOS() +{ + curl --cacert $OAT_CERTFILE \ + -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr?$INFO" +} + +case $1 in + $ADD_PARM) + echo "add PCR:" + addOS + ;; + $EDIT_PARM) + echo "edit PCR:" + editOS + ;; + $DEL_PARM) + echo "del PCR:" + delOS + ;; + *) + echo "Usage oat_pcr {-a|-e|-d}" + ShowPcrExample + exit 3 +esac +echo -e "\n" diff --git a/OpenAttestation/CommandTool/oat_pollhosts b/OpenAttestation/CommandTool/oat_pollhosts new file mode 100644 index 0000000..f6ffb0a --- /dev/null +++ b/OpenAttestation/CommandTool/oat_pollhosts @@ -0,0 +1,40 @@ +#!/bin/bash +#create mles script +HOST_PARM="-h" +HOST_NAME="" +INFO="" +PORT=8443 +ShowPollHostExample() +{ + echo -e "PollHost example:\n\033[31;49;5;1m bash oat_pollhosts -h HOSTNAME_OF_OAT-APPRAISER '{\"hosts\":[\"HOSTNAME_OF_OAT-CLIENT\"]}' \033[0m" +} + +if [ $# -lt 3 ];then + echo "parm num error!" + ShowPollHostExample + exit 0 +fi + +if [ ! -z $OAT_CERTFILE ] && [ -e $OAT_CERTFILE ];then + echo " " +else + OAT_CERTFILE="certfile.cer" +fi + +if [ $1 != $HOST_PARM ];then + echo "-h parm error!" + ShowPollHostExample + exit 1 +else + HOST_NAME="$2" +fi + +INFO="$3" + +pollHosts() +{ + curl --cacert $OAT_CERTFILE -H "Content-Type: application/json" \ + -X POST -d "$INFO" "https://$HOST_NAME:$PORT/AttestationService/resources/PollHosts" +} +pollHosts +echo -e "\n" diff --git a/OpenAttestation/CommandTool/oat_posthosts b/OpenAttestation/CommandTool/oat_posthosts new file mode 100644 index 0000000..0fc2cc9 --- /dev/null +++ b/OpenAttestation/CommandTool/oat_posthosts @@ -0,0 +1,74 @@ +#!/bin/bash +#submit periodic/async requests +HOST_PARM="-h" +ADD_REQUEST="-a" +DEL_REQUEST="-d" +GET_RESULT="-g" +HOST_NAME="" +INFO="" +PORT=8443 +ShowPostHostExample() +{ + echo -e "PostHost:" + echo -e "Add periodic request example:\n\033[31;49;5;1m bash oat_posthosts -a -h HOSTNAME_OF_OAT-APPRAISER '{\"hosts\":[\"HOSTNAME_OF_OAT-CLIENT\"], \"analysisType\":\"ANALYSIS_NAME,ANALYSIS_PARAM;ANALYSIS_NAME\", \"timeThreshold\":\"MILLISECONDS_INTERVAL\", \"expirationTime\":\"TIME_INTERVAL\"}' \033[0m" + echo -e "Add asynchronous request example:\n\033[31;49;5;1m bash oat_posthosts -a -h HOSTNAME_OF_OAT-APPRAISER '{\"hosts\":[\"HOSTNAME_OF_OAT-CLIENT\"], \"analysisType\":\"ANALYSIS_NAME,ANALYSIS_PARAM;ANALYSIS_NAME\"}' \033[0m" + echo -e "Get attestation result example:\n\033[31;49;5;1m bash oat_posthosts -g -h HOSTNAME_OF_OAT-APPRAISER '{\"requestId\":\"PREV_RECEIVED_ID\", \"lastResult\":\"BOOLEAN_VALUE\"}' \033[0m" + echo -e "Remove periodic request example:\n\033[31;49;5;1m bash oat_posthosts -d -h HOSTNAME_OF_OAT-APPRAISER '{\"requestId\":\"PREV_RECEIVED_ID\"}' \033[0m" +} + +if [ $# -lt 4 ];then + echo "parm num error!" + ShowPostHostExample + exit 0 +fi + +if [ ! -z $OAT_CERTFILE ] && [ -e $OAT_CERTFILE ];then + echo " " +else + OAT_CERTFILE="certfile.cer" +fi + +if [ $2 != $HOST_PARM ];then + echo "-h parm error!" + ShowPostHostExample + exit 1 +else + HOST_NAME="$3" +fi + +INFO="$4" + +addRequest() +{ + curl --cacert $OAT_CERTFILE -H "Content-Type: application/json" \ + -X POST -d "$INFO" "https://$HOST_NAME:$PORT/AttestationService/resources/PostHosts" +} + +delRequest() +{ + curl --cacert $OAT_CERTFILE -H "Content-Type: application/json" \ + -X DELETE -d "$INFO" "https://$HOST_NAME:$PORT/AttestationService/resources/PostHosts" +} + +getResult() +{ + curl --cacert $OAT_CERTFILE -H "Content-Type: application/json" \ + -X GET -d "$INFO" "https://$HOST_NAME:$PORT/AttestationService/resources/PostHosts" +} + +case $1 in + $ADD_REQUEST) + addRequest + ;; + $DEL_REQUEST) + delRequest + ;; + $GET_RESULT) + getResult + ;; + *) + echo "Usage oat_posthosts {-a|-g|-d}" + ShowMleExample + exit 3 +esac +echo -e "\n" diff --git a/OpenAttestation/CommandTool/oat_view_mle b/OpenAttestation/CommandTool/oat_view_mle new file mode 100644 index 0000000..42e9cf4 --- /dev/null +++ b/OpenAttestation/CommandTool/oat_view_mle @@ -0,0 +1,50 @@ +#!/bin/bash +#mle view +HOST_PARM="-h" +HOST_NAME="" +INFO="" +PORT=8443 + +ShowMleViewExample() +{ + echo -e "bios Mle View example:\n\033[31;49;5;1m bash oat_view_mle -h HOSTNAME_OF_OAT-APPRAISER '{\"mleName\":\"MLE_NAME\",\"mleVersion\":\"MLE_VERSION\",\"oemName\":\"OEM_NAME\"}' \033[0m" + echo -e "vmm Mle View example:\n\033[31;49;5;1m bash oat_view_mle -h HOSTNAME_OF_OAT-APPRAISER '{\"mleName\":\"MLE_NAME\",\"mleVersion\":\"MLE_VERSION\",\"osName\":\"OS_NAME\",\"osVersion\":\"OS_VERSION\"}' \033[0m" +} + +if [ $# -lt 3 ];then + echo "parm num error!" + ShowMleViewExample + exit 0 +fi + +if [ ! -z $OAT_CERTFILE ] && [ -e $OAT_CERTFILE ];then + echo " " +else + OAT_CERTFILE="certfile.cer" +fi + +if [ ! -z $OAT_CERTFILE ] && [ -e $OAT_CERTFILE ];then + echo " " +else + OAT_CERTFILE="certfile.cer" +fi + +if [ $1 != $HOST_PARM ];then + echo "-h parm error!" + ShowMleViewExample + exit 1 +else + HOST_NAME="$2" +fi + +INFO="`echo "$3" | awk -F{ '{print $2}'| awk -F} '{print $1}'\ + | sed 's/\"//g' | sed 's/:/=/g' | sed 's/,/\&/g'| sed 's/ /%20/g'`" + +view_mle() +{ + curl --cacert ./$OAT_CERTFILE -H "Content-Type: application/json" \ + -X GET "https://$HOST_NAME:$PORT/WLMService/resources/mles/manifest?$INFO" +} + +view_mle +echo -e "\n" diff --git a/OpenAttestation/CommandTool/oat_view_oem b/OpenAttestation/CommandTool/oat_view_oem new file mode 100644 index 0000000..d82f992 --- /dev/null +++ b/OpenAttestation/CommandTool/oat_view_oem @@ -0,0 +1,50 @@ +#!/bin/bash +#oem view +PARM="-h" +PORT="8443" +ShowOemViewExample() +{ + echo -e "Oem View example:\n\033[31;49;5;1m bash oat_view_oem -h HOSTNAME_OF_OAT-APPRAISER\033[0m" +} + +if [ $# -lt 2 ];then + echo "parm num error!" + ShowOemViewExample + exit 0 +fi + +if [ ! -z $OAT_CERTFILE ] && [ -e $OAT_CERTFILE ];then + echo " " +else + OAT_CERTFILE="certfile.cer" +fi + +if [ $1 != $PARM ];then + echo "parm error!" + ShowOemViewExample + exit 0 +fi + +HOST_NAME="$2" +view_oem() +{ + res=`ping -c 1 $HOST_NAME > /dev/null 2>&1` + if [ $? != 0 ];then + echo "host is unreachable" + exit 0 + fi + if [ -z $HOST_NAME ];then + echo "invalid hostname" + exit 0 + fi + len=`expr length $HOST_NAME` + if [ $len -gt 50 ];then + echo "size of host name exceeds the max number allowed" + exit 0 + fi + curl --cacert ./$OAT_CERTFILE -H "Content-Type: application/json" \ + -X GET https://$HOST_NAME:$PORT/WLMService/resources/oem +} + +view_oem +echo -e "\n" diff --git a/OpenAttestation/CommandTool/oat_view_os b/OpenAttestation/CommandTool/oat_view_os new file mode 100644 index 0000000..8ebea19 --- /dev/null +++ b/OpenAttestation/CommandTool/oat_view_os @@ -0,0 +1,50 @@ +#!/bin/bash +#OS view +PARM="-h" +PORT="8443" +ShowOSViewExample() +{ + echo -e "OS view example:\n\033[31;49;5;1m bash oat_view_os -h HOSTNAME_OF_OAT-APPRAISER\033[0m" +} + +if [ $# -lt 2 ];then + echo "parm num error!" + ShowOSViewExample + exit 0 +fi + +if [ ! -z $OAT_CERTFILE ] && [ -e $OAT_CERTFILE ];then + echo " " +else + OAT_CERTFILE="certfile.cer" +fi + +if [ $1 != $PARM ];then + echo "parm error!" + ShowOSViewExample + exit 0 +fi + +HOST_NAME="$2" +view_os() +{ + res=`ping -c 1 $HOST_NAME > /dev/null 2>&1` + if [ $? != 0 ];then + echo "host is unreachable" + exit 0 + fi + if [ -z $HOST_NAME ];then + echo "invalid hostname" + exit 0 + fi + len=`expr length $HOST_NAME` + if [ $len -gt 50 ];then + echo "size of host name exceeds the max number allowed" + exit 0 + fi + curl --cacert ./$OAT_CERTFILE -H "Content-Type: application/json" \ + -X GET https://$HOST_NAME:$PORT/WLMService/resources/os +} + +view_os +echo -e "\n" diff --git a/OpenAttestation/CommandTool/update_cert.sh b/OpenAttestation/CommandTool/update_cert.sh new file mode 100644 index 0000000..622921e --- /dev/null +++ b/OpenAttestation/CommandTool/update_cert.sh @@ -0,0 +1,19 @@ +#! /bin/bash + +OAT=$1 +HOST=$2 +HOSTIP=$3 +HOSTDISTRO=$4 +HOSTCERTDGST=$5 + +if [ -z "$OAT" ] || [ -z "$HOST" ] || [ -z "$HOSTIP" ] || [ -z "$HOSTDISTRO" ] || [ -z "$HOSTCERTDGST" ]; then + echo "Missing parameters" + exit 1 +fi + +set -x + +bash oat_host -e -h $OAT '{"HostName":"'$HOST'","IPAddress":"'$HOSTIP'","Port":"9999","VMM_Name":"'$HOST'-'$HOSTDISTRO'","VMM_Version":"123","VMM_OSName":"'$HOSTDISTRO'","VMM_OSVersion":"v1234","Email":"","AddOn_Connection_String":"","Description":"'$HOSTCERTDGST'"}' + + +set +x diff --git a/OpenAttestation/Installer/DPKG-OAT-Appraiser-Base/DEBIAN/control b/OpenAttestation/Installer/DPKG-OAT-Appraiser-Base/DEBIAN/control new file mode 100644 index 0000000..d48feaa --- /dev/null +++ b/OpenAttestation/Installer/DPKG-OAT-Appraiser-Base/DEBIAN/control @@ -0,0 +1,11 @@ +Package: oat-appraiser-base-oatapp +Version: 1.0.0-3 +Architecture: amd64 +Maintainer: Jimmy Wei +Installed-Size: 130284 +Section: +Priority: extra +Description: The OAT Appraiser Base Install + The Host Integrity at Startup Installation + of the OAT Appraiser Server Base Install + . diff --git a/OpenAttestation/Installer/DPKG-OAT-Appraiser-Base/DEBIAN/md5sums b/OpenAttestation/Installer/DPKG-OAT-Appraiser-Base/DEBIAN/md5sums new file mode 100644 index 0000000..61ede9a --- /dev/null +++ b/OpenAttestation/Installer/DPKG-OAT-Appraiser-Base/DEBIAN/md5sums @@ -0,0 +1,10 @@ +660b6acd03a5b2adf2f4db0113db8356 OAT-Appraiser-Base/ClientInstallForLinux.zip +3aa85d0e87c92ed70d7609a6dc4e2a7a OAT-Appraiser-Base/HisPrivacyCAWebServices2.war +99aaba9d55f7fcc6b514d0bb6f8b6852 OAT-Appraiser-Base/MySQLdrop.zip +949a9b5b9ecfeed070cb311f2684ea13 OAT-Appraiser-Base/OAT.zip +530f6b614cf117a93600ad7469d8beaf OAT-Appraiser-Base/OAT_Server_Install.zip +e7da48959ec86c1b2e6de9e9ecf24c4d OAT-Appraiser-Base/apache-tomcat-6.0.29.tar.gz +fe801b9772676fe983cf25603d49cfa1 OAT-Appraiser-Base/clientInstallRefresh.zip +420f2b11b4a77f19e77ebccbb0911604 OAT-Appraiser-Base/linuxClientInstallRefresh.zip +f80310ff189f0049761ab0c76afa58ab OAT-Appraiser-Base/oatSetup.zip +c18fe6b2b4248d53ebef3d7dcfad2422 OAT-Appraiser-Base/service.zip diff --git a/OpenAttestation/Installer/DPKG-OAT-Appraiser-Base/DEBIAN/postinst b/OpenAttestation/Installer/DPKG-OAT-Appraiser-Base/DEBIAN/postinst new file mode 100644 index 0000000..5256a14 --- /dev/null +++ b/OpenAttestation/Installer/DPKG-OAT-Appraiser-Base/DEBIAN/postinst @@ -0,0 +1,455 @@ +#!/bin/bash + +echo "Making OAT Appraiser" + +#tomcat configure +TOMCAT_INSTALL_DIR=/usr/lib +TOMCAT_NAME=apache-tomcat-6.0.29 +#CERT_DIR=/var/lib/oat-appraiser/Certificate +#CERT_DIR=${TEMP_DIR} +if [ -d /var/lib/oat-appraiser ] +then + rm -rf /var/lib/oat-appraiser + mkdir /var/lib/oat-appraiser + mkdir /var/lib/oat-appraiser/CaCerts + mkdir /var/lib/oat-appraiser/ClientFiles +else + mkdir /var/lib/oat-appraiser + mkdir /var/lib/oat-appraiser/CaCerts + mkdir /var/lib/oat-appraiser/ClientFiles +fi + +if [ -d /etc/oat-appraiser ] +then + rm -rf /etc/oat-appraiser + mkdir /etc/oat-appraiser +else + mkdir /etc/oat-appraiser +fi + +if [ $TOMCAT_DIR -a -d $TOMCAT_DIR ];then + if [[ ${TOMCAT_DIR:$((${#TOMCAT_DIR}-1)):1} == / ]];then + TOMCAT_DIR_TMP=${TOMCAT_DIR:0:$((${#TOMCAT_DIR}-1))} + else + TOMCAT_DIR_TMP=$TOMCAT_DIR + fi + + TOMCAT_INSTALL_DIR=${TOMCAT_DIR_TMP%/*} + TOMCAT_NAME=${TOMCAT_DIR_TMP##*/} +fi +TOMCAT_DIR_COFNIG_TYPE=${TOMCAT_INSTALL_DIR//\//\\/} +echo $TOMCAT_INSTALL_DIR > ~/dpkg.log +echo $TOMCAT_DIR_COFNIG_TYPE >> ~/dpkg.log +update-rc.d tomcat6 defaults 99 1>>/dev/null +###Random generation /dev/urandom is good but just in case... +# Creating randoms for the p12 files and setting up truststore and keystore +ip12="internal.p12" +ipassfile="internal.pass" +idomfile="internal.domain" +name="OAT-Appraiser-Base" +iloc="/$name/" +p12file="$loc$ip12" +RAND1=$(dd if=/dev/urandom bs=1 count=1024) +RAND2=$(dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}') +RAND3=$(dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}') +randbits="$(echo "$( echo "`date +%y%m%d%m%s%N`" | md5sum | md5sum )$( echo "`dd if=/dev/urandom bs=1 count=1024`" | md5sum | md5sum)$(echo "`date +%y%m%d%m%s%N`" | md5sum | md5sum )$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`date +%y%m%d%m%s%N`" | md5sum | md5sum)$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`date +%y%m%d%m%s%N`" | md5sum | md5sum )" | md5sum | md5sum )" +randpass="${randbits:0:30}" +randbits2="$(echo "$( echo "`date +%y%m%d%m%s%N`" | md5sum | md5sum )$( echo "`dd if=/dev/urandom bs=1 count=1024`" | md5sum | md5sum)$(echo "`date +%y%m%d%m%s%N`" | md5sum | md5sum )$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`date +%y%m%d%m%s%N`" | md5sum | md5sum)$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`date +%y%m%d%m%s%N`" | md5sum | md5sum )" | md5sum | md5sum )" +randpass2="${randbits2:0:30}" +randbits3="$(echo "$( echo "`date +%y%m%d%m%s%N`" | md5sum | md5sum )$( echo "`dd if=/dev/urandom bs=1 count=1024`" | md5sum | md5sum)$(echo "`date +%y%m%d%m%s%N`" | md5sum | md5sum )$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`date +%y%m%d%m%s%N`" | md5sum | md5sum)$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`date +%y%m%d%m%s%N`" | md5sum | md5sum )" | md5sum | md5sum )" +randpass3="${randbits3:0:30}" +p12pass="$randpass" +mysqlPass="$randpass2" +keystore="keystore.jks" +truststore="TrustStore.jks" +if [ "`ls $iloc | grep $ip12`" ] && [ "`ls $iloc | grep $ipassfile`" ] ; then + p12pass="`cat $loc$ipassfile`" +fi +if [ "`ls $iloc | grep $idomfile`" ] ; then + domain="`cat $loc$idomfile`" +fi + + +cp /${name}/tomcat6.deb /etc/init.d/tomcat6 +#stop mysql and tomcat service +MYSQL=`netstat -nutlp | grep :3306 | grep mysql` +if [ "$MYSQL" ]; then + service mysql stop +fi + +TOMCAT=`netstat -nutlp | grep :8443 | grep java` +if [ "$TOMCAT" ]; then + service tomcat6 stop +fi + +sleep 10 + +#Configuring mysql so we can set up database and hisAppraiser profile +ISSKIPGRANTEXIT=`grep skip-grant-tables /etc/mysql/my.cnf` +if [ ! "$ISSKIPGRANTEXIT" ]; then + sed -i 's/\[mysqld\]/\[mysqld\]\nskip-grant-tables/g' /etc/mysql/my.cnf +fi +#start mysql service +if [ ! `netstat -nutlp | grep :3306 | grep mysql` ]; then + service mysql start +fi + +#Sets up database and user +mysql -u root --execute="CREATE DATABASE oat_db; FLUSH PRIVILEGES; GRANT ALL ON oat_db.* TO 'oatAppraiser'@'localhost' IDENTIFIED BY '$randpass3';" + +#stop mysql service +if [ "`netstat -nutlp | grep :3306 | grep mysql`" ]; then + service mysql stop +fi + + +#setting up tomcat at $TOMCAT_INSTALL_DIR/ +if [ $TOMCAT_NAME == apache-tomcat-6.0.29 ];then +rm -f $TOMCAT_INSTALL_DIR/apache-tomcat-6.0.29.tar.gz +mv /$name/apache-tomcat-6.0.29.tar.gz $TOMCAT_INSTALL_DIR/. +fi + +unzip /$name/service.zip -d /$name/ +rm -f /$name/service.zip + +if [ $TOMCAT_NAME == apache-tomcat-6.0.29 ];then + rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME + tar -zxf $TOMCAT_INSTALL_DIR/apache-tomcat-6.0.29.tar.gz -C $TOMCAT_INSTALL_DIR/ +fi + +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/service +mv -f /$name/service $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/service +#rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/Certificate +rm -rf /var/lib/oat-appraiser/Certificate +#mkdir $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/Certificate +mkdir /var/lib/oat-appraiser/Certificate +unzip /$name/setupProperties.zip -d /$name/ +mv /$name/setup.properties /etc/oat-appraiser/ +rm -R -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/* + +#TODO +#chkconfig --del NetworkManager +#chkconfig network on +#chkconfig httpd --add +#chkconfig httpd on +#service httpd start +#chkconfig mysql on +#service mysql start + +#start mysql service +if [ ! `netstat -nutlp | grep :3306 | grep mysql` ]; then + service mysql start +fi + + +#running OAT database full setup +if [ "`netstat -nutlp | grep :3306 | grep mysql`" ]; then + service mysql stop +fi +sed -i 's/skip-grant-tables//g' /etc/mysql/my.cnf +if [ ! `netstat -nutlp | grep :3306 | grep mysql` ]; then + service mysql start +fi +rm -rf /$name/MySQLdrop.txt +unzip /$name/MySQLdrop.zip -d /$name/ +#ubuntu has different behavior on ' conduction comparing with fedora +sed -i "s/DROP USER ''/DROP USER 'oatAppraiser'@'localhost'/g" /$name/MySQLdrop.txt +mysql -u root < /$name/MySQLdrop.txt +rm -rf /$name/OAT_Server_Install +unzip /$name/OAT_Server_Install.zip -d /$name/ +rm -rf /tmp/OAT_Server_Install +mv -f /$name/OAT_Server_Install /tmp/OAT_Server_Install +mysql -u root --execute="DROP DATABASE IF EXISTS oat_db;" +mysql -u root < /tmp/OAT_Server_Install/oat_db.MySQL +################### + +mysql -u root < /tmp/OAT_Server_Install/init.sql +mysql -u root --execute="FLUSH PRIVILEGES; GRANT ALL ON oat_db.* TO 'oatAppraiser'@'localhost' IDENTIFIED BY '$randpass3';" +#setting up access control in tomcat context.xml +#sed -i "/<\/Context>/i\\ " $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/conf/context.xml + +sed -i "/<\/Context>/i\\ " $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/conf/context.xml + +#setting up port 8443 in tomcat server.xml +#sed -i "s/ <\/Service>/<\/Service>/g" $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/conf/server.xml + +sed -i "s/ <\/Service>/<\/Service>/g" $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/conf/server.xml + +cp -R /tmp/OAT_Server_Install/HisWebServices $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/ +# +#if [ -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationAdminConsole.war ];then +# rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationAdminConsole.war +#fi +# +#if [ -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationManifestWebServices.war ];then +# rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationManifestWebServices.war +#fi +# +#if [ -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationWebServices.war ];then +# rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationWebServices.war +#fi + +unzip /tmp/OAT_Server_Install/WLMService.war -d /tmp/OAT_Server_Install/WLMService +unzip /tmp/OAT_Server_Install/AttestationService.war -d /tmp/OAT_Server_Install/AttestationService +cp -R /tmp/OAT_Server_Install/WLMService $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/ +cp -R /tmp/OAT_Server_Install/AttestationService $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/ +echo "$TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationAdminConsole/WEB-INF/classes/manifest.properties has updated" + +mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/AttestationService/WEB-INF/classes/OpenAttestationWebServices.properties /etc/oat-appraiser/OpenAttestationWebServices.properties +sed -i "s//$(hostname)/g" /etc/oat-appraiser/OpenAttestationWebServices.properties +#sed -i "s//$(hostname)/g" $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationAdminConsole/WEB-INF/classes/manifest.properties +#configuring hibernateHis for OAT appraiser setup +cp /tmp/OAT_Server_Install/hibernateOat.cfg.xml /tmp/ +cp /tmp/hibernateOat.cfg.xml $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisWebServices/WEB-INF/classes/ +cp /tmp/OAT_Server_Install/OAT.properties /etc/oat-appraiser/ +mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisWebServices/WEB-INF/classes/OpenAttestation.properties /etc/oat-appraiser/ +sed -i "s//$(hostname)/g" /etc/oat-appraiser/OpenAttestation.properties + +#sed -i "s/^truststore_path.*$/truststore_path=$TOMCAT_DIR_COFNIG_TYPE\/$TOMCAT_NAME\/Certificate\/TrustStore.jks/g" $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationAdminConsole/WEB-INF/classes/manifest.properties +sed -i "s/^truststore_path.*$/truststore_path=\/var\/lib\/oat-appraiser\/Certificate\/TrustStore.jks/g" /etc/oat-appraiser/OpenAttestation.properties + +sed -i "s/^TrustStore.*$/TrustStore=\/var\/lib\/oat-appraiser\/Certificate\/TrustStore.jks/g" /etc/oat-appraiser/OpenAttestation.properties + +mkdir -p /var/log/oat_ir +#placing OAT web portal in correct folder to be seen by tomcat6 + +rm -rf /${name}/OAT +unzip /${name}/OAT.zip -d /${name}/ +rm -rf /var/www/OAT +mv -f /${name}/OAT /var/www/OAT + +#setting the user and password in the OAT appraiser that will be used to access the mysql database. +sed -i 's/user = "root"/user = "oatAppraiser"/g' /var/www/OAT/includes/dbconnect.php +sed -i "s/pass = \"newpwd\"/pass = \"$randpass3\"/g" /var/www/OAT/includes/dbconnect.php + +#setting up OAT database to talk with the web portal correctly +rm -f /${name}/oatSetup.txt +unzip /${name}/oatSetup.zip -d /${name}/ +mysql -u root --database=oat_db < /${name}/oatSetup.txt + +#stop mysql service +if [ "`netstat -nutlp | grep :3306 | grep mysql`" ]; then + service mysql stop +fi + +#start mysql service +if [ ! `netstat -nutlp | grep :3306 | grep mysql` ]; then + service mysql start +fi + +#this code sets up the certificate attached to this computers hostname +#cd $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/Certificate/ + +cd /var/lib/oat-appraiser/Certificate/ +echo "127.0.0.1 `hostname`" >> /etc/hosts +if [ "`echo $p12pass | grep $randpass`" ] ; then + openssl req -x509 -nodes -days 730 -newkey rsa:2048 -keyout hostname.pem -out hostname.cer -subj "/C=US/O=U.S. Government/OU=DoD/CN=`hostname`" + openssl pkcs12 -export -in hostname.cer -inkey hostname.pem -out $p12file -passout pass:$p12pass +fi + +keytool -importkeystore -srckeystore $p12file -destkeystore $keystore -srcstoretype pkcs12 -srcstorepass $p12pass -deststoretype jks -deststorepass $p12pass -noprompt + +myalias=`keytool -list -v -keystore $keystore -storepass $p12pass | grep -B2 'PrivateKeyEntry' | grep 'Alias name:'` + +keytool -changealias -alias ${myalias#*:} -destalias tomcat -v -keystore $keystore -storepass $p12pass + +rm -f $truststore +keytool -import -keystore $truststore -storepass password -file hostname.cer -noprompt + +#sets up the tomcat6 service +chmod -R 755 $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/service/* +#cp /${name}/tomcat6 /etc/init.d/ +#chkconfig tomcat6 --add +#chkconfig tomcat6 on + + +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2.war + +# TOAT IS THE BEGINNING OF THE PCA PORTION +#rm -rf /%{name}/OAT_PrivacyCA_Install +#unzip /%{name}/OAT_PrivacyCA_Install.zip -d /%{name}/ +#rm -rf /tmp/OAT_PrivacyCA_Install +#mv /%{name}/OAT_PrivacyCA_Install /tmp/OAT_PrivacyCA_Install + +chmod 777 /tmp +sleep 10 +#catalina.sh +sed -i "/^#CATALINA_BIN/d" /etc/init.d/tomcat6 +sed -i "s/^CATALINA_BIN/#TOMCAT_DIR/g" /etc/init.d/tomcat6 +sed -i "/^#TOMCAT_DIR/i\\TOMCAT_DIR=\'$TOMCAT_INSTALL_DIR/$TOMCAT_NAME\';" /etc/init.d/tomcat6 + +service tomcat6 start + +# TOAT FOR LOOP IS NEEDED TO MAKE SURE THAT TOMCAT6 IS STARTED WELL BEFORE THE .WAR FILE IS MOVED +for((i = 1; i < 60; i++)) +do + + rm -f ./serviceLog + + service tomcat6 status | grep "running" >> ./serviceLog + + if [ -s ./serviceLog ]; then + + echo tomcat6 has started! +# rm -f ./serviceLog + sleep 10 + break + fi + + sleep 1 + + echo If this file is present after install then starting tomcat6 timed-out >> serviceLog + +done + +#moves the war file to webapps folder to unpack it +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2.war +cp /${name}/HisPrivacyCAWebServices2.war $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/ +#unzip $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2.war -d $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2 +# This for loop makes the rpm wait until the .war file has unpacked before attempting to access the files that will be created +for((i = 1; i < 60; i++)) +do + + rm -f ./warLog + + if [ -e /var/lib/oat-appraiser -a -e /var/lib/oat-appraiser/ClientFiles/OATprovisioner.properties ]; then + + + echo the Privacy CA was unpacked! + rm -f ./warLog + sleep 5 + break + fi + + sleep 5 + + echo If this file is present after install then unpacking the Privacy CA war file timed-out >> warLog + +done + +#this is a script to re-run certificate creation using new p12 files after installation +rm -rf /${name}/clientInstallRefresh.sh +rm -rf /${name}/linuxClientInstallRefresh.sh +cur_dir=$(pwd) +unzip /${name}/clientInstallRefresh.zip -d /${name}/ +unzip /${name}/linuxClientInstallRefresh.zip -d /${name}/ +cd /${name}/ +sed -i "s/\/usr\/lib\/apache-tomcat-6.0.29/$TOMCAT_DIR_COFNIG_TYPE\/$TOMCAT_NAME/g" clientInstallRefresh.sh +sed -i "s/\/usr\/lib\/apache-tomcat-6.0.29/$TOMCAT_DIR_COFNIG_TYPE\/$TOMCAT_NAME/g" linuxClientInstallRefresh.sh + +rm -rf clientInstallRefresh.zip +rm -rf linuxClientInstallRefresh.zip + +mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/lib /var/lib/oat-appraiser/ClientFiles/ +mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/TPMModule.properties /var/lib/oat-appraiser/ClientFiles/ +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/CaCerts +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/ +zip -9 linuxClientInstallRefresh.zip linuxClientInstallRefresh.sh +zip -9 clientInstallRefresh.zip clientInstallRefresh.sh +#test Q +cp -rf linuxClientInstallRefresh.zip /tmp +cd $cur_dir + +rm -rf /${name}/installers +#unzip /%{name}/ClientInstall.zip -d /%{name}/ +unzip /${name}/ClientInstallForLinux.zip -d /${name}/ + +sleep 5 + +# zky: similar from here +#rm -f /%{name}/ClientInstallOld.zip +#mv /%{name}/ClientInstall.zip /%{name}/ClientInstallOld.zip + +#rm -rf /%{name}/ClientInstall +#mkdir /%{name}/ClientInstall + +#This code grabs all of the needed files from the privacy CA folder and packages them into a Client Installation folder +#cp -r -f /%{name}/installers /%{name}/ClientInstall + +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/endorsement.p12 /%{name}/ClientInstall/installers/hisInstall/ +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/lib /%{name}/ClientInstall/installers/hisInstall/ +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/TPMModule.properties /%{name}/ClientInstall/installers/hisInstall/ +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/exe /%{name}/ClientInstall/installers/hisInstall/ +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/PrivacyCA.cer /%{name}/ClientInstall/installers/hisInstall/ +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/TrustStore.jks /%{name}/ClientInstall/installers/hisInstall/ +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/OATprovisioner.properties /%{name}/ClientInstall/installers/hisInstall/ +##DWC added two following lines for Chris +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/install.bat /%{name}/ClientInstall/installers/hisInstall/ +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/OAT.properties /%{name}/ClientInstall/installers/hisInstall/ +# +##privacy.jar for windows +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/lib/PrivacyCA.jar /%{name}/ClientInstall/installers/hisInstall/lib + + +#cd /%{name}/; zip -9 -r ClientInstall.zip ClientInstall + + +#places the client installation folder up for tomcat6 to display +#cp -f /%{name}/ClientInstall.zip /var/www/html/ + +#zky: for linux, do similar things +rm -f /${name}/ClientInstallForLinuxOld.zip +mv /${name}/ClientInstallForLinux.zip /${name}/ClientInstallForLinuxOld.zip + +rm -rf /${name}/ClientInstallForLinux + +cp -r -f /${name}/linuxOatInstall /${name}/ClientInstallForLinux + +cp /OAT-Appraiser-Base/OAT_Standalone.jar /OAT-Appraiser-Base/ClientInstallForLinux/ +cp -r /OAT-Appraiser-Base/lib /OAT-Appraiser-Base/ClientInstallForLinux/ + + +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/endorsement.p12 /${name}/ClientInstallForLinux/ +cp -r -f /var/lib/oat-appraiser/ClientFiles/PrivacyCA.cer /${name}/ClientInstallForLinux/ +cp -r -f /var/lib/oat-appraiser/ClientFiles/TrustStore.jks /${name}/ClientInstallForLinux/ +cp -r -f /var/lib/oat-appraiser/ClientFiles/OATprovisioner.properties /${name}/ClientInstallForLinux/ +sed -i '/ClientPath/s/C:.*/\/OAT/' /${name}/ClientInstallForLinux/OATprovisioner.properties +#remove credential information here +sed -i '/TpmEndorsmentP12/d' /${name}/ClientInstallForLinux/OATprovisioner.properties +sed -i '/EndorsementP12Pass/d' /${name}/ClientInstallForLinux/OATprovisioner.properties +#end remove +cp -r -f /var/lib/oat-appraiser/ClientFiles/OAT.properties /${name}/ClientInstallForLinux/ +sed -i 's/NIARL_TPM_Module\.exe/NIARL_TPM_Module/g' /${name}/ClientInstallForLinux/OAT.properties +sed -i 's/HIS07\.jpg/OAT07\.jpg/g' /${name}/ClientInstallForLinux/OAT.properties +cd /${name}/; zip -9 -r ClientInstallForLinux.zip ClientInstallForLinux + +#Test +cp -f /${name}/ClientInstallForLinux.zip /tmp/ +# + + +#places the client installation folder up for tomcat6 to display +cp -f /${name}/ClientInstallForLinux.zip /var/www/ + + +#creates the web page that allows access for the download of the client files folder +echo "" >> /var/www/ClientInstaller.html +echo "" >> /var/www/ClientInstaller.html +#echo "

Client Installation Files

" >> /var/www/html/ClientInstaller.html +echo "

Client Installation Files For Linux

" >> /var/www/ClientInstaller.html +echo "" >> /var/www/ClientInstaller.html +echo "" >> /var/www/ClientInstaller.html + +chmod 755 /var/www/Client* + + +#closes some known security holes in tomcat6 +#sed -i "s/AllowOverride None/AllowOverride All/" /etc/httpd/conf/httpd.conf +#echo "TraceEnable Off" >> /etc/httpd/conf/httpd.conf +sed -i "s/ServerTokens OS/ServerTokens Prod/" /etc/apache2/conf.d/security +sed -i "s/Options Indexes/Options/" /etc/apache2/sites-available/default +sed -i "s/Options Indexes/Options/" /etc/apache2/sites-available/default-ssl +sed -i "s/Options Indexes/Options/" /etc/apache2/mods-available/alias.conf +sed -i "s/Options Indexes/Options/" /etc/apache2/sites-enabled/000-default +/etc/init.d/apache2 restart +#sed -i "s/expose_php = On/expose_php = Off/" /etc/php.ini + +#rm -f /etc/httpd/conf.d/welcome.conf +#echo "" >> /etc/httpd/conf.d/welcome.conf + + + +####################################################################### +printf "done\n" diff --git a/OpenAttestation/Installer/DPKG-OAT-Appraiser-Base/DEBIAN/postrm b/OpenAttestation/Installer/DPKG-OAT-Appraiser-Base/DEBIAN/postrm new file mode 100644 index 0000000..02e2f55 --- /dev/null +++ b/OpenAttestation/Installer/DPKG-OAT-Appraiser-Base/DEBIAN/postrm @@ -0,0 +1,75 @@ +#! /bin/bash + +TOMCAT_INSTALL_DIR2=/usr/lib +TOMCAT_NAME2=apache-tomcat-6.0.29 +name=OAT-Appraiser-Base + +if [ $TOMCAT_DIR -a -d $TOMCAT_DIR ];then + if [[ ${TOMCAT_DIR:$((${#TOMCAT_DIR}-1)):1} == / ]];then + TOMCAT_DIR_TMP=${TOMCAT_DIR:0:$((${#TOMCAT_DIR}-1))} + else + TOMCAT_DIR_TMP=$TOMCAT_DIR + fi + + TOMCAT_INSTALL_DIR2=${TOMCAT_DIR_TMP%/*} + TOMCAT_NAME2=${TOMCAT_DIR_TMP##*/} +fi +service tomcat6 stop +update-rc.d -f tomcat6 remove 1>>/dev/null +sed -i "/<\/Service>/d" $TOMCAT_INSTALL_DIR2/$TOMCAT_NAME2/conf/server.xml +sed -i "/<\/Server>/i\\ <\/Service>" $TOMCAT_INSTALL_DIR2/$TOMCAT_NAME2/conf/server.xml +rm -rf /$name/ +#stop tomcat service and remove apache-tomcat +kill -9 `ps -ef | grep tomcat | grep -v grep | awk '{print $2}'` +if [ -d /usr/lib/apache-tomcat-6.0.29 ];then +rm -f -r $TOMCAT_INSTALL_DIR2/apache-tomcat-6.0.29.tar.gz +rm -rf $TOMCAT_INSTALL_DIR2/apache-tomcat-6.0.29 +fi +if [ -d /etc/oat-appraiser ] +then +rm -rf /etc/oat-appraiser +fi + +if [ -d /var/lib/oat-appraiser ] +then +rm -rf /var/lib/oat-appraiser +fi + +#OAT_Server +rm -f -r /tmp/OAT_Server_Install +rm -f -r /var/www/OAT + +#OAT_PrivacyCA +#rm -f -r /tmp/OAT_PrivacyCA_Install +#rm -f -r /var/www/html/ClientInstall.zip +rm -f -r /var/www/ClientInstallForLinux.zip +rm -f -r /var/www/ClientInstaller.html + +#removes both the OAT mysql database and the hisAppraiser mysql user +#stop mysql and tomcat service +MYSQL=`netstat -nutlp | grep :3306 | grep mysql` +if [ "$MYSQL" ]; then + service mysql stop +fi +ISSKIPGRANTEXIT=`grep skip-grant-tables /etc/mysql/my.cnf` +if [ ! "$ISSKIPGRANTEXIT" ]; then + sed -i 's/\[mysqld\]/\[mysqld\]\nskip-grant-tables/g' /etc/mysql/my.cnf +fi +if [ ! `netstat -nutlp | grep :3306 | grep mysql` ]; then + service mysql start +fi + +mysql -u root --execute="FLUSH PRIVILEGES; DROP DATABASE IF EXISTS oat_db; DELETE FROM mysql.user WHERE User='oatAppraiser' and Host='localhost';" + +printf "OAT database removed\n" + +if [ "`netstat -nutlp | grep :3306 | grep mysql`" ]; then + service mysql stop +fi + +sed -i 's/skip-grant-tables//g' /etc/mysql/my.cnf + +if [ ! `netstat -nutlp | grep :3306 | grep mysql` ]; then + service mysql start +fi + diff --git a/OpenAttestation/Installer/DPKG-OAT-Appraiser-Base/tomcat6.deb b/OpenAttestation/Installer/DPKG-OAT-Appraiser-Base/tomcat6.deb new file mode 100644 index 0000000..d449924 --- /dev/null +++ b/OpenAttestation/Installer/DPKG-OAT-Appraiser-Base/tomcat6.deb @@ -0,0 +1,106 @@ +#!/bin/sh +# +# "$Id: catalina ,v 1.0 2010/08/10 Chris_g Exp $" +# +# Startup/shutdown script for tomcat(Catalina) Application server. +# +# Linux chkconfig stuff: +# +# chkconfig: 2345 56 10 +# description: Startup/shutdown script for the tomcat application server. +###### +#test + +# Define where the catalina.sh script is located. +###### +TOMCAT_DIR='/usr/lib/apache-tomcat-6.0.29'; +#CATALINA_BIN='/usr/lib/apache-tomcat-6.0.29/bin/catalina.sh 1> /dev/null'; + +# Find the catalina process using ps / awk. +# The match function will return 0 when no match is found with the string "java". +# Position $9 should contain the path to the Java executable used by catalina. +###### +PROC=`ps -efc | grep apache.catalina | awk 'BEGIN { FS=" "}; { if( match($9, "java") != 0 ) print $9;}'` + +# Replace a potential empty string with a fake process so the RH daemon functions are able to parse +# it properly +###### +if [ ! "$PROC" ]; then + PROC='Tomcat_JVM'; +fi +echo $PROC + +# Define the application name that is listed in the daemonize step. +PROG='Tomcat JVM'; + +# LOCKFILE +LOCK='/var/lock/subsys/tomcat'; +if [ ! -d "/var/lock/subsys" ] +then + mkdir /var/lock/subsys +fi +start () { + echo -n "Starting $PROG: " + + if [ -f /etc/oat-appraiser/OAT.properties ]; then + . /etc/oat-appraiser/OAT.properties >> /dev/null 2>&1 + IR_DIR=$(echo $IR_DIR|tr -d '\r') + if [ ! -d $IR_DIR ]; then + echo "Missing directory $IR_DIR" + echo "Unable to start $PROG" + exit 6; + fi + fi + + # start daemon + $TOMCAT_DIR/bin/catalina.sh 1>/dev/null start + RETVAL=$? + echo + [ $RETVAL = 0 ] && touch $LOCK + return $RETVAL +} + +stop () { + # stop daemon + echo -n "Stopping $PROG: " +# killall $PROC + $TOMCAT_DIR/bin/shutdown.sh 1>/dev/null + RETVAL=$? + echo + [ $RETVAL = 0 ] && rm -f $LOCK +} + +restart() { + stop + start +} + + + +case $1 in + start) + start + ;; + stop) + stop + ;; + restart) + restart + ;; + status) + STAT=`pidof $PROC` + if [ "$STAT" ] + then + echo "tomcat6 start/running... $STAT" + else + echo "tomcat6 wait/stopping..." + fi + ;; + *) + + echo "Usage: $prog {start|stop|restart|status}" + exit 3 +esac + +exit $RETVAL + diff --git a/OpenAttestation/Installer/FilesForLinux/OAT.sh b/OpenAttestation/Installer/FilesForLinux/OAT.sh new file mode 100644 index 0000000..ae4fdcd --- /dev/null +++ b/OpenAttestation/Installer/FilesForLinux/OAT.sh @@ -0,0 +1,113 @@ +#!/bin/bash +# +# +# /etc/rc.d/init.d/OAT +# +# OAT This shell script takes care of starting and stopping +# the OAT daemon. +# +# chkconfig: 2345 99 99 +# description: Host Integrity at Startup (OAT) sends a TCG defined Integrity Report on startup.. +# processname: hisd + +# Source function library. +. /etc/init.d/functions + +JAVA=/usr/bin/java +TROUSERS=/usr/sbin/tcsd +prog="java" +OATD=/OAT/OAT_Standalone.jar +pid_file=/var/run/his.pid +lock_file=/var/lock/subsys/his +log_file=/var/log/OAT.log +RETVAL=0 + +[ -x ${TROUSERS} ] || exit 0 +service tcsd status || failure $"tcsd needs to be running" || exit 0 +[ -x ${JAVA} ] || exit 0 + +OAT_status(){ + if [ -e "$pid_file" ]; then + pid=$"`cat $pid_file`" + item=`ps aux | grep "$pid\ "` + if [ $"$item" ]; then + echo $"OAT (pid $pid) is running..." + else + echo $"OAT is stopped" + fi + else + echo $"OAT is stopped" + fi +} + +start() { + #[ -x $OATD ] || exit 5 + [ -f /OAT/OAT.properties ] || exit 6 + + echo -n $"Starting $OATD: " + $JAVA -jar $OATD /OAT/ -d > "$log_file" 2>&1 & + PID=$! + RETVAL=$? + [ "$RETVAL" = 0 ] && touch $lock_file && echo $PID > $pid_file + echo + return $RETVAL +} + +stop() { + #[ -x $OATD ] || exit 5 + [ -f /OAT/OAT.properties ] || exit 6 + #echo $pid_file + if [ -e "$pid_file" ] ; then + pid=$"`cat $pid_file`" + kill -9 $pid + item=`ps aux | grep "$pid\ "` + #echo $item + if [ $"$item" ]; then + failure $"Stopping $OATD" + else + success $"Stopping $OATD" + fi + else + failure $"Stopping $OATD" + fi + RETVAL=$? + # if we are in halt or reboot runlevel kill all running sessions + # so the OAT connections are closed cleanly + if [ "x$runlevel" = x0 -o "x$runlevel" = x6 ] ; then + trap '' TERM + killall $prog 2>/dev/null + trap TERM + fi + [ "$RETVAL" = 0 ] && rm -f $lock_file && rm -f $pid_file + echo +} + +restart() { + stop + start +} + +status() { + OAT_status + RETURN=$? +} + +case "$1" in + start) + start + ;; + stop) + stop + ;; + restart) + restart + ;; + status) + status + ;; + *) + echo "Usage: his {start|stop|restart|status}" + exit 1 + ;; +esac +exit $? diff --git a/OpenAttestation/Installer/FilesForLinux/general-install.sh b/OpenAttestation/Installer/FilesForLinux/general-install.sh new file mode 100644 index 0000000..1c0e9bd --- /dev/null +++ b/OpenAttestation/Installer/FilesForLinux/general-install.sh @@ -0,0 +1,82 @@ +#!/bin/bash + +# default +dist="fedora" + +#ec storage type, file or NVARM +ecStorage=-ecs +sed -i "s/^ecStorage.*$/ecStorage = NVRAM/g" OATprovisioner.properties +if [ $# -ge 2 ];then + if [ $1 = $ecStorage ];then + sed -i "s/^ecStorage.*$/ecStorage = $2/g" OATprovisioner.properties + fi +fi + +# check distrition +if [ -f /etc/issue ]; then +if [ -n "`grep -i 'ubuntu' /etc/issue`" ]; then + echo "Linux distribution is Ubuntu" + dist="ubuntu" +fi + +if [ -n "`grep -i 'suse' /etc/issue`" ]; then + echo "Linux distribution is SUSE" + dist="suse" +fi + +if [ -n "`grep -i 'fedora' /etc/issue`" ]; then + echo "Linux distribution is Fedora" + dist="fedora" +fi +fi + + +# unpack OAT client files +if [ -d /OAT/ ]; then +rm -rf /OAT/* +else +mkdir /OAT/ +fi +chmod -R a+w /OAT/ + +cp shells/$dist.sh /OAT/OAT.sh +chmod +x /OAT/OAT.sh +cp -f OAT_Standalone.jar /OAT +touch /OAT/log4j.properties +cp -rf lib/ /OAT +cp -f /OAT/OAT.sh /etc/init.d/OATClient +cp -f OAT.properties /OAT +cp -f TrustStore.jks /OAT +cp -f NIARL_TPM_Module /OAT + +rm -f /OAT/uninstallOAT.sh +echo "/etc/init.d/OATClient stop" >> /OAT/uninstallOAT.sh +echo "rm -rf /OAT" >> /OAT/uninstallOAT.sh +echo "rm -f /etc/init.d/OATClient" >> /OAT/uninstallOAT.sh + +# let it run at startup +if [ "$dist" = "fedora" ]; then + ln -fs /etc/init.d/OATClient /etc/rc5.d/S99OATClient + ln -fs /etc/init.d/OATClient /etc/rc3.d/S99OATClient + chkconfig OATClient on + echo "rm -f /etc/rc5.d/S99OATClient" >> /OAT/uninstallOAT.sh + echo "rm -f /etc/rc3.d/S99OATClient" >> /OAT/uninstallOAT.sh +fi + +if [ "$dist" = "suse" ]; then + ln -fs /etc/init.d/OATClient /etc/init.d/rc5.d/S99OATClient + ln -fs /etc/init.d/OATClient /etc/init.d/rc3.d/S99OATClient + chkconfig OATClient on + echo "rm -f /etc/init.d/rc5.d/S99OATClient" >> /OAT/uninstallOAT.sh + echo "rm -f /etc/init.d/rc3.d/S99OATClient" >> /OAT/uninstallOAT.sh +fi + +if [ "$dist" = "ubuntu" ]; then + update-rc.d OATClient defaults 99 + update-rc.d OATClient enable + echo "update-rc.d OATClient disable" >> /OAT/uninstallOAT.sh + echo "update-rc.d -f OATClient remove" >> /OAT/uninstallOAT.sh +fi + +# OAT provisioning +bash provisioner.sh diff --git a/OpenAttestation/Installer/FilesForLinux/init.sql b/OpenAttestation/Installer/FilesForLinux/init.sql new file mode 100644 index 0000000..7cc14de --- /dev/null +++ b/OpenAttestation/Installer/FilesForLinux/init.sql @@ -0,0 +1,158 @@ +USE oat_db; + +CREATE TABLE `PCR_manifest` ( + `index` int(11) NOT NULL AUTO_INCREMENT, + `PCR_number` int(11) DEFAULT NULL, + `PCR_value` varchar(100) DEFAULT NULL, + `PCR_desc` varchar(100) DEFAULT NULL, + `create_time` datetime DEFAULT NULL, + `create_request_host` varchar(50) DEFAULT NULL, + `last_update_time` datetime DEFAULT NULL, + `last_update_request_host` varchar(50) DEFAULT NULL, + PRIMARY KEY (`index`), + UNIQUE KEY `PCR_UNIQUE` (`PCR_number`,`PCR_value`) +); + +CREATE TABLE `attest_request` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `request_id` varchar(50) DEFAULT NULL, + `host_name` varchar(50) DEFAULT NULL, + `request_time` datetime DEFAULT NULL, + `next_action` int(11) DEFAULT NULL, + `is_consumed_by_pollingWS` tinyint(1) DEFAULT NULL, + `audit_log_id` int(11) DEFAULT NULL, + `host_id` int(11) DEFAULT NULL, + `request_host` varchar(50) DEFAULT NULL, + `count` int(11) DEFAULT NULL, + `PCRMask` varchar(50) DEFAULT NULL, + `result` int(11) DEFAULT NULL, + `is_sync` tinyint(1) DEFAULT NULL, + `validate_time` datetime DEFAULT NULL, + `analysis_request` varchar(1320) DEFAULT NULL, + `analysis_results` varchar(1320) DEFAULT NULL, + `threshold` bigint DEFAULT NULL, + `expiration_time` datetime DEFAULT NULL, + `last_read_time` datetime DEFAULT NULL, + `current_processing_time` bigint DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `FK_audit_log_id` (`audit_log_id`), + KEY `UNIQUE` (`request_id`,`host_id`) +); + + + +/*==============================================================*/ +/* DBMS name: MySQL 5.0 */ +/* Created on: 2012/9/7 10:13:55 */ +/*==============================================================*/ + + +drop table if exists HOST; + +drop table if exists MLE; + +drop table if exists OEM; + +drop table if exists OS; + +drop table if exists PCR_WHITE_LIST; + + +/*==============================================================*/ +/* Table: HOST */ +/*==============================================================*/ +create table HOST +( + ID int not null auto_increment, + HOST_NAME varchar(50), + IP_ADDRESS varchar(50), + PORT varchar(50), + EMAIL varchar(100), + ADDON_CONNECTION_STRING varchar(100), + DESCRIPTION varchar(100), + PCR_IML_MASK varchar(50), + primary key (ID) +); + +/*==============================================================*/ +/* Table: MLE */ +/*==============================================================*/ +create table MLE +( + ID int not null auto_increment, + OEM_ID int, + OS_ID int, + NAME varchar(50), + VERSION varchar(100), + ATTESTATION_TYPE varchar(50), + MLE_TYPE varchar(50), + DESCRIPTION varchar(100), + primary key (ID) +); + +/*==============================================================*/ +/* Table: HOST_MLE */ +/*==============================================================*/ +create table HOST_MLE +( + ID int not null auto_increment, + HOST_ID int , + MLE_ID int , + primary key (ID) , + FOREIGN KEY (HOST_ID) REFERENCES HOST(ID) ON DELETE CASCADE , + CONSTRAINT mle_fk FOREIGN KEY (MLE_ID) REFERENCES MLE(ID) +); + + +/*==============================================================*/ +/* Table: OEM */ +/*==============================================================*/ +create table OEM +( + ID int not null auto_increment, + NAME varchar(50), + DESCRIPTION varchar(100), + primary key (ID) +); + +/*==============================================================*/ +/* Table: OS */ +/*==============================================================*/ +create table OS +( + ID int not null auto_increment, + NAME varchar(50), + VERSION varchar(50), + DESCRIPTION varchar(100), + primary key (ID) +); + +/*==============================================================*/ +/* Table: PCR_WHITE_LIST */ +/*==============================================================*/ +create table PCR_WHITE_LIST +( + ID int not null auto_increment, + MLE_ID int, + PCR_NAME varchar(10), + PCR_DIGEST varchar(100) default NULL, + primary key (ID) +); + +/*==============================================================*/ +/* Table: analysis_types */ +/*==============================================================*/ +CREATE TABLE analysis_types ( + id int(11) NOT NULL AUTO_INCREMENT, + name varchar(64) NOT NULL, + module varchar(64) NOT NULL, + version int NOT NULL, + url varchar(256) NOT NULL, + deleted tinyint(1) NOT NULL DEFAULT 0, + required_pcr_mask varchar(50) DEFAULT NULL, + PRIMARY KEY (id) +); + +/*==============================================================*/ +/* End */ +/*==============================================================*/ diff --git a/OpenAttestation/Installer/FilesForLinux/install.sh b/OpenAttestation/Installer/FilesForLinux/install.sh new file mode 100644 index 0000000..28c832b --- /dev/null +++ b/OpenAttestation/Installer/FilesForLinux/install.sh @@ -0,0 +1,8 @@ +#call UninstallUSW.bat +rpm -ivh NIARL_OAT_Standalone-2.0-1.x86_64.rpm +cp -f OAT.properties /OAT +cp -f TrustStore.jks /OAT +cp -f NIARL_TPM_Module /OAT +sh provisioner.sh +#cd "C:\Program Files\NIARL\HIS\service\" +#call "replaceUSW.bat" diff --git a/OpenAttestation/Installer/FilesForLinux/shells/fedora.sh b/OpenAttestation/Installer/FilesForLinux/shells/fedora.sh new file mode 100644 index 0000000..ae4fdcd --- /dev/null +++ b/OpenAttestation/Installer/FilesForLinux/shells/fedora.sh @@ -0,0 +1,113 @@ +#!/bin/bash +# +# +# /etc/rc.d/init.d/OAT +# +# OAT This shell script takes care of starting and stopping +# the OAT daemon. +# +# chkconfig: 2345 99 99 +# description: Host Integrity at Startup (OAT) sends a TCG defined Integrity Report on startup.. +# processname: hisd + +# Source function library. +. /etc/init.d/functions + +JAVA=/usr/bin/java +TROUSERS=/usr/sbin/tcsd +prog="java" +OATD=/OAT/OAT_Standalone.jar +pid_file=/var/run/his.pid +lock_file=/var/lock/subsys/his +log_file=/var/log/OAT.log +RETVAL=0 + +[ -x ${TROUSERS} ] || exit 0 +service tcsd status || failure $"tcsd needs to be running" || exit 0 +[ -x ${JAVA} ] || exit 0 + +OAT_status(){ + if [ -e "$pid_file" ]; then + pid=$"`cat $pid_file`" + item=`ps aux | grep "$pid\ "` + if [ $"$item" ]; then + echo $"OAT (pid $pid) is running..." + else + echo $"OAT is stopped" + fi + else + echo $"OAT is stopped" + fi +} + +start() { + #[ -x $OATD ] || exit 5 + [ -f /OAT/OAT.properties ] || exit 6 + + echo -n $"Starting $OATD: " + $JAVA -jar $OATD /OAT/ -d > "$log_file" 2>&1 & + PID=$! + RETVAL=$? + [ "$RETVAL" = 0 ] && touch $lock_file && echo $PID > $pid_file + echo + return $RETVAL +} + +stop() { + #[ -x $OATD ] || exit 5 + [ -f /OAT/OAT.properties ] || exit 6 + #echo $pid_file + if [ -e "$pid_file" ] ; then + pid=$"`cat $pid_file`" + kill -9 $pid + item=`ps aux | grep "$pid\ "` + #echo $item + if [ $"$item" ]; then + failure $"Stopping $OATD" + else + success $"Stopping $OATD" + fi + else + failure $"Stopping $OATD" + fi + RETVAL=$? + # if we are in halt or reboot runlevel kill all running sessions + # so the OAT connections are closed cleanly + if [ "x$runlevel" = x0 -o "x$runlevel" = x6 ] ; then + trap '' TERM + killall $prog 2>/dev/null + trap TERM + fi + [ "$RETVAL" = 0 ] && rm -f $lock_file && rm -f $pid_file + echo +} + +restart() { + stop + start +} + +status() { + OAT_status + RETURN=$? +} + +case "$1" in + start) + start + ;; + stop) + stop + ;; + restart) + restart + ;; + status) + status + ;; + *) + echo "Usage: his {start|stop|restart|status}" + exit 1 + ;; +esac +exit $? diff --git a/OpenAttestation/Installer/FilesForLinux/shells/suse.sh b/OpenAttestation/Installer/FilesForLinux/shells/suse.sh new file mode 100644 index 0000000..8a02220 --- /dev/null +++ b/OpenAttestation/Installer/FilesForLinux/shells/suse.sh @@ -0,0 +1,117 @@ +#!/bin/bash +# +# +# /etc/rc.d/init.d/HIS +# +# HIS This shell script takes care of starting and stopping +# the HIS daemon. +# +# chkconfig: 2345 99 99 +# description: Host Integrity at Startup (HIS) sends a TCG defined Integrity Report on startup.. +# processname: hisd + +# Source function library. +. /etc/rc.status +rc_reset + +JAVA=/usr/bin/java +TROUSERS=/usr/sbin/tcsd +prog="java" +HISD=/OAT/OAT_Standalone.jar +pid_file=/var/run/his.pid +lock_file=/var/lock/subsys/his +log_file=/var/log/OAT.log +RETVAL=0 + +[ -x ${TROUSERS} ] || exit 0 +service tcsd status || echo $"tcsd needs to be running" || exit 0 +[ -x ${JAVA} ] || exit 0 + +HIS_status(){ + if [ -e "$pid_file" ]; then + pid=$"`cat $pid_file`" + item=`ps aux | grep "$pid "` + if [ $"$item" ]; then + echo $"OAT (pid $pid) is running..." + else + echo $"OAT is stopped" + fi + else + echo $"OAT is stopped" + fi +} + +start() { + #[ -x $HISD ] || exit 5 + [ -f /OAT/OAT.properties ] || exit 6 + + echo -n $"Starting $HISD: " + $JAVA -jar $HISD /OAT/ -d > "$log_file" 2>&1 & + PID=$! + RETVAL=$? + [ "$RETVAL" = 0 ] && touch $lock_file && echo $PID > $pid_file + echo + return $RETVAL +} + +stop() { + #[ -x $HISD ] || exit 5 + [ -f /OAT/OAT.properties ] || exit 6 + #echo $pid_file + if [ -e "$pid_file" ] ; then + pid=$"`cat $pid_file`" + kill -9 $pid + item=`ps aux | grep "$pid\ "` + #echo $item + if [ $"$item" ]; then + echo $"Stopping $HISD" + else + echo $"Stopping $HISD" + fi + else + echo $"Stopping $HISD" + fi + RETVAL=$? + # if we are in halt or reboot runlevel kill all running sessions + # so the HIS connections are closed cleanly + if [ "x$runlevel" = x0 -o "x$runlevel" = x6 ] ; then + trap '' TERM + killall $prog 2>/dev/null + trap TERM + fi + [ "$RETVAL" = 0 ] && rm -f $lock_file && rm -f $pid_file + echo +} + +restart() { + stop + start +} + +status() { + HIS_status + RETURN=$? +} + +case "$1" in + start) + start + rc_status -v + ;; + stop) + stop + rc_status -v + ;; + restart) + restart + rc_status -v + ;; + status) + status + ;; + *) + echo "Usage: his {start|stop|restart|status}" + exit 1 + ;; +esac +exit $? diff --git a/OpenAttestation/Installer/FilesForLinux/shells/ubuntu.sh b/OpenAttestation/Installer/FilesForLinux/shells/ubuntu.sh new file mode 100644 index 0000000..e2db111 --- /dev/null +++ b/OpenAttestation/Installer/FilesForLinux/shells/ubuntu.sh @@ -0,0 +1,113 @@ +#!/bin/bash +# +# +# /etc/rc.d/init.d/OAT +# +# OAT This shell script takes care of starting and stopping +# the OAT daemon. +# +# chkconfig: 2345 99 99 +# description: Host Integrity at Startup (OAT) sends a TCG defined Integrity Report on startup.. +# processname: hisd + +# Source function library. + +JAVA=/usr/bin/java +TROUSERS=/usr/sbin/tcsd +prog="java" +OATD=/OAT/OAT_Standalone.jar +pid_file=/var/run/his.pid +mkdir -p /var/lock/subsys +lock_file=/var/lock/subsys/his +log_file=/var/log/OAT.log +RETVAL=0 + +[ -x ${TROUSERS} ] || exit 0 +service trousers status || echo $"tcsd needs to be running" || exit 0 +[ -x ${JAVA} ] || exit 0 + +OAT_status(){ + if [ -e "$pid_file" ]; then + pid=$"`cat $pid_file`" + item=`ps aux | grep "$pid\ "` + if [ $"$item" ]; then + echo $"OAT (pid $pid) is running..." + else + echo $"OAT is stopped" + fi + else + echo $"OAT is stopped" + fi +} + +start() { + #[ -x $OATD ] || exit 5 + [ -f /OAT/OAT.properties ] || exit 6 + + echo -n $"Starting $OATD: " + $JAVA -jar $OATD /OAT/ -d > "$log_file" 2>&1 & + PID=$! + RETVAL=$? + [ "$RETVAL" = 0 ] && touch $lock_file && echo $PID > $pid_file + echo + return $RETVAL +} + +stop() { + #[ -x $OATD ] || exit 5 + [ -f /OAT/OAT.properties ] || exit 6 + #echo $pid_file + if [ -e "$pid_file" ] ; then + pid=$"`cat $pid_file`" + kill -9 $pid + item=`ps aux | grep "$pid\ "` + #echo $item + if [ $"$item" ]; then + echo $"Stopping $OATD" + else + echo $"Stopping $OATD" + fi + else + echo $"Stopping $OATD" + fi + RETVAL=$? + # if we are in halt or reboot runlevel kill all running sessions + # so the OAT connections are closed cleanly + if [ "x$runlevel" = x0 -o "x$runlevel" = x6 ] ; then + trap '' TERM + killall $prog 2>/dev/null + trap TERM + fi + [ "$RETVAL" = 0 ] && rm -f $lock_file && rm -f $pid_file + echo +} + +restart() { + stop + start +} + +status() { + OAT_status + RETURN=$? +} + +case "$1" in + start) + start + ;; + stop) + stop + ;; + restart) + restart + ;; + status) + status + ;; + *) + echo "Usage: his {start|stop|restart|status}" + exit 1 + ;; +esac +exit $? diff --git a/OpenAttestation/Installer/OAT-Appraiser-Base-for-SLES.spec b/OpenAttestation/Installer/OAT-Appraiser-Base-for-SLES.spec new file mode 100644 index 0000000..53b3857 --- /dev/null +++ b/OpenAttestation/Installer/OAT-Appraiser-Base-for-SLES.spec @@ -0,0 +1,557 @@ +Name: OAT-Appraiser-Base +Summary: [OAT Crossbow] Host Integrity at Startup Installation of Appraiser Server +Version: 1.0.1 +Release: 2%{?dist} +License: DoD +Group: Department of Defense +Vendor: Department of Defense +Source: OAT-Appraiser-Base.tar.gz +BuildRoot: /var/tmp/%{name}-%{PACKAGE_VERSION} + +%description +Host Integrity at Startup (OAT) is a project that explores how software and processes on standard desktop computers can be measured to detect and report important and specific changes which highlight potential compromise of the host platform. OAT provides the first examples of effective Measurement and Attestation on the path toward trusted platforms. + +%package OATapp +Summary: The OAT Appraiser Base Install +Group: Department of Defense +#we use mysql for OAT Appraiser, and php is needed for the web portal +#openjdk 1.6 is not available anymore from the latest distro +#Requires: mysql, php5, php5-mysql, apache2, apache2-mod_php5, java-1_6_0-openjdk, openssl +Requires: mysql, php5, php5-mysql, apache2, apache2-mod_php5,openssl,xerces-j2 +%description OATapp +The Host Integrity at Startup Installation +of the OAT Appraiser Server Base Install +%prep +%setup -n %{name} +rm -rf $RPM_BUILD_ROOT +mkdir $RPM_BUILD_ROOT/ +cp -R $RPM_BUILD_DIR/%{name} $RPM_BUILD_ROOT + +%post OATapp +echo -ne "Making OAT Appraiser\n" + +#######Install script########################################################### +service mysql start +#TOMCAT_INSTALL_DIR=/usr/lib +#TOMCAT_INSTALL_DIR=$TOMCAT_DIR +#TOMCAT_DIR_COFNIG_TYPE=${TOMCAT_INSTALL_DIR//\//\\/} +##TOMCAT_NAME=apache-tomcat-6.0.35 +#TOMCAT_NAME=apache-tomcat-6.0.29 +#echo $TOMCAT_INSTALL_DIR > ~/rpm.log +#echo $TOMCAT_DIR_COFNIG_TYPE >> ~/rpm.log +TOMCAT_INSTALL_DIR=/usr/lib +TOMCAT_NAME=apache-tomcat-6.0.29 + +if [ -d /var/lib/oat-appraiser ] +then + rm -rf /var/lib/oat-appraiser + mkdir /var/lib/oat-appraiser + mkdir /var/lib/oat-appraiser/CaCerts + mkdir /var/lib/oat-appraiser/ClientFiles + mkdir /var/lib/oat-appraiser/Certificate +else + mkdir /var/lib/oat-appraiser + mkdir /var/lib/oat-appraiser/CaCerts + mkdir /var/lib/oat-appraiser/ClientFiles + mkdir /var/lib/oat-appraiser/Certificate +fi + + +if [ -d /etc/oat-appraiser ] +then + rm -rf /etc/oat-appraiser + mkdir /etc/oat-appraiser +else + mkdir /etc/oat-appraiser +fi + +if [ $TOMCAT_DIR -a -d $TOMCAT_DIR ];then + if [[ ${TOMCAT_DIR:$((${#TOMCAT_DIR}-1)):1} == / ]];then + TOMCAT_DIR_TMP=${TOMCAT_DIR:0:$((${#TOMCAT_DIR}-1))} + else + TOMCAT_DIR_TMP=$TOMCAT_DIR + fi + + TOMCAT_INSTALL_DIR=${TOMCAT_DIR_TMP%/*} + TOMCAT_NAME=${TOMCAT_DIR_TMP##*/} +fi +TOMCAT_DIR_COFNIG_TYPE=${TOMCAT_INSTALL_DIR//\//\\/} +echo $TOMCAT_INSTALL_DIR > ~/rpm.log +echo $TOMCAT_DIR_COFNIG_TYPE >> ~/rpm.log + +###Random generation /dev/urandom is good but just in case... +# Creating randoms for the p12 files and setting up truststore and keystore +ip12="internal.p12" +ipassfile="internal.pass" +idomfile="internal.domain" +iloc="/%{name}/" +p12file="$loc$ip12" +RAND1=$(dd if=/dev/urandom bs=1 count=1024) +RAND2=$(dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}') +RAND3=$(dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}') +randbits="$(echo "$( echo "`hwclock`" | md5sum | md5sum )$( echo "`dd if=/dev/urandom bs=1 count=1024`" | md5sum | md5sum)$(echo "`hwclock`" | md5sum | md5sum )$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`hwclock`" | md5sum | md5sum)$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`hwclock`" | md5sum | md5sum )" | md5sum | md5sum )" +randpass="${randbits:0:30}" +randbits2="$(echo "$( echo "`hwclock`" | md5sum | md5sum )$( echo "`dd if=/dev/urandom bs=1 count=1024`" | md5sum | md5sum)$(echo "`hwclock`" | md5sum | md5sum )$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`hwclock`" | md5sum | md5sum)$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`hwclock`" | md5sum | md5sum )" | md5sum | md5sum )" +randpass2="${randbits2:0:30}" +randbits3="$(echo "$( echo "`hwclock`" | md5sum | md5sum )$( echo "`dd if=/dev/urandom bs=1 count=1024`" | md5sum | md5sum)$(echo "`hwclock`" | md5sum | md5sum )$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`hwclock`" | md5sum | md5sum)$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`hwclock`" | md5sum | md5sum )" | md5sum | md5sum )" +randpass3="${randbits3:0:30}" +p12pass="$randpass" +mysqlPass="$randpass2" +keystore="keystore.jks" +truststore="TrustStore.jks" +if [ "`ls $iloc | grep $ip12`" ] && [ "`ls $iloc | grep $ipassfile`" ] ; then + p12pass="`cat $loc$ipassfile`" +fi +if [ "`ls $iloc | grep $idomfile`" ] ; then + domain="`cat $loc$idomfile`" +fi + +#ls -al /tomcat6 +service mysql stop +service tomcat6 stop + +sleep 10 + +#Configuring mysql so we can set up database and hisAppraiser profile +ISENGINE=`grep "default-storage-engine=INNODB" /etc/my.cnf` +if [ ! "$ISENGINE" ]; then + sed -i 's/\[mysqld\]/\[mysqld\]\ndefault-storage-engine=INNODB/g' /etc/my.cnf +fi + +#sed -i 's/--datadir="$datadir" --socket="$socketfile"/--datadir="$datadir" --skip-grant-tables --socket="$socketfile"/g' /etc/rc.d/init.d/mysql + +service mysql start + +#Sets up database and user +ISSKIPGRANTEXIT=`grep skip-grant-tables /etc/my.cnf` +if [ ! "$ISSKIPGRANTEXIT" ]; then + sed -i 's/\[mysqld\]/\[mysqld\]\nskip-grant-tables/g' /etc/my.cnf +fi + + +mysql -u root --execute="CREATE DATABASE oat_db; FLUSH PRIVILEGES; GRANT ALL ON oat_db.* TO 'oatAppraiser'@'localhost' IDENTIFIED BY '$randpass3';" + +service mysql stop + +#sed -i 's/--datadir="$datadir" --socket="$socketfile"/--datadir="$datadir" --skip-grant-tables --socket="$socketfile"/g' /etc/rc.d/init.d/mysql + + +#setting up tomcat at $TOMCAT_INSTALL_DIR/ +if [ $TOMCAT_NAME == apache-tomcat-6.0.29 ];then +rm -f $TOMCAT_INSTALL_DIR/apache-tomcat-6.0.29.tar.gz +mv /%{name}/apache-tomcat-6.0.29.tar.gz $TOMCAT_INSTALL_DIR/. +fi +unzip /%{name}/service.zip -d /%{name}/ +rm -f /%{name}/service.zip +cp /%{name}/tomcat6 /etc/init.d/ +#mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME $TOMCAT_INSTALL_DIR/apache-tomcat-old +if [ $TOMCAT_NAME == apache-tomcat-6.0.29 ];then +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME +tar -zxf $TOMCAT_INSTALL_DIR/apache-tomcat-6.0.29.tar.gz -C $TOMCAT_INSTALL_DIR/ +fi + +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/service +mv -f /%{name}/service $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/service +#rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/Certificate +#mkdir $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/Certificate +unzip /%{name}/setupProperties.zip -d /%{name}/ +mv /%{name}/setup.properties /etc/oat-appraiser/ + +rm -R -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/* + +#chkconfig --del NetworkManager +chkconfig apache2 on +chkconfig mysql on +service mysql start + +#running OAT database full setup +#rm -rf /%{name}/MySQLdrop.txt +#unzip /%{name}/MySQLdrop.zip -d /%{name}/ +#mysql -u root < /%{name}/MySQLdrop.txt +rm -rf /%{name}/OAT_Server_Install +unzip /%{name}/OAT_Server_Install.zip -d /%{name}/ +rm -rf /tmp/OAT_Server_Install +mv -f /%{name}/OAT_Server_Install /tmp/OAT_Server_Install +mysql -u root --execute="DROP DATABASE IF EXISTS oat_db;" +mysql -u root < /tmp/OAT_Server_Install/oat_db.MySQL +mysql -u root < /tmp/OAT_Server_Install/init.sql +#setting up access control in tomcat context.xml +#sed -i "/<\/Context>/i\\ " $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/conf/context.xml + +sed -i "/<\/Context>/i\\ " $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/conf/context.xml + +#setting up port 8443 in tomcat server.xml +sed -i "s/ <\/Service>/<\/Service>/g" $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/conf/server.xml + + + + +cp -R /tmp/OAT_Server_Install/HisWebServices $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/ +# +#if [ -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationAdminConsole.war ];then +# rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationAdminConsole.war +#fi +# +#if [ -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationManifestWebServices.war ];then +# rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationManifestWebServices.war +#fi +# +#if [ -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationWebServices.war ];then +# rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationWebServices.war +#fi + +cp /tmp/OAT_Server_Install/WLMService.war $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/ +cp /tmp/OAT_Server_Install/AttestationService.war $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/ +unzip $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/WLMService.war -d $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/WLMService +unzip $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/AttestationService.war -d $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/AttestationService +#delete the OpenAttestation war package +rm -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/WLMService.war +rm -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/AttestationService.war +mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/AttestationService/WEB-INF/classes/OpenAttestationWebServices.properties /etc/oat-appraiser/OpenAttestationWebServices.properties +sed -i "s//$(hostname)/g" /etc/oat-appraiser/OpenAttestationWebServices.properties +#configuring hibernateHis for OAT appraiser setup +cp /tmp/OAT_Server_Install/hibernateOat.cfg.xml /tmp/ +sed -i 's/root<\/property>/oatAppraiser<\/property>/' /tmp/hibernateOat.cfg.xml +sed -i "s/oat-password<\/property>/$randpass3<\/property>/" /tmp/hibernateOat.cfg.xml +cp /tmp/hibernateOat.cfg.xml $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisWebServices/WEB-INF/classes/ +cp /tmp/OAT_Server_Install/OAT.properties /etc/oat-appraiser/ +mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisWebServices/WEB-INF/classes/OpenAttestation.properties /etc/oat-appraiser/OpenAttestation.properties +sed -i "s//$(hostname)/g" /etc/oat-appraiser/OpenAttestation.properties + +sed -i "s/^truststore_path.*$/truststore_path=\/var\/lib\/oat-appraiser\/Certificate\/TrustStore.jks/g" /etc/oat-appraiser/OpenAttestation.properties + +sed -i "s/^TrustStore.*$/TrustStore=\/var\/lib\/oat-appraiser\/Certificate\/TrustStore.jks/g" /etc/oat-appraiser/OpenAttestation.properties + +mkdir -p /var/log/oat_ir +#placing OAT web portal in correct folder to be seen by tomcat6 +rm -rf /%{name}/OAT +unzip /%{name}/OAT.zip -d /%{name}/ +rm -rf /srv/www/htdocs/OAT +mv -f /%{name}/OAT /srv/www/htdocs/OAT + +#setting all files in the OAT portal to be compiant to selinux +#/sbin/restorecon -R '/srv/www/htdocsOAT' + +#setting the user and password in the OAT appraiser that will be used to access the mysql database. +sed -i 's/user = "root"/user = "oatAppraiser"/g' /srv/www/htdocs/OAT/includes/dbconnect.php +sed -i "s/pass = \"newpwd\"/pass = \"$randpass3\"/g" /srv/www/htdocs/OAT/includes/dbconnect.php + +#setting up OAT database to talk with the web portal correctly +rm -f /%{name}/oatSetup.txt +unzip /%{name}/oatSetup.zip -d /%{name}/ +mysql -u root --database=oat_db < /%{name}/oatSetup.txt + + +# This is setting the OAT mysql user to the password given to the Appraiser +#mysql -u root --database=mysql --execute="UPDATE user SET password=PASSWORD('newpwd') WHERE user='hisAppraiser';" +service mysql stop + +#sets configuration of mysql back to normal +#sed -i 's/--datadir="$datadir" --skip-grant-tables --socket="$socketfile"/--datadir="$datadir" --socket="$socketfile"/g' /etc/rc.d/init.d/mysql +ISSKIPGRANTEXIT=`grep nskip-grant-tables /etc/my.cnf` +if [ "$ISSKIPGRANTEXIT" ]; then + sed -i 's/skip-grant-tables//g' /etc/my.cnf +fi + + +service mysql start + + +#this code sets up the certificate attached to this computers hostname +#cd $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/Certificate/ +cd /var/lib/oat-appraiser/Certificate/ +echo "127.0.0.1 `hostname`" >> /etc/hosts +if [ "`echo $p12pass | grep $randpass`" ] ; then + openssl req -x509 -nodes -days 730 -newkey rsa:2048 -keyout hostname.pem -out hostname.cer -subj "/C=US/O=U.S. Government/OU=DoD/CN=`hostname`" + openssl pkcs12 -export -in hostname.cer -inkey hostname.pem -out $p12file -passout pass:$p12pass +fi + +keytool -importkeystore -srckeystore $p12file -destkeystore $keystore -srcstoretype pkcs12 -srcstorepass $p12pass -deststoretype jks -deststorepass $p12pass -noprompt + +myalias=`keytool -list -v -keystore $keystore -storepass $p12pass | grep -B2 'PrivateKeyEntry' | grep 'Alias name:'` + +keytool -changealias -alias ${myalias#*:} -destalias tomcat -v -keystore $keystore -storepass $p12pass + +rm -f $truststore +keytool -import -keystore $truststore -storepass password -file hostname.cer -noprompt + +#sets up the tomcat6 service +chmod -R 755 $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/service/* + +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2.war + +# TOAT IS THE BEGINNING OF THE PCA PORTION +#rm -rf /%{name}/OAT_PrivacyCA_Install +#unzip /%{name}/OAT_PrivacyCA_Install.zip -d /%{name}/ +#rm -rf /tmp/OAT_PrivacyCA_Install +#mv /%{name}/OAT_PrivacyCA_Install /tmp/OAT_PrivacyCA_Install + +chmod 777 /tmp +sleep 10 +#catalina.sh +service tomcat6 start + +# TOAT FOR LOOP IS NEEDED TO MAKE SURE THAT TOMCAT6 IS STARTED WELL BEFORE THE .WAR FILE IS MOVED +for((i = 1; i < 60; i++)) +do + if [ -e ./serviceLog ];then + rm -f ./serviceLog + fi + service tomcat6 status | grep "is running" >> ./serviceLog + + if [ -s ./serviceLog ]; then + + echo "tomcat6 has started!" + rm -f ./serviceLog + sleep 10 + break + fi + + sleep 1 + + echo "If this file is present after install then starting tomcat6 timed-out" >> serviceLog + +done + +#moves the war file to webapps folder to unpack it +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2.war +cp /%{name}/HisPrivacyCAWebServices2.war $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/ +# This for loop makes the rpm wait until the .war file has unpacked before attempting to access the files that will be created +for((i = 1; i < 60; i++)) +do + + rm -f ./warLog + + if [ -e /var/lib/oat-appraiser -a -e /var/lib/oat-appraiser/ClientFiles/OATprovisioner.properties ]; then +# if [ -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2 -a -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/OATprovisioner.properties ]; then + + + echo "the Privacy CA was unpacked!" + rm -f ./warLog + sleep 5 + break + fi + + sleep 1 + + echo If this file is present after install then unpacking the Privacy CA war file timed-out >> warLog + +done +#this is a script to re-run certificate creation using new p12 files after installation +rm -rf /%{name}/clientInstallRefresh.sh +rm -rf /%{name}/linuxClientInstallRefresh.sh +cur_dir=$(pwd) +unzip /%{name}/clientInstallRefresh.zip -d /%{name}/ +unzip /%{name}/linuxClientInstallRefresh.zip -d /%{name}/ +cd /%{name}/ +sed -i "s/\/usr\/lib\/apache-tomcat-6.0.29/$TOMCAT_DIR_COFNIG_TYPE\/$TOMCAT_NAME/g" clientInstallRefresh.sh +sed -i "s/\/usr\/lib\/apache-tomcat-6.0.29/$TOMCAT_DIR_COFNIG_TYPE\/$TOMCAT_NAME/g" linuxClientInstallRefresh.sh + +rm -rf clientInstallRefresh.zip +rm -rf linuxClientInstallRefresh.zip + +mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/lib /var/lib/oat-appraiser/ClientFiles/ +mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/TPMModule.properties /var/lib/oat-appraiser/ClientFiles/ +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/CaCerts +zip -9 linuxClientInstallRefresh.zip linuxClientInstallRefresh.sh +zip -9 clientInstallRefresh.zip clientInstallRefresh.sh +#test Q +cp -rf linuxClientInstallRefresh.zip /tmp +cd $cur_dir + +rm -rf /%{name}/installers +#unzip /%{name}/ClientInstall.zip -d /%{name}/ +unzip /%{name}/ClientInstallForLinux.zip -d /%{name}/ + +sleep 5 + +# zky: similar from here +#rm -f /%{name}/ClientInstallOld.zip +#mv /%{name}/ClientInstall.zip /%{name}/ClientInstallOld.zip + +#rm -rf /%{name}/ClientInstall +#mkdir /%{name}/ClientInstall + +#This code grabs all of the needed files from the privacy CA folder and packages them into a Client Installation folder +#cp -r -f /%{name}/installers /%{name}/ClientInstall + +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/endorsement.p12 /%{name}/ClientInstall/installers/hisInstall/ +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/lib /%{name}/ClientInstall/installers/hisInstall/ +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/TPMModule.properties /%{name}/ClientInstall/installers/hisInstall/ +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/exe /%{name}/ClientInstall/installers/hisInstall/ +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/PrivacyCA.cer /%{name}/ClientInstall/installers/hisInstall/ +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/TrustStore.jks /%{name}/ClientInstall/installers/hisInstall/ +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/OATprovisioner.properties /%{name}/ClientInstall/installers/hisInstall/ +##DWC added two following lines for Chris +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/install.bat /%{name}/ClientInstall/installers/hisInstall/ +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/OAT.properties /%{name}/ClientInstall/installers/hisInstall/ +# +##privacy.jar for windows +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/lib/PrivacyCA.jar /%{name}/ClientInstall/installers/hisInstall/lib + + +#cd /%{name}/; zip -9 -r ClientInstall.zip ClientInstall + + +#places the client installation folder up for tomcat6 to display +#cp -f /%{name}/ClientInstall.zip /srv/www/htdocs/ + +#zky: for linux, do similar things +rm -f /%{name}/ClientInstallForLinuxOld.zip +mv /%{name}/ClientInstallForLinux.zip /%{name}/ClientInstallForLinuxOld.zip + +rm -rf /%{name}/ClientInstallForLinux + +cp -r -f /%{name}/linuxOatInstall /%{name}/ClientInstallForLinux + +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/endorsement.p12 /%{name}/ClientInstallForLinux/ +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/PrivacyCA.cer /%{name}/ClientInstallForLinux/ +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/TrustStore.jks /%{name}/ClientInstallForLinux/ +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/OATprovisioner.properties /%{name}/ClientInstallForLinux/ + +cp -rf /OAT-Appraiser-Base/OAT_Standalone.jar /OAT-Appraiser-Base/ClientInstallForLinux/ +cp -rf /OAT-Appraiser-Base/lib /OAT-Appraiser-Base/ClientInstallForLinux/ + +cp -r -f /var/lib/oat-appraiser/ClientFiles/PrivacyCA.cer /%{name}/ClientInstallForLinux/ +cp -r -f /var/lib/oat-appraiser/ClientFiles/TrustStore.jks /%{name}/ClientInstallForLinux/ +cp -r -f /var/lib/oat-appraiser/ClientFiles/OATprovisioner.properties /%{name}/ClientInstallForLinux/ + +#remove credential information here +sed -i '/TpmEndorsmentP12/d' /%{name}/ClientInstallForLinux/OATprovisioner.properties +sed -i '/EndorsementP12Pass/d' /%{name}/ClientInstallForLinux/OATprovisioner.properties +#end remove + +cp -r -f /var/lib/oat-appraiser/ClientFiles/OAT.properties /%{name}/ClientInstallForLinux/ +sed -i '/ClientPath/s/C:.*/\/OAT/' /%{name}/ClientInstallForLinux/OATprovisioner.properties +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/OAT.properties /%{name}/ClientInstallForLinux/ +sed -i 's/NIARL_TPM_Module\.exe/NIARL_TPM_Module/g' /%{name}/ClientInstallForLinux/OAT.properties +sed -i 's/HIS07\.jpg/OAT07\.jpg/g' /%{name}/ClientInstallForLinux/OAT.properties +cd /%{name}/; zip -9 -r ClientInstallForLinux.zip ClientInstallForLinux + +#Test +cp -f /%{name}/ClientInstallForLinux.zip /tmp/ +# + + +#places the client installation folder up for tomcat6 to display +cp -f /%{name}/ClientInstallForLinux.zip /srv/www/htdocs + + +#creates the web page that allows access for the download of the client files folder +echo "" >> /srv/www/htdocs/ClientInstaller.html +echo "" >> /srv/www/htdocs/ClientInstaller.html +#echo "

Client Installation Files

" >> /srv/www/htdocs/ClientInstaller.html +echo "

Client Installation Files For Linux

" >> /srv/www/htdocs/ClientInstaller.html +echo "" >> /srv/www/htdocs/ClientInstaller.html +echo "" >> /srv/www/htdocs/ClientInstaller.html + +chmod 755 /srv/www/htdocs/Client* + + +#closes some known security holes in tomcat6 +sed -i "s/AllowOverride None/AllowOverride All/" /etc/apache2/httpd.conf +sed -i "s/ServerTokens OS/ServerTokens Prod/" /etc/apache2/httpd.conf +sed -i "s/Options Indexes/Options/" /etc/apache2/httpd.conf +sed -i "s/expose_php = On/expose_php = Off/" /etc/php5/cli/php.ini + +#rm -f /etc/apache2.d/welcome.conf +#echo "" >> /etc/apache2.d/welcome.conf + +#/sbin/restorecon -R '/srv/www/htdocs/OAT' +service apache2 restart + +####################################################################### +printf "done\n" + +%postun OATapp +#HAPCrpmremoval.sh script********************************************** +TOMCAT_INSTALL_DIR2=/usr/lib +TOMCAT_NAME2=apache-tomcat-6.0.29 +service tomcat6 stop +if [ $TOMCAT_DIR -a -d $TOMCAT_DIR ];then + if [[ ${TOMCAT_DIR:$((${#TOMCAT_DIR}-1)):1} == / ]];then + TOMCAT_DIR_TMP=${TOMCAT_DIR:0:$((${#TOMCAT_DIR}-1))} + else + TOMCAT_DIR_TMP=$TOMCAT_DIR + fi + + TOMCAT_INSTALL_DIR2=${TOMCAT_DIR_TMP%/*} + TOMCAT_NAME2=${TOMCAT_DIR_TMP##*/} +fi +chkconfig tomcat6 --del + +sed -i "/<\/Service>/d" $TOMCAT_INSTALL_DIR2/$TOMCAT_NAME2/conf/server.xml +sed -i "/<\/Server>/i\\ <\/Service>" $TOMCAT_INSTALL_DIR2/$TOMCAT_NAME2/conf/server.xml +rm -rf /%{name}/ +#stop tomcat service and remove apache-tomcat +kill -9 `ps -ef | grep tomcat | grep -v grep | awk '{print $2}'` +if [ $TOMCAT_NAME2 == apache-tomcat-6.0.29 ];then +rm -f -r $TOMCAT_INSTALL_DIR2/apache-tomcat-6.0.29.tar.gz +rm -rf $TOMCAT_INSTALL_DIR2/apache-tomcat-6.0.29 +fi + +if [ -d /etc/oat-appraiser ] +then +rm -rf /etc/oat-appraiser +fi + +if [ -d /var/lib/oat-appraiser ] +then +rm -rf /var/lib/oat-appraiser +fi + +#OAT_Server +rm -f -r /tmp/OAT_Server_Install +rm -f -r /srv/www/htdocs/OAT + +#OAT_PrivacyCA +#rm -f -r /tmp/OAT_PrivacyCA_Install +#rm -f -r /srv/www/htdocs/ClientInstall.zip +rm -f -r /srv/www/htdocs/ClientInstallForLinux.zip +rm -f -r /srv/www/htdocs/ClientInstaller.html + +#removes both the OAT mysql database and the hisAppraiser mysql user + +service mysql stop +#sed -i 's/--datadir="$datadir" --socket="$socketfile"/--datadir="$datadir" --skip-grant-tables --socket="$socketfile"/g' /etc/rc.d/init.d/mysql + +service mysql start +mysql -u root --execute="FLUSH PRIVILEGES; DROP DATABASE IF EXISTS oat_db; DELETE FROM mysql.user WHERE User='oatAppraiser' and Host='localhost';" + + +service mysql stop + +#sed -i 's/--datadir="$datadir" --skip-grant-tables --socket="$socketfile"/--datadir="$datadir" --socket="$socketfile"/g' /etc/rc.d/init.d/mysql + +service mysql start + +echo -ne "OAT database removed\n" +echo -ne "package remove clean\n" +#********************************************************************** + +%clean +rm -rf $RPM_BUILD_ROOT + + +%files OATapp +/%{name}/apache-tomcat-6.0.29.tar.gz +/%{name}/clientInstallRefresh.zip +/%{name}/linuxClientInstallRefresh.zip +#/%{name}/ClientInstall.zip +/%{name}/ClientInstallForLinux.zip +/%{name}/tomcat6 +/%{name}/HisPrivacyCAWebServices2.war +/%{name}/OAT_Server_Install.zip +/%{name}/oatSetup.zip +/%{name}/OAT.zip +/%{name}/MySQLdrop.zip +/%{name}/service.zip +/%{name}/setupProperties.zip +/%{name}/OAT.sh +/%{name}/OAT_Standalone.jar +/%{name}/log4j.properties +/%{name}/lib/ + diff --git a/OpenAttestation/Installer/OAT-Appraiser-Base.spec b/OpenAttestation/Installer/OAT-Appraiser-Base.spec new file mode 100644 index 0000000..322f8c0 --- /dev/null +++ b/OpenAttestation/Installer/OAT-Appraiser-Base.spec @@ -0,0 +1,509 @@ +Name: OAT-Appraiser-Base +Summary: [OAT Crossbow] Host Integrity at Startup Installation of Appraiser Server +Version: 1.0.0 +Release: 2%{?dist} +License: DoD +Group: Department of Defense +Vendor: Department of Defense +Source0: OAT-Appraiser-Configure.tar.gz +BuildRoot: /var/tmp/OAT-Appraiser-Configure-%{PACKAGE_VERSION} + +%description +Host Integrity at Startup (OAT) is a project that explores how software and processes on standard desktop computers can be measured to detect and report important and specific changes which highlight potential compromise of the host platform. OAT provides the first examples of effective Measurement and Attestation on the path toward trusted platforms. + +%package OATapp +Summary: The OAT Appraiser Base Install +Group: Department of Defense +#we use mysql for OAT Appraiser, and php is needed for the web portal +#Requires: mysql, mysql-server, php, php-mysql +Requires: mariadb, mariadb-server, php, php-mysql +%description OATapp +The Host Integrity at Startup Installation +of the OAT Appraiser Server Base Install +%prep +%setup -n OAT-Appraiser-Configure +rm -rf $RPM_BUILD_ROOT +mkdir $RPM_BUILD_ROOT/ +cp -R $RPM_BUILD_DIR/OAT-Appraiser-Configure $RPM_BUILD_ROOT + +%post OATapp +echo -n "Making OAT Appraiser\n" + +#######Install script########################################################### + +service mysqld start +#TOMCAT_INSTALL_DIR=/usr/lib +#TOMCAT_INSTALL_DIR=$TOMCAT_DIR +#TOMCAT_DIR_COFNIG_TYPE=${TOMCAT_INSTALL_DIR//\//\\/} +##TOMCAT_NAME=apache-tomcat-6.0.35 +#TOMCAT_NAME=apache-tomcat-6.0.29 +#echo $TOMCAT_INSTALL_DIR > ~/rpm.log +#echo $TOMCAT_DIR_COFNIG_TYPE >> ~/rpm.log +TOMCAT_INSTALL_DIR=/usr/lib +TOMCAT_NAME=apache-tomcat-6.0.29 + +if [ -d /var/lib/oat-appraiser ] +then + rm -rf /var/lib/oat-appraiser + mkdir /var/lib/oat-appraiser + mkdir /var/lib/oat-appraiser/CaCerts + mkdir /var/lib/oat-appraiser/ClientFiles +else + mkdir /var/lib/oat-appraiser + mkdir /var/lib/oat-appraiser/CaCerts + mkdir /var/lib/oat-appraiser/ClientFiles +fi + +if [ -d /etc/oat-appraiser ] +then + rm -rf /etc/oat-appraiser + mkdir /etc/oat-appraiser +else + mkdir /etc/oat-appraiser +fi + +if [ $TOMCAT_DIR -a -d $TOMCAT_DIR ];then + if [[ ${TOMCAT_DIR:$((${#TOMCAT_DIR}-1)):1} == / ]];then + TOMCAT_DIR_TMP=${TOMCAT_DIR:0:$((${#TOMCAT_DIR}-1))} + else + TOMCAT_DIR_TMP=$TOMCAT_DIR + fi + + TOMCAT_INSTALL_DIR=${TOMCAT_DIR_TMP%/*} + TOMCAT_NAME=${TOMCAT_DIR_TMP##*/} +fi +TOMCAT_DIR_COFNIG_TYPE=${TOMCAT_INSTALL_DIR//\//\\/} +echo $TOMCAT_INSTALL_DIR > ~/rpm.log +echo $TOMCAT_DIR_COFNIG_TYPE >> ~/rpm.log + +###Random generation /dev/urandom is good but just in case... +# Creating randoms for the p12 files and setting up truststore and keystore +ip12="internal.p12" +ipassfile="internal.pass" +idomfile="internal.domain" +iloc="/OAT-Appraiser-Configure/" +p12file="$loc$ip12" +RAND1=$(dd if=/dev/urandom bs=1 count=1024) +RAND2=$(dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}') +RAND3=$(dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}') +randbits="$(echo "$( echo "`clock`" | md5sum | md5sum )$( echo "`dd if=/dev/urandom bs=1 count=1024`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum )$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum)$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum )" | md5sum | md5sum )" +randpass="${randbits:0:30}" +randbits2="$(echo "$( echo "`clock`" | md5sum | md5sum )$( echo "`dd if=/dev/urandom bs=1 count=1024`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum )$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum)$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum )" | md5sum | md5sum )" +randpass2="${randbits2:0:30}" +randbits3="$(echo "$( echo "`clock`" | md5sum | md5sum )$( echo "`dd if=/dev/urandom bs=1 count=1024`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum )$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum)$(echo "`dd if=/dev/urandom bs=1 count=1024 | awk '{print $1}'`" | md5sum | md5sum)$(echo "`clock`" | md5sum | md5sum )" | md5sum | md5sum )" +randpass3="${randbits3:0:30}" +p12pass="$randpass" +mysqlPass="$randpass2" +keystore="keystore.jks" +truststore="TrustStore.jks" +if [ "`ls $iloc | grep $ip12`" ] && [ "`ls $iloc | grep $ipassfile`" ] ; then + p12pass="`cat $loc$ipassfile`" +fi +if [ "`ls $iloc | grep $idomfile`" ] ; then + domain="`cat $loc$idomfile`" +fi + + +service mysqld stop +service tomcat6 stop + +sleep 10 + +#Configuring mysqld so we can set up database and hisAppraiser profile + +#sed -i 's/--datadir="$datadir" --socket="$socketfile"/--datadir="$datadir" --skip-grant-tables --socket="$socketfile"/g' /etc/rc.d/init.d/mysqld + +service mysqld start + +#Sets up database and user +ISSKIPGRANTEXIT=`grep skip-grant-tables /etc/my.cnf` +if [ ! "$ISSKIPGRANTEXIT" ]; then + sed -i 's/\[mysqld\]/\[mysqld\]\nskip-grant-tables/g' /etc/my.cnf +fi + + +mysql -u root --execute="CREATE DATABASE oat_db; FLUSH PRIVILEGES; GRANT ALL ON oat_db.* TO 'oatAppraiser'@'localhost' IDENTIFIED BY '$randpass3';" + +service mysqld stop + +#sed -i 's/--datadir="$datadir" --socket="$socketfile"/--datadir="$datadir" --skip-grant-tables --socket="$socketfile"/g' /etc/rc.d/init.d/mysqld + + +#setting up tomcat at $TOMCAT_INSTALL_DIR/ +if [ $TOMCAT_NAME == apache-tomcat-6.0.29 ];then +rm -f $TOMCAT_INSTALL_DIR/apache-tomcat-6.0.29.tar.gz +mv /OAT-Appraiser-Configure/apache-tomcat-6.0.29.tar.gz $TOMCAT_INSTALL_DIR/. +fi + +unzip /OAT-Appraiser-Configure/service.zip -d /OAT-Appraiser-Configure/ +rm -f /OAT-Appraiser-Configure/service.zip + +#mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME $TOMCAT_INSTALL_DIR/apache-tomcat-old +if [ $TOMCAT_NAME == apache-tomcat-6.0.29 ];then +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME +tar -zxf $TOMCAT_INSTALL_DIR/apache-tomcat-6.0.29.tar.gz -C $TOMCAT_INSTALL_DIR/ +fi + +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/service +mv -f /OAT-Appraiser-Configure/service $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/service +#rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/Certificate +#mkdir $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/Certificate +rm -rf /var/lib/oat-appraiser/Certificate +mkdir /var/lib/oat-appraiser/Certificate +unzip /OAT-Appraiser-Configure/setupProperties.zip -d /OAT-Appraiser-Configure/ +mv /OAT-Appraiser-Configure/setup.properties /etc/oat-appraiser/ + +rm -R -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/* + +#chkconfig --del NetworkManager +chkconfig network on +chkconfig httpd --add +chkconfig httpd on +service httpd start +chkconfig mysqld on +service mysqld start + +#running OAT database full setup +#rm -rf /OAT-Appraiser-Configure/MySQLdrop.txt +#unzip /OAT-Appraiser-Configure/MySQLdrop.zip -d /OAT-Appraiser-Configure/ +#mysql -u root < /OAT-Appraiser-Configure/MySQLdrop.txt +rm -rf /OAT-Appraiser-Configure/OAT_Server_Install +unzip /OAT-Appraiser-Configure/OAT_Server_Install.zip -d /OAT-Appraiser-Configure/ +rm -rf /tmp/OAT_Server_Install +mv -f /OAT-Appraiser-Configure/OAT_Server_Install /tmp/OAT_Server_Install +mysql -u root --execute="DROP DATABASE IF EXISTS oat_db;" +mysql -u root < /tmp/OAT_Server_Install/oat_db.MySQL +mysql -u root < /tmp/OAT_Server_Install/init.sql +#setting up access control in tomcat context.xml +#sed -i "/<\/Context>/i\\ " $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/conf/context.xml + +sed -i "/<\/Context>/i\\ " $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/conf/context.xml + +#setting up port 8443 in tomcat server.xml +sed -i "s/ <\/Service>/<\/Service>/g" $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/conf/server.xml + + + +cp -R /tmp/OAT_Server_Install/HisWebServices $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/ +# +#if [ -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationAdminConsole.war ];then +# rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationAdminConsole.war +#fi +# +#if [ -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationManifestWebServices.war ];then +# rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationManifestWebServices.war +#fi +# +#if [ -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationWebServices.war ];then +# rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/OpenAttestationWebServices.war +#fi + +cp /tmp/OAT_Server_Install/WLMService.war $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/ +cp /tmp/OAT_Server_Install/AttestationService.war $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/ +unzip $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/WLMService.war -d $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/WLMService +unzip $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/AttestationService.war -d $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/AttestationService +#delete the OpenAttestation war package +rm -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/WLMService.war +rm -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/AttestationService.war +mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/AttestationService/WEB-INF/classes/OpenAttestationWebServices.properties /etc/oat-appraiser/OpenAttestationWebServices.properties +sed -i "s//$(hostname)/g" /etc/oat-appraiser/OpenAttestationWebServices.properties +#configuring hibernateHis for OAT appraiser setup +cp /tmp/OAT_Server_Install/hibernateOat.cfg.xml /tmp/ +sed -i 's/root<\/property>/oatAppraiser<\/property>/' /tmp/hibernateOat.cfg.xml +sed -i "s/oat-password<\/property>/$randpass3<\/property>/" /tmp/hibernateOat.cfg.xml +cp /tmp/hibernateOat.cfg.xml $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisWebServices/WEB-INF/classes/ +cp /tmp/OAT_Server_Install/OAT.properties /etc/oat-appraiser/ +mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisWebServices/WEB-INF/classes/OpenAttestation.properties /etc/oat-appraiser/ +sed -i "s//$(hostname)/g" /etc/oat-appraiser/OpenAttestation.properties +sed -i "s/^truststore_path.*$/truststore_path=\/var\/lib\/oat-appraiser\/Certificate\/TrustStore.jks/g" /etc/oat-appraiser/OpenAttestation.properties + +sed -i "s/^TrustStore.*$/TrustStore=\/var\/lib\/oat-appraiser\/Certificate\/TrustStore.jks/g" /etc/oat-appraiser/OpenAttestation.properties + +mkdir -p /var/log/oat_ir +#placing OAT web portal in correct folder to be seen by tomcat6 +rm -rf /OAT-Appraiser-Configure/OAT +unzip /OAT-Appraiser-Configure/OAT.zip -d /OAT-Appraiser-Configure/ +rm -rf /var/www/html/OAT +mv -f /OAT-Appraiser-Configure/OAT /var/www/html/OAT + +#setting all files in the OAT portal to be compiant to selinux +/sbin/restorecon -R '/var/www/html/OAT' + +#setting the user and password in the OAT appraiser that will be used to access the mysql database. +sed -i 's/user = "root"/user = "oatAppraiser"/g' /var/www/html/OAT/includes/dbconnect.php +sed -i "s/pass = \"newpwd\"/pass = \"$randpass3\"/g" /var/www/html/OAT/includes/dbconnect.php + +#setting up OAT database to talk with the web portal correctly +rm -f /OAT-Appraiser-Configure/oatSetup.txt +unzip /OAT-Appraiser-Configure/oatSetup.zip -d /OAT-Appraiser-Configure/ +mysql -u root --database=oat_db < /OAT-Appraiser-Configure/oatSetup.txt + + +# This is setting the OAT mysql user to the password given to the Appraiser +#mysql -u root --database=mysql --execute="UPDATE user SET password=PASSWORD('newpwd') WHERE user='hisAppraiser';" +service mysqld stop + +#sets configuration of mysql back to normal +#sed -i 's/--datadir="$datadir" --skip-grant-tables --socket="$socketfile"/--datadir="$datadir" --socket="$socketfile"/g' /etc/rc.d/init.d/mysqld +ISSKIPGRANTEXIT=`grep nskip-grant-tables /etc/my.cnf` +if [ "$ISSKIPGRANTEXIT" ]; then + sed -i 's/\[mysqld\]\nskip-grant-tables/\[mysqld\]g' /etc/my.cnf +fi + + +service mysqld start + + +#this code sets up the certificate attached to this computers hostname +cd /var/lib/oat-appraiser/Certificate/ +echo "127.0.0.1 `hostname`" >> /etc/hosts +if [ "`echo $p12pass | grep $randpass`" ] ; then + openssl req -x509 -nodes -days 730 -newkey rsa:2048 -keyout hostname.pem -out hostname.cer -subj "/C=US/O=U.S. Government/OU=DoD/CN=`hostname`" + openssl pkcs12 -export -in hostname.cer -inkey hostname.pem -out $p12file -passout pass:$p12pass +fi + +keytool -importkeystore -srckeystore $p12file -destkeystore $keystore -srcstoretype pkcs12 -srcstorepass $p12pass -deststoretype jks -deststorepass $p12pass -noprompt + +myalias=`keytool -list -v -keystore $keystore -storepass $p12pass | grep -B2 'PrivateKeyEntry' | grep 'Alias name:'` + +keytool -changealias -alias ${myalias#*:} -destalias tomcat -v -keystore $keystore -storepass $p12pass + +rm -f $truststore +keytool -import -keystore $truststore -storepass password -file hostname.cer -noprompt + +#sets up the tomcat6 service +chmod -R 755 $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/service/* +cp $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/service/tomcat6 /etc/rc.d/init.d/ +sed -i "s/killproc \$PROC/daemon \$CATALINA_BIN stop/g" /etc/rc.d/init.d/tomcat6 +chkconfig tomcat6 --add +chkconfig tomcat6 on + +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2.war + +# TOAT IS THE BEGINNING OF THE PCA PORTION +#rm -rf /OAT-Appraiser-Configure/OAT_PrivacyCA_Install +#unzip /OAT-Appraiser-Configure/OAT_PrivacyCA_Install.zip -d /OAT-Appraiser-Configure/ +#rm -rf /tmp/OAT_PrivacyCA_Install +#mv /OAT-Appraiser-Configure/OAT_PrivacyCA_Install /tmp/OAT_PrivacyCA_Install + +chmod 777 /tmp +sleep 10 +#catalina.sh +sed -i "/^#CATALINA_BIN/d" /etc/init.d/tomcat6 +sed -i "s/^CATALINA_BIN/#CATALINA_BIN/g" /etc/init.d/tomcat6 +sed -i "/^#CATALINA_BIN/i\\CATALINA_BIN=\'$TOMCAT_INSTALL_DIR/$TOMCAT_NAME/bin/catalina.sh 1> /dev/null\';" /etc/init.d/tomcat6 + +service tomcat6 start + +# TOAT FOR LOOP IS NEEDED TO MAKE SURE THAT TOMCAT6 IS STARTED WELL BEFORE THE .WAR FILE IS MOVED +for((i = 1; i < 60; i++)) +do + + rm -f ./serviceLog + + service tomcat6 status | grep "is running" >> ./serviceLog + + if [ -s ./serviceLog ]; then + + echo tomcat6 has started! + rm -f ./serviceLog + sleep 10 + break + fi + + sleep 1 + + echo If this file is present after install then starting tomcat6 timed-out >> serviceLog + +done + +#moves the war file to webapps folder to unpack it +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2.war +cp /OAT-Appraiser-Configure/HisPrivacyCAWebServices2.war $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/ + +# This for loop makes the rpm wait until the .war file has unpacked before attempting to access the files that will be created +for((i = 1; i < 60; i++)) +do + + rm -f ./warLog + if [ -e /var/lib/oat-appraiser -a -e /var/lib/oat-appraiser/ClientFiles/OATprovisioner.properties ]; then +# if [ -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2 -a -e $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/OATprovisioner.properties ]; then + + + echo the Privacy CA was unpacked! + rm -f ./warLog + sleep 5 + break + fi + + sleep 1 + + echo If this file is present after install then unpacking the Privacy CA war file timed-out >> warLog + +done + +#this is a script to re-run certificate creation using new p12 files after installation +rm -rf /OAT-Appraiser-Configure/clientInstallRefresh.sh +rm -rf /OAT-Appraiser-Configure/linuxClientInstallRefresh.sh +cur_dir=$(pwd) +unzip /OAT-Appraiser-Configure/clientInstallRefresh.zip -d /OAT-Appraiser-Configure/ +unzip /OAT-Appraiser-Configure/linuxClientInstallRefresh.zip -d /OAT-Appraiser-Configure/ +cd /OAT-Appraiser-Configure/ +sed -i "s/\/usr\/lib\/apache-tomcat-6.0.29/$TOMCAT_DIR_COFNIG_TYPE\/$TOMCAT_NAME/g" clientInstallRefresh.sh +sed -i "s/\/usr\/lib\/apache-tomcat-6.0.29/$TOMCAT_DIR_COFNIG_TYPE\/$TOMCAT_NAME/g" linuxClientInstallRefresh.sh + +mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/lib /var/lib/oat-appraiser/ClientFiles/ +mv $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/TPMModule.properties /var/lib/oat-appraiser/ClientFiles/ +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/ +rm -rf $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/CaCerts +rm -rf clientInstallRefresh.zip +rm -rf linuxClientInstallRefresh.zip + +zip -9 linuxClientInstallRefresh.zip linuxClientInstallRefresh.sh +zip -9 clientInstallRefresh.zip clientInstallRefresh.sh +cp -rf linuxClientInstallRefresh.zip /tmp +cd $cur_dir + +rm -rf /OAT-Appraiser-Configure/installers +#unzip /OAT-Appraiser-Configure/ClientInstall.zip -d /OAT-Appraiser-Configure/ +unzip /OAT-Appraiser-Configure/ClientInstallForLinux.zip -d /OAT-Appraiser-Configure/ + +sleep 5 + +mv /OAT-Appraiser-Configure/ClientInstallForLinux.zip /OAT-Appraiser-Configure/ClientInstallForLinuxOld.zip + +rm -rf /OAT-Appraiser-Configure/ClientInstallForLinux + +cp -r -f /OAT-Appraiser-Configure/linuxOatInstall /OAT-Appraiser-Configure/ClientInstallForLinux + + +cp -rf /OAT-Appraiser-Configure/OAT_Standalone.jar /OAT-Appraiser-Configure/ClientInstallForLinux/ +cp -rf /OAT-Appraiser-Configure/lib /OAT-Appraiser-Configure/ClientInstallForLinux/ +cp -r -f /var/lib/oat-appraiser/ClientFiles/PrivacyCA.cer /OAT-Appraiser-Configure/ClientInstallForLinux/ +cp -r -f /var/lib/oat-appraiser/ClientFiles/TrustStore.jks /OAT-Appraiser-Configure/ClientInstallForLinux/ +cp -r -f /var/lib/oat-appraiser/ClientFiles/OATprovisioner.properties /OAT-Appraiser-Configure/ClientInstallForLinux/ +cp -r -f /var/lib/oat-appraiser/ClientFiles/OAT.properties /OAT-Appraiser-Configure/ClientInstallForLinux/ +sed -i '/ClientPath/s/C:.*/\/OAT/' /OAT-Appraiser-Configure/ClientInstallForLinux/OATprovisioner.properties +#cp -r -f $TOMCAT_INSTALL_DIR/$TOMCAT_NAME/webapps/HisPrivacyCAWebServices2/ClientFiles/OAT.properties /OAT-Appraiser-Configure/ClientInstallForLinux/ +sed -i 's/NIARL_TPM_Module\.exe/NIARL_TPM_Module/g' /OAT-Appraiser-Configure/ClientInstallForLinux/OAT.properties +sed -i 's/HIS07\.jpg/OAT07\.jpg/g' /OAT-Appraiser-Configure/ClientInstallForLinux/OAT.properties +cd /OAT-Appraiser-Configure/; zip -9 -r ClientInstallForLinux.zip ClientInstallForLinux + +#places the client installation folder up for tomcat6 to display +cp -f /OAT-Appraiser-Configure/ClientInstallForLinux.zip /var/www/html/ + + +#creates the web page that allows access for the download of the client files folder +echo "" >> /var/www/html/ClientInstaller.html +echo "" >> /var/www/html/ClientInstaller.html +#echo "

Client Installation Files

" >> /var/www/html/ClientInstaller.html +echo "

Client Installation Files For Linux

" >> /var/www/html/ClientInstaller.html +echo "" >> /var/www/html/ClientInstaller.html +echo "" >> /var/www/html/ClientInstaller.html + +chmod 755 /var/www/html/Client* + + +#closes some known security holes in tomcat6 +sed -i "s/AllowOverride None/AllowOverride All/" /etc/httpd/conf/httpd.conf +echo "TraceEnable Off" >> /etc/httpd/conf/httpd.conf +sed -i "s/ServerTokens OS/ServerTokens Prod/" /etc/httpd/conf/httpd.conf +sed -i "s/Options Indexes/Options/" /etc/httpd/conf/httpd.conf +sed -i "s/expose_php = On/expose_php = Off/" /etc/php.ini + +rm -f /etc/httpd/conf.d/welcome.conf +echo "" >> /etc/httpd/conf.d/welcome.conf + +/sbin/restorecon -R '/var/www/html/OAT' + +service tomcat6 restart +####################################################################### +printf "done\n" + +%postun OATapp +#HAPCrpmremoval.sh script********************************************** +TOMCAT_INSTALL_DIR2=/usr/lib +TOMCAT_NAME2=apache-tomcat-6.0.29 + +if [ $TOMCAT_DIR -a -d $TOMCAT_DIR ];then + if [[ ${TOMCAT_DIR:$((${#TOMCAT_DIR}-1)):1} == / ]];then + TOMCAT_DIR_TMP=${TOMCAT_DIR:0:$((${#TOMCAT_DIR}-1))} + else + TOMCAT_DIR_TMP=$TOMCAT_DIR + fi + + TOMCAT_INSTALL_DIR2=${TOMCAT_DIR_TMP%/*} + TOMCAT_NAME2=${TOMCAT_DIR_TMP##*/} +fi + +sed -i "/<\/Service>/d" $TOMCAT_INSTALL_DIR2/$TOMCAT_NAME2/conf/server.xml +sed -i "/<\/Server>/i\\ <\/Service>" $TOMCAT_INSTALL_DIR2/$TOMCAT_NAME2/conf/server.xml +rm -rf /OAT-Appraiser-Configure/ +#stop tomcat service and remove apache-tomcat +kill -9 `ps -ef | grep tomcat | grep -v grep | awk '{print $2}'` +if [ -d $TOMCAT_INSTALL_DIR2/apache-tomcat-6.0.29 ];then +rm -f -r $TOMCAT_INSTALL_DIR2/apache-tomcat-6.0.29.tar.gz +rm -rf $TOMCAT_INSTALL_DIR2/apache-tomcat-6.0.29 +fi + +if [ -d /etc/oat-appraiser ] +then +rm -rf /etc/oat-appraiser +fi + +if [ -d /var/lib/oat-appraiser ] +then +rm -rf /var/lib/oat-appraiser +fi + +#OAT_Server +rm -f -r /tmp/OAT_Server_Install +rm -f -r /var/www/html/OAT + +#OAT_PrivacyCA +#rm -f -r /tmp/OAT_PrivacyCA_Install +#rm -f -r /var/www/html/ClientInstall.zip +rm -f -r /var/www/html/ClientInstallForLinux.zip +rm -f -r /var/www/html/ClientInstaller.html + +#removes both the OAT mysql database and the hisAppraiser mysql user + +service mysqld stop +#sed -i 's/--datadir="$datadir" --socket="$socketfile"/--datadir="$datadir" --skip-grant-tables --socket="$socketfile"/g' /etc/rc.d/init.d/mysqld + +service mysqld start +mysql -u root --execute="FLUSH PRIVILEGES; DROP DATABASE IF EXISTS oat_db; DELETE FROM mysql.user WHERE User='oatAppraiser' and Host='localhost';" + +printf "OAT database removed\n" + +service mysqld stop + +#sed -i 's/--datadir="$datadir" --skip-grant-tables --socket="$socketfile"/--datadir="$datadir" --socket="$socketfile"/g' /etc/rc.d/init.d/mysqld + +service mysqld start + + +#********************************************************************** + +%clean +rm -rf $RPM_BUILD_ROOT + + +%files OATapp +/OAT-Appraiser-Configure/apache-tomcat-6.0.29.tar.gz +/OAT-Appraiser-Configure/clientInstallRefresh.zip +/OAT-Appraiser-Configure/linuxClientInstallRefresh.zip +/OAT-Appraiser-Configure/ClientInstallForLinux.zip +/OAT-Appraiser-Configure/HisPrivacyCAWebServices2.war +/OAT-Appraiser-Configure/OAT_Server_Install.zip +/OAT-Appraiser-Configure/oatSetup.zip +/OAT-Appraiser-Configure/OAT.zip +/OAT-Appraiser-Configure/MySQLdrop.zip +/OAT-Appraiser-Configure/service.zip +/OAT-Appraiser-Configure/setupProperties.zip +/OAT-Appraiser-Configure/OAT.sh +/OAT-Appraiser-Configure/OAT_Standalone.jar +/OAT-Appraiser-Configure/lib +/OAT-Appraiser-Configure/log4j.properties diff --git a/OpenAttestation/Installer/OAT-Appraiser-Configure/MySQLdrop.txt b/OpenAttestation/Installer/OAT-Appraiser-Configure/MySQLdrop.txt new file mode 100644 index 0000000..a176de7 --- /dev/null +++ b/OpenAttestation/Installer/OAT-Appraiser-Configure/MySQLdrop.txt @@ -0,0 +1,2 @@ +DROP USER ''; +quit \ No newline at end of file diff --git a/OpenAttestation/Installer/OAT-Appraiser-Configure/OAT_Server_Install/OAT.properties b/OpenAttestation/Installer/OAT-Appraiser-Configure/OAT_Server_Install/OAT.properties new file mode 100644 index 0000000..cff47c9 --- /dev/null +++ b/OpenAttestation/Installer/OAT-Appraiser-Configure/OAT_Server_Install/OAT.properties @@ -0,0 +1,76 @@ +#The ALERT_MASK_CSV variable below is a comma separated list of numbers from 0 to 23 including the word signature +#Example: +#ALERT_MASK_CSV=0,4,5,signature +#For all errors to create alerts leave ALERT_MASK_CSV blank i.e.: +#ALERT_MASK_CSV= +#WARNING: Please review the logs of the web server to find the results of the ALERT_MASK_CSV setting. +ATTEST_TYPE=PCR +ALERT_MASK_CSV=0 +COMP_MASK=stmHash,xen.gz + +#PCR select for integrity reports +PCR_SELECT=FFFFFF + +######################################################################## +####### IR on file Properties +######################################################################## +# +# IR_DIR - Setting this property the integrity report will be written +# into the given directory. It will be saved on DB otherwise. +# If the property is set, OAT expects that given directory +# exists and it's accessible; on Fedora it means that the +# user 'tomcat' should be the directory owner. +# +# IR_DIGEST_METHOD - Digest method used to check the integrity of +# reports in case they are stored on file. +# (default: SHA-256) +# +# IR_DIR=/var/log/oat_ir +# IR_DIGEST_METHOD=SHA-256 + +######################################################################## +####### Scalability Properties +######################################################################## +# +# SCALABILITY - This property activates/deactivates the scalability +# mechanism. If it is set to "on" the client will +# receive a report type defining if it has to send +# the entire list of measurements or only measurements +# not already sent. +# If the property is set to "off" (or not set), OAT +# behaviour will be unchanged. +# SCALABILITY=on + +######################################################################## +####### Discard Identical Reports Properties +######################################################################## +# +# DISCARD_IDENTICAL_IR - This property activates/deactivates a +# space-saving feature that discards an +# integrity report if it is identical to +# the last one received. +# If the property is set to "off" (or not +# set), OAT behaviour will be unchanged. +# DISCARD_IDENTICAL_IR=on + +############################################################################# +####### Mail Properties +############################################################################# + +####### Message Properties +#message.to is a comma separated list of email addresses +alert.message.to=OATApp@dod.mil +alert.message.subject=OAT Alert Notification +#message.body is a simple html email message (with the correct escape characters for a property) +alert.message.body=An integrity alert has been triggered. Please refer to the OAT portal for the OAT appraiser. PLEASE DO NOT REPLY TO TOAT AUTOMATED MESSAGE. + +####### JavaMail API Mail Properties +mail.host=localhost +mail.from=noreply@dod.mil +# mail.user= +# mail.password= +# mail.store.protocol= +# mail.transport.protocol= +# mail.smtp.host= +# mail.smtp.user= +# mail.debug= diff --git a/OpenAttestation/Installer/OAT-Appraiser-Configure/OAT_Server_Install/hibernateOat.cfg.xml b/OpenAttestation/Installer/OAT-Appraiser-Configure/OAT_Server_Install/hibernateOat.cfg.xml new file mode 100644 index 0000000..91bcd52 --- /dev/null +++ b/OpenAttestation/Installer/OAT-Appraiser-Configure/OAT_Server_Install/hibernateOat.cfg.xml @@ -0,0 +1,38 @@ + + + + + + + org.hibernate.dialect.MySQLDialect + java:comp/env/jdbc/oat + + thread + org.hibernate.hql.classic.ClassicQueryTranslatorFactory + + org.hibernate.cache.NoCacheProvider + false + true + + + false + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Installer/OAT-Appraiser-Configure/OAT_Server_Install/oat_db.MySQL b/OpenAttestation/Installer/OAT-Appraiser-Configure/OAT_Server_Install/oat_db.MySQL new file mode 100644 index 0000000..c3d23f7 --- /dev/null +++ b/OpenAttestation/Installer/OAT-Appraiser-Configure/OAT_Server_Install/oat_db.MySQL @@ -0,0 +1,71 @@ +set @@sql_mode=''; +CREATE DATABASE oat_db; +USE oat_db; +CREATE TABLE alerts ( + id int NOT NULL AUTO_INCREMENT, + audit_fk int, + status varchar(255), + assignedTo varchar(255), + comments text, + PRIMARY KEY (id) +); +CREATE TABLE audit_log ( + id int NOT NULL AUTO_INCREMENT, + SID varchar(255), + machine_name varchar(255), + timestamp datetime, + pcr0 varchar(100), + pcr1 varchar(100), + pcr4 varchar(100), + pcr5 varchar(100), + report text, + previous_differences varchar(255), + report_compare_errors text, + validation_errors text, + pcr2 varchar(100), + pcr3 varchar(100), + pcr6 varchar(100), + pcr7 varchar(100), + pcr8 varchar(100), + pcr9 varchar(100), + pcr10 varchar(100), + pcr11 varchar(100), + pcr12 varchar(100), + pcr13 varchar(100), + pcr14 varchar(100), + pcr15 varchar(100), + pcr16 varchar(100), + pcr17 varchar(100), + pcr18 varchar(100), + pcr19 varchar(100), + pcr20 varchar(100), + pcr21 varchar(100), + pcr22 varchar(100), + pcr23 varchar(100), + machine_id int, + pcr_select varchar(100), + nonce varchar(100), + signature_verified tinyint NOT NULL DEFAULT 0, + first_report int NOT NULL DEFAULT -1, + pcr_iml_mask varchar(50), + PRIMARY KEY (id) +); +CREATE TABLE machine_cert ( + id int NOT NULL AUTO_INCREMENT, + machine_name varchar(50), + certificate text, + active tinyint NOT NULL DEFAULT 1, + privacy_ca_id int, + timestamp datetime, + last_poll datetime, + next_action int, + poll_args varchar(255), + PRIMARY KEY (id) +); +CREATE TABLE system_constants ( + id int NOT NULL AUTO_INCREMENT, + key_id varchar(255), + value text, + description text, + PRIMARY KEY (id) +);insert into system_constants (key_id, value) values ('default_delay', 2500); diff --git a/OpenAttestation/Installer/OAT-Appraiser-Configure/clientInstallRefresh.sh b/OpenAttestation/Installer/OAT-Appraiser-Configure/clientInstallRefresh.sh new file mode 100644 index 0000000..ee16b92 --- /dev/null +++ b/OpenAttestation/Installer/OAT-Appraiser-Configure/clientInstallRefresh.sh @@ -0,0 +1,27 @@ +#!/bin/sh +mv ClientInstall.zip ClientInstallOld.zip +if test -d ClientInstall;then +rm -rf ClientInstall +fi +mkdir ClientInstall +cp -rf installers ClientInstall + +cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/endorsement.p12 ClientInstall/installers/hisInstall/ +cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/lib ClientInstall/installers/hisInstall/ +cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/TPMModule.properties ClientInstall/installers/hisInstall/ +cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/exe ClientInstall/installers/hisInstall/ +cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/PrivacyCA.cer ClientInstall/installers/hisInstall/ +cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/TrustStore.jks ClientInstall/installers/hisInstall/ +cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/OATprovisioner.properties ClientInstall/installers/hisInstall/ +cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/install.bat ClientInstall/installers/hisInstall/ +cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/OAT.properties ClientInstall/installers/hisInstall/ + +if test -e ClientInstall.zip;then +rm -rf ClientInstall.zip +fi +zip -9 -r ClientInstall.zip ClientInstall + +sleep 5 + +cp -f ClientInstall.zip /var/www/html/ + diff --git a/OpenAttestation/Installer/OAT-Appraiser-Configure/linuxClientInstallRefresh.sh b/OpenAttestation/Installer/OAT-Appraiser-Configure/linuxClientInstallRefresh.sh new file mode 100644 index 0000000..430b021 --- /dev/null +++ b/OpenAttestation/Installer/OAT-Appraiser-Configure/linuxClientInstallRefresh.sh @@ -0,0 +1,33 @@ +#!/bin/sh +if test -e ClientInstallForLinuxOld.zip;then +rm -f ClientInstallForLinuxOld.zip +fi +mv ClientInstallForLinux.zip ClientInstallForLinuxOld.zip +if test -d ClientInstallForLinux;then +rm -rf ClientInstallForLinux +fi +mkdir ClientInstallForLinux + +cp -rf linuxOatInstall/* ClientInstallForLinux + +cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/endorsement.p12 ClientInstallForLinux/ +#cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/lib ./ClientInstallForLinux/ +#cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/TPMModule.properties ./ClientInstallForLinux/ +#cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/exe ./ClientInstallForLinux/ +cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/PrivacyCA.cer ClientInstallForLinux/ +cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/TrustStore.jks ClientInstallForLinux/ +cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/OATprovisioner.properties ClientInstallForLinux/ +sed -i '/ClientPath/s/C:.*/\/OAT/' ClientInstallForLinux/OATprovisioner.properties +#DWC added two following lines for Chris +#cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/install.bat ./ClientInstallForLinux/ +cp -r -f /usr/lib/apache-tomcat-6.0.29/webapps/HisPrivacyCAWebServices2/ClientFiles/OAT.properties ClientInstallForLinux/ +sed -i 's/NIARL_TPM_Module\.exe/NIARL_TPM_Module/g' ./ClientInstallForLinux/OAT.properties + +if test -e ClientInstallForLinux.zip;then +rm -rf ClientInstallForLinux.zip +fi + +zip -9 -r ClientInstallForLinux.zip ClientInstallForLinux + +#places the client installation folder up for tomcat6 to display +cp -f ClientInstallForLinux.zip /var/www/html/ diff --git a/OpenAttestation/Installer/OAT-Appraiser-Configure/oatSetup.txt b/OpenAttestation/Installer/OAT-Appraiser-Configure/oatSetup.txt new file mode 100644 index 0000000..c660961 --- /dev/null +++ b/OpenAttestation/Installer/OAT-Appraiser-Configure/oatSetup.txt @@ -0,0 +1,16 @@ +CREATE TABLE `his_users` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `name` varchar(255) DEFAULT NULL, + `email` varchar(255) DEFAULT NULL, + `access` int(11) DEFAULT NULL, + `active` int(11) DEFAULT NULL, + `password` varchar(255) DEFAULT NULL, + `getsEmail` int(11) DEFAULT '0', + PRIMARY KEY (`id`) +); + + +INSERT INTO his_users +(name,email,access,active,password,getsEmail) +VALUES +('admin', 'admin', 3, 1, 'hI3MbI8WiatWI', 1); diff --git a/OpenAttestation/Installer/OAT-Appraiser-Configure/service/tomcat6 b/OpenAttestation/Installer/OAT-Appraiser-Configure/service/tomcat6 new file mode 100644 index 0000000..a037abe --- /dev/null +++ b/OpenAttestation/Installer/OAT-Appraiser-Configure/service/tomcat6 @@ -0,0 +1,96 @@ +#!/bin/sh +# +# "$Id: catalina ,v 1.0 2010/08/10 Chris_g Exp $" +# +# Startup/shutdown script for tomcat(Catalina) Application server. +# +# Linux chkconfig stuff: +# +# chkconfig: 2345 56 10 +# description: Startup/shutdown script for the tomcat application server. +###### + +# Source function library. +###### +. /etc/init.d/functions + +# Define where the catalina.sh script is located. +###### +CATALINA_BIN='/usr/lib/apache-tomcat-6.0.29/bin/catalina.sh 1> /dev/null'; + +# Find the catalina process using ps / awk. +# The match function will return 0 when no match is found with the string "java". +# Position $9 should contain the path to the Java executable used by catalina. +###### +PROC=`ps -efc | grep apache.catalina | awk 'BEGIN { FS=" "}; { if( match($9, "java") != 0 ) print $9;}'` + +# Replace a potential empty string with a fake process so the RH daemon functions are able to parse +# it properly +###### +if [[ "$PROC" == '' ]]; then + PROC='Tomcat_JVM'; +fi + +# Define the application name that is listed in the daemonize step. +PROG='Tomcat JVM'; + +# LOCKFILE +LOCK='/var/lock/subsys/tomcat'; + +start () { + echo -n $"Starting $PROG: " + + if [ -f /etc/oat-appraiser/OAT.properties ]; then + . /etc/oat-appraiser/OAT.properties >> /dev/null 2>&1 + IR_DIR=$(echo $IR_DIR|tr -d '\r') + if [ ! -d $IR_DIR ]; then + echo "Missing directory $IR_DIR" + echo "Unable to start $PROG" + exit 6; + fi + fi + + # start daemon + daemon $CATALINA_BIN start + RETVAL=$? + echo + [ $RETVAL = 0 ] && touch $LOCK + return $RETVAL +} + +stop () { + # stop daemon + echo -n $"Stopping $PROG: " + killproc $PROC + RETVAL=$? + echo + [ $RETVAL = 0 ] && rm -f $LOCK +} + +restart() { + stop + start +} + +case $1 in + start) + start + ;; + stop) + stop + ;; + restart) + restart + ;; + status) + status $PROC + RETVAL=$? + ;; + *) + + echo $"Usage: $prog {start|stop|restart|status}" + exit 3 +esac + +exit $RETVAL + diff --git a/OpenAttestation/Installer/deb.sh b/OpenAttestation/Installer/deb.sh new file mode 100644 index 0000000..aa94056 --- /dev/null +++ b/OpenAttestation/Installer/deb.sh @@ -0,0 +1,564 @@ +#!/bin/bash +DEB_BUILD_DIRECTORY=/tmp/debbuild +DEB_BUILD_SOURCE_DIRECTORY=/tmp/debbuild/SOURCE +DEB_BUILD_DPKG_DIRECTORY=/tmp/debbuild/DPKG +DEB_BUILD_DEBS_DIRECTORY=/tmp/debbuild/DEBS/x86_64 +OATSOURCE_DIRECTORY=/root/OAT/Source +#TOMCAT_DIRECTORY=/root/OAT/Installer/apache-tomcat-7.0.26 +EC_SIGNING_KEY_SIZE=2048 + +#DEB_V=NIARL_OAT_Standalone-2.0-1.x86_64.deb +SUCCESS_STATUS=1 + +ShowLogOK() +{ + echo -e "$1: --------------\033[32;49;5;1m [ OK ]\033[0m" +} + +ShowLogFaild() +{ + SUCCESS_STATUS=0 + echo -e "$1:------------\033[31;49;5;1m [ Failed ]\033[0m" + exit 0 +} + + +CreateDEBdirectory() +{ + if test -d $DEB_BUILD_DIRECTORY;then + rm -rf $DEB_BUILD_DIRECTORY + fi + mkdir $DEB_BUILD_DIRECTORY + mkdir $DEB_BUILD_DIRECTORY/BUILD + mkdir $DEB_BUILD_DIRECTORY/BUILDROOT + mkdir $DEB_BUILD_DIRECTORY/DPKG + mkdir $DEB_BUILD_DIRECTORY/DEBS + mkdir $DEB_BUILD_DIRECTORY/DEBS/x86_64 + mkdir $DEB_BUILD_DIRECTORY/DPKG/DPKG-OAT-Appraiser-Base + mkdir $DEB_BUILD_DIRECTORY/SDEBS + mkdir $DEB_BUILD_DIRECTORY/SOURCE + ShowLogOK "creat DEB directory:" +} + +#Install HIS-Appraiser-Base.tar.gz +InstallOatAppraiserBase() +{ + if test -d ./OAT-Appraiser-Configure;then + cd ./OAT-Appraiser-Configure + zip -9 clientInstallRefresh.zip clientInstallRefresh.sh + rm -f clientInstallRefresh.sh + zip -9 linuxClientInstallRefresh.zip linuxClientInstallRefresh.sh + rm -f linuxClientInstallRefresh.sh + zip -9 MySQLdrop.zip MySQLdrop.txt + rm -f MySQLdrop.txt + chmod 755 MySQLdrop.zip + zip -9 -r OAT_Server_Install.zip OAT_Server_Install/ + rm -rf OAT_Server_Install/ + zip -9 oatSetup.zip oatSetup.txt + rm -f oatSetup.txt + zip -9 -r service.zip service/ + rm -rf service/ + cd ../ + mv ./OAT-Appraiser-Configure ./OAT-Appraiser-Base + tar -czvf OAT-Appraiser-Base.tar.gz ./OAT-Appraiser-Base/ + rm -rf ./OAT-Appraiser-Base/ + fi + + if test -e ./OAT-Appraiser-Base.tar.gz;then + cp OAT-Appraiser-Base.tar.gz $DEB_BUILD_SOURCE_DIRECTORY + cp DPKG-OAT-Appraiser-Base/tomcat6.deb $DEB_BUILD_SOURCE_DIRECTORY + ShowLogOK "./OAT-Appraiser-Base.tar.gz" + else + ShowLogFaild "./OAT-Appraiser-Base.tar.gz" + fi +} + + +#NIARL_HIS_Standalone.tar.gz +CreatNiarlOatStandalone() +{ + if test -d NIARL_OAT_Standalone;then + rm -rf NIARL_OAT_Standalone + fi + mkdir NIARL_OAT_Standalone + + if test -e $OATSOURCE_DIRECTORY/HisClient/OAT07.jpg;then + cp $OATSOURCE_DIRECTORY/HisClient/OAT07.jpg NIARL_OAT_Standalone + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/OAT07.jpg" + fi + + if test -e ./FilesForLinux/OAT.sh;then + cp ./FilesForLinux/OAT.sh NIARL_OAT_Standalone + else + ShowLogFaild "./FilesForLinux/OAT.sh" + fi + if test -e $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar;then + cp $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar NIARL_OAT_Standalone + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar" + fi + + if test -e $OATSOURCE_DIRECTORY/HisClient/log4j.properties;then + cp $OATSOURCE_DIRECTORY/HisClient/log4j.properties NIARL_OAT_Standalone + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/log4j.properties" + fi + +# if test -e $OATSOURCE_DIRECTORY/HisClient/OAT.properties;then +# cp $OATSOURCE_DIRECTORY/HisClient/OAT.properties NIARL_OAT_Standalone +# else +# ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/OAT.properties" +# fi + + if test -d $OATSOURCE_DIRECTORY/HisClient/lib/;then + cp -r $OATSOURCE_DIRECTORY/HisClient/lib/ NIARL_OAT_Standalone + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/lib/" + fi + + + tar -zcvf NIARL_OAT_Standalone.tar.gz NIARL_OAT_Standalone + mv NIARL_OAT_Standalone.tar.gz $DEB_BUILD_SOURCE_DIRECTORY + rm -rf OAT + mv NIARL_OAT_Standalone OAT + tar -zcvf NIARL_OAT_Standalone.tar.gz OAT + ShowLogOK "NIARL_OAT_Standalone.tar.gz" +} + + +LinuxOatInstall() +{ + if test -d linuxOatInstall;then + rm -rf linuxOatInstall + fi + mkdir linuxOatInstall + + if test -e ./FilesForLinux/install.sh ;then + cp ./FilesForLinux/install.sh linuxOatInstall + else + ShowLogFaild "./FilesForLinux/install.sh" + fi + + if test -e ./FilesForLinux/general-install.sh;then + cp ./FilesForLinux/general-install.sh linuxOatInstall + else + ShowLogFaild "./FilesForLinux/general-install.sh" + fi + + if test -d ./FilesForLinux/shells;then + cp -ar ./FilesForLinux/shells linuxOatInstall + else + ShowLogFaild "./FilesForLinux/shells" + fi + + if test -e $OATSOURCE_DIRECTORY/PrivacyCA/provisioner.sh;then + cp $OATSOURCE_DIRECTORY/PrivacyCA/provisioner.sh linuxOatInstall + else + ShowLogFaild "$OATSOURCE_DIRECTORY/PrivacyCA/provisioner.sh" + fi + + + if test -e $OATSOURCE_DIRECTORY/PrivacyCA/TPMModule.properties;then + cp $OATSOURCE_DIRECTORY/PrivacyCA/TPMModule.properties linuxOatInstall + else + ShowLogFaild "$OATSOURCE_DIRECTORY/PrivacyCA/TPMModule.properties" + fi + + + if test -d $OATSOURCE_DIRECTORY/HisClient/lib;then + cp -r $OATSOURCE_DIRECTORY/HisClient/lib linuxOatInstall + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/lib" + fi + + if test -d $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/ClientFiles/lib;then + cp $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/ClientFiles/lib/* linuxOatInstall/lib + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/ClientFiles/lib" + fi + + if test -e linuxOatInstall/lib/PrivacyCA.jar;then + rm -rf linuxOatInstall/lib/PrivacyCA.jar + fi + + if test -e $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar;then + cp $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar linuxOatInstall/lib + else + ShowLogFaild "$OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar" + fi + chmod 755 linuxOatInstall/lib/* + + if test -e $OATSOURCE_DIRECTORY/TPMModule/plain/linux/NIARL_TPM_Module;then + cp $OATSOURCE_DIRECTORY/TPMModule/plain/linux/NIARL_TPM_Module linuxOatInstall + mkdir -p linuxOatInstall/exe + cp linuxOatInstall/NIARL_TPM_Module linuxOatInstall/exe + else + ShowLogFaild "$OATSOURCE_DIRECTORY/TPMModule/plain/linux/NIARL_TPM_Module" + fi + + +# if test -e ./NIARL_OAT_Standalone.tar.gz;then +# cp ./NIARL_OAT_Standalone.tar.gz linuxOatInstall +# else +# ShowLogFaild "./NIARL_OAT_Standalone.tar.gz" +# fi + + if test -e ./ClientInstallForLinux.zip;then + rm -rf ClientInstallForLinux.zip + fi + zip -r ClientInstallForLinux.zip linuxOatInstall + ShowLogOK "ClientInstallForLinux.zip" + rm -rf linuxOatInstall +} + +RePkgInstallOatAppraiserBase() +{ + CurDir=$(pwd) + if test -e $DEB_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base.tar.gz;then + cd $DEB_BUILD_SOURCE_DIRECTORY + rm -rf OAT-Appraiser-Base + tar -zxvf OAT-Appraiser-Base.tar.gz + else + ShowLogFaild "$DEB_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base.tar.gz" + fi + +##################################################################################### + echo "$DEB_BUILD_SOURCE_DIRECTORY" + if test -e $CurDir/FilesForLinux/OAT.sh;then + cp $CurDir/FilesForLinux/OAT.sh $DEB_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + else + ShowLogFaild "./FilesForLinux/OAT.sh" + fi + if test -e $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar;then + cp $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar $DEB_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + echo "dave print out the location of OAT_Standalong.jar" + echo -e '\n' + echo $DEB_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar" + fi + + if test -e $OATSOURCE_DIRECTORY/HisClient/log4j.properties;then + cp $OATSOURCE_DIRECTORY/HisClient/log4j.properties $DEB_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/log4j.properties" + fi + + + if test -d $OATSOURCE_DIRECTORY/HisClient/lib/;then + cp -r $OATSOURCE_DIRECTORY/HisClient/lib/ $DEB_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/lib/" + fi +###################################################################################### + + cp $DEB_BUILD_SOURCE_DIRECTORY/tomcat6.deb OAT-Appraiser-Base + + if test -e $CurDir/FilesForLinux/apache-tomcat-6.0.29.tar.gz;then + cp $CurDir/FilesForLinux/apache-tomcat-6.0.29.tar.gz $DEB_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + else + ShowLogFaild "$CurDir/FilesForLinux/apache-tomcat-6.0.29.tar.gz" + fi + + if test -e $CurDir/ClientInstallForLinux.zip;then + cp $CurDir/ClientInstallForLinux.zip $DEB_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + else + ShowLogFaild "$CurDir/ClientInstallForLinux.zip" + fi + + cd $DEB_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + + if test -e HisPrivacyCAWebServices2.war;then + rm -rf HisPrivacyCAWebServices2.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war;then + cp $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war . + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war" + fi + + mkdir HisPrivacyCAWebServices2 + mv HisPrivacyCAWebServices2.war HisPrivacyCAWebServices2 + cd HisPrivacyCAWebServices2 + unzip HisPrivacyCAWebServices2.war + rm -rf HisPrivacyCAWebServices2.war + + echo "\n\r" >> setup.properties + echo "ecSigningKeySize=$EC_SIGNING_KEY_SIZE" >> setup.properties + echo "ecStorage=NVRAM" >> setup.properties + zip -9 setupProperties.zip setup.properties + mv setupProperties.zip ../ + if test -d CaCerts;then + rm -rf CaCerts + fi + mkdir CaCerts + + zip -9 -r HisPrivacyCAWebServices2.war . + if test -e HisPrivacyCAWebServices2.war;then + mv HisPrivacyCAWebServices2.war ../ + cd ../ + rm -rf HisPrivacyCAWebServices2 + fi + +###HIS_Server_Install.zip#### + cd $DEB_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + if test -e OAT_Server_Install.zip;then + unzip OAT_Server_Install.zip + rm -rf OAT_Server_Install.zip + else + ShowLogFaild "OAT_Server_Install.zip" + fi + + cd OAT_Server_Install + + if test -d HisWebServices;then + rm -rf HisWebServices + fi + mkdir HisWebServices + + if test -d $OATSOURCE_DIRECTORY/HisWebServices/WEB-INF;then + cp -r $OATSOURCE_DIRECTORY/HisWebServices/WEB-INF ./HisWebServices/ + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisWebServices/WEB-INF" + fi + #HIS.properties +# sed -i "s/^PCR_SELECT=.*$/PCR_SELECT=FFFFFF/g" OAT.properties +# echo "insert into system_constants (key_id, value) values ('default_delay', 10000);" >> oat_db.MySQL +# sed -ie '/<\/session-factory\>/i\\ ' hibernateOat.cfg.xml + + if test -e hibernateOat.cfg.xmle;then + rm -rf hibernateOat.cfg.xmle + fi + + cp $OATSOURCE_DIRECTORY/WLMService/WLMService.war . + cp $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war . + + if test -e $CurDir/FilesForLinux/init.sql;then + cp $CurDir/FilesForLinux/init.sql . + else + ShowLogFaild "$CurDir/FilesForLinux/init.sql" + fi + + cd $DEB_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + + zip -9 -r OAT_Server_Install.zip OAT_Server_Install + + rm -rf OAT_Server_Install + ###### + #OAT.zip + if test -d $OATSOURCE_DIRECTORY/Portal;then + cp -r $OATSOURCE_DIRECTORY/Portal OAT + else + ShowLogFaild "$OATSOURCE_DIRECTORY/Portal" + fi + + if test -e OAT.zip;then + rm -rf OAT.zip + fi + + zip -9 -r OAT.zip OAT + rm -rf OAT + ############# + + cd $DEB_BUILD_SOURCE_DIRECTORY + rm -rf OAT-Appraiser-Base.tar.gz + tar -zcvf OAT-Appraiser-Base.tar.gz OAT-Appraiser-Base + rm -rf OAT-Appraiser-Base + cd $DEB_BUILD_SOURCE_DIRECTORY + cp OAT-Appraiser-Base.tar.gz $DEB_BUILD_DPKG_DIRECTORY/DPKG-OAT-Appraiser-Base/ + cd $DEB_BUILD_DPKG_DIRECTORY/DPKG-OAT-Appraiser-Base + tar -xzvf OAT-Appraiser-Base.tar.gz + cd $CurDir + ShowLogOK "repackage OAT-Appraiser-Base.tar.gz" +} + +debbuild() +{ + if test -e ./DPKG-OAT-Appraiser-Base/DEBIAN/postinst;then + cp -R ./DPKG-OAT-Appraiser-Base/DEBIAN/ $DEB_BUILD_DPKG_DIRECTORY/DPKG-OAT-Appraiser-Base + else + ShowLogFaild "./DPKG-OAT-Appraiser-Base/DEBIAN/postinst" + fi + + if test -d /OAT-Appraiser-Base;then + rm -rf /OAT-Appraiser-Base + fi + + cd $DEB_BUILD_DPKG_DIRECTORY + rm -rf $DEB_BUILD_DPKG_DIRECTORY/DPKG-OAT-Appraiser-Base/OAT-Appraiser-Base.tar.gz + dpkg -b DPKG-OAT-Appraiser-Base $DEB_BUILD_DEBS_DIRECTORY/OAT-Appraiser-Base-OATapp-1.0.0-2.x86_64.deb +} + + +Build_xml() +{ + CurDir=$(pwd) + if test -e $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar;then + rm -rf $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar + fi + + if test -e $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar;then + rm -rf $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar + fi + + if test -e $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar;then + rm -rf $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar + fi + + if test -e $OATSOURCE_DIRECTORY/HisWebServices/clientlib/HisWebServices-client.jar;then + rm -rf $OATSOURCE_DIRECTORY/HisWebServices/clientlib/HisWebServices-client.jar + fi + + if test -e $OATSOURCE_DIRECTORY/HisWebServices/HisWebServices.war;then + rm -rf $OATSOURCE_DIRECTORY/HisWebServices/HisWebServices.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war;then + rm -rf $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/clientlib/HisPrivacyCAWebServices2-client.jar;then + rm -rf $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/clientlib/HisPrivacyCAWebServices2-client.jar + fi + + if test -e $OATSOURCE_DIRECTORY/WLMService/WLMService.war;then + rm -rf $OATSOURCE_DIRECTORY/WLMService/WLMService.war + fi + + if test -e $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war;then + rm -rf $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war + fi + + if test -e $OATSOURCE_DIRECTORY/build.sh;then + cd $OATSOURCE_DIRECTORY + bash build.sh + #bash build.sh $TOMCAT_DIRECTORY + else + ShowLogFaild "$OATSOURCE_DIRECTORY/build.sh" + fi + + if test -d $OATSOURCE_DIRECTORY/WLMService;then + cd $OATSOURCE_DIRECTORY/WLMService + ant -file build.xml + else + ShowLogFaild "$OATSOURCE_DIRECTORY/WLMService" + fi + if test -d $OATSOURCE_DIRECTORY/AttestationService;then + cd $OATSOURCE_DIRECTORY/AttestationService + cp -rf $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar ./WebContent/WEB-INF/lib/ + ant -file build.xml + else + ShowLogFaild "$OATSOURCE_DIRECTORY/AttestationService" + fi + + + if test -e $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar;then + ShowLogOK $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar + fi + + if test -e $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar;then + ShowLogOK $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar + else + ShowLogFaild $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar + fi + + if test -e $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar;then + ShowLogOK $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar + fi + + if test -e $OATSOURCE_DIRECTORY/WLMService/WLMService.war;then + ShowLogOK $OATSOURCE_DIRECTORY/WLMService/WLMService.war + else + ShowLogFaild $OATSOURCE_DIRECTORY/WLMService/WLMService.war + fi + + if test -e $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war;then + ShowLogOK $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war + else + ShowLogFaild $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisWebServices/HisWebServices.war;then + ShowLogOK $OATSOURCE_DIRECTORY/HisWebServices/HisWebServices.war + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisWebServices/HisWebServices.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisWebServices/clientlib/HisWebServices-client.jar;then + ShowLogOK $OATSOURCE_DIRECTORY/HisWebServices/clientlib/HisWebServices-client.jar + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisWebServices/clientlib/HisWebServices-client.jar + fi + + + if test -e $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war;then + ShowLogOK $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/clientlib/HisPrivacyCAWebServices2-client.jar;then + ShowLogOK $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/clientlib/HisPrivacyCAWebServices2-client.jar + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/clientlib/HisPrivacyCAWebServices2-client.jar + fi + + + cd $CurDir +} + +#main +SourceFileOP=-s +#TomCatOP=-t +if [ $# -lt 2 ];then +ShowLogFaild "Parameter ERROR! for example:sh deb.sh -s /usr/local/src/OAT/Source" +fi + +if [ $1 = $SourceFileOP ];then + OATSOURCE_DIRECTORY=$2 +fi + +if [ -d $OATSOURCE_DIRECTORY ]; then + ShowLogOK "Source file" +else + ShowLogFaild "$OATSOURCE_DIRECTORY No such directory" +fi +Lchar=${OATSOURCE_DIRECTORY:$((${#OATSOURCE_DIRECTORY}-1)):1} +if [ $Lchar == "/" ];then + OATSOURCE_DIRECTORY=${OATSOURCE_DIRECTORY:0:$((${#OATSOURCE_DIRECTORY}-1))} +fi +echo $OATSOURCE_DIRECTORY + +#if [ $3 = $TomCatOP ];then +# TOMCAT_DIRECTORY=$4 +#fi + +#if [ -d $TOMCAT_DIRECTORY ]; then +# ShowLogOK "tomcat" +#else +# ShowLogFaild "$TOMCAT_DIRECTORY No such directory" +#fi + +if [ $# -gt 3 -a $3="-ks" ];then + EC_SIGNING_KEY_SIZE=$4 +fi + +Build_xml +CreateDEBdirectory +InstallOatAppraiserBase +#CreatNiarlOatStandalone +LinuxOatInstall +RePkgInstallOatAppraiserBase +debbuild +echo $SUCCESS_STATUS +if [ $SUCCESS_STATUS -eq 1 ];then + ShowLogOK "DEB build" +else + ShowLogFaild "DEB build" +fi diff --git a/OpenAttestation/Installer/readme.txt b/OpenAttestation/Installer/readme.txt new file mode 100644 index 0000000..3190f91 --- /dev/null +++ b/OpenAttestation/Installer/readme.txt @@ -0,0 +1,5 @@ +################ Build installation package process############# +. run "sh remove_jar_packages.sh" to remove all unnecessary jar packages +. run "sh download_jar_packages.sh" to download new third party jar packages +. run "sh distribute_jar_packages.sh" to distribute downloaded third party jar packages to corresponding source folders +. run "sh rpm.sh -s /xxx/Source -t /xxx/apache-tomcat-x.x.x" to build installation rpm package diff --git a/OpenAttestation/Installer/rpm.sh b/OpenAttestation/Installer/rpm.sh new file mode 100644 index 0000000..920d681 --- /dev/null +++ b/OpenAttestation/Installer/rpm.sh @@ -0,0 +1,533 @@ +#!/bin/sh +RPM_BUILD_DIRECTORY=/root/rpmbuild +RPM_BUILD_SOURCE_DIRECTORY=/root/rpmbuild/SOURCES +RPM_BUILD_SPECS_DIRECTORY=/root/rpmbuild/SPECS +RPM_BUILD_RPMS_DIRECTORY=/root/rpmbuild/RPMS/x86_64 +OATSOURCE_DIRECTORY=/root/OAT/Source +#TOMCAT_DIRECTORY=/root/OAT/Installer/apache-tomcat-7.0.26 +EC_SIGNING_KEY_SIZE=2048 +RPM_V=NIARL_OAT_Standalone-2.0-1.x86_64.rpm +SUCCESS_STATUS=1 + +ShowLogOK() +{ + echo -e "$1: --------------\033[32;49;5;1m [ OK ]\033[0m" +} + +ShowLogFaild() +{ + SUCCESS_STATUS=0 + echo -e "$1:------------\033[31;49;5;1m [ Failed ]\033[0m" + exit 0 +} + + +CreateRPMdirectory() +{ + if test -d $RPM_BUILD_DIRECTORY;then + rm -rf $RPM_BUILD_DIRECTORY + fi + mkdir $RPM_BUILD_DIRECTORY + mkdir $RPM_BUILD_DIRECTORY/BUILD + mkdir $RPM_BUILD_DIRECTORY/BUILDROOT + mkdir $RPM_BUILD_DIRECTORY/RPMS + mkdir $RPM_BUILD_DIRECTORY/SOURCES + mkdir $RPM_BUILD_DIRECTORY/SPECS + mkdir $RPM_BUILD_DIRECTORY/SRPMS + ShowLogOK "creat RPM directory:" +} + +#Install HIS-Appraiser-Base.tar.gz +InstallOatAppraiserBase() +{ + if test -d ./OAT-Appraiser-Configure;then + cd ./OAT-Appraiser-Configure + zip -9 clientInstallRefresh.zip clientInstallRefresh.sh + rm -f clientInstallRefresh.sh + zip -9 linuxClientInstallRefresh.zip linuxClientInstallRefresh.sh + rm -f linuxClientInstallRefresh.sh + zip -9 MySQLdrop.zip MySQLdrop.txt + rm -f MySQLdrop.txt + chmod 755 MySQLdrop.zip + zip -9 -r OAT_Server_Install.zip OAT_Server_Install/ + rm -rf OAT_Server_Install/ + zip -9 oatSetup.zip oatSetup.txt + rm -f oatSetup.txt + zip -9 -r service.zip service/ + rm -rf service/ + cd ../ + tar -czvf OAT-Appraiser-Configure.tar.gz ./OAT-Appraiser-Configure/ + fi + + if test -e ./OAT-Appraiser-Configure.tar.gz;then + cp OAT-Appraiser-Configure.tar.gz $RPM_BUILD_SOURCE_DIRECTORY + ShowLogOK "./OAT-Appraiser-Configure.tar.gz" + rm -rf ./OAT-Appraiser-Configure + else + ShowLogFaild "./OAT-Appraiser-Configure.tar.gz" + fi +} + + +#NIARL_HIS_Standalone.tar.gz +CreatNiarlOatStandalone() +{ + if test -d NIARL_OAT_Standalone;then + rm -rf NIARL_OAT_Standalone + fi + mkdir NIARL_OAT_Standalone + + if test -e $OATSOURCE_DIRECTORY/HisClient/OAT07.jpg;then + cp $OATSOURCE_DIRECTORY/HisClient/OAT07.jpg NIARL_OAT_Standalone + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/OAT07.jpg" + fi + + if test -e ./FilesForLinux/OAT.sh;then + cp ./FilesForLinux/OAT.sh NIARL_OAT_Standalone + else + ShowLogFaild "./FilesForLinux/OAT.sh" + fi + if test -e $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar;then + cp $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar NIARL_OAT_Standalone + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar" + fi + + if test -e $OATSOURCE_DIRECTORY/HisClient/log4j.properties;then + cp $OATSOURCE_DIRECTORY/HisClient/log4j.properties NIARL_OAT_Standalone + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/log4j.properties" + fi + + + if test -d $OATSOURCE_DIRECTORY/HisClient/lib/;then + cp -r $OATSOURCE_DIRECTORY/HisClient/lib/ NIARL_OAT_Standalone + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/lib/" + fi + +} + + +LinuxOatInstall() +{ + if test -d linuxOatInstall;then + rm -rf linuxOatInstall + fi + mkdir linuxOatInstall + + if test -e ./FilesForLinux/install.sh ;then + cp ./FilesForLinux/install.sh linuxOatInstall + else + ShowLogFaild "./FilesForLinux/install.sh" + fi + + if test -e ./FilesForLinux/general-install.sh;then + cp ./FilesForLinux/general-install.sh linuxOatInstall + else + ShowLogFaild "./FilesForLinux/general-install.sh" + fi + + if test -d ./FilesForLinux/shells;then + cp -ar ./FilesForLinux/shells linuxOatInstall + else + ShowLogFaild "./FilesForLinux/shells" + fi + +# if test -e $RPM_BUILD_RPMS_DIRECTORY/$RPM_V;then +# cp $RPM_BUILD_RPMS_DIRECTORY/$RPM_V linuxOatInstall +# else +# ShowLogFaild "$RPM_BUILD_RPMS_DIRECTORY/$RPM_V" +# fi + + if test -e $OATSOURCE_DIRECTORY/PrivacyCA/provisioner.sh;then + cp $OATSOURCE_DIRECTORY/PrivacyCA/provisioner.sh linuxOatInstall + else + ShowLogFaild "$OATSOURCE_DIRECTORY/PrivacyCA/provisioner.sh" + fi + + + if test -e $OATSOURCE_DIRECTORY/PrivacyCA/TPMModule.properties;then + cp $OATSOURCE_DIRECTORY/PrivacyCA/TPMModule.properties linuxOatInstall + else + ShowLogFaild "$OATSOURCE_DIRECTORY/PrivacyCA/TPMModule.properties" + fi + + + if test -d $OATSOURCE_DIRECTORY/HisClient/lib;then + cp -r $OATSOURCE_DIRECTORY/HisClient/lib linuxOatInstall + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/lib" + fi + + if test -d $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/ClientFiles/lib;then + cp $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/ClientFiles/lib/* linuxOatInstall/lib + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/ClientFiles/lib" + fi + + if test -e linuxOatInstall/lib/PrivacyCA.jar;then + rm -rf linuxOatInstall/lib/PrivacyCA.jar + fi + + if test -e $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar;then + cp $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar linuxOatInstall/lib + else + ShowLogFaild "$OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar" + fi + chmod 755 linuxOatInstall/lib/* + + if test -e $OATSOURCE_DIRECTORY/TPMModule/plain/linux/NIARL_TPM_Module;then + cp $OATSOURCE_DIRECTORY/TPMModule/plain/linux/NIARL_TPM_Module linuxOatInstall + mkdir -p linuxOatInstall/exe + cp linuxOatInstall/NIARL_TPM_Module linuxOatInstall/exe + else + ShowLogFaild "$OATSOURCE_DIRECTORY/TPMModule/plain/linux/NIARL_TPM_Module" + fi + + if test -e ./ClientInstallForLinux.zip;then + rm -rf ClientInstallForLinux.zip + fi + zip -r ClientInstallForLinux.zip linuxOatInstall + ShowLogOK "ClientInstallForLinux.zip" + rm -rf linuxOatInstall +} + +RePkgInstallOatAppraiserBase() +{ + CurDir=$(pwd) + if test -e $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Configure.tar.gz;then + cd $RPM_BUILD_SOURCE_DIRECTORY + rm -rf OAT-Appraiser-Configure + tar -zxvf OAT-Appraiser-Configure.tar.gz + else + ShowLogFaild "$RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Configure.tar.gz" + fi + +########################### + echo "$RPM_BUILD_SOURCE_DIRECTORY" + if test -e $CurDir/FilesForLinux/OAT.sh;then + cp $CurDir/FilesForLinux/OAT.sh $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Configure + else + ShowLogFaild "./FilesForLinux/OAT.sh" + fi + if test -e $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar;then + cp $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Configure + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar" + fi + + if test -e $OATSOURCE_DIRECTORY/HisClient/log4j.properties;then + cp $OATSOURCE_DIRECTORY/HisClient/log4j.properties $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Configure + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/log4j.properties" + fi + + + if test -d $OATSOURCE_DIRECTORY/HisClient/lib/;then + cp -r $OATSOURCE_DIRECTORY/HisClient/lib/ $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Configure + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/lib/" + fi +########################## + + if test -e $CurDir/FilesForLinux/apache-tomcat-6.0.29.tar.gz;then + cp $CurDir/FilesForLinux/apache-tomcat-6.0.29.tar.gz $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Configure + else + ShowLogFaild "$CurDir/FilesForLinux/apache-tomcat-6.0.29.tar.gz" + fi + + if test -e $CurDir/ClientInstallForLinux.zip;then + cp $CurDir/ClientInstallForLinux.zip $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Configure + else + ShowLogFaild "$CurDir/ClientInstallForLinux.zip" + fi + + cd $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Configure + + if test -e HisPrivacyCAWebServices2.war;then + rm -rf HisPrivacyCAWebServices2.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war;then + cp $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war . + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war" + fi + + mkdir HisPrivacyCAWebServices2 + mv HisPrivacyCAWebServices2.war HisPrivacyCAWebServices2 + cd HisPrivacyCAWebServices2 + unzip HisPrivacyCAWebServices2.war + rm -rf HisPrivacyCAWebServices2.war + + echo "\n\r" >> setup.properties + echo "ecSigningKeySize=$EC_SIGNING_KEY_SIZE" >> setup.properties + echo "ecStorage=NVRAM" >> setup.properties + zip -9 setupProperties.zip setup.properties + mv setupProperties.zip ../ + + if test -d CaCerts;then + rm -rf CaCerts + fi + mkdir CaCerts + + zip -9 -r HisPrivacyCAWebServices2.war . + if test -e HisPrivacyCAWebServices2.war;then + mv HisPrivacyCAWebServices2.war ../ + cd ../ + rm -rf HisPrivacyCAWebServices2 + fi + +###HIS_Server_Install.zip#### + cd $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Configure + if test -e OAT_Server_Install.zip;then + unzip OAT_Server_Install.zip + rm -rf OAT_Server_Install.zip + else + ShowLogFaild "OAT_Server_Install.zip" + fi + + cd OAT_Server_Install + + if test -d HisWebServices;then + rm -rf HisWebServices + fi + mkdir HisWebServices + + if test -d $OATSOURCE_DIRECTORY/HisWebServices/WEB-INF;then + cp -r $OATSOURCE_DIRECTORY/HisWebServices/WEB-INF ./HisWebServices/ + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisWebServices/WEB-INF" + fi + +# OpenAttestation *.war --> HIS_Server_Install.zip +#if test -e $CurDir/$OATSOURCE_DIRECTORY/OpenAttestationAdminConsole/OpenAttestationAdminConsole.war -a -e $CurDir/$OATSOURCE_DIRECTORY/OpenAttestationManifestWebServices/OpenAttestationManifestWebServices.war -e $CurDir/$OATSOURCE_DIRECTORY/OpenAttestationWebServices/OpenAttestationWebServices.war;then + cp $OATSOURCE_DIRECTORY/WLMService/WLMService.war . + cp $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war . +#else +# ShowLogFaild "$OATSOURCE_DIRECTORY/OpenAttestationAdminConsole/OpenAttestationAdminConsole.war ^ $OATSOURCE_DIRECTORY/OpenAttestationManifestWebServices/OpenAttestationManifestWebServices.war ^ $OATSOURCE_DIRECTORY/OpenAttestationWebServices/OpenAttestationWebServices.war " +#fi + + +if test -e $CurDir/FilesForLinux/init.sql;then + cp $CurDir/FilesForLinux/init.sql . +else + ShowLogFaild "$CurDir/FilesForLinux/init.sql" +fi + + cd $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Configure + + zip -9 -r OAT_Server_Install.zip OAT_Server_Install + +rm -rf OAT_Server_Install +###### +#OAT.zip +if test -d $OATSOURCE_DIRECTORY/Portal;then + cp -r $OATSOURCE_DIRECTORY/Portal OAT +else + ShowLogFaild "$OATSOURCE_DIRECTORY/Portal" +fi + +if test -e OAT.zip;then + rm -rf OAT.zip +fi + +zip -9 -r OAT.zip OAT +rm -rf OAT +############# + + cd $RPM_BUILD_SOURCE_DIRECTORY + rm -rf OAT-Appraiser-Configure.tar.gz + tar -zcvf OAT-Appraiser-Configure.tar.gz OAT-Appraiser-Configure + rm -rf OAT-Appraiser-Configure + cd $CurDir + ShowLogOK "repackage OAT-Appraiser-Configure.tar.gz" +} + +RPMbuild() +{ + if test -e ./OAT-Appraiser-Base.spec;then + cp OAT-Appraiser-Base.spec $RPM_BUILD_SPECS_DIRECTORY + else + ShowLogFaild "./OAT-Appraiser-Base.spec" + fi + + if test -d /OAT-Appraiser-Configure;then + rm -rf /OAT-Appraiser-Configure + fi + + cd $RPM_BUILD_SPECS_DIRECTORY + rpmbuild -bb OAT-Appraiser-Base.spec +} + + +Build_xml() +{ + CurDir=$(pwd) + if test -e $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar;then + rm -rf $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar + fi + + if test -e $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar;then + rm -rf $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar + fi + + if test -e $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar;then + rm -rf $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar + fi + + if test -e $OATSOURCE_DIRECTORY/HisWebServices/clientlib/HisWebServices-client.jar;then + rm -rf $OATSOURCE_DIRECTORY/HisWebServices/clientlib/HisWebServices-client.jar + fi + + if test -e $OATSOURCE_DIRECTORY/HisWebServices/HisWebServices.war;then + rm -rf $OATSOURCE_DIRECTORY/HisWebServices/HisWebServices.war + fi + + if test -e $OATSOURCE_DIRECTORY/WLMService/WLMService.war;then + rm -rf $OATSOURCE_DIRECTORY/WLMService/WLMService.war + fi + + if test -e $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war;then + rm -rf $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war;then + rm -rf $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/clientlib/HisPrivacyCAWebServices2-client.jar;then + rm -rf $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/clientlib/HisPrivacyCAWebServices2-client.jar + fi + + if test -e $OATSOURCE_DIRECTORY/build.sh;then + cd $OATSOURCE_DIRECTORY +# sh build.sh $TOMCAT_DIRECTORY + sh build.sh + else + ShowLogFaild "$OATSOURCE_DIRECTORY/build.sh" + fi + + + if test -d $OATSOURCE_DIRECTORY/WLMService;then + cd $OATSOURCE_DIRECTORY/WLMService + ant -file build.xml + else + ShowLogFaild "$OATSOURCE_DIRECTORY/WLMService" + fi + + if test -d $OATSOURCE_DIRECTORY/AttestationService;then + cd $OATSOURCE_DIRECTORY/AttestationService + cp -rf $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar ./WebContent/WEB-INF/lib/ + ant -file build.xml + else + ShowLogFaild "$OATSOURCE_DIRECTORY/AttestationService" + fi + + if test -e $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar;then + ShowLogOK $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar + fi + + if test -e $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar;then + ShowLogOK $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar + else + ShowLogFaild $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar + fi + + if test -e $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar;then + ShowLogOK $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar + fi + + if test -e $OATSOURCE_DIRECTORY/HisWebServices/HisWebServices.war;then + ShowLogOK $OATSOURCE_DIRECTORY/HisWebServices/HisWebServices.war + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisWebServices/HisWebServices.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisWebServices/clientlib/HisWebServices-client.jar;then + ShowLogOK $OATSOURCE_DIRECTORY/HisWebServices/clientlib/HisWebServices-client.jar + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisWebServices/clientlib/HisWebServices-client.jar + fi + + if test -e $OATSOURCE_DIRECTORY/WLMService/WLMService.war;then + ShowLogOK $OATSOURCE_DIRECTORY/WLMService/WLMService.war + else + ShowLogFaild $OATSOURCE_DIRECTORY/WLMService/WLMService.war + fi + + if test -e $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war;then + ShowLogOK $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war + else + ShowLogFaild $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war;then + ShowLogOK $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/clientlib/HisPrivacyCAWebServices2-client.jar;then + ShowLogOK $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/clientlib/HisPrivacyCAWebServices2-client.jar + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/clientlib/HisPrivacyCAWebServices2-client.jar + fi + + + cd $CurDir +} + +#main +SourceFileOP=-s +#TomCatOP=-t +if [ $# -lt 2 ];then +ShowLogFaild "Parameter ERROR! for example:sh rpm.sh -s /usr/local/src/OAT/Source" +fi + +if [ $1 = $SourceFileOP ];then + OATSOURCE_DIRECTORY=$2 +fi + +if [ -d $OATSOURCE_DIRECTORY ]; then + ShowLogOK "Source file" +else + ShowLogFaild "$OATSOURCE_DIRECTORY No such directory" +fi + +#if [ $3 = $TomCatOP ];then +# TOMCAT_DIRECTORY=$4 +#fi + +#if [ -d $TOMCAT_DIRECTORY ]; then +# ShowLogOK "tomcat" +#else +# ShowLogFaild "$TOMCAT_DIRECTORY No such directory" +#fi + +if [ $# -gt 3 -a $3 = "-ks" ];then + EC_SIGNING_KEY_SIZE=$4 +fi +echo "EC_SIGNING_KEY_SIZE=$4" + + +Build_xml +CreateRPMdirectory +echo "########install oat base########" +InstallOatAppraiserBase +CreatNiarlOatStandalone +LinuxOatInstall +RePkgInstallOatAppraiserBase +RPMbuild +echo $SUCCESS_STATUS +if [ $SUCCESS_STATUS -eq 1 ];then + ShowLogOK "RPM build" +else + ShowLogFaild "RPM build" +fi diff --git a/OpenAttestation/Installer/rpm_for_sles.sh b/OpenAttestation/Installer/rpm_for_sles.sh new file mode 100644 index 0000000..9f932ed --- /dev/null +++ b/OpenAttestation/Installer/rpm_for_sles.sh @@ -0,0 +1,590 @@ +#!/bin/sh +RPM_BUILD_DIRECTORY=/root/rpmbuild +RPM_BUILD_SOURCE_DIRECTORY=/root/rpmbuild/SOURCES +RPM_BUILD_SPECS_DIRECTORY=/root/rpmbuild/SPECS +RPM_BUILD_RPMS_DIRECTORY=/root/rpmbuild/RPMS/x86_64 +OATSOURCE_DIRECTORY=/root/OAT/Source +#TOMCAT_DIRECTORY=/root/OAT/Installer/apache-tomcat-7.0.26 +DEFAULT_DIRECTORY=/usr/src/packages +EC_SIGNING_KEY_SIZE=2048 + +#RPM_V=NIARL_OAT_Standalone-2.0-1.x86_64.rpm +SUCCESS_STATUS=1 + +ShowLogOK() +{ + echo -e "$1: --------------\033[32;49;5;1m [ OK ]\033[0m" +} + +ShowLogFaild() +{ + SUCCESS_STATUS=0 + echo -e "$1:------------\033[31;49;5;1m [ Failed ]\033[0m" + exit 0 +} + + +CreateRPMdirectory() +{ + if test -d $RPM_BUILD_DIRECTORY;then + rm -rf $RPM_BUILD_DIRECTORY + fi + [[ -d $DEFAULT_DIRECTORY ]] && rm -rf $DEFAULT_DIRECTORY + mkdir $RPM_BUILD_DIRECTORY + mkdir $DEFAULT_DIRECTORY + mkdir $DEFAULT_DIRECTORY/BUILD + mkdir $DEFAULT_DIRECTORY/RPMS + mkdir $DEFAULT_DIRECTORY/SOURCES + mkdir $DEFAULT_DIRECTORY/SPEC + mkdir $DEFAULT_DIRECTORY/SRPMS + + if test -d $DEFAULT_DIRECTORY;then + ln -fs $DEFAULT_DIRECTORY/BUILD $RPM_BUILD_DIRECTORY/BUILD + ln -fs $DEFAULT_DIRECTORY/RPMS $RPM_BUILD_DIRECTORY/RPMS + ln -fs $DEFAULT_DIRECTORY/SOURCES $RPM_BUILD_DIRECTORY/SOURCES + ln -fs $DEFAULT_DIRECTORY/SPEC $RPM_BUILD_DIRECTORY/SPECS + ln -fs $DEFAULT_DIRECTORY/SRPMS $RPM_BUILD_DIRECTORY/SRPMS + ShowLogOK "creat RPM directory:" + fi +} + +#Install HIS-Appraiser-Base.tar.gz +InstallOatAppraiserBase() +{ + if test -d ./OAT-Appraiser-Configure;then + cd ./OAT-Appraiser-Configure + zip -9 clientInstallRefresh.zip clientInstallRefresh.sh + rm -f clientInstallRefresh.sh + zip -9 linuxClientInstallRefresh.zip linuxClientInstallRefresh.sh + rm -f linuxClientInstallRefresh.sh + zip -9 MySQLdrop.zip MySQLdrop.txt + rm -f MySQLdrop.txt + chmod 755 MySQLdrop.zip + zip -9 -r OAT_Server_Install.zip OAT_Server_Install/ + rm -rf OAT_Server_Install/ + zip -9 oatSetup.zip oatSetup.txt + rm -f oatSetup.txt + zip -9 -r service.zip service/ + rm -rf service/ + cd ../ + mv ./OAT-Appraiser-Configure ./OAT-Appraiser-Base + tar -czvf OAT-Appraiser-Base.tar.gz ./OAT-Appraiser-Base/ + rm -rf ./OAT-Appraiser-Configure/ + fi + + if test -e ./OAT-Appraiser-Base.tar.gz;then + cp OAT-Appraiser-Base.tar.gz $RPM_BUILD_SOURCE_DIRECTORY + ShowLogOK "./OAT-Appraiser-Base.tar.gz" + else + ShowLogFaild "./OAT-Appraiser-Base.tar.gz" + fi + +# if test -e ./tomcat6;then +# cp ./tomcat6 $RPM_BUILD_SOURCE_DIRECTORY +# ShowLogOK "./tomcat6" +# else +# ShowLogFaild "./tomca6" +# fi +} + + +#NIARL_HIS_Standalone.tar.gz +#CreatNiarlOatStandalone() +#{ +# if test -d NIARL_OAT_Standalone;then +# rm -rf NIARL_OAT_Standalone +# fi +# mkdir NIARL_OAT_Standalone +# +# if test -e $OATSOURCE_DIRECTORY/HisClient/OAT07.jpg;then +# cp $OATSOURCE_DIRECTORY/HisClient/OAT07.jpg NIARL_OAT_Standalone +# else +# ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/OAT07.jpg" +# fi +# +# if test -e ./FilesForLinux/OAT.sh;then +# cp ./FilesForLinux/OAT.sh NIARL_OAT_Standalone +# else +# ShowLogFaild "./FilesForLinux/OAT.sh" +# fi +# if test -e $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar;then +# cp $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar NIARL_OAT_Standalone +# else +# ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar" +# fi +# +# if test -e $OATSOURCE_DIRECTORY/HisClient/log4j.properties;then +# cp $OATSOURCE_DIRECTORY/HisClient/log4j.properties NIARL_OAT_Standalone +# else +# ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/log4j.properties" +# fi +# +## if test -e $OATSOURCE_DIRECTORY/HisClient/OAT.properties;then +## cp $OATSOURCE_DIRECTORY/HisClient/OAT.properties NIARL_OAT_Standalone +## else +## ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/OAT.properties" +## fi +# +# if test -d $OATSOURCE_DIRECTORY/HisClient/lib/;then +# cp -r $OATSOURCE_DIRECTORY/HisClient/lib/ NIARL_OAT_Standalone +# else +# ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/lib/" +# fi +# +# +# tar -zcvf NIARL_OAT_Standalone.tar.gz NIARL_OAT_Standalone +# mv NIARL_OAT_Standalone.tar.gz $RPM_BUILD_SOURCE_DIRECTORY +# rm -rf OAT +# mv NIARL_OAT_Standalone OAT +# tar -zcvf NIARL_OAT_Standalone.tar.gz OAT +# ShowLogOK "NIARL_OAT_Standalone.tar.gz" +# +## if test -e ./OAT-Standalone-for-SLES.spec;then +## cp -r ./OAT-Standalone-for-SLES.spec $RPM_BUILD_SPECS_DIRECTORY +## else +## ShowLogFaild "./OAT-Standalone-for-SLES.spec" +## fi +## +## rpmbuild -bb $RPM_BUILD_SPECS_DIRECTORY/OAT-Standalone.spec +## +## if test -e $RPM_BUILD_DIRECTORY/RPMS/x86_64/$RPM_V;then +## ShowLogOK "$RPM_V" +## else +## ShowLogFaild "$RPM_V" +## fi +#} + + +LinuxOatInstall() +{ + if test -d linuxOatInstall;then + rm -rf linuxOatInstall + fi + mkdir linuxOatInstall + + if test -e ./FilesForLinux/install.sh ;then + cp ./FilesForLinux/install.sh linuxOatInstall + else + ShowLogFaild "./FilesForLinux/install.sh" + fi + + if test -e ./FilesForLinux/general-install.sh;then + cp ./FilesForLinux/general-install.sh linuxOatInstall + else + ShowLogFaild "./FilesForLinux/general-install.sh" + fi + + if test -d ./FilesForLinux/shells;then + cp -ar ./FilesForLinux/shells linuxOatInstall + else + ShowLogFaild "./FilesForLinux/shells" + fi + +# if test -e $RPM_BUILD_RPMS_DIRECTORY/$RPM_V;then +# cp $RPM_BUILD_RPMS_DIRECTORY/$RPM_V linuxOatInstall +# else +# ShowLogFaild "$RPM_BUILD_RPMS_DIRECTORY/$RPM_V" +# fi + + if test -e $OATSOURCE_DIRECTORY/PrivacyCA/provisioner.sh;then + cp $OATSOURCE_DIRECTORY/PrivacyCA/provisioner.sh linuxOatInstall + else + ShowLogFaild "$OATSOURCE_DIRECTORY/PrivacyCA/provisioner.sh" + fi + + + if test -e $OATSOURCE_DIRECTORY/PrivacyCA/TPMModule.properties;then + cp $OATSOURCE_DIRECTORY/PrivacyCA/TPMModule.properties linuxOatInstall + else + ShowLogFaild "$OATSOURCE_DIRECTORY/PrivacyCA/TPMModule.properties" + fi + + + if test -d $OATSOURCE_DIRECTORY/HisClient/lib;then + cp -r $OATSOURCE_DIRECTORY/HisClient/lib linuxOatInstall + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/lib" + fi + + if test -d $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/ClientFiles/lib;then + cp $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/ClientFiles/lib/* linuxOatInstall/lib + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/ClientFiles/lib" + fi + + if test -e linuxOatInstall/lib/PrivacyCA.jar;then + rm -rf linuxOatInstall/lib/PrivacyCA.jar + fi + + if test -e $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar;then + cp $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar linuxOatInstall/lib + else + ShowLogFaild "$OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar" + fi + chmod 755 linuxOatInstall/lib/* + + if test -e $OATSOURCE_DIRECTORY/TPMModule/plain/linux/NIARL_TPM_Module;then + cp $OATSOURCE_DIRECTORY/TPMModule/plain/linux/NIARL_TPM_Module linuxOatInstall + mkdir -p linuxOatInstall/exe + cp linuxOatInstall/NIARL_TPM_Module linuxOatInstall/exe + else + ShowLogFaild "$OATSOURCE_DIRECTORY/TPMModule/plain/linux/NIARL_TPM_Module" + fi + + +# if test -e ./NIARL_OAT_Standalone.tar.gz;then +# cp ./NIARL_OAT_Standalone.tar.gz linuxOatInstall +# else +# ShowLogFaild "./NIARL_OAT_Standalone.tar.gz" +# fi + + if test -e ./ClientInstallForLinux.zip;then + rm -rf ClientInstallForLinux.zip + fi + zip -r ClientInstallForLinux.zip linuxOatInstall + ShowLogOK "ClientInstallForLinux.zip" + rm -rf linuxOatInstall +} + +RePkgInstallOatAppraiserBase() +{ + CurDir=$(pwd) + if test -e $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base.tar.gz;then + cd $RPM_BUILD_SOURCE_DIRECTORY + rm -rf OAT-Appraiser-Base + tar -zxvf OAT-Appraiser-Base.tar.gz + else + ShowLogFaild "$RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base.tar.gz" + fi + + +##################################################################################### + echo "$RPM_BUILD_SOURCE_DIRECTORY" + if test -e $CurDir/FilesForLinux/OAT.sh;then + cp $CurDir/FilesForLinux/OAT.sh $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + else + ShowLogFaild "./FilesForLinux/OAT.sh" + fi + if test -e $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar;then + cp $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar" + fi + + if test -e $OATSOURCE_DIRECTORY/HisClient/log4j.properties;then + cp $OATSOURCE_DIRECTORY/HisClient/log4j.properties $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/log4j.properties" + fi + + + if test -d $OATSOURCE_DIRECTORY/HisClient/lib/;then + cp -r $OATSOURCE_DIRECTORY/HisClient/lib/ $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisClient/lib/" + fi +###################################################################################### + + if test -e $CurDir/FilesForLinux/apache-tomcat-6.0.29.tar.gz;then + cp $CurDir/FilesForLinux/apache-tomcat-6.0.29.tar.gz $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + else + ShowLogFaild "$CurDir/FilesForLinux/apache-tomcat-6.0.29.tar.gz" + fi + + if test -e $CurDir/tomcat6.suse;then + cp $CurDir/tomcat6.suse $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base/tomcat6 + else + ShowLogFaild "$CurDir/tomcat6" + fi + if test -e $CurDir/ClientInstallForLinux.zip;then + cp $CurDir/ClientInstallForLinux.zip $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + else + ShowLogFaild "$CurDir/ClientInstallForLinux.zip" + fi + + cd $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + + if test -e HisPrivacyCAWebServices2.war;then + rm -rf HisPrivacyCAWebServices2.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war;then + cp $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war . + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war" + fi + + mkdir HisPrivacyCAWebServices2 + mv HisPrivacyCAWebServices2.war HisPrivacyCAWebServices2 + cd HisPrivacyCAWebServices2 + unzip HisPrivacyCAWebServices2.war + rm -rf HisPrivacyCAWebServices2.war + + echo "\n\r" >> setup.properties + echo "ecSigningKeySize=$EC_SIGNING_KEY_SIZE" >> setup.properties + echo "ecStorage=NVRAM" >> setup.properties + mkdir -p /etc/oat-appraiser/ + zip -9 setupProperties.zip setup.properties + mv setupProperties.zip ../ + + if test -d CaCerts;then + rm -rf CaCerts + fi + mkdir CaCerts + + zip -9 -r HisPrivacyCAWebServices2.war . + if test -e HisPrivacyCAWebServices2.war;then + mv HisPrivacyCAWebServices2.war ../ + cd ../ + rm -rf HisPrivacyCAWebServices2 + fi + +###HIS_Server_Install.zip#### + cd $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + if test -e OAT_Server_Install.zip;then + unzip OAT_Server_Install.zip + rm -rf OAT_Server_Install.zip + else + ShowLogFaild "OAT_Server_Install.zip" + fi + + cd OAT_Server_Install + + if test -d HisWebServices;then + rm -rf HisWebServices + fi + mkdir HisWebServices + + if test -d $OATSOURCE_DIRECTORY/HisWebServices/WEB-INF;then + cp -r $OATSOURCE_DIRECTORY/HisWebServices/WEB-INF ./HisWebServices/ + else + ShowLogFaild "$OATSOURCE_DIRECTORY/HisWebServices/WEB-INF" + fi + +# OpenAttestation *.war --> HIS_Server_Install.zip +#if test -e $CurDir/$OATSOURCE_DIRECTORY/OpenAttestationAdminConsole/OpenAttestationAdminConsole.war -a -e $CurDir/$OATSOURCE_DIRECTORY/OpenAttestationManifestWebServices/OpenAttestationManifestWebServices.war -e $CurDir/$OATSOURCE_DIRECTORY/OpenAttestationWebServices/OpenAttestationWebServices.war;then + cp $OATSOURCE_DIRECTORY/WLMService/WLMService.war . + cp $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war . +#else +# ShowLogFaild "$OATSOURCE_DIRECTORY/OpenAttestationAdminConsole/OpenAttestationAdminConsole.war ^ $OATSOURCE_DIRECTORY/OpenAttestationManifestWebServices/OpenAttestationManifestWebServices.war ^ $OATSOURCE_DIRECTORY/OpenAttestationWebServices/OpenAttestationWebServices.war " +#fi + + +if test -e $CurDir/FilesForLinux/init.sql;then + cp $CurDir/FilesForLinux/init.sql . +else + ShowLogFaild "$CurDir/FilesForLinux/init.sql" +fi + + cd $RPM_BUILD_SOURCE_DIRECTORY/OAT-Appraiser-Base + + zip -9 -r OAT_Server_Install.zip OAT_Server_Install + +rm -rf OAT_Server_Install +###### +#OAT.zip +if test -d $OATSOURCE_DIRECTORY/Portal;then + cp -r $OATSOURCE_DIRECTORY/Portal OAT +else + ShowLogFaild "$OATSOURCE_DIRECTORY/Portal" +fi + +if test -e OAT.zip;then + rm -rf OAT.zip +fi + +zip -9 -r OAT.zip OAT +rm -rf OAT +############# + + cd $RPM_BUILD_SOURCE_DIRECTORY + rm -rf OAT-Appraiser-Base.tar.gz + mv OAT-Appraiser-Configure OAT-Appraiser-Base + tar -zcvf OAT-Appraiser-Base.tar.gz OAT-Appraiser-Base + rm -rf OAT-Appraiser-Base + cd $CurDir + ShowLogOK "repackage OAT-Appraiser-Base.tar.gz" +} + +RPMbuild() +{ + if test -e ./OAT-Appraiser-Base-for-SLES.spec;then + cp OAT-Appraiser-Base-for-SLES.spec $RPM_BUILD_SPECS_DIRECTORY + else + ShowLogFaild "./OAT-Appraiser-Base-for-SLES.spec" + fi + + if test -d /OAT-Appraiser-Configure;then + rm -rf /OAT-Appraiser-Configure + fi + + cd $RPM_BUILD_SPECS_DIRECTORY + rpmbuild -bb OAT-Appraiser-Base-for-SLES.spec + +} + + +Build_xml() +{ + CurDir=$(pwd) + if test -e $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar;then + rm -rf $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar + fi + + if test -e $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar;then + rm -rf $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar + fi + + if test -e $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar;then + rm -rf $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar + fi + + if test -e $OATSOURCE_DIRECTORY/HisWebServices/clientlib/HisWebServices-client.jar;then + rm -rf $OATSOURCE_DIRECTORY/HisWebServices/clientlib/HisWebServices-client.jar + fi + + if test -e $OATSOURCE_DIRECTORY/HisWebServices/HisWebServices.war;then + rm -rf $OATSOURCE_DIRECTORY/HisWebServices/HisWebServices.war + fi + + if test -e $OATSOURCE_DIRECTORY/WLMService/WLMService.war;then + rm -rf $OATSOURCE_DIRECTORY/WLMService/WLMService.war + fi + + if test -e $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war;then + rm -rf $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war;then + rm -rf $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/clientlib/HisPrivacyCAWebServices2-client.jar;then + rm -rf $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/clientlib/HisPrivacyCAWebServices2-client.jar + fi + + if test -e $OATSOURCE_DIRECTORY/build.sh;then + cd $OATSOURCE_DIRECTORY + sh build.sh $TOMCAT_DIRECTORY + else + ShowLogFaild "$OATSOURCE_DIRECTORY/build.sh" + fi + + if test -d $OATSOURCE_DIRECTORY/WLMService;then + cd $OATSOURCE_DIRECTORY/WLMService + ant -file build.xml + else + ShowLogFaild "$OATSOURCE_DIRECTORY/WLMService" + fi + + if test -d $OATSOURCE_DIRECTORY/AttestationService;then + cd $OATSOURCE_DIRECTORY/AttestationService + cp -rf $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar ./WebContent/WEB-INF/lib/ + ant -file build.xml + else + ShowLogFaild "$OATSOURCE_DIRECTORY/AttestationService" + fi + + if test -e $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar;then + ShowLogOK $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisAppraiser/HisAppraiser.jar + fi + + if test -e $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar;then + ShowLogOK $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar + else + ShowLogFaild $OATSOURCE_DIRECTORY/PrivacyCA/PrivacyCA.jar + fi + + if test -e $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar;then + ShowLogOK $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisClient/jar/OAT_Standalone.jar + fi + + if test -e $OATSOURCE_DIRECTORY/HisWebServices/HisWebServices.war;then + ShowLogOK $OATSOURCE_DIRECTORY/HisWebServices/HisWebServices.war + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisWebServices/HisWebServices.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisWebServices/clientlib/HisWebServices-client.jar;then + ShowLogOK $OATSOURCE_DIRECTORY/HisWebServices/clientlib/HisWebServices-client.jar + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisWebServices/clientlib/HisWebServices-client.jar + fi + + if test -e $OATSOURCE_DIRECTORY/WLMService/WLMService.war;then + ShowLogOK $OATSOURCE_DIRECTORY/WLMService/WLMService.war + else + ShowLogFaild $OATSOURCE_DIRECTORY/WLMService/WLMService.war + fi + + if test -e $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war;then + ShowLogOK $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war + else + ShowLogFaild $OATSOURCE_DIRECTORY/AttestationService/AttestationService.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war;then + ShowLogOK $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war + fi + + if test -e $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/clientlib/HisPrivacyCAWebServices2-client.jar;then + ShowLogOK $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/clientlib/HisPrivacyCAWebServices2-client.jar + else + ShowLogFaild $OATSOURCE_DIRECTORY/HisPrivacyCAWebServices2/clientlib/HisPrivacyCAWebServices2-client.jar + fi + + + cd $CurDir +} + +#main +SourceFileOP=-s +#TomCatOP=-t +if [ $# -lt 2 ];then +ShowLogFaild "Parameter ERROR! for example:sh rpm.sh -s /usr/local/src/OAT/Source " +fi + +if [ $1 = $SourceFileOP ];then + OATSOURCE_DIRECTORY=$2 +fi + +if [ -d $OATSOURCE_DIRECTORY ]; then + ShowLogOK "Source file" +else + ShowLogFaild "$OATSOURCE_DIRECTORY No such directory" +fi + +#if [ $3 = $TomCatOP ];then +# TOMCAT_DIRECTORY=$4 +#fi +# +#if [ -d $TOMCAT_DIRECTORY ]; then +# ShowLogOK "tomcat" +#else +# ShowLogFaild "$TOMCAT_DIRECTORY No such directory" +#fi + +if [ $# -gt 3 -a $3 = "-ks" ];then + EC_SIGNING_KEY_SIZE=$4 +fi + + + +Build_xml +CreateRPMdirectory +InstallOatAppraiserBase +####CreatNiarlOatStandalone +LinuxOatInstall +RePkgInstallOatAppraiserBase +RPMbuild +if [ $SUCCESS_STATUS -eq 1 ];then + ShowLogOK "RPM build" +else + ShowLogFaild "RPM build" +fi diff --git a/OpenAttestation/Installer/tomcat6.suse b/OpenAttestation/Installer/tomcat6.suse new file mode 100644 index 0000000..df40012 --- /dev/null +++ b/OpenAttestation/Installer/tomcat6.suse @@ -0,0 +1,119 @@ +#!/bin/sh +# +# "$Id: catalina ,v 1.0 2010/08/10 Chris_g Exp $" +# +# Startup/shutdown script for tomcat(Catalina) Application server. +# +# Linux chkconfig stuff: +# +# chkconfig: 2345 56 10 +# description: Startup/shutdown script for the tomcat application server. +###### + +# Source function library. +###### + + +# Define where the catalina.sh script is located. +###### +CATALINA_BIN="/usr/lib/apache-tomcat-6.0.29/bin/startup.sh"; +#CATALINA_BIN='/usr/lib/apache-tomcat-6.0.29/bin/catalina.sh 1> /dev/null'; + +# Find the catalina process using ps / awk. +# The match function will return 0 when no match is found with the string "java". +# Position $9 should contain the path to the Java executable used by catalina. +###### +PROC=`ps -efc | grep apache.catalina | awk 'BEGIN { FS=" "}; { if( match($9, "java") != 0 ) print $9;}'` +TOMCAT_PIDFILE=/var/run/tomcat6.init.pid +# Replace a potential empty string with a fake process so the RH daemon functions are able to parse +# it properly +###### +if [ $PROC ];then + TOMCAT_PID=`ps -efc | grep apache.catalina | awk 'BEGIN { FS=" "}; { if( match($9, "java") != 0 ) print $2;}'` +else + TOMCAT_PID=0 +fi + +if [[ "$PROC" == '' ]]; then + PROC='Tomcat_JVM'; +fi + +# Define the application name that is listed in the daemonize step. +PROG='Tomcat JVM'; + +# LOCKFILE +LOCK='/var/lock/subsys/tomcat'; + +start () { + echo -n $"Starting $PROG: " + if [ $TOMCAT_PID -ne 0 ];then + TOMCAT_PID=`cat $TOMCAT_PIDFILE` + echo -ne "\033[31m \t [ failed ] \033[0m" + echo + echo -n "The process $TOMCAT_PID is running..." + else + $CATALINA_BIN 1> /dev/null + RETVAL=$? + if [ $RETVAL -eq 0 ];then + echo -ne "\033[32m \t [ successed ] \033[0m" + ps -efc | grep apache.catalina | awk 'BEGIN { FS=" "}; { if( match($9, "java") != 0 ) print $2;}' > $TOMCAT_PIDFILE + fi + fi + echo + [ $RETVAL=0 ] && touch $LOCK + return $RETVAL +} + +stop () { + # stop daemon + echo -n "Stopping $PROG: " + killproc -p $TOMCAT_PIDFILE -TERM $PROC 2> /dev/null + if [ $? -eq 0 ];then + echo -ne "\033[32m \t [ successed ] \033[0m" + else + echo -ne "\033[31m \t [ failed ] \033[0m" + fi + RETVAL=$? + echo + [ $RETVAL = 0 ] && rm -f $LOCK +} + +restart() { + stop + start +} + +status(){ + echo -n "Service tomcat6 status:" + checkproc -p $TOMCAT_PIDFILE $PROC + if [ $? -eq 0 ];then + TOMCAT_PID=`cat $TOMCAT_PIDFILE` + echo -ne "\033[32m [ actived ] \033[0m \n" + echo -n "The process $TOMCAT_PID is running..." + else + echo -n "[ inactived ]" + fi + RETVAL=$? + echo +} +case $1 in + start) + start + ;; + stop) + stop + ;; + restart) + restart + ;; + status) + status + ;; + *) + + echo $"Usage: $prog {start|stop|restart|status}" + exit 3 +esac + +exit $RETVAL + diff --git a/OpenAttestation/JAR_SOURCE/Core_Integrity_Manifest_v1_0_1.xsd b/OpenAttestation/JAR_SOURCE/Core_Integrity_Manifest_v1_0_1.xsd new file mode 100644 index 0000000..38bdc35 --- /dev/null +++ b/OpenAttestation/JAR_SOURCE/Core_Integrity_Manifest_v1_0_1.xsd @@ -0,0 +1,131 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/JAR_SOURCE/FastInfoset.jar b/OpenAttestation/JAR_SOURCE/FastInfoset.jar new file mode 100644 index 0000000..c34ccce Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/FastInfoset.jar differ diff --git a/OpenAttestation/JAR_SOURCE/Integrity_Report_Manifest_v1_0.xsd b/OpenAttestation/JAR_SOURCE/Integrity_Report_Manifest_v1_0.xsd new file mode 100644 index 0000000..a49d75e --- /dev/null +++ b/OpenAttestation/JAR_SOURCE/Integrity_Report_Manifest_v1_0.xsd @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/OpenAttestation/JAR_SOURCE/activation.jar b/OpenAttestation/JAR_SOURCE/activation.jar new file mode 100644 index 0000000..3e8808b Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/activation.jar differ diff --git a/OpenAttestation/JAR_SOURCE/ant-antlr-1.6.5.jar b/OpenAttestation/JAR_SOURCE/ant-antlr-1.6.5.jar new file mode 100644 index 0000000..167ac03 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/ant-antlr-1.6.5.jar differ diff --git a/OpenAttestation/JAR_SOURCE/apache-tomcat-6.0.29.tar.gz b/OpenAttestation/JAR_SOURCE/apache-tomcat-6.0.29.tar.gz new file mode 100644 index 0000000..574b72a Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/apache-tomcat-6.0.29.tar.gz differ diff --git a/OpenAttestation/JAR_SOURCE/asm-3.1.jar b/OpenAttestation/JAR_SOURCE/asm-3.1.jar new file mode 100644 index 0000000..8217cae Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/asm-3.1.jar differ diff --git a/OpenAttestation/JAR_SOURCE/asm.jar b/OpenAttestation/JAR_SOURCE/asm.jar new file mode 100644 index 0000000..a50aa61 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/asm.jar differ diff --git a/OpenAttestation/JAR_SOURCE/axis.jar b/OpenAttestation/JAR_SOURCE/axis.jar new file mode 100644 index 0000000..df936e2 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/axis.jar differ diff --git a/OpenAttestation/JAR_SOURCE/bcprov-jdk15-129.jar b/OpenAttestation/JAR_SOURCE/bcprov-jdk15-129.jar new file mode 100644 index 0000000..f7bf116 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/bcprov-jdk15-129.jar differ diff --git a/OpenAttestation/JAR_SOURCE/bcprov-jdk15-141.jar b/OpenAttestation/JAR_SOURCE/bcprov-jdk15-141.jar new file mode 100644 index 0000000..f7bf116 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/bcprov-jdk15-141.jar differ diff --git a/OpenAttestation/JAR_SOURCE/c3p0-0.9.0.jar b/OpenAttestation/JAR_SOURCE/c3p0-0.9.0.jar new file mode 100644 index 0000000..a99c36d Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/c3p0-0.9.0.jar differ diff --git a/OpenAttestation/JAR_SOURCE/cglib-2.1.3.jar b/OpenAttestation/JAR_SOURCE/cglib-2.1.3.jar new file mode 100644 index 0000000..ddfbdb0 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/cglib-2.1.3.jar differ diff --git a/OpenAttestation/JAR_SOURCE/cglib-2.2.jar b/OpenAttestation/JAR_SOURCE/cglib-2.2.jar new file mode 100644 index 0000000..084ef6e Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/cglib-2.2.jar differ diff --git a/OpenAttestation/JAR_SOURCE/commons-beanutils.jar b/OpenAttestation/JAR_SOURCE/commons-beanutils.jar new file mode 100644 index 0000000..16dcf6f Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/commons-beanutils.jar differ diff --git a/OpenAttestation/JAR_SOURCE/commons-cli-1.0.jar b/OpenAttestation/JAR_SOURCE/commons-cli-1.0.jar new file mode 100644 index 0000000..22a004e Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/commons-cli-1.0.jar differ diff --git a/OpenAttestation/JAR_SOURCE/commons-codec-1.3.jar b/OpenAttestation/JAR_SOURCE/commons-codec-1.3.jar new file mode 100644 index 0000000..957b675 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/commons-codec-1.3.jar differ diff --git a/OpenAttestation/JAR_SOURCE/commons-codec-1.4.jar b/OpenAttestation/JAR_SOURCE/commons-codec-1.4.jar new file mode 100644 index 0000000..458d432 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/commons-codec-1.4.jar differ diff --git a/OpenAttestation/JAR_SOURCE/commons-collections-2.1.1.jar b/OpenAttestation/JAR_SOURCE/commons-collections-2.1.1.jar new file mode 100644 index 0000000..3272f2b Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/commons-collections-2.1.1.jar differ diff --git a/OpenAttestation/JAR_SOURCE/commons-collections.jar b/OpenAttestation/JAR_SOURCE/commons-collections.jar new file mode 100644 index 0000000..3272f2b Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/commons-collections.jar differ diff --git a/OpenAttestation/JAR_SOURCE/commons-digester.jar b/OpenAttestation/JAR_SOURCE/commons-digester.jar new file mode 100644 index 0000000..9765493 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/commons-digester.jar differ diff --git a/OpenAttestation/JAR_SOURCE/commons-discovery-0.2.jar b/OpenAttestation/JAR_SOURCE/commons-discovery-0.2.jar new file mode 100644 index 0000000..b885548 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/commons-discovery-0.2.jar differ diff --git a/OpenAttestation/JAR_SOURCE/commons-httpclient-3.0.jar b/OpenAttestation/JAR_SOURCE/commons-httpclient-3.0.jar new file mode 100644 index 0000000..54a9300 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/commons-httpclient-3.0.jar differ diff --git a/OpenAttestation/JAR_SOURCE/commons-logging-1.0.4.jar b/OpenAttestation/JAR_SOURCE/commons-logging-1.0.4.jar new file mode 100644 index 0000000..b73a80f Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/commons-logging-1.0.4.jar differ diff --git a/OpenAttestation/JAR_SOURCE/commons-logging-1.1.1.jar b/OpenAttestation/JAR_SOURCE/commons-logging-1.1.1.jar new file mode 100644 index 0000000..1deef14 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/commons-logging-1.1.1.jar differ diff --git a/OpenAttestation/JAR_SOURCE/commons-logging.jar b/OpenAttestation/JAR_SOURCE/commons-logging.jar new file mode 100644 index 0000000..b73a80f Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/commons-logging.jar differ diff --git a/OpenAttestation/JAR_SOURCE/dom4j-1.6.1.jar b/OpenAttestation/JAR_SOURCE/dom4j-1.6.1.jar new file mode 100644 index 0000000..c8c4dbb Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/dom4j-1.6.1.jar differ diff --git a/OpenAttestation/JAR_SOURCE/hibernate3.jar b/OpenAttestation/JAR_SOURCE/hibernate3.jar new file mode 100644 index 0000000..43a9938 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/hibernate3.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jaas.jar b/OpenAttestation/JAR_SOURCE/jaas.jar new file mode 100644 index 0000000..967457c Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jaas.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jackson-core-asl-1.8.3.jar b/OpenAttestation/JAR_SOURCE/jackson-core-asl-1.8.3.jar new file mode 100644 index 0000000..e4159ec Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jackson-core-asl-1.8.3.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jackson-jaxrs-1.8.3.jar b/OpenAttestation/JAR_SOURCE/jackson-jaxrs-1.8.3.jar new file mode 100644 index 0000000..1065a63 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jackson-jaxrs-1.8.3.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jackson-mapper-asl-1.8.3.jar b/OpenAttestation/JAR_SOURCE/jackson-mapper-asl-1.8.3.jar new file mode 100644 index 0000000..9360ff6 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jackson-mapper-asl-1.8.3.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jackson-xc-1.8.3.jar b/OpenAttestation/JAR_SOURCE/jackson-xc-1.8.3.jar new file mode 100644 index 0000000..9e168ec Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jackson-xc-1.8.3.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jax-qname.jar b/OpenAttestation/JAR_SOURCE/jax-qname.jar new file mode 100644 index 0000000..ff6ac6e Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jax-qname.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jaxb-api.jar b/OpenAttestation/JAR_SOURCE/jaxb-api.jar new file mode 100644 index 0000000..2b5dc7e Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jaxb-api.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jaxb-impl-2.1.12.jar b/OpenAttestation/JAR_SOURCE/jaxb-impl-2.1.12.jar new file mode 100644 index 0000000..392e682 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jaxb-impl-2.1.12.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jaxb-impl.jar b/OpenAttestation/JAR_SOURCE/jaxb-impl.jar new file mode 100644 index 0000000..392e682 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jaxb-impl.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jaxb-libs.jar b/OpenAttestation/JAR_SOURCE/jaxb-libs.jar new file mode 100644 index 0000000..cc6554f Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jaxb-libs.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jaxb-xjc.jar b/OpenAttestation/JAR_SOURCE/jaxb-xjc.jar new file mode 100644 index 0000000..9fafae8 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jaxb-xjc.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jaxrpc.jar b/OpenAttestation/JAR_SOURCE/jaxrpc.jar new file mode 100644 index 0000000..a2c13d9 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jaxrpc.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jaxws-api.jar b/OpenAttestation/JAR_SOURCE/jaxws-api.jar new file mode 100644 index 0000000..e403445 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jaxws-api.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jaxws-rt.jar b/OpenAttestation/JAR_SOURCE/jaxws-rt.jar new file mode 100644 index 0000000..973e787 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jaxws-rt.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jaxws-tools.jar b/OpenAttestation/JAR_SOURCE/jaxws-tools.jar new file mode 100644 index 0000000..b28afcd Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jaxws-tools.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jdbc2_0-stdext.jar b/OpenAttestation/JAR_SOURCE/jdbc2_0-stdext.jar new file mode 100644 index 0000000..ddafa13 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jdbc2_0-stdext.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jersey-bundle-1.9.1.jar b/OpenAttestation/JAR_SOURCE/jersey-bundle-1.9.1.jar new file mode 100644 index 0000000..7f74bfb Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jersey-bundle-1.9.1.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jersey-client-1.9.1.jar b/OpenAttestation/JAR_SOURCE/jersey-client-1.9.1.jar new file mode 100644 index 0000000..3400320 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jersey-client-1.9.1.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jersey-core-1.9.1.jar b/OpenAttestation/JAR_SOURCE/jersey-core-1.9.1.jar new file mode 100644 index 0000000..12e9279 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jersey-core-1.9.1.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jersey-json-1.9.1.jar b/OpenAttestation/JAR_SOURCE/jersey-json-1.9.1.jar new file mode 100644 index 0000000..b93c579 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jersey-json-1.9.1.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jersey-server-1.9.1.jar b/OpenAttestation/JAR_SOURCE/jersey-server-1.9.1.jar new file mode 100644 index 0000000..883991b Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jersey-server-1.9.1.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jettison-1.1.jar b/OpenAttestation/JAR_SOURCE/jettison-1.1.jar new file mode 100644 index 0000000..7e4f4a6 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jettison-1.1.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jsp-api.jar b/OpenAttestation/JAR_SOURCE/jsp-api.jar new file mode 100644 index 0000000..3d0c81f Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jsp-api.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jsr173_api.jar b/OpenAttestation/JAR_SOURCE/jsr173_api.jar new file mode 100644 index 0000000..987db0f Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jsr173_api.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jsr181-api.jar b/OpenAttestation/JAR_SOURCE/jsr181-api.jar new file mode 100644 index 0000000..91538a7 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jsr181-api.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jsr250-api.jar b/OpenAttestation/JAR_SOURCE/jsr250-api.jar new file mode 100644 index 0000000..c1f29bf Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jsr250-api.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jsr311-api-1.1.1.jar b/OpenAttestation/JAR_SOURCE/jsr311-api-1.1.1.jar new file mode 100644 index 0000000..ec8bc81 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jsr311-api-1.1.1.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jta-spec1_0_1.jar b/OpenAttestation/JAR_SOURCE/jta-spec1_0_1.jar new file mode 100644 index 0000000..705e8c8 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jta-spec1_0_1.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jta.jar b/OpenAttestation/JAR_SOURCE/jta.jar new file mode 100644 index 0000000..40a2cbd Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jta.jar differ diff --git a/OpenAttestation/JAR_SOURCE/jtds-1.2.jar b/OpenAttestation/JAR_SOURCE/jtds-1.2.jar new file mode 100644 index 0000000..ba783d8 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/jtds-1.2.jar differ diff --git a/OpenAttestation/JAR_SOURCE/log4j-1.2.14.jar b/OpenAttestation/JAR_SOURCE/log4j-1.2.14.jar new file mode 100644 index 0000000..b3aec9e Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/log4j-1.2.14.jar differ diff --git a/OpenAttestation/JAR_SOURCE/log4j-1.2.8.jar b/OpenAttestation/JAR_SOURCE/log4j-1.2.8.jar new file mode 100644 index 0000000..493a3cc Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/log4j-1.2.8.jar differ diff --git a/OpenAttestation/JAR_SOURCE/mail.jar b/OpenAttestation/JAR_SOURCE/mail.jar new file mode 100644 index 0000000..aa357d4 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/mail.jar differ diff --git a/OpenAttestation/JAR_SOURCE/mimepull.jar b/OpenAttestation/JAR_SOURCE/mimepull.jar new file mode 100644 index 0000000..d33a746 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/mimepull.jar differ diff --git a/OpenAttestation/JAR_SOURCE/mysql-connector-java-5.0.7-bin.jar b/OpenAttestation/JAR_SOURCE/mysql-connector-java-5.0.7-bin.jar new file mode 100644 index 0000000..412138a Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/mysql-connector-java-5.0.7-bin.jar differ diff --git a/OpenAttestation/JAR_SOURCE/org.springframework.context.support-3.0.3.RELEASE.jar b/OpenAttestation/JAR_SOURCE/org.springframework.context.support-3.0.3.RELEASE.jar new file mode 100644 index 0000000..bcc0e6a Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/org.springframework.context.support-3.0.3.RELEASE.jar differ diff --git a/OpenAttestation/JAR_SOURCE/relaxngDatatype.jar b/OpenAttestation/JAR_SOURCE/relaxngDatatype.jar new file mode 100644 index 0000000..b0e8e2f Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/relaxngDatatype.jar differ diff --git a/OpenAttestation/JAR_SOURCE/resolver.jar b/OpenAttestation/JAR_SOURCE/resolver.jar new file mode 100644 index 0000000..0f97dc7 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/resolver.jar differ diff --git a/OpenAttestation/JAR_SOURCE/saaj-api.jar b/OpenAttestation/JAR_SOURCE/saaj-api.jar new file mode 100644 index 0000000..a75a492 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/saaj-api.jar differ diff --git a/OpenAttestation/JAR_SOURCE/saaj-impl.jar b/OpenAttestation/JAR_SOURCE/saaj-impl.jar new file mode 100644 index 0000000..e1fb59b Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/saaj-impl.jar differ diff --git a/OpenAttestation/JAR_SOURCE/saaj.jar b/OpenAttestation/JAR_SOURCE/saaj.jar new file mode 100644 index 0000000..4ea696e Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/saaj.jar differ diff --git a/OpenAttestation/JAR_SOURCE/servlet-api.jar b/OpenAttestation/JAR_SOURCE/servlet-api.jar new file mode 100644 index 0000000..dd326d3 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/servlet-api.jar differ diff --git a/OpenAttestation/JAR_SOURCE/servlet.jar b/OpenAttestation/JAR_SOURCE/servlet.jar new file mode 100644 index 0000000..fc0e167 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/servlet.jar differ diff --git a/OpenAttestation/JAR_SOURCE/stax-ex.jar b/OpenAttestation/JAR_SOURCE/stax-ex.jar new file mode 100644 index 0000000..0059f4b Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/stax-ex.jar differ diff --git a/OpenAttestation/JAR_SOURCE/streambuffer.jar b/OpenAttestation/JAR_SOURCE/streambuffer.jar new file mode 100644 index 0000000..c9da9ad Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/streambuffer.jar differ diff --git a/OpenAttestation/JAR_SOURCE/uuid-3.2.jar b/OpenAttestation/JAR_SOURCE/uuid-3.2.jar new file mode 100644 index 0000000..b205a24 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/uuid-3.2.jar differ diff --git a/OpenAttestation/JAR_SOURCE/woodstox.jar b/OpenAttestation/JAR_SOURCE/woodstox.jar new file mode 100644 index 0000000..b874538 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/woodstox.jar differ diff --git a/OpenAttestation/JAR_SOURCE/wsdl4j-1.5.1.jar b/OpenAttestation/JAR_SOURCE/wsdl4j-1.5.1.jar new file mode 100644 index 0000000..c6254ee Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/wsdl4j-1.5.1.jar differ diff --git a/OpenAttestation/JAR_SOURCE/xsdlib.jar b/OpenAttestation/JAR_SOURCE/xsdlib.jar new file mode 100644 index 0000000..abd4704 Binary files /dev/null and b/OpenAttestation/JAR_SOURCE/xsdlib.jar differ diff --git a/OpenAttestation/README b/OpenAttestation/README new file mode 100644 index 0000000..648cc5d --- /dev/null +++ b/OpenAttestation/README @@ -0,0 +1,7 @@ + OpenAttestation project is to provide SDK, Software Development Kit, to add cloud management tools with capability of establishing hosts integrity information by remotely retrieving and verifying Hosts' integrity with TPM quote. + + The SDK is expected to be integrated, and enhanced with security features, into 3rd party cloud management software, and distributed by ISV to cloud providers + + The integrated software is hosted and operated by cloud service providers + + For further details, please read docucuments in ~/docs diff --git a/OpenAttestation/Source/AttestationService/WebContent/META-INF/MANIFEST.MF b/OpenAttestation/Source/AttestationService/WebContent/META-INF/MANIFEST.MF new file mode 100644 index 0000000..254272e --- /dev/null +++ b/OpenAttestation/Source/AttestationService/WebContent/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/OpenAttestation/Source/AttestationService/WebContent/WEB-INF/web.xml b/OpenAttestation/Source/AttestationService/WebContent/WEB-INF/web.xml new file mode 100644 index 0000000..fee68a1 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/WebContent/WEB-INF/web.xml @@ -0,0 +1,23 @@ + + + AttestationService + + DB Connection + jdbc/oat + com.mchange.v2.c3p0.ComboPooledDataSource + Container + + + jersey Web Application + com.sun.jersey.spi.container.servlet.ServletContainer + + com.sun.jersey.config.property.packages + com.intel.openAttestation.AttestationService.resource + + 1 + + + jersey Web Application + /* + + diff --git a/OpenAttestation/Source/AttestationService/build.xml b/OpenAttestation/Source/AttestationService/build.xml new file mode 100644 index 0000000..de3ae1a --- /dev/null +++ b/OpenAttestation/Source/AttestationService/build.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/AttestationService/src/OpenAttestationWebServices.properties b/OpenAttestation/Source/AttestationService/src/OpenAttestationWebServices.properties new file mode 100644 index 0000000..73f1389 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/OpenAttestationWebServices.properties @@ -0,0 +1,4 @@ +default_attest_timeout=50000 +check_attest_interval=1000 +portal_address= +default_expiration_time=7 diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/AnalysisDetails.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/AnalysisDetails.java new file mode 100644 index 0000000..9e5b1f0 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/AnalysisDetails.java @@ -0,0 +1,61 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Copyright (C) 2013 Politecnico di Torino, Italy + TORSEC group -- http://security.polito.it + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other ma + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prio + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +*/ +package com.intel.openAttestation.AttestationService.bean; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class AnalysisDetails { + private String name; + + private String result; + + private String status; + + private String output; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getResult() { + return result; + } + + public void setResult(String result) { + this.result = result; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + public String getOutput() { + return output; + } + + public void setOutput(String output) { + this.output = output; + } +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/AsyncBean.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/AsyncBean.java new file mode 100644 index 0000000..5c7bace --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/AsyncBean.java @@ -0,0 +1,42 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Copyright (C) 2014 Politecnico di Torino, Italy + TORSEC group -- http://security.polito.it + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other ma + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prio + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES +*/ +package com.intel.openAttestation.AttestationService.bean; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class AsyncBean { + + private String requestId; + + private String lastResult; + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getLastResult() { + return lastResult; + } + + public void setLastResult(String lastResult) { + this.lastResult = lastResult; + } +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/AttestationResponseFault.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/AttestationResponseFault.java new file mode 100644 index 0000000..0c891dd --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/AttestationResponseFault.java @@ -0,0 +1,102 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.AttestationService.bean; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class AttestationResponseFault { + int code; + String name; + String message; + String detail; + + public AttestationResponseFault(){} + + public AttestationResponseFault (int code){ + this.code= code; + switch (code){ + case 400: + this.name = FaultName.FAULT_BAD_REQUEST; + break; + case 500: + this.name = FaultName.FAULT_ATTEST_ERROR; + break; + case 401: + this.name = FaultName.FAULT_UNAUTH; + break; + case 404: + this.name = FaultName.FAULT_ITEM_NOT_FOUND; + break; + default: + this.name = "UnknownFault"; + } + } + + public AttestationResponseFault(String name){ + this.name = name; + if (name.equals(FaultName.FAULT_UNAUTH)) + this.code = FaultCode.FAULT_401; + else if (name.equals(FaultName.FAULT_BAD_REQUEST)) + this.code = FaultCode.FAULT_400; + else if (name.equals(FaultName.FAULT_ATTEST_ERROR)) + this.code = FaultCode.FAULT_500; + else if (name.equals(FaultName.FAULT_ITEM_NOT_FOUND)) + this.code = FaultCode.FAULT_404; + + else + this.code = 0; + } + + public int getCode() { + return code; + } + public void setCode(int code) { + this.code = code; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + public String getDetail() { + return detail; + } + public void setDetail(String detail) { + this.detail = detail; + } + + public static class FaultCode{ + public static int FAULT_400 = 400; + public static int FAULT_401 = 401; + public static int FAULT_404 = 404; + public static int FAULT_500 = 500; + } + public static class FaultName{ + public static String FAULT_ATTEST_ERROR = "AttestationServersFault"; + public static String FAULT_UNAUTH = "Unauthorized"; + public static String FAULT_BAD_REQUEST = "BadRequest"; + public static String FAULT_ITEM_NOT_FOUND = "ItemNotFound"; + } +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/Host.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/Host.java new file mode 100644 index 0000000..b406a2e --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/Host.java @@ -0,0 +1,95 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.AttestationService.bean; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import javax.xml.bind.annotation.XmlRootElement; + +import com.intel.openAttestation.AttestationService.bean.PCRValue; +import com.intel.openAttestation.AttestationService.bean.AnalysisDetails; + +@XmlRootElement +public class Host { + + private String host_name; + + private String trust_lvl; + + private List pcr_values = new ArrayList(); + + private Date vtime; + + private Boolean report_is_valid; + + private String url; + + private List analysis_details = new ArrayList(); + + public String getTrust_lvl() { + return trust_lvl; + } + + public void setTrust_lvl(String trust_lvl) { + this.trust_lvl = trust_lvl; + } + + public List getPcr_values() { + return pcr_values; + } + + public void setPcr_values(List pcr_values) { + this.pcr_values = pcr_values; + } + + public Date getVtime() { + return vtime; + } + + public void setVtime(Date vtime) { + this.vtime = vtime; + } + + public String getHost_name() { + return host_name; + } + + public void setHost_name(String host_name) { + this.host_name = host_name; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public Boolean getReport_is_valid() { + return report_is_valid; + } + + public void setReport_is_valid(Boolean report_is_valid) { + this.report_is_valid = report_is_valid; + } + + public List getAnalysis_details() { + return analysis_details; + } + + public void setAnalysis_details(List analysis_details) { + this.analysis_details = analysis_details; + } +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/HostBean.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/HostBean.java new file mode 100644 index 0000000..9acde83 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/HostBean.java @@ -0,0 +1,168 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.AttestationService.bean; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class HostBean { + + private Long ID; + private String HostName; + private String IPAddress; + private String Port; + private String Email; + private String AddOn_Connection_String; + private String Description; + private String BIOSName; + private String BIOSVersion; + private String BIOSOem; + private String VMMName; + private String VMMVersion; + private String VMMOSName; + private String VMMOSVersion; + private String Location; + private String pcrIMLMask; + + + public Long getID() { + return ID; + } + + @XmlElement(name = "ID") + public void setID(Long iD) { + ID = iD; + } + + public String getPort() { + return Port; + } + + @XmlElement(name = "Port") + public void setPort(String port) { + Port = port; + } + public String getHostName() { + return HostName; + } + + @XmlElement(name = "HostName") + public void setHostName(String hostName) { + HostName = hostName; + } + + public String getIPAddress() { + return IPAddress; + } + + @XmlElement(name = "IPAddress") + public void setIPAddress(String iPAddress) { + IPAddress = iPAddress; + } + + public String getAddOn_Connection_String() { + return AddOn_Connection_String; + } + + @XmlElement(name = "AddOn_Connection_String") + public void setAddOn_Connection_String(String addOn_Connection_String) { + AddOn_Connection_String = addOn_Connection_String; + } + + public String getEmail() { + return Email; + } + + @XmlElement(name = "Email") + public void setEmail(String email) { + Email = email; + } + + public String getDescription() { + return Description; + } + + @XmlElement(name = "Description") + public void setDescription(String description) { + Description = description; + } + + public String getBIOSName() { + return BIOSName; + } + + @XmlElement(name="BIOS_Name") + public void setBIOSName(String bIOSName) { + BIOSName = bIOSName; + } + public String getBIOSVersion() { + return BIOSVersion; + } + @XmlElement(name="BIOS_Version") + public void setBIOSVersion(String bIOSVersion) { + BIOSVersion = bIOSVersion; + } + public String getBIOSOem() { + return BIOSOem; + } + @XmlElement(name="BIOS_Oem") + public void setBIOSOem(String bIOSOem) { + BIOSOem = bIOSOem; + } + public String getVMMVersion() { + return VMMVersion; + } + @XmlElement(name="VMM_Version") + public void setVMMVersion(String vMMVersion) { + VMMVersion = vMMVersion; + } + public String getVMMOSName() { + return VMMOSName; + } + @XmlElement(name="VMM_OSName") + public void setVMMOSName(String vMMOSName) { + VMMOSName = vMMOSName; + } + public String getVMMOSVersion() { + return VMMOSVersion; + } + @XmlElement(name="VMM_OSVersion") + public void setVMMOSVersion(String vMMOSVersion) { + VMMOSVersion = vMMOSVersion; + } + public String getVMMName() { + return VMMName; + } + @XmlElement(name="VMM_Name") + public void setVMMName(String vMMName) { + VMMName = vMMName; + } + + public String getLocation() { + return Location; + } + @XmlElement(name="Location") + public void setLocation(String location) { + Location = location; + } + + public String getPcrIMLMask() { + return pcrIMLMask; + } + + @XmlElement(name="pcrIMLMask") + public void setPcrIMLMask(String pcrIMLMask) { + this.pcrIMLMask = pcrIMLMask; + } +} \ No newline at end of file diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/OpenAttestationResponseFault.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/OpenAttestationResponseFault.java new file mode 100644 index 0000000..ce5fe9c --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/OpenAttestationResponseFault.java @@ -0,0 +1,65 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source error_code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.AttestationService.bean; + +import javax.xml.bind.annotation.XmlRootElement; + + +@XmlRootElement +public class OpenAttestationResponseFault { + private int error_code; + private String error_message; + private String detail; + + public OpenAttestationResponseFault(){} + + public OpenAttestationResponseFault (int error_code){ + this.error_code= error_code; + } + + + public int getError_code() { + return error_code; + } + public void setError_code(int code) { + this.error_code = code; + } + + public String getError_message() { + return error_message; + } + public void setError_message(String message) { + this.error_message = message; + } + + public String getDetail() { + return detail; + } + + public void setDetail(String detail) { + this.detail = detail; + } + + public static class FaultCode{ + public static int FAULT_1006 = 1006; + public static int FAULT_401 = 401; + public static int FAULT_404 = 404; + public static int FAULT_500 = 500; + public static int FAULT_2001 = 2001; + public static int FAULT_412 = 412; + public static int FAULT_2000 = 2000; + } + + +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/PCRValue.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/PCRValue.java new file mode 100644 index 0000000..bd2c800 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/PCRValue.java @@ -0,0 +1,42 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.AttestationService.bean; + +public class PCRValue { + + Integer number; + String value; + + + public PCRValue() { + + } + public PCRValue(Integer number, String value) { + + this.number = number; + this.value = value; + } + public Integer getNumber() { + return number; + } + public void setNumber(Integer number) { + this.number = number; + } + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } + +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/ReqAttestationBean.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/ReqAttestationBean.java new file mode 100644 index 0000000..9e72a13 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/ReqAttestationBean.java @@ -0,0 +1,76 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.AttestationService.bean; + +import java.util.List; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class ReqAttestationBean { + + private List hosts; + + private Long timeThreshold; + + private String PCRmask; + + private String analysisType; + + private String expirationTime; + + public ReqAttestationBean(){ + + } + + public List getHosts() { + return hosts; + } + + public void setHosts(List hosts) { + this.hosts = hosts; + } + + public Long getTimeThreshold() { + return timeThreshold; + } + + public void setTimeThreshold(Long timeThreshold) { + this.timeThreshold = timeThreshold; + } + + public String getPCRmask() { + return PCRmask; + } + + public void setPCRmask(String pCRmask) { + PCRmask = pCRmask; + } + + public String getAnalysisType() { + return analysisType; + } + + public void setAnalysisType(String analysisType) { + this.analysisType = analysisType; + } + + public String getExpirationTime() { + return expirationTime; + } + + public void setExpirationTime(String expirationTime) { + this.expirationTime = expirationTime; + } + +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/RequestBean.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/RequestBean.java new file mode 100644 index 0000000..be7b1d6 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/RequestBean.java @@ -0,0 +1,58 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.AttestationService.bean; + + +public class RequestBean { + private String requestId; + + private String hosts; + + private Long count; + + private String PCRMask; + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + public String getHosts() { + return hosts; + } + + public void setHosts(String hosts) { + this.hosts = hosts; + } + + + public Long getCount() { + return count; + } + + public void setCount(Long count) { + this.count = count; + } + + public String getPCRMask() { + return PCRMask; + } + + public void setPCRMask(String pCRMask) { + PCRMask = pCRMask; + } + +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/RespSyncBean.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/RespSyncBean.java new file mode 100644 index 0000000..3ea7bb5 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/bean/RespSyncBean.java @@ -0,0 +1,37 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.AttestationService.bean; + +import java.util.List; + +import javax.xml.bind.annotation.XmlRootElement; + +import com.intel.openAttestation.AttestationService.bean.Host; + +@XmlRootElement +public class RespSyncBean { + + private List hosts; + + public List getHosts() { + return hosts; + } + + public void setHosts(List hosts) { + this.hosts = hosts; + } + + + + +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/dao/AttestDao.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/dao/AttestDao.java new file mode 100644 index 0000000..b3d7c15 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/dao/AttestDao.java @@ -0,0 +1,242 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.AttestationService.hibernate.dao; + +import gov.niarl.hisAppraiser.hibernate.domain.AuditLog; +import gov.niarl.hisAppraiser.hibernate.domain.MachineCert; +import java.util.ArrayList; +import java.util.List; +import org.hibernate.Query; +import org.hibernate.Session; +import gov.niarl.hisAppraiser.hibernate.domain.AttestRequest; +import com.intel.openAttestation.AttestationService.hibernate.util.HibernateUtilHis; + +public class AttestDao { + + public AttestDao() { + } + + + /** + * save a request for given request + * @param req + */ + public void saveRequest(AttestRequest req){ + try { + HibernateUtilHis.beginTransaction(); + HibernateUtilHis.getSession().save(req); + HibernateUtilHis.commitTransaction(); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + + /** + * get request by id + * @param id + * @return + */ + public AttestRequest getRequestById(Long id){ + AttestRequest req = null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from AttestRequest a where a.id = :id"); + query.setLong("id", id); + List list = query.list(); + if (list.size() < 1) { + req = new AttestRequest(); + } else { + req = (AttestRequest) list.iterator().next(); + } + HibernateUtilHis.commitTransaction(); + return req; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + /** + * get requests by requestId + * @param requestId + * @return + */ + public List getRequestsByRequestId(String requestId){ + List reqs = null; + try{ + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from AttestRequest a where a.requestId= :requestId"); + query.setString("requestId", requestId); + List list = query.list(); + if (list.size() < 1) { + reqs = new ArrayList(); + } else { + reqs = (List) list; + } + HibernateUtilHis.commitTransaction(); + return reqs; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + + /** + * get all async requests + * @return + */ + public List getAllRequestsAsync(){ + List reqs = null; + try{ + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from AttestRequest a where a.isSync=:isSync order by a.requestTime desc"); + query.setBoolean("isSync", false); + List list = query.list(); + if (list.size() < 1) { + reqs = new ArrayList(); + } else { + reqs = (List) list; + System.out.println("zlj:" +reqs.get(0).getRequestId() +reqs.get(0).getMachineCert()); + } + HibernateUtilHis.commitTransaction(); + return reqs; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + + /** + * get auditLog by auditId + * @param id + * @return + */ + public AuditLog getAuditLogById(long id){ + AuditLog auditLog = null; + try{ + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from AuditLog a where a.id = :id"); + query.setLong("id", id); + List list = query.list(); + if (list.size() < 1) { + auditLog = null; + } else { + auditLog = (AuditLog) list.iterator().next(); + } + HibernateUtilHis.commitTransaction(); + return auditLog; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + + /* + * update the request row for a given request + * @Param req of the request of interest. + * + */ + public AttestRequest updateRequest(AttestRequest req){ + try { + HibernateUtilHis.beginTransaction(); + Session session = HibernateUtilHis.getSession(); + session.update(req); + HibernateUtilHis.commitTransaction(); + return (AttestRequest)session.get(AttestRequest.class, req.getId()); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + /* + * obtain the last attested attestRequest row for a given host name. + * @Param hostName Name of the machine of interest. + * @Return The AttestRequest entry + */ + public AttestRequest getLastAttestedRequest(String hostName){ + AttestRequest req = null; + try { + HibernateUtilHis.beginTransaction(); + hostName = hostName.toLowerCase(); + Query query = HibernateUtilHis.getSession().createQuery("from AttestRequest a where a.hostName = :hostName and" + + " a.result is not null order by a.validateTime desc"); + query.setString("hostName", hostName); + List list = query.list(); + if (list.size() < 1) { + req = new AttestRequest(); + } else { + req = (AttestRequest) list.iterator().next(); + } + HibernateUtilHis.commitTransaction(); + return req; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + /** + * Obtain the active MachineCert row for a given machine name. + * @param machineName Name of the machine of interest. + * @return The MachineCert entry or null if the machine name has no + * active registrations + */ + public MachineCert getMachineCert(String machineName) { + machineName = machineName.toLowerCase(); + MachineCert cert = null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from MachineCert m where m.machineName = :machineName and m.active = :active"); + query.setString("machineName", machineName); + query.setBoolean("active", true); + List list = query.list(); + if (list.size() < 1) { + cert = null; + } else { + cert = (MachineCert) list.iterator().next(); + } + HibernateUtilHis.commitTransaction(); + return cert; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/dao/HOSTDAO.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/dao/HOSTDAO.java new file mode 100644 index 0000000..409a50d --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/dao/HOSTDAO.java @@ -0,0 +1,421 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.AttestationService.hibernate.dao; + +import gov.niarl.hisAppraiser.hibernate.domain.MachineCert; + +import java.util.ArrayList; +import java.util.List; +import java.util.HashMap; + +import org.hibernate.Query; +import org.hibernate.Session; + +import gov.niarl.hisAppraiser.hibernate.domain.HOST; +import gov.niarl.hisAppraiser.hibernate.domain.AttestRequest; +import gov.niarl.hisAppraiser.hibernate.domain.HOST_MLE; +import gov.niarl.hisAppraiser.hibernate.domain.MLE; + +import com.intel.openAttestation.AttestationService.hibernate.util.HibernateUtilHis; + +/** + * This class serves as a central location for updates and queries against + * the host table + * @author intel + * @version OpenAttestation + * + */ +public class HOSTDAO { + + /** + * Constructor to start a hibernate transaction in case one has not + * already been started + */ + public HOSTDAO() { + } + + public HOST addHOSTEntry (HOST HostEntry){ + try { + HibernateUtilHis.beginTransaction(); + HibernateUtilHis.getSession().save(HostEntry); + HibernateUtilHis.commitTransaction(); + return HostEntry; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + public HOST updatehostEntry (HOST host){ + try { + HibernateUtilHis.beginTransaction(); + Session session = HibernateUtilHis.getSession(); + Query query = session.createQuery("from HOST a where a.HostName = :HostName"); + query.setString("HostName", host.getHostName()); + List list = query.list(); + if (list.size() < 1){ + throw new Exception ("Object not found"); + } + HOST hostOld = (HOST)list.get(0); + hostOld.setAddOn_Connection_String(host.getAddOn_Connection_String()); + hostOld.setDescription(host.getDescription()); + hostOld.setEmail(host.getEmail()); + hostOld.setIPAddress(host.getIPAddress()); + hostOld.setPort(host.getPort()); + if ( host.getPcrIMLMask() != null ) + hostOld.setPcrIMLMask(host.getPcrIMLMask()); + session.update(hostOld); + HibernateUtilHis.commitTransaction(); + return host; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + public HOST DeleteHOSTEntry (String HostName){ + try { + HibernateUtilHis.beginTransaction(); + Session session = HibernateUtilHis.getSession(); + Query query = session.createQuery("from HOST a where a.HostName = :NAME"); + query.setString("NAME", HostName); + List list = query.list(); + if (list.size() < 1){ + throw new Exception ("Object not found"); + } + HOST hostEntry = (HOST)list.get(0); + session.delete(hostEntry); + HibernateUtilHis.commitTransaction(); + return hostEntry; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + public boolean isHOSTExisted(String Name){ + boolean flag =false; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from HOST a where a.HostName = :value"); + query.setString("value", Name); + List list = query.list(); + if (list.size() < 1) { + flag = false; + } else { + flag = true; + } + HibernateUtilHis.commitTransaction(); + return flag; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + + + /** + * get hostID by HostName + * @return + */ + public long getHostId(String HostName){ + long hostId; + List reqs = null; + try{ + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from HOST a where a.HostName=:HostName"); + query.setString("HostName", HostName); + List list = query.list(); + if (list.size() < 1) { + hostId = 0L; + } else { + reqs = (List) list; + hostId = reqs.get(0).getID(); + } + HibernateUtilHis.commitTransaction(); + return hostId; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + /** + * get requests by requestId + * @param requestId + * @return + */ + public List getRequestsByRequestId(String requestId){ + System.out.println("dao requestId:"+requestId); + List reqs = null; + try{ + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from AttestRequest a where a.requestId= :requestId"); + query.setString("requestId", requestId); + List list = query.list(); + if (list.size() < 1) { + reqs = new ArrayList(); + } else { + reqs = (List) list; + } + HibernateUtilHis.commitTransaction(); + return reqs; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + /** + * Obtain the active MachineCert row for a given machine name. + * @param machineName Name of the machine of interest. + * @return The MachineCert entry or null if the machine name has no + * active registrations + */ + public MachineCert getMachineCert(String machineName) { + machineName = machineName.toLowerCase(); + MachineCert cert = null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from MachineCert m where m.machineName = :machineName and m.active = :active"); + query.setString("machineName", machineName); + query.setBoolean("active", true); + List list = query.list(); + if (list.size() < 1) { + cert = null; + } else { + cert = (MachineCert) list.iterator().next(); + } + HibernateUtilHis.commitTransaction(); + return cert; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + /** + * save a request for given request + * @param req + */ + public void saveRequest(AttestRequest req){ + try { + HibernateUtilHis.beginTransaction(); + HibernateUtilHis.getSession().save(req); + HibernateUtilHis.commitTransaction(); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + /* + * obtain the last attested attestRequest row for a given host name. + * @Param hostName Name of the machine of interest. + * @Return The AttestRequest entry + */ + public AttestRequest getLastAttestedRequest(String hostName){ + AttestRequest req = null; + try { + HibernateUtilHis.beginTransaction(); + hostName = hostName.toLowerCase(); + Query query = HibernateUtilHis.getSession().createQuery("from AttestRequest a where a.hostName = :hostName and" + + " a.result is not null order by a.validateTime desc"); + query.setString("hostName", hostName); + List list = query.list(); + if (list.size() < 1) { + req = new AttestRequest(); + } else { + req = (AttestRequest) list.iterator().next(); + } + HibernateUtilHis.commitTransaction(); + return req; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + /* + * update the request row for a given request + * @Param req of the request of interest. + * + */ + public AttestRequest updateRequest(AttestRequest req){ + try { + HibernateUtilHis.beginTransaction(); + Session session = HibernateUtilHis.getSession(); + session.update(req); + HibernateUtilHis.commitTransaction(); + return (AttestRequest)session.get(AttestRequest.class, req.getId()); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + /** + * get request by id + * @param id + * @return + */ + public AttestRequest getRequestById(Long id){ + AttestRequest req = null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from AttestRequest a where a.id = :id"); + query.setLong("id", id); + List list = query.list(); + if (list.size() < 1) { + req = new AttestRequest(); + } else { + req = (AttestRequest) list.iterator().next(); + } + HibernateUtilHis.commitTransaction(); + return req; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + + public boolean checkOEM(HashMap attributes){ + boolean flag =false; + try { + HibernateUtilHis.beginTransaction(); + //Query query = HibernateUtilHis.getSession().createQuery("from OEM a where a.Name = :value"); + String name = attributes.get("BIOSName"); + String version = attributes.get("BIOSVersion"); + String biosOem = attributes.get("BIOSOem"); + Query query = HibernateUtilHis.getSession().createQuery("select a from MLE a inner join a.oem b where a.Name = :name and a.Version = :version and " + + "b.Name = :biosOem and a.MLE_Type = BIOS"); + query.setString("name", name); + query.setString("version", version); + query.setString("biosOem", biosOem); + + List list = query.list(); + if (list.size() < 1) { + flag = false; + } else { + flag = true; + } + HibernateUtilHis.commitTransaction(); + return flag; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + public void addHostMle(HOST_MLE hostMle) { + try { + HibernateUtilHis.beginTransaction(); + HibernateUtilHis.getSession().save(hostMle); + HibernateUtilHis.commitTransaction(); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + public void DeleteHostMle(HOST host) { + try { + HibernateUtilHis.beginTransaction(); + Session session = HibernateUtilHis.getSession(); + Query query = session.createQuery("from HOST_MLE a where a.host = :host"); + query.setEntity("host", host); + List list = query.list(); + for(int i=0; i < list.size(); i++){ + session.delete((HOST_MLE)list.get(i)); + } + HibernateUtilHis.commitTransaction(); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + public List getAllHostEntries(){ + try{ + ArrayList hostList = new ArrayList(); + Query query = HibernateUtilHis.getSession().createQuery("from HOST host"); + System.out.println("query:"+query.toString()); + List list = query.list(); + for (int i=0;i getMLEList(HOST host){ + try { + ArrayList hostList = new ArrayList(); + Query query = HibernateUtilHis.getSession().createQuery("select a.mle from HOST_MLE a where a.host = :host"); + query.setEntity("host", host); + List list = query.list(); + return (List)list; + } catch (Exception e){ + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + } + } +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/dao/MLEDAO.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/dao/MLEDAO.java new file mode 100644 index 0000000..b87124d --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/dao/MLEDAO.java @@ -0,0 +1,116 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.AttestationService.hibernate.dao; + +import gov.niarl.hisAppraiser.hibernate.domain.MLE; +import java.util.List; +import org.hibernate.Query; +import com.intel.openAttestation.AttestationService.bean.HostBean; +import com.intel.openAttestation.AttestationService.hibernate.util.HibernateUtilHis; + +/** + * This class serves as a central location for updates and queries against + * the OEM table + * @author Lijuan + * @version OpenAttestation + * + */ +public class MLEDAO { + + /** + * Constructor to start a hibernate transaction in case one has not + * already been started + */ + public MLEDAO() { + } + + //"BIOS_Name":"EPSD","BIOS_Version":"55","BIOS_Oem":"EPSD","VMM_Name":"Xen","VMM_Version":"4.1.1","VMM_OSName":"RHEL","VMM_OSVersion":"6.1" + public MLE getMLE(HostBean hostFullObj, int order){ + MLE mle=null;; + String[] queryString = new String[2]; + try{ + HibernateUtilHis.beginTransaction(); + queryString[0]="select m from MLE m inner join m.oem o where m.Name=:biosName and m.Version=:biosVersion and o.Name =:oemName";//query BIOS information + queryString[1]="select m from MLE m inner join m.os o where m.Name=:VMMName and m.Version=:VMMVersion and o.Name=:osName and o.Version=:osVersion";//query VMM information + Query query = HibernateUtilHis.getSession().createQuery(queryString[order]); + if(order == 0){ + if (hostFullObj.getBIOSName() != null){ + query.setString("biosName", hostFullObj.getBIOSName()); + } else { + System.out.println("BIOS name is null"); + } + if (hostFullObj.getBIOSVersion() != null){ + query.setString("biosVersion", hostFullObj.getBIOSVersion()); + } else { + System.out.println("BIOS version is null"); + } + if (hostFullObj.getBIOSOem() !=null){ + query.setString("oemName", hostFullObj.getBIOSOem()); + } else { + System.out.println("OEM is null"); + } + } + else if(order ==1){ + if (hostFullObj.getVMMName() != null){ + query.setString("VMMName", hostFullObj.getVMMName()); + } else { + System.out.println("VMM name is null"); + } + if (hostFullObj.getVMMVersion() != null){ + query.setString("VMMVersion", hostFullObj.getVMMVersion()); + } else { + System.out.println("VMM version is null"); + } + if (hostFullObj.getVMMOSName() != null){ + query.setString("osName", hostFullObj.getVMMOSName()); + } else { + System.out.println("VMM OS name is null"); + } + if (hostFullObj.getVMMOSVersion() != null){ + query.setString("osVersion", hostFullObj.getVMMOSVersion()); + } else { + System.out.println("VMM OS version is null"); + } + + } + List list = query.list(); + if(list.size()>0) + mle= (MLE)list.iterator().next(); + HibernateUtilHis.commitTransaction(); + return mle; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + public void updateMle(MLE mle) { + try { + HibernateUtilHis.beginTransaction(); + HibernateUtilHis.getSession().update(mle); + HibernateUtilHis.commitTransaction(); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + + } + +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/domain/HOST.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/domain/HOST.java new file mode 100644 index 0000000..5d77063 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/domain/HOST.java @@ -0,0 +1,101 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.AttestationService.hibernate.domain; + +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlElement; + +/** + * Java class linked to the HOST table. + * @author intel + * @version OpenAttestation + * + */ + +@XmlRootElement + +public class HOST { + private Long ID; + private String HostName; + private String IPAddress; + private String Port; + private String Email; + private String AddOn_Connection_String; + private String Description; + private String pcrIMLMask; + public Long getID() { + return ID; + } + public void setID(Long iD) { + ID = iD; + } + public String getHostName() { + return HostName; + } + + @XmlElement(name = "HostName") + public void setHostName(String hostName) { + HostName = hostName; + } + public String getIPAddress() { + return IPAddress; + } + + @XmlElement(name = "IPAddress") + public void setIPAddress(String iPAddress) { + IPAddress = iPAddress; + } + public String getPort() { + return Port; + } + + @XmlElement(name = "Port") + public void setPort(String port) { + Port = port; + } + public String getEmail() { + return Email; + } + + @XmlElement(name = "Email") + public void setEmail(String email) { + Email = email; + } + public String getAddOn_Connection_String() { + return AddOn_Connection_String; + } + + @XmlElement(name = "AddOn_Connection_String") + public void setAddOn_Connection_String(String addOn_Connection_String) { + AddOn_Connection_String = addOn_Connection_String; + } + public String getDescription() { + return Description; + } + + @XmlElement(name = "Description") + public void setDescription(String description) { + Description = description; + } + + @XmlElement(name = "pcrIMLMask") + public void setPcrIMLMask(String pcrIMLMask) { + this.pcrIMLMask = pcrIMLMask; + } + + public String getPcrIMLMask() { + return pcrIMLMask; + } + +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/mapping/HOST.hbm.xml b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/mapping/HOST.hbm.xml new file mode 100644 index 0000000..eed555f --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/mapping/HOST.hbm.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/mapping/attestRequest.hbm.xml b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/mapping/attestRequest.hbm.xml new file mode 100644 index 0000000..2385790 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/mapping/attestRequest.hbm.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/util/HibernateUtilHis.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/util/HibernateUtilHis.java new file mode 100644 index 0000000..7a0703f --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/util/HibernateUtilHis.java @@ -0,0 +1,265 @@ +package com.intel.openAttestation.AttestationService.hibernate.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.HibernateException; +import org.hibernate.Interceptor; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.cfg.Configuration; + + +/** + * Basic Hibernate helper class, handles SessionFactory, Session and Transaction. + *

+ * Uses a static initializer for the initial SessionFactory creation + * and holds Session and Transactions in thread local variables. All + * exceptions are wrapped in an unchecked InfrastructureException. + * + * @author christian@hibernate.org + */ +public class HibernateUtilHis { + + private static Log log = LogFactory.getLog(HibernateUtilHis.class); + + private static Configuration configuration; + private static SessionFactory sessionFactory; + private static final ThreadLocal threadSession = new ThreadLocal(); + private static final ThreadLocal threadTransaction = new ThreadLocal(); + private static final ThreadLocal threadInterceptor = new ThreadLocal(); + + // Create the initial SessionFactory from the default configuration files + + static { + try { + configuration = new Configuration(); + sessionFactory = configuration.configure("/hibernateOat.cfg.xml").buildSessionFactory(); + // We could also let Hibernate bind it to JNDI: + + // configuration.configure().buildSessionFactory() + } catch (Throwable ex) { + // We have to catch Throwable, otherwise we will miss + // NoClassDefFoundError and other subclasses of Error + log.error("Building SessionFactory failed.", ex); + throw new ExceptionInInitializerError(ex); + } + } + + /** + * Returns the SessionFactory used for this static class. + * + * @return SessionFactory + */ + + public static SessionFactory getSessionFactory() { + /* Instead of a static variable, use JNDI: + SessionFactory sessions = null; + try { + Context ctx = new InitialContext(); + String jndiName = "java:hibernate/HibernateFactory"; + sessions = (SessionFactory)ctx.lookup(jndiName); + } catch (NamingException ex) { + throw new InfrastructureException(ex); + } + return sessions; + */ + synchronized (sessionFactory) { + return sessionFactory; + } + } + + /** + * Returns the original Hibernate configuration. + * + * @return Configuration + */ + + public static Configuration getConfiguration() { + return configuration; + } + + /** + * Rebuild the SessionFactory with the static Configuration. + * + */ + public static void rebuildSessionFactory() throws OATException { + synchronized (sessionFactory) { + try { + sessionFactory = getConfiguration().buildSessionFactory(); + } catch (Exception ex) { + throw new OATException(ex); + } + } + } + + /** + * Rebuild the SessionFactory with the given Hibernate Configuration. + * + * @param cfg + */ + + public static void rebuildSessionFactory(Configuration cfg) throws + OATException { + synchronized (sessionFactory) { + try { + sessionFactory = cfg.buildSessionFactory(); + configuration = cfg; + } catch (Exception ex) { + throw new OATException(ex); + } + } + } + + /** + * Retrieves the current Session local to the thread. + *

+ + * If no Session is open, opens a new Session for the running thread. + * + * @return Session + */ + public static Session getSession() throws OATException { + Session s = (Session) threadSession.get(); + try { + if (s == null) { + log.debug("Opening new Session for this thread."); + if (getInterceptor() != null) { + log.debug("Using interceptor: " + getInterceptor().getClass()); + s = getSessionFactory().openSession(getInterceptor()); + } else { + s = getSessionFactory().openSession(); + } + threadSession.set(s); + } + } catch (HibernateException ex) { + throw new OATException(ex); + } + return s; + } + + /** + * Closes the Session local to the thread. + */ + + public static void closeSession() throws OATException { + try { + Session s = (Session) threadSession.get(); + threadSession.set(null); + if (s != null && s.isOpen()) { + log.debug("Closing Session of this thread."); + s.close(); + } + } catch (HibernateException ex) { + throw new OATException(ex); + } + } + + /** + * Start a new database transaction. + */ + + public static void beginTransaction() throws OATException { + Transaction tx = (Transaction) threadTransaction.get(); + try { + if (tx == null) { + log.debug("Starting new database transaction in this thread."); + tx = getSession().beginTransaction(); + threadTransaction.set(tx); + } + } catch (HibernateException ex) { + throw new OATException(ex); + } + } + + /** + * Commit the database transaction. + */ + + public static void commitTransaction() throws OATException { + Transaction tx = (Transaction) threadTransaction.get(); + try { + if (tx != null && !tx.wasCommitted() + && !tx.wasRolledBack()) { + log.debug("Committing database transaction of this thread."); + tx.commit(); + } + threadTransaction.set(null); + } catch (HibernateException ex) { + rollbackTransaction(); + throw new OATException(ex); + } + } + + /** + * Commit the database transaction. + */ + + public static void rollbackTransaction() throws OATException { + Transaction tx = (Transaction) threadTransaction.get(); + try { + threadTransaction.set(null); + if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) { + log.debug( + "Tyring to rollback database transaction of this thread."); + tx.rollback(); + } + } catch (HibernateException ex) { + throw new OATException(ex); + } finally { + closeSession(); + } + } + + /** + * Reconnects a Hibernate Session to the current Thread. + * + * @param session The Hibernate Session to be reconnected. + */ + + public static void reconnect(Session session) throws + OATException { + try { + session.reconnect(); + threadSession.set(session); + } catch (HibernateException ex) { + throw new OATException(ex); + } + } + + /** + * Disconnect and return Session from current Thread. + * + * @return Session the disconnected Session + */ + + public static Session disconnectSession() throws OATException { + + Session session = getSession(); + try { + threadSession.set(null); + session.disconnect(); + } catch (HibernateException ex) { + throw new OATException(ex); + } + return session; + } + + /** + * Register a Hibernate interceptor with the current thread. + *

+ + * Every Session opened is opened with this interceptor after + * registration. Has no effect if the current Session of the + * thread is already open, effective on next close()/getSession(). + */ + public static void registerInterceptor(Interceptor interceptor) { + threadInterceptor.set(interceptor); + } + + private static Interceptor getInterceptor() { + Interceptor interceptor = (Interceptor) threadInterceptor.get(); + return interceptor; + } + +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/util/OATException.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/util/OATException.java new file mode 100644 index 0000000..12e6ba5 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/hibernate/util/OATException.java @@ -0,0 +1,22 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.AttestationService.hibernate.util; + +public class OATException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public OATException(Throwable cause) { + super(cause); + } +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/resource/AttestService.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/resource/AttestService.java new file mode 100644 index 0000000..710cf1f --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/resource/AttestService.java @@ -0,0 +1,282 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.AttestationService.resource; + +import gov.niarl.hisAppraiser.hibernate.domain.AuditLog; + +import org.apache.log4j.Logger; + +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; + +import com.intel.openAttestation.AttestationService.util.AttestUtil; +import com.intel.openAttestation.AttestationService.bean.Host; +import com.intel.openAttestation.AttestationService.bean.PCRValue; +import com.intel.openAttestation.AttestationService.bean.RespSyncBean; +import com.intel.openAttestation.AttestationService.bean.AnalysisDetails; +import com.intel.openAttestation.AttestationService.util.ResultConverter; +import com.intel.openAttestation.AttestationService.util.ResultConverter.AttestResult; +import com.intel.openAttestation.AttestationService.hibernate.dao.AttestDao; + +import gov.niarl.hisAppraiser.Constants; +import gov.niarl.hisAppraiser.hibernate.domain.AttestRequest; + +public class AttestService { + + public static Logger logger = Logger.getLogger("AttestService"); + /** + * generate a hashMap of pcrs for a given auditlog. The hashMap key is pcr's number and value is pcr's value. + * @param auditlog of interest + * @return contain key-values of pcrs like {<'1','11111111111'>,<'2','111111111111111111111'>,...} + */ + public static HashMap generatePcrsByAuditId(AuditLog auditlog){ + HashMap pcrs = new HashMap(); + pcrs.put(0, auditlog.getPcr0()); + pcrs.put(1, auditlog.getPcr1()); + pcrs.put(2, auditlog.getPcr2()); + pcrs.put(3, auditlog.getPcr3()); + pcrs.put(4, auditlog.getPcr4()); + pcrs.put(5, auditlog.getPcr5()); + pcrs.put(6, auditlog.getPcr6()); + pcrs.put(7, auditlog.getPcr7()); + pcrs.put(8, auditlog.getPcr8()); + pcrs.put(9, auditlog.getPcr9()); + pcrs.put(10, auditlog.getPcr10()); + pcrs.put(11, auditlog.getPcr11()); + pcrs.put(12, auditlog.getPcr12()); + pcrs.put(13, auditlog.getPcr13()); + pcrs.put(14, auditlog.getPcr14()); + pcrs.put(15, auditlog.getPcr15()); + pcrs.put(16, auditlog.getPcr16()); + pcrs.put(17, auditlog.getPcr17()); + pcrs.put(18, auditlog.getPcr18()); + pcrs.put(19, auditlog.getPcr19()); + pcrs.put(20, auditlog.getPcr20()); + pcrs.put(21, auditlog.getPcr21()); + pcrs.put(22, auditlog.getPcr22()); + pcrs.put(23, auditlog.getPcr23()); + return pcrs; + } + + /** + * decide whether all hosts has attested for a given requestId. + * @param requestId of interest + * @return true if all has attested, else false + */ + public static boolean isAllAttested(String requestId){ + AttestDao attestationDao = new AttestDao(); + List attestRequests = attestationDao.getRequestsByRequestId(requestId); + for (AttestRequest attestRequest : attestRequests){ + if (attestRequest.getResult() == null) + return false; + } + return true; + } + + /** + * Compares the requested threshold and the time since the last + * attestation was executed in order to determine if the result + * is usable. + * @param request The AttestRequest entry to be tested + * @return True if the result of the AttestRequest respects + * time interval constraints; false otherwise. + */ + public static boolean isPeriodicResultValid(AttestRequest request) { + boolean returnValue = false; + + if (request.getThreshold() == null || request.getValidateTime() == null || + request.getThreshold() == Constants.PERIODIC_HOST_UNREACHABLE) + return returnValue; + + Long currentTime = new Date().getTime(); + Long lastAttestationTime = request.getValidateTime().getTime(); + + /* + * The periodic attestation result is valid if: + * - the result is UN_KNOWN, because in this case no + * attestation is done and the result must be returned + * to the user; + * - the interval between the last attestation request time + * and the last validation time is lesser than the provided + * threshold. + */ + if (ResultConverter.getResultFromInt(request.getResult()) == AttestResult.UN_KNOWN || + currentTime - lastAttestationTime < request.getThreshold()) + returnValue = true; + + return returnValue; + } + + /** + * get synchronous result for a given requestId. Just get value from DB. + * @param requestId + * @return + */ + public static RespSyncBean getRespSyncResult(String requestId) { + AttestDao dao = new AttestDao(); + RespSyncBean resp = new RespSyncBean(); + List hosts = new ArrayList (); + + for (AttestRequest attest: dao.getRequestsByRequestId(requestId)){ + Integer result = attest.getResult()==null ? ResultConverter.getIntFromResult(AttestResult.PENDING) : attest.getResult(); + Host host = new Host(); + List pcr_values = new ArrayList(); + HashMap pcrs = new HashMap(); + if (ResultConverter.getResultFromInt(result) == AttestResult.TRUSTED || ResultConverter.getResultFromInt(result) == AttestResult.UN_TRUSTED){ + if (attest.getPCRMask()!=null){ + AuditLog auditlog = dao.getAuditLogById(attest.getAuditLog().getId()); + if (auditlog != null){ + pcrs = generatePcrsByAuditId(auditlog); + for (Integer i : AttestUtil.generatePcrSelectedPositions(attest.getPCRMask())){ + pcr_values.add(new PCRValue(i,pcrs.get(i))); + } + host.setPcr_values(pcr_values); + } + } + } + host.setHost_name(attest.getHostName()); + host.setTrust_lvl(ResultConverter.getStringFromInt(result)); + + if (attest.getThreshold() != null && attest.getThreshold() > 0 && attest.getResult() != null) { + if (!isPeriodicResultValid(attest)) { + host.setTrust_lvl(ResultConverter.getStringFromInt(ResultConverter.getIntFromResult(AttestResult.TIME_OUT))); + hosts.add(host); + continue; + } + } + host.setVtime(attest.getValidateTime()); + + String[] analysisList = {"VALIDATE_PCR", "COMPARE_REPORT"}; + String analysisRequest = attest.getAnalysisRequest(); + if (analysisRequest != null) { + if (attest.getAuditLog() != null) { + AttestUtil.loadProp(); + host.setUrl("http://" + AttestUtil.getPortalAddress() + "/OAT/report.php?id=" + attest.getAuditLog().getId()); + } + host.setReport_is_valid(false); + + if (attest.getAuditLog() != null) { + AuditLog auditlog = dao.getAuditLogById(attest.getAuditLog().getId()); + if (auditlog.getValidationErrors() == null) { + host.setReport_is_valid(true); + } + } + + analysisList = analysisRequest.split(";"); + + String analysisResults = attest.getAnalysisResults(); + List detailsList = null; + + if (analysisResults != null && !analysisResults.equals("")) { + detailsList = new ArrayList(); + int analysisCounter = 0; + while (analysisResults.length() > 0) { + String[] analysisElements = analysisResults.split("\\|", 5); + AnalysisDetails detail = new AnalysisDetails(); + + int outputLength = Integer.parseInt(analysisElements[3]); + int tmpLength = 0; + for (int i = 0; i < 4; i++) + tmpLength += analysisElements[i].length() + 1; + + detail.setName(analysisList[analysisCounter].split(",")[0]); + detail.setResult(analysisElements[1]); + detail.setStatus(analysisElements[2]); + detail.setOutput(analysisResults.substring(tmpLength, tmpLength + outputLength)); + detailsList.add(detail); + + analysisResults = analysisResults.substring(tmpLength + outputLength + 1); + analysisCounter++; + } + } + + host.setAnalysis_details(detailsList); + } + hosts.add(host); + } + resp.setHosts(hosts); + return resp; + } + + /** + * add requests to DB and return requestId. + * @param reqAttestation + * @param Xauthuser + * @param isSync + * @return requestId + */ + + +// public static String addRequests(ReqAttestationBean reqAttestation, +// String requestHost, boolean isSync) { +// AttestDao dao = new AttestDao(); +// int hostNum = Integer.parseInt(String.valueOf(reqAttestation.getCount())); +// AttestRequest[] attestRequests = new AttestRequest[hostNum]; +// String requestId; +// if (isSync) +// requestId = AttestUtil.generateRequestId("PollHostsRequestId"); +// else +// requestId = AttestUtil.generateRequestId("PostHostsRequestId"); +// Date requestTime = new Date(); +// for(int i=0; i getRequestsByReqId(String requestId) { + AttestDao dao = new AttestDao(); + return dao.getRequestsByRequestId(requestId); + } + + /** + * get newest request by id. + * @param id + * @return + */ + public static AttestRequest loadRequest(Long id) { + AttestDao dao = new AttestDao(); + return dao.getRequestById(id); + } + + /** + * authentication + * @param authblob + * @return + */ + public static boolean ISV_Autherntication_module() { + return true; + } +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/resource/CheckAttestThread.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/resource/CheckAttestThread.java new file mode 100644 index 0000000..a0105a1 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/resource/CheckAttestThread.java @@ -0,0 +1,84 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.AttestationService.resource; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import org.apache.log4j.Logger; + +import com.intel.openAttestation.AttestationService.util.AttestUtil; +import com.intel.openAttestation.AttestationService.hibernate.dao.AttestDao; +import com.intel.openAttestation.AttestationService.resource.AttestService; +import com.intel.openAttestation.AttestationService.util.ResultConverter; +import com.intel.openAttestation.AttestationService.util.ResultConverter.AttestResult; + +import gov.niarl.hisAppraiser.hibernate.domain.AttestRequest; + +public class CheckAttestThread extends Thread { + + private String requestId; + private boolean running = true; + + private static Logger logger = Logger.getLogger("OpenAttestation"); + + + public CheckAttestThread(String requestId){ + this.requestId = requestId; + } + + @Override + public void run() { + try { + while (running) { + sleep(AttestUtil.getDefaultAttestTimeout()); + checkAttest(requestId); + } + + } catch (InterruptedException e) { +// e.printStackTrace(); + logger.fatal("Exception:", e); + } + } + + + public void checkAttest(String requestId){ + AttestDao dao = new AttestDao(); + List reqs= new ArrayList(); + reqs = AttestService.getRequestsByReqId(requestId); + for (AttestRequest req: reqs){ + AttestRequest reqnew = AttestService.loadRequest(req.getId()); + if (reqnew.getResult() == null){ + long timeUsed = System.currentTimeMillis() - req.getRequestTime().getTime(); + if (req.getMachineCert() == null ){ + logger.warn("Host:" +req.getHostName() +" Machine Cert is null"); + req.setResult(ResultConverter.getIntFromResult(AttestResult.UN_KNOWN)); + req.setValidateTime(new Date()); + dao.updateRequest(req); + } + else if (timeUsed > AttestUtil.getDefaultAttestTimeout()){ + logger.warn("Host:" +req.getHostName() +" time is out"); + req.setResult(ResultConverter.getIntFromResult(AttestResult.TIME_OUT)); + req.setValidateTime(new Date()); + dao.updateRequest(req); + } + //AttestResult.KNOWN is written by HisAppraiser + } + } + if (AttestService.isAllAttested(requestId)){ + running = false; + logger.info("requestId:" +requestId +"is all attested"); + } + } +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/resource/HOSTResource.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/resource/HOSTResource.java new file mode 100644 index 0000000..2ef7c5e --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/resource/HOSTResource.java @@ -0,0 +1,987 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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. +@author: wchen106 & lijuan +*/ + +package com.intel.openAttestation.AttestationService.resource; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; + +import org.apache.log4j.Logger; + +import gov.niarl.hisAppraiser.hibernate.domain.AttestRequest; +import gov.niarl.hisAppraiser.hibernate.domain.HOST_MLE; +import gov.niarl.hisAppraiser.hibernate.domain.MLE; +import gov.niarl.hisAppraiser.hibernate.domain.HOST; +import gov.niarl.hisAppraiser.hibernate.domain.OEM; +import gov.niarl.hisAppraiser.hibernate.domain.OS; + +import com.intel.openAttestation.AttestationService.resource.HOSTResource; +import com.intel.openAttestation.AttestationService.resource.AttestService; +import com.intel.openAttestation.AttestationService.bean.HostBean; +import com.intel.openAttestation.AttestationService.bean.RespSyncBean; +import com.intel.openAttestation.AttestationService.bean.AsyncBean; +import com.intel.openAttestation.AttestationService.bean.ReqAttestationBean; +import com.intel.openAttestation.AttestationService.hibernate.dao.AttestDao; +import com.intel.openAttestation.AttestationService.util.ActionConverter; + +import gov.niarl.hisAppraiser.Constants; +import gov.niarl.hisAppraiser.util.HisUtil; + +import com.intel.openAttestation.AttestationService.util.ActionDelay.Action; +import com.intel.openAttestation.AttestationService.util.ResultConverter; +import com.intel.openAttestation.AttestationService.util.ResultConverter.AttestResult; +import com.intel.openAttestation.AttestationService.util.AttestUtil; +import com.intel.openAttestation.AttestationService.bean.AttestationResponseFault; +import com.intel.openAttestation.AttestationService.bean.OpenAttestationResponseFault; +import com.intel.openAttestation.AttestationService.hibernate.dao.HOSTDAO; +import com.intel.openAttestation.AttestationService.hibernate.dao.MLEDAO; +import com.intel.openAttestation.AttestationService.hibernate.util.HibernateUtilHis; + + + +/** + * RESTful web service interface to work with HOST DB. + * + */ + +@Path("/resources") +public class HOSTResource { + private static Logger logger = Logger.getLogger("OpenAttestation"); + + @POST + @Path("/hosts") + @Consumes("application/json") + @Produces("application/json") + public Response addHOST(@Context UriInfo uriInfo, HostBean hostFullObj, @Context javax.servlet.http.HttpServletRequest request){ + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(HOSTResource.class); + Response.Status status = Response.Status.OK; + boolean isAnomaly = false; + List mles= new ArrayList(); + boolean isValidKey = true; + try{ + + HOSTDAO dao = new HOSTDAO(); + MLEDAO mleDao = new MLEDAO(); + MLE mle = null; + + //Check the length of input parameters + HashMap parameters = new HashMap(); + if (hostFullObj.getHostName() != null){ + parameters.put(hostFullObj.getHostName(), 50); + } else { + isValidKey = false; + } + + if (hostFullObj.getIPAddress() != null){ + parameters.put(hostFullObj.getIPAddress(), 50); + } + + if (hostFullObj.getPort() != null){ + parameters.put(hostFullObj.getPort(), 50); + } + + if (hostFullObj.getBIOSName() != null){ + parameters.put(hostFullObj.getBIOSName(), 50); + } + + if (hostFullObj.getBIOSVersion() != null){ + parameters.put(hostFullObj.getBIOSVersion(), 100); + } + + if (hostFullObj.getBIOSOem() != null){ + parameters.put(hostFullObj.getBIOSOem(), 50); + } + + if (hostFullObj.getVMMName() != null){ + parameters.put(hostFullObj.getVMMName(), 50); + } + + if (hostFullObj.getVMMVersion() != null){ + parameters.put(hostFullObj.getVMMVersion(), 100); + } + + if (hostFullObj.getVMMOSName() != null){ + parameters.put(hostFullObj.getVMMOSName(), 50); + } + + if (hostFullObj.getVMMOSVersion() != null){ + parameters.put(hostFullObj.getVMMOSVersion(), 50); + } + + if (hostFullObj.getAddOn_Connection_String() != null){ + parameters.put(hostFullObj.getAddOn_Connection_String(), 100); + } + + if (hostFullObj.getDescription() != null){ + parameters.put(hostFullObj.getDescription(), 100); + } + if (hostFullObj.getPcrIMLMask() != null){ + if (hostFullObj.getPcrIMLMask().matches("[0-9A-Fa-f]{6}")) + parameters.put(hostFullObj.getPcrIMLMask(), 50); + else + isValidKey = false; + } + + if (!isValidKey || hostFullObj.getHostName().length() < 1 || !HisUtil.validParas(parameters)){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Add HOST entry failed, please check the length for each parameters" + + " and remove all of the unwanted characters belonged to [# & + : \" \']"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + //Check if the HOST Name exists + if (dao.isHOSTExisted(hostFullObj.getHostName())){ + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(2001); + fault.setError_message("Data Error - HOST " + hostFullObj.getHostName() +" already exists in the database"); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + + //Constraint check + if (hostFullObj.getBIOSName() == null && hostFullObj.getVMMName() == null){ + isAnomaly = true; + } else if (hostFullObj.getBIOSName() != null && (hostFullObj.getBIOSOem() == null || hostFullObj.getBIOSVersion() == null)){ + isAnomaly = true; + } else if (hostFullObj.getVMMName() != null && (hostFullObj.getVMMOSName() == null || hostFullObj.getVMMOSVersion() == null || hostFullObj.getVMMVersion() == null)){ + isAnomaly = true; + } + + if (isAnomaly){ + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(2001); + fault.setError_message("Data Error - HOST " + "please check the input parameters and provide complete information"); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + + if (hostFullObj.getBIOSName() != null && hostFullObj.getBIOSName().length() > 0) { + //relation check for BIOS table + mle = mleDao.getMLE(hostFullObj, 0); + if (mle == null){ + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(2001); + fault.setError_message("Data Error - HOST " + "proper BIOS or OEM is not chosen"); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + mles.add(mle); + + } + if (hostFullObj.getVMMName() != null && hostFullObj.getVMMName().length() >0 ) { + //relation check for VMM MLE + mle = mleDao.getMLE(hostFullObj,1); + if (mle == null){ + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(2001); + fault.setError_message("Data Error - HOST " + "proper VMM or OS is not chosen"); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + mles.add(mle); + } + + HOST host = new HOST(); + host.setAddOn_Connection_String(hostFullObj.getAddOn_Connection_String()); + host.setDescription(hostFullObj.getDescription()); + host.setEmail(hostFullObj.getEmail()); + host.setHostName(hostFullObj.getHostName()); + host.setIPAddress(hostFullObj.getIPAddress()); + host.setPort(hostFullObj.getPort()); + host.setPcrIMLMask((hostFullObj.getPcrIMLMask() == null) ? "000000" : hostFullObj.getPcrIMLMask()); + + dao.addHOSTEntry(host); + + //insert an entry into HOST_MLE; + for (int i=0; i requestsList = attestDao.getRequestsByRequestId(reqAttestation.getRequestId()); + if (requestsList.size() == 0) + throw new IllegalArgumentException("Can't find a request with given ID (" + reqAttestation.getRequestId() + ")"); + + for (AttestRequest attest : requestsList) { + if (reqAttestation.getRequestId().startsWith("Poll") || attest.getThreshold() == null) + throw new IllegalArgumentException("The requested attestation is not periodic"); + else if (attest.getThreshold() < 0) + throw new IllegalArgumentException("The requested periodic attestation has been already deleted"); + + attest.setThreshold(Constants.PERIODIC_DELETED_BY_USER); + attestDao.updateRequest(attest); + } + + return Response.status(status).header("Location", b.build()).type(MediaType.TEXT_PLAIN).entity("True").build(); + } catch (Exception e) { + status = Response.Status.INTERNAL_SERVER_ERROR; + + AttestationResponseFault fault = null; + if (e instanceof IllegalArgumentException) + fault = new AttestationResponseFault(AttestationResponseFault.FaultName.FAULT_ITEM_NOT_FOUND); + else { + fault = new AttestationResponseFault(AttestationResponseFault.FaultName.FAULT_ATTEST_ERROR); + logger.fatal(fault.getMessage(), e); + } + fault.setMessage("PostHosts failed."); + fault.setDetail(e.getMessage()); + + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + } + + /** + * Receives an attestation ID and returns corresponding result. + * @param uriInfo An object containing information about request URI + * @param reqAttestation An object mapping the attestation request + * @param request An object providing request information for HTTP servlets + * @return An object mapping the attestation response + */ + @GET + @Path("/PostHosts") + @Consumes("application/json") + @Produces("application/json") + public Response getPostHosts(@Context UriInfo uriInfo, AsyncBean reqAttestation, @Context javax.servlet.http.HttpServletRequest request){ + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(HOSTResource.class); + Response.Status status = Response.Status.OK; + String requestHost = request.getRemoteHost(); + + AttestUtil.loadProp(); + try { + AttestDao attestDao = new AttestDao(); + List requestsList = attestDao.getRequestsByRequestId(reqAttestation.getRequestId()); + if (requestsList.size() == 0) + throw new IllegalArgumentException("Can't find an attestation request with given ID (" + reqAttestation.getRequestId() + ")"); + + for (AttestRequest attest : requestsList) { + if (reqAttestation.getRequestId().startsWith("Poll")) + throw new IllegalArgumentException("The attestation request is neither periodic nor asynchronous"); + + long timeUsed = System.currentTimeMillis() - attest.getRequestTime().getTime(); + + boolean DISABLE_EXCEPTION = (reqAttestation.getLastResult() == null); + DISABLE_EXCEPTION |= reqAttestation.getLastResult() != null && !reqAttestation.getLastResult().equals("true"); + if (attest.getThreshold() != null) { + if (DISABLE_EXCEPTION && attest.getThreshold() == Constants.PERIODIC_DELETED_BY_USER) + throw new IllegalArgumentException("The attestation request has been deleted by the user"); + else if (DISABLE_EXCEPTION && attest.getThreshold() == Constants.PERIODIC_TIME_EXPIRED) + throw new IllegalArgumentException("The attestation request has been deleted because the expiration time was reached"); + else if (DISABLE_EXCEPTION && attest.getThreshold() == Constants.PERIODIC_IDLE_EXPIRED) + throw new IllegalArgumentException("The attestation request has been deleted because unread for too much time"); + else if (DISABLE_EXCEPTION && attest.getThreshold() == Constants.PERIODIC_HOST_UNREACHABLE) + throw new IllegalArgumentException("The attestation request has been deleted because one or more of requested hosts were not reachable"); + else if (DISABLE_EXCEPTION && attest.getThreshold() == Constants.PERIODIC_HOST_UNTRUSTED) + throw new IllegalArgumentException("The attestation request has been deleted because one or more of requested hosts were untrusted."); + + if (attest.getResult() != null && attest.getResult() == ResultConverter.getIntFromResult(AttestResult.UN_KNOWN)) + continue; + + /* + * A periodic request is disabled if time between + * current time and last attestation is higher then + * three times the threshold value. + * All entry with given requestId must be disabled, + * but only for current request the result should + * be set to TIME_OUT, in order to maintain previous + * results of the other entries. + */ + if (attest.getThreshold() >= 0 && timeUsed > 3 * attest.getThreshold()) { + for (AttestRequest attestRequest : requestsList) { + attestRequest.setThreshold(Constants.PERIODIC_HOST_UNREACHABLE); + attestDao.updateRequest(attestRequest); + } + attest.setResult(ResultConverter.getIntFromResult(AttestResult.TIME_OUT)); + attest.setValidateTime(new Date()); + } + } else if (attest.getResult() == null && timeUsed > AttestUtil.getDefaultAttestTimeout()){ + /* + * If an asynchronous request was submitted for an + * unreachable host, the TIME_OUT result is set. + */ + attest.setResult(ResultConverter.getIntFromResult(AttestResult.TIME_OUT)); + attest.setValidateTime(new Date()); + } + + attest.setLastReadTime(new Date()); + attestDao.updateRequest(attest); + } + + RespSyncBean syncResult = AttestService.getRespSyncResult(reqAttestation.getRequestId()); + + logger.info("requestId:" + reqAttestation.getRequestId() +" has returned the attested result"); + return Response.status(status).header("Location", b.build()).entity(syncResult).build(); + } catch (Exception e) { + status = Response.Status.INTERNAL_SERVER_ERROR; + + AttestationResponseFault fault = null; + if (e instanceof IllegalArgumentException) + fault = new AttestationResponseFault(AttestationResponseFault.FaultName.FAULT_ITEM_NOT_FOUND); + else { + fault = new AttestationResponseFault(AttestationResponseFault.FaultName.FAULT_ATTEST_ERROR); + logger.fatal(fault.getMessage(), e); + } + fault.setMessage("PostHosts failed."); + fault.setDetail(e.getMessage()); + + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + } + + /** + * Receives an attestation request, writes it on DB and returns + * the ID to be used to retrieve attestation result. + * @param uriInfo An object containing information about request URI + * @param reqAttestation An object mapping the attestation request + * @param request An object providing request information for HTTP servlets + * @return An object mapping the attestation response + */ + @POST + @Path("/PostHosts") + @Consumes("application/json") + @Produces("application/json") + public Response postHosts(@Context UriInfo uriInfo, ReqAttestationBean reqAttestation, @Context javax.servlet.http.HttpServletRequest request){ + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(HOSTResource.class); + Response.Status status = Response.Status.OK; + String requestHost = request.getRemoteHost(); + gov.niarl.hisAppraiser.hibernate.util.AttestUtil.loadProp(); + AttestUtil.loadProp(); + try { + HOSTDAO dao = new HOSTDAO(); + List host = reqAttestation.getHosts(); + + if (host == null || host.size() == 0) + throw new IllegalArgumentException("The request must contain at least one host."); + + HashMap parameters = new HashMap(); + for (int i = 0; i < host.size(); i++){ + parameters.put(host.get(i), 50); + if (host.get(i).length() == 0) + throw new IllegalArgumentException("Parameters validation failed."); + } + + if (!HisUtil.validParas(parameters)) + throw new IllegalArgumentException("Parameters validation failed."); + + /* + * Required checks differ between periodic and asynchronous + * attestation requests. In the first case it's necessary + * to validate the expirationTime format and the + * timeThreshold value. + * + * Syntax of the element "expirationTime" is as follows: + * [d|h|m|s] | never + * If the given expirationTime does not match this + * syntax an error is returned. + * + * On the contrary, asynchronous requests require that + * either expirationTime and threshold are not + * specified. + */ + if (reqAttestation.getTimeThreshold() != null) { + String expirationTime = reqAttestation.getExpirationTime(); + try { + if (expirationTime != null && !expirationTime.equals("never") && + expirationTimeToLong(expirationTime) < reqAttestation.getTimeThreshold()) + throw new IllegalArgumentException("Given expirationTime can't be lower than threshold."); + } catch (Exception e) { + if (e instanceof IllegalArgumentException) + throw e; + throw new IllegalArgumentException("Wrong syntax of element \"expirationTime\""); + } + + double anticipationFactor = gov.niarl.hisAppraiser.hibernate.util.AttestUtil.getAnticipationFactor(); + long minAttestInterval = gov.niarl.hisAppraiser.hibernate.util.AttestUtil.getMinAttestInterval(); + double minThreshold = minAttestInterval + (AttestUtil.getDefaultAttestTimeout() * anticipationFactor); + if (reqAttestation.getTimeThreshold() < minThreshold) + throw new IllegalArgumentException("Minimum acceptable value for \"timeThreshold\" is: " + Math.ceil(minThreshold) + "ms."); + } else if (reqAttestation.getExpirationTime() != null) + throw new IllegalArgumentException("Only periodic requests can contain the element \"expirationTime\"."); + + String requestId = addRequests(reqAttestation, requestHost, false); + + AsyncBean asyncResult = new AsyncBean(); + asyncResult.setRequestId(requestId); + + logger.info("requestId:" +requestId +" has returned the attested result"); + return Response.status(status).header("Location", b.build()).entity(asyncResult).build(); + } catch (Exception e) { + status = Response.Status.INTERNAL_SERVER_ERROR; + + AttestationResponseFault fault = null; + if (e instanceof IllegalArgumentException) + fault = new AttestationResponseFault(OpenAttestationResponseFault.FaultCode.FAULT_500); + else { + fault = new AttestationResponseFault(AttestationResponseFault.FaultName.FAULT_ATTEST_ERROR); + logger.fatal(fault.getMessage(), e); + } + fault.setMessage("PostHosts failed."); + fault.setDetail(e.getMessage()); + + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + } + + /** + * synchronous attest model: client sends hosts and pcrmask to be attested, server attest these hosts and return specific PCR values. + * in this model, the client will always wait the response of server + * @param Xauthuser + * @param Xauthpasswd + * @param reqAttestation + * @param uriInfo + * @return + */ + @POST + @Path("/PollHosts") + @Consumes("application/json") + @Produces("application/json") + public Response pollHosts(@Context UriInfo uriInfo, ReqAttestationBean reqAttestation, @Context javax.servlet.http.HttpServletRequest request){ + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(HOSTResource.class); + Response.Status status = Response.Status.OK; + String requestHost = request.getRemoteHost(); + long timeThreshold = reqAttestation.getTimeThreshold() == null ? 0 :reqAttestation.getTimeThreshold(); + long validateInterval = 0; + boolean isValid = true; + AttestUtil.loadProp(); + try{ + HOSTDAO dao = new HOSTDAO(); + + List host = reqAttestation.getHosts(); + + if (host == null || host.size() == 0){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Poll Hosts failed, please make sure the host information is correct"); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + + HashMap parameters = new HashMap(); + for(int i=0; i reqs= getRequestsByReqId(requestId); + if (reqs != null){ + if (timeThreshold != 0 ){ + logger.info("timeThreshold:" + timeThreshold); + for (AttestRequest req: reqs){ + AttestRequest lastReq = dao.getLastAttestedRequest(req.getHostName()); + long lastValidateTime = lastReq.getId()== null? 0: lastReq.getValidateTime().getTime(); + validateInterval = System.currentTimeMillis() - lastValidateTime; + logger.info("validateInterval:" +validateInterval); + if (validateInterval < timeThreshold && lastValidateTime !=0 ){ + System.out.println("obtain the trustworthiness of last record"); + req.setAuditLog(lastReq.getAuditLog()); + req.setResult(lastReq.getResult()); + req.setValidateTime(lastReq.getValidateTime()); + } + else{ + req.setNextAction(ActionConverter.getIntFromAction(Action.SEND_REPORT)); + req.setIsConsumedByPollingWS(false);//this flags must be set at the same time. + logger.debug("Next Action:" +req.getNextAction()); + } + dao.updateRequest(req); + } + //start a thread to attest the pending request + if (!isAllAttested(requestId)){ + logger.info("requestId:" +requestId +"is not attested."); + CheckAttestThread checkAttestThread = new CheckAttestThread(requestId); + checkAttestThread.start(); + } + } + else{// timeThreshold is null + do{ //loop until all hosts are finished + for (AttestRequest req: reqs){ + //load the request again because its status may be changed for each loop + AttestRequest reqnew = AttestService.loadRequest(req.getId()); + if (reqnew.getResult() == null){ + long timeUsed = System.currentTimeMillis() - req.getRequestTime().getTime(); + if (req.getMachineCert() == null ){ + req.setResult(ResultConverter.getIntFromResult(AttestResult.UN_KNOWN)); + req.setValidateTime(new Date()); + dao.updateRequest(req); + } + else if (timeUsed > AttestUtil.getDefaultAttestTimeout()){ + req.setResult(ResultConverter.getIntFromResult(AttestResult.TIME_OUT)); + req.setValidateTime(new Date()); + dao.updateRequest(req); + } + } + } + Thread.sleep(AttestUtil.getCheckAttestInterval()); + }while(!AttestService.isAllAttested(requestId)); + logger.info("requestId:" +requestId +" has attested"); + } + + RespSyncBean syncResult = AttestService.getRespSyncResult(requestId); + logger.info("requestId:" +requestId +" has returned the attested result"); + return Response.status(status).header("Location", b.build()).entity(syncResult).build(); + } else { + status = Response.Status.INTERNAL_SERVER_ERROR; + AttestationResponseFault fault = new AttestationResponseFault(AttestationResponseFault.FaultName.FAULT_ATTEST_ERROR); + fault.setMessage("cannot fetch an entry from the table of AttestRequest, please check it"); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + }catch(Exception e){ + status = Response.Status.INTERNAL_SERVER_ERROR; + AttestationResponseFault fault = new AttestationResponseFault(AttestationResponseFault.FaultName.FAULT_ATTEST_ERROR); + fault.setMessage("poll hosts failed."); + fault.setDetail("Exception:" + e.toString()); + logger.fatal(fault.getMessage(), e); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + } + + @GET + @Path("/hosts") + @Produces("application/json") + public List searchHost(@QueryParam("searchCriteria") String criteria){ + HOSTDAO dao = new HOSTDAO(); + List hostList = new ArrayList(); + List hostBeanList = new ArrayList(); + HibernateUtilHis.beginTransaction(); + hostList = dao.getAllHostEntries(); + List MLEList = new ArrayList(); + MLE mle = null; + HOST host = null; + OEM oem = null; + OS os = null; + try { + for (int i=0; i host = reqAttestation.getHosts(); + int hostNum = host.size(); + AttestRequest[] attestRequests = new AttestRequest[hostNum]; + + for(int i=0; i getRequestsByReqId(String requestId) { + System.out.println("getRequestsByReqId requestId:"+requestId); + HOSTDAO dao = new HOSTDAO(); + return dao.getRequestsByRequestId(requestId); + } + + /** + * decide whether all hosts has attested for a given requestId. + * @param requestId of interest + * @return true if all has attested, else false + */ + public static boolean isAllAttested(String requestId){ + HOSTDAO attestationDao = new HOSTDAO(); + List attestRequests = attestationDao.getRequestsByRequestId(requestId); + for (AttestRequest attestRequest : attestRequests){ + if (attestRequest.getResult() == null) + return false; + } + return true; + } + + /** + * get newest request by id. + * @param id + * @return + */ + public static AttestRequest loadRequest(Long id) { + HOSTDAO dao = new HOSTDAO(); + return dao.getRequestById(id); + } + +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/resource/JAXBContextResolver.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/resource/JAXBContextResolver.java new file mode 100644 index 0000000..fb3051e --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/resource/JAXBContextResolver.java @@ -0,0 +1,77 @@ +/* + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. + * + * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved. + * + * The contents of this file are subject to the terms of either the GNU + * General Public License Version 2 only ("GPL") or the Common Development + * and Distribution License("CDDL") (collectively, the "License"). You + * may not use this file except in compliance with the License. You can + * obtain a copy of the License at + * http://glassfish.java.net/public/CDDL+GPL_1_1.html + * or packager/legal/LICENSE.txt. See the License for the specific + * language governing permissions and limitations under the License. + * + * When distributing the software, include this License Header Notice in each + * file and include the License file at packager/legal/LICENSE.txt. + * + * GPL Classpath Exception: + * Oracle designates this particular file as subject to the "Classpath" + * exception as provided by Oracle in the GPL Version 2 section of the License + * file that accompanied this code. + * + * Modifications: + * If applicable, add the following below the License Header, with the fields + * enclosed by brackets [] replaced by your own identifying information: + * "Portions Copyright [year] [name of copyright owner]" + * + * Contributor(s): + * If you wish your version of this file to be governed by only the CDDL or + * only the GPL Version 2, indicate your decision by adding "[Contributor] + * elects to include this software in this distribution under the [CDDL or GPL + * Version 2] license." If you don't indicate a single choice of license, a + * recipient has the option to distribute your version of this file under + * either the CDDL, the GPL Version 2 or to extend the choice of license to + * its licensees as provided above. However, if you add GPL Version 2 code + * and therefore, elected the GPL Version 2 license, then the option applies + * only if the new code is made subject to such option by the copyright + * holder. + */ +package com.intel.openAttestation.AttestationService.resource; + +import com.intel.openAttestation.AttestationService.bean.ReqAttestationBean; +import com.intel.openAttestation.AttestationService.bean.RespSyncBean; +import com.sun.jersey.api.json.JSONConfiguration; +import com.sun.jersey.api.json.JSONJAXBContext; +import javax.ws.rs.ext.ContextResolver; +import javax.ws.rs.ext.Provider; +import javax.xml.bind.JAXBContext; + +/** + * + * + */ +@Provider +public class JAXBContextResolver implements ContextResolver { + + private JAXBContext context; + private Class[] types = {ReqAttestationBean.class,RespSyncBean.class}; + +// public JAXBContextResolver() throws Exception { +// this.context = new JSONJAXBContext(JSONConfiguration.natural().build(), types); +// } + + public JAXBContextResolver() throws Exception { + this.context = new JSONJAXBContext(JSONConfiguration.mapped().arrays("hosts").build(), types); + } + + public JAXBContext getContext(Class objectType) { + for (Class type : types) { + if (type == objectType) { + return context; + } + } + return null; + + } +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/util/ActionConverter.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/util/ActionConverter.java new file mode 100644 index 0000000..cd79552 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/util/ActionConverter.java @@ -0,0 +1,81 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 com.intel.openAttestation.AttestationService.util; + +import com.intel.openAttestation.AttestationService.util.ActionDelay.Action; + +import java.util.HashMap; + +/** + * Utility class to help with Action enumeration serialization and + * de-serialization. + * @author syelama + * @version Crossbow + * + */ +public class ActionConverter { + private static HashMap integerActionHashMap = new HashMap() { + { + put(0, Action.DO_NOTHING); + put(1, Action.SEND_REPORT); + put(2, Action.REBOOT); + put(3, Action.VERIFY_CLIENT); + put(4, Action.CLEAN_CLIENT); + } + }; + + private static HashMap actionIntegerHashMap = new HashMap(); + static { + for (Integer integer : integerActionHashMap.keySet()) { + actionIntegerHashMap.put(integerActionHashMap.get(integer), integer); + } + } + + /** + * Converts a integer into an Action enumeration. + * @param i Integer linked to an action. + * @return Action enumeration related to an integer. + */ + public static Action getActionFromInt(int i) { + return integerActionHashMap.get(i) == null ? Action.DO_NOTHING : integerActionHashMap.get(i); + } + + /** + * Converts an Action enumeration into the related integer. + * @param action Enumeration value. + * @return Integer related to the enumeration. + */ + public static int getIntFromAction(Action action) { + return actionIntegerHashMap.get(action); + } +} \ No newline at end of file diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/util/ActionDelay.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/util/ActionDelay.java new file mode 100644 index 0000000..795f6f4 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/util/ActionDelay.java @@ -0,0 +1,115 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 com.intel.openAttestation.AttestationService.util; + +/** + * ActionDelay is returned by the HisPollingWebService and contains + * information to be acted on by the clients. + * + */ +public class ActionDelay { + /** + * Enumeration containing actions to be taken by the clients. + */ + public static enum Action { + DO_NOTHING, SEND_REPORT, REBOOT, VERIFY_CLIENT, CLEAN_CLIENT + } + + Action action; + long delayMilliseconds; + String args; + + /** + * Default constructor with zero arguments. + */ + public ActionDelay() { + super(); + } + + /** + * Creates an ActionDelay and sets all elements at once. + * @param action An action from the action enumeration. + * @param delayMilliseconds Milliseconds for the client to wait for + * doing another poll. + * @param args Arguments the client may need to complete an action. + */ + public ActionDelay(Action action, long delayMilliseconds, String args) { + super(); + this.action = action; + this.delayMilliseconds = delayMilliseconds; + this.args = args; + } + + /** + * @return the action + */ + public Action getAction() { + return action; + } + + /** + * @param action the action to set + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * @return the delayMilliseconds + */ + public long getDelayMilliseconds() { + return delayMilliseconds; + } + + /** + * @param delayMilliseconds the delayMilliseconds to set + */ + public void setDelayMilliseconds(long delayMilliseconds) { + this.delayMilliseconds = delayMilliseconds; + } + + /** + * @return the args + */ + public String getArgs() { + return args; + } + + /** + * @param args the args to set + */ + public void setArgs(String args) { + this.args = args; + } +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/util/AttestUtil.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/util/AttestUtil.java new file mode 100644 index 0000000..d4083f6 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/util/AttestUtil.java @@ -0,0 +1,121 @@ +/* +Copyright (c) , Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.AttestationService.util; + +import java.io.FileInputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Properties; +import java.util.SortedSet; +import java.util.TreeSet; + +import gov.niarl.hisAppraiser.util.HisUtil; + +public class AttestUtil { + + private static String PROPERTIES_NAME = "OpenAttestationWebServices.properties"; + private static Properties attestationProperties = new Properties(); + + private static Long timeout; + private static Long checkAttestInterval; + private static String portalAddress; + private static Long defaultExpirationTime; + + public static void loadProp(){ + FileInputStream attestationPropertyFile = null; + try { + String configPath = "/etc/oat-appraiser/"; + attestationPropertyFile = new FileInputStream(configPath + PROPERTIES_NAME); + attestationProperties.load(attestationPropertyFile); + timeout = Long.parseLong(attestationProperties.getProperty("default_attest_timeout")); + checkAttestInterval = Long.parseLong(attestationProperties.getProperty("check_attest_interval", "1000")); + portalAddress = attestationProperties.getProperty("portal_address"); + defaultExpirationTime = Long.parseLong(attestationProperties.getProperty("default_expiration_time", "7")); + if (portalAddress == null) { + try { + portalAddress = java.net.InetAddress.getLocalHost().getHostName(); + } catch (java.net.UnknownHostException e) { + portalAddress = "localhost"; + } + } + attestationPropertyFile.close(); + } + catch (IOException e) { + e.printStackTrace(); + } + finally{ + try { + if (attestationPropertyFile != null) + attestationPropertyFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + public static Long getDefaultAttestTimeout() { + return timeout; + } + + public static Long getCheckAttestInterval(){ + return checkAttestInterval; + } + public static String getPortalAddress() { + return portalAddress; + } + + public static Long getDefaultExpirationTime() { + return defaultExpirationTime; + } + + public static synchronized String generateRequestId(String label){ + byte[] nonce = HisUtil.generateSecureRandom(16); + return label+ HisUtil.hexString(nonce); + } + + + public static ArrayList generatePcrSelectedPositions(String PCRMask){ + ArrayList arrayList = new ArrayList(); + PCRMask = PCRMask.length() %2 !=0 ? "0" + PCRMask : PCRMask; + byte[] bytes= HisUtil.unHexString(PCRMask); + for (int i = 0; i < bytes.length; i++) { + for (Integer integer : AttestUtil.getSelectedPCR(bytes[bytes.length -i-1])) { + arrayList.add(integer + (i * 8)); + } + } + return arrayList; + } + + + /** + * Get the sorted selected positions in a byte with the right most + * position as zero. + * @param input Byte to be evaluated + * @return Array of integer positions. + */ + public static SortedSet getSelectedPCR(byte input) { + ArrayList arrayList = new ArrayList(); + byte mask = 0x01; + for (int i = 0; i <= 7; i++) { + int value = (input >>> i) & mask; + if (value == 1) { + arrayList.add(i); + } + } + Collections.sort(arrayList); + return Collections.unmodifiableSortedSet(new TreeSet(arrayList)); + } + +} diff --git a/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/util/ResultConverter.java b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/util/ResultConverter.java new file mode 100644 index 0000000..bb0c853 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/com/intel/openAttestation/AttestationService/util/ResultConverter.java @@ -0,0 +1,85 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.AttestationService.util; + +import java.util.HashMap; + +public class ResultConverter { + + public static enum AttestResult { + UN_TRUSTED, TRUSTED, UN_KNOWN,TIME_OUT, PENDING + } + + private static HashMap integerResultHashMap = new HashMap() { + /** + * + */ + private static final long serialVersionUID = 1L; + + { + put(0, AttestResult.UN_TRUSTED); + put(1, AttestResult.TRUSTED); + put(2, AttestResult.UN_KNOWN); + put(3, AttestResult.TIME_OUT); + put(4, AttestResult.PENDING); + } + }; + + private static HashMap ResultIntegerHashMap = new HashMap(); + static { + for (Integer integer : integerResultHashMap.keySet()) { + ResultIntegerHashMap.put(integerResultHashMap.get(integer), integer); + } + } + + /** + * Converts a integer into an Action enumeration. + * @param i Integer linked to an action. + * @return Action enumeration related to an integer. + */ + public static AttestResult getResultFromInt(int i) { + return integerResultHashMap.get(i); + } + + /** + * Converts an Action enumeration into the related integer. + * @param action Enumeration value. + * @return Integer related to the enumeration. + */ + public static int getIntFromResult(AttestResult result) { + return ResultIntegerHashMap.get(result); + } + + public static String getStringFromInt(int i){ + String trust_lvl = ""; + + switch(i){ + case 0 : + trust_lvl = "untrusted"; + break; + case 1: + trust_lvl = "trusted"; + break; + case 2: + trust_lvl = "unknown"; + break; + case 3: + trust_lvl = "timeout"; + break; + case 4: + trust_lvl = "pending"; + break; + } + return trust_lvl; + } +} diff --git a/OpenAttestation/Source/AttestationService/src/hibernateOat.cfg.xml b/OpenAttestation/Source/AttestationService/src/hibernateOat.cfg.xml new file mode 100644 index 0000000..2d62126 --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/hibernateOat.cfg.xml @@ -0,0 +1,36 @@ + + + + + + org.hibernate.dialect.MySQLDialect + java:comp/env/jdbc/oat + + thread + org.hibernate.hql.classic.ClassicQueryTranslatorFactory + + org.hibernate.cache.NoCacheProvider + false + true + + + false + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/AttestationService/src/log4j.properties b/OpenAttestation/Source/AttestationService/src/log4j.properties new file mode 100644 index 0000000..b94df8a --- /dev/null +++ b/OpenAttestation/Source/AttestationService/src/log4j.properties @@ -0,0 +1,31 @@ +# Set root category priority to INFO and its only appender to CONSOLE. +log4j.rootCategory=INFO, CONSOLE +#log4j.rootCategory=INFO, CONSOLE, LOGFILE + +# Set the enterprise logger category to FATAL and its only appender to CONSOLE. +log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE + +# CONSOLE is set to be a ConsoleAppender using a PatternLayout. +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.Threshold=INFO +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=- %m%n + +# LOGFILE is set to be a File appender using a PatternLayout. +log4j.appender.LOGFILE=org.apache.log4j.FileAppender +log4j.appender.LOGFILE.File=axis.log +log4j.appender.LOGFILE.Append=true +log4j.appender.LOGFILE.Threshold=INFO +log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout +log4j.appender.LOGFILE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n + +# Set the HisAppraiser logger category +log4j.logger.gov.niarl.hisAppraiser.hibernate=INFO, HisAppraiser_CONSOLE +log4j.logger.gov.niarl.hisAppraiser=ALL, HisAppraiser_CONSOLE +log4j.logger.gov.niarl.his.xsd=ALL, HisAppraiser_CONSOLE + +# CONSOLE is set to be a ConsoleAppender using a PatternLayout. +log4j.appender.HisAppraiser_CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.HisAppraiser_CONSOLE.Threshold=ALL +log4j.appender.HisAppraiser_CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.HisAppraiser_CONSOLE.layout.ConversionPattern=%d{dd/MMM/yyyy HH:mm:ss} %p - %m%n \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/build.xml b/OpenAttestation/Source/HisAppraiser/build.xml new file mode 100644 index 0000000..1eafac4 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/build.xml @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisAppraiser/src/OAT.properties b/OpenAttestation/Source/HisAppraiser/src/OAT.properties new file mode 100644 index 0000000..0683506 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/OAT.properties @@ -0,0 +1,32 @@ +#The ALERT_MASK_CSV variable below is a comma separated list of numbers from 0 to 23 including the word signature +#Example: +#ALERT_MASK_CSV=0,4,5,signature +#For all errors to create alerts leave ALERT_MASK_CSV blank i.e.: +#ALERT_MASK_CSV= +#WARNING: Please review the logs of the web server to find the results of the ALERT_MASK_CSV setting. +ALERT_MASK_CSV=0 + +#PCR select for integrity reports +PCR_SELECT=FFFFFF + +############################################################################# +####### Mail Properties +############################################################################# + +####### Message Properties +#message.to is a comma separated list of email addresses +alert.message.to=OATApp@dod.mil +alert.message.subject=OAT Alert Notification +#message.body is a simple html email message (with the correct escape characters for a property) +alert.message.body=An integrity alert has been triggered. Please refer to the OAT portal for the OAT appraiser. PLEASE DO NOT REPLY TO TOAT AUTOMATED MESSAGE. + +####### JavaMail API Mail Properties +mail.host=localhost +mail.from=noreply@dod.mil +# mail.user= +# mail.password= +# mail.store.protocol= +# mail.transport.protocol= +# mail.smtp.host= +# mail.smtp.user= +# mail.debug= diff --git a/OpenAttestation/Source/HisAppraiser/src/OpenAttestation.properties b/OpenAttestation/Source/HisAppraiser/src/OpenAttestation.properties new file mode 100644 index 0000000..195f22b --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/OpenAttestation.properties @@ -0,0 +1,2 @@ +ManifestWebServicesUrl=https://:8443/OpenAttestationManifestWebServices/V1.0/PCR +TrustStore=/usr/lib/apache-tomcat-6.0.29/Certificate/TrustStore.jks \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/his/xsd/JAXBContextIntegrity_Report_Manifest_v1_0String.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/his/xsd/JAXBContextIntegrity_Report_Manifest_v1_0String.java new file mode 100644 index 0000000..5a61d38 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/his/xsd/JAXBContextIntegrity_Report_Manifest_v1_0String.java @@ -0,0 +1,24 @@ +package gov.niarl.his.xsd; + +/** + * This class serves as a central location for the context string used to + * marshal and un-marshal. + * @author syelama + * @version Crossbow + * + */ +public class JAXBContextIntegrity_Report_Manifest_v1_0String { + /** + * This string is a delimited list of classes used by the marshaler + * and un-marshaler. + */ + public static String contextString = getContextString(); + + private static String getContextString() { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("gov.niarl.his.xsd.integrity_Report_v1_0.org.w3._2000._09.xmldsig"); + stringBuffer.append(":gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.core_Integrity_v1_0_1"); + stringBuffer.append(":gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.integrity_Report_v1_0"); + return stringBuffer.toString(); + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/his/xsd/JAXBContextPCR_DifferenceString.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/his/xsd/JAXBContextPCR_DifferenceString.java new file mode 100644 index 0000000..7942b30 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/his/xsd/JAXBContextPCR_DifferenceString.java @@ -0,0 +1,23 @@ +package gov.niarl.his.xsd; + +/** + * This class serves as a central location for the context string used to + * marshal and un-marshal. + * @author syelama + * @version Crossbow + * + */ +public class JAXBContextPCR_DifferenceString { + /** + * This string is a delimited list of classes used by the marshaler + * and un-marshaler. + */ + public static String contextString = getContextString(); + + private static String getContextString() { + StringBuffer stringBuffer = new StringBuffer(); + stringBuffer.append("gov.niarl.his.xsd.pcr_difference"); +// stringBuffer.append(":gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.core_Integrity_v1_0_1"); + return stringBuffer.toString(); + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/his/xsd/package-info.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/his/xsd/package-info.java new file mode 100644 index 0000000..32a6582 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/his/xsd/package-info.java @@ -0,0 +1,9 @@ +/** + * Provides the classes necessary to marshal and un-marshal TCG integrity + * reports. The source and classes are generated by the xjc tool, integrity + * report schema, and binding document. + * + * @version Crossbow + */ +package gov.niarl.his.xsd; + diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/Constants.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/Constants.java new file mode 100644 index 0000000..7daa727 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/Constants.java @@ -0,0 +1,141 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser; + +import gov.niarl.hisAppraiser.util.AlertConfiguration; +import gov.niarl.hisAppraiser.util.Emailer; + +import java.io.IOException; +import java.util.Properties; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; + +import javax.mail.internet.InternetAddress; + +import org.apache.log4j.Logger; +import org.hibernate.util.ConfigHelper; + +public class Constants { + private static Logger logger = Logger.getLogger(Constants.class); + /** + * Create properties object using location of properties file. + */ + private static Properties properties = loadProperties("/etc/oat-appraiser/OAT.properties"); + + /** + * Determines where to place integrity reports + */ + public static final String IR_DIR = (getProperty("IR_DIR") == null) ? null : (getProperty("IR_DIR") + "/").replace("//", "/"); + + /** + * Get the digest algorithm to use to check the integrity of reports + */ + public static final String IR_DIGEST_METHOD = (getProperty("IR_DIGEST_METHOD") == null) ? "SHA-256" : getProperty("IR_DIGEST_METHOD"); + + /** + * Returns true if the SCALABILITY property is set to "on"; + * returns false otherwise. + */ + public static final boolean SCALABILITY = (getProperty("SCALABILITY") != null && getProperty("SCALABILITY").equals("on")) ? true : false; + + /** + * Returns true if the DISCARD_IDENTICAL_IR property is set to "on"; + * returns false otherwise. + */ + public static final boolean DISCARD_IDENTICAL_IR = (getProperty("DISCARD_IDENTICAL_IR") != null && getProperty("DISCARD_IDENTICAL_IR").equals("on")) ? true : false; + + /** + * Determines which alerts to generate. + */ + static String ALERT_MASK_CSV = getProperty("ALERT_MASK_CSV"); + public static final AlertConfiguration ALERT_CONFIGURATION = new AlertConfiguration(ALERT_MASK_CSV == null ? "0":ALERT_MASK_CSV); + /** + * Determines the PCR select for integrity reports. + */ + public static final String PCR_SELECT = getProperty("PCR_SELECT"); + /** + * JavaMail API Mail Properties + */ + public static final Properties MAIL_SERVER_PROPERTIES = Emailer.parseMailServerProperties(getProperties()); + /** + * List of addresses to which to send administrative email. + */ + public static final InternetAddress[] ALERT_MESSAGE_TO = Emailer.parseDefaultAlertMessageTo(getProperty("alert.message.to")); + /** + * Subject of the default email. + */ + public static final String ALERT_MESSAGE_SUBJECT = getProperty("alert.message.subject"); + /** + * Body of the default email. + */ + public static final String ALERT_MESSAGE_BODY = getProperty("alert.message.body"); + + public static final long PERIODIC_TIME_EXPIRED = -1; + public static final long PERIODIC_IDLE_EXPIRED = -2; + public static final long PERIODIC_DELETED_BY_USER = -3; + public static final long PERIODIC_HOST_UNTRUSTED = -4; + public static final long PERIODIC_HOST_UNREACHABLE = -5; + + /** + * Creates properties object from file name. + */ + private static Properties loadProperties(String file) { + try { + FileInputStream PropertyFile = new FileInputStream(file); + Properties SetupProperties = new Properties(); + SetupProperties.load(PropertyFile); + return SetupProperties; + } catch (IOException e) { + logger.fatal(e, e); + throw new RuntimeException(e); + } + } + + /** + * Return the entire properties object created above. + * @return + */ + private static Properties getProperties() { + return properties; + } + + /** + * Retrieve a property using the property name. + * @param key Property name. + * @return property value. + */ + private static String getProperty(String key) { + return properties.getProperty(key); + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/AnalysisTypesDao.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/AnalysisTypesDao.java new file mode 100644 index 0000000..fca4ad0 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/AnalysisTypesDao.java @@ -0,0 +1,93 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Copyright (C) 2013 Politecnico di Torino, Italy + * TORSEC group -- http://security.polito.it + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser.hibernate.dao; + +import gov.niarl.hisAppraiser.hibernate.util.HibernateUtilHis; +import gov.niarl.hisAppraiser.hibernate.domain.AnalysisTypes; + +import java.util.List; +import java.util.Iterator; + +import org.hibernate.Query; +import org.hibernate.Session; + +/** + * This class serves as a central location for updates and queries against + * the measures_log table + * @author syelama + * @version Crossbow + * + */ +public class AnalysisTypesDao { + + /** + * Constructor to start a hibernate transaction in case one has not + * already been started + */ + public AnalysisTypesDao() { + HibernateUtilHis.beginTransaction(); + } + + /** + * Retrieve an AnalysisTypes entry based on the primary key + * @param id The id or primary key of the needed AnalysisTypes entry + * @return The AnalysisTypes entry retrieved from the database + */ + public AnalysisTypes getAnalysisType(Long id) { + Query query = HibernateUtilHis.getSession().createQuery("from AnalysisTypes a where a.id = :id"); + query.setLong("id", id); + List list = query.list(); + if (list.size() < 1) { + return null; + } + return (AnalysisTypes) list.iterator().next(); + } + + /** + * Retrieve not deleted AnalysisTypes entry based on its name + * @param name The name of the needed AnalysisTypes entry + * @return The AnalysisTypes entry retrieved from the database + */ + public AnalysisTypes getAnalysisTypeByName(String name) { + Query query = HibernateUtilHis.getSession().createQuery("from AnalysisTypes a where a.name = :name and a.deleted=0"); + query.setString("name", name); + List list = query.list(); + if (list.size() < 1) { + return null; + } + return (AnalysisTypes) list.iterator().next(); + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/AttestDao.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/AttestDao.java new file mode 100644 index 0000000..b57f69e --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/AttestDao.java @@ -0,0 +1,265 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 gov.niarl.hisAppraiser.hibernate.dao; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Iterator; + +import org.hibernate.Query; +import org.hibernate.Session; + + + + +import gov.niarl.hisAppraiser.Constants; +import gov.niarl.hisAppraiser.hibernate.domain.AttestRequest; +import gov.niarl.hisAppraiser.hibernate.domain.MLE; +//import gov.niarl.hisAppraiser.hibernate.domain. +import gov.niarl.hisAppraiser.hibernate.domain.HOST_MLE; +import gov.niarl.hisAppraiser.hibernate.domain.PcrWhiteList; +import gov.niarl.hisAppraiser.hibernate.util.AttestUtil; +import gov.niarl.hisAppraiser.hibernate.util.HibernateUtilHis; +import gov.niarl.hisAppraiser.hibernate.util.ResultConverter; +import gov.niarl.hisAppraiser.hibernate.domain.HOST; + +public class AttestDao { + + public AttestDao(){ + HibernateUtilHis.beginTransaction(); + } + + /* + * update the request row for a given request + * @Param req of the request of interest. + * + */ + public AttestRequest updateRequest(AttestRequest req){ + try { + Session session = HibernateUtilHis.getSession(); + session.update(req); + session.flush(); + return (AttestRequest)session.get(AttestRequest.class, req.getId()); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + } + } + + + /* + * obtain the first attestRequest row for a given host name. + * @Param hostName Name of the machine of interest. + * @Return The AttestRequest entry + */ + public AttestRequest getLatestPolledRequest(String hostName){ + hostName = hostName.toLowerCase(); + Query query = HibernateUtilHis.getSession().createQuery("from AttestRequest a where a.hostName = :hostName and" + + " a.isConsumedByPollingWS = :isConsumedByPollingWS and a.auditLog is null and a.result is null order by a.requestTime asc"); + query.setString("hostName", hostName); + query.setBoolean("isConsumedByPollingWS", true); + List list = query.list(); + if (list.size() < 1) { + return new AttestRequest(); + } else { + return (AttestRequest) list.iterator().next(); + } + } + + /** + * Disables requests where: + * - lastReadTime is older than configured maxIdleTime + * - expirationTime is up + * - result is UN_TRUSTED + * @param hostName Name of the machine of interest. + */ + public void disableUnusedRequests(String hostName) { + AttestUtil.loadProp(); + + String queryString = "from AttestRequest a where a.hostName = :hostName " + + "and a.threshold is not null and a.threshold >= 0 and a.expirationTime is not null"; + Query query = HibernateUtilHis.getSession().createQuery(queryString); + query.setString("hostName", hostName.toLowerCase()); + + List list = query.list(); + AttestRequest tmpRequest = null; + Iterator iter = list.iterator(); + while (iter.hasNext()) { + tmpRequest = (AttestRequest) iter.next(); + + Long currentTime = new Date().getTime(); + Long maxIdleTime = AttestUtil.getMaxIdleTime() * 1000 * 60 * 60 * 24; + boolean IDLE_EXPIRED = currentTime - tmpRequest.getLastReadTime().getTime() > maxIdleTime; + boolean TIME_EXPIRED = currentTime > tmpRequest.getExpirationTime().getTime(); + boolean UN_TRUSTED = tmpRequest.getResult() != null && + tmpRequest.getResult() == ResultConverter.getIntFromResult(ResultConverter.AttestResult.UN_TRUSTED); + + if (IDLE_EXPIRED || TIME_EXPIRED || UN_TRUSTED) { + queryString = "from AttestRequest a where a.requestId = :requestId"; + query = HibernateUtilHis.getSession().createQuery(queryString); + query.setString("requestId", tmpRequest.getRequestId()); + + for (AttestRequest request : (List)query.list()) { + if (IDLE_EXPIRED) + request.setThreshold(Constants.PERIODIC_IDLE_EXPIRED); + else if (TIME_EXPIRED) + request.setThreshold(Constants.PERIODIC_TIME_EXPIRED); + else if (UN_TRUSTED) + request.setThreshold(Constants.PERIODIC_HOST_UNTRUSTED); + updateRequest(request); + } + } + } + } + + /** + * Obtains a list of attestRequests to be served. + * @param hostName Name of the machine of interest. + * @param isConsumed The desired value for field isConsumedByPollingWS + * @return A list of AttestRequest entries to be served + */ + public List getPendingRequests(String hostName, boolean isConsumed) { + List requestList = new ArrayList(); + AttestUtil.loadProp(); + + String queryString = "from AttestRequest a where a.hostName = :hostName and " + + "((a.isConsumedByPollingWS = :isConsumedByPollingWS and a.auditLog is null and a.result is null) " + + "or (a.threshold is not null and a.threshold >= 0)) order by a.validateTime asc"; + Query query = HibernateUtilHis.getSession().createQuery(queryString); + query.setString("hostName", hostName.toLowerCase()); + query.setBoolean("isConsumedByPollingWS", isConsumed); + + List list = query.list(); + AttestRequest tmpRequest = null; + Iterator iter = list.iterator(); + while (iter.hasNext()) { + tmpRequest = (AttestRequest) iter.next(); + + if (tmpRequest.getThreshold() == null || tmpRequest.getValidateTime() == null || + tmpRequest.getCurrentProcessingTime() == null) { + requestList.add(tmpRequest); + continue; + } + + Long currentTime = new Date().getTime(); + Long lastValidateTime = tmpRequest.getValidateTime().getTime(); + + /* + * If requestTime is greater than validateTime the + * request is currently being processed by the + * Appraiser. Then if isConsumed is true, the request + * can be directly added to the requestList; otherwise + * it has to be skipped + */ + if (lastValidateTime < tmpRequest.getRequestTime().getTime()) { + if (isConsumed) + requestList.add(tmpRequest); + continue; + } + + if ((currentTime - lastValidateTime) > AttestUtil.getMinAttestInterval() && + (currentTime - lastValidateTime) > tmpRequest.getThreshold() - tmpRequest.getCurrentProcessingTime() * AttestUtil.getAnticipationFactor()) { + requestList.add(tmpRequest); + } + } + + if (requestList.size() == 0) + requestList.add(new AttestRequest()); + + return requestList; + } + + /** + * get the earliest request attest for given host + * @param hostName + * @return + */ + public AttestRequest getFirstRequest(String hostName){ + hostName = hostName.toLowerCase(); + Query query = HibernateUtilHis.getSession().createQuery("from AttestRequest a where a.hostName = :hostName " + + "and a.isConsumedByPollingWS = :isConsumedByPollingWS and a.auditLog is null and a.result is null order by a.requestTime asc"); + query.setString("hostName", hostName); + query.setBoolean("isConsumedByPollingWS", false); + List list = query.list(); + if (list.size() < 1) { + return new AttestRequest(); + } else { + return (AttestRequest) list.iterator().next(); + } + } + + /** + * get pcr_name, pcr_digest from table prc_white_list, mle, host + * @param hostName + * @return + */ + public List getPcrValue(String hostName){ + hostName = hostName.toLowerCase(); + List pcrs = new ArrayList(); + Long mleId =0L; + + + + +// Query query = HibernateUtilHis.getSession().createQuery("select a from MLE a inner join a.host b where b.HostName = :hostName"); +// query.setString("hostName", hostName); +// List list = query.list(); +// List prcList; + + Query query = HibernateUtilHis.getSession().createQuery("select a from HOST_MLE a inner join a.host b where b.HostName = :hostName"); + query.setString("hostName", hostName); + List list = query.list(); + List prcList; + + if (list.size()>0) { + Iterator iterator = list.iterator(); + while (iterator.hasNext()){ + mleId = ((HOST_MLE)iterator.next()).getMle().getMLEID(); + query = HibernateUtilHis.getSession().createQuery("select a from PcrWhiteList a inner join a.mle b where b.MLEID = :mleId"); + query.setLong("mleId", mleId); + prcList = query.list(); + pcrs.addAll((List)prcList); + } + } + + return pcrs; + } + + /** + * Obtains the pcrIMLMask from the host name reading + * information stored on DB. + * @param hostName The host name to look for + * @return The validationMask associated with the host name received + */ + public String getPcrIMLMask(String hostName) { + String pcrLogMask = null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("select h from HOST h where h.HostName = :hostName"); + query.setString("hostName", hostName); + + List list = query.list(); + + if (list.size() > 0) { + pcrLogMask = ((HOST)list.get(0)).getPcrIMLMask(); + } + return pcrLogMask; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + } + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/HisAuditDao.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/HisAuditDao.java new file mode 100644 index 0000000..35dfbe6 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/HisAuditDao.java @@ -0,0 +1,242 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser.hibernate.dao; + +import gov.niarl.hisAppraiser.hibernate.domain.Alerts; +import gov.niarl.hisAppraiser.hibernate.domain.AuditLog; +import gov.niarl.hisAppraiser.hibernate.util.HibernateUtilHis; + +import java.util.Date; +import java.util.List; + +import org.hibernate.Query; +import org.hibernate.Session; + +/** + * This class serves as a central location for updates and queries against + * the AuditLog table + * @author syelama + * @version Crossbow + * + */ +public class HisAuditDao { + + /** + * Constructor to start a hibernate transaction in case one has not + * already been started + */ + public HisAuditDao() { + HibernateUtilHis.beginTransaction(); + } + + /** + * This saves an AuditLog making sure that the time stamp is current + * and the machine name is lower case + * @param auditLog AuditLog entry to save + */ + public void saveAuditLog(AuditLog auditLog) { + try { + auditLog.setTimestamp(new Date()); + auditLog.setMachineName(auditLog.getMachineName().toLowerCase()); + HibernateUtilHis.getSession().save(auditLog); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + } + } + + /** + * Update the given auditLog + * @param auditLog AuditLog entry to update + * + */ + public AuditLog updateAuditLog(AuditLog auditLog) { + try { + Session session = HibernateUtilHis.getSession(); + session.update(auditLog); + return (AuditLog)session.get(AuditLog.class, auditLog.getId()); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + } + } + + /** + * Create a new alert linked to an AuditLog entry + * @param auditLog AuditLog linked by foreign key + * @return return the newly created alert + */ + public Alerts createAlert(AuditLog auditLog) { + try { + Alerts alerts = new Alerts(); + alerts.setAuditLog(auditLog); + alerts.setStatus("New"); + HibernateUtilHis.getSession().save(alerts); + return alerts; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + } + } + + /** + * Retrieve an AuditLog entry based on the primary key + * @param id The id or primary key of the needed AuditLog entry + * @return The AuditLog entry retrieved from the database + */ + public AuditLog getAuditLog(int id) { + Query query = HibernateUtilHis.getSession().createQuery("from AuditLog a where a.id = :id"); + query.setLong("id", id); + List list = query.list(); + if (list.size() < 1) { + return null; + } else { + return (AuditLog) list.iterator().next(); + } + } + + /** + * Based on a id retrieve an AuditLog prior to that id. + * @param machineName The machine for which the previous AuditLog is needed + * @param date The date prior to which an AuditLog must be retrieved. + * @return Previous AuditLog or null if none exists + */ + public AuditLog getPreviousAuditLog(String machineName, Long id) { + machineName = machineName.toLowerCase(); + + Long longId = null; + Query query = HibernateUtilHis.getSession().createQuery("select max(a.id) from AuditLog a where a.machineName = :machineName and a.id < :id"); + query.setString("machineName", machineName); + query.setLong("id", id); + List list = query.list(); + if (list.size() < 1) { + return null; + } else { + longId = (Long) list.iterator().next(); + if (longId == null) { + return null; + } + } + + query = HibernateUtilHis.getSession().createQuery("from AuditLog a where a.id = :id"); + query.setLong("id", longId); + list = query.list(); + if (list.size() < 1) { + return null; + } else { + return (AuditLog) list.iterator().next(); + } + } + + /** + * Returns the last audit log from a machine or null if none exists. + * @param machineName Name of the machine for which a previous comparison is required + * @return The last audit log from a machine or null if none exists. + */ + public AuditLog getLastAuditLog(String machineName) { + return getPreviousAuditLog(machineName, Long.MAX_VALUE); + } + + /** + * Total count of integrity reports. + * @return Total count of integrity reports. + */ + public int getAuditLogCount() { + try { + final String queryString = "select count(a.id) from AuditLog a"; + + return ((Integer) HibernateUtilHis.getSession().createQuery(queryString).list().iterator().next()).intValue(); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + } + } + + /** + * Retrieves a list of AuditLog entries containing portions of the + * integrity measurements list, whose last part is contained in + * the given AuditLog. + * The function queries the database for all the AuditLog entries + * between the firstReport and the ID of the given AuditLog, + * considering only entries with same machineName. + * @param auditLog The AuditLog entry containing the last part of + * integrity measurements list. + * @return List of AuditLog entries in descending order (from the + * newest to the oldest). + */ + public List getRelatedAuditLogs(AuditLog auditLog) { + try { + Query query = HibernateUtilHis.getSession().createQuery("from AuditLog a where a.machineName = :machineName and a.id >= :firstReportId and a.id < :lastReportId order by a.id desc"); + query.setLong("firstReportId", auditLog.getFirstReport()); + query.setLong("lastReportId", auditLog.getId()); + query.setString("machineName", auditLog.getMachineName()); + + return (List) query.list(); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + } + } + + /** + * Retrieve a list of AuditLog entries beginning with + * @param order Integer 0,1 indicated whether to sort by machine name or by time stamp + * @param firstResult The first result in a set of thousands of results. + * @param maxResults Maximum number of results to return. + * @return List of AuditLog entries retrieved from the database. + */ + public List getAuditLogPageWithOrder(int order, int firstResult, int maxResults) { + try { + if (HibernateUtilHis.getConfiguration().getProperties().get("hibernate.dialect").toString().toLowerCase().contains("sqlserver")) { + final String[] queryString = new String[10]; + queryString[0] = "select {audit_logaudit_log.*} from (select *, ROW_NUMBER() OVER (order by machine_name asc,timestamp desc) AS 'RowNumber' from audit_log) as audit_logaudit_log where RowNumber between " + Integer.toString(firstResult + 1) + " and " + Integer.toString(firstResult + maxResults); + queryString[1] = "select {audit_logaudit_log.*} from (select *, ROW_NUMBER() OVER (order by timestamp desc,machine_name asc) AS 'RowNumber' from audit_log) as audit_logaudit_log where RowNumber between " + Integer.toString(firstResult + 1) + " and " + Integer.toString(firstResult + maxResults); + + Query query = HibernateUtilHis.getSession().createSQLQuery(queryString[order]).addEntity("audit_logaudit_log", AuditLog.class); + return (List) query.list(); + } else { + final String[] queryString = new String[10]; + queryString[0] = "from AuditLog a order by a.machineName asc,a.timestamp desc"; + queryString[1] = "from AuditLog a order by a.timestamp desc,a.machineName asc"; + + Query query = HibernateUtilHis.getSession().createQuery(queryString[order]); + query.setFirstResult(firstResult); + query.setMaxResults(maxResults); + return (List) query.list(); + } + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + } + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/HisMachineCertDao.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/HisMachineCertDao.java new file mode 100644 index 0000000..27f3bad --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/HisMachineCertDao.java @@ -0,0 +1,183 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser.hibernate.dao; + +import gov.niarl.hisAppraiser.hibernate.domain.MachineCert; +import gov.niarl.hisAppraiser.hibernate.util.HibernateUtilHis; +import gov.niarl.hisAppraiser.integrityReport.HisReportUtil; + +import java.security.cert.X509Certificate; +import java.util.Date; +import java.util.List; + +import org.hibernate.Query; + +/** + * This class serves as a central location for updates and queries against + * the MachineCert table + * @author syelama + * @version Crossbow + * + */ +public class HisMachineCertDao { + + /** + * Constructor to start a hibernate transaction in case one has not + * already been started + */ + public HisMachineCertDao() { + HibernateUtilHis.beginTransaction(); + } + + /** + * Obtain the active MachineCert row for a given machine name. + * @param machineName Name of the machine of interest. + * @return The MachineCert entry or null if the machine name has no + * active registrations + */ + public MachineCert getMachineCert(String machineName) { + machineName = machineName.toLowerCase(); + Query query = HibernateUtilHis.getSession().createQuery("from MachineCert m where m.machineName = :machineName and m.active = :active"); + query.setString("machineName", machineName); + query.setBoolean("active", true); + List list = query.list(); + if (list.size() < 1) { + return null; + } else { + return (MachineCert) list.iterator().next(); + } + } + + /** + * Create a new MachineCert entry and de-activate the previous entry. + * @param machineName Machine name for the new entry. + * @param machineCertPEM Machine certificate fro the new entry in PEM + * format. + * @return The newly created entry. + */ + public MachineCert createMachineCert(String machineName, String machineCertPEM) { + machineName = machineName.toLowerCase(); + MachineCert machineCertPrevious = getMachineCert(machineName); + if (machineCertPrevious != null) { + machineCertPrevious.setActive(false); + HibernateUtilHis.getSession().saveOrUpdate(machineCertPrevious); + } + + MachineCert machineCertNew = new MachineCert(); + machineCertNew.setActive(true); + machineCertNew.setCertificate(machineCertPEM); + machineCertNew.setMachineName(machineName); + Exception exception = null; + try { + X509Certificate privacyCaCert = getPrivacyCaCert(); + if (privacyCaCert != null) + HisReportUtil.pemToX509Certificate(machineCertNew.getCertificate()).verify(privacyCaCert.getPublicKey()); + else + machineCertNew.setPrivacyCaMachineCert(null); + } catch (Exception e) { + e.printStackTrace(); + exception = e; + } + if (exception == null) { + machineCertNew.setPrivacyCaMachineCert(getPrivacyCaMachineCert()); + } else { + machineCertNew.setPrivacyCaMachineCert(null); + } + machineCertNew.setTimestamp(new Date()); + HibernateUtilHis.getSession().saveOrUpdate(machineCertNew); + + return machineCertNew; + } + + /** + * Retrieve the certificate of the privacy CA + * @return Certificate in X509 format. + */ + public X509Certificate getPrivacyCaCert() { + return getMachineCertX509Certificate(MachineCert.PRIVACY_CA_NAME); + } + + /** + * Retrieve the active privacy CA entry in the MachineCert table. + * @return The entry from the MachineCert table. + */ + public MachineCert getPrivacyCaMachineCert() { + return getMachineCert(MachineCert.PRIVACY_CA_NAME); + } + + /** + * Retrieve the certificate enrolled for a machine by machine name. + * @param machineName The machine name. + * @return Certificate in X509 format. + */ + public X509Certificate getMachineCertX509Certificate(String machineName) { + try { + //X509Certificate x509C0erificate = null; + MachineCert machineCert = getMachineCert(machineName); + if(machineCert == null) + return null; + else + return HisReportUtil.pemToX509Certificate(machineCert.getCertificate()); + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + /** + * Retrieve an ordered list of machines. + * @param order Currently only one order, machine name. + * @return List of entries from the MachineCert table. + */ + public List getMachineCertAllWithOrder(int order) { + try { + Query[] query = new Query[10]; + query[1] = HibernateUtilHis.getSession().createQuery("from MachineCert m where m.active = :active order by m.machineName asc,m.id asc"); + query[1].setBoolean("active", true); + + return (List) query[order].list(); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + } + } + + /** + * Retrieve a MachineCert entry based on the primary key. + * @param id The id, primary key. + * @return Entry from the MachineCert table. + */ + public MachineCert getMachineCert(int id) { + return (MachineCert) HibernateUtilHis.getSession().load(MachineCert.class, new Long(id)); + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/HisSystemConstants.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/HisSystemConstants.java new file mode 100644 index 0000000..03352f6 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/HisSystemConstants.java @@ -0,0 +1,88 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser.hibernate.dao; + +import gov.niarl.hisAppraiser.hibernate.domain.SystemConstants; +import gov.niarl.hisAppraiser.hibernate.util.HibernateUtilHis; + +import java.util.HashMap; +import java.util.List; + +import org.hibernate.Query; + +/** + * This class serves as a central location for updates and queries against + * the SystemConstants table. + * @author syelama + * @version Crossbow + * + */ +public class HisSystemConstants { + + private static HashMap HASH_MAP = getSystemConstants(); + + /** + * The delay linked to the + */ + public static final long DEFAULT_DELAY = Long.parseLong(getSystemConstants().get("default_delay")); + + static { + HASH_MAP = null; + } + + /** + * Generate a hash map from the SystemConstants table. + * @return Hash map of the SystemConstants table. + */ + private static synchronized HashMap getSystemConstants() { + HashMap hashMap = new HashMap(); + try { + HibernateUtilHis.beginTransaction(); + + Query query = HibernateUtilHis.getSession().createQuery("from SystemConstants"); + List list = query.list(); + for (SystemConstants systemConstants : list) { + hashMap.put(systemConstants.getKeyId(), systemConstants.getValue()); + } + + HibernateUtilHis.commitTransaction(); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e.toString()); + } finally { + HibernateUtilHis.closeSession(); + } + return hashMap; + } +} \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/MeasureDao.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/MeasureDao.java new file mode 100644 index 0000000..b1c91b7 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/MeasureDao.java @@ -0,0 +1,79 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 gov.niarl.hisAppraiser.hibernate.dao; + +import gov.niarl.hisAppraiser.hibernate.domain.AuditLog; +import gov.niarl.hisAppraiser.hibernate.domain.MeasureLog; +import gov.niarl.hisAppraiser.hibernate.domain.Module; +import gov.niarl.hisAppraiser.hibernate.domain.SystemConstants; +import gov.niarl.hisAppraiser.hibernate.domain.TxtLog; +import gov.niarl.hisAppraiser.hibernate.util.HibernateUtilHis; +import java.util.ArrayList; +import java.util.List; +import org.hibernate.Query; + +public class MeasureDao { + + public MeasureDao(){ + HibernateUtilHis.beginTransaction(); + } + /** + * This saves an MeasureLog + * @param measureLog MeasureLog entry to save + */ + public void saveMeasureLog(MeasureLog measureLog, TxtLog txtLog, List modules) { + try { + //save measureLog + HibernateUtilHis.getSession().save(measureLog); + + //save txtLogs + if (measureLog.getTxtStatus() == 1 || measureLog.getTxtStatus() ==2){ + HibernateUtilHis.getSession().save(txtLog); + } + + //save modules + if (modules.size() > 0){ + for (Module module: modules){ + HibernateUtilHis.getSession().save(module); + } + } + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + } + + } + + public List getModuleNamesByMeasureLog(MeasureLog measureLog){ + Query query = HibernateUtilHis.getSession().createQuery("select distinct m.moduleName from Module m where m.measureLog = :measureLog"); + query.setEntity("measureLog", measureLog); + List list = query.list(); + if (list.size() < 1) { + return new ArrayList(); + } else { + return (List) list; + } + } + + public List getModuleNames(){ + Query query = HibernateUtilHis.getSession().createQuery("select distinct m.moduleName from Module m"); + List list = query.list(); + if (list.size() < 1) { + return new ArrayList(); + } else { + return (List) list; + } + } + +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/OSDao.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/OSDao.java new file mode 100644 index 0000000..830d4fe --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/OSDao.java @@ -0,0 +1,77 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Copyright (C) 2014 Politecnico di Torino, Italy + * TORSEC group -- http://security.polito.it + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser.hibernate.dao; + +import gov.niarl.hisAppraiser.hibernate.domain.OS; +import gov.niarl.hisAppraiser.hibernate.util.HibernateUtilHis; + +import java.util.List; + +import org.hibernate.Query; + +public class OSDao { + public OSDao() { + } + + /** + * Obtains the OS from the host name reading + * information stored on DB. + * @param hostName The host name to look for + * @return The OS associated with the host name received + */ + public String findHostOS(String hostName) { + String os_name = null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("select c from OS c where ID in " + + "(select a.os from MLE a where ID in (select b.mle from HOST_MLE b where HOST_ID in " + + "(select h.ID from HOST h where HOST_NAME = :host_name)))"); + query.setString("host_name", hostName); + + List list = query.list(); + + if (list.size() > 0) { + os_name = ((OS)list.get(0)).getName(); + } + return os_name; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + } + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/package-info.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/package-info.java new file mode 100644 index 0000000..f008d26 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/dao/package-info.java @@ -0,0 +1,7 @@ +/** + * This package holds data access objects which mainly include hibernate + * and SQL queries to return data from the database. + * + * @version Crossbow + */ +package gov.niarl.hisAppraiser.hibernate.dao; \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/Alerts.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/Alerts.java new file mode 100644 index 0000000..1fa1d0f --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/Alerts.java @@ -0,0 +1,117 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser.hibernate.domain; + +/** + * Java class linked to the Alerts table. + * @author syelama + * @version Crossbow + * + */ +public class Alerts { + Long id; + AuditLog auditLog; + String status; + String assignedTo; + String comments; + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the auditLog + */ + public AuditLog getAuditLog() { + return auditLog; + } + + /** + * @param auditLog the auditLog to set + */ + public void setAuditLog(AuditLog auditLog) { + this.auditLog = auditLog; + } + + /** + * @return the status + */ + public String getStatus() { + return status; + } + + /** + * @param status the status to set + */ + public void setStatus(String status) { + this.status = status; + } + + /** + * @return the assignedTo + */ + public String getAssignedTo() { + return assignedTo; + } + + /** + * @param assignedTo the assignedTo to set + */ + public void setAssignedTo(String assignedTo) { + this.assignedTo = assignedTo; + } + + /** + * @return the comments + */ + public String getComments() { + return comments; + } + + /** + * @param comments the comments to set + */ + public void setComments(String comments) { + this.comments = comments; + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/AnalysisTypes.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/AnalysisTypes.java new file mode 100644 index 0000000..a552bc8 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/AnalysisTypes.java @@ -0,0 +1,87 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Copyright (C) 2013 Politecnico di Torino, Italy + TORSEC group -- http://security.polito.it + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 gov.niarl.hisAppraiser.hibernate.domain; + + +public class AnalysisTypes { + + private Long id; + + private String name; + + private String module; + + private Integer version; + + private String URL; + + private boolean deleted; + + private String requiredPcrMask; + + public AnalysisTypes() { + } + + public void setId(Long id) { + this.id = id; + } + public Long getId() { + return id; + } + + public void setName(String name) { + this.name = name; + } + public String getName() { + return name; + } + + public void setModule(String module) { + this.module = module; + } + public String getModule() { + return module; + } + + public void setVersion(Integer version) { + this.version = version; + } + public Integer getVersion() { + return version; + } + + public void setURL(String URL) { + this.URL = URL; + } + public String getURL() { + return URL; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + public boolean getDeleted() { + return deleted; + } + + public void setRequiredPcrMask(String requiredPcrMask) { + this.requiredPcrMask = requiredPcrMask; + } + public String getRequiredPcrMask() { + return requiredPcrMask; + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/AttestRequest.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/AttestRequest.java new file mode 100644 index 0000000..d73bf06 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/AttestRequest.java @@ -0,0 +1,233 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 gov.niarl.hisAppraiser.hibernate.domain; + +import gov.niarl.hisAppraiser.hibernate.domain.AuditLog; +import gov.niarl.hisAppraiser.hibernate.domain.MachineCert; +import java.util.Date; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class AttestRequest { + + private Long id; + + private String requestId; + + private String hostName; + + private Date requestTime; + + private Integer nextAction; + + private Boolean isConsumedByPollingWS; + + private AuditLog auditLog; + + private MachineCert machineCert; + + private String requestHost; + + private Long count; + + private String PCRMask; + + private Boolean isSync; + + private Integer result; + + private Date validateTime; + + private String analysisRequest; + + private String analysisResults; + + private Long threshold; + + private Date expirationTime; + + private Date lastReadTime; + + private Long currentProcessingTime; + + public Date getValidateTime() { + return validateTime; + } + + public void setValidateTime(Date validateTime) { + this.validateTime = validateTime; + } + + public AttestRequest(){ + + } + + public Boolean getIsSync() { + return isSync; + } + + + public void setIsSync(Boolean isSync) { + this.isSync = isSync; + } + + public Long getCount() { + return count; + } + + public void setCount(Long count) { + this.count = count; + } + + + public String getPCRMask() { + return PCRMask; + } + + public void setPCRMask(String pCRMask) { + PCRMask = pCRMask; + } + + public Integer getResult() { + return result; + } + + public void setResult(Integer result) { + this.result = result; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getRequestId() { + return requestId; + } + + public void setRequestId(String requestId) { + this.requestId = requestId; + } + + + + public String getHostName() { + return hostName; + } + + public void setHostName(String hostName) { + this.hostName = hostName; + } + + public Date getRequestTime() { + return requestTime; + } + + public void setRequestTime(Date requestTime) { + this.requestTime = requestTime; + } + + + + public Integer getNextAction() { + return nextAction; + } + + public void setNextAction(Integer nextAction) { + this.nextAction = nextAction; + } + + public Boolean getIsConsumedByPollingWS() { + return isConsumedByPollingWS; + } + + public void setIsConsumedByPollingWS(Boolean isConsumedByPollingWS) { + this.isConsumedByPollingWS = isConsumedByPollingWS; + } + + public AuditLog getAuditLog() { + return auditLog; + } + + public void setAuditLog(AuditLog auditLog) { + this.auditLog = auditLog; + } + + public MachineCert getMachineCert() { + return machineCert; + } + + public void setMachineCert(MachineCert machineCert) { + this.machineCert = machineCert; + } + + public String getRequestHost() { + return requestHost; + } + + public void setRequestHost(String requestHost) { + this.requestHost = requestHost; + } + + public String getAnalysisRequest() { + return analysisRequest; + } + + public void setAnalysisRequest(String analysisRequest) { + this.analysisRequest = analysisRequest; + } + + public String getAnalysisResults() { + return analysisResults; + } + + public void setAnalysisResults(String analysisResults) { + this.analysisResults = analysisResults; + } + + public Long getThreshold() { + return threshold; + } + + public void setThreshold(Long threshold) { + this.threshold = threshold; + } + + public Date getExpirationTime() { + return expirationTime; + } + + public void setExpirationTime(Date expirationTime) { + this.expirationTime = expirationTime; + } + + public Date getLastReadTime() { + return lastReadTime; + } + + public void setLastReadTime(Date lastReadTime) { + this.lastReadTime = lastReadTime; + } + + public Long getCurrentProcessingTime() { + return currentProcessingTime; + } + + public void setCurrentProcessingTime(Long currentProcessingTime) { + this.currentProcessingTime = currentProcessingTime; + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/AuditLog.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/AuditLog.java new file mode 100644 index 0000000..db0785a --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/AuditLog.java @@ -0,0 +1,615 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser.hibernate.domain; + +import java.util.Date; + +/** + * Java class linked to the AuditLog table. + * @author syelama + * @version Crossbow + * + */ +public class AuditLog { + Long id; + String sid; + String machineName; + Date timestamp; + String pcr0; + String pcr1; + String pcr2; + String pcr3; + String pcr4; + String pcr5; + String pcr6; + String pcr7; + String pcr8; + String pcr9; + String pcr10; + String pcr11; + String pcr12; + String pcr13; + String pcr14; + String pcr15; + String pcr16; + String pcr17; + String pcr18; + String pcr19; + String pcr20; + String pcr21; + String pcr22; + String pcr23; + MachineCert machine; + String pcrSelect; + String nonce; + Boolean signatureVerified; + String report; + String previousDifferences; + String reportCompareErrors; + String validationErrors; + Long firstReport; + String pcrIMLMask; + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the sid + */ + public String getSid() { + return sid; + } + + /** + * @param sid the sid to set + */ + public void setSid(String sid) { + this.sid = sid; + } + + /** + * @return the machineName + */ + public String getMachineName() { + return machineName; + } + + /** + * @param machineName the machineName to set + */ + public void setMachineName(String machineName) { + this.machineName = machineName; + } + + /** + * @return the timestamp + */ + public Date getTimestamp() { + return timestamp; + } + + /** + * @param timestamp the timestamp to set + */ + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } + + /** + * @return the pcr0 + */ + public String getPcr0() { + return pcr0; + } + + /** + * @param pcr0 the pcr0 to set + */ + public void setPcr0(String pcr0) { + this.pcr0 = pcr0; + } + + /** + * @return the pcr1 + */ + public String getPcr1() { + return pcr1; + } + + /** + * @param pcr1 the pcr1 to set + */ + public void setPcr1(String pcr1) { + this.pcr1 = pcr1; + } + + /** + * @return the pcr2 + */ + public String getPcr2() { + return pcr2; + } + + /** + * @param pcr2 the pcr2 to set + */ + public void setPcr2(String pcr2) { + this.pcr2 = pcr2; + } + + /** + * @return the pcr3 + */ + public String getPcr3() { + return pcr3; + } + + /** + * @param pcr3 the pcr3 to set + */ + public void setPcr3(String pcr3) { + this.pcr3 = pcr3; + } + + /** + * @return the pcr4 + */ + public String getPcr4() { + return pcr4; + } + + /** + * @param pcr4 the pcr4 to set + */ + public void setPcr4(String pcr4) { + this.pcr4 = pcr4; + } + + /** + * @return the pcr5 + */ + public String getPcr5() { + return pcr5; + } + + /** + * @param pcr5 the pcr5 to set + */ + public void setPcr5(String pcr5) { + this.pcr5 = pcr5; + } + + /** + * @return the pcr6 + */ + public String getPcr6() { + return pcr6; + } + + /** + * @param pcr6 the pcr6 to set + */ + public void setPcr6(String pcr6) { + this.pcr6 = pcr6; + } + + /** + * @return the pcr7 + */ + public String getPcr7() { + return pcr7; + } + + /** + * @param pcr7 the pcr7 to set + */ + public void setPcr7(String pcr7) { + this.pcr7 = pcr7; + } + + /** + * @return the pcr8 + */ + public String getPcr8() { + return pcr8; + } + + /** + * @param pcr8 the pcr8 to set + */ + public void setPcr8(String pcr8) { + this.pcr8 = pcr8; + } + + /** + * @return the pcr9 + */ + public String getPcr9() { + return pcr9; + } + + /** + * @param pcr9 the pcr9 to set + */ + public void setPcr9(String pcr9) { + this.pcr9 = pcr9; + } + + /** + * @return the pcr10 + */ + public String getPcr10() { + return pcr10; + } + + /** + * @param pcr10 the pcr10 to set + */ + public void setPcr10(String pcr10) { + this.pcr10 = pcr10; + } + + /** + * @return the pcr11 + */ + public String getPcr11() { + return pcr11; + } + + /** + * @param pcr11 the pcr11 to set + */ + public void setPcr11(String pcr11) { + this.pcr11 = pcr11; + } + + /** + * @return the pcr12 + */ + public String getPcr12() { + return pcr12; + } + + /** + * @param pcr12 the pcr12 to set + */ + public void setPcr12(String pcr12) { + this.pcr12 = pcr12; + } + + /** + * @return the pcr13 + */ + public String getPcr13() { + return pcr13; + } + + /** + * @param pcr13 the pcr13 to set + */ + public void setPcr13(String pcr13) { + this.pcr13 = pcr13; + } + + /** + * @return the pcr14 + */ + public String getPcr14() { + return pcr14; + } + + /** + * @param pcr14 the pcr14 to set + */ + public void setPcr14(String pcr14) { + this.pcr14 = pcr14; + } + + /** + * @return the pcr15 + */ + public String getPcr15() { + return pcr15; + } + + /** + * @param pcr15 the pcr15 to set + */ + public void setPcr15(String pcr15) { + this.pcr15 = pcr15; + } + + /** + * @return the pcr16 + */ + public String getPcr16() { + return pcr16; + } + + /** + * @param pcr16 the pcr16 to set + */ + public void setPcr16(String pcr16) { + this.pcr16 = pcr16; + } + + /** + * @return the pcr17 + */ + public String getPcr17() { + return pcr17; + } + + /** + * @param pcr17 the pcr17 to set + */ + public void setPcr17(String pcr17) { + this.pcr17 = pcr17; + } + + /** + * @return the pcr18 + */ + public String getPcr18() { + return pcr18; + } + + /** + * @param pcr18 the pcr18 to set + */ + public void setPcr18(String pcr18) { + this.pcr18 = pcr18; + } + + /** + * @return the pcr19 + */ + public String getPcr19() { + return pcr19; + } + + /** + * @param pcr19 the pcr19 to set + */ + public void setPcr19(String pcr19) { + this.pcr19 = pcr19; + } + + /** + * @return the pcr20 + */ + public String getPcr20() { + return pcr20; + } + + /** + * @param pcr20 the pcr20 to set + */ + public void setPcr20(String pcr20) { + this.pcr20 = pcr20; + } + + /** + * @return the pcr21 + */ + public String getPcr21() { + return pcr21; + } + + /** + * @param pcr21 the pcr21 to set + */ + public void setPcr21(String pcr21) { + this.pcr21 = pcr21; + } + + /** + * @return the pcr22 + */ + public String getPcr22() { + return pcr22; + } + + /** + * @param pcr22 the pcr22 to set + */ + public void setPcr22(String pcr22) { + this.pcr22 = pcr22; + } + + /** + * @return the pcr23 + */ + public String getPcr23() { + return pcr23; + } + + /** + * @param pcr23 the pcr23 to set + */ + public void setPcr23(String pcr23) { + this.pcr23 = pcr23; + } + + /** + * @return the machine + */ + public MachineCert getMachine() { + return machine; + } + + /** + * @param machine the machine to set + */ + public void setMachine(MachineCert machine) { + this.machine = machine; + } + + /** + * @return the pcrSelect + */ + public String getPcrSelect() { + return pcrSelect; + } + + /** + * @param pcrSelect the pcrSelect to set + */ + public void setPcrSelect(String pcrSelect) { + this.pcrSelect = pcrSelect; + } + + /** + * @return the nonce + */ + public String getNonce() { + return nonce; + } + + /** + * @param nonce the nonce to set + */ + public void setNonce(String nonce) { + this.nonce = nonce; + } + + /** + * @return the signatureVerified + */ + public Boolean getSignatureVerified() { + return signatureVerified; + } + + /** + * @param signatureVerified the signatureVerified to set + */ + public void setSignatureVerified(Boolean signatureVerified) { + this.signatureVerified = signatureVerified; + } + + /** + * @return the report + */ + public String getReport() { + return report; + } + + /** + * @param report the report to set + */ + public void setReport(String report) { + this.report = report; + } + + /** + * @return the previousDifferences + */ + public String getPreviousDifferences() { + return previousDifferences; + } + + /** + * @param previousDifferences the previousDifferences to set + */ + public void setPreviousDifferences(String previousDifferences) { + this.previousDifferences = previousDifferences; + } + + /** + * @return the reportCompareErrors + */ + public String getReportCompareErrors() { + return reportCompareErrors; + } + + /** + * @param reportCompareErrors the reportCompareErrors to set + */ + public void setReportCompareErrors(String reportCompareErrors) { + this.reportCompareErrors = reportCompareErrors; + } + + /** + * @return the validationErrors + */ + public String getValidationErrors() { + return validationErrors; + } + + /** + * @param validationErrors the validationErrors to set + */ + public void setValidationErrors(String validationErrors) { + this.validationErrors = validationErrors; + } + + /** + * @return the firstReport + */ + public Long getFirstReport() { + return firstReport; + } + + /** + * @param firstReport the firstReport to set + */ + public void setFirstReport(Long firstReport) { + this.firstReport = firstReport; + } + + /** + * @return the pcrIMLMask + */ + public String getPcrIMLMask() { + return pcrIMLMask; + } + + /** + * @param pcrIMLMask the pcrIMLMask to set + */ + public void setPcrIMLMask(String pcrIMLMask) { + this.pcrIMLMask = pcrIMLMask; + } + +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/ComponentManifest.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/ComponentManifest.java new file mode 100644 index 0000000..80b5630 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/ComponentManifest.java @@ -0,0 +1,103 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 gov.niarl.hisAppraiser.hibernate.domain; + +import java.util.Date; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class ComponentManifest { + + private Long index; + + private String compName; + + private String compValue; + + private String compDesc; + + private Date createTime; + + private String createRequestHost; + + private Date lastUpdateTime; + + private String lastUpdateRequestHost; + + public Long getIndex() { + return index; + } + + public void setIndex(Long index) { + this.index = index; + } + + public String getCompName() { + return compName; + } + + public void setCompName(String compName) { + this.compName = compName; + } + + public String getCompValue() { + return compValue; + } + + public void setCompValue(String compValue) { + this.compValue = compValue; + } + + public String getCompDesc() { + return compDesc; + } + + public void setCompDesc(String compDesc) { + this.compDesc = compDesc; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public String getCreateRequestHost() { + return createRequestHost; + } + + public void setCreateRequestHost(String createRequestHost) { + this.createRequestHost = createRequestHost; + } + + public Date getLastUpdateTime() { + return lastUpdateTime; + } + + public void setLastUpdateTime(Date lastUpdateTime) { + this.lastUpdateTime = lastUpdateTime; + } + + public String getLastUpdateRequestHost() { + return lastUpdateRequestHost; + } + + public void setLastUpdateRequestHost(String lastUpdateRequestHost) { + this.lastUpdateRequestHost = lastUpdateRequestHost; + } + + +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/HOST.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/HOST.java new file mode 100644 index 0000000..024ed20 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/HOST.java @@ -0,0 +1,79 @@ +package gov.niarl.hisAppraiser.hibernate.domain; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement + +public class HOST { + private Long ID; + private String HostName; + private String IPAddress; + private String Port; + private String Email; + private String AddOn_Connection_String; + private String Description; + private String pcrIMLMask; + public Long getID() { + return ID; + } + public void setID(Long iD) { + ID = iD; + } + public String getHostName() { + return HostName; + } + + @XmlElement(name = "HostName") + public void setHostName(String hostName) { + HostName = hostName; + } + public String getIPAddress() { + return IPAddress; + } + + @XmlElement(name = "IPAddress") + public void setIPAddress(String iPAddress) { + IPAddress = iPAddress; + } + public String getPort() { + return Port; + } + + @XmlElement(name = "Port") + public void setPort(String port) { + Port = port; + } + public String getEmail() { + return Email; + } + + @XmlElement(name = "Email") + public void setEmail(String email) { + Email = email; + } + public String getAddOn_Connection_String() { + return AddOn_Connection_String; + } + + @XmlElement(name = "AddOn_Connection_String") + public void setAddOn_Connection_String(String addOn_Connection_String) { + AddOn_Connection_String = addOn_Connection_String; + } + public String getDescription() { + return Description; + } + + @XmlElement(name = "Description") + public void setDescription(String description) { + Description = description; + } + public String getPcrIMLMask() { + return pcrIMLMask; + } + + @XmlElement(name="pcrIMLMask") + public void setPcrIMLMask(String pcrIMLMask) { + this.pcrIMLMask = pcrIMLMask; + } +} \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/HOST_MLE.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/HOST_MLE.java new file mode 100644 index 0000000..3a55aa0 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/HOST_MLE.java @@ -0,0 +1,30 @@ +package gov.niarl.hisAppraiser.hibernate.domain; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class HOST_MLE { + private Long ID; + private HOST host; + private MLE mle; + + public Long getID() { + return ID; + } + public void setID(Long iD) { + ID = iD; + } + public HOST getHost() { + return host; + } + public void setHost(HOST host) { + this.host = host; + } + public MLE getMle() { + return mle; + } + public void setMle(MLE mle) { + this.mle = mle; + } + +} \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/MLE.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/MLE.java new file mode 100644 index 0000000..42972de --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/MLE.java @@ -0,0 +1,87 @@ +package gov.niarl.hisAppraiser.hibernate.domain; + + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import java.util.Set; + +@XmlRootElement +public class MLE { + + private Long MLEID; + private String Name; + private String Version; + private OEM oem; + private OS os; + private String Attestation_Type; + private String MLE_Type; + private String Description; + + public Long getMLEID() { + return MLEID; + } + + public void setMLEID(Long mLEID) { + MLEID = mLEID; + } + + public String getName() { + return Name; + } + + @XmlElement(name = "Name") + public void setName(String name) { + Name = name; + } + + public String getVersion() { + return Version; + } + + @XmlElement(name = "Version") + public void setVersion(String version) { + Version = version; + } + + public OEM getOem() { + return oem; + } + + public void setOem(OEM oem) { + this.oem = oem; + } + + public OS getOs() { + return os; + } + + public void setOs(OS os) { + this.os = os; + } + + public String getAttestation_Type() { + return Attestation_Type; + } + + @XmlElement(name = "Attestation_Type") + public void setAttestation_Type(String attestation_Type) { + Attestation_Type = attestation_Type; + } + + public String getMLE_Type() { + return MLE_Type; + } + + @XmlElement(name = "MLE_Type") + public void setMLE_Type(String mLE_Type) { + MLE_Type = mLE_Type; + } + + public String getDescription() { + return Description; + } + @XmlElement(name = "Description") + public void setDescription(String description) { + Description = description; + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/MachineCert.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/MachineCert.java new file mode 100644 index 0000000..ce1f818 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/MachineCert.java @@ -0,0 +1,184 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser.hibernate.domain; + +import java.util.Date; + +/** + * Java class linked to the MachineCert table. + * @author syelama + * @version Crossbow + * + */ +public class MachineCert { + /** + * Central location to set the machine name linked to the privacy CA + */ + public static final String PRIVACY_CA_NAME = "_privacyca"; + + Long id; + String machineName; + String certificate; + Boolean active; + Date timestamp; + MachineCert privacyCaMachineCert; + Date lastPoll; + Integer nextAction; + String pollArgs; + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the machineName + */ + public String getMachineName() { + return machineName; + } + + /** + * @param machineName the machineName to set + */ + public void setMachineName(String machineName) { + this.machineName = machineName; + } + + /** + * @return the certificate + */ + public String getCertificate() { + return certificate; + } + + /** + * @param certificate the certificate to set + */ + public void setCertificate(String certificate) { + this.certificate = certificate; + } + + /** + * @return the active + */ + public Boolean getActive() { + return active; + } + + /** + * @param active the active to set + */ + public void setActive(Boolean active) { + this.active = active; + } + + /** + * @return the timestamp + */ + public Date getTimestamp() { + return timestamp; + } + + /** + * @param timestamp the timestamp to set + */ + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } + + /** + * @return the privacyCaMachineCert + */ + public MachineCert getPrivacyCaMachineCert() { + return privacyCaMachineCert; + } + + /** + * @param privacyCaMachineCert the privacyCaMachineCert to set + */ + public void setPrivacyCaMachineCert(MachineCert privacyCaMachineCert) { + this.privacyCaMachineCert = privacyCaMachineCert; + } + + /** + * @return the lastPoll + */ + public Date getLastPoll() { + return lastPoll; + } + + /** + * @param lastPoll the lastPoll to set + */ + public void setLastPoll(Date lastPoll) { + this.lastPoll = lastPoll; + } + + /** + * @return the nextAction + */ + public Integer getNextAction() { + return nextAction; + } + + /** + * @param nextAction the nextAction to set + */ + public void setNextAction(Integer nextAction) { + this.nextAction = nextAction; + } + + /** + * @return the pollArgs + */ + public String getPollArgs() { + return pollArgs; + } + + /** + * @param pollArgs the pollArgs to set + */ + public void setPollArgs(String pollArgs) { + this.pollArgs = pollArgs; + } +} \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/MeasureLog.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/MeasureLog.java new file mode 100644 index 0000000..15631e6 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/MeasureLog.java @@ -0,0 +1,48 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 gov.niarl.hisAppraiser.hibernate.domain; + +public class MeasureLog { + + private Long id; + + private AuditLog auditLog; + + private Integer txtStatus; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public AuditLog getAuditLog() { + return auditLog; + } + + public void setAuditLog(AuditLog auditLog) { + this.auditLog = auditLog; + } + + public Integer getTxtStatus() { + return txtStatus; + } + + public void setTxtStatus(Integer txtStatus) { + this.txtStatus = txtStatus; + } + + +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/Module.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/Module.java new file mode 100644 index 0000000..d614809 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/Module.java @@ -0,0 +1,68 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 gov.niarl.hisAppraiser.hibernate.domain; + + +public class Module { + + private Long id; + + private MeasureLog measureLog; + + private String moduleName; + + private String moduleValue; + + private Integer pcrNumber; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public MeasureLog getMeasureLog() { + return measureLog; + } + + public void setMeasureLog(MeasureLog measureLog) { + this.measureLog = measureLog; + } + + public String getModuleName() { + return moduleName; + } + + public void setModuleName(String moduleName) { + this.moduleName = moduleName; + } + + public String getModuleValue() { + return moduleValue; + } + + public void setModuleValue(String moduleValue) { + this.moduleValue = moduleValue; + } + + public Integer getPcrNumber() { + return pcrNumber; + } + + public void setPcrNumber(Integer pcrNumber) { + this.pcrNumber = pcrNumber; + } + +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/OEM.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/OEM.java new file mode 100644 index 0000000..7a7a8f2 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/OEM.java @@ -0,0 +1,74 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 gov.niarl.hisAppraiser.hibernate.domain; + +import javax.xml.bind.annotation.XmlRootElement; + +import javax.xml.bind.annotation.XmlElement; + +/** + * Java class linked to the PCR_manifest table. + * @author intel + * @version OpenAttestation + * + */ + +@XmlRootElement + +public class OEM { + Long OEMID; + String Name; + String Description; + + public OEM(){} + + public OEM(Long ID, String name, String desc){ + this.Name = name; + this.Description = desc; + } + + public Long getOEMID() { + return OEMID; + } + + public void setOEMID(Long id) { + OEMID = id; + } + + public String getName() { + return Name; + } + + @XmlElement(name = "Name") + public void setName(String name) { + Name = name; + } + + public String getDescription() { + return Description; + } + + @XmlElement(name = "Description") + public void setDescription(String desc) { + Description = desc; + } + + /** + * validate + * @return + */ + public String validateDataFormat(){ + return ""; + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/OS.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/OS.java new file mode 100644 index 0000000..cc41e23 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/OS.java @@ -0,0 +1,84 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 gov.niarl.hisAppraiser.hibernate.domain; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * Java class linked to the PCR_manifest table. + * @author intel + * @version OpenAttestation + * + */ + +@XmlRootElement + +public class OS { + Long ID; + String Name; + String Version; + String Description; + + public OS(){} + + public OS(Long ID, String name, String version, String desc){ + this.Name = name; + this.Version = version; + this.Description = desc; + } + + public Long getID() { + return ID; + } + + public void setID(Long id) { + ID = id; + } + + public String getName() { + return Name; + } + + @XmlElement(name = "Name") + public void setName(String name) { + Name = name; + } + + public String getVersion() { + return Version; + } + + @XmlElement(name = "Version") + public void setVersion(String version) { + Version = version; + } + + public String getDescription() { + return Description; + } + + @XmlElement(name = "Description") + public void setDescription(String desc) { + Description = desc; + } + + /** + * validate + * @return + */ + public String validateDataFormat(){ + return ""; + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/PCRManifest.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/PCRManifest.java new file mode 100644 index 0000000..d478599 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/PCRManifest.java @@ -0,0 +1,129 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 gov.niarl.hisAppraiser.hibernate.domain; + +import java.util.Date; + +import javax.xml.bind.annotation.XmlRootElement; + +/** + * Java class linked to the PCR_manifest table. + * @author intel + * @version OpenAttestation + * + */ + +@XmlRootElement + +public class PCRManifest { + Long index; + Integer PCRNumber; + String PCRValue; + String PCRDesc; + Date createTime; + String createRequestHost; + Date lastUpdateTime; + String lastUpdateRequestHost; + + public PCRManifest(){} + + public PCRManifest(Long index){ + this.index = index; + } + + public PCRManifest(Long index, Integer number, String value, String desc, Date createTime, + String createRequestHost, Date lastUpdateTime, String lastUpdateRequestHost){ + this.index = index; + this.PCRNumber = number; + this.PCRValue = value; + this.PCRDesc = desc; + this.createTime = createTime; + this.createRequestHost = createRequestHost; + this.lastUpdateTime = lastUpdateTime; + this.lastUpdateRequestHost = lastUpdateRequestHost; + } + + public Long getIndex() { + return index; + } + + public void setIndex(Long index) { + this.index = index; + } + + public Integer getPCRNumber() { + return PCRNumber; + } + + public void setPCRNumber(Integer pCRNumber) { + PCRNumber = pCRNumber; + } + + public String getPCRValue() { + return PCRValue; + } + + public void setPCRValue(String pCRValue) { + PCRValue = pCRValue; + } + + public String getPCRDesc() { + return PCRDesc; + } + + public void setPCRDesc(String pCRDesc) { + PCRDesc = pCRDesc; + } + + public Date getCreateTime() { + return createTime; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getLastUpdateTime() { + return lastUpdateTime; + } + + public void setLastUpdateTime(Date lastUpdateTime) { + this.lastUpdateTime = lastUpdateTime; + } + + + public String getCreateRequestHost() { + return createRequestHost; + } + + public void setCreateRequestHost(String createRequestHost) { + this.createRequestHost = createRequestHost; + } + + public String getLastUpdateRequestHost() { + return lastUpdateRequestHost; + } + + public void setLastUpdateRequestHost(String lastUpdateRequestHost) { + this.lastUpdateRequestHost = lastUpdateRequestHost; + } + + /** + * validate + * @return + */ + public String validateDataFormat(){ + return ""; + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/PcrWhiteList.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/PcrWhiteList.java new file mode 100644 index 0000000..b71e1a6 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/PcrWhiteList.java @@ -0,0 +1,46 @@ +package gov.niarl.hisAppraiser.hibernate.domain; + +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement + +public class PcrWhiteList { + + private Long PcrWhiteListID; + private String pcrName; + private String pcrDigest; + private MLE mle; + + public Long getPcrWhiteListID() { + return PcrWhiteListID; + } + + public void setPcrWhiteListID(Long pcrWhiteListID) { + PcrWhiteListID = pcrWhiteListID; + } + + public String getPcrName() { + return pcrName; + } + + public void setPcrName(String pcrName) { + this.pcrName = pcrName; + } + + public String getPcrDigest() { + return pcrDigest; + } + + public void setPcrDigest(String pcrDigest) { + this.pcrDigest = pcrDigest; + } + + public MLE getMle() { + return mle; + } + + public void setMle(MLE mle) { + this.mle = mle; + } + +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/SystemConstants.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/SystemConstants.java new file mode 100644 index 0000000..4dc5026 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/SystemConstants.java @@ -0,0 +1,102 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser.hibernate.domain; + +/** + * Java class linked to the MachineCert table. + * @author syelama + * @version Crossbow + * + */ +public class SystemConstants { + Long id; + String keyId; + String value; + String description; + + /** + * @return the id + */ + public Long getId() { + return id; + } + + /** + * @param id the id to set + */ + public void setId(Long id) { + this.id = id; + } + + /** + * @return the keyId + */ + public String getKeyId() { + return keyId; + } + + /** + * @param keyId the keyId to set + */ + public void setKeyId(String keyId) { + this.keyId = keyId; + } + + /** + * @return the value + */ + public String getValue() { + return value; + } + + /** + * @param value the value to set + */ + public void setValue(String value) { + this.value = value; + } + + /** + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * @param description the description to set + */ + public void setDescription(String description) { + this.description = description; + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/TxtLog.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/TxtLog.java new file mode 100644 index 0000000..2a91eea --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/TxtLog.java @@ -0,0 +1,150 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 gov.niarl.hisAppraiser.hibernate.domain; + +public class TxtLog { + + private Long id; + + private MeasureLog measureLog; + + private String osSinitDataCapabilities; + + private Integer version; + + private String sinitHash; + + private String edxSenterFlags; + + private String biosAcmId; + + private String msegValid; + + private String stmHash; + + private String policyControl; + + private String lcpPolicyHash; + + private String processorScrTmStatus; + + private String mleHash; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public MeasureLog getMeasureLog() { + return measureLog; + } + + public void setMeasureLog(MeasureLog measureLog) { + this.measureLog = measureLog; + } + + public String getOsSinitDataCapabilities() { + return osSinitDataCapabilities; + } + + public void setOsSinitDataCapabilities(String osSinitDataCapabilities) { + this.osSinitDataCapabilities = osSinitDataCapabilities; + } + + public Integer getVersion() { + return version; + } + + public void setVersion(Integer version) { + this.version = version; + } + + public String getSinitHash() { + return sinitHash; + } + + public void setSinitHash(String sinitHash) { + this.sinitHash = sinitHash; + } + + public String getEdxSenterFlags() { + return edxSenterFlags; + } + + public void setEdxSenterFlags(String edxSenterFlags) { + this.edxSenterFlags = edxSenterFlags; + } + + public String getBiosAcmId() { + return biosAcmId; + } + + public void setBiosAcmId(String biosAcmId) { + this.biosAcmId = biosAcmId; + } + + public String getMsegValid() { + return msegValid; + } + + public void setMsegValid(String msegValid) { + this.msegValid = msegValid; + } + + public String getStmHash() { + return stmHash; + } + + public void setStmHash(String stmHash) { + this.stmHash = stmHash; + } + + public String getPolicyControl() { + return policyControl; + } + + public void setPolicyControl(String policyControl) { + this.policyControl = policyControl; + } + + public String getLcpPolicyHash() { + return lcpPolicyHash; + } + + public void setLcpPolicyHash(String lcpPolicyHash) { + this.lcpPolicyHash = lcpPolicyHash; + } + + public String getProcessorScrTmStatus() { + return processorScrTmStatus; + } + + public void setProcessorScrTmStatus(String processorScrTmStatus) { + this.processorScrTmStatus = processorScrTmStatus; + } + + public String getMleHash() { + return mleHash; + } + + public void setMleHash(String mleHash) { + this.mleHash = mleHash; + } + + + + +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/package-info.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/package-info.java new file mode 100644 index 0000000..556ae65 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/domain/package-info.java @@ -0,0 +1,6 @@ +/** + * This package holds domain objects for hibernate + * + * @version Crossbow + */ +package gov.niarl.hisAppraiser.hibernate.domain; \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/HOST.hbm.xml b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/HOST.hbm.xml new file mode 100644 index 0000000..92669bd --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/HOST.hbm.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/HOST_MLE.hbm.xml b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/HOST_MLE.hbm.xml new file mode 100644 index 0000000..b84d2bd --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/HOST_MLE.hbm.xml @@ -0,0 +1,12 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/MLE.hbm.xml b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/MLE.hbm.xml new file mode 100644 index 0000000..b06f626 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/MLE.hbm.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/OEM.hbm.xml b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/OEM.hbm.xml new file mode 100644 index 0000000..1f7f0a0 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/OEM.hbm.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/OS.hbm.xml b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/OS.hbm.xml new file mode 100644 index 0000000..ddc4e05 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/OS.hbm.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/PcrWhiteList.hbm.xml b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/PcrWhiteList.hbm.xml new file mode 100644 index 0000000..3491454 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/PcrWhiteList.hbm.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/alerts.hbm.xml b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/alerts.hbm.xml new file mode 100644 index 0000000..34f0a7f --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/alerts.hbm.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/analysisTypes.hbm.xml b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/analysisTypes.hbm.xml new file mode 100644 index 0000000..6c71d08 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/analysisTypes.hbm.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/attestRequest.hbm.xml b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/attestRequest.hbm.xml new file mode 100644 index 0000000..3a6b2dc --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/attestRequest.hbm.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/audit_log.hbm.xml b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/audit_log.hbm.xml new file mode 100644 index 0000000..fa7b963 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/audit_log.hbm.xml @@ -0,0 +1,48 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/machine_cert.hbm.xml b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/machine_cert.hbm.xml new file mode 100644 index 0000000..c42c3f9 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/machine_cert.hbm.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/measure_log.hbm.xml b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/measure_log.hbm.xml new file mode 100644 index 0000000..96294b3 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/measure_log.hbm.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/module.hbm.xml b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/module.hbm.xml new file mode 100644 index 0000000..c1fd081 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/module.hbm.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/system_constants.hbm.xml b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/system_constants.hbm.xml new file mode 100644 index 0000000..874c2fc --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/system_constants.hbm.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/txt_log.hbm.xml b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/txt_log.hbm.xml new file mode 100644 index 0000000..11175f2 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/mapping/txt_log.hbm.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/AttestService.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/AttestService.java new file mode 100644 index 0000000..b1746fb --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/AttestService.java @@ -0,0 +1,369 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 gov.niarl.hisAppraiser.hibernate.util; +import gov.niarl.hisAppraiser.hibernate.dao.AnalysisTypesDao; +import gov.niarl.hisAppraiser.hibernate.dao.AttestDao; +import gov.niarl.hisAppraiser.hibernate.dao.OSDao; +import gov.niarl.hisAppraiser.hibernate.domain.AnalysisTypes; +import gov.niarl.hisAppraiser.hibernate.domain.AttestRequest; +import gov.niarl.hisAppraiser.hibernate.domain.AuditLog; +import gov.niarl.hisAppraiser.hibernate.domain.PCRManifest; +import gov.niarl.hisAppraiser.hibernate.domain.PcrWhiteList; +import gov.niarl.hisAppraiser.hibernate.util.ResultConverter.AttestResult; +import gov.niarl.hisAppraiser.util.HisUtil; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; + +import javax.ws.rs.core.GenericEntity; + +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; + +public class AttestService { + + /** + * Reads the list of analyses requested within the attestation + * request received and executes them. + * @param attestRequest The attestation request to be fulfilled + * @return The attestation request received, updated with analyses + * result. + */ + public static AttestRequest doAnalyses(AttestRequest attestRequest, String machineName) { + System.out.println("here is in the do analysis script, this is the machine name " + machineName); + String analysisReqString = "VALIDATE_PCR;COMPARE_REPORT"; + if (attestRequest.getAnalysisRequest() != null) { + analysisReqString = attestRequest.getAnalysisRequest(); + } + + String[] analysisReqList = analysisReqString.split(";"); + for (String analysis : analysisReqList) { + if (analysis.length() == 0 && analysisReqList.length == 1) { + break; + } else if (analysis.equals("VALIDATE_PCR")) { + attestRequest = validatePCRReport(attestRequest, machineName); + } else if (analysis.equals("COMPARE_REPORT")) { + attestRequest = evaluateCompareReport(attestRequest); + } else { + attestRequest = analysisLauncher(attestRequest, analysis); + } + } + + System.out.println("here is in the end of do analysis script, this is the analysisReqString " + analysisReqString); + return attestRequest; + } + + /** + * Executes the received analysis, writing thier result in the + * received AttestRequest + * @param attestRequest The AttestRequest to be updated + * @param analysis The analysis to be executed + * @return The updated AttestRequest + */ + public static AttestRequest analysisLauncher(AttestRequest attestRequest, String analysis) { + OSDao osDao = new OSDao(); + boolean analysisResult = false; + String analysisStatus = "ANALYSIS_COMPLETED"; + String analysisOutput = ""; + String analysisName = analysis.split(",")[0].trim(); + String analysisParameters = ""; + String os_name = osDao.findHostOS(attestRequest.getHostName()); + AnalysisTypesDao ATDao = new AnalysisTypesDao(); + AnalysisTypes analysisType = ATDao.getAnalysisTypeByName(analysisName); + + if (analysisType == null) { + attestRequest = updateAnalysisResult(attestRequest, "NULL", false, "ANALYSIS_NOT_FOUND", ""); + attestRequest.setResult(ResultConverter.getIntFromResult(AttestResult.UN_TRUSTED)); + return attestRequest; + } + + try { + if (os_name == null) + throw new Exception ("Error occurred retrieving OS name"); + + if (analysis.indexOf(',') != -1) { + analysisParameters = analysis.substring(analysis.indexOf(',') + 1); + } + + int intParamPcrMask = -1; + for (String parameter : analysisParameters.split(",")) { + if (!parameter.startsWith("pcrs=")) + continue; + + intParamPcrMask = 0; + + for (String pcr : parameter.substring("pcrs=".length()).split("\\|")) { + if (pcr.trim().equals("")) + continue; + int intPcr; + try { + intPcr = Integer.parseInt(pcr.trim()); + } catch (Exception e) { + throw new IllegalArgumentException("Wrong syntax: requested PCRs are not integers"); + } + if (intPcr < 0 || intPcr > 23) + throw new IllegalArgumentException("Wrong syntax: requested PCRs not in the allowed range [0-23]"); + intParamPcrMask |= (0x00800000 >> intPcr); + } + break; + } + + byte[] requiredPcrMask = HisUtil.unHexString(analysisType.getRequiredPcrMask()); + int intRequiredPcrMask = (requiredPcrMask[2] & 0xFF) | ((requiredPcrMask[1] & 0xFF) << 8) | ((requiredPcrMask[0] & 0xFF) << 16); + + byte[] pcrIMLMask = HisUtil.unHexString(new AttestDao().getPcrIMLMask(attestRequest.getHostName())); + int intPcrIMLMask = (pcrIMLMask[2] & 0xFF) | ((pcrIMLMask[1] & 0xFF) << 8) | ((pcrIMLMask[0] & 0xFF) << 16); + + /* + * If the request does not contain the "pcrs" parameter + * the entire list of PCRs from requiredPcrMask is assumed + * to be requested by the analysis. + */ + if (intParamPcrMask == -1) + intParamPcrMask = intRequiredPcrMask; + else if ((intParamPcrMask | intRequiredPcrMask) != intRequiredPcrMask) + throw new UnsupportedOperationException("PCRs specified as parameter are not in the set of PCRs required by the analysis"); + if ((intParamPcrMask | intPcrIMLMask) != intPcrIMLMask) + throw new UnsupportedOperationException("The host does not provide the complete logs (IML) for requested PCRs"); + + AttestUtil.loadProp(); + String path = System.getenv("PATH"); + String[] env_var = { "PATH=" + path, "ANALYSIS=" + analysisType.getName() + "," + analysisParameters, "OS=" + os_name, + "URL=" + AttestUtil.getDownloadIRWebServiceUrl(), "IR=" + attestRequest.getAuditLog().getId()}; + Runtime r = Runtime.getRuntime(); + String script_string = analysisType.getURL(); + System.out.println("here is in the do analysis launcher, this is the script_string " + script_string); + System.out.println("here is in the do analysis launcher function after the exec call, this is the analysis " + analysisType.getName()); + Process p = r.exec(script_string, env_var); + + for (String variabl : env_var) { + + System.out.println("here is in the do analysis launcher function after the exec call, this is the variables" + variabl); + } + + String currentLine; + BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); + + while((currentLine = br.readLine()) != null){ + + System.out.println("here is in after get BufferedReader " + currentLine); + } + BufferedReader brerr = new BufferedReader(new InputStreamReader(p.getErrorStream())); + + while((currentLine = brerr.readLine()) != null){ + System.out.println("here is in after get BufferedReader Error " + currentLine); + } + + int exitCode = p.waitFor(); + + System.out.println("here is in after exitCode " + exitCode); + + + String line = ""; + analysisOutput = ""; + + System.out.println("here is in the middle of nowhere " ); + + while ((line = br.readLine()) != null) { + analysisOutput += line + "\n"; + System.out.println("here is in the do analysis launcher function after the exec call, this is the line" + line); + } + + System.out.println("here is in the do analysis launcher function after the exec call, this isanalysisOutput" + analysisOutput); + + analysisOutput = analysisOutput.substring(0, Math.min(analysisOutput.length(), 80)); + + analysisOutput = analysisOutput.trim(); + if (exitCode == 0) { + analysisResult = true; + } else if (exitCode != 1) { + analysisStatus = "SCRIPT_ERROR"; + + System.out.println("error: External analysis tool returned error code " + exitCode); + System.out.println("\tAnalysis tool output: " + analysisOutput.replace("\n", " \\n ")); + } + } catch (Exception e) { + if (e instanceof IOException) + System.out.println("IO error executing analysis: " + e.getMessage()); + else + System.out.println("Error executing analysis: " + e.getMessage()); + + analysisResult = false; + analysisStatus = "OAT_ERROR"; + analysisOutput = ""; + + if (e instanceof UnsupportedOperationException || e instanceof IllegalArgumentException) + analysisOutput = e.getMessage(); + } + + if (!analysisResult) + attestRequest.setResult(ResultConverter.getIntFromResult(AttestResult.UN_TRUSTED)); + + attestRequest = updateAnalysisResult(attestRequest, "DB:" + analysisType.getId().toString(), + analysisResult, analysisStatus, analysisOutput); + return attestRequest; + } + + /** + * Verifies if any errors occurred during the report comparison. + * It updates the fields Result and analysisResults of the recevied + * attestRequest and returns the updated object. + * @param attestRequest The attestation request to be analysed + * @return The updated attestRequest + */ + public static AttestRequest evaluateCompareReport(AttestRequest attestRequest) { + boolean analysisResult = false; + String analysisOutput = ""; + AuditLog auditLog = attestRequest.getAuditLog(); + if (auditLog != null && attestRequest.getIsConsumedByPollingWS()) { + if (auditLog.getReportCompareErrors() != null) { + analysisOutput = auditLog.getReportCompareErrors().trim(); + } else { + analysisResult = true; + } + } else { + analysisOutput = "Analysis requested for a not valid report"; + } + + if (!analysisResult) { + attestRequest.setResult(ResultConverter.getIntFromResult(AttestResult.UN_TRUSTED)); + } + attestRequest = updateAnalysisResult(attestRequest, "COMPARE_REPORT", analysisResult, "ANALYSIS_COMPLETED", analysisOutput); + return attestRequest; + } + + /** + * validate PCR value of a request. Here is 4 cases, that is timeout, unknown, trusted and untrusted. + * case1 (timeout): attest's time is greater than default timeout of attesting from OpenAttestation.properties. In generally, it is usually set as 60 seconds; + * case2 (unknown): machine is not enrolled in attest server. Just check whether active machineCert is existed. + * case3 (trusted): all hosts has attested and their pcrs has matched with PCRManifest table; + * case4 (untrusted): all hosts has attested, but their pcrs cannot match with PCRManifest table. + * @param attestRequest of intending to validate. + * @return + */ + public static AttestRequest validatePCRReport(AttestRequest attestRequest,String machineNameInput){ + String analysisOutput = ""; + attestRequest.getAuditLog(); + List whiteList = new ArrayList(); + AttestDao dao = new AttestDao(); + boolean flag = true; + whiteList = dao.getPcrValue(machineNameInput); + + System.out.println(attestRequest.getId() +":" +attestRequest.getAuditLog().getId()); + + if(attestRequest.getAuditLog()!= null && attestRequest.getIsConsumedByPollingWS()){ + + AuditLog auditLog = attestRequest.getAuditLog(); + HashMap pcrs = new HashMap(); + pcrs = generatePcrsByAuditId(auditLog); + + if (whiteList!=null && whiteList.size() != 0){ + for(int i=0; i. + * A request may contain several pcrs, so needs parse a List of PCRmanifest. + * @Return null string if PCR not exists, else not null string + * with different pcrs' number and separating them with '|' like this '2|20' + */ + public static String compareManifestPCR(List manifestPcrs){ + GenericEntity> entity = new GenericEntity>(manifestPcrs) {}; + AttestUtil.loadProp(); + //manifestPcrs. + WebResource resource = AttestUtil.getClient(AttestUtil.getManifestWebServicesUrl()); + ClientResponse res = resource.path("/Validate").type("application/json"). + accept("application/json").post(ClientResponse.class,entity); + return res.getEntity(String.class); + } + + + /** + * generate a hashMap of pcrs for a given auditlog. The hashMap key is pcr's number and value is pcr's value. + * @param auditlog of interest + * @return contain key-values of pcrs like {<'1','11111111111'>,<'2','111111111111111111111'>,...} + */ + public static HashMap generatePcrsByAuditId(AuditLog auditlog){ + HashMap pcrs = new HashMap(); + pcrs.put(0, auditlog.getPcr0()); + pcrs.put(1, auditlog.getPcr1()); + pcrs.put(2, auditlog.getPcr2()); + pcrs.put(3, auditlog.getPcr3()); + pcrs.put(4, auditlog.getPcr4()); + pcrs.put(5, auditlog.getPcr5()); + pcrs.put(6, auditlog.getPcr6()); + pcrs.put(7, auditlog.getPcr7()); + pcrs.put(8, auditlog.getPcr8()); + pcrs.put(9, auditlog.getPcr9()); + pcrs.put(10, auditlog.getPcr10()); + pcrs.put(11, auditlog.getPcr11()); + pcrs.put(12, auditlog.getPcr12()); + pcrs.put(13, auditlog.getPcr13()); + pcrs.put(14, auditlog.getPcr14()); + pcrs.put(15, auditlog.getPcr15()); + pcrs.put(16, auditlog.getPcr16()); + pcrs.put(17, auditlog.getPcr17()); + pcrs.put(18, auditlog.getPcr18()); + pcrs.put(19, auditlog.getPcr19()); + pcrs.put(20, auditlog.getPcr20()); + pcrs.put(21, auditlog.getPcr21()); + pcrs.put(22, auditlog.getPcr22()); + pcrs.put(23, auditlog.getPcr23()); + return pcrs; + } + +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/AttestUtil.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/AttestUtil.java new file mode 100644 index 0000000..43cc8fd --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/AttestUtil.java @@ -0,0 +1,169 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 gov.niarl.hisAppraiser.hibernate.util; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; +import java.util.SortedSet; +import java.util.TreeSet; +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.api.client.config.DefaultClientConfig; + +import gov.niarl.hisAppraiser.Constants; +import gov.niarl.hisAppraiser.integrityReport.HisReportValidator; +import gov.niarl.hisAppraiser.util.AlertConfiguration; +import gov.niarl.hisAppraiser.util.HisUtil; + +public class AttestUtil { + + private static String manifestWSURL =""; + private static String trustStorePath = ""; + private static String downloadIRWebServiceUrl = ""; + private static double anticipationFactor = 0; + private static long maxIdleTime = 0; + private static long minAttestInterval = 0; + + private static String PROPERTIES_NAME = "OpenAttestation.properties"; + private static Properties attestationProperties = new Properties(); + + public static void loadProp(){ + FileInputStream attestationPropertyFile = null; + try { + String path = AttestUtil.class.getClassLoader().getResource("/").getPath(); + String configPath = "/etc/oat-appraiser/"; + attestationPropertyFile = new FileInputStream(configPath +PROPERTIES_NAME); + attestationProperties.load(attestationPropertyFile); + String manifesturl = attestationProperties.getProperty("ManifestWebServicesUrl"); + String truststore = attestationProperties.getProperty("TrustStore"); + String downloadWS = attestationProperties.getProperty("DownloadIRWebServiceUrl"); + String anticipation = attestationProperties.getProperty("anticipationFactor"); + String idleTime = attestationProperties.getProperty("maxIdleTime"); + String attestInterval = attestationProperties.getProperty("minAttestInterval"); + manifestWSURL = manifesturl == null ? "":manifesturl; + trustStorePath =truststore == null? "":truststore; + downloadIRWebServiceUrl = (downloadWS == null) ? "" : downloadWS; + anticipationFactor = (anticipation == null) ? 1.5 : Double.parseDouble(anticipation); + maxIdleTime = (idleTime == null) ? 7 : Integer.parseInt(idleTime); + minAttestInterval = (attestInterval == null) ? 300000 : Integer.parseInt(attestInterval); + } + catch (IOException e) { + e.printStackTrace(); + } + finally{ + try { + if (attestationPropertyFile != null) + attestationPropertyFile.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + } + + public static String getManifestWebServicesUrl(){ + AttestUtil.loadProp(); + return manifestWSURL; + } + + public static String getTrustStore(){ + return trustStorePath; + } + + public static String getDownloadIRWebServiceUrl(){ + return downloadIRWebServiceUrl; + } + + public static double getAnticipationFactor(){ + return anticipationFactor; + } + + public static long getMaxIdleTime(){ + return maxIdleTime; + } + + public static long getMinAttestInterval(){ + return minAttestInterval; + } + + public static WebResource getClient(String url){ + if (url.startsWith("https")){ + System.setProperty("javax.net.ssl.trustStore", trustStorePath); + } + ClientConfig config = new DefaultClientConfig(); + WebResource resource = Client.create(config).resource(url); + return resource; + } + + + public static synchronized String generateRequestId(String label){ + byte[] nonce = HisUtil.generateSecureRandom(16); + return label+ HisUtil.hexString(nonce); + } + + + /** + * get validated pcrs from HIS.properties + * @return + */ + public static ArrayList generatePcrValidatedPositions(){ + List pcrs = new ArrayList(); + AlertConfiguration alertConfiguration = Constants.ALERT_CONFIGURATION; + for (int i = 0; i < 24; i++) { + if (alertConfiguration.getPcrAlerts(i)) { + pcrs.add(i); + } + } + return (ArrayList) pcrs; + } + + public static ArrayList generatePcrSelectedPositions(String PCRMask){ + ArrayList arrayList = new ArrayList(); + PCRMask = PCRMask.length() %2 !=0 ? "0" + PCRMask : PCRMask; + byte[] bytes= HisUtil.unHexString(PCRMask); + for (int i = 0; i < bytes.length; i++) { + for (Integer integer : AttestUtil.getSelectedPCR(bytes[bytes.length -i-1])) { + arrayList.add(integer + (i * 8)); + } + } + return arrayList; + } + + + /** + * Get the sorted selected positions in a byte with the right most + * position as zero. + * @param input Byte to be evaluated + * @return Array of integer positions. + */ + public static SortedSet getSelectedPCR(byte input) { + ArrayList arrayList = new ArrayList(); + byte mask = 0x01; + for (int i = 0; i <= 7; i++) { + int value = (input >>> i) & mask; + if (value == 1) { + arrayList.add(i); + } + } + Collections.sort(arrayList); + return Collections.unmodifiableSortedSet(new TreeSet(arrayList)); + } + +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/HibernateUtilHis.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/HibernateUtilHis.java new file mode 100644 index 0000000..6a1d92b --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/HibernateUtilHis.java @@ -0,0 +1,269 @@ +package gov.niarl.hisAppraiser.hibernate.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.HibernateException; +import org.hibernate.Interceptor; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.cfg.Configuration; + + +/** + * Basic Hibernate helper class, handles SessionFactory, Session and Transaction. + *

+ * Uses a static initializer for the initial SessionFactory creation + * and holds Session and Transactions in thread local variables. All + * exceptions are wrapped in an unchecked InfrastructureException. + * + * @author christian@hibernate.org + */ +public class HibernateUtilHis { + + private static Log log = LogFactory.getLog(HibernateUtilHis.class); + + private static Configuration configuration; + private static SessionFactory sessionFactory; + private static final ThreadLocal threadSession = new ThreadLocal(); + private static final ThreadLocal threadTransaction = new ThreadLocal(); + private static final ThreadLocal threadInterceptor = new ThreadLocal(); + + // Create the initial SessionFactory from the default configuration files + + static { + try { + configuration = new Configuration(); + sessionFactory = configuration.configure("/hibernateOat.cfg.xml").buildSessionFactory(); + // We could also let Hibernate bind it to JNDI: + + // configuration.configure().buildSessionFactory() + } catch (Throwable ex) { + // We have to catch Throwable, otherwise we will miss + // NoClassDefFoundError and other subclasses of Error + log.error("Building SessionFactory failed.", ex); + throw new ExceptionInInitializerError(ex); + } + } + + /** + * Returns the SessionFactory used for this static class. + * + * @return SessionFactory + */ + + public static SessionFactory getSessionFactory() { + /* Instead of a static variable, use JNDI: + SessionFactory sessions = null; + try { + Context ctx = new InitialContext(); + String jndiName = "java:hibernate/HibernateFactory"; + sessions = (SessionFactory)ctx.lookup(jndiName); + } catch (NamingException ex) { + throw new InfrastructureException(ex); + } + return sessions; + */ + synchronized (sessionFactory) { + return sessionFactory; + } + } + + /** + * Returns the original Hibernate configuration. + * + * @return Configuration + */ + + public static Configuration getConfiguration() { + return configuration; + } + + /** + * Rebuild the SessionFactory with the static Configuration. + * + */ + public static void rebuildSessionFactory() throws OATException { + synchronized (sessionFactory) { + try { + sessionFactory = getConfiguration().buildSessionFactory(); + } catch (Exception ex) { + throw new OATException(ex); + } + } + } + + /** + * Rebuild the SessionFactory with the given Hibernate Configuration. + * + * @param cfg + */ + + public static void rebuildSessionFactory(Configuration cfg) throws + OATException { + synchronized (sessionFactory) { + try { + sessionFactory = cfg.buildSessionFactory(); + configuration = cfg; + } catch (Exception ex) { + throw new OATException(ex); + } + } + } + + /** + * Retrieves the current Session local to the thread. + *

+ + * If no Session is open, opens a new Session for the running thread. + * + * @return Session + */ + public static Session getSession() throws OATException { + Session s = (Session) threadSession.get(); + try { + if (s == null) { + log.debug("Opening new Session for this thread."); + if (getInterceptor() != null) { + log.debug("Using interceptor: " + getInterceptor().getClass()); + s = getSessionFactory().openSession(getInterceptor()); + } else { + s = getSessionFactory().openSession(); + } + threadSession.set(s); + } + } catch (HibernateException ex) { + throw new OATException(ex); + } + return s; + } + + /** + * Closes the Session local to the thread. + */ + + public static void closeSession() throws OATException { + try { + Session s = (Session) threadSession.get(); + threadSession.set(null); + if (s != null && s.isOpen()) { + log.debug("Closing Session of this thread."); + s.close(); + } + } catch (HibernateException ex) { + throw new OATException(ex); + } + } + + /** + * Start a new database transaction. + */ + + public static void beginTransaction() throws OATException { + Transaction tx = (Transaction) threadTransaction.get(); + try { + if (tx == null) { + log.debug("Starting new database transaction in this thread."); + tx = getSession().beginTransaction(); + threadTransaction.set(tx); + } + } catch (HibernateException ex) { + throw new OATException(ex); + } + } + + /** + * Commit the database transaction. + */ + + public static void commitTransaction() throws OATException { + Transaction tx = (Transaction) threadTransaction.get(); + try { + if (tx != null && !tx.wasCommitted() + && !tx.wasRolledBack()) { + log.debug("Committing database transaction of this thread."); + tx.commit(); + } + threadTransaction.set(null); + } catch (HibernateException ex) { + rollbackTransaction(); + throw new OATException(ex); + } + } + + /** + * Commit the database transaction. + */ + + public static void rollbackTransaction() throws OATException { + Transaction tx = (Transaction) threadTransaction.get(); + try { + threadTransaction.set(null); + if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) { + log.debug( + "Tyring to rollback database transaction of this thread."); + tx.rollback(); + } + } catch (HibernateException ex) { + throw new OATException(ex); + } finally { + closeSession(); + } + } + + /** + * Reconnects a Hibernate Session to the current Thread. + * + * @param session The Hibernate Session to be reconnected. + */ + + public static void reconnect(Session session) throws + OATException { + try { + session.reconnect(); + threadSession.set(session); + } catch (HibernateException ex) { + throw new OATException(ex); + } + } + + /** + * Disconnect and return Session from current Thread. + * + * @return Session the disconnected Session + */ + + public static Session disconnectSession() throws OATException { + + Session session = getSession(); + try { + threadSession.set(null); +// if (session.isConnected() && session.isOpen()) { +// session.disconnect(); +// } + session.disconnect(); + } catch (HibernateException ex) { + throw new OATException(ex); + } + return session; + } + + /** + * Register a Hibernate interceptor with the current thread. + *

+ + * Every Session opened is opened with this interceptor after + * registration. Has no effect if the current Session of the + * thread is already open, effective on next close()/getSession(). + */ + public static void registerInterceptor(Interceptor interceptor) { + threadInterceptor.set(interceptor); + } + + private static Interceptor getInterceptor() { + Interceptor interceptor = + (Interceptor) threadInterceptor.get(); + return interceptor; + } + +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/OATException.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/OATException.java new file mode 100644 index 0000000..49bf3f6 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/OATException.java @@ -0,0 +1,22 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 gov.niarl.hisAppraiser.hibernate.util; + +public class OATException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public OATException(Throwable cause) { + super(cause); + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/ResultConverter.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/ResultConverter.java new file mode 100644 index 0000000..b6633ec --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/ResultConverter.java @@ -0,0 +1,52 @@ +package gov.niarl.hisAppraiser.hibernate.util; + +import java.util.HashMap; + + +public class ResultConverter { + + public static enum AttestResult { + UN_TRUSTED, TRUSTED, UN_KNOWN,TIME_OUT,PENDING + } + + private static HashMap integerResultHashMap = new HashMap() { + /** + * + */ + private static final long serialVersionUID = 1L; + + { + put(0, AttestResult.UN_TRUSTED); + put(1, AttestResult.TRUSTED); + put(2, AttestResult.UN_KNOWN); + put(3, AttestResult.TIME_OUT); + put(4, AttestResult.PENDING); + } + }; + + private static HashMap ResultIntegerHashMap = new HashMap(); + static { + for (Integer integer : integerResultHashMap.keySet()) { + ResultIntegerHashMap.put(integerResultHashMap.get(integer), integer); + } + } + + /** + * Converts a integer into an Action enumeration. + * @param i Integer linked to an action. + * @return Action enumeration related to an integer. + */ + public static AttestResult getResultFromInt(int i) { + return integerResultHashMap.get(i); + } + + /** + * Converts an Action enumeration into the related integer. + * @param action Enumeration value. + * @return Integer related to the enumeration. + */ + public static int getIntFromResult(AttestResult result) { + return ResultIntegerHashMap.get(result); + } + +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/package-info.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/package-info.java new file mode 100644 index 0000000..8e6fbd8 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/hibernate/util/package-info.java @@ -0,0 +1,7 @@ +/** + * This package holds code created by the makers of hibernate for general + * purpose functionality. + * + * @version Crossbow + */ +package gov.niarl.hisAppraiser.hibernate.util; \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportData.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportData.java new file mode 100644 index 0000000..0c7ce31 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportData.java @@ -0,0 +1,316 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser.integrityReport; + +import gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.integrity_Report_v1_0.QuoteDataType; +import gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.integrity_Report_v1_0.QuoteType; +import gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.integrity_Report_v1_0.ReportType; +import gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.integrity_Report_v1_0.PcrCompositeType.PcrValue; +import gov.niarl.hisAppraiser.util.HisUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Hashtable; +import java.util.List; +import java.util.SortedSet; +import java.util.TreeSet; + +import javax.xml.bind.JAXBElement; + +import org.apache.log4j.Logger; + +/** + * This class generates data needed during report evaluation. + * @author syelama + * @version Crossbow + * + */ +public class HisReportData { + private static Logger logger = Logger.getLogger(HisReportData.class); + private ReportType report; + private byte[] pcrSelectSubstitute = null; + private Integer pcrSizeOfSelectSubstitute = null; + private Hashtable pcrValuesTable = null; + + /** + * Initialize with the report. + * @param reportString XML report string. + */ + public HisReportData(String reportString) { + report = HisReportUtil.unmarshallReport(reportString); + } + + /** + * Retrieve quote data object from report. + * @return List of quote data + */ + public List getQuoteData() { + return report.getQuoteData(); + } + + /** + * Retrieve first quote object from report. + * @return Quote + */ + public QuoteType getQuote() { + return ((QuoteDataType) (report.getQuoteData().get(0))).getQuote(); + } + + /** + * PCR select truncated or padded based on the size of select. + * @return PCR select as byte[] + */ + public byte[] generatePcrSelect() { + byte[] pcrSelect = null; + byte pcrSelect_tmp; + int m, n; + + if (pcrSelectSubstitute != null) { + pcrSelect = pcrSelectSubstitute; + } else { + pcrSelect = getQuote().getPcrComposite().getPcrSelection().getPcrSelect(); + } + for (m = 0; m < pcrSelect.length; m++) { + pcrSelect_tmp = pcrSelect[m]; + pcrSelect[m] = 0; + + for (n = 0; n < 8; n++) { + if ((128 >> n & pcrSelect_tmp) != 0) + pcrSelect[m] += 1 << n; + } + } + + //truncate or pad + int length = getPcrSizeOfSelect() - pcrSelect.length; + StringBuffer sb = new StringBuffer(); + String stringPcrSelect = HisUtil.hexString(pcrSelect); + if (length < 0) { + stringPcrSelect = stringPcrSelect.substring(0, getPcrSizeOfSelect() * 2); + } else { + for (int i = 0; i < length; i++) { + stringPcrSelect = sb.append("00").toString(); + } + } + return HisUtil.unHexString(stringPcrSelect); + } + + /** + * PCR select from the report. + * @return PCR select as byte[] + */ + public byte[] getOriginalPcrSelect() { + return getQuote().getPcrComposite().getPcrSelection().getPcrSelect(); + } + + /** + * Retrieve PCR selected count from generated PCR select. + * @return Number of selected PCRs + */ + public int generatePcrSelectedCount() { + byte[] bytes = generatePcrSelect(); + int count = 0; + for (int i = 0; i < bytes.length; i++) { + count = count + HisUtil.getSelected(bytes[i]).size(); + } + return count; + } + + /** + * Generates a list of selected PCRs. + * @return Sorted list of selected selected PCRs. + */ + public SortedSet generatePcrSelectedPositions() { + ArrayList arrayList = new ArrayList(); + byte[] bytes = generatePcrSelect(); + for (int i = 0; i < bytes.length; i++) { + for (Integer integer : HisUtil.getSelected(bytes[i])) { + arrayList.add(integer + (i * 8)); + } + } + Collections.sort(arrayList); + return Collections.unmodifiableSortedSet(new TreeSet(arrayList)); + } + + /** + * Supply substitute value for the PCR select. + * @param pcrSelect + */ + public void substitutePcrSelect(byte[] pcrSelect) { + this.pcrSelectSubstitute = pcrSelect; + } + + /** + * Retrieve the currently used size of select. + * @return the pcrSizeOfSelect + */ + public int getPcrSizeOfSelect() { + if (pcrSizeOfSelectSubstitute == null) { + return getQuote().getPcrComposite().getPcrSelection().getSizeOfSelect(); + } else { + return pcrSizeOfSelectSubstitute; + } + } + + /** + * Supply substitute value for the PCR size of select. + * @param pcrSizeOfSelect the pcrSizeOfSelect to set + */ + public void substitutePcrSizeOfSelect(int pcrSizeOfSelect) { + this.pcrSizeOfSelectSubstitute = pcrSizeOfSelect; + } + + /** + * Number of PCRs in the report. + * @return The number of PCR values. + */ + public int getPcrValueCount() { + return getQuote().getPcrComposite().getPcrValue().size(); + } + + /** + * Populate the PCR hash table. + */ + private void populatePcrValues() { + pcrValuesTable = new Hashtable(); + for (int i = 0; i < getQuote().getPcrComposite().getPcrValue().size(); i++) { + PcrValue pcrValuePcrComposite = (PcrValue) getQuote().getPcrComposite().getPcrValue().get(i); + pcrValuesTable.put(pcrValuePcrComposite.getPcrNumber().intValue(), pcrValuePcrComposite); + } + } + + /** + * Get PCR number i. populate PCR Values + * @param i PCR number + * @return PCR value + * @throws RuntimeException if no PCR value exists. + */ + public byte[] getPcrValue(int pcrNumber) { + if (pcrValuesTable == null) { + populatePcrValues(); + } + PcrValue key = pcrValuesTable.get(pcrNumber); + if (key != null) + return key.getValue(); + + return null; + } + + /** + * The length of each PCR. + * @return The length of each PCR + */ + public int getPcrValueSize() { + return getQuote().getPcrComposite().getValueSize().intValue(); + } + + /** + * Possible values of PCR number. + * @return SortedSet of integers. + */ + public SortedSet getPossiblePcrs() { + if (pcrValuesTable == null) { + populatePcrValues(); + } + return Collections.unmodifiableSortedSet(new TreeSet(pcrValuesTable.keySet())); + } + + /** + * The fixed string related to the quote. + * @return Text value of the fixed string. + */ + public String getQuoteFixedString() { + return getQuote().getQuoteInfo().getFixed(); + } + + /** + * Digest stored in the report. + * @return Digest value. + */ + public byte[] getDigest() { + return getQuote().getQuoteInfo().getDigestValue(); + } + + /** + * Nonce stored in the report. + * @return Nonce value. + */ + public byte[] getNonce() { + return getQuote().getQuoteInfo().getExternalData(); + } + + /** + * Machine name stored in the report. + * @return Machine name value. + */ + public String getMachineName() { + QuoteDataType quoteData = ((QuoteDataType) (report.getQuoteData().get(0))); + return ((JAXBElement) quoteData.getTpmSignature().getKeyInfo().getContent().get(0)).getValue(); + } + + /** + * Signature stored in the report. + * @return Signature value. + */ + public byte[] getSignature() { + QuoteDataType quoteData = ((QuoteDataType) (report.getQuoteData().get(0))); + return quoteData.getTpmSignature().getSignatureValue().getValue(); + } + + /** + * Create the quote version used at the beginning of the signed data. + * @return Quote version data at the beginning of the signed data. + */ + public byte[] getTpmQuoteVersion() { + String tpmQuoteVersionString = HisUtil.hexString(HisUtil.intToByteArray(getQuote().getQuoteInfo().getVersionMajor(), 1)); + tpmQuoteVersionString = tpmQuoteVersionString + HisUtil.hexString(HisUtil.intToByteArray(getQuote().getQuoteInfo().getVersionMinor(), 1)); + tpmQuoteVersionString = tpmQuoteVersionString + HisUtil.hexString(HisUtil.intToByteArray(getQuote().getQuoteInfo().getVersionRevMajor(), 1)); + tpmQuoteVersionString = tpmQuoteVersionString + HisUtil.hexString(HisUtil.intToByteArray(getQuote().getQuoteInfo().getVersionRevMinor(), 1)); + return HisUtil.unHexString(tpmQuoteVersionString); + } + + /** + * Retrieve the ID stored in the XML integrity report. + * @return The unique ID string found in an XML integrity report. + */ + public String getReportID() { + return report.getID(); + } + + /** + * Compare digest with the report digest. + * @return True if equal, false otherwise. + */ + public boolean compareDigest(byte[] digest) { + return HisUtil.hexString(digest).equalsIgnoreCase(HisUtil.hexString(getDigest())); + } +} \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportException.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportException.java new file mode 100644 index 0000000..c11566c --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportException.java @@ -0,0 +1,71 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser.integrityReport; + +/** + * Signals a do not store report exception. + * @author syelama + * @version Crossbow + * + */ +public class HisReportException extends RuntimeException { + + /** + * Default constructor + */ + public HisReportException() { + super(); + } + + /** + * @param message + * @param cause + */ + public HisReportException(String message, Throwable cause) { + super(message, cause); + } + + /** + * @param message + */ + public HisReportException(String message) { + super(message); + } + + /** + * @param cause + */ + public HisReportException(Throwable cause) { + super(cause); + } +} \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportIO.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportIO.java new file mode 100644 index 0000000..1bd670d --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportIO.java @@ -0,0 +1,155 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * (copyright) 2013 Politecnico di Torino, Italy + * TORSEC group -- http://security.polito.it + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser.integrityReport; + +import gov.niarl.hisAppraiser.Constants; +import gov.niarl.hisAppraiser.util.HisUtil; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.InputMismatchException; + +import org.apache.log4j.Logger; + +/** + * This class manages the IO of the integrity report. + * @author Nicola Barresi + * + */ +public class HisReportIO { + private static Logger logger = Logger.getLogger(HisReportIO.class); + private static final String IRprefix = "report_log_"; + + public static String readIR(long reportId, String reportString) { + if (reportString == null) + return ""; + + /* + * For compatibility reason, the function checks if + * reportString contains report XML instead of the + * new syntax: + * report_digest:: + */ + if (!reportString.startsWith("report_digest")) + return reportString; + + String returnValue = null; + try { + String[] reportStringParts = reportString.split(":"); + if (reportStringParts.length != 3) { + throw new Exception("readReportFromFile(): unexpected format of field 'report'"); + } + String digestMethod = reportStringParts[1]; + String digestValue = reportStringParts[2]; + + StringBuilder result = new StringBuilder(); + BufferedReader reader = null; + MessageDigest md = MessageDigest.getInstance(digestMethod); + + String IRdir = Constants.IR_DIR; + + File file = new File(IRdir + IRprefix + reportId + ".xml"); + reader = new BufferedReader(new FileReader(file)); + + String tmpString = null; + while ((tmpString = reader.readLine()) != null) { + result.append(tmpString); + md.update(tmpString.getBytes(), 0, tmpString.length()); + } + reader.close(); + + if (!digestValue.equals(HisUtil.hexString(md.digest()))) { + throw new InputMismatchException(); + } + returnValue = result.toString(); + } catch (FileNotFoundException exception) { + logger.error("readReportFromFile(): cannot find report file"); + } catch (IOException exception) { + logger.error("readReportFromFile(): cannot read report file"); + } catch (NoSuchAlgorithmException exception) { + logger.error("readReportFromFile(): cannot find requested digest method"); + } catch (InputMismatchException exception) { + logger.error("readReportFromFile(): report digest does not match the expected one"); + } catch (Exception exception) { + logger.error(exception.getMessage()); + } + return returnValue; + } + + public static String writeIR(long reportId, String reportString) { + String returnValue = null; + try { + BufferedWriter IRBufferedWriter = null; + MessageDigest md = null; + + String IRdir = Constants.IR_DIR; + String digestMethod = Constants.IR_DIGEST_METHOD; + + if (IRdir == null) + return reportString; + + if (!new File(IRdir).isDirectory()) + throw new FileNotFoundException("writeReportToFile(): cannot find directory " + IRdir); + + File IRfile = new File(IRdir + IRprefix + reportId + ".xml"); + IRBufferedWriter = new BufferedWriter(new FileWriter(IRfile)); + IRBufferedWriter.write(reportString); + IRBufferedWriter.close(); + + try { + md = MessageDigest.getInstance(digestMethod); + } catch (NoSuchAlgorithmException ex) { + logger.info("writeReportToFile(): requested digest method (" + digestMethod + ") does not exist"); + digestMethod = "SHA-256"; + md = MessageDigest.getInstance(digestMethod); + } + md.update(reportString.getBytes(), 0, reportString.length()); + returnValue = "report_digest:" + digestMethod + ":" + HisUtil.hexString(md.digest()); + } catch (FileNotFoundException exception) { + logger.error(exception.getMessage()); + } catch (Exception exception) { + logger.error("writeReportToFile(): a problem occurred writing report to file"); + } + return returnValue; + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportUtil.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportUtil.java new file mode 100644 index 0000000..015cdb6 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportUtil.java @@ -0,0 +1,464 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser.integrityReport; + +import gov.niarl.his.xsd.JAXBContextIntegrity_Report_Manifest_v1_0String; +import gov.niarl.his.xsd.JAXBContextPCR_DifferenceString; +import gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.integrity_Report_v1_0.ReportType; +import gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.integrity_Report_v1_0.SnapshotType; +import gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.core_Integrity_v1_0_1.ValueType; +import gov.niarl.his.xsd.pcr_difference.ObjectFactory; +import gov.niarl.his.xsd.pcr_difference.PCRDifferenceReport; +import gov.niarl.his.xsd.pcr_difference.PCRDifferenceReport.CurrentValue; +import gov.niarl.his.xsd.pcr_difference.PCRDifferenceReport.PreviousCurrent; +import gov.niarl.his.xsd.pcr_difference.PCRDifferenceReport.PreviousValue; +import gov.niarl.hisAppraiser.Constants; +import gov.niarl.hisAppraiser.hibernate.dao.AttestDao; +import gov.niarl.hisAppraiser.hibernate.dao.HisAuditDao; +import gov.niarl.hisAppraiser.hibernate.dao.HisMachineCertDao; +import gov.niarl.hisAppraiser.hibernate.domain.AttestRequest; +import gov.niarl.hisAppraiser.hibernate.domain.AuditLog; +import gov.niarl.hisAppraiser.hibernate.domain.MachineCert; +import gov.niarl.hisAppraiser.hibernate.util.AttestService; +import gov.niarl.hisAppraiser.hibernate.util.HibernateUtilHis; +import gov.niarl.hisAppraiser.hibernate.util.ResultConverter; +import gov.niarl.hisAppraiser.integrityReport.HisReportIO; +import gov.niarl.hisAppraiser.util.AlertConfiguration; +import gov.niarl.hisAppraiser.util.Emailer; +import gov.niarl.hisAppraiser.util.HisUtil; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.StringReader; +import java.io.StringWriter; +import java.io.File; +import java.io.IOException; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.math.BigInteger; +import java.security.cert.X509Certificate; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.InputMismatchException; +import java.util.List; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; +import javax.xml.datatype.DatatypeFactory; + +import org.apache.log4j.Logger; +import org.bouncycastle.openssl.PEMReader; + +/** + * This class is used by the HisReportParser and others for utility functions. + * @author syelama + * @version Crossbow + * + */ +public class HisReportUtil { + private static Logger logger = Logger.getLogger(HisReportUtil.class); + + static Unmarshaller unmarshallerIntegrity_Report_Manifest_v1_0; + static { + try { + JAXBContext context = JAXBContext.newInstance(JAXBContextIntegrity_Report_Manifest_v1_0String.contextString); + unmarshallerIntegrity_Report_Manifest_v1_0 = context.createUnmarshaller(); + // unmarshallerIntegrity_Report_Manifest_v1_0.setValidating(true); + + // For org.bouncycastle.openssl.PEMReader + HisUtil.loadBouncyCastleProvider(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + /** + * This is a convenience method to un-marshal a report and return the + * top level JAXB element. + * @param xmlReport XML string integrity report. + * @return ReportType top level JAXB element. + */ + public synchronized static ReportType unmarshallReport(String xmlReport) { + try { + return ((JAXBElement) unmarshallerIntegrity_Report_Manifest_v1_0.unmarshal(new ByteArrayInputStream(xmlReport.getBytes()))).getValue(); + } catch (JAXBException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + /** + * Convert a PEM formatted certificate in X509 format. + * @param machineCertPEM Machine certificate in PEM/text format. + * @return An X509 certificate object. + */ + public static X509Certificate pemToX509Certificate(String machineCertPEM) { + try { + PEMReader reader = new PEMReader(new StringReader(machineCertPEM.replace("-----BEGIN CERTIFICATE-----", "-----BEGIN CERTIFICATE-----\n").replace("-----END CERTIFICATE-----", "\n-----END CERTIFICATE-----"))); + return (X509Certificate) reader.readObject(); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + /** + * This function was used to create XML for a difference report when a + * detail link was clicked on the old portal. + * @param auditLogDifferentThanPrevious AuditLog entry from the database. + * @param pcrNumber PCR number for which the difference was requested. + * @return XML string showing differences from the previous report PCR. + */ + public static String getPCRDifferenceReport(AuditLog auditLogDifferentThanPrevious, int pcrNumber) { + try { + ObjectFactory objectFactory = new ObjectFactory(); + PCRDifferenceReport differenceReport = objectFactory.createPCRDifferenceReport(); + differenceReport.setMachineName(auditLogDifferentThanPrevious.getMachineName()); + differenceReport.setPCRNumber(BigInteger.valueOf(pcrNumber)); + differenceReport.setPCRDescription(HisReportValidator.getPcrDescription(pcrNumber, false)); + + CurrentValue currentValue = objectFactory.createPCRDifferenceReportCurrentValue(); + String reportString = null; + + AuditLog auditLogPrevious = new HisAuditDao().getPreviousAuditLog(auditLogDifferentThanPrevious.getMachineName(), auditLogDifferentThanPrevious.getId()); + String report = null; + if (auditLogPrevious != null) + report = HisReportIO.readIR(auditLogPrevious.getId(), auditLogPrevious.getReport()); + if (auditLogDifferentThanPrevious != null) + reportString = HisReportIO.readIR(auditLogDifferentThanPrevious.getId(), auditLogDifferentThanPrevious.getReport()); + + if ((auditLogDifferentThanPrevious != null && reportString == null) || (auditLogPrevious != null && report == null)) { + StringWriter stringWriter = new StringWriter(); + Marshaller marshaller = JAXBContext.newInstance(JAXBContextPCR_DifferenceString.contextString).createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "PCR_Difference.xsd"); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE); + marshaller.marshal(differenceReport, stringWriter); + return stringWriter.toString(); + } + + HisReportValidator currentValuehisReportValidator = new HisReportValidator(reportString, null, null, null, null, null); + currentValue.setReportID(currentValuehisReportValidator.getHisReportData().getReportID()); + GregorianCalendar gregorianCalendar = new GregorianCalendar(); + gregorianCalendar.setTime(auditLogDifferentThanPrevious.getTimestamp()); + currentValue.setTimestamp(DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar)); + currentValue.setValue(currentValuehisReportValidator.getPcrValue(pcrNumber)); + + PreviousValue previousValue = objectFactory.createPCRDifferenceReportPreviousValue(); + +// String report = auditLogPrevious.getReport(); + + if (auditLogPrevious != null) + { + HisReportValidator previousValuehisReportValidator = new HisReportValidator(report, null, null, null, null, null); + previousValue.setReportID(previousValuehisReportValidator.getHisReportData().getReportID()); + GregorianCalendar gregorianCalendarPrevious = new GregorianCalendar(); + gregorianCalendarPrevious.setTime(auditLogPrevious.getTimestamp()); + previousValue.setTimestamp(DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendarPrevious)); + previousValue.setValue(previousValuehisReportValidator.getPcrValue(pcrNumber)); + + differenceReport.setCurrentValue(currentValue); + differenceReport.setPreviousValue(previousValue); + + PreviousCurrent previousCurrent = objectFactory.createPCRDifferenceReportPreviousCurrent(); + previousCurrent.getValue().add(previousValuehisReportValidator.getPcrValue(pcrNumber)); + previousCurrent.getValue().add(currentValuehisReportValidator.getPcrValue(pcrNumber)); + differenceReport.setPreviousCurrent(previousCurrent); + } + StringWriter stringWriter = new StringWriter(); + Marshaller marshaller = JAXBContext.newInstance(JAXBContextPCR_DifferenceString.contextString).createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "PCR_Difference.xsd"); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + marshaller.marshal(differenceReport, stringWriter); + return stringWriter.toString(); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + private static AuditLog createAuditLog(MachineCert machineCert, AuditLog lastAuditLog, HisReportValidator hisReportValidator, String sid, String reportString, byte[] nonceInput, byte[] pcrSelectInput, String machineNameInput) { + HisAuditDao hisAuditDao = new HisAuditDao(); + AuditLog auditLog = new AuditLog(); + auditLog.setPcr0(hisReportValidator.getPcrValue(0)); + auditLog.setPcr1(hisReportValidator.getPcrValue(1)); + auditLog.setPcr2(hisReportValidator.getPcrValue(2)); + auditLog.setPcr3(hisReportValidator.getPcrValue(3)); + auditLog.setPcr4(hisReportValidator.getPcrValue(4)); + auditLog.setPcr5(hisReportValidator.getPcrValue(5)); + auditLog.setPcr6(hisReportValidator.getPcrValue(6)); + auditLog.setPcr7(hisReportValidator.getPcrValue(7)); + auditLog.setPcr8(hisReportValidator.getPcrValue(8)); + auditLog.setPcr9(hisReportValidator.getPcrValue(9)); + auditLog.setPcr10(hisReportValidator.getPcrValue(10)); + auditLog.setPcr11(hisReportValidator.getPcrValue(11)); + auditLog.setPcr12(hisReportValidator.getPcrValue(12)); + auditLog.setPcr13(hisReportValidator.getPcrValue(13)); + auditLog.setPcr14(hisReportValidator.getPcrValue(14)); + auditLog.setPcr15(hisReportValidator.getPcrValue(15)); + auditLog.setPcr16(hisReportValidator.getPcrValue(16)); + auditLog.setPcr17(hisReportValidator.getPcrValue(17)); + auditLog.setPcr18(hisReportValidator.getPcrValue(18)); + auditLog.setPcr19(hisReportValidator.getPcrValue(19)); + auditLog.setPcr20(hisReportValidator.getPcrValue(20)); + auditLog.setPcr21(hisReportValidator.getPcrValue(21)); + auditLog.setPcr22(hisReportValidator.getPcrValue(22)); + auditLog.setPcr23(hisReportValidator.getPcrValue(23)); + + auditLog.setSid(sid); + auditLog.setMachineName(machineNameInput); + auditLog.setNonce(HisUtil.hexString(nonceInput)); + auditLog.setPcrSelect(HisUtil.hexString(pcrSelectInput)); + auditLog.setSignatureVerified(hisReportValidator.isSignatureVerified()); + auditLog.setMachine(machineCert); + auditLog.setPreviousDifferences(hisReportValidator.getPreviousReportDifferences()); + auditLog.setReportCompareErrors(hisReportValidator.getCompareErrors()); + auditLog.setValidationErrors(hisReportValidator.getErrors()); + auditLog.setFirstReport((long) -1); + auditLog.setPcrIMLMask(hisReportValidator.getPcrIMLMask()); + + hisAuditDao.saveAuditLog(auditLog); + + if (auditLog.getValidationErrors() == null) { + auditLog.setFirstReport(auditLog.getId()); + if (!hisReportValidator.isFirstIR()) + auditLog.setFirstReport(lastAuditLog.getFirstReport()); + } + + try { + String reportDBString = HisReportIO.writeIR(auditLog.getId(), reportString); + auditLog.setReport(reportDBString); + } catch (Exception e) { + logger.error("A problem occurred writing report to file"); + } + hisAuditDao.updateAuditLog(auditLog); + + /* + * New AuditLog has to be immediately saved on DB in order + * to realise analyses, because analysis tools rely on + * information on DB in order to obtain the IR. + */ + HibernateUtilHis.commitTransaction(); + HibernateUtilHis.beginTransaction(); + + return auditLog; + } + + private static void createAlert(AuditLog auditLog) { + HisAuditDao hisAuditDao = new HisAuditDao(); + AlertConfiguration alertConfiguration = Constants.ALERT_CONFIGURATION; + boolean createAlert = false; + if (alertConfiguration.getAllAlerts()) { + if ((auditLog.getValidationErrors() != null && auditLog.getValidationErrors().length() > 0) || + (auditLog.getReportCompareErrors() != null && auditLog.getReportCompareErrors().length() > 0)) { + createAlert = true; + } + } + if (alertConfiguration.getSignatureAlerts() && !auditLog.getSignatureVerified()) { + createAlert = true; + } + for (int i = 0; i < 24; i++) { + if (alertConfiguration.getPcrAlerts(i) && auditLog.getPreviousDifferences().contains(HisReportValidator.DIFFERENCE_SEPARATOR + Integer.toString(i) + HisReportValidator.DIFFERENCE_SEPARATOR)) { + createAlert = true; + break; + } + } + if (createAlert) { + hisAuditDao.createAlert(auditLog); + //Save before attempting to send an email. + HibernateUtilHis.commitTransaction(); + //Begin a new transaction if needed further on in the code. + HibernateUtilHis.beginTransaction(); + Emailer.sendDefaultAlertEmail(); + } + } + + /** + * This function is used by both the login module and the web services + * to submit an integrity report. It calls alert creation functions and + * email functionality. + * @param sid The SID sent from the client. + * @param reportString The integrity report sent form the client. + * @param nonceInput The nonce provided to the client. + * @param pcrSelectInput The PCR select provided to the client. + * @param machineNameInput The machine name sent from the client. + */ + public static void submitReport(String sid, String reportString, byte[] nonceInput, byte[] pcrSelectInput, String machineNameInput) { + + HisMachineCertDao hisMachineCertDao = new HisMachineCertDao(); + MachineCert machineCert = null; + X509Certificate machineCertificate = null; + machineCert = hisMachineCertDao.getMachineCert(machineNameInput); + if (machineCert == null) { + logger.error("Machine '" + machineNameInput + "' is not enrolled."); + } else { + machineCertificate = pemToX509Certificate(machineCert.getCertificate()); + } + + HisAuditDao hisAuditDao = new HisAuditDao(); + + AuditLog lastAuditLog = hisAuditDao.getLastAuditLog(machineNameInput); + String previousReportString = null; + + if (lastAuditLog != null) { + previousReportString = HisReportIO.readIR(lastAuditLog.getId(), lastAuditLog.getReport()); + } + + + HisReportValidator hisReportValidator = new HisReportValidator(reportString, nonceInput, pcrSelectInput, machineNameInput, machineCertificate, previousReportString); + + boolean IDENTICAL_REPORT = (lastAuditLog != null && !lastAuditLog.getFirstReport().equals((long)-1)); + IDENTICAL_REPORT &= (hisReportValidator.getErrors() == null && hisReportValidator.getPreviousReportDifferences().equals("")); + AuditLog auditLog = null; + if (!(Constants.DISCARD_IDENTICAL_IR && IDENTICAL_REPORT)) { + auditLog = createAuditLog(machineCert, lastAuditLog, hisReportValidator, sid, reportString, nonceInput, pcrSelectInput, machineNameInput); + } + + + /******************************************************************************************************** + * OpenAttestation code: + * Validating host's PCR with table PCR_manifest. + * + *******************************************************************************************************/ + AttestDao attestDao = new AttestDao(); + HisAuditDao auditLogDao = new HisAuditDao(); + AuditLog newAuditLog = auditLogDao.getLastAuditLog(machineNameInput); + AttestRequest latestPolledRequest = attestDao.getPendingRequests(machineNameInput, true).get(0); + + boolean DO_ANALYSES = latestPolledRequest.getThreshold() == null || latestPolledRequest.getResult() == null; + DO_ANALYSES |= latestPolledRequest.getThreshold() != null && !IDENTICAL_REPORT; + if (latestPolledRequest.getId() != null && newAuditLog != null && newAuditLog.getReport() != null) { + Date validateTime = null; + if (DO_ANALYSES) { + System.out.println("latestPolledRequest" +latestPolledRequest.getId()); + latestPolledRequest.setAnalysisResults(""); + latestPolledRequest.setAuditLog(newAuditLog); + + if (newAuditLog.getValidationErrors() != null) { + latestPolledRequest.setResult(ResultConverter.getIntFromResult(ResultConverter.AttestResult.UN_TRUSTED)); + } else { + latestPolledRequest.setResult(ResultConverter.getIntFromResult(ResultConverter.AttestResult.TRUSTED)); + latestPolledRequest = AttestService.doAnalyses(latestPolledRequest, machineNameInput); + } + validateTime = new Date(); + latestPolledRequest.setCurrentProcessingTime(validateTime.getTime() - latestPolledRequest.getRequestTime().getTime()); + } + + latestPolledRequest.setValidateTime((validateTime != null) ? validateTime : new Date()); + attestDao.updateRequest(latestPolledRequest); + System.out.println("------------------------OpenAttestation complete!------------------------------------------"); + /****************************************************************************************************/ + } + if (!(Constants.DISCARD_IDENTICAL_IR && IDENTICAL_REPORT)) { + createAlert(auditLog); + } + } + + public static String fetchReport(Long reportId, boolean partial) throws IllegalStateException { + String reportXML = ""; + try { + if (reportId == null) { + throw new Exception("fetchReport(): null reportId received"); + } + + HisAuditDao auditDao = new HisAuditDao(); + AuditLog auditLog = auditDao.getAuditLog(reportId.intValue()); + if (auditLog == null) { + throw new Exception("fetchReport(): no report with id '" + reportId + "'"); + } + reportXML = HisReportIO.readIR(reportId, auditLog.getReport()); + + List relatedAuditLogs = auditDao.getRelatedAuditLogs(auditLog); + + boolean reportValid = reportXML != null && !reportXML.equals(""); + if (!partial && relatedAuditLogs.size() > 0 && reportValid) { + InputStream stream = new ByteArrayInputStream(reportXML.getBytes()); + + JAXBContext context = JAXBContext.newInstance(JAXBContextIntegrity_Report_Manifest_v1_0String.contextString + + ":gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.simple_object_v1_0_"); + Unmarshaller unmarshaller = context.createUnmarshaller(); + ReportType lastReport = ((JAXBElement) unmarshaller.unmarshal(stream)).getValue(); + + ReportType tmpReport = null; + String tmpReportString = null; + + /* + * relatedAuditLogs order is inverted because + * measurements can be attached always on top + * of the other + */ + for (AuditLog tmpAuditLog : relatedAuditLogs) { + tmpReportString = HisReportIO.readIR(tmpAuditLog.getId(), tmpAuditLog.getReport()); + if (tmpReportString == null || tmpReportString.equals("")) { + throw new IllegalStateException("A problem occurred reading integrity report"); + } + stream = new ByteArrayInputStream(tmpReportString.getBytes()); + tmpReport = ((JAXBElement) unmarshaller.unmarshal(stream)).getValue(); + + for (SnapshotType snap : tmpReport.getSnapshotCollection()) { + boolean snapshotFound = false; + for (SnapshotType lastReportSnap : lastReport.getSnapshotCollection()) { + if (!snap.getPcrHash().get(0).getNumber().equals(lastReportSnap.getPcrHash().get(0).getNumber())) + continue; + + lastReportSnap.getValues().addAll(0, snap.getValues()); + lastReportSnap.getPcrHash().get(0).setStartHash(HisUtil.unHexString("0000000000000000000000000000000000000000")); + snapshotFound = true; + break; + } + if (!snapshotFound) { + lastReport.getSnapshotCollection().add(snap); + } + } + } + + Marshaller m = context.createMarshaller(); + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + JAXBElement report = new gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.integrity_Report_v1_0.ObjectFactory().createReport(lastReport); + m.marshal(report, bOut); + + reportXML = new String(bOut.toByteArray()); + } + } catch (IllegalStateException exception) { + logger.error(exception.getMessage()); + throw exception; + } catch (Exception exception) { + logger.error(exception.getMessage()); + } + return reportXML; + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportValidator.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportValidator.java new file mode 100644 index 0000000..3cd65b4 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/HisReportValidator.java @@ -0,0 +1,675 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser.integrityReport; + +import gov.niarl.his.xsd.JAXBContextIntegrity_Report_Manifest_v1_0String; +import gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.core_Integrity_v1_0_1.DigestValueType; +import gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.core_Integrity_v1_0_1.ValueType; +import gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.integrity_Report_v1_0.PcrCompositeType.PcrValue; +import gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.integrity_Report_v1_0.QuoteType; +import gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.integrity_Report_v1_0.ReportType; +import gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.integrity_Report_v1_0.SnapshotType; +import gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.simple_object_v1_0_.SimpleObjectType; +import gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.simple_object_v1_0_.ValuesType; +import gov.niarl.hisAppraiser.hibernate.dao.AttestDao; +import gov.niarl.hisAppraiser.hibernate.dao.HisAuditDao; +import gov.niarl.hisAppraiser.hibernate.dao.HisMachineCertDao; +import gov.niarl.hisAppraiser.hibernate.domain.AuditLog; +import gov.niarl.hisAppraiser.Constants; +import gov.niarl.hisAppraiser.util.HisUtil; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.io.PrintStream; +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.Signature; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.SortedSet; +import java.util.StringTokenizer; +import java.util.TreeSet; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; + +import org.apache.log4j.Logger; + +/** + * This class does the main work with the report when it comes into the + * web services or login modules. + * @author syelama + * @version Crossbow + * + */ +public class HisReportValidator { + private static Logger logger = Logger.getLogger(HisReportValidator.class); + static { + // For signature + HisUtil.loadBouncyCastleProvider(); + } + + /** + * This is used in the database previous_differences field to separate PCR + * numbers. + */ + public final static String DIFFERENCE_SEPARATOR = "|"; + /** + * This is used in the report_errors field in the to separate errors + * generated below. + */ + public final static String ERROR_SEPARATOR = "----------------------------------------------------------------------"; + + public static final int PCR_HASH_SIZE = 20; + public static final int PCR_MAX_NUM = 24; + + HisReportData hisReportData; + String reportString; + X509Certificate machineCertificate; + + byte[] lastDigestData = null; + + boolean nonceMatch = false; + boolean machineNameMatch = false; + boolean digestMatch = false; + boolean signatureVerified = false; + String previousReportDifferences = ""; + + ArrayList errors = new ArrayList(); + ArrayList compareErrors = new ArrayList(); + HisReportValidator previousReportValidator; + boolean FIRST_IR; + String currentPcrIMLMask; + + /** + * The constructor does all the work for verifying the report and returning + * useful information. + * @param reportString Only required parameter to the constructor + * containing the XML integrity report. + * @param nonceInput The nonce provided to the client in the first + * stage of submitting an integrity report. + * @param pcrSelectInput The PCR select provided to the client in the + * first stage of submitting an integrity report. + * @param machineNameInput The machine name provided by the client in the + * first stage of submitting an integrity report. + * @param machineCertificate The X509Certificate stored in the database for + * the machine. + * @param previousReportString Previous XML integrity report, if any, + * stored in the database for the machine. + */ + public HisReportValidator(String reportString, byte[] nonceInput, byte[] pcrSelectInput, String machineNameInput, X509Certificate machineCertificate, String previousReportString) { + try { + boolean DO_VALIDATION = true; + + /* + * If all parameters except reportString are null, + * HisReportValidator is used only to parse the + * report, then the validation of measurements is + * not required. + */ + if (nonceInput == null && pcrSelectInput == null && machineNameInput == null && machineCertificate == null && previousReportString == null) + DO_VALIDATION = false; + // replace nulls for null pointer exceptions + if (nonceInput == null) { + nonceInput = new byte[1]; + } + if (pcrSelectInput == null) { + pcrSelectInput = new byte[1]; + } + if (machineNameInput == null) { + machineNameInput = ""; + } + //Can't do this for machineCertificate + if (previousReportString == null) { + previousReportValidator = null; + previousReportString = ""; + } + + this.FIRST_IR = true; + this.reportString = reportString; + this.machineCertificate = machineCertificate; + this.currentPcrIMLMask = new AttestDao().getPcrIMLMask(machineNameInput); + this.currentPcrIMLMask = this.currentPcrIMLMask==null?"000000":this.currentPcrIMLMask; + try { + hisReportData = new HisReportData(reportString); + //drop null reports + QuoteType quote = hisReportData.getQuote(); + } catch (Exception e) { + throw new HisReportException(e); + } + + if (hisReportData.getQuoteData().size() > 1) + errors.add("Multiple quote data"); + + /*-------------------------------------------------------------------------------------------------------------------------*/ + /*-------------------------------------------------Signature Verification -------------------------------------------------*/ + /*-------------------------------------------------------------------------------------------------------------------------*/ + digestMatch = false; + if (hisReportData.compareDigest(computeDigest())) { + digestMatch = true; + logger.debug("Found digest match location 1."); + } + //***************************************************************************** + //***************************************************************************** + //Linux and Windows compute this differently + //***************************************************************************** + //***************************************************************************** + + //Try size of select 2 + if (digestMatch == false && hisReportData.getPcrSizeOfSelect() != 2) { + hisReportData.substitutePcrSizeOfSelect(2); + + if (hisReportData.compareDigest(computeDigest())) { + digestMatch = true; + logger.debug("Found digest match location 2."); + } + } + + //Try size of select 3 + if (digestMatch == false && hisReportData.getPcrSizeOfSelect() != 3) { + hisReportData.substitutePcrSizeOfSelect(3); + + if (hisReportData.compareDigest(computeDigest())) { + digestMatch = true; + logger.debug("Found digest match location 3."); + } + } + + //Try to zero out the last byte + if (digestMatch == false) { + hisReportData.substitutePcrSizeOfSelect(3); + byte[] generatedPcrSelect = hisReportData.generatePcrSelect(); + generatedPcrSelect[2] = 0; + hisReportData.substitutePcrSelect(generatedPcrSelect); + + if (hisReportData.compareDigest(computeDigest())) { + digestMatch = true; + logger.debug("Found digest match location 4."); + } + } + + if (digestMatch == false) { + errors.add("Computed digest value does not match digest value in report."); + digestMatch = false; + } + + if (HisUtil.hexString(hisReportData.getNonce()).equalsIgnoreCase(HisUtil.hexString(nonceInput))) { + nonceMatch = true; + } else { + errors.add("Nonce does not match nonce in report."); + nonceMatch = false; + } + + if (hisReportData.getMachineName().equalsIgnoreCase(machineNameInput)) { + machineNameMatch = true; + } else { + errors.add("Report machine name does not equal given machine name. " + hisReportData.getMachineName() + " " + machineNameInput); + machineNameMatch = false; + } + + if (machineCertificate == null) { + errors.add(machineNameInput + " certificate not uploaded. Machine must be reenrolled."); + } else { + Exception exception = null; + try { + X509Certificate privacyCaCert = new HisMachineCertDao().getPrivacyCaCert(); + if (privacyCaCert != null) + machineCertificate.verify(privacyCaCert.getPublicKey()); + } catch (Exception e) { + exception = e; + } + if (exception != null) { + errors.add("Machine certificate was not signed by the privacy CA."); + machineCertificate = null; + } + } + + if (!digestMatch || !nonceMatch || !machineNameMatch || machineCertificate == null) { + errors.add("Signature not verified due to non-matching machine name, nonce or digest."); + signatureVerified = false; + } else { + if (verifySignature()) { + signatureVerified = true; + } else { + signatureVerified = false; + errors.add("Signature did not verify."); + } + } + + /*-------------------------------------------------Appraiser Functionality-------------------------------------------------*/ + if (previousReportString.length() > 0) { + comparePreviousReport(previousReportString); + } else { + logger.info("HisReportParser: No previous report for comparison. Report ID:" + hisReportData.getReportID()); + } + + if (DO_VALIDATION) + validateMeasurements(reportString); + } catch (HisReportException hisReportException) { + logger.fatal(hisReportException, hisReportException); + throw hisReportException; + } catch (Exception e) { + logger.fatal(e, e); + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + PrintStream printStream = new PrintStream(byteArrayOutputStream); + e.printStackTrace(printStream); + errors.add(byteArrayOutputStream.toString()); + } + } + + /** + * Returns true if the validated report contains the first + * part of measurements; returns false otherwise. + * @return True/False depending on the type of report validated + */ + boolean isFirstIR() { + return FIRST_IR; + } + + /** + * Returns the value of the pcrIMLMask used to validate the PCRs. + * @return pcrIMLMask used to validate the PCRs + */ + String getPcrIMLMask() { + return currentPcrIMLMask; + } + + /** + * Reads each SnapshoCollection from the integrity report, + * extends measures inside them and compare the result with + * the element PcrHash and the PCR value read from the + * Quote. If values match it sets the field result of + * attestation request to TRUSTED. + * @param attestRequest The attestation request to be fulfilled + */ + public void validateMeasurements(String reportString) { + boolean[] snapFound = new boolean[PCR_MAX_NUM]; + for (int i = 0; i < PCR_MAX_NUM; i++) + snapFound[i] = false; + + + ReportType report = null; + Unmarshaller unmarshaller; + try { + InputStream stream = new ByteArrayInputStream(reportString.getBytes()); + JAXBContext context = JAXBContext.newInstance(JAXBContextIntegrity_Report_Manifest_v1_0String.contextString + ":gov.niarl.his.xsd.integrity_Report_v1_0.org.trustedcomputinggroup.xml.schema.simple_object_v1_0_"); + unmarshaller = context.createUnmarshaller(); + report = ((JAXBElement) unmarshaller.unmarshal(stream)).getValue(); + + String[] splittedReportId = report.getID().split("-"); + FIRST_IR = true; + if (splittedReportId.length > 2) + FIRST_IR = !splittedReportId[splittedReportId.length - 2].equals("continue"); + + if (!FIRST_IR && previousReportValidator == null) { + errors.add("Report type \"continue\" but no previous report found"); + return; + } + + String hostName = report.getID().split("-[^-]*-[^-]*$")[0]; + AuditLog lastAuditLog = new HisAuditDao().getLastAuditLog(hostName); + + if (!FIRST_IR && !lastAuditLog.getPcrIMLMask().equals(this.currentPcrIMLMask)) { + errors.add("Report type \"continue\" but pcrIMLMask is changed"); + return; + } + + List pcrValues = report.getQuoteData().get(0).getQuote().getPcrComposite().getPcrValue(); + + byte[] pcrIMLMask = HisUtil.unHexString(this.currentPcrIMLMask); + int intPcrIMLMask = (pcrIMLMask[2] & 0xFF) | ((pcrIMLMask[1] & 0xFF) << 8) | ((pcrIMLMask[0] & 0xFF) << 16); + + for (SnapshotType snapCollection : report.getSnapshotCollection()) { + List values = snapCollection.getValues(); + + SimpleObjectType objects; + DigestValueType hash; + + BigInteger pcrNumber = snapCollection.getPcrHash().get(0).getNumber(); + if ((intPcrIMLMask & (0x00800000 >> pcrNumber.intValue())) == 0) + continue; + + String hashString; + + MessageDigest md = MessageDigest.getInstance("SHA-1"); + byte[] pcr = snapCollection.getPcrHash().get(0).getStartHash(); + + boolean startHashMatch = true; + if (previousReportValidator != null) + startHashMatch = previousReportValidator.getPcrValue(pcrNumber.intValue()).equals(HisUtil.hexString(pcr)); + + if ((FIRST_IR && !HisUtil.hexString(pcr).equals("0000000000000000000000000000000000000000")) || + (!FIRST_IR && !startHashMatch)) { + errors.add("PCR " + pcrNumber + ": Unexpected value of StartHash"); + } + + for (int i = 0; i < values.size(); i++) { + objects = ((JAXBElement) values.get(i).getAny()).getValue(); + + ValuesType tmp = objects.getObjects().get(0); + hash = tmp.getHash().get(0); + hashString = HisUtil.hexString(hash.getValue()).toLowerCase(); + + md.reset(); + md.update(pcr, 0, PCR_HASH_SIZE); + + if (hashString.equals("0000000000000000000000000000000000000000")) + hashString = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; + + md.update(HisUtil.unHexString(hashString), 0, PCR_HASH_SIZE); + md.digest(pcr, 0, PCR_HASH_SIZE); + } + + //Comparison with PCR value read from PcrHash element + if (!HisUtil.hexString(snapCollection.getPcrHash().get(0).getValue()).equals(HisUtil.hexString(pcr))) + errors.add("PCR " + pcrNumber + ": PcrHash does not match the extension of PCRs in report"); + + //Comparison with PCR value read from Quote + for (PcrValue pcrValue : pcrValues) { + if (pcrValue.getPcrNumber().equals(pcrNumber)) { + if (!HisUtil.hexString(pcrValue.getValue()).equals(HisUtil.hexString(pcr))) + errors.add("PCR " + pcrNumber + ": PCR value in the quote does not match the extension of PCRs in report"); + break; + } + } + + snapFound[pcrNumber.intValue()] = true; + } + + for (PcrValue pcrValue : pcrValues) { + if ((intPcrIMLMask & (0x00800000 >> pcrValue.getPcrNumber().intValue())) == 0) + continue; + + boolean pcrMatch = true; + if (previousReportValidator != null) + pcrMatch = previousReportValidator.getPcrValue(pcrValue.getPcrNumber().intValue()).equals(getPcrValue(pcrValue.getPcrNumber().intValue())); + + if (((FIRST_IR && !HisUtil.hexString(pcrValue.getValue()).equals("0000000000000000000000000000000000000000")) || + (!FIRST_IR && !pcrMatch)) && !snapFound[pcrValue.getPcrNumber().intValue()]) { + errors.add("PCR " + pcrValue.getPcrNumber() + ": SnapshotCollection expected but not found"); + } + } + } catch (Exception e) { + e.printStackTrace(); + errors.add("An error occurred during measurements validation"); + } + } + + /** + * Size of select + select + length of data + data + * @return resulting byte array. + */ + private byte[] computeDigest() { + try { + int sizeOfSelect = hisReportData.getPcrSizeOfSelect(); + byte[] select = hisReportData.generatePcrSelect(); + /* + * WRONG!! According to TCG specs, ValueSize is the total size of the array of PcrValue structures + * int dataLength = hisReportData.generatePcrSelectedCount() * hisReportData.getPcrValueSize(); + */ + int dataLength = hisReportData.getPcrValueSize(); + + //concatenate the values + String stringDigest = HisUtil.hexString(HisUtil.intToByteArray(sizeOfSelect, 2)); + stringDigest = stringDigest + HisUtil.hexString(select); + stringDigest = stringDigest + HisUtil.hexString(HisUtil.intToByteArray(dataLength, 4)); + StringBuffer sb = new StringBuffer(stringDigest); + //concatenate the PCR data + for (Integer integer : hisReportData.generatePcrSelectedPositions()) { + byte [] pcrValue = hisReportData.getPcrValue(integer); + if(pcrValue != null) + stringDigest = sb.append(HisUtil.hexString(pcrValue)).toString(); + } + + lastDigestData = HisUtil.unHexString(stringDigest); + + logger.debug("computeDigest:Digest before hash:" + stringDigest); + MessageDigest messageDigest = MessageDigest.getInstance("SHA-1"); + return messageDigest.digest(lastDigestData); + } catch (Exception e) { + logger.fatal(e, e); + throw new RuntimeException(e); + } + + } + + /** + * Create quote and verify signature. + * @return True if signature verifies else false. + */ + private boolean verifySignature() { + try { + //String values of hexadecimal representations of quote data + String tpmQuoteVersion = HisUtil.hexString(hisReportData.getTpmQuoteVersion()); + String quoteFixedString = HisUtil.hexString(hisReportData.getQuoteFixedString().getBytes()); + String digest = HisUtil.hexString(hisReportData.getDigest()); + String nonce = HisUtil.hexString(hisReportData.getNonce()); + + String quote = tpmQuoteVersion + quoteFixedString + digest + nonce; + logger.debug("Signature data:" + quote); + + Signature signature = Signature.getInstance("SHA1withRSA", "BC"); + signature.initVerify(machineCertificate); + signature.update(HisUtil.unHexString(quote)); + + if (!signature.verify(hisReportData.getSignature())) { + return false; + } else { + return true; + } + + } catch (Exception e) { + logger.fatal(e, e); + } + return false; + } + + /** + * Compare the PCRs of the previous report. + * @param previousReportString XML string of the previous report. + */ + private void comparePreviousReport(String previousReportString) { + logger.info("----------begin comparing to previous report----------"); + HisReportValidator hisReportValidator = new HisReportValidator(previousReportString, null, null, null, null, null); + this.previousReportValidator = hisReportValidator; + StringBuffer sb = new StringBuffer(); + + SortedSet possiblePcrs = new TreeSet(); + possiblePcrs.addAll(hisReportValidator.getHisReportData().getPossiblePcrs()); + possiblePcrs.addAll(hisReportData.getPossiblePcrs()); + for (Integer i : possiblePcrs) { + if (hisReportValidator.getPcrValue(i).length() == 0) { + previousReportDifferences = sb.append(DIFFERENCE_SEPARATOR).append(Integer.toString(i)).append(DIFFERENCE_SEPARATOR).toString(); + compareErrors.add("PCR #" + Integer.toString(i) + " new. "); + } else if (getPcrValue(i).length() == 0) { + previousReportDifferences = sb.append(DIFFERENCE_SEPARATOR).append(Integer.toString(i)).append(DIFFERENCE_SEPARATOR).toString(); + compareErrors.add("PCR #" + Integer.toString(i) + " absent. "); + } else if (!getPcrValue(i).equalsIgnoreCase(hisReportValidator.getPcrValue(i))) { + previousReportDifferences = sb.append(DIFFERENCE_SEPARATOR).append(Integer.toString(i)).append(DIFFERENCE_SEPARATOR).toString(); + compareErrors.add("PCR #" + Integer.toString(i) + " differs. "); + } + } + logger.info("----------end comparing to previous report----------"); + } + + /** + * Generate the contents of the previous differences + * @return Delimited string containing PCRs which differed from the last report. + */ + public String getPreviousReportDifferences() { + return previousReportDifferences; + } + + /** + * Determine whether there was a difference for a PCR given a delimited + * PCR difference string. + * @param previousReportDifferences Delimited string containing PCRs + * which differed from the last report. + * @param i The PCR number for which you would like to know whether + * it differed from the last report. + * @return Whether or not the PCR indicated by i differed from this + * report to the last report + */ + public static boolean getPreviousReportDifference(String previousReportDifferences, int i) { + return !(previousReportDifferences.indexOf(DIFFERENCE_SEPARATOR + Integer.toString(i) + DIFFERENCE_SEPARATOR) < (1 - 1)); + } + + /** + * After the constructor generates and stores compararison errors + * in a list this function concatenates and returns them. + * @return The error string generated from compareErrors list. + */ + public String getCompareErrors() { + String errorsString = null; + StringBuffer sb = new StringBuffer(); + Iterator iterator = compareErrors.iterator(); + + while (iterator.hasNext()) { + errorsString = sb.append(iterator.next()).toString(); + } + return errorsString; + } + + /** + * After the constructor generates and stores errors in a list + * this function concatenates and returns them. + * @return The errors generated from parsing an verification. + */ + public String getErrors() { + String errorsString = null; + StringBuffer sb = new StringBuffer(); + for (Iterator iterator = errors.iterator(); iterator.hasNext();) { + String string = (String) iterator.next(); + if (errorsString != null) { + errorsString = sb.append("\n").append(ERROR_SEPARATOR).append("\n").toString(); + } + errorsString = sb.append(string).toString(); + } + return errorsString; + } + + /** + * Counts the number of errors given a generated error string. + * @param errorsString An error string created from getErrors(). + * @return The number of errors within an error string. + */ + public static int getErrorsCount(String errorsString) { + if (errorsString == null) { + errorsString = ""; + } + if (errorsString.length() < 1) { + return (1 - 1); + } + return new StringTokenizer(errorsString, ERROR_SEPARATOR).countTokens(); + } + + /** + * Number of PCRs in the report. + * @return The number of PCR values. + */ + public int getPcrValueCount() { + return hisReportData.getPcrValueCount(); + } + + /** + * Generate a hexadecimal string for a PCR. + * @param i PCR number + * @return String with the hexadecimal value of the PCR or an empty + * string for no entry. + */ + public String getPcrValue(int i) { + byte[] pcrValue = null; + + pcrValue = hisReportData.getPcrValue(i); + + if (pcrValue == null) { + return ""; + } else { + return HisUtil.hexString(pcrValue); + } + } + + /** + * Used to populate the signature verified field stored with the + * integrity reports. + * @return Whether the signature was verified during parsing. + */ + public boolean isSignatureVerified() { + return signatureVerified; + } + + /** + * Data related to the submitted report. + * @return the hisReportData + */ + public HisReportData getHisReportData() { + return hisReportData; + } + + /** + * PCR descriptions for several PCRs in text and HTML format. + * @param i PCR for number needing description + * @param html if true return HTML formatted output else return plain text + * @return HTML or plain text output + */ + public static String getPcrDescription(int i, boolean html) { + int length = 77; + String pcrDescriptionString = ""; + + String[] pcrDescription = new String[length]; + pcrDescription[0] = "BIOS"; + pcrDescription[4] = "MBR, Boot Order"; + pcrDescription[5] = "Partition Tables"; + + String[] pcrDescriptionHTML = new String[length]; + pcrDescriptionHTML[0] = "BIOS"; + pcrDescriptionHTML[4] = "MBR,
Boot Order"; + pcrDescriptionHTML[5] = "Partition
Tables"; + + if (i < 0 || i >= length) { + return ""; + } else { + pcrDescriptionString = html ? pcrDescriptionHTML[i] : pcrDescription[i]; + } + if (pcrDescriptionString == null) { + return ""; + } else { + return pcrDescriptionString; + } + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/package-info.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/package-info.java new file mode 100644 index 0000000..5d4d9b6 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/integrityReport/package-info.java @@ -0,0 +1,7 @@ +/** + * This package holds code to parse, validate and other functionality for + * integrity reports. + * + * @version Crossbow + */ +package gov.niarl.hisAppraiser.integrityReport; \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/loginModule/HisLoginModule.xml b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/loginModule/HisLoginModule.xml new file mode 100644 index 0000000..683b06d --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/loginModule/HisLoginModule.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + What is your sid. + + + What is your machineName. + + + + + Replace with TextOutputCallback for nonce + + + Replace with NameCallback for pcrSelect + + + Replace with TextInputCallback for Integrity Report + + + diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/loginModule/package-info.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/loginModule/package-info.java new file mode 100644 index 0000000..aa9ff46 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/loginModule/package-info.java @@ -0,0 +1,6 @@ +/** + * This package holds code related to the HIS login module. + * + * @version Crossbow + */ +package gov.niarl.hisAppraiser.loginModule; \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/util/AlertConfiguration.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/util/AlertConfiguration.java new file mode 100644 index 0000000..5ccfbff --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/util/AlertConfiguration.java @@ -0,0 +1,158 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser.util; + +import java.util.StringTokenizer; + +import org.apache.log4j.Logger; + +/** + * This class is used to store and retrieve information about which alerts + * to generate + * @author syelama + * @version Crossbow + * + */ +public class AlertConfiguration { + private static Logger logger = Logger.getLogger(AlertConfiguration.class); + boolean allAlerts; + boolean[] pcrAlerts = new boolean[24]; + boolean signatureAlerts; + + /** + * This constructor parses the string which configures the alerts. + * @param property The comma separated string with alert configuration. + */ + public AlertConfiguration(String property) { + property = property.trim(); + + allAlerts = false; + for (int i = 0; i < pcrAlerts.length; i++) { + pcrAlerts[i] = false; + } + signatureAlerts = false; + + if (property == null || property.length() < 1) { + allAlerts = true; + for (int i = 0; i < pcrAlerts.length; i++) { + pcrAlerts[i] = true; + } + signatureAlerts = true; + } else { + StringTokenizer stringTokenizer = new StringTokenizer(property, ","); + while (stringTokenizer.hasMoreElements()) { + String string = (String) stringTokenizer.nextElement(); + + int pcr = -1; + try { + pcr = Integer.parseInt(string); + } catch (Exception e) { + e.printStackTrace(); + } + + if ("signature".equalsIgnoreCase(string)) { + if (signatureAlerts) { + logger.warn("Duplicate entry in alert configuration: " + string); + } else { + signatureAlerts = true; + } + } else if (pcr >= 0 && pcr <= 23) { + if (pcrAlerts[pcr]) { + logger.warn("Duplicate entry in alert configuration: " + string); + } else { + pcrAlerts[pcr] = true; + } + } else { + logger.warn("Unknown entry in alert configuration: " + string); + } + } + } + // printSummary(); + } + + /** + * Whether or not to ignore this alert configuration and generate all + * alerts. + * @return Whether or not to generate all alerts regardless of configuration. + */ + public boolean getAllAlerts() { + return allAlerts; + } + + /** + * Determines whether to generate alerts for a PCR based on PCR number. + * @param i PCR number + * @return True if alerts should be generated for this PCR. + */ + public boolean getPcrAlerts(int i) { + return pcrAlerts[i]; + } + + /** + * Determines if signature alerts should be generated. + * @return True if signature alerts should be generated. + */ + public boolean getSignatureAlerts() { + return signatureAlerts; + } + + /** + * Prints an alert generation summary using the logger created for this + * class. + */ + public void printSummary() { + logger.info("-----------------------------------------------------------------------------"); + logger.info("Printing HIS web services alert configuration summary:"); + logger.info("-----------------------------------------------------------------------------"); + boolean noAlertConfiguration = true; + if (getAllAlerts()) { + logger.info("Alerts will be generated for all errors."); + noAlertConfiguration = false; + } else { + if (getSignatureAlerts()) { + logger.info("Alerts will be generated for signature errors."); + noAlertConfiguration = false; + } + for (int i = 0; i < pcrAlerts.length; i++) { + if (getPcrAlerts(i)) { + logger.info("Alerts will be generated for PCR number:" + i); + noAlertConfiguration = false; + } + } + } + if (noAlertConfiguration) { + logger.warn("WARNING: No alert configuration found. No alerts will be generated."); + } + logger.info("-----------------------------------------------------------------------------"); + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/util/Emailer.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/util/Emailer.java new file mode 100644 index 0000000..0469e13 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/util/Emailer.java @@ -0,0 +1,114 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser.util; + +import gov.niarl.hisAppraiser.Constants; + +import java.util.Properties; +import java.util.StringTokenizer; +import java.util.Map.Entry; + +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.Session; +import javax.mail.Transport; +import javax.mail.internet.AddressException; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; + +/** + * This class is a central location for dealing with email functionality. + * @author syelama + * @version Crossbow + * + */ +public class Emailer { + /** + * Extracts properties for mail configuration. + * @param completeProperties + * @return A subset of properties containing mail configuration. + */ + public static Properties parseMailServerProperties(Properties completeProperties) { + Properties mailServerProperties = new Properties(); + for (Entry entry : completeProperties.entrySet()) { + if (((String) entry.getKey()).trim().toLowerCase().startsWith("mail.")) { + mailServerProperties.put(entry.getKey(), entry.getValue()); + } + } + return mailServerProperties; + } + + /** + * Constructs an array of InternetAddress from a property containing a + * comma separated list. + * @param defaultAlertMessageTo Comma separated list of email "to" addresses. + * @return An array of InternetAddress to be used to send email. + */ + public static InternetAddress[] parseDefaultAlertMessageTo(String defaultAlertMessageTo) { + InternetAddress[] internetAddresses; + try { + StringTokenizer stringTokenizer = new StringTokenizer(defaultAlertMessageTo, ","); + internetAddresses = new InternetAddress[stringTokenizer.countTokens()]; + for (int i = 0; i < internetAddresses.length; i++) { + if (stringTokenizer.hasMoreElements()){ + internetAddresses[i] = new InternetAddress((String) stringTokenizer.nextElement()); + } + } + } catch (AddressException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + return internetAddresses; + } + + /** + * Send a general purpose email set from text properties. + */ + public static void sendDefaultAlertEmail() { + Session session = Session.getDefaultInstance(Constants.MAIL_SERVER_PROPERTIES, null); + MimeMessage mimeMessage = new MimeMessage(session); + try { + //"mail.from" set in the properties + //message.setFrom(new InternetAddress(fromEmailAddr)); + for (int i = 0; i < Constants.ALERT_MESSAGE_TO.length; i++) { + mimeMessage.addRecipient(Message.RecipientType.TO, Constants.ALERT_MESSAGE_TO[i]); + } + mimeMessage.setSubject(Constants.ALERT_MESSAGE_SUBJECT); + mimeMessage.setContent(Constants.ALERT_MESSAGE_BODY, "text/html; charset=ISO-8859-1"); + Transport.send(mimeMessage); + } catch (MessagingException ex) { + System.err.println("Cannot send email. " + ex); + ex.printStackTrace(); + } + } +} diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/util/HisUtil.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/util/HisUtil.java new file mode 100644 index 0000000..aadd881 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/util/HisUtil.java @@ -0,0 +1,261 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.hisAppraiser.util; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.security.SecureRandom; +import java.security.Security; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; + +/** + * This class is a central location for utility functions used throughout + * HIS projects. + * @author syelama + * @version Crossbow + * + */ +public class HisUtil { + private static Provider SECURITY_PROVIDER = new BouncyCastleProvider(); + + private static boolean BOUNCY_CASTLE_PROVIDER_LOADED = false; + + static { + loadBouncyCastleProvider(); + } + + /** + * If not already loaded, load the Java Bouncy Castle security provider. + */ +// public static synchronized void loadBouncyCastleProvider() { + public static synchronized void loadBouncyCastleProvider() { + if (BOUNCY_CASTLE_PROVIDER_LOADED) { + return; + } else { + Security.removeProvider(SECURITY_PROVIDER.getName()); + Security.addProvider(SECURITY_PROVIDER); + BOUNCY_CASTLE_PROVIDER_LOADED = true; + } + } + + /** + * @return + */ + public static Provider getProvider() { + return SECURITY_PROVIDER; + } + + /** + * Blocking read of an entire input stream into a byte array. + * @param inputStream Input stream to be read. + * @return Byte array contents of an input stream. + */ + public static byte[] InputStreamToByteArray(InputStream inputStream) { + try { + + int i; + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + + while ((i = inputStream.read()) != -1) { + byteArrayOutputStream.write(i); + } + + return byteArrayOutputStream.toByteArray(); + + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } finally { + try { + inputStream.close(); + } catch (Exception exception) { + exception.printStackTrace(); + } + + } + } + + /** + * Removes white space from a string. + * @param string String from which white space will be removed. + * @return String without white space. + */ + public static String removeWhiteSpace(String string) { + string = string.replace("\r", ""); + string = string.replace("\n", ""); + string = string.replace("\t", ""); + string = string.replace(" ", ""); + return string; + } + + /** + * Turns a hexadecimal string representation to a byte array. + * @param string Hexadecimal formatted string. + * @return Byte array generated from a hexadecimal string representation + */ + public static byte[] unHexString(String string) { + + string = removeWhiteSpace(string); + string = string.toUpperCase().replace("0X", ""); + + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + for (int i = 0; i < string.length(); i += 2) { + byteArrayOutputStream.write(Integer.parseInt(string.substring(i, i + 2), 16)); + } + + return byteArrayOutputStream.toByteArray(); + } + + /** + * Turn a byte array into a hexadecimal string representation. + * @param byteArray Byte array to be converted into a hexadecimal + * string representation. + * @return A string containing a hexadecimal representation of a byte + * array without space or 0x's. + */ + public static String hexString(byte[] byteArray) { + String returnstring = ""; + StringBuffer sb = new StringBuffer(); + for (int i = 0; i < byteArray.length; i++) { + Integer integer = byteArray[i] < 0 ? byteArray[i] + 256 : byteArray[i]; + String integerString = Integer.toString(integer, 16); +// returnstring += integerString.length() == 1 ? "0" + integerString : integerString; + returnstring = sb.append(integerString.length() == 1 ? "0" + integerString : integerString).toString(); + } + + return returnstring.toUpperCase(); + } + + /** + * Changes a byte array which is signed into an int array with values + * ranging from 0 to 255 + * @param byteArray Byte array to be converted to an unsigned + * representation. + * @return An integer array with values ranging from 0 to 255. + */ + public static int[] byteArrayToUnsignedIntArray(byte[] byteArray) { + int[] ints = new int[byteArray.length]; + + for (int i = 0; i < byteArray.length; i++) { + ints[i] = byteArray[i] < 0 ? byteArray[i] + 256 : byteArray[i]; + } + + return ints; + } + + /** + * Generate a secure byte array of a given length. + * @param length Length of the needed byte array. + * @return Byte array of randomly generated numbers. + */ + public static byte[] generateSecureRandom(int length) { + try { + //SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); + SecureRandom random = SecureRandom.getInstance("NativePRNG"); + byte[] bytes = new byte[length]; + random.nextBytes(bytes); + return bytes; + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + /** + * Converts an integer to a byte array of given length + * @param input Integer to be converted + * @param arrayLength Length of the byte array to be returned, padded + * with zeros if necessary. + * @return Byte array representation. + * @throws RuntimeException if the input integer is larger than the byte + * array can hold. + */ + public static byte[] intToByteArray(int input, int arrayLength) { + String string = Integer.toHexString(input); + string = string.length() % 2 == 1 ? "0" + string : string; + int length = arrayLength - (string.length() / 2); + if (length < 0) { + throw new RuntimeException("Integer exceeds length."); + } else { + for (int i = 0; i < length; i++) { + string = "00" + string; + } + } + return HisUtil.unHexString(string); + } + + /** + * Get the sorted selected positions in a byte with the left most + * position as zero. + * @param input Byte to be evaluated + * @return Array of integer positions. + */ + public static SortedSet getSelected(byte input) { + ArrayList arrayList = new ArrayList(); + byte mask = 0x01; + for (int i = 0; i <= 7; i++) { + int value = (input >>> i) & mask; + if (value == 1) { + arrayList.add(7 - i); + } + } + Collections.sort(arrayList); + return Collections.unmodifiableSortedSet(new TreeSet(arrayList)); + } + + public static boolean validParas(HashMap parameters) { + String regex="[#&+:\"\']"; + Pattern p = Pattern.compile(regex); + for (Iterator iter = parameters.keySet().iterator(); iter.hasNext();){ + String key = (String)iter.next(); + Integer value = (Integer)parameters.get(key); + Matcher m = p.matcher(key); + if (key.length() > value.intValue() || m.find() ){ + return false; + } + + } + return true; + } +} \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/util/package-info.java b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/util/package-info.java new file mode 100644 index 0000000..f9a8a15 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/gov/niarl/hisAppraiser/util/package-info.java @@ -0,0 +1,6 @@ +/** + * This package holds general utilities used throughout the HIS project. + * + * @version Crossbow + */ +package gov.niarl.hisAppraiser.util; \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/hibernateOat.cfg.xml b/OpenAttestation/Source/HisAppraiser/src/hibernateOat.cfg.xml new file mode 100644 index 0000000..d680f4d --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/hibernateOat.cfg.xml @@ -0,0 +1,38 @@ + + + + + + + org.hibernate.dialect.MySQLDialect + java:comp/env/jdbc/oat + + thread + org.hibernate.hql.classic.ClassicQueryTranslatorFactory + + org.hibernate.cache.NoCacheProvider + false + true + + + false + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisAppraiser/src/log4j.properties b/OpenAttestation/Source/HisAppraiser/src/log4j.properties new file mode 100644 index 0000000..b94df8a --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/log4j.properties @@ -0,0 +1,31 @@ +# Set root category priority to INFO and its only appender to CONSOLE. +log4j.rootCategory=INFO, CONSOLE +#log4j.rootCategory=INFO, CONSOLE, LOGFILE + +# Set the enterprise logger category to FATAL and its only appender to CONSOLE. +log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE + +# CONSOLE is set to be a ConsoleAppender using a PatternLayout. +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.Threshold=INFO +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=- %m%n + +# LOGFILE is set to be a File appender using a PatternLayout. +log4j.appender.LOGFILE=org.apache.log4j.FileAppender +log4j.appender.LOGFILE.File=axis.log +log4j.appender.LOGFILE.Append=true +log4j.appender.LOGFILE.Threshold=INFO +log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout +log4j.appender.LOGFILE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n + +# Set the HisAppraiser logger category +log4j.logger.gov.niarl.hisAppraiser.hibernate=INFO, HisAppraiser_CONSOLE +log4j.logger.gov.niarl.hisAppraiser=ALL, HisAppraiser_CONSOLE +log4j.logger.gov.niarl.his.xsd=ALL, HisAppraiser_CONSOLE + +# CONSOLE is set to be a ConsoleAppender using a PatternLayout. +log4j.appender.HisAppraiser_CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.HisAppraiser_CONSOLE.Threshold=ALL +log4j.appender.HisAppraiser_CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.HisAppraiser_CONSOLE.layout.ConversionPattern=%d{dd/MMM/yyyy HH:mm:ss} %p - %m%n \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/src/overview.html b/OpenAttestation/Source/HisAppraiser/src/overview.html new file mode 100644 index 0000000..2119060 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/src/overview.html @@ -0,0 +1,6 @@ + + +This project serves as the main library for the server side Java HIS +appraiser components + + diff --git a/OpenAttestation/Source/HisAppraiser/xml/Integrity_Report_Manifest_v1_0/binding.xjb b/OpenAttestation/Source/HisAppraiser/xml/Integrity_Report_Manifest_v1_0/binding.xjb new file mode 100644 index 0000000..24b9dad --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/xml/Integrity_Report_Manifest_v1_0/binding.xjb @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisAppraiser/xml/Integrity_Report_Manifest_v1_0/build.xml b/OpenAttestation/Source/HisAppraiser/xml/Integrity_Report_Manifest_v1_0/build.xml new file mode 100644 index 0000000..43a1d1c --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/xml/Integrity_Report_Manifest_v1_0/build.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisAppraiser/xml/PCR_Difference/PCR_Difference.binding.xjb.xml b/OpenAttestation/Source/HisAppraiser/xml/PCR_Difference/PCR_Difference.binding.xjb.xml new file mode 100644 index 0000000..b470eef --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/xml/PCR_Difference/PCR_Difference.binding.xjb.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisAppraiser/xml/PCR_Difference/PCR_Difference.xjc.bat b/OpenAttestation/Source/HisAppraiser/xml/PCR_Difference/PCR_Difference.xjc.bat new file mode 100644 index 0000000..faf4e1b --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/xml/PCR_Difference/PCR_Difference.xjc.bat @@ -0,0 +1,3 @@ +cd /D %~dp0 +java -jar C:\ApplicationData\jwsdp-1.5\jaxb\lib\jaxb-xjc.jar -d . -b PCR_Difference.binding.xjb.xml PCR_DifferenceXMLSchema.xsd PCR_Difference.xsd +PAUSE \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/xml/PCR_Difference/PCR_Difference.xsd b/OpenAttestation/Source/HisAppraiser/xml/PCR_Difference/PCR_Difference.xsd new file mode 100644 index 0000000..7dc9866 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/xml/PCR_Difference/PCR_Difference.xsd @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/xml/PCR_Difference/PCR_DifferenceXMLSchema.xsd b/OpenAttestation/Source/HisAppraiser/xml/PCR_Difference/PCR_DifferenceXMLSchema.xsd new file mode 100644 index 0000000..8626cd7 --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/xml/PCR_Difference/PCR_DifferenceXMLSchema.xsd @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisAppraiser/xml/PCR_Difference/build.xml b/OpenAttestation/Source/HisAppraiser/xml/PCR_Difference/build.xml new file mode 100644 index 0000000..17e7fed --- /dev/null +++ b/OpenAttestation/Source/HisAppraiser/xml/PCR_Difference/build.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisClient/OAT07.jpg b/OpenAttestation/Source/HisClient/OAT07.jpg new file mode 100644 index 0000000..f5ef979 Binary files /dev/null and b/OpenAttestation/Source/HisClient/OAT07.jpg differ diff --git a/OpenAttestation/Source/HisClient/build.txt b/OpenAttestation/Source/HisClient/build.txt new file mode 100644 index 0000000..1ad2cfc --- /dev/null +++ b/OpenAttestation/Source/HisClient/build.txt @@ -0,0 +1,12 @@ +Build Instructions: + +JAVA Project: + +The JAVA project is designed to be loaded into an IDE such as Netbeans ot Eclipse with the /src directory set for the existing source files and all of the jar files in /lib added to the project. If compiling a jar the gov.niarl.his.StandaloneHIS main method should be set the execution point for the jar. + +Instructions to run and configure the project is located in the official project documentation / wiki. Runtime file placement is also spelled out in these documents. + +Inno Setup Project + +The HIS-installer.iss file is compiled by Inno Setup v5.1.7 and requires all of the files to be loaded into the install archive to be placed according to the locations in the .iss script. + diff --git a/OpenAttestation/Source/HisClient/build.xml b/OpenAttestation/Source/HisClient/build.xml new file mode 100644 index 0000000..e1b298a --- /dev/null +++ b/OpenAttestation/Source/HisClient/build.xml @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisClient/log4j.properties b/OpenAttestation/Source/HisClient/log4j.properties new file mode 100644 index 0000000..a6812df --- /dev/null +++ b/OpenAttestation/Source/HisClient/log4j.properties @@ -0,0 +1,61 @@ +#------------------------------------------------------------------------------ +# +# The following properties set the logging levels and log appender. The +# log4j.rootCategory variable defines the default log level and one or more +# appenders. For the console, use 'S'. For the daily rolling file, use 'R'. +# For an HTML formatted log, use 'H'. +# +# To override the default (rootCategory) log level, define a property of the +# form (see below for available values): +# +# log4j.logger. = +# +# Available logger names: +# TODO +# +# Possible Log Levels: +# FATAL, ERROR, WARN, INFO, DEBUG +# +#------------------------------------------------------------------------------ + +#log4j.rootCategory=FATAL, S, R +#log4j.rootCategory=ERROR, S, R +#log4j.rootCategory=WARN, S, R +log4j.rootCategory=INFO, S, R +#log4j.rootCategory=DEBUG, S, R + + +#------------------------------------------------------------------------------ +# +# The following properties configure the console (stdout) appender. +# See http://logging.apache.org/log4j/docs/api/index.html for details. +# +#------------------------------------------------------------------------------ +log4j.appender.S = org.apache.log4j.ConsoleAppender +log4j.appender.S.layout = org.apache.log4j.PatternLayout +log4j.appender.S.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n + +#------------------------------------------------------------------------------ +# +# The following properties configure the Daily Rolling File appender. +# See http://logging.apache.org/log4j/docs/api/index.html for details. +# +#------------------------------------------------------------------------------ +log4j.appender.R = org.apache.log4j.DailyRollingFileAppender +log4j.appender.R.File = logs/OAT.log +log4j.appender.R.Append = true +log4j.appender.R.DatePattern = '.'yyy-MM-dd +log4j.appender.R.layout = org.apache.log4j.PatternLayout +log4j.appender.R.layout.ConversionPattern = %d{yyyy-MM-dd HH:mm:ss} %c{1} [%p] %m%n + +#------------------------------------------------------------------------------ +# +# The following properties configure the Rolling File appender in HTML. +# See http://logging.apache.org/log4j/docs/api/index.html for details. +# +#------------------------------------------------------------------------------ +log4j.appender.H = org.apache.log4j.RollingFileAppender +log4j.appender.H.File = logs/OATlog.html +log4j.appender.H.MaxFileSize = 100KB +log4j.appender.H.Append = false +log4j.appender.H.layout = org.apache.log4j.HTMLLayout \ No newline at end of file diff --git a/OpenAttestation/Source/HisClient/src/gov/niarl/his/HisListener.java b/OpenAttestation/Source/HisClient/src/gov/niarl/his/HisListener.java new file mode 100644 index 0000000..6673cef --- /dev/null +++ b/OpenAttestation/Source/HisClient/src/gov/niarl/his/HisListener.java @@ -0,0 +1,318 @@ +/************************************************************************** +* 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory +* +* This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright +* protection in the United States. Foreign copyrights may apply. +* +* Redistribution and use in source and binary forms, with or without modification, +* are permitted provided that the following conditions are met: +* +* 鈥�Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* +* 鈥�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. +* +* 鈥�Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY +* nor the names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +* ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.Properties; +import org.apache.log4j.Logger; + +/** This serves as a wrapper for the normal HIS Client that recieves a socket connection from the HIS server + * and triggers HIS to obtain and send a quote via the normal methods. + * + * + * @deprecated Functionality replaced by the On Demand web service polling method, but left as an example alternate On Demand method. + * @author mcbrotz + */ + +public class HisListener +{ + + //global String for the applications working directory + String hisPath="./"; + //The server socket on which the messages are recieved + ServerSocket serverSocket = null; + //The port number + int listenPort = 8888; + + Properties hisProperties = new Properties(); + //The timeout in approximate ms for any blocking function to wait for a process to return + int blockingTimeout=10000; + + public static Logger s_logger = Logger.getLogger( "HIS" ); + + //Property file labels and defaults + public static final String TRUST_STORE_LABEL = "TrustStore"; + public static final String SOCKET_PORT_LABEL = "SocketListnerPort"; + public static final String DEFAULT_SOCKET_PORT = "8888"; + + //Various Constants + public static final String DEFAULT_HIS_PATH = "/OAT/"; + public static final String PROPERTIES_NAME = "OAT.properties"; + public static final String PROPERTIES_EXTENSION = ".properties"; + public static final String DEFAULT_STATE_MESSAGE = "100"; + public static final String SUCCESS_MESSAGE = "success"; + + + /** + * @param args the command line arguments + * + * The first parameter is the working directory. + */ + + public static void main(String[] args) + { + StandaloneHIS his = null; + HisListener client=null; + String path= DEFAULT_HIS_PATH;; + + + //bounds check for presence of the path argument + if(args.length>=0) + { + path = args[0]; + } + + //initialize the two main modules + try + { + client = new HisListener(path); + } + catch(Exception e) + { + System.out.println(e.getMessage()); + e.printStackTrace(); + System.exit(1); + } + + //start the listening loop + client.listen(); + } + + /** Begins a new HIS Listner process. + * + * @param path Path that the HIS Client is running in (same path parameter used in standard HIS Client) + * @throws java.lang.Exception + */ + public HisListener(String path) throws Exception + { + + hisPath = path; + + FileInputStream HISPropertyFile = null; + + try + { + HISPropertyFile = new FileInputStream(hisPath+PROPERTIES_NAME); + } + catch (java.io.FileNotFoundException fnfe) + { + //Try to create the Property File if it is not present + try + { + File fileName= new File(hisPath+PROPERTIES_NAME); // create the directory + fileName.createNewFile(); + HISPropertyFile = new FileInputStream(fileName); + + } + catch (Exception ioe) + { + s_logger.error("HIS Property File empty.\n Unable to create new HIS property file!\n"); + throw new Exception("HIS Property File empty.\n Unable to create new HIS property file!\n"); + } + } + + s_logger.debug( "Using HIS Property File: "+ HISPropertyFile.toString()); + + //If we load in a file put it in to a proprties object +// if(HISPropertyFile!=null) +// { + try + { + hisProperties.load(HISPropertyFile); + + } + catch (java.io.FileNotFoundException fnfe) + { + s_logger.error( "HIS Property file not found on Property load!" ); + throw new Exception("HIS Property file not found on Property load!"); + } + catch (java.io.IOException ioe) + { + s_logger.error( "Error loading HIS Property file!" ); + throw new Exception("Error loading HIS Property file!"); + } + finally{ + HISPropertyFile.close(); + } +// } +// else +// { +// s_logger.error( "Error loading HIS Property file!" ); +// throw new Exception("Error loading HIS Property file!"); +// } + + //Initialize the SSL Trust store + String trustStoreUrl = hisProperties.getProperty(TRUST_STORE_LABEL,hisPath+"TrustStore.jks"); + System.setProperty("javax.net.ssl.trustStore", trustStoreUrl); + + //get the socket listening port + listenPort = Integer.parseInt(hisProperties.getProperty(SOCKET_PORT_LABEL, DEFAULT_SOCKET_PORT)); + + //Set up the listening socket + try + { + serverSocket = new ServerSocket(listenPort); + } + catch (IOException e) + { + s_logger.error("Could not listen on port: "+listenPort, e); + System.exit(1); + } + } + + /** Perpetually loops, listening for and acting upon connections + * + * + */ + + private void listen() + { + Socket clientSocket=null; + PrintWriter out=null; + BufferedReader in=null; + String inputLine="000"; + StandaloneHIS his; + + + while(true) + { + + //Open the connection with the client + try + { + //this blocks until a connection is made + clientSocket = serverSocket.accept(); + out = new PrintWriter(clientSocket.getOutputStream(), true); + in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + } + catch(IOException ioe) + { + if (clientSocket != null) + { + try { + clientSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + s_logger.error("Could not accept connection!", ioe); + + } + + try + { + + //read the input from the steam. Initial message should be short so no need for loop here + //NOTE One might want to add input while loop for extended messages or protocols + if (in != null) + { + inputLine = in.readLine(); + } + + //if the input message matches we should activate the HIS Standalone app. + if (inputLine != null) + { + if(inputLine.equals(DEFAULT_STATE_MESSAGE)) + { + + + //run the integrity check + try + { + //Set up the his object + his = new StandaloneHIS(hisPath, false, false); + his.checkIntegrity(); + } + catch(Exception e) + { + s_logger.error("Error generating quote!", e); + System.out.println(e.getMessage()); + e.printStackTrace(); + } + + //when the integrity check completes return a courtesy success message + out.println(SUCCESS_MESSAGE); + + } + else + { + System.out.println("Unknown recieved message: "+inputLine); + s_logger.warn("Unknown recieved message: "+inputLine); + } + } + + + } + catch(IOException ioe) + { + s_logger.error("Could not read from I/O stream!", ioe); + } + finally + { + //close the sockets and wait for the next connection + if (in != null) + { + try + { + in.close(); + } + catch (IOException e) + { + e.printStackTrace(); + } + } + if (out != null) + out.close(); + if (clientSocket != null) + { + try + { + clientSocket.close(); + } + catch (IOException e) + { + e.printStackTrace(); + } + } + } + } + } + +} diff --git a/OpenAttestation/Source/HisClient/src/gov/niarl/his/HisSplash.java b/OpenAttestation/Source/HisClient/src/gov/niarl/his/HisSplash.java new file mode 100644 index 0000000..9983ed2 --- /dev/null +++ b/OpenAttestation/Source/HisClient/src/gov/niarl/his/HisSplash.java @@ -0,0 +1,161 @@ +/************************************************************************** +* 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory +* +* This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright +* protection in the United States. Foreign copyrights may apply. +* +* Redistribution and use in source and binary forms, with or without modification, +* are permitted provided that the following conditions are met: +* +* 鈥�Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* +* 鈥�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. +* +* 鈥�Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY +* nor the names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +* ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his; + +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Toolkit; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JWindow; +import javax.swing.SwingUtilities; + +/** Helper class that enables and shows the HIS splash image + * + * @author mcbrotz + */ + + +//This was largely copied from a template +public class HisSplash extends JWindow { + + private int duration; + String imgFilePath; + + /** Creates a new HisSplash object. + * + * @param d The duration the splash screen is displayed for + * @param path The path to the image file to be displayed. + */ + public HisSplash(int d, String path) { + duration = d; + imgFilePath= path; + } + + + /** Shows the HIS Splash image + * + */ + public void showSplash() { + + JPanel content = (JPanel)getContentPane(); + content.setBackground(Color.white); + + Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); + // Build the splash screen + JLabel label = new JLabel(new ImageIcon(imgFilePath)); + + + //set the image to be displayed in the middle of the screen + Dimension labelSize = label.getPreferredSize(); + int x = (screen.width-labelSize.width)/2; + int y = (screen.height-labelSize.height)/2; + setBounds(x,y,labelSize.width,labelSize.height); + + + content.add(label, BorderLayout.CENTER); + + //allow the users to click the image and make it disappear. + addMouseListener(new MouseAdapter() + { + public void mousePressed(MouseEvent e) + { + setVisible(false); + dispose(); + } + }); + + ///inner class that displays and runs the splash screen in its own thread. + final int pause = duration; + final Runnable closerRunner = new Runnable() + { + public void run() + { + setVisible(false); + dispose(); + } + }; + Runnable waitRunner = new Runnable() + { + public void run() + { + try + { + Thread.sleep(pause); + SwingUtilities.invokeAndWait(closerRunner); + } + catch(Exception e) + { + e.printStackTrace(); + // can catch InvocationTargetException + // can catch InterruptedException + } + } + }; + setVisible(true); + Thread splashThread = new Thread(waitRunner, "SplashThread"); + splashThread.start(); + + + // Display it + setVisible(true); + + // Wait a little while, maybe while loading resources + try + { + Thread.sleep(0); + } + catch (Exception e) + { + e.printStackTrace(); + } + + + + } + + /** Shows the HIS Splash image and exits. Used for the HIS branding mode. + * + */ + public void showSplashAndExit() { + + showSplash(); + System.exit(0); + + } + +} \ No newline at end of file diff --git a/OpenAttestation/Source/HisClient/src/gov/niarl/his/StandaloneHIS.java b/OpenAttestation/Source/HisClient/src/gov/niarl/his/StandaloneHIS.java new file mode 100644 index 0000000..7b6338e --- /dev/null +++ b/OpenAttestation/Source/HisClient/src/gov/niarl/his/StandaloneHIS.java @@ -0,0 +1,2311 @@ +/************************************************************************** +* 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory +* +* This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright +* protection in the United States. Foreign copyrights may apply. +* +* Redistribution and use in source and binary forms, with or without modification, +* are permitted provided that the following conditions are met: +* +* ...Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* +* ...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. +* +* ...Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY +* nor the names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +* ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his; + +import gov.niarl.sal.webservices.hisWebService.client.*; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.Action; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.ActionDelay; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.HisPollingWebService; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.HisWebService; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.NonceSelect; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.Quote; +import java.util.Properties; +import org.apache.log4j.Logger; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.math.BigInteger; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Arrays; +import java.util.List; +import java.util.StringTokenizer; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.Marshaller; + +import org.apache.log4j.PropertyConfigurator; +import org.trustedcomputinggroup.xml.schema.core_integrity_v1_0_1_.ComponentIDType; +import org.trustedcomputinggroup.xml.schema.core_integrity_v1_0_1_.DigestMethodType; +import org.trustedcomputinggroup.xml.schema.core_integrity_v1_0_1_.ObjectFactory; +import org.trustedcomputinggroup.xml.schema.core_integrity_v1_0_1_.ValueType; +import org.trustedcomputinggroup.xml.schema.core_integrity_v1_0_1_.VendorIdType; +import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.PcrCompositeType; +import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.PcrSelectionType; +import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.QuoteDataType; +import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.QuoteInfoType; +import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.QuoteSignatureType; +import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.QuoteType; +import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.ReportType; +import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.SnapshotType; +import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.PcrCompositeType.PcrValue; +import org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.TpmDigestValueType; +import org.trustedcomputinggroup.xml.schema.simple_object_v1_0_.SimpleObjectType; +import org.trustedcomputinggroup.xml.schema.simple_object_v1_0_.ValuesType; +import org.trustedcomputinggroup.xml.schema.core_integrity_v1_0_1_.DigestValueType; +import org.w3._2000._09.xmldsig_.KeyInfoType; +import org.w3._2000._09.xmldsig_.KeyValueType; +import org.w3._2000._09.xmldsig_.SignatureMethodType; +import org.w3._2000._09.xmldsig_.SignatureValueType; + + + + + + +/** StandaloneHIS is a self contained client application for the Host Integrity at Startup (HIS) system. + * This application can be run as any other and will query the local Trusted Platform Module (TPM) for + * host integrity measurements in the form of a signed Quote.
+ *
+ * The HIS Client makes use of binary TPM Interface Module to access the TPM via a system call, + * a TCG defined XML integrity report format and web service stype communications with a back end HIS server.
+ *
+ * The HIS Client can be run in a once through mode that runs the reporting process and then terminates or + * an On Demand mode that sets the process to poll for instructions via web services. + * The On Demand mode has expanded the range of functions that the HIS Client can carry out + * including capabilities for system reboot (in order to generate fresh measurements) and process + * specially configured commands in order to handle scenarios with virtualized guest environments.
+ *
+ * The HIS Client application uses log4j logging as well as sending special Error Reports to the back end server. + * In addition to this certain errors also print to Std Out or Std Err to better enable field debugging. + *
+ * The HIS Client also makes use of a HIS.properties file located in the root of the application path supplied as an argument. + * This property file contains all of the Client's configuration data. While defaults can be substituted lack of a + * proper configuration will cause the HIS Client to not function. + *
+ * Other dependencies include both a binary TPM interface module and splash screen image, the location of which are pointed to in the HIS.properties file. + *
+ * + * + * @author mcbrotz + */ +public class StandaloneHIS +{ + + //Version for the UUID + public static String UUID_VERSION = "1"; + //Prefix to differentiate the snapshot ID space + public static final String SNAPSHOT_PREFIX = "S"; + //Prefix to differentiate the snapshot ID space + public static final String QUOTE_PREFIX = "Q"; + //TCG Required Quote Version Major Value - placeholder + public static final short QUOTE_VERSION_MAJOR = 0x01; + //TCG Required Quote Version Minor Value - placeholder + public static final short QUOTE_VERSION_MINOR = 0x01; + //TCG Required Quote Version Rev Major Value - placeholder + public static final short QUOTE_VERSION_REV_MAJOR = 0x00; + //TCG Required Quote Version Rev Minor Value - placeholder + public static final short QUOTE_VERSION_REV_MINOR = 0x00; + //Fimename for auto-reg cert file + //public static final String AIC_FILNAME = "AIK.cer"; + //Snapshot Revision Number + public static final String SNAPSHOT_REV_LEVEL = "0"; + //size of the PCR bitmask in bytes + //TODO make this a property? + //public static final int PCR_BITMASK_SIZE = 3; + //variable for the PCR bitmask + private byte[] pcrBitmask; + //default value for the pcr bitmask + public static final byte[] DEFAULT_PCR_BITMASK = {(byte)0xff, (byte)0xff, (byte)0xff}; + //Default blocking timeout value in whole seconds. + public static final String DEFAULT_TIMEOUT_VALUE = "10"; + + //command flags for the native interface + public static final String MODE_FLAG = "-mode"; + public static final String NONCE_FLAG = "-nonce"; + public static final String BITMASK_FLAG = "-mask"; + public static final String KEY_AUTH_FLAG = "-key_auth"; + public static final String KEY_INDEX_FLAG = "-key_index"; + + //Properties file object for the application + Properties hisProperties = new Properties(); + + //The timeout in approximate ms for any blocking function to wait for a process to return + int blockingTimeout=10000; + int splashDuration = 3000; + + //The nonce for the TPM quote + String nonce=""; + //This is the raw bitmask as sent by the web service + String rawBitmask=""; + //global String for the applications working directory + String hisPath="./"; + //The type of appraiser registration to use, manual or auto + //String regType = "manual"; + //the flag for the running OS + int hostOS=0; + //host name of the local computer + String computerName= "unknownHost"; + + //name for the log4j properties file + public static final String LOG4J_PROPERTIES_FILE = "log4j.properties"; + + public static Logger s_logger; + + //Web Service variables + HisWebService hisAuthenticationWebService; + String webServiceUrl = ""; + + //Property labels and defaults + public static final String TPM_QUOTE_EXECUTABLE_NAME_LABEL = "TpmQuoteExecutableName"; + public static final String TPM_QUOTE_EXECUTABLE_PATH_LABEL = "TpmQuoteExecutablePath"; + public static final String VENDOR_GUID_LABEL = "VendorGUID"; + public static final String VENDOR_NAME_LABEL = "Vendor"; + public static final String MODEL_NAME_LABEL = "ModelName"; + public static final String MODEL_NUMBER_LABEL = "ModelNumber"; + public static final String VERSION_MAJOR_LABEL = "ModelMajorRev"; + public static final String VERSION_MINOR_LABEL = "ModelMinorRev"; + public static final String WEB_SERVICE_URL_LABEL = "WebServiceUrl"; + public static final String MODEL_SN_LABEL = "ModelSerialNumber"; + public static final String MODEL_PATCH_LEVEL_LABEL = "PatchLevel"; + public static final String MODEL_MFG_DATE_LABEL = "MfgDate"; + public static final String BLOCKING_TIMEOUT_LABEL = "BlockingTimeout"; + public static final String KEY_AUTH_LABEL = "KeyAuth"; + public static final String KEY_INDEX_LABEL = "KeyIndex"; + public static final String TRUST_STORE_LABEL = "TrustStore"; + public static final String SPLASH_IMAGE_LABEL = "SplashImage"; + public static final String POLLING_PERIOD_LABEL = "PollingPeriod"; + public static final String UUID_VERSION_LABEL = "UUIDversion"; + //public static final String REGISTRATION_TYPE_LABEL = "RegistrationType"; + public static final String OS_TYPE_LABEL = "OSType"; + public static final String VERIFY_COMMAND_LABEL = "VerifyClientAction"; + public static final String CLEAN_COMMAND_LABEL = "CleanClientAction"; + + //OS Type ID + static final int WINDOWS_OS = 1; + static final int LINUX_OS = 2; + public static final String WINDOWS_OS_TAG ="W"; + public static final String LINUX_OS_TAG ="X"; + + //Various Constants + public static final String DEFAULT_HIS_PATH = "/OAT/"; + public static final String PROPERTIES_NAME = "OAT.properties"; + public static final String PROPERTIES_EXTENSION = ".properties"; + public static final String DEFAULT_KEY_AUTH = "0123456789012345678901234567890123456789"; + public static final String DEFAULT_KEY_INDEX = "1"; + public static final String DEFAULT_POLLING_VALUE = "30"; + public static final String TPM_QUOTE_MODE = "5"; + public static final String TPM_QUOTE1_MODE = "56"; + public static final String TPM_QUOTE2_MODE = "24"; + public static final String ERROR_MESSAGE_ID = "0001"; + public static final String UNLOCK_SCREEN_MESSAGE_ID = "0002"; + public static final String WINDOWS_REBOOT_CMD = "shutdown -r"; + public static final String LINUX_REBOOT_CMD = "shutdown -r 15"; + + public static boolean clientStartUpDone = false; + public static boolean lastReportSendSuccess = true; + + String reportType = "start"; + //global variable that indicates the quote type to be used + int quoteType=2; + + //TPM Quote Struct Constants + public static final String EXPECTED_QUOTE_VERSION_TAG = "01010000"; + public static final String QUOTE_FIXED = "QUOT";//TCG Defined Quote Info Fxied Value + //public static final int SEGMENT_LENGH_FIELD_SIZE = 4; + public static final int PCR_MAX_NUM = 24; + public static final int PCR_FIELD_SIZE = 2; + public static final int PCR_LENGTH_SIZE = 2; + public static final int PCR_SIZE = 20; + public static final int QUOTE_SIZE = 48; + public static final int QUOTE_VERSION_SIZE = 4; + public static final int QUOTE_FIXED_SIZE = 4; + public static final int PCR_HASH_SIZE = 20; + public static final int NONCE_SIZE = 20; + public static final int SIGNATURE_SIZE = 256; + //TPM Quote 2 Struct Constants + public static final int QUOTE2_SIZE_BASE = 49;//not including variable length bitmask + public static final byte[] EXPECTED_QUOTE2_VERSION_TAG = {(byte)0x00, (byte)0x36}; + public static final String QUOTE2_FIXED = "QUT2"; //TCG Defined Quote 2 Info Fxied Value + public static final String QUOTE2_FILLER_BYTE = "01"; + public static final int QUOTE2_VERSION_SIZE = 2; + public static final int QUOTE2_BITMASK_LENGTH_SIZE = 2; + + + String tpmOutput = ""; + private static long lastByteBIOS; + private static long lastByteIMA; + private static byte[][] lastPcrHash = new byte[PCR_MAX_NUM][20]; + private static int[] lastEventCount = new int[PCR_MAX_NUM]; + + /** + * Removes white space from a string. + * @param string String from which white space will be removed. + * @return String without white space. + */ + public static String removeWhiteSpace(String string) { + string = string.replace("\r", ""); + string = string.replace("\n", ""); + string = string.replace("\t", ""); + string = string.replace(" ", ""); + return string; + } + + /** + * Turns a hexadecimal string representation to a byte array. + * @param string Hexadecimal formatted string. + * @return Byte array generated from a hexadecimal string representation + */ + public static byte[] unHexString(String string) { + + string = removeWhiteSpace(string); + string = string.toUpperCase().replace("0X", ""); + + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + for (int i = 0; i < string.length(); i += 2) { + byteArrayOutputStream.write(Integer.parseInt(string.substring(i, i + 2), 16)); + } + + return byteArrayOutputStream.toByteArray(); + } + + /** + * Turn a byte array into a hexadecimal string representation. + * @param byteArray Byte array to be converted into a hexadecimal + * string representation. + * @return A string containing a hexadecimal representation of a byte + * array without space or 0x's. + */ + public static String hexString(byte[] byteArray) { + String returnstring = new String(); + + for (int i = 0; i < byteArray.length; i++) { + Integer integer = byteArray[i] < 0 ? byteArray[i] + 256 : byteArray[i]; + String integerString = Integer.toString(integer, 16); + returnstring += integerString.length() == 1 ? "0" + integerString : integerString; + } + + return returnstring.toUpperCase(); + } + + + + /** Main medhod for running the application.
+ *
+ * @param args the command line arguments
+ *
+ * The first parameter is the working directory. + *
+ * The second is the flasg to handle the splash screen:
+ * -s if the splash screen is to be displayed
+ * -b if the splash screen is to be displayed without running the TPM report
+ * -d if the HIS client is to be run in dynamic mode (disables splash screen)
+ *
+ * The parameters can be used individually, but only one of each
+ */ + public static void main(String[] args) + { + String path=DEFAULT_HIS_PATH; + StandaloneHIS his=null; + boolean dynamicHIS = false; + boolean showSplash = false; + boolean brandHIS = false; + + //bounds check for presence of the first argument + if(args.length>=1) + { + //check for the presence of a second argument, path first + if(args.length>=2 && (args[1].equals("-s")||args[1].equals("-b")||args[1].equals("-d"))) + { + if(args[1].equals("-s")) + { + showSplash = true; + path = args[0]; + } + if(args[1].equals("-b")) + { + brandHIS=true; + path = args[0]; + } + if(args[1].equals("-d")) + { + dynamicHIS = true; + path = args[0]; + } + } + //check for the presence of a second argument, path second just in case the user screws up + else if(args.length>=2 && (args[0].equals("-s")||args[0].equals("-b")||args[0].equals("-d"))) + { + if(args[0].equals("-s")) + { + showSplash = true; + path = args[1]; + } + if(args[0].equals("-b")) + { + brandHIS=true; + path = args[1]; + } + if(args[0].equals("-d")) + { + dynamicHIS = true; + path = args[1]; + } + + } + else if(args[0].equals("-d")) + { + dynamicHIS=true; + } + else if(args[0].equals("-b")) + { + brandHIS=true; + } + else if(args[0].equals("-s")) + { + showSplash = true; + } + else + { + path = args[0]; + } + + } + + System.out.println("Flags recieved: Brand = "+brandHIS+", Show Splash = "+showSplash+", On Demand = "+dynamicHIS+", Path = "+path); + + try + { + his = new StandaloneHIS(path, showSplash, brandHIS); + } + catch(Exception e) + { + e.printStackTrace(); + System.exit(1); + } + + //run the integrity check once + try + { + his.checkIntegrity(); + clientStartUpDone = true; + } + catch(Exception e) + { + e.printStackTrace(); + //System.exit(1); + } + + //if we are setting up dynamic polling do it + //If entered this function will not return. + if(dynamicHIS) + { + his.dynamicPoll(); + } + + + } + + /** Constructor. Loads HIS property file, various properties and other global variables + * + * @param path The path to where the HIS files have been installed + * @param splash Is the splash scteen to be displayed + * @param brand Is HIS in branding mode + * @throws java.lang.Exception Thown is HIS has a problem + */ + + public StandaloneHIS(String path, boolean splash, boolean brand) throws Exception + { + resetScalabilityCounters(); + + if(path.length() == 0) + { + path = DEFAULT_HIS_PATH; + } + + hisPath = path; + + //set up the logging. + PropertyConfigurator.configure(hisPath+LOG4J_PROPERTIES_FILE); + s_logger = Logger.getLogger( "HIS" ); + + + //Set up the HIS properties file. + FileInputStream HISPropertyFile = null; + + try + { + HISPropertyFile = new FileInputStream(hisPath+PROPERTIES_NAME); + } + catch (java.io.FileNotFoundException fnfe) + { + s_logger.warn( "HIS Property file not found!" ); + //Try to create the Property File if it is not present + try + { + File fileName= new File(hisPath+PROPERTIES_NAME); // create the directory + fileName.createNewFile(); + HISPropertyFile = new FileInputStream(fileName); + s_logger.debug( "Using HIS Property File: "+ HISPropertyFile.toString()); + + } + catch (Exception ioe) + { + s_logger.error("HIS Property File empty.\n Unable to create new HIS property file!\n"); + } + } + + + //If we load in a file put it in to a proprties object + if(HISPropertyFile!=null) + { + try + { + hisProperties.load(HISPropertyFile); + + } + catch (java.io.FileNotFoundException fnfe) + { + s_logger.error( "HIS Property file not found on Property load!" ); + } + catch (java.io.IOException ioe) + { + s_logger.error( "Error loading HIS Property file!" ); + } + finally{ + HISPropertyFile.close(); + } + } + else + { + s_logger.error( "Error loading HIS Property file!" ); + } + + //Set various properties + blockingTimeout = 1000 * new Integer(hisProperties.getProperty(BLOCKING_TIMEOUT_LABEL, DEFAULT_TIMEOUT_VALUE)).intValue(); + + //Set up the Web services + + //Initialize the SSL Trust store + String trustStoreUrl = hisPath+hisProperties.getProperty(TRUST_STORE_LABEL,"./TrustStore.jks"); + System.setProperty("javax.net.ssl.trustStore", trustStoreUrl); + + //Pull the URLs from properties + webServiceUrl = hisProperties.getProperty(WEB_SERVICE_URL_LABEL,""); + + //Set the UUID version number + UUID_VERSION = hisProperties.getProperty(UUID_VERSION_LABEL, "1"); + + //get the registration type + //regType = hisProperties.getProperty(REGISTRATION_TYPE_LABEL, "manual"); + + //Set the web service URL + webServiceUrl = hisProperties.getProperty(WEB_SERVICE_URL_LABEL,""); + + //check for valid URLs. + if(webServiceUrl.length() == 0) + { + throw new Exception("Web Service URL not present. Unable to initialize HIS client."); + } + + //get the OS type + String hostOSstr = hisProperties.getProperty(OS_TYPE_LABEL, ""); + + if(hostOSstr.equals(WINDOWS_OS_TAG)) + { + hostOS = WINDOWS_OS; + } + else if(hostOSstr.equals(LINUX_OS_TAG)) + { + hostOS = LINUX_OS ; + } + else{hostOS=0;} + + //Obtain the computer name + try + { + //computerName = InetAddress.getLocalHost().getCanonicalHostName(); + computerName = InetAddress.getLocalHost().getHostName(); + s_logger.debug("Computer name found as: "+computerName); + } + + catch(Exception ex) + { + //computerName="DefaultHost"; + //s_logger.warn("Computer name set to default"); + + //UnknownHostException will be thrown sometime on RHEL, + //so get computer name from the exception msg + StringTokenizer st = new StringTokenizer(ex.getMessage()); + while (st.hasMoreTokens()) computerName = st.nextToken(); + } + + //pull the splash image from properties + String splashFile = hisProperties.getProperty(SPLASH_IMAGE_LABEL); + + System.out.println("Splash path = "+hisPath + splashFile); + + //only display a splash screen if a splash image file has been entered and the flag is set + if(splashFile!=null && (splash == true || brand == true)) + { + new HisSplash(splashDuration, hisPath + splashFile).showSplash(); + //if we are in Branding mode show the splash screen and exit + if(brand == true) + { + s_logger.info( "HIS branding display complete" ); + Thread.sleep(splashDuration+100); + System.exit(0); + } + } + + + } + + /** This function sets up the HIS application into a dynamic polling mode where the app will poll a web service to determine if it needs to send back a report. + * + * The poll interval is set within the property file and defaults to 30 seconds. + * + * + */ + + public void dynamicPoll() + { + HisPollingWebService hisPollingWebService = null; + ActionDelay actionDelay = null; + Action action = null; + long pollInterval; + int defaultPollInterval; + + //load the default polling interval value in whole seconds + defaultPollInterval = new Integer(hisProperties.getProperty(POLLING_PERIOD_LABEL, DEFAULT_POLLING_VALUE)).intValue(); + + //make a call to the web service to get the type of action and action delay + hisPollingWebService = HisWebServicesClientInvoker.getHisPollingWebService(webServiceUrl);//"http://toc.dod.mil:8080/HisWebServices"); + + //enter a polling loop + while(true) + { + pollInterval = 0; + action = Action.DO_NOTHING; + + + try + { + if(hisPollingWebService==null) + { + System.out.println("Web service object null"); + } + + else{ + actionDelay = hisPollingWebService.getNextAction(computerName); + action = actionDelay.getAction(); + + //save the delay until the next poll + pollInterval = actionDelay.getDelayMilliseconds(); + } + + } + catch (Exception e) + { + resetScalabilityCounters(); + lastReportSendSuccess = false; + + //we want to trigger the default polling interval if there is a web service exception + pollInterval=0; + + //Handle the exception by reporting the error, but do not kill the loop + s_logger.error( "On Demand web service Error: "+e.getMessage() ); + System.out.println( "On Demand web service Error: "+e.getMessage() ); + //e.printStackTrace(); + } + + switch (action) + { + case DO_NOTHING: + System.out.println("Action:DO_NOTHING"); + s_logger.debug("Action:DO_NOTHING"); + break; + case SEND_REPORT: + System.out.println("Action:SEND_REPORT"); + s_logger.debug("Action:SEND_REPORT"); + try + { + checkIntegrity(); + lastReportSendSuccess = true; + } + catch(Exception e) + { + resetScalabilityCounters(); + lastReportSendSuccess = false; + + e.printStackTrace(); + s_logger.error( "Error checking integrity on demand: "+e.getMessage() ); + } + break; + case REBOOT: + System.out.println("Action:REBOOT"); + s_logger.debug("Action:REBOOT"); + //TODO ENABLE THIS WHEN SAFE + restartComputer(hostOS); + break; + case VERIFY_CLIENT: + System.out.println("Action: VERIFY CLIENT"); + s_logger.debug("Action: VERIFY CLIENT"); + + if (actionDelay != null) + commandProcessor(VERIFY_COMMAND_LABEL, actionDelay.getArgs() == null? "":actionDelay.getArgs()); + break; + + case CLEAN_CLIENT: + System.out.println("Action: CLEAN CLIENT"); + s_logger.debug("Action: CLEAN CLIENT"); + if (actionDelay != null) + commandProcessor(CLEAN_COMMAND_LABEL, actionDelay.getArgs() == null? "":actionDelay.getArgs()); + break; + } + action = null; + //delay for the poll interval + try + { + if(pollInterval==0) + { + Thread.sleep(defaultPollInterval*1000); + } + else + { + if (actionDelay != null) + Thread.sleep(pollInterval); + } + + } + //do we care about this o.0 + catch(InterruptedException e) + { + e.printStackTrace(); + } + } + + } + + /** Method performs a system integrity check by calling the TPM and returning the Report. + * + * @throws java.lang.Exception + */ + + public void checkIntegrity() throws Exception + { + s_logger.debug( "Checking system integrity" ); + + int bitCount=0; //number of PCR values asked for in the bitmask + + String userName; + String tpmInput=""; + byte[] b = new byte[4]; + ReportType report; + SnapshotType snap; + QuoteDataType quote; + String errMsg="*"; + String quoteMode = TPM_QUOTE_MODE; + + //get the key Auth and Index properties + String keyAuth = hisProperties.getProperty(KEY_AUTH_LABEL, DEFAULT_KEY_AUTH); + String keyIndex = hisProperties.getProperty(KEY_INDEX_LABEL, DEFAULT_KEY_INDEX); + s_logger.debug("Using Key Auth " + keyAuth + " and Key Index " + keyIndex + ".\n"); + + //Get the username + userName = System.getProperty("user.name"); + s_logger.debug("User name found as: "+userName); + + //Initialize the web service + hisAuthenticationWebService = HisWebServicesClientInvoker.getHisWebService(webServiceUrl); + + //this sets the nonce and bitmask global variables via a web service call + try + { + getReportParams(userName, computerName); + + } + //Failure to get proper params will result in an error report + catch(Exception e) + { + s_logger.error("Error recieving server Nonce and Bitmask."); + + report = createEmptyReport("Error recieving server Nonce and Bitmask: "+ e.getMessage(), ERROR_MESSAGE_ID); + + sendIntegrityReport(report); + + throw new Exception( "Error recieving server Nonce and Bitmask. " + e.getMessage()); + + } + + //log the nonce and bitmask + s_logger.debug("Nonce recieved: "+nonce); + s_logger.debug("Bitmask recieved: "+rawBitmask); + + //convert the raw bitmask to one that we can use + try + { + pcrBitmask = unHexString(rawBitmask); + } + //if there is a problem, use default + catch(Exception e) + { + pcrBitmask = DEFAULT_PCR_BITMASK; + s_logger.error("Error recieving PCR Bitmask. Using default value."); + } + + //if the bitmask is invalid, use default + if(pcrBitmask.length>3 || pcrBitmask.length<1) + { + pcrBitmask = DEFAULT_PCR_BITMASK; + s_logger.error("Error recieving PCR Bitmask. Using default value."); + } + + //select the TPM QUOTE Mode (v1 or v2) based on the parameter from the web service (formerly bitmask length) + if(quoteType == 2)//pcrBitmask.length == 3)// quoteType == 2) + { + //quoteType = 2; + quoteMode = TPM_QUOTE2_MODE; + } + else if(quoteType == 1)//pcrBitmask.length == 2) + { + //quoteType = 1; + quoteMode = TPM_QUOTE_MODE; + } + else + { + //quoteType = 1; + quoteMode = TPM_QUOTE_MODE; + } + + //construct the input string + tpmInput = MODE_FLAG + " " + quoteMode + " " + BITMASK_FLAG + " "+ rawBitmask + " " + NONCE_FLAG + + " " + nonce + " " + KEY_AUTH_FLAG + " " + keyAuth + " " + KEY_INDEX_FLAG + " " + keyIndex; + + //make the TPM call that gets the required PCR values. The complete return is stored in the member variable tpmOutput + errMsg = runTPMrequest(tpmInput); + + //If we don't get a responce handle the error by creating an empty report and sending that back +// if(!errMsg.equals("")) + if (errMsg.length() != 0) + { + report = createEmptyReport(errMsg, ERROR_MESSAGE_ID); + + sendIntegrityReport(report); + + throw new Exception( "Error retrieving TPM data! " + errMsg); + } + + //count all the bits in the mask + //Made more complicated by Java's lack of support for bits + for(int i = 0; i=blockingTimeout) + { + //kill the threads + sp.interrupt(); + so.interrupt(); + //kill the process + proc.destroy(); + so.stopThread(); + sp.stopThread(); + + System.out.println("TPM Quote interface timeout, process aborted. Unable to capture quote."); + s_logger.error("TPM Quote interface timeout, process aborted. Unable to capture quote."); + return "TPM Interface Timeout"; + } + + //if we get a non-0 return value then we also have a problem + if(exitVal!=0) + { + System.out.println("TPM Quote interface returned error code "+exitVal+"."); + s_logger.error("TPM Quote interface returned error code "+exitVal+"."); + return "TPM error: "+exitVal; + } + + //Provide time for the output to be read from StdOut + while(j<=dataTimeout ) + { + if (this.tpmOutput.length() < 1) + Thread.sleep(1);// give a litte extra time before stopping the other threads so Output can be updated + else break; + j++; + } + + //if j has reached the data wait timeout + if(j>=dataTimeout ) + { + //kill the process + proc.destroy(); + //kill the threads + sp.interrupt(); + so.interrupt(); + so.stopThread(); + sp.stopThread(); + + //throw new IOException("TPM interface data wait timeout, process aborted. Unable to capture TPM data."); + s_logger.error("TPM interface data wait timeout, process aborted. Unable to capture TPM data."); + return "TPM Data Timeout"; + } + + so.stopThread(); + sp.stopThread(); + + } + catch(Throwable t) + { + t.printStackTrace(); + + System.out.println("Error running TPM Quote interface! Unable to capture quote."); + + s_logger.error("Error running TPM Quote interface! Unable to capture quote.", t); + return "TPM Interface Unavailable: "+t.getMessage(); + } + + + return ""; + + } + + /** Generates the base XML integrity report accouting to the TCG Integrity Report 1.0 Scheema + * Report needs to have the Quote and Snapshot data added to it later + * + * @param hostName The hostname of the machine + * + */ + + private ReportType createIntegrityReport(String hostName) + { + ReportType report = new ReportType(); + String reportID; + + //Set the Report ID to the host name concatonated with the time ++ + reportID = hostName + "-" + reportType + "-" + System.currentTimeMillis(); + report.setID(reportID); + + //Set the UUID to the UUID prefix concatonated with the reportID ++ + report.setUUID(generateUUID(UUID_VERSION)); + + + return report; + + } + + /** Creates an empty report with no quote structure. This is used in case there is an issue accessing the TPM or no TPM is installed. + * @param message a message proviging the reason for the empty report + * @param messageTag a code setting the class of message sent in the Empty report + * + * @return the empty integrity report with message in the snapshot + */ + + private ReportType createEmptyReport(String message, String messageTag) + { + ReportType report; + SnapshotType snap; + String taggedMessage; + + //combine the message and the ID to avoid problems using the any type + taggedMessage = messageTag + "-" + message; + + //create the base integrity report + report = createIntegrityReport(computerName); + + //Set up the system snapshot with the error message + snap = createSnapshot(report.getID(), taggedMessage); + report.getSnapshotCollection().add(snap); + + return report; + + } + + /** This creates the system snapshot object. The snapshot can contain a listing of all the system components and their various attributes + * Only one component is required along with various snapshot ID. Each component element itself have a large list of optional data that pertains solely to that component. + * + * This method is currently only filling in the single required component element with default values. + * + * Also used for the error report by stuffing the error report into the Value Type field. + * + * The PcrHash must be added seperately. + * + * @param id The ID number for the overall integrity report. + * @param taggedMessage A message string tagged with an appropiate value for use in Error reports or to send other information to the server + */ + + private SnapshotType createSnapshot(String id, String taggedMessage) + { + SnapshotType snap = new SnapshotType(); + ComponentIDType component = new ComponentIDType(); + VendorIdType vendorID = new VendorIdType(); + JAXBElement vendorGUID = new ObjectFactory().createVendorIdTypeVendorGUID(hisProperties.getProperty(VENDOR_GUID_LABEL, "0000")); + ValueType messageValue = new ValueType();//Error message storage + KeyValueType kv = new KeyValueType();//Error message storage + org.w3._2000._09.xmldsig_.ObjectFactory of = new org.w3._2000._09.xmldsig_.ObjectFactory(); + + //Get the Vendor GUID and other info from a from a property file + vendorID.getTcgVendorIdOrSmiVendorIdOrVendorGUID().add(vendorGUID); + vendorID.setName(hisProperties.getProperty(VENDOR_NAME_LABEL, "Unknown Vendor")); + + + //construct the component type + component.setVendorID(vendorID); + component.setId("Default_Component"); + //optional data fields, use TBD + component.setModelName(hisProperties.getProperty(MODEL_NAME_LABEL, "")); + component.setModelNumber(hisProperties.getProperty(MODEL_NUMBER_LABEL, "XXXX")); + component.setVersionMajor(new BigInteger(hisProperties.getProperty(VERSION_MAJOR_LABEL, "00"))); + component.setVersionMinor(new BigInteger(hisProperties.getProperty(VERSION_MINOR_LABEL, "00"))); + component.setModelSerialNumber(hisProperties.getProperty(MODEL_SN_LABEL, "XXXX")); + component.setPatchLevel(hisProperties.getProperty(MODEL_PATCH_LEVEL_LABEL, "")); + + //construct the Composite Hash Type + //pcrHashType.setId(id); + //pcrHashType.setValue(pcrHash); + + //Now construct the snapshot object + //Set the IDs + snap.setUUID(generateUUID(UUID_VERSION));//UUID_PREFIX + "."+SNAPSHOT_PREFIX+"."+id); + snap.setId(SNAPSHOT_PREFIX+"."+id); + snap.setRevLevel(new BigInteger(SNAPSHOT_REV_LEVEL)); + //add the component + snap.setComponentID(component); + //Add the pcr hash returned from the TPM quote into a digest value + + //snap.getCompositeHash().add(pcrHash); + + //if a message is set add it to a Value type to be reported to the server +// if(!taggedMessage.equals("")) + if (taggedMessage.length() != 0) + { + //construct the ValueType with the message + //To match the schema we must add a Key Value object with a placeholder value + kv.getContent().add("-"); + messageValue.setAny(of.createKeyName("placeholder")); + messageValue.setId(taggedMessage);//the message is stored in the Value type ID field + snap.getValues().add(messageValue); + } + + return snap; + } + + /** + * Calls the right function depending on the received IML type + * and returns the final report. + * + * @param report The report that will contain the SnapshotCollection + * elements + * @param imlType The type of integrity measurements to be parsed + */ + private void createMeasureSnapshot(ReportType report, String imlType) { + try { + if (imlType.equals("bios")) + createBIOSSnapshot(report); + else if (imlType.equals("ima")) + createIMASnapshot(report); + } catch (Exception e) { + if (e instanceof NoSuchAlgorithmException) + s_logger.error("SHA-1 is required to create a valid snapshot"); + else + s_logger.error(e.getMessage()); + + e.printStackTrace(); + } + } + + private String getValueFromPcrNumber(int pcrNumber) { + int intBitmask = (pcrBitmask[2] & 0xFF) | ((pcrBitmask[1] & 0xFF) << 8) | ((pcrBitmask[0] & 0xFF) << 16); + int pcrPosition = -1; + + for (int i = 0; i < PCR_MAX_NUM; i++) { + if ((intBitmask & (0x00800000 >> i)) != 0) + pcrPosition++; + if (i == pcrNumber) + break; + } + if (pcrPosition == -1) + return null; + return tpmOutput.split(" ")[pcrPosition]; + } + + /** + * Creates an element SnapshotCollection, writes IMA measurements + * inside it and adds it to the given ReportType element. + * + * @param report The report that will contain the SnapshotCollection + * elements + */ + private void createIMASnapshot(ReportType report) throws NoSuchAlgorithmException, Exception { + int intBitmask = (pcrBitmask[2] & 0xFF) | ((pcrBitmask[1] & 0xFF) << 8) | ((pcrBitmask[0] & 0xFF) << 16); + + SnapshotType snap = null; + String UUID = generateUUID("4"); + byte[] tmpBytes = new byte[4]; + int eventCount = 0; + + int pcrNumber; + byte[] hashValue = null; + byte[] digestValue = null; + byte[] readImageSize = null; + int imageSize; + + File ima_file = new File("/sys/kernel/security/ima/binary_runtime_measurements"); + if (!ima_file.exists()) + return; + + InputStream in = new FileInputStream("/sys/kernel/security/ima/binary_runtime_measurements"); + + in.skip(lastByteIMA); + while (in.read(tmpBytes, 0, 4) == 4) { + pcrNumber = ByteBuffer.wrap(tmpBytes).order(ByteOrder.nativeOrder()).getInt(); + if ((intBitmask & (0x00800000 >> pcrNumber)) == 0) + return; + + eventCount = lastEventCount[pcrNumber]; + hashValue = new byte[PCR_SIZE]; + in.read(hashValue, 0, PCR_SIZE); + + in.read(tmpBytes, 0, 4); + int templateNameSize = ByteBuffer.wrap(tmpBytes).order(ByteOrder.nativeOrder()).getInt(); + + byte[] templateName = new byte[templateNameSize]; + in.read(templateName, 0, templateNameSize); + + imageSize = 0; + digestValue = null; + if (new String(templateName).equals("ima")) { + digestValue = new byte[PCR_SIZE]; + in.read(digestValue, 0, PCR_SIZE); + imageSize += PCR_SIZE; + } + + readImageSize = new byte[4]; + in.read(readImageSize, 0, 4); + int templateDataSize = ByteBuffer.wrap(readImageSize).order(ByteOrder.nativeOrder()).getInt(); + byte[] templateData = new byte[templateDataSize]; + in.read(templateData, 0, templateDataSize); + imageSize += templateDataSize; + + ByteBuffer imageBuffer = ByteBuffer.allocate(imageSize); + if (digestValue != null) + imageBuffer.put(digestValue); + imageBuffer.put(templateData); + + if (snap == null) { + snap = initializeSnapshot(UUID, 10); + } + snap = createValuesType(snap, UUID, 10, new String(templateName), eventCount, hashValue, imageBuffer.array()); + + eventCount++; + + /* 3 * 4 bytes are for PCR number, template name length and template data length */ + lastByteIMA += 3 * 4 + templateNameSize + imageSize + PCR_SIZE; + lastEventCount[pcrNumber] = eventCount; + + if (hexString(lastPcrHash[pcrNumber]).toUpperCase().equals(getValueFromPcrNumber(pcrNumber).toUpperCase())) + break; + } + + report.getSnapshotCollection().add(snap); + in.close(); + } + + /** + * Creates an element SnapshotCollection for each PCR entry + * read from the BIOS measurements file and adds it to the + * given ReportType element. + * + * @param report The report that will contain the SnapshotCollection + * elements + */ + private void createBIOSSnapshot(ReportType report) throws NoSuchAlgorithmException, Exception { + int intBitmask = (pcrBitmask[2] & 0xFF) | ((pcrBitmask[1] & 0xFF) << 8) | ((pcrBitmask[0] & 0xFF) << 16); + byte[] tmpBytes = new byte[4]; + String UUID = generateUUID("4"); + SnapshotType snap = null; + int pcrNumber; + + byte[] hashValue = null; + String eventType; + byte[] readImageSize = null; + int imageSize; + byte[] digestValue = null; + int imageBufferSize; + + int[] eventCount = new int[PCR_MAX_NUM]; + for (int i=0; i= 0; i--) + sb.append(String.format("%02x", tmpBytes[i]&0xff)); + eventType = sb.toString().replaceFirst("^(00)+(?!$)", ""); + + hashValue = new byte[PCR_SIZE]; + tpmFileStream.read(hashValue, 0, PCR_SIZE); + + readImageSize = new byte[4]; + tpmFileStream.read(readImageSize, 0, 4); + imageSize = ByteBuffer.wrap(readImageSize).order(ByteOrder.nativeOrder()).getInt(); + + digestValue = new byte[imageSize]; + tpmFileStream.read(digestValue, 0, imageSize); + + imageBufferSize = readImageSize.length + digestValue.length; + ByteBuffer imageBuffer = ByteBuffer.allocate(imageBufferSize); + imageBuffer.put(readImageSize); + imageBuffer.put(digestValue); + + /* 4 * 3 bytes are for PCR number, template name length and template data length */ + lastByteBIOS += 4 * 3 + PCR_SIZE + imageSize; + + if (pcrValueReached[pcrNumber] || (intBitmask & (0x00800000 >> pcrNumber)) == 0) + continue; + + snap = null; + for (SnapshotType tmpSnap : report.getSnapshotCollection()) { + if (tmpSnap.getComponentID().getId().equals("CID_" + pcrNumber)) { + snap = tmpSnap; + break; + } + } + + if (snap == null) { + snap = initializeSnapshot(UUID, pcrNumber); + snap = createValuesType(snap, UUID, pcrNumber, eventType, eventCount[pcrNumber], hashValue, imageBuffer.array()); + report.getSnapshotCollection().add(snap); + } else { + createValuesType(snap, UUID, pcrNumber, eventType, eventCount[pcrNumber], hashValue, imageBuffer.array()); + } + + eventCount[pcrNumber]++; + lastEventCount[pcrNumber] = eventCount[pcrNumber]; + + if (hexString(lastPcrHash[pcrNumber]).toUpperCase().equals(getValueFromPcrNumber(pcrNumber).toUpperCase())) + pcrValueReached[pcrNumber] = true; + } + + tpmFileStream.close(); + } + + /** + * Creates an element SnapshotCollection for the given PCR number. + * + * @param pcrIndex Number of the PCR whose measurements will be + * placed in the SnapshotCollection + * @param UUID UUID of the SnapshotCollection + * @return The SnapshotCollection to be included in the report + */ + private SnapshotType initializeSnapshot(String UUID, int pcrIndex) { + SnapshotType snap = new SnapshotType(); + + ComponentIDType component = new ComponentIDType(); + VendorIdType vendorID = new VendorIdType(); + + vendorID.setName(hisProperties.getProperty(VENDOR_NAME_LABEL, "JJ")); + vendorID.getTcgVendorIdOrSmiVendorIdOrVendorGUID().add(new ObjectFactory().createVendorIdTypeSmiVendorId(new BigInteger("0"))); + vendorID.getTcgVendorIdOrSmiVendorIdOrVendorGUID().add(new ObjectFactory().createVendorIdTypeTcgVendorId("DEMO")); + + component.setVendorID(vendorID); + component.setId("CID_" + pcrIndex); + component.setModelSystemClass ("TBD"); + if (pcrIndex == 10) + component.setSimpleName ("OAT IMA"); + else + component.setSimpleName ("JJ"); + component.setVersionBuild (new BigInteger ("1250694000000")); + component.setVersionString ("JJ"); + + DigestMethodType digestMethod = new DigestMethodType(); + digestMethod.setAlgorithm ("unknown"); + digestMethod.setId ("sha1"); + snap.getDigestMethod().add(digestMethod); + + //Set the IDs + snap.setUUID(UUID); + snap.setId("IR_" + UUID); + snap.setRevLevel(new BigInteger(SNAPSHOT_REV_LEVEL)); + + snap.setComponentID(component); + return snap; + } + + /** + * Creates an element Values and adds it to the received + * SnapshotCollection; if the SnapshotCollection is null + * the function also creates it. + * + * @param snap SnapshotCollection to be created or extended + * @param UUID UUID of the SnapshotCollection + * @param pcrIndex Index of the PCR the hash refers to + * @param eventType Number used to compose the Id of element Hash + * @param eventCount Number used to compose the Id of element Hash + * @param hashValue Content of element Hash + * @param imageValue Content of parameter Image in element Objects + * @return The SnapshotCollection to be included in the report + */ + private SnapshotType createValuesType(SnapshotType snap, String UUID, int pcrIndex, String eventType, int eventCount, byte[] hashValue, byte[] imageValue) throws NoSuchAlgorithmException { + MessageDigest md = MessageDigest.getInstance("SHA-1"); + byte[] startHash = new byte[PCR_SIZE]; + + ValueType messageValue = new ValueType(); + TpmDigestValueType pcrHash; + ValuesType objects = new ValuesType(); + DigestValueType hash = new DigestValueType(); + SimpleObjectType simpleObject = (new org.trustedcomputinggroup.xml.schema.simple_object_v1_0_.ObjectFactory()).createSimpleObjectType(); + + String levelString = "LV0"; + String eventTypeString = eventType.replaceFirst("^0+(?!$)", ""); + if (pcrIndex == 10) { + levelString = "LV1"; + eventTypeString = "0"; + } + + hash.setId("PCR_" + pcrIndex + "_" + levelString + "_" + eventTypeString + "_" + eventCount + "_EVENT"); + hash.setAlgRef(snap.getDigestMethod().get(0).getId()); + hash.setValue(hashValue); + + objects.getHash().add(hash); + objects.setImage(imageValue); + objects.setType(eventType); + + simpleObject.getObjects().add(objects); + messageValue.setAny(new org.trustedcomputinggroup.xml.schema.simple_object_v1_0_.ObjectFactory().createSimpleObject (simpleObject)); + snap.getValues().add(messageValue); + + /* + * PcrHash + */ + if (snap.getPcrHash().size() == 0) { + pcrHash = new TpmDigestValueType(); + + pcrHash.setAlgRef("sha1"); + pcrHash.setId("PCR_" + pcrIndex + "_" + levelString + "_HASH"); + pcrHash.setIsResetable(false); + pcrHash.setNumber(BigInteger.valueOf(pcrIndex)); + + startHash = lastPcrHash[pcrIndex]; + pcrHash.setStartHash(startHash); + + snap.getPcrHash().add(pcrHash); + } else { + pcrHash = snap.getPcrHash().get(0); + startHash = lastPcrHash[pcrIndex]; + } + + md.reset(); + md.update (startHash, 0, PCR_SIZE); + if (hexString(hashValue).equals("0000000000000000000000000000000000000000")) + md.update(unHexString("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"), 0, PCR_SIZE); + else + md.update(hashValue, 0, PCR_SIZE); + pcrHash.setValue(md.digest()); + + lastPcrHash[pcrIndex] = pcrHash.getValue(); + + return snap; + } + + /** Takes raw PCR data and constructs a QuoteData element that conrails the a PCR value quote and a corresponding signature. + * @param id The report ID to for use by the Quote Data object. + * @param pcrComposite This object is loaded with all of the PCR values from the TPM + * @param quoteSignature The object containing the TPM signature over the returned PCR data + * @param nonce The nonce returned with the TPM quote + * @param pcrHash a hash of all the returned PCR values which is signed in the quote + */ + private QuoteDataType createQuoteDataEntry(String reportId, PcrCompositeType pcrComposite, QuoteSignatureType quoteSignature, byte[] nonce, byte[] pcrHash, short quoteVersion) + { + + //Here is the element we return + QuoteDataType qData = new QuoteDataType(); + + //set the ID field + qData.setID(QUOTE_PREFIX+"."+reportId); + + //QuoteData needs these two other objects + QuoteType quote = new QuoteType(); + QuoteSignatureType tpmSIG =quoteSignature; + + //Quote needs the following objects, PcrComposite and QuoteInfo + quote.setPcrComposite(pcrComposite); + QuoteInfoType quoteInfo = new QuoteInfoType(); + + + //Now set up the Quote Info first with various pre-configured values + quoteInfo.setVersionMajor(QUOTE_VERSION_MAJOR); + quoteInfo.setVersionMinor(QUOTE_VERSION_MINOR); + quoteInfo.setVersionRevMajor(QUOTE_VERSION_REV_MAJOR); + quoteInfo.setVersionRevMinor(QUOTE_VERSION_REV_MINOR); + if(quoteVersion==1) + { + quoteInfo.setFixed(QUOTE_FIXED); + } + if(quoteVersion==2) + { + quoteInfo.setFixed(QUOTE2_FIXED); + } + + //then the nonce and pcr hash + quoteInfo.setExternalData(nonce); + quoteInfo.setDigestValue(pcrHash); + + + quote.setQuoteInfo(quoteInfo); + + //add the components to the quote data type + qData.setQuote(quote); + qData.setTpmSignature(tpmSIG); + + + return qData; + } + + + /** Parses a raw TPM version 1 quote (in Hex String format) and puts the PCR values into an TCG Integrity report + * + * This function does not attempt to check if the Quote values are valid + * + * @param quoteVer The version of quote to parse against, Quote or Quote 2 + * @param pcrNumber The number of PCR values being returned + * @param reportID The Report ID. + * @return A Quate Data object containing the data parsed from the TPM output + * @throws java.io.IOException + */ + + private QuoteDataType parseQuote(int quoteVer, int pcrNumber, String reportID) throws IOException + { + //All HexString sizes are BYTES TIMES TWO + int segmentSize=0; + int sizeCounter = 0; + String quoteVersionTag= ""; + byte[] bitmask = pcrBitmask; + String bitmaskLenStr= ""; + int bitmaskLen=1; + String returnedNonce=""; + byte[] nonceBytes; + String pcrHash=""; + byte[] pcrHashBytes; + String signature=""; + PcrCompositeType pcrComposite; + PcrSelectionType pcrSelect = new PcrSelectionType(); + QuoteSignatureType quoteSig = new QuoteSignatureType(); + QuoteDataType quote; + + //This parcer scans through the output of the TPM module and rigorously checks to make sure the returned value meet the spec + + + //---------------------READ PCR VALUES-------------------------------// + + s_logger.debug("Parsing "+pcrNumber+" PCR values."); + + pcrComposite = new PcrCompositeType(); + + //pull the PCR list from the snapshot to add the values to + List pcrs = pcrComposite.getPcrValue(); + + //Loop through the PCR values adding them to the list + for(int i = 0; i < 8 * bitmask.length; i++) + { + PcrValue pcrEntry = new org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.ObjectFactory().createPcrCompositeTypePcrValue(); + String pcrValue; + byte[] pcrValueBytes; + + if ((128 >> (i % 8) & bitmask[i/8]) == 0) + continue; + + //Set the index number of the first PCR value + pcrEntry.setPcrNumber(new BigInteger(new Integer(i).toString())); + + //pull off the PCR chunk + segmentSize = PCR_SIZE; + pcrValue = tpmOutput.substring(sizeCounter, sizeCounter+(segmentSize*2)); + + //parse the PCR value + try + { + pcrValueBytes = unHexString(pcrValue); + } + catch(Exception e) + { + s_logger.error( "Error parsing PCR Value hex string #"+i+" , invalid input. Error at count: "+ sizeCounter + ".\n"+ tpmOutput, e); + throw new IOException("Error parsing PCR Value hex string #"+i+" , invalid input."); + } + + //set the value and add it to the list + pcrEntry.setValue(pcrValueBytes); + pcrs.add(pcrEntry); + + sizeCounter = sizeCounter+(segmentSize*2); + + + //Check for the space? + if(tpmOutput.charAt(sizeCounter)!=' ') + { + s_logger.error("Parsing error at PCR #"+i+". Unexpected length. Error at count: "+ sizeCounter + ".\n"+ tpmOutput); + throw new IOException("Parsing error at PCR #"+i+". Unexpected length."); + } + //One for the space + sizeCounter++; + } + + s_logger.debug("Parsing quote."); + + //--------------------INPUT NONCE------------------------// + + //just skip it and the extra space after it. The nonce is also included in the Quote + sizeCounter = sizeCounter+(NONCE_SIZE*2)+1; + + //--------------------QUOTE------------------------------// + + + //parse Version 1 quote + if(quoteVer==1) + { + segmentSize = QUOTE_SIZE; + //Get the quote version + try + { + quoteVersionTag = tpmOutput.substring(sizeCounter, sizeCounter+QUOTE_VERSION_SIZE*2); + } + catch(Exception e) + { + + s_logger.error( "Unable to read TPM Quote Version Hex String! Error at count: "+ sizeCounter +".\n"+ tpmOutput, e); + throw new IOException("Unable to read TPM Quote Version Hex String!"); + } + + if(!quoteVersionTag.equals(EXPECTED_QUOTE_VERSION_TAG)) + { + s_logger.warn( "Quote version "+quoteVersionTag+ " does not match expected version "+EXPECTED_QUOTE_VERSION_TAG); + } + + sizeCounter = sizeCounter+(QUOTE_VERSION_SIZE*2); + //skip over the fixed value + sizeCounter = sizeCounter+(QUOTE_FIXED_SIZE*2); + + //Get the PCR Hash PCR_HASH_SIZE + pcrHash = tpmOutput.substring(sizeCounter, sizeCounter+PCR_HASH_SIZE*2); + sizeCounter = sizeCounter+(PCR_HASH_SIZE*2); + + //Get the nonce + returnedNonce = tpmOutput.substring(sizeCounter, sizeCounter+NONCE_SIZE*2); + sizeCounter = sizeCounter+(NONCE_SIZE*2); + + bitmaskLen=bitmask.length;//PCR_BITMASK_SIZE; + + } + + //parse Version 2 quote + if(quoteVer==2) + { + //QUOTE 2 can have a variable length of between 50 and 52 bytes + + //Get the quote version/tag The value for Quote 2 is 0x0036 + try + { + quoteVersionTag = tpmOutput.substring(sizeCounter, sizeCounter+QUOTE2_VERSION_SIZE*2); + + if(!Arrays.equals(unHexString(quoteVersionTag), EXPECTED_QUOTE2_VERSION_TAG)) + { + s_logger.warn( "Quote version "+quoteVersionTag+ " does not match expected version "+hexString(EXPECTED_QUOTE2_VERSION_TAG)); + } + } + catch(Exception e) + { + + s_logger.error( "Unable to read TPM Quote Version Hex String! Error at count: "+ sizeCounter +".\n"+ tpmOutput, e); + throw new IOException("Unable to read TPM Quote Version Hex String!"); + } + + sizeCounter = sizeCounter+(QUOTE2_VERSION_SIZE*2); + //skip over the fixed value + sizeCounter = sizeCounter+(QUOTE_FIXED_SIZE*2); + + //Get the nonce + returnedNonce = tpmOutput.substring(sizeCounter, sizeCounter+NONCE_SIZE*2); + sizeCounter = sizeCounter+(NONCE_SIZE*2); + + bitmaskLenStr = tpmOutput.substring(sizeCounter, sizeCounter+QUOTE2_BITMASK_LENGTH_SIZE*2); + sizeCounter = sizeCounter+(QUOTE2_BITMASK_LENGTH_SIZE*2); + + //pull the size of the bitmask in bytes from the length field + if(bitmaskLenStr.endsWith("1")){bitmaskLen=1;} + else if(bitmaskLenStr.endsWith("2")){bitmaskLen=2;} + else if(bitmaskLenStr.endsWith("3")){bitmaskLen=3;} + + //calculate the segment size + segmentSize = QUOTE2_SIZE_BASE+bitmaskLen; + + //pull out the bitmask + try + { + bitmask = unHexString(tpmOutput.substring(sizeCounter, sizeCounter+bitmaskLen*2)); + sizeCounter = sizeCounter+(bitmaskLen*2); + } + catch(Exception e) + { + s_logger.error( "Error parsing Quote 2 bitmask hex string, invalid input.", e); + throw new IOException("Error parsing Quote 2 bitmask hex string, invalid input."); + } + + //Parse the one byte filler byte + if(!tpmOutput.substring(sizeCounter, sizeCounter+2).equals(QUOTE2_FILLER_BYTE)) + { + s_logger.warn("TPM Quote 2 Filler byte incorrect: "+tpmOutput.substring(sizeCounter, sizeCounter+2)); + } + sizeCounter = sizeCounter+2; + + //Get the PCR Hash PCR_HASH_SIZE + pcrHash = tpmOutput.substring(sizeCounter, sizeCounter+PCR_HASH_SIZE*2); + sizeCounter = sizeCounter+(PCR_HASH_SIZE*2); + + } + + //Check for the space + if(tpmOutput.charAt(sizeCounter)!=' ') + { + s_logger.error( "Parsing error in TPM Quote - "+tpmOutput.charAt(sizeCounter)+" - Unexpected length at count " + sizeCounter + ".\n"+ tpmOutput); + throw new IOException("Parsing error in TPM Quote - "+tpmOutput.charAt(sizeCounter)+" - Unexpected length at count " + sizeCounter); + } + + sizeCounter++; + + //----------------------------SIGNATURE------------------------------// + + s_logger.debug("Parsing signature."); + + segmentSize=SIGNATURE_SIZE; + + + //grab the signature block using the dynamic size + signature = tpmOutput.substring(sizeCounter, sizeCounter+segmentSize*2); + + //Now we populate the TPM signature information + //First set the signature method + SignatureMethodType sm = new SignatureMethodType(); + sm.setAlgorithm(""); + quoteSig.setSignatureMethod(sm); + //Then the key info + //NOTE Currently no info on the signature/cert/key are available from the TPM so default values are used + KeyInfoType ki = new KeyInfoType(); + JAXBElement kn = new org.w3._2000._09.xmldsig_.ObjectFactory().createKeyName(computerName); + ki.getContent().add(kn); + quoteSig.setKeyInfo(ki); + + + //Finally add the actual signature bytes + SignatureValueType sigVal = new SignatureValueType(); + + try + { + sigVal.setValue(unHexString(signature)); + } + catch(Exception e) + { + s_logger.error( "Error parsing signature hex string, invalid input.", e); + throw new IOException("Error parsing signature hex string, invalid input."); + } + + quoteSig.setSignatureValue(sigVal); + + + //------------------------QUOTE DATA PROCESSING --------------------------------// + + s_logger.debug("Processing Quote data."); + + + //here all of the info we just parsed from the quote is assembled into a Quote Data structure + pcrComposite.setValueSize(new BigInteger(new Integer(PCR_SIZE * pcrNumber).toString())); + + pcrSelect.setPcrSelect(bitmask); + pcrSelect.setSizeOfSelect(bitmaskLen); + pcrComposite.setPcrSelection(pcrSelect); + + //parse the nonce + try + { + nonceBytes = unHexString(returnedNonce); + } + catch(Exception e) + { + s_logger.error( "Error parsing nonce hex string, invalid input.", e); + throw new IOException("Error parsing nonce hex string, invalid input."); + } + //parse the PCR Composite + try + { + pcrHashBytes = unHexString(pcrHash); + } + catch(Exception e) + { + s_logger.error( "Error parsing PCR Compisite hash hex string, invalid input.", e); + throw new IOException("Error parsing PCR Compisite hash hex string, invalid input."); + } + + //now create the Quote Data object in the report + quote = createQuoteDataEntry(reportID, pcrComposite, quoteSig, nonceBytes, pcrHashBytes, (short)quoteVer); + + + return quote; + } + + /** + * Resets counters used by the client to + * implement the scalability mechanism. + */ + private void resetScalabilityCounters() { + reportType = "start"; + lastByteBIOS = 0; + lastByteIMA = 0; + for (int i = 0; i < PCR_MAX_NUM; i++) { + lastPcrHash[i] = unHexString("0000000000000000000000000000000000000000"); + lastEventCount[i] = 0; + } + } + + /** Makes a web service call to get the parameters for the Integrity check. + * The parameters include a Quote type (1 or 2) nonce and PCR selection and are customized for the computer and user. + * + * @param userName The username of the principal logging in + * @param compName The name of the workstation being logged into + * + */ + private void getReportParams(String userName, String compName) + { + //get the web service object with the correct computer name + NonceSelect nonceSelect = hisAuthenticationWebService.getNonce(compName, userName); + + /* + * Ignore the report type requested by the Appraiser, + * if the Client service restarted or last report was + * not successfully sent. + */ + if (clientStartUpDone && lastReportSendSuccess) { + reportType = nonceSelect.getReportType(); + } + if (reportType.equals("start")) { + resetScalabilityCounters(); + } + + //NOTE: This can be considered input filtering for command line arguments as the Hex tool can only generate 0-9 A-F + //This selection must account for null return from older versions of the web service + try + { + if(nonceSelect.getQuote() == Quote.QUOTE_2) + { + quoteType = 2; + } + else + { + quoteType = 1; + } + } + catch(Exception e){quoteType = 1;} + System.out.println("Quote type = "+quoteType); + nonce = hexString(nonceSelect.getNonce()); + rawBitmask = hexString(nonceSelect.getSelect()); + + } + + /** Marshalls the integrity report object into a string format and sends it to the server via a web service + * + * @param reportType The integrity report to be sent + */ + + private void sendIntegrityReport(ReportType reportType) throws Exception + { + + JAXBContext jc=null; + Marshaller m=null; + + System.out.println("Sending integrity report"); + try + { + jc = JAXBContext.newInstance("org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_:org.trustedcomputinggroup.xml.schema.simple_object_v1_0_"); + m = jc.createMarshaller(); + } + catch(Exception e) + { + throw new Exception( "Error setting up TCG report marshaller: " + e.getMessage() ); + } + + //make an output stream for the marshaller and then turn the object into bytes + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + + try + { + JAXBElement report = new org.trustedcomputinggroup.xml.schema.integrity_report_v1_0_.ObjectFactory().createReport(reportType); + m.marshal(report, bOut); + } + catch(Exception e) + { + e.printStackTrace(); + throw new Exception( "Error marshalling TCG Integrity report: " + e.getMessage() ); + } + + //Make a web service call to send the report + try + { + hisAuthenticationWebService.postIntegrityReport(new String(bOut.toByteArray())); + } + catch(Exception e) + { + throw new Exception( "Web service error: " + e.getMessage() ); + } + + + } + + /** Performs a system call to reboot the system to enable fresh measurements to be taken. + * This is not intended as a sophisticated administrative tool, only a quick and dirty proof of concept/ + * + * @param osType The type of OS runnign the application + */ + + private void restartComputer(int osType) + { + Runtime rt = Runtime.getRuntime(); + String cmd = ""; + String cmd1 = "shutdown"; + + //try to send an OS specific command based on the configured OS type or if not configured, use both + switch(osType) + { + case WINDOWS_OS: + cmd = WINDOWS_REBOOT_CMD; + break; + case LINUX_OS: + cmd = LINUX_REBOOT_CMD; + break; + default: + //If no OS is specified then just try both commands. + cmd = WINDOWS_REBOOT_CMD; + cmd1 = LINUX_REBOOT_CMD; + + } + + try + { + rt.exec(cmd); + //if this is "shutdown" then nothing will happen, not like it matters anyway with a reboot + rt.exec(cmd1); + } + //If the command fails there's no much we can really do except possibly send an error report + catch (IOException ioe) + { + System.out.println("Error rebooting client."); + ioe.printStackTrace(); + + ReportType report = createEmptyReport("Error rebooting client: "+ ioe.getMessage(), ERROR_MESSAGE_ID); + + try + { + sendIntegrityReport(report); + } + catch(Exception e) + { + System.out.println("Error sending error report: "+e.getMessage()+"\nI give up."); + e.printStackTrace(); + } + } + + return; + } + + /** A wrapper method to log and send an error report with the specified error message + * + * @param errMsg The error message + * @return true for sucess, false for a sending error + */ + + private boolean sendErrorReport(String errMsg) + { + + s_logger.error( errMsg); + + //create a new Integrity report of the empty/error type + ReportType report = createEmptyReport(errMsg, ERROR_MESSAGE_ID); + + //then send it using the normal method + try + { + sendIntegrityReport(report); + } + catch(Exception e) + { + s_logger.error("Error sending error report after \""+errMsg+"\" error: "+e.getMessage()); + e.printStackTrace(); + return false; + } + + return true; + } + + /** Processes generic commands from the on demand system. + * Takes in an index which points to a command in a properties file and applies the arguments. + * + * @param commandLabel The command index in the properties file + * @param args The arguments applied to the command + */ + + private void commandProcessor(String commandLabel, String args) + { + Runtime rt = Runtime.getRuntime(); + String commandRoot=""; + String command=""; + int exitVal=99999; + int i = 0 ; + + //pull the command from the property specified by the index + commandRoot = hisProperties.getProperty(commandLabel); + + if(commandRoot==null || commandRoot.length() == 0) + { + sendErrorReport( "Command not found at specified index."); + return; + } + + //assemble the command, the arg string is single quote escaped to prevent command injection + command= commandRoot + " \'"+args+"\'"; + + try + { + //Run the process + Process proc = rt.exec(command); + + //now loop until we get a return value or we reach a timeout + while(i<=blockingTimeout) + { + + try + { + exitVal = proc.exitValue(); + } + catch(Exception e) + { + //if the process has not completed we get an exception, just catch and loop + Thread.sleep(1); + } + if(exitVal!=99999) + { + //if we get a valid exit code break out of the loop + break; + } + + i++; + } + + //if i has reached the blocking timeout value we need to throw an error + if(i>=blockingTimeout) + { + System.out.println("No Return value from "+command+" command."); + s_logger.warn("No Return value from "+command+" command."); + return; + //TODO report this via an error report? + } + + //if we get a non-0 return value then we also have a problem and should report it to the server + if(exitVal!=0) + { + System.out.println("Error code returned from "+command+" command: "+exitVal); + sendErrorReport("Error code returned from "+command+" command: "+exitVal); + return; + } + + } + catch(Throwable t) + { + t.printStackTrace(); + sendErrorReport("Error running On Demand command: "+t.getMessage()); + s_logger.error("Error running On Demand command: "+t.getMessage(), t); + return; + } + + + } + + /** Generated a UUID vased on the supplied version number. Currently UUID versions 1, 3 and 4 are supported. + * Unsupported versions will result in a default value being returned. + * + * @param version the version number of the UUID to be geerated. Ver 1, 3 and 4 supported. + * @return a properly formatted UUID + */ + + public static String generateUUID(String version) + { + String uuid=""; + + if(version.equals("1")) + { + //UUID Version 1 uses MAC address and timestamp + com.eaio.uuid.UUID u = new com.eaio.uuid.UUID(); + uuid=u.toString(); + } + else if(version.equals("3")) + { + //UUID version 3 uses the machine's full domain name + byte[] name; + try + { + //name = InetAddress.getLocalHost().getCanonicalHostName().getBytes(); + name = InetAddress.getLocalHost().getHostName().getBytes(); + } + catch(Exception e) + { + //if we can't find the official hostname use localhost + s_logger.error( "Unable to obtain POSIX domain nane for Version 3 UUID. Using default name localhost.", e); + name = "localhost".getBytes(); + } + java.util.UUID u = java.util.UUID.nameUUIDFromBytes(name); + uuid = u.toString(); + + } + else if(version.equals("4")) + { + //UUID version 4 uses a random number + java.util.UUID u = java.util.UUID.randomUUID(); + uuid = u.toString(); + } + else + { + s_logger.error( "Invalid UUID version: "+ version+ ". Using random UUID as default."); + java.util.UUID u = java.util.UUID.randomUUID(); + uuid = u.toString(); + } + + return uuid; + } + +} + +/** Helper class that provides general stream printing capability to Std out + * + * + */ + +//This was copied from an online template with minimal modifications +class StreamPrinter extends Thread +{ + InputStream is; + String type; + StandaloneHIS his; + private volatile Thread streamPrinterThread; + + /** Basic constructor + * + * @param is The output stream to print from, either stdErr or stdOut + * @param type String label for the stream being printed + * @param h Pointer to the HIS Client in order to use its logging functions + */ + + StreamPrinter(InputStream is, String type, StandaloneHIS h) + { + this.is = is; + this.type = type; + this.his = h; + } + + /** Main method of class. Pulls anything written to the stream and sends it to the HIS Client logger + * + */ + + public void run() + { + try + { + //prepare a buffered reader to read from + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + String line=null; + + //loop until thread terminated + while ( (line = br.readLine()) != null) + { + //Log to the HIS plugin logger + his.s_logger.error("Executable interface output: " +type + "> " + line); + System.out.println(type + ">" + line); + } + } + catch (IOException ioe) + { + ioe.printStackTrace(); + } + } + + /** Starts the thread + * + * + */ + public void start (boolean RequestTempCertRButton) + { + + streamPrinterThread = new Thread (this); + streamPrinterThread.start (); + } + + /** Stops the thread + * + */ + public void stopThread () + { + streamPrinterThread = null; + } +} + +/** Helper class that returns all of the output from the specified stream into a string + * + */ + +//This was copied from an online template with minimal modifications +class StreamOutput extends Thread +{ + InputStream is; + String output; + StandaloneHIS his; + private volatile Thread streamOutputThread; + + /** Basic constructor + * + * @param is The output stream to print from, either stdErr or stdOut + * @param h Pointer to the HIS Client in order to write to its tpmOutput buffer + */ + StreamOutput(InputStream is, StandaloneHIS h) + { + this.is = is; + his=h; + } + + /** Main method of class. Pulls anything written to the stream and sends it to the HIS Client tpmOutput buffer + * + */ + + public void run() + { + + try + { + //set up the buffered reader + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + StringBuffer sb = new StringBuffer(); + String line=null; + //keeps reading until terminated + while ( (line = br.readLine()) != null) + { + //concatonate the new line to the existing output + his.tpmOutput = sb.append(line).toString(); + } + + //System.out.println(hisPlug.tpmOutput); + } + catch (Exception ioe) + { + his.tpmOutput = ""; + ioe.printStackTrace(); + } + + } + /** Starts the thread + * + */ + public void start (boolean RequestTempCertRButton) + { + + streamOutputThread = new Thread (this); + streamOutputThread.start (); + } + + /** Stops the thread + * + */ + public void stopThread () + { + streamOutputThread = null; + } + +} + + + diff --git a/OpenAttestation/Source/HisClient/xml/Integrity_Report_Manifest_v1_0/binding.xjb b/OpenAttestation/Source/HisClient/xml/Integrity_Report_Manifest_v1_0/binding.xjb new file mode 100644 index 0000000..3c7f170 --- /dev/null +++ b/OpenAttestation/Source/HisClient/xml/Integrity_Report_Manifest_v1_0/binding.xjb @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisClient/xml/Integrity_Report_Manifest_v1_0/build.xml b/OpenAttestation/Source/HisClient/xml/Integrity_Report_Manifest_v1_0/build.xml new file mode 100644 index 0000000..75b40c7 --- /dev/null +++ b/OpenAttestation/Source/HisClient/xml/Integrity_Report_Manifest_v1_0/build.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/ClientFiles/TPMModule.properties b/OpenAttestation/Source/HisPrivacyCAWebServices2/ClientFiles/TPMModule.properties new file mode 100644 index 0000000..a0dc8a7 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/ClientFiles/TPMModule.properties @@ -0,0 +1,4 @@ +TpmModuleExePath = ./exe/ +ExeName = NIARL_TPM_Module +TrousersMode = False +DebugMode = False diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/WEB-INF/sun-jaxws.xml b/OpenAttestation/Source/HisPrivacyCAWebServices2/WEB-INF/sun-jaxws.xml new file mode 100644 index 0000000..7744c57 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/WEB-INF/sun-jaxws.xml @@ -0,0 +1,10 @@ + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/WEB-INF/web.xml b/OpenAttestation/Source/HisPrivacyCAWebServices2/WEB-INF/web.xml new file mode 100644 index 0000000..e992d2a --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/WEB-INF/web.xml @@ -0,0 +1,42 @@ + + + + + HisPrivacyCAWebServices2 + + + + + com.sun.xml.ws.transport.http.servlet.WSServletContextListener + + + + + jaxWsServlet + + com.sun.xml.ws.transport.http.servlet.WSServlet + + 1 + + + + HisPrivacyCAWebServices2LoadOnStartup + + gov.niarl.his.webservices.hisPrivacyCAWebService2.server.HisPrivacyCAWebServices2LoadOnStartup + + 2 + + + + jaxWsServlet + + /hisPrivacyCAWebService2 + + + + jaxWsServlet + + /hisPrivacyCAWebService2FactoryService + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/build.xml b/OpenAttestation/Source/HisPrivacyCAWebServices2/build.xml new file mode 100644 index 0000000..6e97955 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/build.xml @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/setup.properties b/OpenAttestation/Source/HisPrivacyCAWebServices2/setup.properties new file mode 100644 index 0000000..88d199a --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/setup.properties @@ -0,0 +1,10 @@ +PrivacyCaSubjectName = HIS_Privacy_CA +PrivacyCaPassword = ***replace*** +EndorsementCaSubjectName = Endorsement_CA_Rev_1 +EndorsementCaPassword = ***replace*** +HisRegistrationUrl = https://***replace***:8443/HisWebServices +PrivacyCaUrl = https://***replace***:8443/HisPrivacyCAWebServices2 +CertValidityDays = 3652 +FileLocation = ./HIS_Setup +ClientPath = C:/Program Files/NIARL/HIS +AikAuth=1111111111111111111111111111111111111111 \ No newline at end of file diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/Main.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/Main.java new file mode 100644 index 0000000..3431fbb --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/Main.java @@ -0,0 +1,47 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. + */ + +import gov.niarl.his.privacyca.TpmUtils; +import gov.niarl.his.webservices.hisPrivacyCAWebService2.IHisPrivacyCAWebService2; +import gov.niarl.his.webservices.hisPrivacyCAWebService2.client.HisPrivacyCAWebServices2ClientInvoker; + + +/** + * The main class is used for testing purposes only. It acts as a client to connect + * to the web service. It cannot fully interact with the web service because it + * does not interact with a TPM or TPM emulator. + * + * @author schawki + * + */ +public class Main { + /** + * Entry point into the program. + */ + public static void main(){ + //System.setProperty("javax.net.ssl.trustStore", "\\\\Toc\\Shared\\TrustStore.jks"); + try { + IHisPrivacyCAWebService2 hisPrivacyCAWebService2 = HisPrivacyCAWebServices2ClientInvoker.getHisPrivacyCAWebService2("http://localhost:8080/HisPrivacyCAWebServices2"); + byte[] received = hisPrivacyCAWebService2.identityRequestGetChallenge("identityRequest".getBytes(), "endorsementCertificate".getBytes()); + //System.out.println(new String(hisPrivacyCAWebService2.identityRequestGetChallenge("identityRequest".getBytes(), "endorsementCertificate".getBytes()))); + System.out.println(TpmUtils.byteArrayToHexString(received)); + + byte[] received2 = hisPrivacyCAWebService2.identityRequestSubmitResponse(received); + //System.out.println(new String(hisPrivacyCAWebService2.identityRequestSubmitResponse("identityRequestResponseToChallenge".getBytes()))); + System.out.println(TpmUtils.byteArrayToHexString(received2)); + + } catch (Exception e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/HisSetup.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/HisSetup.java new file mode 100644 index 0000000..123c110 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/HisSetup.java @@ -0,0 +1,495 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.io.*; +import java.security.KeyStore; +import java.security.cert.X509Certificate; +import java.util.Enumeration; +import java.util.Properties; +import java.util.StringTokenizer; + +/** + * @deprecated + * + * This method will create all new files for a HIS deployment. + * + * The setup of the HisPrivacyCAWebServices2 Privacy CA replaces the functionality + * of this class. It currently does this by using this class. + * + * @author schawki + * + */ +public class HisSetup { + + /** + * @param args + */ + public static void main(String[] args) { + /* + * File needed to run: setup.properties + * Files needed as output: + * - endorsement p12 + * - Privacy CA p12 + * - Privacy CA certificate + * - Privacy CA properties + * - HIS provisioner properties + * + * Additional items needed (external): + * - trust store jks for web apps + */ + + // Read the properties file + /* + * PrivacyCaSubjectName = HIS_Privacy_CA + * PrivacyCaFileName = PrivCA.p12 + * PrivacyCaPassword = replace + * EndorsementCaSubjectame = Endorsement_CA_Rev_1 + * EndorsementCaFileName = EndorseCA.p12 + * EndorsementCaPassword = replace + * HisRegistrationUrl = https://replace + * PrivacyCaUrl = https://replace + * CertValidityDays = 3652 + * PrivacyCaCertFileName = PricCa.cer + * FileLocation = ./HIS_Setup + */ + FileOutputStream fos = null; + try { + System.out.print("Reading properties file..."); + final String PRIVACY_CA_SUBJECT_NAME = "PrivacyCaSubjectName"; + //final String PRIVACY_CA_FILE_NAME = "PrivacyCaFileName"; + final String PRIVACY_CA_PASSWORD = "PrivacyCaPassword"; + final String ENDORSEMENT_CA_SUBJECT_NAME = "EndorsementCaSubjectName"; + //final String ENDORSEMENT_CA_FILE_NAME = "EndorsementCaFileName"; + final String ENDORSEMENT_CA_PASSWORD = "EndorsementCaPassword"; + final String HIS_REGISTRATION_URL = "HisRegistrationUrl"; + final String PRIVACY_CA_URL = "PrivacyCaUrl"; + final String CERT_VALIDITY_DAYS = "CertValidityDays"; + //final String PRIVACY_CA_CERTIFICATE_FILE_NAME = "PrivacyCaCertFileName"; + final String FILE_LOCATION = "FileLocation"; + final String CLIENT_PATH = "ClientPath"; + final String AIK_AUTH = "AikAuth"; + final String EC_SIGNING_KEY_SIZE = "ecSigningKeySize"; + final String EC_STORAGE = "ecStorage"; + + FileInputStream PropertyFile = null; + String PrivacyCaSubjectName = "null"; + String PrivacyCaFileName = "PrivacyCA.p12"; + String PrivacyCaPassword = "null"; + String EndorsementCaSubjectName = "null"; + String EndorsementCaFileName = "endorsement.p12"; + String EndorsementCaPassword = "null"; + String HisRegistrationUrl = "null"; + String PrivacyCaUrl = "null"; + String CertValidityDays = "null"; + String PrivacyCaCertFileName = "PrivacyCA.cer"; + String EndorsementCaCertFileName = "EndorsementCA.cer"; + String FileLocation = ""; + String CredentialLocation = "/var/lib/oat-appraiser/"; + int ValidityDays; + String ClientPath = ""; + String AikAuth = ""; + String ecSigningKeySize = ""; + String ecStorage = ""; + String tomcatPath = System.getProperty("catalina.base"); + String configPath = "/etc/oat-appraiser/"; + /* + if (tomcatPath != null){ + configPath = tomcatPath + "/webapps/HisPrivacyCAWebServices2/"; + + } + */ + try { + PropertyFile = new FileInputStream(configPath + "setup.properties"); + Properties SetupProperties = new Properties(); + SetupProperties.load(PropertyFile); + PrivacyCaSubjectName = SetupProperties.getProperty(PRIVACY_CA_SUBJECT_NAME, "null"); + //PrivacyCaFileName = SetupProperties.getProperty(PRIVACY_CA_FILE_NAME, "null"); + PrivacyCaPassword = SetupProperties.getProperty(PRIVACY_CA_PASSWORD, "null"); + EndorsementCaSubjectName = SetupProperties.getProperty(ENDORSEMENT_CA_SUBJECT_NAME, "null"); + //EndorsementCaFileName = SetupProperties.getProperty(ENDORSEMENT_CA_FILE_NAME, "null"); + EndorsementCaPassword = SetupProperties.getProperty(ENDORSEMENT_CA_PASSWORD, "null"); + HisRegistrationUrl = SetupProperties.getProperty(HIS_REGISTRATION_URL, "null"); + PrivacyCaUrl = SetupProperties.getProperty(PRIVACY_CA_URL, "null"); + CertValidityDays = SetupProperties.getProperty(CERT_VALIDITY_DAYS, "null"); + //PrivacyCaCertFileName = SetupProperties.getProperty(PRIVACY_CA_CERTIFICATE_FILE_NAME, "null"); + FileLocation = SetupProperties.getProperty(FILE_LOCATION, "null"); + ClientPath = SetupProperties.getProperty(CLIENT_PATH, "C:/Program Files/NIARL/HIS"); + AikAuth = SetupProperties.getProperty(AIK_AUTH, "1111111111111111111111111111111111111111"); + ecSigningKeySize = SetupProperties.getProperty(EC_SIGNING_KEY_SIZE,"2048"); + ecStorage = SetupProperties.getProperty(EC_STORAGE, "NVRAM"); + System.out.println("ecSigningKeySize = " + ecSigningKeySize + "\n"); + System.out.println("ecStorage = " + ecStorage + "\n"); + + } catch (FileNotFoundException e) { + System.out.println("Error finding setup.properties file. Setup cannot continue without the information in this file."); + return; + } catch (IOException e) { + System.out.println("Error loading setup.properties file. Setup cannot continue without the information in this file."); + return; + } + finally{ + if (PropertyFile != null) + try { + PropertyFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + // Populate some strings if running from Tomcat + if (CredentialLocation != null){ + // Look for TrustStore.jks in tomcatPath + "/Certificate" + KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); +// FileInputStream fis = new FileInputStream(tomcatPath + "/Certificate/TrustStore.jks"); + FileInputStream fis = new FileInputStream(CredentialLocation + "Certificate/TrustStore.jks"); + + try { + ks.load(fis, null); + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (fis != null){ + fis.close(); + } + } + + Enumeration certList = ks.aliases(); + if (certList.hasMoreElements()){ + X509Certificate test = (X509Certificate)ks.getCertificate(certList.nextElement()); + String certDN = test.getSubjectX500Principal().getName("RFC1779"); + + StringTokenizer st = new StringTokenizer(certDN, ","); + String certCN = ""; + while(st.hasMoreElements()){ + String line = st.nextToken(); + if(line.startsWith("CN")){ + certCN = line.subSequence(line.indexOf("=") + 1, line.length()).toString(); + break; + } + } + while(certCN.startsWith(" ")){ + certCN = certCN.subSequence(1, certCN.length()).toString(); + } + // If there, it can be copied later, but now should be used to extract the url! + PrivacyCaUrl = "https://" + certCN + ":8443/HisPrivacyCAWebServices2"; + HisRegistrationUrl = "https://" + certCN + ":8443/HisWebServices"; + } + + } + // Continue processing properties file + if (PrivacyCaSubjectName.equals("null")){ + System.out.println("Error finding element \"PrivacyCaSubjectName\" in properties file. Setup cannot continue without this information."); + return; + } + /*if (PrivacyCaFileName.equals("null")){ + System.out.println("Error finding element \"PrivacyCaFileName\" in properties file. Setup cannot continue without this information."); + return; + }*/ + if (PrivacyCaPassword.equals("null")){ + System.out.println("Error finding element \"PrivacyCaPassword\" in properties file. Setup cannot continue without this information."); + return; + } + if (EndorsementCaSubjectName.equals("null")){ + System.out.println("Error finding element \"EndorsementCaSubjectName\" in properties file. Setup cannot continue without this information."); + return; + } + /*if (EndorsementCaFileName.equals("null")){ + System.out.println("Error finding element \"EndorsementCaFileName\" in properties file. Setup cannot continue without this information."); + return; + }*/ + if (EndorsementCaPassword.equals("null")){ + System.out.println("Error finding element \"EndorsementCaPassword\" in properties file. Setup cannot continue without this information."); + return; + } + if (HisRegistrationUrl.equals("null")){ + System.out.println("Error finding element \"HisRegistrationUrl\" in properties file. Setup cannot continue without this information."); + return; + } + if (PrivacyCaUrl.equals("null")){ + System.out.println("Error finding element \"PrivacyCaUrl\" in properties file. Setup cannot continue without this information."); + return; + } + if (CertValidityDays.equals("null")){ + System.out.println("Error finding element \"CertValidityDays\" in properties file. Setup cannot continue without this information."); + return; + } + /*if (PrivacyCaCertFileName.equals("null")){ + System.out.println("Error finding element \"PrivacyCaCertFileName\" in properties file. Setup cannot continue without this information."); + return; + }*/ + if (FileLocation.equals("null")){ + System.out.println("Error finding element \"FileLocation\" in properties file. Setup cannot continue without this information."); + return; + } + + //create random passwords! + if(PrivacyCaPassword.equals("***replace***")) + PrivacyCaPassword = TpmUtils.byteArrayToHexString(TpmUtils.createRandomBytes(16)); + if(EndorsementCaPassword.equals("***replace***")) + EndorsementCaPassword = TpmUtils.byteArrayToHexString(TpmUtils.createRandomBytes(16)); + String clientPath = ""; + String ecCaPath = ""; + int KeySize = 2048; + if (tomcatPath != null){ + InputStream in = null; + OutputStream out = null; + try { + //FileLocation = tomcatPath + "/webapps/HisPrivacyCAWebServices2/"; + //FileLocation = "/var/lib/oat-appraiser/"; + clientPath = "ClientFiles"; + ecCaPath = "CaCerts"; + //copy the TrustStore: FileLocation + "/Certificate/TrustStore.jks" + //in = new FileInputStream(new File(tomcatPath + "/Certificate/TrustStore.jks")); + in = new FileInputStream(new File(CredentialLocation + "Certificate/TrustStore.jks")); + out = new FileOutputStream(new File(CredentialLocation + clientPath + "/TrustStore.jks")); + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) + out.write(buf, 0, len); + in.close(); + out.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (in != null){ + try { + in.close(); + } catch (Exception e2) { + if (out != null) + out.close(); + } + + } + if (out != null){ + out.close(); + } + } + + } else { + tomcatPath = ""; + } + + ValidityDays = Integer.parseInt(CertValidityDays); + System.out.println("DONE"); + // Create the p12 files (2) + /* + * PrivacyCaSubjectName = HIS_Privacy_CA + * PrivacyCaFileName = PrivacyCA.p12 + * PrivacyCaPassword = replace + * EndorsementCaSubjectName = Endorsement_CA_Rev_1 + * EndorsementCaFileName = EndorseCA.p12 + * EndorsementCaPassword = replace + * HisRegistrationUrl = https://replace + * PrivacyCaUrl = https://replace + * CertValidityDays = 3652 + * PrivacyCaCertFileName = PrivCa.cer + * FileLocation = ./HIS_Setup .equals + */ + System.out.print("Creating p12 files..."); + // if(Integer.parseInt(ecSigningKeySize) == 1024 || Integer.parseInt(ecSigningKeySize) == 3072) + if(ecSigningKeySize.equals("1024") || ecSigningKeySize.equals("2048") || ecSigningKeySize.equals("3072")) + { + KeySize = Integer.parseInt(ecSigningKeySize); + } + TpmUtils.createCaP12(2048, PrivacyCaSubjectName, PrivacyCaPassword, CredentialLocation + PrivacyCaFileName, ValidityDays); + TpmUtils.createCaP12(KeySize, EndorsementCaSubjectName, EndorsementCaPassword, CredentialLocation + clientPath + "/" + EndorsementCaFileName, ValidityDays); + + + System.out.println("DONE"); + // Create the Privacy CA certificate file + System.out.print("Creating Privacy CA certificate..."); + X509Certificate pcaCert = TpmUtils.certFromP12(CredentialLocation + PrivacyCaFileName, PrivacyCaPassword); + FileOutputStream pcaFileOut = new FileOutputStream(new File(CredentialLocation + clientPath + "/" + PrivacyCaCertFileName)); + try { + if (pcaCert != null) + pcaFileOut.write(pcaCert.getEncoded()); + pcaFileOut.flush(); + pcaFileOut.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (pcaFileOut != null) + pcaFileOut.close(); + } + System.out.println("DONE"); + + // Create the Endorsement CA certificate file + System.out.print("Creating Endorsement CA certificate..."); + X509Certificate ecCert = TpmUtils.certFromP12(CredentialLocation + clientPath + "/" + EndorsementCaFileName, EndorsementCaPassword); + FileOutputStream ecFileOut = new FileOutputStream(new File(CredentialLocation + ecCaPath + "/" + EndorsementCaCertFileName)); + try { + if (ecCert != null) + ecFileOut.write(ecCert.getEncoded()); + ecFileOut.flush(); + ecFileOut.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (ecFileOut != null) + ecFileOut.close(); + } + + System.out.println("DONE"); + + // Create the other properties files (HISprovisioner and PrivacyCA) + System.out.print("Creating properties files..."); + String PrivacyCaPropertiesFile = "PrivacyCA.properties"; + String HisProvisionerPropertiesFile = "OATprovisioner.properties"; + String HisStandalonePropertiesFile = "OAT.properties"; + + /* + * + */ + //fos = new FileOutputStream(FileLocation + "/" + PrivacyCaPropertiesFile); + fos = new FileOutputStream(configPath + PrivacyCaPropertiesFile); + /* + * #Privacy CA Operation + * P12filename = PrivacyCA.p12 + * P12password = ***replace*** + * PrivCaCertValiditydays = 3652 + * #Privacy CA Registration + * HisRegistrationUrl = ***replace*** + * TrustStore = TrustStore.jks + */ + String toWrite = + "#Privacy CA Operation\r\n" + + "P12filename = " + PrivacyCaFileName + "\r\n" + + "P12password = " + PrivacyCaPassword + "\r\n" + + "PrivCaCertValiditydays = " + CertValidityDays + "\r\n" + + "#Privacy CA Registration\r\n" + + "HisRegistrationUrl = " + HisRegistrationUrl + "\r\n" + + "TrustStore = TrustStore.jks"; + try { + fos.write(toWrite.getBytes("US-ASCII")); + fos.flush(); + fos.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (fos != null) + fos.close(); + } + + + /* + * File: OATprovisioner.properties + * Used by: HisTpmProvisioner, HisIdentityProvisioner, HisRegisterIdentity + */ + fos = new FileOutputStream(CredentialLocation + clientPath + "/" + HisProvisionerPropertiesFile); + toWrite = + "#TPM Provisioning Data\r\n" + + "TpmEndorsmentP12 = " + EndorsementCaFileName + "\r\n" + + "EndorsementP12Pass = " + EndorsementCaPassword + "\r\n" + + "EcValidityDays = " + CertValidityDays + "\r\n" + + "TpmOwnerAuth = 1111111111111111111111111111111111111111\r\n" + + "##########HIS Identity Provisioning Data############\r\n" + + "HisIdentityLabel = HIS Identity Key\r\n" + + "HisIdentityIndex = 1\r\n" + + "HisIdentityAuth = " + AikAuth + "\r\n" + + "PrivacyCaCertFile = " + PrivacyCaCertFileName + "\r\n" + + "PrivacyCaUrl = " + PrivacyCaUrl + "\r\n" + + "HisRegistrationUrl = " + HisRegistrationUrl + "\r\n" + + "TrustStore = TrustStore.jks\r\n" + + "NtruBypass = true\r\n" + + "ClientPath = " + ClientPath + "\r\n" + + "ecStorage = " + ecStorage + "\r\n" + + "ecSigningKeySize = " + ecSigningKeySize + "\r\n"; + + try { + fos.write(toWrite.getBytes("US-ASCII")); + fos.flush(); + fos.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (fos != null) + fos.close(); + } + + + /* + * File: HIS.properties + * Used by: HIS Standalone (client reporter) + */ + fos = new FileOutputStream(CredentialLocation + clientPath + "/" + HisStandalonePropertiesFile); + toWrite = + "WebServiceUrl=" + HisRegistrationUrl + "\r\n" + + "KeyAuth=" + AikAuth + "\r\n" + + "KeyIndex=1\r\n" + + "TpmQuoteExecutableName=NIARL_TPM_Module.exe\r\n" + + "SplashImage=HIS07.jpg\r\n" + + "TrustStore=TrustStore.jks\r\n"; + + try { + fos.write(toWrite.getBytes("US-ASCII")); + fos.flush(); + fos.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (fos != null) + fos.close(); + } + + + /* + * File: install.bat + * Used by: not a properties file, but... assembles a batch file for the client installer + */ + String WinClientPath = CredentialLocation.replace("/", "\\"); + fos = new FileOutputStream(CredentialLocation + clientPath + "/install.bat"); + toWrite = + "rem DO NOT EDIT THIS FILE!\r\n" + + "rem This file is generated by the Privacy CA installation utility in Java\r\n" + + "call UninstallUSW.bat\r\n" + + "HIS-Standalone-Setup-v3.0a.exe /VERYSILENT /SUPPRESSMSGBOXES /LOG=\"tpminstall.log\" /DIR=\"" + ClientPath + "/\"\r\n" + + "copy /Y OAT.properties \"" + WinClientPath + "\\HIS.properties\"\r\n" + + "copy /Y trustStore.jks \"" + WinClientPath + "\\\"\r\n" + + "copy /Y NIARL_TPM_Module.exe \"" + WinClientPath + "\\\"\r\n" + + "rem cd \"HIS Provisioner\" \r\n" + + "call provisioner.bat\r\n" + + "cd \"" + WinClientPath + "\\service\\\"\r\n" + + "call \"replaceUSW.bat\"\r\n"; + try { + fos.write(toWrite.getBytes("US-ASCII")); + fos.flush(); + fos.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (fos != null) + fos.close(); + } + + System.out.println("DONE"); + } catch (Exception e) { + System.out.println(e.toString()); + } + } +} diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/PrivacyCaException.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/PrivacyCaException.java new file mode 100644 index 0000000..0f69790 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/PrivacyCaException.java @@ -0,0 +1,32 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +/** + *

This exception is intended to be used to throw Privacy CA-specific exceptions.

+ * + * @author schawki + * + */ +public class PrivacyCaException extends Exception { + private static final long serialVersionUID = 0; + /** + * Create the exception using a message string. + * + * @param msg Custom message for the exception + */ + public PrivacyCaException(String msg) { + super(msg); + } +} diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmAsymCaContents.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmAsymCaContents.java new file mode 100644 index 0000000..d6783a0 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmAsymCaContents.java @@ -0,0 +1,129 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.security.*; +import java.security.spec.*; +import java.security.interfaces.*; +import javax.crypto.*; +import javax.crypto.spec.*; + +/** + *

This class is the Java version of the C-style structure TPM_ASYM_CA_CONTENTS, + * as specified by the TCG. It contains all of the member variables specified by + * the TCG, and any applicable functions. This structure is normally created by + * the Privacy CA, is encrypted using a TPM's public EK, and holds the symmetric + * key needed to decrypt a paired TpmSymCaAttestation.

+ * + * @author schawki + * + */ +public class TpmAsymCaContents { + private TpmSymmetricKey symKey = null; + private byte [] tpmDigest = null; + private byte [] encrypted = null; + public TpmAsymCaContents(){} + /** + * Set the TpmSymmetricKey member data. + * + * @param newKey + */ + public void setSymmetricKey(TpmSymmetricKey newKey) { + symKey = newKey; + } + /** + * Set the TPM digest. This is required before the TpmAsymCaContents structure can be encrypted. + * + * @param aik The AIK in the form of a TpmPubKeu. + * @throws NoSuchAlgorithmException Thrown if the MessageDigest class doesn't know what "SHA-1" means. + * @throws TpmUtils.TpmUnsignedConversionException Thrown if there is a problem converting the AIK to a byte array. + */ + public void setDigest(TpmPubKey aik) + throws NoSuchAlgorithmException, + TpmUtils.TpmUnsignedConversionException { + MessageDigest md; + md = MessageDigest.getInstance("SHA-1"); + md.update(aik.toByteArray()); + tpmDigest = md.digest(); + } + /** + * Encrypt the TpmAsymCaContents for return to the TPM. The symmetric key and digest must be set for this function to run without Exception. + * + * @param ekPubKey The EK public key, extracted form the EK certificate included in the identity request/proof. + * @throws NoSuchPaddingException Encryption error. + * @throws NoSuchAlgorithmException Encryption error. + * @throws InvalidKeyException Encryption error. + * @throws InvalidAlgorithmParameterException Encryption error. + * @throws IllegalBlockSizeException Encryption error. + * @throws BadPaddingException Encryption error. + * @throws TpmUtils.TpmUnsignedConversionException Error in converting structures to byte arrays (bad data, most likely). + * @throws PrivacyCaException All required prerequisites were not met. + */ + public void encrypt(RSAPublicKey ekPubKey, boolean TrousersModeBlankOeap) // use the TPM's EK + throws NoSuchPaddingException, + NoSuchAlgorithmException, + InvalidKeyException, + InvalidAlgorithmParameterException, + IllegalBlockSizeException, + BadPaddingException, + TpmUtils.TpmUnsignedConversionException, + PrivacyCaException { + OAEPParameterSpec oaepSpec; + if (!TrousersModeBlankOeap) + oaepSpec = new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified("TCPA".getBytes())); + else + oaepSpec = new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified("".getBytes())); + Cipher asymCipher = Cipher.getInstance("RSA/ECB/OAEPWithSha1AndMGF1Padding"); + asymCipher.init(Cipher.PUBLIC_KEY, ekPubKey, oaepSpec); + byte[] newbytes = this.toPlaintextByteArray(); + asymCipher.update(newbytes); + encrypted = asymCipher.doFinal(); + } + /** + * Get the encrypted TpmAsymCaContents as a byte array suitable for delivery to the TPM with TPM_ActivateIdentity. + * + * @return A byte array form of the TpmAsymCaContents. + * @throws PrivacyCaException Throws if the structure is not ready to be sent back to the TPM. + */ + public byte [] toByteArray() + throws PrivacyCaException { + if (encrypted == null) { + throw new PrivacyCaException("Cannot access encrypted TpmAsymCaContents until encryption process has been run."); + } + return encrypted; + } + /** + * Return a byte array of the plaintext structure suitable for encryption. All prerequisites must be met, + * which are just populating all of the private member variables. + * + * @return the plaintext byte array. + * @throws TpmUtils.TpmUnsignedConversionException Thrown if there is a problem in assembling the array. + * @throws PrivacyCaException If the prereqs are not met. + */ + private byte [] toPlaintextByteArray() + throws TpmUtils.TpmUnsignedConversionException, + PrivacyCaException { + if (symKey == null) { + throw new PrivacyCaException("Cannot convert TpmAsymCaContents to byte array until TpmSymmetricKey is set."); + } + if (tpmDigest == null) { + throw new PrivacyCaException("Cannot convert TpmAsymCaContents to byte array until TPM digest has been created."); + } + byte [] symKeyBytes = symKey.toByteArray(); + byte [] returnArray = new byte[symKeyBytes.length + tpmDigest.length]; + System.arraycopy(symKeyBytes, 0, returnArray, 0, symKeyBytes.length); + System.arraycopy(tpmDigest, 0, returnArray, symKeyBytes.length, tpmDigest.length); + return returnArray; + } +} diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmIdentityProof.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmIdentityProof.java new file mode 100644 index 0000000..573a797 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmIdentityProof.java @@ -0,0 +1,415 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.security.*; +import java.security.spec.*; +import java.security.interfaces.*; +import java.io.*; +import javax.security.cert.*; + +/** + * See TPM_IDENTITY_PROOF

+ * + *

The TpmIdentityProof is the plain-text incarnation of a TPM's request for an + * AIK credential. The data contained in the identity proof is used to verify the + * integrity of the request, and to construct an AIK credential.

+ * + * The TPM_IDENTITY_PROOF structure, as defined by the TCG, contains the following elements: + *
    + *
  • TPM_STRUCT_VER, which is a byte array always equal to 0x01010000
  • + *
  • AIK in the form of a TPM_PUBKEY (TpmPubKey class)
  • + *
  • Identity label The requested name for the identity. This will (probably) be placed in the Subject Alternative Name field in the AIC by the Privacy CA, per specification.
  • + *
  • Identity binding This is the signature, made using the private AIK, of a hash made of the TPM_IDENTITY_CONTENTS structure (see note below).
  • + *
  • Endorsement Certificate (optional) This really should be a required item, but isn't.
  • + *
  • Platform Certificate (optional)
  • + *
  • Conformance Certificate (optional)
  • + *
+ * + * This class adds additional flags to clarify discrepancies that have been observed among TSS implementations. These flags include: + *
    + *
  • TrousersModeIV (boolean) Though both NTRU and TrouSerS place the initialization vector for symmetrically encrypted data within, but at the beginning of, the encrypted data blob, the specification states that the IV should be recorded within the TPM_KEY_PARMS structure for the symmetric key. Setting this boolean to TRUE indicates the use of "TrouSerS-style placement.
  • + *
  • TrousersModeSymkeyEncscheme (boolean) TrouSerS (but not NTRU) incorrectly sets the symmetric encryption scheme to TPM_ES_NONE. The correct scheme to use is TPM_ES_SYM_CBC_PKCS5PAD. Both NTRU and TrouSerS use this scheme for encryption, but TrouSerS records it as otherwise.
  • + *
  • TrousersModeBlankOeap (boolean) TrouSerS incorrectly encrypts the asymmetric blob, as it uses a blank OEAP password. The password should be "TCPA".
  • + *
+ * + *

Developer note: Methods in this class are responsible for working with all aspects of the + * TPM_IDENTITY_CONTENTS structure. A future version of the TPM support code may include + * a TpmIdentityContents class, which would greatly simplify the code in this class.

+ * + *

This class can be used by a Privacy CA for parsing an incoming request, but + * it can also be used by a client for constructing a new request.

+ * + * @author schawki + * @see TpmIdentityRequest + */ +public class TpmIdentityProof { + private byte [] structVer; + private TpmPubKey Aik; + private byte [] idLabelBytes; + private byte [] idBindingBytes; + private byte [] ekCredBytes; + private byte [] platformCredBytes; + private byte [] conformCredBytes; + private boolean TrousersModeIV = false; + private boolean TrousersModeSymkeyEncscheme = false; + private boolean TrousersModeBlankOeap = false; + /** + * Get the TrousersModeIV status. A value of TRUE indicates that the IV placement is inside, and at the beginning of, the symmetrically encrypted blob and not in the symmetric key parameters. This will almost always be set at TRUE. + * + * @return The status of the flag. + */ + public boolean getIVmode(){ + return TrousersModeIV; + } + /** + * Set the TrousersModeIV status. A value of TRUE indicates that the IV placement is inside, and at the beginning of, the symmetrically encrypted blob and not in the symmetric key parameters. This will almost always be set at TRUE. + * + * @param newMode Set to TRUE for greatest compatibility; set to FALSE for compliance to specification. + */ + public void setIVmode(boolean newMode) { + TrousersModeIV = newMode; + } + /** + * Get the TrousersModeSymkeyEncscheme status. A value of TRUE indicates that the identity proof was constructed by TrouSerS, and is not compliant with the specification. + * + * @return The status of the flag. + */ + public boolean getSymkeyEncscheme() { + return TrousersModeSymkeyEncscheme; + } + /** + * Set the TrousersModeSymkeyEncscheme flag. This should always be set to FALSE. + * + * @param newScheme Set to TRUE to emulate an identity proof created by TrouSerS; set to FALSE to comply with the specification. + */ + public void setSymkeyEncscheme(boolean newScheme) { + TrousersModeSymkeyEncscheme = newScheme; + } + /** + * Get the TrousersModeBlankOeap flag. A value of TRUE indicates that the identity proof was constructed by TrouSerS, and is not compliant with the specification. + * + * @return The status of the flag. + */ + public boolean getOeapMode () { + return TrousersModeBlankOeap; + } + /** + * Set the TrousersModeBlankOeap flag. A value of TRUE indicates that the identity proof was constructed by TrouSerS, and is not compliant with the specification. + * + * @param newMode Set to TRUE to emulate an identity proof constructed by TrouSerS; set to FALSE to comply with the specification. + */ + public void getOeapMode(boolean newMode) { + TrousersModeBlankOeap = newMode; + } + /** + * Create new TpmIdentityProof object by parsing the decrypted data from a + * TPM_IDENTITY_REQ. Information gathered while parsing and decrypting the + * Identity Request is needed to properly parse the Ideneity Proof. Also, + * that information may be useful when crafting the response to the client. + * + * @param blob The decrypted form of the sym blob from the Identity Request. + * @param IV Set to TRUE if the IV was placed at the beginning of the symblob of the Identity Request instead of in the key parameters. + * @param symKey Set to TRUE if the symmetric encryption scheme was set to TPM_ES_NONE in the Identity Request. + * @param oaep Set to TRUE if the OAEP password was blank. + * @throws PrivacyCaException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public TpmIdentityProof(byte[] blob, boolean IV, boolean symKey, boolean oaep) + throws PrivacyCaException, + TpmUtils.TpmUnsignedConversionException, + TpmUtils.TpmBytestreamResouceException { + TrousersModeIV = IV; + TrousersModeSymkeyEncscheme = symKey; + TrousersModeBlankOeap = oaep; + ByteArrayInputStream bs = new ByteArrayInputStream(blob); + structVer = new byte[4]; + structVer = TpmUtils.getBytes(bs, 4); + int labelSize = TpmUtils.getUINT32(bs); + int identBindingSize = TpmUtils.getUINT32(bs); + int ekCredSize = TpmUtils.getUINT32(bs); + //This is where things go wrong with no EK certificate!! + //if (ekCredSize == 0) throw new PrivacyCaException("PrivacyCaException: Error parsing TPM_IDENTITY_PROOF: there is no endorsement credential."); + int platformCredSize = TpmUtils.getUINT32(bs); + int conformCredSize = TpmUtils.getUINT32(bs); + Aik = new TpmPubKey(bs); + idLabelBytes = TpmUtils.getBytes(bs, labelSize); + idBindingBytes = TpmUtils.getBytes(bs, identBindingSize); + ekCredBytes = TpmUtils.getBytes(bs, ekCredSize); + platformCredBytes = TpmUtils.getBytes(bs, platformCredSize); + conformCredBytes = TpmUtils.getBytes(bs, conformCredSize); + } + /** + * Create a new TpmIdentityProof by supplying all of the necessary elements to construct one from scratch. + * + * @param idLabel The requested Identity Label. This is usually assigned as the Subject Alternative Name in the AIC. Supply as ASCII string in byte array. + * @param idBinding The identity binding is supplied from the TPM by running TPM_MakeIdentity (available via TCS, not TSP). Should be 256 byte (signature made using 2048 bit AIK). + * @param AIK The AIK in TpmPubKey form. This should also be supplied from the TPM using TPM_MakeIdentity. + * @param ekCertBytes (Optional) Endorsement Certificate (EC), usually as an X.509 certificate, as a byte array. Null is acceptable. + * @param platformCertBytes (Optional) Platform Certificate, usually as an X.509 certificate, as a byte array. Null is acceptable. + * @param conformanceCertBytes (Optional) Conformance Certificate, usually as an X.509 certificate, as a byte array. Null is acceptable. + * @param IV TrouSerS IV placement mode flag. Recommended setting is TRUE. + * @param symKey TrouSerS symmetric encryption scheme flag. Recommended setting is FALSE. + * @param oaep TrouSerS use of blank OAEP password flag. Recommended setting is FALSE. + */ + public TpmIdentityProof(byte [] idLabel, byte [] idBinding, TpmPubKey AIK, byte [] ekCertBytes, byte [] platformCertBytes, byte [] conformanceCertBytes, boolean IV, boolean symKey, boolean oaep) { + TrousersModeIV = IV; + TrousersModeSymkeyEncscheme = symKey; + TrousersModeBlankOeap = oaep; + byte [] temp = {(byte)0x01, (byte)0x01, (byte)0x00, (byte)0x00}; + structVer = temp; + Aik = AIK; + idLabelBytes = idLabel; + idBindingBytes = idBinding; + ekCredBytes = ekCertBytes; + platformCredBytes = platformCertBytes; + conformCredBytes = conformanceCertBytes; + } + /** + * Get the Identity Proof in the form of a byte array. + * + * @return Entire Identity Proof in the form of a byte array. + * @throws TpmUtils.TpmUnsignedConversionException Thrown if there are any out-of-bounds problems converting from (signed) Java long to UINT32. + */ + public byte [] toByteArray() + throws TpmUtils.TpmUnsignedConversionException { + // Get byte elements of the proof + //byte [] structVer - already exists in final form + byte [] labelSize = TpmUtils.intToByteArray(idLabelBytes.length); + byte [] idBindingSize = TpmUtils.intToByteArray(idBindingBytes.length); + byte [] endorsementSize = TpmUtils.intToByteArray(ekCredBytes.length); + byte [] platformSize = TpmUtils.intToByteArray(ekCredBytes.length); + byte [] conformanceSize = TpmUtils.intToByteArray(ekCredBytes.length); + byte [] identityKey = Aik.toByteArray(); + //byte [] idLabelBytes - already exists in final form + //byte [] idBindingBytes - already exists in final form + //byte [] ekCredBytes - already exists in final form + //byte [] platformCredBytes - already exists in final form + //byte [] conformCredBytes - already exists in final form + // Assemble the return array + byte [] toReturn = new byte[structVer.length + labelSize.length + idBindingSize.length + endorsementSize.length + platformSize.length + conformanceSize.length + + identityKey.length + idLabelBytes.length + idBindingBytes.length + ekCredBytes.length + platformCredBytes.length + conformCredBytes.length]; + int copyOffset = 0; + System.arraycopy(structVer, 0, toReturn, copyOffset, structVer.length); + copyOffset += structVer.length; + System.arraycopy(labelSize, 0, toReturn, copyOffset, labelSize.length); + copyOffset += labelSize.length; + System.arraycopy(idBindingSize, 0, toReturn, copyOffset, idBindingSize.length); + copyOffset += idBindingSize.length; + System.arraycopy(endorsementSize, 0, toReturn, copyOffset, endorsementSize.length); + copyOffset += endorsementSize.length; + System.arraycopy(platformSize, 0, toReturn, copyOffset, platformSize.length); + copyOffset += platformSize.length; + System.arraycopy(conformanceSize, 0, toReturn, copyOffset, conformanceSize.length); + copyOffset += conformanceSize.length; + System.arraycopy(identityKey, 0, toReturn, copyOffset, identityKey.length); + copyOffset += identityKey.length; + System.arraycopy(idLabelBytes, 0, toReturn, copyOffset, idLabelBytes.length); + copyOffset += idLabelBytes.length; + System.arraycopy(idBindingBytes, 0, toReturn, copyOffset, idBindingBytes.length); + copyOffset += idBindingBytes.length; + System.arraycopy(ekCredBytes, 0, toReturn, copyOffset, ekCredBytes.length); + copyOffset += ekCredBytes.length; + System.arraycopy(platformCredBytes, 0, toReturn, copyOffset, platformCredBytes.length); + copyOffset += platformCredBytes.length; + System.arraycopy(conformCredBytes, 0, toReturn, copyOffset, conformCredBytes.length); + return toReturn; + } + /** + * Display the parsed contents of the request in a form suitable for display on console or in log file. This is intended to be used when troubleshooting. + * + * @return Multi-line human readable breakdown of identity proof contents + */ + public String toString() { + String returnVal = ""; + returnVal += "TpmIdentityProof:\n"; + returnVal += " StructVer: " + TpmUtils.byteArrayToString(structVer, 16) + "\n"; + returnVal += " Aik:\n" + Aik.toString() + "\n"; + String junk = new String(idLabelBytes); + returnVal += " idLabel:\n" + junk + "\n"; + returnVal += " idBinding:\n" + TpmUtils.byteArrayToString(idBindingBytes, 16) + "\n"; + returnVal += " ekCred:\n" + TpmUtils.byteArrayToString(ekCredBytes, 16) + "\n"; + returnVal += " platformCred:\n" + TpmUtils.byteArrayToString(platformCredBytes, 16) + "\n"; + returnVal += " conformCred:\n" + TpmUtils.byteArrayToString(conformCredBytes, 16) + "\n"; + return returnVal; + } + /** + * Use the identity binding (the signature value of the TPM_IDENTITY_CONTENTS structure) to determine the validity of the request.

+ * The TPM_IDENTITY_CONTENTS structure contains the public AIK and a hash of the idLabel and the Privacy CA's public key.

+ * + * @param caPubKey The Privacy CA's public key. + * @return True if the identity binding checks out, false if it does not. + * @throws NoSuchAlgorithmException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws InvalidKeyException + * @throws InvalidKeySpecException + * @throws SignatureException + */ + public boolean checkValidity(RSAPublicKey caPubKey) + throws NoSuchAlgorithmException, + TpmUtils.TpmUnsignedConversionException, + InvalidKeyException, + InvalidKeySpecException, + SignatureException { + TpmPubKey pca = new TpmPubKey(caPubKey, 3, 1); + MessageDigest md = MessageDigest.getInstance("SHA1"); + byte [] pcaBytes = pca.toByteArray(); + byte [] chosenId = new byte[idLabelBytes.length + pcaBytes.length]; + System.arraycopy(idLabelBytes, 0, chosenId, 0, idLabelBytes.length); + System.arraycopy(pcaBytes, 0, chosenId, idLabelBytes.length, pcaBytes.length); + md.update(chosenId); + byte [] chosenIdHash = md.digest(); + byte [] tpmMakeIdOrd = TpmUtils.intToByteArray(0x79); + byte [] aikPubKey = Aik.toByteArray(); + //Structver in new (NTru) requests is appearing as 01 02 04 1E. Strange. (9/8/2009). + //To compensate, using a shim copy of structver populated with the correct values. + // + //In this case, the problem is that the structver included as cleartext in the identity proof is + //placed by the TSS, but the identity binding is created by the TPM independently. If one value of + //structver is used during the creation of the identity binding signature but a different structver + //is used when performing verification, the result will always be a failure to verify. + byte [] thisStructVer = structVer; + byte [] traditionalStructVer = {(byte)0x01, (byte)0x01, (byte)0x00, (byte)0x00}; + thisStructVer = traditionalStructVer; + byte [] identityContents = new byte[thisStructVer.length + tpmMakeIdOrd.length + chosenIdHash.length + aikPubKey.length]; + System.arraycopy(thisStructVer, 0, identityContents, 0, thisStructVer.length); + System.arraycopy(tpmMakeIdOrd, 0, identityContents, thisStructVer.length, tpmMakeIdOrd.length); + System.arraycopy(chosenIdHash, 0, identityContents, thisStructVer.length + tpmMakeIdOrd.length, chosenIdHash.length); + System.arraycopy(aikPubKey, 0, identityContents, thisStructVer.length + tpmMakeIdOrd.length + chosenIdHash.length, aikPubKey.length); + Signature sig = Signature.getInstance("SHA1withRSA"); + sig.initVerify(Aik.getKey()); + sig.update(identityContents); + boolean bindingCheck = sig.verify(idBindingBytes); + //if (bindingCheck) System.out.println("bindingCheck is TRUE"); else System.out.println("bindingCheck is FALSE"); + return bindingCheck; + } + /** + * Get the AIK stored in the request. + * + * @return The AIK as a TpmPubKey. + */ + public TpmPubKey getAik() { + return Aik; + } + /** + * Get the TPM_STRUCT_VER. Should always be 0x01010000. + * + * @return The four-byte TpmStructVer. + */ + public byte [] getVer() { + return structVer; + } + /** + * Get the Identity Label string (in ASCII byte array) as stored in the Identity Proof. + * + * @return The identity label as a byte string (ASCII). + */ + public byte [] getIdLableBytes() { + return idLabelBytes; + } + /** + * Return the Identity Binding. It should be the signature of the Identity Contents made using the AIK. Should always be 256 bytes. + * + * @return The identity binding, as extracted directly from the identity proof. + */ + public byte [] getIdBindingBytes() { + return idBindingBytes; + } + /** + * EC stored in the Identity Proof, if present, in the form of raw bytes. + * + * @return The X509 Endorsement Key Certificate as a byte array. This must be present to complete the Privacy CA process. + */ + public byte [] getEkCredBytes() { + return ekCredBytes; + } + /** + * EC stored in the Identity Proof, if present, in the form of an X509Certificate object. + * + * @return The EK certificate as a java X509Certificate. + * @throws CertificateException + */ + public X509Certificate getEkCred() + throws CertificateException { + return X509Certificate.getInstance(ekCredBytes); + } + /** + * PC stored in the Identity Proof, if present, in the form of raw bytes. + * + * @return The Platform Certificate as a byte array. May be null. + */ + public byte [] getPlatformCredBytes() { + return platformCredBytes; + } + /** + * PC stored in the Identity Proof, if present, in the form of an X509Certificate object. + * + * @return The Platform Certificate as a Java X509Certificate. If not present, will throw exception. + * @throws CertificateException + * @throws java.security.cert.CertificateException + * @throws java.security.cert.CertificateEncodingException + */ + public X509Certificate getPlatformCred() + throws CertificateException, + java.security.cert.CertificateException, + java.security.cert.CertificateEncodingException { + return getCertFromBytes(platformCredBytes); + } + /** + * CC stored in the Identity Proof, if present, in the form of raw bytes. + * + * @return The Conformance Credential as a byte array. May be null. + */ + public byte [] getConformCredBytes() { + return conformCredBytes; + } + /** + * CC stored in the Identity Proof, if present, in the form of an X509Certificate object. + * + * @return The Conformance Credential as a Java X509Certificate. If not present, will throw exception. + * @throws CertificateException + * @throws java.security.cert.CertificateException + * @throws java.security.cert.CertificateEncodingException + */ + public X509Certificate getConformCred() + throws CertificateException, + java.security.cert.CertificateException, + java.security.cert.CertificateEncodingException { + return getCertFromBytes(conformCredBytes); + } + /** + * Convert from a byte array to a Java X509 Certificate. By default, all of the Privacy CA functions use + * javax.security.cert.X509Certificate. The conversion process requires the creation of a + * java.security.cert.X509Certificate. Although these two are identitical in structure, their member + * functions are different, and are seen by Java as different. This function performs the conversion process + * between the two. + * + * @param certBytes The byte array to convert. + * @return A javax.security.cert.X509Certificate. + * @throws CertificateException + * @throws java.security.cert.CertificateException + * @throws java.security.cert.CertificateEncodingException + */ + private X509Certificate getCertFromBytes(byte [] certBytes) + throws CertificateException, + java.security.cert.CertificateException, + java.security.cert.CertificateEncodingException { + ByteArrayInputStream bs = new ByteArrayInputStream(certBytes); + java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509"); + java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate)cf.generateCertificate(bs); + X509Certificate xcert = javax.security.cert.X509Certificate.getInstance(cert.getEncoded()); + return xcert; + } +} diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmIdentityRequest.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmIdentityRequest.java new file mode 100644 index 0000000..74d3183 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmIdentityRequest.java @@ -0,0 +1,656 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import javax.crypto.Cipher; +import java.security.interfaces.*; +import java.security.spec.*; +import java.security.*; +import javax.crypto.*; +import javax.crypto.spec.*; + +import java.io.*; + +/** + *

The TpmIdentityRequest class is based on the TPM_IDENTITY_REQUEST structure and includes + * associated methods. An identity request is generally created by running the TSS function + * Tspi_TPM_CollateIdentityRequest. The request contains two parts: a symmetrically + * encrypted identity proof (TPM_IDENTITY_PROOF); and an asymmetrically encrypted portion + * containing the key used to encrypt the symmetric portion. This class contains + * functionality to decode and decrypt the identity request and return an identity proof. + * There is also functionality to create a new request, given an identity proof and the key + * needed to encrypt it.

+ *

Different implementations of the TSS create slightly different formats of identity requests. + * The two version of TSS researched in the development of this class were NTru's CTSS v1.2.1.29 + * and IBM's TrouSerS v

+ * + * @author schawki + * + */ +public class TpmIdentityRequest { + private byte[] asymBlob; + private byte[] symBlob; + private TpmKeyParams asymAlgorithm; + private TpmKeyParams symAlgorithm; + private boolean TrousersModeIV = false; + private boolean TrousersModeSymkeyEncscheme = false; + private boolean TrousersModeBlankOeap = false; + + public byte[] getAsymBlob(){ + return asymBlob; + } + public byte[] getSymBlob(){ + return symBlob; + } + + /** + * Get a copy of the flag used to indicate the placement of the initialization vector used for this request. + * + * @return True indicates that the placement is the first part of the symmetrically encrypted blob; false indicates that the placement is within the TPM_SYMMETRIC_KEY_PARMS portion of the TPM_KEY_PARMS structure used to describe the symmetric key usage. + */ + public boolean getIVmode(){ + return TrousersModeIV; + } + /** + * Set the flag used to dictate the placement of the initialization vector for this request. + * + * @param newMode True indicates that the placement be the first part of the symmetrically encrypted blob; false indicates that the placement be within the TPM_SYMMETRIC_KEY_PARMS portion of the TPM_KEY_PARMS structure used to describe the symmetric key usage. + */ + public void setIVmode(boolean newMode) { + TrousersModeIV = newMode; + } + /** + * Get a status of the flag that indicates the usage of the encryption mode used for symmetric encryption. Based on observation, all TSS implementations use + * + * @return TRUE if TrouSerS use of TPM_ES_NONE is used; FALSE if consistent with the specification. + */ + public boolean getSymkeyEncscheme() { + return TrousersModeSymkeyEncscheme; + } + /** + * Set the status of the TrouSerS encryption scheme flag. + * + * @param newScheme Set to TRUE to emulate TrouSerS' use of TPM_ES_NONE; set to FALSE to comply with the specification. + */ + public void setSymkeyEncscheme(boolean newScheme) { + TrousersModeSymkeyEncscheme = newScheme; + } + /** + * Get the status of the TrouSerS OEAP flag. TrouSerS (at least in the version available through Yum) uses a blank OEAP password when performing asymmetric encryption. The password should be "TCPA". + * + * @return TRUE if TrouSerS use of a blank OEAP password is in use; FALSE if the correct password is used. + */ + public boolean getOeapMode () { + return TrousersModeBlankOeap; + } + /** + * Set the status of the TrouSerS OEAP flag. + * + * @param newMode Set to TRUE to emulate TrouSerS use of a blank OEAP password; set to FALSE to comply with the specification. + */ + public void getOeapMode(boolean newMode) { + TrousersModeBlankOeap = newMode; + } + + /** + * Create a new TpmIdentityRequest object by initializing with a byte blob from the output of + * Tspi_TPM_CollateIdentityRequest. + * + * @param blob The byte blob form of the identity request. + * @throws TpmUtils.TpmUnsignedConversionException + * @throws TpmUtils.TpmBytestreamResouceException + * @throws PrivacyCaException + */ + public TpmIdentityRequest(byte[] blob) + throws TpmUtils.TpmUnsignedConversionException, + TpmUtils.TpmBytestreamResouceException, + PrivacyCaException { + ByteArrayInputStream bs = new ByteArrayInputStream(blob); + int asymSize = TpmUtils.getUINT32(bs); + int symSize = TpmUtils.getUINT32(bs); + asymAlgorithm = new TpmKeyParams(bs); + symAlgorithm = new TpmKeyParams(bs); + TrousersModeIV = symAlgorithm.getTrouSerSmode(); + asymBlob = TpmUtils.getBytes(bs, asymSize); + symBlob = TpmUtils.getBytes(bs, symSize); + findIv(); + } + /** + * Create a new TpmIdentityRequest by supplying a TpmIdentityProof and the Privacy CA's public key. A symmetric key and IV will be randomly created. + * + * @param newIdProof A TpmIdentityProof object + * @param caKey The Privacy CA's private key + * @throws IOException + * @throws IllegalBlockSizeException + * @throws BadPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws TpmUtils.TpmUnsignedConversionException + */ + public TpmIdentityRequest(TpmIdentityProof newIdProof, RSAPublicKey caKey) + throws IOException, + IllegalBlockSizeException, + BadPaddingException, + InvalidKeyException, + InvalidAlgorithmParameterException, + NoSuchAlgorithmException, + NoSuchPaddingException, + TpmUtils.TpmUnsignedConversionException { + this(newIdProof, caKey, TpmUtils.createRandomBytes(16), TpmUtils.createRandomBytes(16)); + } + /** + * Create a new TpmIdentityRequest by supplying a TpmIdentityProof, the Privacy CA's public key, a symmetric key, and an IV. + * + * @param newIdProof A TpmIdentityProof object + * @param caKey The Privacy CA's private key + * @param key Symmetric key to use for encrypting the request (will itself be encrypted using the Privacy CA public key) + * @param iv Initialization Vector to be used for symmetric encryption + * @throws IllegalBlockSizeException + * @throws BadPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws TpmUtils.TpmUnsignedConversionException + */ + public TpmIdentityRequest(TpmIdentityProof newIdProof, RSAPublicKey caKey, byte [] key, byte [] iv) + throws IllegalBlockSizeException, + BadPaddingException, + InvalidKeyException, + InvalidAlgorithmParameterException, + NoSuchAlgorithmException, + NoSuchPaddingException, + TpmUtils.TpmUnsignedConversionException { + this(newIdProof, caKey, createDefaultAsymAlgorithm(), createDefaultSymAlgorithm(iv), key); + } + /** + * Create a new TpmIdentityRequest by supplying a TpmIdentityProof, the Privacy CA's public key, a symmetric key, and an IV. + * + * @param newIdProof A TpmIdentityProof object + * @param caKey The Privacy CA's private key + * @param newAsymAlgorithm Asymmetric encryption information in the form of a TpmKeyParams object + * @param newSymAlgorithm Symmetric encryption information in the form of a TpmKeyParams object + * @throws IOException + * @throws IllegalBlockSizeException + * @throws BadPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws TpmUtils.TpmUnsignedConversionException + */ + public TpmIdentityRequest(TpmIdentityProof newIdProof, RSAPublicKey caKey, TpmKeyParams newAsymAlgorithm, TpmKeyParams newSymAlgorithm) + throws IOException, + IllegalBlockSizeException, + BadPaddingException, + InvalidKeyException, + InvalidAlgorithmParameterException, + NoSuchAlgorithmException, + NoSuchPaddingException, + TpmUtils.TpmUnsignedConversionException { + this(newIdProof, caKey, newAsymAlgorithm, newSymAlgorithm, TpmUtils.createRandomBytes(16)); + } + public TpmIdentityRequest(TpmIdentityProof newIdProof, RSAPublicKey caKey, TpmKeyParams newAsymAlgorithm, TpmKeyParams newSymAlgorithm, byte [] key) + throws IllegalBlockSizeException, + BadPaddingException, + InvalidKeyException, + InvalidAlgorithmParameterException, + NoSuchAlgorithmException, + NoSuchPaddingException, + TpmUtils.TpmUnsignedConversionException { + TrousersModeIV = newIdProof.getIVmode(); + asymAlgorithm = newAsymAlgorithm; + symAlgorithm = newSymAlgorithm; + symAlgorithm.setTrouSerSmode(TrousersModeIV); + TrousersModeSymkeyEncscheme = newIdProof.getSymkeyEncscheme(); + TrousersModeBlankOeap = newIdProof.getOeapMode(); + encryptAsym(encryptSym(newIdProof.toByteArray(), key, symAlgorithm.getSubParams().getByteData()), caKey); + if (TrousersModeIV) { + //symAlgorithm.setSubParams(null); //taken care of by TpmKeyParams + byte [] newSymblob = new byte[symAlgorithm.getSubParams().getByteData().length + symBlob.length]; + System.arraycopy(symAlgorithm.getSubParams().getByteData(), 0, newSymblob, 0, symAlgorithm.getSubParams().getByteData().length); + System.arraycopy(symBlob, 0, newSymblob, symAlgorithm.getSubParams().getByteData().length, symBlob.length); + symBlob = newSymblob; + } + } + /** + * Create a new Identity Request using an arbitrary byte blob as an Identity Proof and random AES 256 key and IV. This function is intended to be used to wrap data in the form of an Identity Request that may not be an Identity Proof. An example of this may be an Endorsement Credential. + * + * @param newIdProof Arbitrary byte blob to take the position of an Identity Proof. + * @param caKey Privacy CA's public key + * @param TrouSerS true if request should be structured like one TrouSerS would create, false if request should be structured like one NTRU would create. + * @throws IllegalBlockSizeException + * @throws BadPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws IOException + */ + public TpmIdentityRequest(byte[] newIdProof, RSAPublicKey caKey, boolean TrouSerS) + throws IllegalBlockSizeException, + BadPaddingException, + InvalidKeyException, + InvalidAlgorithmParameterException, + NoSuchAlgorithmException, + NoSuchPaddingException, + TpmUtils.TpmUnsignedConversionException, IOException { + TrousersModeIV = true; + asymAlgorithm = createDefaultAsymAlgorithm(); + symAlgorithm = createDefaultSymAlgorithm(TpmUtils.createRandomBytes(16)); + symAlgorithm.setTrouSerSmode(TrousersModeIV); + if(TrouSerS){ + TrousersModeSymkeyEncscheme = true; + TrousersModeBlankOeap = true; + }else{ + TrousersModeSymkeyEncscheme = false; + TrousersModeBlankOeap = false; + } + encryptAsym(encryptSym(newIdProof, TpmUtils.createRandomBytes(16), symAlgorithm.getSubParams().getByteData()), caKey); + if (TrousersModeIV) { + byte [] newSymblob = new byte[symAlgorithm.getSubParams().getByteData().length + symBlob.length]; + System.arraycopy(symAlgorithm.getSubParams().getByteData(), 0, newSymblob, 0, symAlgorithm.getSubParams().getByteData().length); + System.arraycopy(symBlob, 0, newSymblob, symAlgorithm.getSubParams().getByteData().length, symBlob.length); + symBlob = newSymblob; + } + } + /** + * Create a default TpmKeyParams for the asym portion of the request. + * + * @return + */ + private static TpmKeyParams createDefaultAsymAlgorithm() { + TpmKeyParams toReturn = new TpmKeyParams(); + toReturn.setAlgorithmId(TpmKeyParams.TPM_ALG_RSA);//1 + toReturn.setEncScheme((short)TpmKeyParams.TPM_ES_RSAESOAEP_SHA1_MGF1);//3 + toReturn.setSigScheme((short)TpmKeyParams.TPM_SS_NONE);//1 + TpmRsaKeyParams newRsaKeyParams = new TpmRsaKeyParams(); + newRsaKeyParams.setKeyLength(2048); + newRsaKeyParams.setValueData(2); + newRsaKeyParams.setByteData(null); + toReturn.setSubParams(newRsaKeyParams); + return toReturn; + } + /** + * Create a default TpmKeyParams for the sym portion of the request. This will include the IV, as per the specification, but this IV will most likely be moved to a TrouSerS-like location when the request is encrypted. + * + * @param iv 128-bit (16 byte) initialization vector + * @return + */ + private static TpmKeyParams createDefaultSymAlgorithm(byte [] iv) { + TpmKeyParams toReturn = new TpmKeyParams(); + toReturn.setAlgorithmId(TpmKeyParams.TPM_ALG_AES);//6 + toReturn.setEncScheme((short)TpmKeyParams.TPM_ES_SYM_CBC_PKCS5PAD);//255=FF + toReturn.setSigScheme((short)TpmKeyParams.TPM_SS_NONE);//1 + TpmSymmetricKeyParams newSymmetricKeyParams = new TpmSymmetricKeyParams(); + newSymmetricKeyParams.setKeyLength(128); + newSymmetricKeyParams.setValueData(128); + newSymmetricKeyParams.setByteData(iv); + toReturn.setSubParams(newSymmetricKeyParams); + return toReturn; + } + /** + * Encrypt the TpmIdentityProof using a specified key and IV; return the TpmSymmetricKey object. The encrypted portion will be stored in this object's symblob variable. + * + * @param proof This is the TpmIdentityProof as a byte array (or anything else to encrypt as if it is an identity proof -- useful for sending encrypted data to a Privacy CA outside of the specification). + * @param key 128-bit (16 byte) AES key + * @param iv 128-bit (16 byte) initialization vector + * @return TpmSymmetricKey containing the used key + * @throws NoSuchPaddingException + * @throws NoSuchAlgorithmException + * @throws InvalidAlgorithmParameterException + * @throws InvalidKeyException + * @throws BadPaddingException + * @throws IllegalBlockSizeException + */ + private TpmSymmetricKey encryptSym(byte [] proof, byte [] key, byte [] iv) + throws NoSuchPaddingException, + NoSuchAlgorithmException, + InvalidAlgorithmParameterException, + InvalidKeyException, + BadPaddingException, + IllegalBlockSizeException{ + //encrypt + Cipher symCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + IvParameterSpec ivSpec = new IvParameterSpec(iv); + SecretKeySpec symKey = new SecretKeySpec(key, "AES"); + symCipher.init(Cipher.ENCRYPT_MODE, symKey, ivSpec); + symBlob = symCipher.doFinal(proof); + //set the TpmSymmetricKey for return + TpmSymmetricKey encryptKey = new TpmSymmetricKey(); + encryptKey.setAlgorithmId(TpmKeyParams.TPM_ALG_AES); + encryptKey.setEncScheme(TpmKeyParams.TPM_ES_SYM_CBC_PKCS5PAD); + encryptKey.setSecretKey(symKey); + if (TrousersModeSymkeyEncscheme) { + encryptKey.setEncScheme(TpmKeyParams.TPM_ES_NONE); + } + return encryptKey; + } + /** + * Encrypt a TpmSymmetricKey, as returned from the private encryptSym() function, and store in the asymblob variable for this object. + * + * @param symKey The TpmSymmetricKey as returned from encryptSym() + * @param caKey The Privacy CA's public key + * @throws NoSuchPaddingException + * @throws NoSuchAlgorithmException + * @throws InvalidAlgorithmParameterException + * @throws InvalidKeyException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws BadPaddingException + * @throws IllegalBlockSizeException + */ + private void encryptAsym(TpmSymmetricKey symKey, RSAPublicKey caKey) + throws NoSuchPaddingException, + NoSuchAlgorithmException, + InvalidAlgorithmParameterException, + InvalidKeyException, + TpmUtils.TpmUnsignedConversionException, + BadPaddingException, + IllegalBlockSizeException { + OAEPParameterSpec oaepSpec; + if (TrousersModeBlankOeap) + oaepSpec = new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified("".getBytes())); + else + oaepSpec = new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified("TCPA".getBytes())); + Cipher asymCipher = Cipher.getInstance("RSA/ECB/OAEPWithSha1AndMGF1Padding"); + asymCipher.init(Cipher.PUBLIC_KEY, caKey, oaepSpec); + asymCipher.update(symKey.toByteArray()); + asymBlob = asymCipher.doFinal(); + } + /** + * Dump the Identity Request as a byte array in the form that it can be sent to a Privacy CA (or as it came from the client, assembled by a TSS) + * + * @return Byte array containing the Identity Request + * @throws TpmUtils.TpmUnsignedConversionException + */ + public byte [] toByteArray() + throws TpmUtils.TpmUnsignedConversionException { + byte [] asymSize = TpmUtils.intToByteArray(asymBlob.length); + byte [] symSize = TpmUtils.intToByteArray(symBlob.length); + byte [] asymAlgorithmBytes = asymAlgorithm.toByteArray(); + byte [] symAlgorithmBytes = symAlgorithm.toByteArray(); + byte [] toReturn = new byte[asymSize.length + symSize.length + asymAlgorithmBytes.length + symAlgorithmBytes.length + asymBlob.length + symBlob.length]; + System.arraycopy(asymSize, 0, toReturn, 0, asymSize.length); + System.arraycopy(symSize, 0, toReturn, asymSize.length, symSize.length); + System.arraycopy(asymAlgorithmBytes, 0, toReturn, asymSize.length + symSize.length, asymAlgorithmBytes.length); + System.arraycopy(symAlgorithmBytes, 0, toReturn, asymSize.length + symSize.length + asymAlgorithmBytes.length, symAlgorithmBytes.length); + System.arraycopy(asymBlob, 0, toReturn, asymSize.length + symSize.length + asymAlgorithmBytes.length + symAlgorithmBytes.length, asymBlob.length); + System.arraycopy(symBlob, 0, toReturn, asymSize.length + symSize.length + asymAlgorithmBytes.length + symAlgorithmBytes.length + asymBlob.length, symBlob.length); + return toReturn; + } + /** + * + * @return The asym key_parms. + */ + public TpmKeyParams getAsymKeyParams() { + return asymAlgorithm; + } + /** + * + * @return The sym algorithm key_parms. + */ + public TpmKeyParams getSymKeyParams() { + return symAlgorithm; + } + /** + * + * @return A textual report of the contents of the identity request. + */ + public String toString() { + String returnVal = ""; + returnVal += "TpmIdentityRequest:\n"; + returnVal += " asymAlgorithm:"; + if (TrousersModeBlankOeap) + returnVal += " (blank OAEP parameter)"; + returnVal += "\n" + asymAlgorithm.toString() + "\n"; + returnVal += " symAlgorithm:"; + if (TrousersModeSymkeyEncscheme) + returnVal += " (bad symmetric enc-scheme)"; + returnVal += "\n" + symAlgorithm.toString() + "\n"; + returnVal += " asymBlob:\n" + TpmUtils.byteArrayToString(asymBlob, 16) + "\n"; + returnVal += " symBlob:\n" + TpmUtils.byteArrayToString(symBlob, 16); + return returnVal; + } + /** + * Decrypt the asymmetric portion of the request to get the key needed to decrypt the symmetric portion. + * + * @param privCaKey The Privacy CA's private key. + * @return + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws BadPaddingException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws NoSuchAlgorithmException + * @throws IllegalBlockSizeException + * @throws InvalidAlgorithmParameterException + * @throws TpmUtils.TpmBytestreamResouceException + */ + private TpmSymmetricKey decryptAsym(RSAPrivateKey privCaKey) + throws NoSuchPaddingException, + InvalidKeyException, + BadPaddingException, + TpmUtils.TpmUnsignedConversionException, + NoSuchAlgorithmException, + IllegalBlockSizeException, + InvalidAlgorithmParameterException, + TpmUtils.TpmBytestreamResouceException, + PrivacyCaException { + TpmSymmetricKey symKey = new TpmSymmetricKey(); + switch (asymAlgorithm.getEncScheme()) { + case 0x3: // <-- most likely with NTRU, TrouSerS + Cipher asymCipher = Cipher.getInstance("RSA/ECB/OAEPWithSha1AndMGF1Padding"); + OAEPParameterSpec oaepSpec = new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified("TCPA".getBytes())); + asymCipher.init(Cipher.PRIVATE_KEY, privCaKey, oaepSpec); + asymCipher.update(asymBlob); + byte[] temparray = null; + try { + temparray = asymCipher.doFinal(); + } catch (BadPaddingException e) { //<- TrouSerS does not use an OAEP parameter string of "TCPA", per 1.1b spec. This results in a BadPaddingException -- try again without! + oaepSpec = new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified("".getBytes())); + asymCipher.init(Cipher.PRIVATE_KEY, privCaKey, oaepSpec); + asymCipher.update(asymBlob); + temparray = asymCipher.doFinal(); + TrousersModeBlankOeap = true; + } + if (temparray == null) + throw new PrivacyCaException("Unable to decrypt asym blob from incoming request."); + symKey = new TpmSymmetricKey(temparray); + break; + default: + asymCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); + asymCipher.init(Cipher.DECRYPT_MODE, privCaKey); + symKey = new TpmSymmetricKey(asymCipher.doFinal(asymBlob)); + break; + } + if ((symKey.getAlgorithmId() == TpmKeyParams.TPM_ALG_AES) && (symKey.getEncScheme() == TpmKeyParams.TPM_ES_NONE)) { + TrousersModeSymkeyEncscheme = true; + symKey.setEncScheme(TpmKeyParams.TPM_ES_SYM_CBC_PKCS5PAD); + } + return symKey; + } + /** + * Decrypt the symmetric portion of the request to get the identity proof. + * + * @param symKey The output of decryptAsym. + * @return + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidAlgorithmParameterException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws InvalidKeyException + * @throws BadPaddingException + * @throws IllegalBlockSizeException + * @throws PrivacyCaException + * @throws TpmUtils.TpmBytestreamResouceException + */ + private TpmIdentityProof decryptSym(TpmSymmetricKey symKey) + throws NoSuchAlgorithmException, + NoSuchPaddingException, + InvalidAlgorithmParameterException, + TpmUtils.TpmUnsignedConversionException, + InvalidKeyException, + BadPaddingException, + IllegalBlockSizeException, + PrivacyCaException, + TpmUtils.TpmBytestreamResouceException { + String instance = symKey.getAlgorithmStr() + "/" + symKey.getEncSchemeStr(); + //System.out.println("Instance: " + instance); + Cipher symCipher = Cipher.getInstance(instance); + IvParameterSpec ivSpec = new IvParameterSpec(symAlgorithm.getSubParams().getByteData()); + symCipher.init(Cipher.DECRYPT_MODE, symKey.getSecretKey(), ivSpec); + TpmIdentityProof identProof = new TpmIdentityProof(symCipher.doFinal(symBlob), TrousersModeIV, TrousersModeSymkeyEncscheme, TrousersModeBlankOeap); + return identProof; + } + /** + * If the byte blob captured as an Identity Request was not an encrypted Identity Proof (which could be done to transfer data from client to Privacy CA outside of the specification), then this method of decrypting the symblob may be preferable. + * + * @param symKey The TpmSymmetricKey as returned from decryptAsym() + * @return Decrypted byte blob + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidAlgorithmParameterException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws InvalidKeyException + * @throws BadPaddingException + * @throws IllegalBlockSizeException + * @throws PrivacyCaException + * @throws TpmUtils.TpmBytestreamResouceException + */ + private byte[] decryptSymRaw(TpmSymmetricKey symKey) + throws NoSuchAlgorithmException, + NoSuchPaddingException, + InvalidAlgorithmParameterException, + TpmUtils.TpmUnsignedConversionException, + InvalidKeyException, + BadPaddingException, + IllegalBlockSizeException, + PrivacyCaException, + TpmUtils.TpmBytestreamResouceException { + String instance = symKey.getAlgorithmStr() + "/" + symKey.getEncSchemeStr(); + //System.out.println("Instance: " + instance); + Cipher symCipher = Cipher.getInstance(instance); + IvParameterSpec ivSpec = new IvParameterSpec(symAlgorithm.getSubParams().getByteData()); + symCipher.init(Cipher.DECRYPT_MODE, symKey.getSecretKey(), ivSpec); + return symCipher.doFinal(symBlob); + } + /** + * Decrypt the identity request to get the identity proof. + * + * @param privCaKey The Privacy CA's private key. + * @return An identity proof. + * @throws InvalidKeyException + * @throws IllegalBlockSizeException + * @throws InvalidAlgorithmParameterException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws NoSuchAlgorithmException + * @throws BadPaddingException + * @throws NoSuchPaddingException + * @throws PrivacyCaException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public TpmIdentityProof decrypt(RSAPrivateKey privCaKey) + throws InvalidKeyException, + IllegalBlockSizeException, + InvalidAlgorithmParameterException, + TpmUtils.TpmUnsignedConversionException, + NoSuchAlgorithmException, + BadPaddingException, + NoSuchPaddingException, + PrivacyCaException, + TpmUtils.TpmBytestreamResouceException { + TpmSymmetricKey tempKey = decryptAsym(privCaKey); + return decryptSym(tempKey); + } + /** + * Decrypts the Identity Request, and DOES NOT assume the contents are an Identity Proof. + * + * @param privCaKey Privacy CA's private key + * @return Raw byte blob + * @throws InvalidKeyException + * @throws IllegalBlockSizeException + * @throws InvalidAlgorithmParameterException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws NoSuchAlgorithmException + * @throws BadPaddingException + * @throws NoSuchPaddingException + * @throws PrivacyCaException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public byte[] decryptRaw(RSAPrivateKey privCaKey) + throws InvalidKeyException, + IllegalBlockSizeException, + InvalidAlgorithmParameterException, + TpmUtils.TpmUnsignedConversionException, + NoSuchAlgorithmException, + BadPaddingException, + NoSuchPaddingException, + PrivacyCaException, + TpmUtils.TpmBytestreamResouceException { + TpmSymmetricKey tempKey = decryptAsym(privCaKey); + return decryptSymRaw(tempKey); + } + /** + * This must be run to properly identity the location of the symmetric encryption Initialization Vector. If TrouSerS-style + * formatting is used on the request, the IV is not in the symmetric key parameters, but rather at the head of the + * symmetrically encrypted blob. In order to decrypt consistently, regardless of the format use, this procedure will adjust + * from TrouSerS-style to 1.2 spec compliant style. A flag is set when parsing (in the constructor) so that the particular + * style is recorded. This will be used when constructing a response. + * + * @throws PrivacyCaException + */ + private void findIv() + throws PrivacyCaException { //must be called at this level to have access to symBlob + //Because TrouSerS-style might be in effect, we may have to find the IV and adjust the symBlob + //Also, based on this populate other values (keyLength, blockSize) + if (symAlgorithm.getSubParams().getValueData() == 0) { + TrousersModeIV = true; + //This indicates TrouSerS mode is active. + //Set the key length and block size to the value for the symmetric algorithm + switch (symAlgorithm.getAlgorithmId()) { + case 0x2: //TPM_ALG_DES + symAlgorithm.getSubParams().setKeyLength(56); + symAlgorithm.getSubParams().setValueData(64); //set block size, assume in bits (not specified in TCG documentation) + break; + case 0x3: //TPM_ALG_3DES + symAlgorithm.getSubParams().setKeyLength(192); + symAlgorithm.getSubParams().setValueData(64); //set block size, assume in bits (not specified in TCG documentation) + break; + case 0x6: //TPM_ALG_AES/AES128* most likely to occur + symAlgorithm.getSubParams().setKeyLength(128); + symAlgorithm.getSubParams().setValueData(128); //set block size, assume in bits (not specified in TCG documentation) + break; + case 0x8: //TPM_ALG_AES192 + symAlgorithm.getSubParams().setKeyLength(192); + symAlgorithm.getSubParams().setValueData(128); //set block size, assume in bits (not specified in TCG documentation) + break; + case 0x9: //TPM_ALG_AES256 + symAlgorithm.getSubParams().setKeyLength(256); + symAlgorithm.getSubParams().setValueData(128); //set block size, assume in bits (not specified in TCG documentation) + break; + default: + throw new PrivacyCaException("Unexpected symmetric algorithm ID: " + Integer.toHexString(symAlgorithm.getAlgorithmId())); + } + //snag the first (blocksize) bits from the symBlob + byte [] newIv = new byte[symAlgorithm.getSubParams().getValueData() / 8]; + System.arraycopy(symBlob, 0, newIv, 0, newIv.length); + symAlgorithm.getSubParams().setByteData(newIv); + byte [] newSymBlob = new byte[symBlob.length - newIv.length]; + System.arraycopy(symBlob, newIv.length, newSymBlob, 0, newSymBlob.length); + symBlob = newSymBlob; + } + } +} diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmKeyParams.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmKeyParams.java new file mode 100644 index 0000000..b1c62c5 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmKeyParams.java @@ -0,0 +1,332 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.io.*; + +/** + *

This class is for the TCG's TPM_KEY_PARMS structure. Several other TCG values are defined here, as it seems appropriate to do so at the time.

+ * @author schawki + * + */ +public class TpmKeyParams { + public static final int TPM_ALG_RSA = 0x1; + public static final int TPM_ALG_DES = 0x2; + public static final int TPM_ALG_3DES = 0x3; + public static final int TPM_ALG_SHA = 0x4; + public static final int TPM_ALG_HMAC = 0x5; + public static final int TPM_ALG_AES = 0x6; + public static final int TPM_ALG_AES128 = TPM_ALG_AES; + public static final int TPM_ALG_MGF1 = 0x7; + public static final int TPM_ALG_AES192 = 0x8; + public static final int TPM_ALG_AES256 = 0x9; + public static final int TPM_ALG_XOR = 0xa; + public static final short TPM_ES_NONE = 0x1; + public static final short TPM_ES_RSAESPKCSv15 = 0x2; + public static final short TPM_ES_RSAESOAEP_SHA1_MGF1 = 0x3; + public static final short TPM_ES_SYM_CNT = 0x4; + public static final short TPM_ES_SYM_OFB = 0x5; + public static final short TPM_ES_SYM_CBC_PKCS5PAD = 0xff; + public static final short TPM_SS_NONE = 0x1; + public static final short TPM_SS_RSASAPKCS1v15_SHA1 = 2; + public static final short TPM_SS_RSASAPKCS1v15_DER = 3; + public static final short TPM_SS_RSASAPKCS1v15_INFO = 4; + + private int algorithmId; + private short encScheme; + private short sigScheme; + private TpmKeySubParams subParams = null; + private boolean TrouSerSmode = false; + + /** + * Given an algorithm, return the text string. Useful for debugging and logging. + * @param alg + * @return + */ + public static String algToString(int alg) { + String returnVal = ""; + switch (alg) { + case TPM_ALG_RSA: + returnVal = "TPM_ALG_RSA"; + break; + case TPM_ALG_DES: + returnVal = "TPM_ALG_DES"; + break; + case TPM_ALG_3DES: + returnVal = "TPM_ALG_3DES"; + break; + case TPM_ALG_SHA: + returnVal = "TPM_ALG_SHA"; + break; + case TPM_ALG_HMAC: + returnVal = "TPM_ALG_HMAC"; + break; + case TPM_ALG_AES: + returnVal = "TPM_ALG_AES/TPM_ALG_AES128"; + break; + case TPM_ALG_MGF1: + returnVal = "TPM_ALG_MGF1"; + break; + case TPM_ALG_AES192: + returnVal = "TPM_ALG_AES192"; + break; + case TPM_ALG_AES256: + returnVal = "TPM_ALG_AES256"; + break; + case TPM_ALG_XOR: + returnVal = "TPM_ALG_XOR"; + break; + default: + returnVal = "UNKNOWN ALG VALUE! (" + Integer.toString(alg) + ")"; + break; + } + return returnVal; + } + /** + * Given an encryption scheme, return the string. Useful for debugging and logging. + * @param es + * @param TrouSerSmode + * @return + */ + public static String esToString(short es, boolean TrouSerSmode) { + String returnVal = ""; + switch (es) { + case TPM_ES_NONE: + returnVal = "TPM_ES_NONE"; + if (TrouSerSmode) + returnVal += " (should be TPM_ES_SYM_CBC_PKCS5PAD)"; + break; + case TPM_ES_RSAESPKCSv15: + returnVal = "TPM_ES_RSAESPKCSv15"; + break; + case TPM_ES_RSAESOAEP_SHA1_MGF1: + returnVal = "TPM_ES_RSAESOAEP_SHA1_MGF1"; + break; + case TPM_ES_SYM_CNT: + returnVal = "TPM_ES_SYM_CNT"; + break; + case TPM_ES_SYM_OFB: + returnVal = "TPM_ES_SYM_OFB"; + break; + case TPM_ES_SYM_CBC_PKCS5PAD: + returnVal = "TPM_ES_SYM_CBC_PKCS5PAD"; + break; + default: + returnVal = "UNKNOWN ENCSCHEME VALUE! (" + Short.toString(es) + ")"; + break; + } + return returnVal; + } + /** + * Given a signature scheme, return the string. Useful for debugging and logging. + * @param ss + * @return + */ + public static String ssToString(short ss) { + String returnVal = ""; + switch (ss) { + case TPM_SS_NONE: + returnVal = "TPM_SS_NONE"; + break; + case TPM_SS_RSASAPKCS1v15_SHA1: + returnVal = "TPM_SS_RSASAPKCS1v15_SHA1"; + break; + case TPM_SS_RSASAPKCS1v15_DER: + returnVal = "TPM_SS_RSASAPKCS1v15_DER"; + break; + case TPM_SS_RSASAPKCS1v15_INFO: + returnVal = "TPM_SS_RSASAPKCS1v15_INFO"; + break; + default: + returnVal = "UNKNOWN SIGSCHEME VALUE! (" + Short.toString(ss) + ")"; + break; + } + return returnVal; + } + /** + * Create a new TpmKeyParms with no default values set. + */ + public TpmKeyParams(){} + /** + * Create a new TpmKeyParams by extracting values from a ByteArrayInputStream. + * + * @param source The InputStream. + * @throws TpmUtils.TpmUnsignedConversionException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public TpmKeyParams(ByteArrayInputStream source) + throws TpmUtils.TpmUnsignedConversionException, + TpmUtils.TpmBytestreamResouceException { + algorithmId = TpmUtils.getUINT32(source); + encScheme = TpmUtils.getUINT16(source); + sigScheme = TpmUtils.getUINT16(source); + int subParamSize = TpmUtils.getUINT32(source); + if ((algorithmId != TPM_ALG_RSA) && (subParamSize == 0)) { + TrouSerSmode = true; + } + switch (algorithmId) { + case TPM_ALG_RSA: + subParams = new TpmRsaKeyParams(source, subParamSize); + break; + case TPM_ALG_DES: + case TPM_ALG_3DES: + case TPM_ALG_AES: //same as TPM_ALG_AES128; most likely to occur + case TPM_ALG_AES192: + case TPM_ALG_AES256: + subParams = new TpmSymmetricKeyParams(source, subParamSize); + break; + default: //?could be an issue if something other than RSA or a DES/AES variant? + if (subParamSize > 0) + TpmUtils.getBytes(source, subParamSize); //just throw it away -- what else to do with it?? + break; + } + } + /** + * Manually set TrouSerS mode. True means that the symmetric IV will appear at the beginning of a symmetrically + * encrypted blob, while false means that it will appear within a SymmetricKeyParams structure. This value is + * used when determining the format of the byte arrays that are passed back from the Privacy CA. By default the Privacy + * CA will set this value based on the format of the incoming identity request. + * + * @param state + */ + public void setTrouSerSmode(boolean state) { + TrouSerSmode = state; + } + /** + * + * @return The current state of TrouSerS mode for this key params structure. + */ + public boolean getTrouSerSmode() { + return TrouSerSmode; + } + /** + * Assemble the KeyParams structure into a byte array. + * + * @return The byte array. + * @throws TpmUtils.TpmUnsignedConversionException + */ + public byte [] toByteArray() + throws TpmUtils.TpmUnsignedConversionException { + byte [] algoId = TpmUtils.intToByteArray(algorithmId); + byte [] encSchm = TpmUtils.shortToByteArray(encScheme); + byte [] sigSchm = TpmUtils.shortToByteArray(sigScheme); + byte [] size; + byte [] subParms; + int x; + if (TrouSerSmode && (algorithmId != 1)) { + size = TpmUtils.intToByteArray(0); + subParms = null; + x = algoId.length + encSchm.length + sigSchm.length + size.length; + } + else { + if (subParams != null) { + subParms = subParams.toByteArray(); + size = TpmUtils.intToByteArray(subParms.length); + x = algoId.length + encSchm.length + sigSchm.length + size.length + subParms.length; + } + else { + subParms = null; + size = TpmUtils.intToByteArray(0); + x = algoId.length + encSchm.length + sigSchm.length + size.length; + } + } + byte [] returnArray = new byte[x]; + System.arraycopy(algoId, 0, returnArray, 0, algoId.length); + System.arraycopy(encSchm, 0, returnArray, algoId.length, encSchm.length); + System.arraycopy(sigSchm, 0, returnArray, algoId.length + encSchm.length, sigSchm.length); + System.arraycopy(size, 0, returnArray, algoId.length + encSchm.length + sigSchm.length, size.length); + if (subParms != null) System.arraycopy(subParms, 0, returnArray, algoId.length + encSchm.length + sigSchm.length + size.length, subParms.length); + return returnArray; + } + /** + * + * @return A String representing a human-readable report of the Key Params. + */ + public String toString() { + String returnVal = ""; + returnVal += "TpmKeyParams:\n"; + //returnVal += " algorithmId: " + Integer.toString(algorithmId) + "\n"; + //returnVal += " encScheme: " + Short.toString(encScheme) + "\n"; + //returnVal += " sigScheme: " + Short.toString(sigScheme) + "\n"; + returnVal += " algorithmId: " + TpmKeyParams.algToString(algorithmId) + "\n"; + returnVal += " encScheme: " + TpmKeyParams.esToString(encScheme, TrouSerSmode) + "\n"; + returnVal += " sigScheme: " + TpmKeyParams.ssToString(sigScheme) + "\n"; + returnVal += " subParameters:";//\n"; + if (TrouSerSmode) { + returnVal += " (fabricated: TrouSerS-style IV placement)"; + } + returnVal += "\n" + subParams.toString(); + return returnVal; + } + /** + * + * @return The current algorithm ID value. + */ + public int getAlgorithmId() { + return algorithmId; + } + /** + * Set a new algorithm ID value; + * + * @param newAlgId The new value. + */ + public void setAlgorithmId(int newAlgId) { + algorithmId = newAlgId; + } + /** + * + * @return The current encryption scheme value. + */ + public short getEncScheme() { + return encScheme; + } + /** + * Set a new encryption scheme value; + * + * @param newEncScheme The new value. + */ + public void setEncScheme(short newEncScheme) { + encScheme = newEncScheme; + } + /** + * + * @return The current signature scheme. + */ + public short getSigScheme() { + return sigScheme; + } + /** + * Set a new signature scheme value. + * + * @param newSigScheme The new value. + */ + public void setSigScheme(short newSigScheme) { + sigScheme = newSigScheme; + } + /** + * + * @return The currently assigned TpmKeySubParams. Will be null, or a TpmRsaKeyParams or TpmSymmetricKeyParams structure. + */ + public TpmKeySubParams getSubParams() { + return subParams; + } + /** + * Set a new TpmKeySubParams structure. + * + * @param newSubParams The new TpmRsaKeyParams or TpmSymmetricKeyParams structure. + */ + public void setSubParams(TpmKeySubParams newSubParams) { + subParams = newSubParams; + } +} diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmKeySubParams.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmKeySubParams.java new file mode 100644 index 0000000..e67926f --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmKeySubParams.java @@ -0,0 +1,30 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +/** + *

Interface for the sub-parameters, as used in a TPM_KEY_PARMS structure. This interface is implemented by TpmRsaKeyParams and TpmSymmetricKeyParams.

+ * @author schawki + * + */ +public interface TpmKeySubParams { + public int getKeyLength(); + public void setKeyLength(int newValue); + public int getValueData(); //The value data is different for RsaKeyParams (number of primes) and SymmetricKeyParams (block size) + public void setValueData(int newValue); + public byte [] getByteData(); //The byte data is different for RsaKeyParams (public exponent) and SymmetricKeyParams (IV) + public void setByteData(byte [] newValue); + public byte [] toByteArray() throws TpmUtils.TpmUnsignedConversionException; + public String toString(); +} diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmPubKey.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmPubKey.java new file mode 100644 index 0000000..505cfcb --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmPubKey.java @@ -0,0 +1,137 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.io.*; +import java.security.*; +import java.security.spec.*; +import java.security.interfaces.*; +import java.math.*; + +/** + *

This class is for the TCG's TPM_PUBKEY structure.

+ * @author schawki + * + */ +public class TpmPubKey { + private TpmKeyParams algorithm; + private byte [] key; //just the modulus!! + + public TpmPubKey() {} + /** + * Create new TPM_PUBKEY by specifying the public key, encryption scheme and signature scheme. + * + * @param pubKey The RSA public key structure, containing the modulus and public exponent. + * @param encScheme The defined encryption scheme value. + * @param sigscheme The defined signature scheme value. + */ + public TpmPubKey(RSAPublicKey pubKey, int encScheme, int sigscheme) { + BigInteger keyBI = pubKey.getModulus(); + key = keyBI.toByteArray(); + if ((key.length == 257)&&(key[0]==0x00)) { + byte [] newKey = new byte[256]; + for (int i = 0; i < 256; i++) + newKey[i] = key[i+1]; + key = newKey; + } + algorithm = new TpmKeyParams(); + algorithm.setAlgorithmId(1); + algorithm.setEncScheme((short)encScheme); + algorithm.setSigScheme((short)sigscheme); + algorithm.setSubParams(new TpmRsaKeyParams()); + algorithm.getSubParams().setByteData(pubKey.getPublicExponent().toByteArray()); + algorithm.getSubParams().setValueData(2); //numPrimes + algorithm.getSubParams().setKeyLength(2048); + } + /** + * Create a TPM_PUBKEY using the specified modulus. An default encryption scheme of 1 (TPM_ES_NONE) and signature scheme + * of 2 (TPM_SS_RSASSAPKCS1v15_SHA1) will be used. + * + * @param newKey The new modulus in the form of a byte array. + */ + public TpmPubKey(byte [] newKey) { + key = newKey; + algorithm = new TpmKeyParams(); + algorithm.setAlgorithmId(1); + algorithm.setEncScheme((short)1); + algorithm.setSigScheme((short)2); + algorithm.setSubParams(new TpmRsaKeyParams()); + byte [] pubExp = {0x01, 0x00, 0x01}; + algorithm.getSubParams().setByteData(pubExp); + algorithm.getSubParams().setValueData(2); //numPrimes + algorithm.getSubParams().setKeyLength(2048); + } + /** + * Create a new TPM_PUBKEY by extracting it from a byte stream. + * + * @param source The ByteArrayInputStream from which to extract the TPM_PUBKEY. + * @throws TpmUtils.TpmUnsignedConversionException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public TpmPubKey(ByteArrayInputStream source) throws TpmUtils.TpmUnsignedConversionException, TpmUtils.TpmBytestreamResouceException { + algorithm = new TpmKeyParams(source); + int storeKeyLength = TpmUtils.getUINT32(source); + key = TpmUtils.getBytes(source, storeKeyLength); + } + /** + * Get the RSA key modulus. + * + * @return The modulus as a byte array. + */ + public byte [] getKeybytes() { + return key; + } + /** + * Return an RSAPublicKey structure representing the key stored in this TPM_PUBKEY. + * + * @return The RSAPublicKey. + * @throws NoSuchAlgorithmException + * @throws InvalidKeySpecException + */ + public RSAPublicKey getKey() throws NoSuchAlgorithmException, InvalidKeySpecException { + byte [] pubExp = new byte[3]; + pubExp[0] = (byte)(0x01 & 0xff); +// pubExp[1] = (byte)(0x00 & 0xff); + pubExp[1] = (byte)(0x00); + pubExp[2] = (byte)(0x01 & 0xff); + return TpmUtils.makePubKey(key, pubExp); + } + /** + * Return a human-readable report of the TPM_PUBKEY. + * + * @return The key report. + */ + public String toString() { + String returnVal = ""; + returnVal += "TpmPubKey:\n"; + returnVal += " " + algorithm.toString() + "\n"; + returnVal += " key:\n" + TpmUtils.byteArrayToString(key, 16); + return returnVal; + } + /** + * + * @return The serialized TPM_PUBKEY. + * @throws TpmUtils.TpmUnsignedConversionException + */ + public byte [] toByteArray() throws TpmUtils.TpmUnsignedConversionException { + byte[] algo = algorithm.toByteArray(); + byte[] keySize = TpmUtils.intToByteArray(key.length); + int x = algo.length + keySize.length + key.length; + byte [] returnArray = new byte[x]; + System.arraycopy(algo, 0, returnArray, 0, algo.length); + System.arraycopy(keySize, 0, returnArray, algo.length, keySize.length); + System.arraycopy(key, 0, returnArray, algo.length + keySize.length, key.length); + return returnArray; + } +} diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmRsaKeyParams.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmRsaKeyParams.java new file mode 100644 index 0000000..954d451 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmRsaKeyParams.java @@ -0,0 +1,139 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.io.ByteArrayInputStream; + +/** + *

This class is for the TCG's TPM_RSA_KEY_PARMS structure. It extends the TpmKeySubParams interface.

+ * @author schawki + * + */ +public class TpmRsaKeyParams implements TpmKeySubParams{ + public int keyLength; + public int numPrimes; //number of primes + public byte[] exponent; //exponent + + public TpmRsaKeyParams() {} + /** + * Create a new RSAKeyParams by extracting it from a byte stream. + * + * @param source The byte stream from which to extract. + * @param length The length of the RSA key params (just used to see if over 0). + * @throws TpmUtils.TpmUnsignedConversionException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public TpmRsaKeyParams(ByteArrayInputStream source, int length) throws TpmUtils.TpmUnsignedConversionException, TpmUtils.TpmBytestreamResouceException { + if (length > 0) { + keyLength = TpmUtils.getUINT32(source); + numPrimes = TpmUtils.getUINT32(source); + int temp = TpmUtils.getUINT32(source); + exponent = TpmUtils.getBytes(source, temp); + } + } + /** + * Serialize the structure. + * + * @return The serialized RSA key params structure. + * @throws TpmUtils.TpmUnsignedConversionException + */ + public byte[] toByteArray() + throws TpmUtils.TpmUnsignedConversionException { + byte [] keyLngth = TpmUtils.intToByteArray(keyLength); + byte [] numPrms = TpmUtils.intToByteArray(numPrimes); + byte [] size; + byte [] exponentOut; + if (defaultExponent()) { + size = TpmUtils.intToByteArray(0); + exponentOut = null; + } else { + size = TpmUtils.intToByteArray(exponent.length); + exponentOut = exponent; + } + int x = keyLngth.length + numPrms.length + size.length; + if (exponentOut != null) x += exponentOut.length; + byte [] returnArray = new byte[x]; + System.arraycopy(keyLngth, 0, returnArray, 0, keyLngth.length); + System.arraycopy(numPrms, 0, returnArray, keyLngth.length, numPrms.length); + System.arraycopy(size, 0, returnArray, keyLngth.length + numPrms.length, size.length); + if (exponentOut != null) System.arraycopy(exponentOut, 0, returnArray, keyLngth.length + numPrms.length + size.length, exponentOut.length); + return returnArray; + } + /** + * Determine if the TCG-defined "default" public exponent is used for this key. + * + * @return True if the exponent defined is 2^16 + 1 (65537 or 0x01 0x00 0x01). + */ + private boolean defaultExponent() { + if (exponent == null) return true; + byte [] defaultExp = {0x01, 0x00, 0x01}; + for (int i = 0; i < exponent.length; i++) + if (exponent[i] != defaultExp[i]) + return false; + return true; + } + /** + * @return The length of the RSA key. + */ + public int getKeyLength() { + return keyLength; + } + /** + * Set the RSA key length. + * + * @param newValue The new key length, in bits. + */ + public void setKeyLength(int newValue) { + keyLength = newValue; + } + /** + * @return The number of primes. + */ + public int getValueData() { + return numPrimes; + } + /** + * Set the number of primes for this RSA key params structure. + * + * @param newValue The new number of primes. + */ + public void setValueData(int newValue) { + numPrimes = newValue; + } + /** + * @return The exponent for this RSA key. + */ + public byte [] getByteData() { + return exponent; + } + /** + * @param newValue Set the RSA exponent to this byte array. + */ + public void setByteData(byte [] newValue) { + exponent = newValue; + } + /** + * Creates a human-readable report of the RSA key parameters structure. + * + * @return The report. + */ + public String toString() { + String returnVal = ""; + returnVal += "TpmRsaKeyParams:\n"; + returnVal += " keyLength: " + Integer.toString(keyLength) + "\n"; + returnVal += " numPrimes: " + Integer.toString(numPrimes) + "\n"; + returnVal += " exponent: " + TpmUtils.byteArrayToString(exponent, 16); + return returnVal; + } +} diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmSymCaAttestation.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmSymCaAttestation.java new file mode 100644 index 0000000..063be12 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmSymCaAttestation.java @@ -0,0 +1,152 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.io.ByteArrayInputStream; +import java.security.cert.*; +//import java.util.*; +import java.io.*; +import java.security.*; +import javax.crypto.*; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +/** + *

This class is for the TCG's TPM_SYM_CA_ATTESTATION structure.

+ * @author schawki + * + */ +public class TpmSymCaAttestation { + private TpmKeyParams algorithm; + private byte [] plainAikCred = null; + private byte [] encAikCred; + + public TpmSymCaAttestation(){} + /** + * Set the AIK certificate to be encrypted. + * + * @param cred The AIK certificate in byte array form. + */ + public void setAikCredential(byte [] cred) { + plainAikCred = cred; + } + /** + * Set the AIK certificate to be encrypted. + * + * @param cred The AIK certificate in X509Certificate form. + * @throws CertificateEncodingException + */ + public void setAikCredential(X509Certificate cred) throws CertificateEncodingException { + plainAikCred = cred.getEncoded(); + } + /** + * @return The stored AIK certificate in X509Certificate form. + * @throws CertificateException + */ + public X509Certificate getAikCredential() + throws CertificateException { + ByteArrayInputStream bs = new ByteArrayInputStream(plainAikCred); + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + return (X509Certificate)cf.generateCertificate(bs); + } + /** + * Encrypt the stored certificate using the specified options. A random key and IV are created. + * + * @param algMode Not used. This parameter is left here to maintain compatibility. This value is hard coded to TPM_ALG_AES. + * @param encScheme Not used. This parameter is left here to maintain compatibility. This value is hard coded to TPM_ES_CBC_PKCS5PAD. + * @param TrousersModeIV Set to TRUE to use a TrouSerS-style initialization vector placement. + * @param TrousersModeSymkeyEncscheme Set to TRUE to set the encryption scheme to TPM_ES_NONE. (Not all versions of TrouSerS use this scheme, but the only ones available in RedHat Yum repositories do.) + * @return The symmetric key used to encrypt the certificate in the form of a TpmSymmetricKey. The encrypted certificate itself is retrieved in raw byte format by running the toByteArray() function. + * @throws IOException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidAlgorithmParameterException + * @throws InvalidKeyException + * @throws IllegalBlockSizeException + * @throws BadPaddingException + * @throws PrivacyCaException + */ + public TpmSymmetricKey encrypt(int algMode, short encScheme, boolean TrousersModeIV, boolean TrousersModeSymkeyEncscheme) + throws IOException, + NoSuchAlgorithmException, + NoSuchPaddingException, + InvalidAlgorithmParameterException, + InvalidKeyException, + IllegalBlockSizeException, + BadPaddingException, + PrivacyCaException { + if (plainAikCred == null) { + throw new PrivacyCaException("TpmSymCaAttestation: Must store certificate prior to encrypting."); + } + algorithm = new TpmKeyParams(); + algorithm.setAlgorithmId(TpmKeyParams.TPM_ALG_AES); + algorithm.setEncScheme(TpmKeyParams.TPM_ES_SYM_CBC_PKCS5PAD); + algorithm.setSigScheme(TpmKeyParams.TPM_SS_NONE); + algorithm.setSubParams(new TpmSymmetricKeyParams()); + algorithm.getSubParams().setKeyLength(128); + algorithm.getSubParams().setValueData(16); + //create a random IV (16 byte) + byte [] newIv = TpmUtils.createRandomBytes(16); + algorithm.getSubParams().setByteData(newIv); //copy IV into params + algorithm.setTrouSerSmode(TrousersModeIV); //set trousers mode + //create a random key for AES (128 bit = 16 byte) + byte [] newKey = TpmUtils.createRandomBytes(16); + //System.out.println("The symmetric key is " + newKey.length + " bytes long"); + //encrypt + Cipher symCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + IvParameterSpec ivSpec = new IvParameterSpec(newIv); + SecretKeySpec symKey = new SecretKeySpec(newKey, "AES"); + symCipher.init(Cipher.ENCRYPT_MODE, symKey, ivSpec); + encAikCred = symCipher.doFinal(plainAikCred); + if (TrousersModeIV) { //copy iv to from of encrypted portion + byte [] temp = new byte[newIv.length + encAikCred.length]; + System.arraycopy(newIv, 0, temp, 0, newIv.length); + System.arraycopy(encAikCred, 0, temp, newIv.length, encAikCred.length); + encAikCred = temp; + } + else { + algorithm.setSubParams(new TpmSymmetricKeyParams()); + algorithm.getSubParams().setByteData(newIv); + algorithm.getSubParams().setValueData(16); + algorithm.getSubParams().setKeyLength(128); + } + //set the Symkey for return + TpmSymmetricKey encryptKey = new TpmSymmetricKey(); + encryptKey.setAlgorithmId(TpmKeyParams.TPM_ALG_AES); + encryptKey.setEncScheme(TpmKeyParams.TPM_ES_SYM_CBC_PKCS5PAD); + encryptKey.setSecretKey(symKey); + if (TrousersModeSymkeyEncscheme) + encryptKey.setEncScheme(TpmKeyParams.TPM_ES_NONE); + return encryptKey; + } + /** + * Serialize the structure. + * + * @return A byte array form of the TpmSymCaAttestation structure. + * @throws TpmUtils.TpmUnsignedConversionException + */ + public byte [] toByteArray() + throws TpmUtils.TpmUnsignedConversionException { + byte [] credSize = TpmUtils.intToByteArray(encAikCred.length); //credSize.length must be 4! + byte [] tempAlgo = algorithm.toByteArray(); + int x = credSize.length + tempAlgo.length + encAikCred.length; + byte [] returnArray = new byte[x]; + System.arraycopy(credSize, 0, returnArray, 0, credSize.length); + System.arraycopy(tempAlgo, 0, returnArray, credSize.length, tempAlgo.length); + System.arraycopy(encAikCred, 0, returnArray, credSize.length + tempAlgo.length, encAikCred.length); + return returnArray; + } +} diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmSymmetricKey.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmSymmetricKey.java new file mode 100644 index 0000000..7c23bf0 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmSymmetricKey.java @@ -0,0 +1,171 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import javax.crypto.spec.*; +import java.io.*; + +/** + *

This class is for the TCG's TPM_SYMMETRIC_KEY structure.

+ * @author schawki + * + */ +public class TpmSymmetricKey { + private byte[] keyBlob; + private int algorithmId; + private short encScheme; + + public TpmSymmetricKey() { + keyBlob = TpmUtils.hexStringToByteArray(""); + } + /** + * Instantiate a new TpmSymmetricKey from a byte array. + * + * @param blob The key bytes to use. + * @throws TpmUtils.TpmUnsignedConversionException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public TpmSymmetricKey(byte [] blob) + throws TpmUtils.TpmUnsignedConversionException, + TpmUtils.TpmBytestreamResouceException { + ByteArrayInputStream bs = new ByteArrayInputStream(blob); + algorithmId = TpmUtils.getUINT32(bs); + encScheme = TpmUtils.getUINT16(bs); + short temp = TpmUtils.getUINT16(bs); + keyBlob = TpmUtils.getBytes(bs, (int)temp); + } + /** + * + * @return The secret key in the form of a SecretKeySpec. + */ + public SecretKeySpec getSecretKey() { + String algorithm = this.getAlgorithmStr(); + SecretKeySpec symKey = new SecretKeySpec(keyBlob, algorithm); + return symKey; + } + /** + * Set the secret key with a SecretKeySpec. + * + * @param newKeySpec New secret key. + */ + public void setSecretKey(SecretKeySpec newKeySpec) { + keyBlob = newKeySpec.getEncoded(); + } + /** + * + * @return The algorithm ID defined for this symmetric key. + */ + public int getAlgorithmId() { + return algorithmId; + } + /** + * Set the algorithm ID for this symmetric key. + * + * @param newAlgId New algorithm ID. + */ + public void setAlgorithmId(int newAlgId) { + algorithmId = newAlgId; + } + /** + * + * @return Human-readable report of the TpmSymmetricKey. + */ + public String getAlgorithmStr(){ + String returnVal = ""; + switch (algorithmId){ + case TpmKeyParams.TPM_ALG_DES: + returnVal = "DES"; + break; + case TpmKeyParams.TPM_ALG_3DES: + returnVal = "DESede"; + break; + case TpmKeyParams.TPM_ALG_AES: + case TpmKeyParams.TPM_ALG_AES192: + case TpmKeyParams.TPM_ALG_AES256: + returnVal = "AES"; + break; + default: + returnVal = "Error"; + break; + } + return returnVal; + } + /** + * + * @return The set encryption scheme. + */ + public short getEncScheme() { + return encScheme; + } + /** + * Set the encryption scheme. + * + * @param newEncScheme New encryption scheme. + */ + public void setEncScheme(short newEncScheme) { + encScheme = newEncScheme; + } + /** + * + * @return The encryption scheme as a string. + */ + public String getEncSchemeStr(){ + String returnVal = ""; + switch (encScheme){ + case TpmKeyParams.TPM_ES_NONE: + returnVal = "NONE/NoPadding"; + break; + case TpmKeyParams.TPM_ES_SYM_CBC_PKCS5PAD: + returnVal = "CBC/PKCS5Padding"; + break; + default: + returnVal = "Error"; + break; + } + return returnVal; + } + /** + * + * @return Symmetric key blob, as a byte array. + */ + public byte [] getKeyBlob() { + return keyBlob; + } + /** + * Set a new key symmetric key by byte blob. + * + * @param newKeyBlob New key. + */ + public void setKeyBlob(byte [] newKeyBlob) { + keyBlob = newKeyBlob; + } + /** + * Serialize the TpmSymmetricKey structure. + * + * @return Byte array form of TpmSymmetricKey. + * @throws TpmUtils.TpmUnsignedConversionException + */ + public byte [] toByteArray() throws TpmUtils.TpmUnsignedConversionException { + byte[] algoId = TpmUtils.intToByteArray(algorithmId); + byte[] encSchm = TpmUtils.shortToByteArray(encScheme); + byte[] size = TpmUtils.shortToByteArray((short)keyBlob.length); + int x = algoId.length + encSchm.length + size.length + keyBlob.length; //calculate # of bytes in structure + byte [] returnArray = new byte[x]; + System.arraycopy(algoId, 0, returnArray, 0, algoId.length); + System.arraycopy(encSchm, 0, returnArray, algoId.length, encSchm.length); + System.arraycopy(size, 0, returnArray, algoId.length + encSchm.length, size.length); + System.arraycopy(keyBlob, 0, returnArray, algoId.length + encSchm.length + size.length, keyBlob.length); + return returnArray; + } +} diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmSymmetricKeyParams.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmSymmetricKeyParams.java new file mode 100644 index 0000000..9a7a59d --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmSymmetricKeyParams.java @@ -0,0 +1,122 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.io.ByteArrayInputStream; + +/** + *

This class is for the TCG's TPM_SYMMETRIC_KEY_PARMS structure.

+ * @author schawki + * + */ +public class TpmSymmetricKeyParams implements TpmKeySubParams{ + private int keyLength = 0; + private int blockSize = 0; + private byte[] iv; + + public TpmSymmetricKeyParams() {} + /** + * Create a new TpmSymmetricKeyParams by extracting from a byte stream. + * + * @param source The ByteArrayInputStream from which to extract the TpmSymmetricKey. + * @param length The number of bytes to extract + * @throws TpmUtils.TpmUnsignedConversionException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public TpmSymmetricKeyParams(ByteArrayInputStream source, int length) + throws TpmUtils.TpmUnsignedConversionException, + TpmUtils.TpmBytestreamResouceException { + if (length > 0) { + keyLength = TpmUtils.getUINT32(source); + blockSize = TpmUtils.getUINT32(source); + int temp = TpmUtils.getUINT32(source); + iv = TpmUtils.getBytes(source, temp); + } + } + /** + * @return Key length in bytes. + */ + public int getKeyLength() { + return keyLength; + } + /** + * Set a new key length. + * + * @param newValue New key length in bytes. + */ + public void setKeyLength(int newValue) { + keyLength = newValue; + } + /** + * @return Encryption block size in bytes. + */ + public int getValueData() { + return blockSize; + } + /** + * Set encryption block size. + * + * @param newValue New block size in bytes. + */ + public void setValueData(int newValue) { + blockSize = newValue; + } + /** + * @return Initialization vector. + */ + public byte [] getByteData() { + return iv; + } + /** + * Set initialization vector. + * + * @param newValue New initialization vector. + */ + public void setByteData(byte [] newValue) { + iv = newValue; + } + /** + * @return Human readable report of TpmSymmetricKeyParams. + */ + public String toString() { + String returnVal = ""; + returnVal += "TpmSymmetricKeyParams:\n"; + returnVal += " keyLength: " + Integer.toString(keyLength) + "\n"; + returnVal += " blockSize: " + Integer.toString(blockSize) + "\n"; + returnVal += " iv: " + TpmUtils.byteArrayToString(iv, 16); + return returnVal; + } + /** + * @return Serialized byte array form of TpmSymmetricKeyParams. + * @throws TpmUtils.TpmUnsignedConversionException + */ + public byte [] toByteArray() + throws TpmUtils.TpmUnsignedConversionException { + byte [] keyLngth = TpmUtils.intToByteArray(keyLength); + byte [] blkSize = TpmUtils.intToByteArray(blockSize); + int ivLength = 0; + if (iv != null) + ivLength = iv.length; + byte [] size = TpmUtils.intToByteArray(ivLength); + int x = keyLngth.length + blkSize.length + size.length + ivLength; + byte [] returnArray = new byte[x]; + + System.arraycopy(keyLngth, 0, returnArray, 0, keyLngth.length); + System.arraycopy(blkSize, 0, returnArray, keyLngth.length, blkSize.length); + System.arraycopy(size, 0, returnArray, keyLngth.length + blkSize.length, size.length); + if (iv != null) + System.arraycopy(iv, 0, returnArray, keyLngth.length + blkSize.length + size.length, iv.length); + return returnArray; + } +} diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmUtils.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmUtils.java new file mode 100644 index 0000000..ee32a94 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/TpmUtils.java @@ -0,0 +1,1107 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.io.*; +import java.math.*; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.security.*; +import java.security.cert.*; +import java.security.cert.Certificate; +import java.security.spec.*; +import java.security.interfaces.*; +import java.security.interfaces.RSAPublicKey; + +import javax.security.auth.x500.X500Principal; +import javax.security.cert.CertificateException; +import org.bouncycastle.util.encoders.Base64; +import org.bouncycastle.x509.*; +import org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure; +import org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure; +import org.bouncycastle.asn1.x509.*; +import org.bouncycastle.jce.provider.*; + +import javax.crypto.*; +import javax.crypto.spec.*; + +//import java.security.interfaces.RSAPublicKey; + +/** + *

The utils class contains functions that fall into two categories: those that provide + * utility to other classes in this package; and those that perform some cross-class + * functionality that is specific to this package.

+ *

This package was created for performing as a Privacy Certification Authority (Privacy CA), + * as specified by the Trusted Computing Group. The function ProcessIdentityRequest encompasses + * the role of a Privacy CA by taking an identity request, processing it with a CA signing key, + * and producing the specified data blobs containing a certificate.

+ *

The function makeEkCert works similarly to create a certificate for a TPM's Endorsement + * Key (EK certificate). This is not a defined role of a Privacy CA, however the process of + * creating an EK certificate is not covered in any TCG documentation, and the process of + * creating such a certificate is very similar to that used for processing an identity request.

+ *

The creation of an identity request is generally performed by the TSS function + * Tspi_TPM_CollateIdentityRequest. There are times, however, when it may be necessary to + * fabricate an identity request from its basic components. The function createIdentityRequest + * can be used to do just that. It is flexible enough to create a request in the format of any + * of the popular flavors of TSS.

+ * + *

Some of the functions provided in this class require the BouncyCastle security provider library, version 141 (for Java 1.5, this is the library named bcprov-jdk15-141.jar).

+ * + * @author schawki + * + */ +public class TpmUtils { + /** + * Converts an integer to a four-byte array. + * + * @param integer The integer to convert. + * @return A byte array with a length of 4 representing the integer as a UINT32. + * @throws TpmUnsignedConversionException This function does not work if the integer to convert is a negative number. + */ + public static byte[] intToByteArray (final int integer) + throws TpmUnsignedConversionException { + if (integer < 0) throw new TpmUnsignedConversionException("Cannot convert negative integer to UINT32 array: " + integer); + byte [] toReturn = new byte[4]; + toReturn[3] = (byte)((integer >> 0)&0x000000ff); + toReturn[2] = (byte)((integer >> 8)&0x000000ff); + toReturn[1] = (byte)((integer >>16)&0x000000ff); + toReturn[0] = (byte)((integer >>24)&0x000000ff); + return toReturn; + } + /** + * Converts a short integer to a two-byte array. + * + * @param shortInt The short integer to convert. + * @return A byte array with a length of 2 representing the integer as a UINT16. + * @throws TpmUnsignedConversionException This function does not work if the integer to convert is a negative number. + */ + public static byte[] shortToByteArray (final short shortInt) + throws TpmUnsignedConversionException { + if (shortInt < 0) throw new TpmUnsignedConversionException("Cannot convert negative short to UINT16 array: " + shortInt); + byte [] toReturn = new byte[2]; + toReturn[1] = (byte)(shortInt&0x000000ff); + toReturn[0] = (byte)((shortInt >> 8)&0x000000ff); + return toReturn; + } + /** + * Extracts four bytes in the form of a UINT32 from a ByteArrayInputStream and converts it to an integer. The byte stream will be reduced + * by four bytes. Note: the Java integer is signed, but the UINT32 is not (by definition). The integer was chosen to hold the value of a UINT32 + * because both are four bytes in size, even though the Java integer has a positive max value half that of the UINT32. As this conversion + * function converts from a UINT32, there sill never be a negative value extracted. The possibility exists that a UINT32 with a value greater + * than the integer MAX_VALUE will attempt to be extracted using this function. In that case, an exception will be thrown. This situation + * is not likely to occur, as UINT32 values are used for two purposes by the TCG: defined attributes/flags, and size values. When a UINT32 is + * used as an attribute or flag, the value is not as important as is the bit order. (Also, there are no attributes of flags in which the most + * significant bit is set.) As a size, the value is usually in numbers of bytes, and occasionally in number of bits. In either case, there is + * not likely to be a size, even in bits, that comes near to approaching the max value of integer. + * + * @param source The ByteArrayInputStream from which the UINT32 is to be extracted. + * @return An integer with the value of the UINT32. + * @throws TpmUnsignedConversionException The UINT32 being extracted is too large to be stored in an integer. + * @throws TpmBytestreamResouceException A UINT32 is four bytes in length, this exception is throws in there are not at least 4 bytes available to extract. + */ + public static int getUINT32(ByteArrayInputStream source) + throws TpmUnsignedConversionException, + TpmBytestreamResouceException { + if (source.available() < 4) { + throw new TpmBytestreamResouceException("There is not enough room in the bytestream to extract a UINT32."); + } + int retval = 0; + byte[] temp = new byte[4]; + int k =source.read(temp, 0, 4); + if ((temp[0]&0x80) == 0x80) throw new TpmUnsignedConversionException("Cannot convert UINT32 to signed Integer: too large - would be converted to negative."); + retval = (int)((temp[0]<<24&0xff000000) + + (int) (temp[1]<<16&0x00ff0000) + + (int) (temp[2]<< 8&0x0000ff00) + + (int) (temp[3]<< 0&0x000000ff)); + return retval; + } + /** + * Extracts a UINT16 from a bytestream and stores is as a short. See getUINT32 for issues that apply to this function. + * + * @param source The ByteArrayInputStream from which the UINT16 will be extracted. + * @return A short with the value of the UINT16 extracted. + * @throws TpmUnsignedConversionException Thrown if the UINT16 is too large to be stored as a short. + * @throws TpmBytestreamResouceException Thrown if there are not at least two bytes available in the bytestream to extract. + */ + public static short getUINT16(ByteArrayInputStream source) + throws TpmUnsignedConversionException, + TpmBytestreamResouceException { + if (source.available() < 2) { + throw new TpmBytestreamResouceException("There is not enough room in the bytestream to extract a UINT32."); + } + int retval = 0; + byte[] temp = new byte[2]; + int k = source.read(temp, 0, 2); + if ((temp[0]&0x80) == 0x80) throw new TpmUnsignedConversionException("Cannot convert UINT16 to signed Short: too large - would be converted to negative."); + retval = (int)((temp[0]<<8)&0x0000ff00) + + (int)((temp[1]<<0)&0x000000ff); + return (short)retval; + } + /** + * This exception is thrown to indicate an error in converting between a signed and an unsigned + * number of equal bit-lengths. This can be a result of attempting to convert an unsigned number + * of capacity greater than that of an equal-length signed number, or attempting to convert a + * negative signed number to an unsigned number. + * + * @author schawki + * + */ + public static class TpmUnsignedConversionException extends Exception { + private static final long serialVersionUID = 0; + public TpmUnsignedConversionException(String msg) { + super(msg); + } + } + /** + * This error is thrown when attempting to read more bytes from a bytestream or array than are + * available to read. For example, attempting to pull a four-byte UINT32 from a stream containing + * only three bytes. + * + * @author schawki + * + */ + public static class TpmBytestreamResouceException extends Exception { + private static final long serialVersionUID = 0; + public TpmBytestreamResouceException(String msg) { + super(msg); + } + } + /** + * Extracts a specified number of bytes from a ByteArrayInputStream and places them into a byte array. + * + * @param source The ByteArrayInputStream from which to extract the requested number of bytes. + * @param size The number of bytes to extract. + * @return A byte array of size size. + * @throws TpmBytestreamResouceException Thrown if the number of bytes requested exceeds the number of available bytes in the bytestream. + */ + public static byte[] getBytes(ByteArrayInputStream source, int size) + throws TpmBytestreamResouceException { + if (source.available() < size) { + throw new TpmBytestreamResouceException("There are not enough available bytes in the bytestream to extract the requested number."); + } + byte[] retval = new byte[size]; + int k = source.read(retval, 0, size); + return retval; + } + /** + * Creates a new X509 V3 certificate for use as an Attestation Identity Key (AIK) using the BouncyCastle provider. The certificate is designed in the + * direction of the Trusted Computing Group's specification of certificates for the Trusted Platform Module, although in its current form this + * function does not meet the standard. To that extent, the Subject Name field is left blank, and the V3 Subject Alternative Name field is marked + * critical and populated with the ID Label specified in the supplied TPM_Identity_Proof structure. + * + * @param idProof The TPM_Identity_Proof structure, used for the identity label field. + * @param privKey The Privacy CA's private key for signing the certificate. + * @param caCert The Privacy CA's public key certificate. + * @param validityDays The number of days until the created certificate expires, from the time this function is run. + * @param level Currently not used. + * @return An AIK certificate. + * @throws InvalidKeySpecException Passed on from the BouncyCastle certificate generator. + * @throws NoSuchAlgorithmException Passed on from the BouncyCastle certificate generator. + * @throws CertificateEncodingException Passed on from the BouncyCastle certificate generator. + * @throws NoSuchProviderException Thrown if the BouncyCastle provider cannot be found. + * @throws SignatureException Passed on from the BouncyCastle certificate generator. + * @throws InvalidKeyException Passed on from the BouncyCastle certificate generator. + */ + public static X509Certificate makeCert(TpmIdentityProof idProof, RSAPrivateKey privKey, X509Certificate caCert, int validityDays, int level) + throws InvalidKeySpecException, + NoSuchAlgorithmException, + CertificateEncodingException, + NoSuchProviderException, + SignatureException, + InvalidKeyException { + Security.addProvider(new BouncyCastleProvider()); + X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); + certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); + certGen.setIssuerDN(caCert.getSubjectX500Principal()); + certGen.setNotBefore(new java.sql.Time(System.currentTimeMillis())); + Calendar expiry = Calendar.getInstance(); + expiry.add(Calendar.DAY_OF_YEAR, validityDays); + certGen.setNotAfter(expiry.getTime()); + certGen.setSubjectDN(new X500Principal("")); + certGen.setPublicKey(idProof.getAik().getKey()); + certGen.setSignatureAlgorithm("SHA1withRSA"); + certGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.SubjectAlternativeName, true, new GeneralNames(new GeneralName(GeneralName.rfc822Name, new String(idProof.getIdLableBytes())))); + X509Certificate cert = certGen.generate(privKey, "BC"); + return cert; + } + /** + * Pulls the system time in "MMM d, yyyy h:mm:ss a" format as a string, suitable for use in a log file. + * @return String as described above. + */ + public static String getTime() { + Calendar time = Calendar.getInstance(); + SimpleDateFormat formatter = new SimpleDateFormat("MMM d, yyyy h:mm:ss a"); + String newString = formatter.format(time.getTime()); + return newString; + } + /** + * Creates a key pair and associated certificate for a certificate authority. An RSA key pair + * of specified size is stored with the self-signed certificate in an encrypted PKCS 12 key + * store file. The format of the certificate and PKCS 12 file are a replica of what is created + * by OpenSSL. + * + * @param keySize The size (in bits) of the RSA key to create + * @param caName The subject name for the new Certificate Authority (do not include "CN=") + * @param newP12Pass The password for encrypting the PKCS 12 file + * @param p12FileName The name for the PKCS 12 key store file (should end with .p12) + * @param validityDays The number of days the certificate should be valid before expiring + * @throws NoSuchAlgorithmException + * @throws InvalidKeyException + * @throws IllegalStateException + * @throws SignatureException + * @throws KeyStoreException + * @throws java.security.cert.CertificateException + * @throws IOException + */ + public static void createCaP12(int keySize, String caName, String newP12Pass, String p12FileName, int validityDays) + throws NoSuchAlgorithmException, + InvalidKeyException, + IllegalStateException, + SignatureException, + KeyStoreException, + java.security.cert.CertificateException, + IOException{ + Security.addProvider(new BouncyCastleProvider()); + KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); + keyGen.initialize(keySize); + KeyPair keyPair = keyGen.generateKeyPair(); + RSAPrivateKey privKey = (RSAPrivateKey)keyPair.getPrivate(); + RSAPublicKey pubKey = (RSAPublicKey)keyPair.getPublic(); + X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); + certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); + certGen.setIssuerDN(new X500Principal("CN=" + caName)); + certGen.setNotBefore(new java.sql.Time(System.currentTimeMillis())); + Calendar expiry = Calendar.getInstance(); + expiry.add(Calendar.DAY_OF_YEAR, validityDays); + certGen.setNotAfter(expiry.getTime()); + certGen.setSubjectDN(new X500Principal("CN=" + caName)); + certGen.setPublicKey(pubKey); + certGen.setSignatureAlgorithm("SHA1withRSA"); + certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); + certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); + X509Certificate caCert = certGen.generate(privKey); + certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); + caCert = certGen.generate(privKey); + FileOutputStream newp12 = new FileOutputStream(p12FileName); + + try { + KeyStore keystore = KeyStore.getInstance("PKCS12"); + keystore.load(null, newP12Pass.toCharArray()); + Certificate [] chain = {caCert}; + keystore.setKeyEntry("1", privKey, newP12Pass.toCharArray(), chain); + keystore.store(newp12, newP12Pass.toCharArray()); + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + newp12.close(); + } + + } + /** + * This function creates a p12 file for a client, creating a new RSA key pair of specified size. A certificate generated, signed by a the CA using the specified private key and CA certificate file. Both the client and CA certificates are stored as a chain in the p12 file. The client certificate's serial number is a system time in miliseconds. + * + * @param keySize Size of the key to generate + * @param subjectName Subject name for the client certificate + * @param newP12Pass Password to use for encrypting the p12 file + * @param p12FileName name for the generated file + * @param validityDays number of days the client certificate should be valid + * @param caCert The CA's certificate + * @param caPrivKey The CA's private key, for signing the client certificate + * @throws NoSuchAlgorithmException + * @throws InvalidKeyException + * @throws IllegalStateException + * @throws SignatureException + * @throws KeyStoreException + * @throws java.security.cert.CertificateException + * @throws IOException + */ + public static void createClientP12(int keySize, String subjectName, String newP12Pass, String p12FileName, int validityDays, X509Certificate caCert, RSAPrivateKey caPrivKey) + throws NoSuchAlgorithmException, + InvalidKeyException, + IllegalStateException, + SignatureException, + KeyStoreException, + java.security.cert.CertificateException, + IOException{ + Security.addProvider(new BouncyCastleProvider()); + KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); + keyGen.initialize(keySize); + KeyPair keyPair = keyGen.generateKeyPair(); + RSAPrivateKey privKey = (RSAPrivateKey)keyPair.getPrivate(); + RSAPublicKey pubKey = (RSAPublicKey)keyPair.getPublic(); + X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); + certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); + certGen.setIssuerDN(caCert.getSubjectX500Principal()); + certGen.setNotBefore(new java.sql.Time(System.currentTimeMillis())); + Calendar expiry = Calendar.getInstance(); + expiry.add(Calendar.DAY_OF_YEAR, validityDays); + certGen.setNotAfter(expiry.getTime()); + certGen.setSubjectDN(new X500Principal("CN=" + subjectName)); + certGen.setPublicKey(pubKey); + certGen.setSignatureAlgorithm("SHA1withRSA"); + certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); + certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); + certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); + X509Certificate clientCert = certGen.generate(caPrivKey); + FileOutputStream newp12 = new FileOutputStream(p12FileName); + + try { + KeyStore keystore = KeyStore.getInstance("PKCS12"); + keystore.load(null, newP12Pass.toCharArray()); + System.out.println(clientCert.toString()); + System.out.println(caCert.toString()); + Certificate [] chain = {clientCert, caCert}; + keystore.setKeyEntry("1", privKey, newP12Pass.toCharArray(), chain); + keystore.store(newp12, newP12Pass.toCharArray()); + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + newp12.close(); + } + + } + /** + * Creates an Endorsement Key (EK) Certificate. This certificate is not fully meet Trusted Computing Group specifications. Aside from the key and label source, the + * certificate is basically identical to the AIK certificate made by the makeCert function. The label used is "TPM EK Credential". Ideally, an EK certificate should + * only be created once per TPM and stored in the TPM's NVRAM, but this function can be used to provide the certificate while a method is being researched for the + * permanent storage of the EK certificate in NVRAM. + * + * @param pubEkMod The modulus of the public Endorsement Key (EK) in the form of a byte array. + * @param privKey The Privacy CA's private signing key. + * @param caCert The Privacy CA's public key certificate. + * @param validityDays The number of days until expiration, from the time this function is run. + * @return An EK certificate for the specified TPM's EK. + * @throws NoSuchAlgorithmException Passed on from the BouncyCastle certificate generator. + * @throws InvalidKeySpecException Passed on from the BouncyCastle certificate generator. + * @throws SignatureException Passed on from the BouncyCastle certificate generator. + * @throws NoSuchProviderException Thrown if the BouncyCastle provider cannot be found. + * @throws InvalidKeyException Passed on from the BouncyCastle certificate generator. + * @throws CertificateEncodingException Passed on from the BouncyCastle certificate generator. + */ + + public static X509Certificate makeEkCert(byte [] pubEkMod, RSAPrivateKey privKey, X509Certificate caCert, int validityDays) + throws NoSuchAlgorithmException, + InvalidKeySpecException, + SignatureException, + NoSuchProviderException, + InvalidKeyException, + CertificateEncodingException { + Security.addProvider(new BouncyCastleProvider()); + X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); + certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); + certGen.setIssuerDN(caCert.getSubjectX500Principal()); + certGen.setNotBefore(new java.sql.Time(System.currentTimeMillis())); + Calendar expiry = Calendar.getInstance(); + expiry.add(Calendar.DAY_OF_YEAR, validityDays); + certGen.setNotAfter(expiry.getTime()); + certGen.setSubjectDN(new X500Principal("")); + byte [] pubExp = new byte[3]; + pubExp[0] = (byte)(0x01 & 0xff); +// pubExp[1] = (byte)(0x00 & 0xff); + pubExp[1] = (byte)(0x00); + pubExp[2] = (byte)(0x01 & 0xff); + RSAPublicKey pubEk = TpmUtils.makePubKey(pubEkMod, pubExp); + certGen.setPublicKey(pubEk); + certGen.setSignatureAlgorithm("SHA1withRSA"); + certGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.SubjectAlternativeName, true, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "TPM EK Credential"))); + X509Certificate cert = certGen.generate(privKey, "BC"); + return cert; + } + + + /** + * Create a Java RSAPublicKey using the specified modulus and public exponent in byte array form. + * + * @param modulus The RSA key modulus in the form of a byte array. + * @param exponent The RSA public exponent in the form of a byte array. + * @return An RSAPublicKey. + * @throws NoSuchAlgorithmException Thrown if the Java KeyFactory doesn't know what "RSA" is. + * @throws InvalidKeySpecException Thrown if the key material is bad. + */ + public static RSAPublicKey makePubKey(byte[] modulus, byte[] exponent) + throws NoSuchAlgorithmException, + InvalidKeySpecException { + BigInteger modulusBI = byteArrayToBigInt(modulus); + BigInteger exponentBI = byteArrayToBigInt(exponent); + RSAPublicKeySpec newKeySpec = new RSAPublicKeySpec(modulusBI, exponentBI); + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + RSAPublicKey newKey = (RSAPublicKey)keyFactory.generatePublic(newKeySpec); + return newKey; + } + /** + * Generate an RSAPrivateKey object using a modulus and exponent, where both are provided as byte arrays. + * + * @param modulus + * @param exponent + * @return + * @throws NoSuchAlgorithmException + * @throws InvalidKeySpecException + */ + public static RSAPrivateKey makePrivKey(byte[] modulus, byte[] exponent) + throws NoSuchAlgorithmException, + InvalidKeySpecException { + BigInteger modulusBI = byteArrayToBigInt(modulus); + BigInteger exponentBI = byteArrayToBigInt(exponent); + RSAPrivateKeySpec newKeySpec = new RSAPrivateKeySpec(modulusBI, exponentBI); + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + RSAPrivateKey newKey = (RSAPrivateKey)keyFactory.generatePrivate(newKeySpec); + return newKey; + } + /** + * Create a Java Big Integer from a specified byte array. Intended for converting an RSA modulus or exponent, which is often + * specified in the form of a byte array for TPM activities. This function properly accounts for the highest-order bit set to + * avoid any complications arising from a conversion to the signed Big Integer. + * + * @param incoming The byte array to convert. + * @return The Big Integer with the value of the byte array. + */ + private static BigInteger byteArrayToBigInt(byte[] incoming) { + byte [] tempArray = null; + if ((incoming[0]&0x80) == 0x80) { + tempArray = new byte[incoming.length + 1]; + tempArray[0] = (byte)0x00; + for (int i = 0; i < incoming.length; i++) + tempArray[i+1] = incoming[i]; + } + else { + tempArray = incoming; + } + return new BigInteger(tempArray); + } + /** + * This function is not yet implemented. The intended purpose is to check the validity of an EK certificate supplied in an identity + * request. A valid certificate is one signed by a trusted entity. Another potential version of validity is the EK being present in + * a database of known TPMs. + * + * @param ekCred The EK certificate from the identity proof. + * @return True, if EK certificate passes verification. + */ + public static boolean verifyTPM(X509Certificate ekCred) { + return true; // TODO: check the EK certificate for authenticity. Only EK certificates signed by trusted sources should be trusted. + } + /** + * Creates a string of uppercase hexidecimal duples representing the supplied byte array. They are placed in lines containing a specified number of duples.. + * + * @param blob The byte array to turn into a string. + * @param perLine The number of hexidecimal duples to place on each line. + * @return A String, perhaps multi-line. + */ + public static String byteArrayToString(byte [] blob, int perLine) { + String returnVal = ""; + StringBuffer sb = new StringBuffer(); + for(int i = 0; i < blob.length; i++) { + String hexDigit = Integer.toHexString((int)blob[i] & 0xff).toUpperCase(); + if (hexDigit.length() == 1) + hexDigit = "0" + hexDigit; +// hexDigit = sb.append("0").append(hexDigit).toString(); + returnVal = sb.append(hexDigit).append(" ").toString(); + if (((i+1)%perLine == 0) && (i < (blob.length - 1))) + returnVal = sb.append("\n").toString(); + } + return returnVal; + } + /** + * Retrieve a private key from a PKCS #12 store. It is expected that the P12 file will contain only one private key and one public key certificate. + * + * @param filename The name of the P12 file. + * @param password The password needed to extract from the specified P12 file. + * @return The private key. + * @throws KeyStoreException Passed on from called functions. + * @throws IOException Passed on from called functions. + * @throws NoSuchAlgorithmException Passed on from called functions. + * @throws UnrecoverableKeyException Passed on from called functions. + * @throws javax.security.cert.CertificateException Passed on from called functions. + * @throws java.security.cert.CertificateException Passed on from called functions. + */ + public static RSAPrivateKey privKeyFromP12(String filename, String password) + throws KeyStoreException, + IOException, + NoSuchAlgorithmException, + UnrecoverableKeyException, + javax.security.cert.CertificateException, + java.security.cert.CertificateException { + KeyStore caKs = KeyStore.getInstance("PKCS12"); + FileInputStream fis = new FileInputStream(filename); + try { + caKs.load(fis, password.toCharArray()); + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + fis.close(); + } + + //caKs.load(ConfigHelper.getResourceAsStream(filename), password.toCharArray()); + Enumeration aliases = caKs.aliases(); + RSAPrivateKey privKey = null; + while(aliases.hasMoreElements()) { + String name = aliases.nextElement(); + privKey = (RSAPrivateKey)caKs.getKey(name, password.toCharArray()); + } + return privKey; + } + /** + * Retrieve a public key certificate from a PKCS #12 store. It is expected that the P12 file will contain only one private key and one public key certificate. + * + * @param filename The name of the P12 file. + * @param password The password needed to extract from the specified P12 file. + * @return The private key. + * @throws IOException Passed on from called functions. + * @throws NoSuchAlgorithmException Passed on from called functions. + * @throws UnrecoverableKeyException Passed on from called functions. + * @throws javax.security.cert.CertificateException Passed on from called functions. + * @throws java.security.cert.CertificateException Passed on from called functions. + */ + public static X509Certificate certFromP12(String filename, String password) + throws KeyStoreException, + IOException, + NoSuchAlgorithmException, + javax.security.cert.CertificateException, + java.security.cert.CertificateException { + KeyStore caKs = KeyStore.getInstance("PKCS12"); + FileInputStream fis =new FileInputStream(filename); + try { + caKs.load(fis, password.toCharArray()); + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + fis.close(); + } + + + Enumeration aliases = caKs.aliases(); + X509Certificate cert = null; + while(aliases.hasMoreElements()) { + String name = aliases.nextElement(); + cert = (X509Certificate)caKs.getCertificate(name); + } + return cert; + } + /** + * Retrieve a certificate as an X509Certificate object from a file (generally .cer or .crt using DER or PEM encoding) + * @param filename + * @return + * @throws KeyStoreException + * @throws IOException + * @throws NoSuchAlgorithmException + * @throws javax.security.cert.CertificateException + * @throws java.security.cert.CertificateException + */ + public static X509Certificate certFromFile(String filename) + throws KeyStoreException, + IOException, + NoSuchAlgorithmException, + javax.security.cert.CertificateException, + java.security.cert.CertificateException { + InputStream certStream = new FileInputStream(filename); +// byte [] certBytes = new byte[certStream.available()]; + byte[] certBytes = new byte[2048]; + try { + int k = certStream.read(certBytes); + + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + certStream.close(); + } + javax.security.cert.X509Certificate cert = javax.security.cert.X509Certificate.getInstance(certBytes); + return convertX509Cert(cert); + } + /** + * Retrieve a certificate as an X509Certificate object from a byte string, assuming DER encoding. + * @param certBytes + * @return + * @throws CertificateException + * @throws CertificateEncodingException + * @throws java.security.cert.CertificateException + */ + public static X509Certificate certFromBytes(byte [] certBytes) + throws CertificateException, + CertificateEncodingException, + java.security.cert.CertificateException{ + java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509"); + return (java.security.cert.X509Certificate)cf.generateCertificate(new ByteArrayInputStream(certBytes)); + } + /** + * Take an incoming identity request, unpack the contents, create an identity certificate, and return it in the properly formated form. + * + * @param idRequestBlob The TPM_Identity_Request, as a byte array, as received from the output of the Tspi_TPM_CollateIdentityRequest TSS function. + * @param caPrivKey The Privacy CA's private signing key. + * @param caPubCert The Privacy CA's public key certificate. + * @param validityDays The number of validity days, after which the certificate will expire. + * @return An idResponse, containing both TPM_ASYM_CA_CONTENTS and TPM_SYM_CA_ATTESTATION structures, suitable as input for the Tspi_TPM_ActivateIdentity function. + * @throws PrivacyCaException Thrown if an error occurs when processing the request. + * @throws TpmUtils.TpmUnsignedConversionException Passed from called functions, this most likely reflects a poorly constructed Identity Request or its base Identity Proof. + * @throws BadPaddingException Passed if an encryption/decryption error occurs. + * @throws IllegalBlockSizeException Passed if an encryption/decryption error occurs. + * @throws InvalidAlgorithmParameterException Passed if an encryption/decryption error occurs. + * @throws NoSuchPaddingException Passed if an encryption/decryption error occurs. + * @throws NoSuchAlgorithmException Passed if an encryption/decryption error occurs. + * @throws InvalidKeyException Passed if an encryption/decryption error occurs. + * @throws CertificateEncodingException Passed if an certificate creation error occurs. + * @throws IOException Passed if an certificate creation error occurs. + * @throws InvalidKeySpecException Passed if an certificate creation error occurs. + * @throws SignatureException Passed if an certificate creation error occurs. + * @throws NoSuchProviderException Passed if an certificate creation error occurs. + * @throws javax.security.cert.CertificateException Passed if an certificate creation error occurs. + * @throws java.security.cert.CertificateException Passed if an certificate creation error occurs. + * @throws TpmUtils.TpmBytestreamResouceException Passed from called functions, this most likely reflects a poorly constructed Identity Request or its base Identity Proof. + */ + public static idResponse ProcessIdentityRequest (byte [] idRequestBlob, RSAPrivateKey caPrivKey, X509Certificate caPubCert, int validityDays) + throws PrivacyCaException, + TpmUtils.TpmUnsignedConversionException, + BadPaddingException, + IllegalBlockSizeException, + InvalidAlgorithmParameterException, + NoSuchPaddingException, + NoSuchAlgorithmException, + InvalidKeyException, + CertificateEncodingException, + IOException, + InvalidKeySpecException, + SignatureException, + NoSuchProviderException, + javax.security.cert.CertificateException, + java.security.cert.CertificateException, + TpmUtils.TpmBytestreamResouceException { + TpmIdentityRequest request = new TpmIdentityRequest(idRequestBlob); + TpmIdentityProof idProof = request.decrypt(caPrivKey); + if (idProof.getEkCredBytes().length == 0) throw new PrivacyCaException("PrivacyCaException: Error parsing TPM_IDENTITY_PROOF: there is no endorsement credential."); + if (!idProof.checkValidity((RSAPublicKey)caPubCert.getPublicKey())) throw new PrivacyCaException("Request does not pass integrity check: identity binding does not pass verification."); + TpmSymCaAttestation symPart = new TpmSymCaAttestation(); + symPart.setAikCredential(TpmUtils.makeCert(idProof, caPrivKey, caPubCert, validityDays, 0)); + TpmAsymCaContents asymPart = new TpmAsymCaContents(); + //pass symmetric encryption mode here + TpmSymmetricKey temp = symPart.encrypt(TpmKeyParams.TPM_ALG_AES, TpmKeyParams.TPM_ES_SYM_CBC_PKCS5PAD, request.getSymKeyParams().getTrouSerSmode(), !request.getSymkeyEncscheme()); //see the ! + asymPart.setSymmetricKey(temp); + asymPart.setDigest(idProof.getAik()); + //pass asymmetric encryption mode here + asymPart.encrypt((RSAPublicKey)idProof.getEkCred().getPublicKey(), !request.getOeapMode());//see the ! + idResponse returnval = new idResponse(asymPart, symPart); + return returnval; + } + /** + * Used by the Privacy CA (version 1) to process Identity Requests that do not contain an EC. The EC is not validated, and the AIC is returned in plaintext. The client can then get the AIC without using ActivateIdentity. This is here because the Windows (NTRU) TSS client is broken, and cannot include the EC in an Identity Request, and also cannot perform an ActivateIdentity properly. + * + * @param idRequestBlob The incomming Identity Request with no EC + * @param caPrivKey The Privacy CA's private key + * @param caPubCert The Privacy CA's certificate + * @param validityDays The number of days before AIC expiration + * @return the AIC in the form of an X509Certificate + * @throws PrivacyCaException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws BadPaddingException + * @throws IllegalBlockSizeException + * @throws InvalidAlgorithmParameterException + * @throws NoSuchPaddingException + * @throws NoSuchAlgorithmException + * @throws InvalidKeyException + * @throws CertificateEncodingException + * @throws IOException + * @throws InvalidKeySpecException + * @throws SignatureException + * @throws NoSuchProviderException + * @throws javax.security.cert.CertificateException + * @throws java.security.cert.CertificateException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public static X509Certificate PartiallyProcessIdentityRequest (byte [] idRequestBlob, RSAPrivateKey caPrivKey, X509Certificate caPubCert, int validityDays) + throws PrivacyCaException, + TpmUtils.TpmUnsignedConversionException, + BadPaddingException, + IllegalBlockSizeException, + InvalidAlgorithmParameterException, + NoSuchPaddingException, + NoSuchAlgorithmException, + InvalidKeyException, + CertificateEncodingException, + IOException, + InvalidKeySpecException, + SignatureException, + NoSuchProviderException, + javax.security.cert.CertificateException, + java.security.cert.CertificateException, + TpmUtils.TpmBytestreamResouceException { + TpmIdentityRequest request = new TpmIdentityRequest(idRequestBlob); + TpmIdentityProof idProof = request.decrypt(caPrivKey); + if (!idProof.checkValidity((RSAPublicKey)caPubCert.getPublicKey())) throw new PrivacyCaException("Request does not pass integrity check: identity binding does not pass verification."); + return TpmUtils.makeCert(idProof, caPrivKey, caPubCert, validityDays, 0); + } + /** + * Generate a new identity request. User supplied data for a new request is the identity label + * and the Privacy CA's public key. This function relies upon a method to obtain the public key + * of a newly-created identity key (to be certified by the Privacy CA), an identity binding + * signed by the TPM, and any certificates available from the TPM's non-volatile storage + * (Endorsement, Platform, and/or Conformance certificates). Note: the endorsement certificate + * must be present to have a complete request! The functionality to get this TPM-supplied + * data is currently not available. + * + * @param idLabel A string, to be submitted in ASCII, to be used as the subject alternative name for the identity certificate + * @param caPubKey The public key of the Privacy CA + * @param IV A boolean flag to specify the placement of the symmetric encryption initialization vector (true indicates that IV should be placed at the beginning of symmetrically encrypted blob instead of the symmetric key parameters) + * @param symKey A boolean flag to specify the symmetric key encryption scheme flag (true indicates the encryption scheme should be specified as "TSS_ES_NONE") + * @param oaep A boolean flag to indicate if the asymmetric OAEP padding will use the string specified in the TSS 1.1b "Main" document (true indicates that the string should be left blank) + * @return + * @throws TpmUtils.TpmUnsignedConversionException + * @throws NoSuchPaddingException + * @throws NoSuchAlgorithmException + * @throws InvalidAlgorithmParameterException + * @throws InvalidKeyException + * @throws BadPaddingException + * @throws IllegalBlockSizeException + * @throws IOException + */ + public static TpmIdentityRequest createIdentityRequest(String idLabel, RSAPublicKey caPubKey, boolean IV, boolean symKey, boolean oaep) + throws TpmUtils.TpmUnsignedConversionException, + NoSuchPaddingException, + NoSuchAlgorithmException, + InvalidAlgorithmParameterException, + InvalidKeyException, + BadPaddingException, + IllegalBlockSizeException, + IOException { + //TODO: Get the following from Tcsip_MakeIdentity + byte [] identityBinding = "".getBytes(); + byte [] identityKey = "".getBytes(); //must be just the modulus!!! + //TODO: Get the following from the NV-RAM, if desired + byte [] endorsementCert = "".getBytes(); + byte [] platformCert = "".getBytes(); + byte [] conformanceCert = "".getBytes(); + // Assemble Identity Proof + TpmIdentityProof idProof = new TpmIdentityProof(idLabel.getBytes(), identityBinding, new TpmPubKey(identityKey), endorsementCert, platformCert, conformanceCert, IV, symKey, oaep); + // Encrypt Identity Proof into Identity Request using Privacy CA public key + TpmIdentityRequest idReq = new TpmIdentityRequest(idProof, caPubKey); + return idReq; + } + /** + * Fills a 16 byte array with random data, using nanoTime. + * + * @return A byte array of length 16 containing new random data. + * @throws IOException + */ + public static byte [] createRandomBytes(int numBytes) + throws IOException { + Random random = new Random(System.nanoTime()); + //byte [] randomBytes = longToByteArray(random.nextLong()); + byte [] randomBytes = new byte[numBytes]; + random.nextBytes(randomBytes); + return randomBytes; + } + /** + * Encode an X509 Certificate in the PEM (base64) encoding format. + * + * @param cert The certificate to encode. + * @return A String with the base64 encoded certificate. + * @throws CertificateEncodingException Thrown if there is a problem with the certificate. + */ + public static String PEMencodeCert(X509Certificate cert) + throws CertificateEncodingException { + return "-----BEGIN CERTIFICATE-----" + base64encode(cert.getEncoded(), false) + "-----END CERTIFICATE-----"; + } + /** + * Base64 encode a byte array. + * + * @param toEncode The byte array to encode. + * @param breakLines Set true if it is desired to place line break at every 76 characters, per spec (not done often). + * @return The String of the encoded array. + */ + public static String base64encode(byte [] toEncode, boolean breakLines) { + StringBuffer sb =new StringBuffer(); + char[] charArray = new String(Base64.encode(toEncode)).toCharArray(); + String toReturn = ""; + for (int i = 0; i < charArray.length; i++){ + if(breakLines){if((i%64 == 0)) toReturn = sb.append("\n").toString(); } + toReturn = sb.append(charArray[i]).toString(); + } + return toReturn; + } + public static byte[] base64decode(String encoded){ + return Base64.decode(encoded); + } + /** + * Convert a javax X509Certificate to a java X509Certificate. + * + * @param cert A certificate in javax.security.cert.X509Certificate format + * @return A certificate in java.security.cert.X509Certificate format + */ + public static java.security.cert.X509Certificate convertX509Cert(javax.security.cert.X509Certificate cert) + throws java.security.cert.CertificateEncodingException, + javax.security.cert.CertificateEncodingException, + java.security.cert.CertificateException, + javax.security.cert.CertificateException { + java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509"); + return (java.security.cert.X509Certificate)cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded())); + } + /** + * Convert a java X509Certificate to a javax X509Certificate. + * + * @param cert A certificate in java.security.cert.X509Certificate format + * @return A certificate in javax.security.cert.X509Certificate format + */ + public static javax.security.cert.X509Certificate convertX509Cert(java.security.cert.X509Certificate cert) + throws java.security.cert.CertificateEncodingException, + javax.security.cert.CertificateEncodingException, + java.security.cert.CertificateException, + javax.security.cert.CertificateException { + return javax.security.cert.X509Certificate.getInstance(cert.getEncoded()); + } + /** + * Given a string of hexadecimal characters, convert to a byte array. No checks are performed to ensure that the string is all valid hexidecimal characters (0-9, a-f, A-F) or that there is an even number of characters. + * @param s The hexadecimal string + * @return A byte array + */ + public static byte[] hexStringToByteArray(String s) { + int sizeInt = s.length()/2; + byte [] returnArray = new byte[sizeInt]; + String byteVal; + for (int i = 0; i < sizeInt; i++) { + int index = 2 * i; + byteVal = s.substring(index, index + 2); + returnArray[i] = (byte)(Integer.parseInt(byteVal, 16)); +// returnArray[i] = (byte)(Integer.parseInt(byteVal, 16) & 0xff); + } + return returnArray; + } + /** + * Convert a byte array to a hexidecimal character string. The string will have no delimeter between hexidecimal duples, and has no line breaks. + * @param b Byte array to convert + * @return A string of hexidecimal characters + */ + public static String byteArrayToHexString(byte[] b) { + StringBuffer sb = new StringBuffer(); + String returnStr = ""; + for (int i = 0; i < b.length; i++) { + String singleByte = Integer.toHexString(b[i] & 0xff); + if (singleByte.length() != 2) singleByte = "0" + singleByte; +// returnStr += singleByte; + returnStr = sb.append(singleByte).toString(); + } + return returnStr; + } + /** + * Convert a byte array to a hexidecimal character string, in a format that can be placed as a parameter in C++. The hexidecimal byte duples are each prefixed with "0x" and delimted with a comma and space (", "). Example: "0x0a, 0xbc, " + * @param b Byte array to convert + * @return String in the format described above + */ + public static String byteArrayToCppHexString(byte[] b){ + StringBuffer sb =new StringBuffer(); + String returnStr = ""; + for (int i = 0; i < b.length; i++) { + String singleByte = Integer.toHexString(b[i] & 0xff); + if (singleByte.length() != 2) singleByte = "0" + singleByte; + returnStr = sb.append("0x").append(singleByte).append(", ").toString(); + } + return returnStr; + } + /** + * Concatenate two byte arrays into one, in the order they are specified. + * @param blob1 Byte array to be placed first in the concatenation + * @param blob2 Byte array to be placed last in the concatenation + * @return + */ + public static byte[] concat(byte[] blob1, byte[] blob2){ + byte[] toReturn = new byte[blob1.length + blob2.length]; + System.arraycopy(blob1, 0, toReturn, 0, blob1.length); + System.arraycopy(blob2, 0, toReturn, blob1.length, blob2.length); + return toReturn; + } + /** + * Perform a SHA-1 hash of a given byte array + * @param blob Byte array to hash + * @return SHA-1 hash of the specified byte array. Should always be 20 bytes in length + * @throws NoSuchAlgorithmException + */ + public static byte[] sha1hash(byte[] blob) + throws NoSuchAlgorithmException{ + byte[] toReturn = null; + MessageDigest md = MessageDigest.getInstance("SHA1"); + md.update(blob); + toReturn = md.digest(); + return toReturn; + } + /** + * Perform an asymmetric encryption of a byte array in the way specified by the TCG for all TPM-related operations, using the given OAEP string (in case it is not the TCG-specified "TCPA") + * @param payload Byte array to encrypt + * @param pubKey RSA public key to use for encryption + * @param OAEPstring The OAEP string to use for padding + * @return An encrypted blob of the length of the pubKey's modulus + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws IllegalBlockSizeException + * @throws BadPaddingException + */ + public static byte[] TCGAsymEncrypt(byte[] payload, RSAPublicKey pubKey, String OAEPstring) + throws NoSuchAlgorithmException, + NoSuchPaddingException, + InvalidKeyException, + InvalidAlgorithmParameterException, + IllegalBlockSizeException, + BadPaddingException{ + OAEPParameterSpec oaepSpec = new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified(OAEPstring.getBytes())); + Cipher asymCipher = Cipher.getInstance("RSA/ECB/OAEPWithSha1AndMGF1Padding"); + asymCipher.init(Cipher.PUBLIC_KEY, pubKey, oaepSpec); + asymCipher.update(payload); + byte [] toReturn = asymCipher.doFinal(); + return toReturn; + } + /** + * Perform an asymmetric encryption of a byte array in the way specified by the TCG for all TPM-related operations, using the OAEP string "TCPA" as specified. + * @param payload Byte array to encrypt + * @param pubKey RSA public key to use for encryption + * @return The encrypted blob of the length of the pubKey's modulus + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws IllegalBlockSizeException + * @throws BadPaddingException + */ + public static byte[] TCGAsymEncrypt(byte[] payload, RSAPublicKey pubKey) + throws NoSuchAlgorithmException, + NoSuchPaddingException, + InvalidKeyException, + InvalidAlgorithmParameterException, + IllegalBlockSizeException, + BadPaddingException{ + return TCGAsymEncrypt(payload, pubKey, "TCPA"); + } + /** + * Perform a symmetric encryption of a byte array in the way specified by the TCG for all TPM-related symmetric encryption activities. The given key and IV are used. + * @param payload Byte array to encrypt + * @param key Symmetric (AES) key to use. Exception will be thrown if key is an invalid length. + * @param iv Initialization Vector to use. Exception will be thrown if IV is an invalid length. + * @return Encrypted byte blob. + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws IllegalBlockSizeException + * @throws BadPaddingException + */ + public static byte[] TCGSymEncrypt(byte[] payload, byte[] key, byte[] iv) + throws NoSuchAlgorithmException, + NoSuchPaddingException, + InvalidKeyException, + InvalidAlgorithmParameterException, + IllegalBlockSizeException, + BadPaddingException{ + Cipher symCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + IvParameterSpec ivSpec = new IvParameterSpec(iv); + SecretKeySpec symKey = new SecretKeySpec(key, "AES"); + symCipher.init(Cipher.ENCRYPT_MODE, symKey, ivSpec); + byte [] toReturn = symCipher.doFinal(payload); + return toReturn; + } + /** + * Create a random 128-bit value that can be used as an AES key or IV. + * @return + * @throws IOException + */ + public static byte[] newRandomAESValue() //key or iv + throws IOException{ + return TpmUtils.createRandomBytes(16); + } + /** + * Decrypt an TCG-style asymmetrically encrypted byte blob, given the correct RSA private key and OAEP string. If properly encrypted, the OAEP string should be "TCPA" (less the quotes). + * @param ciphertext Asymmetrically encrypted byte array + * @param privKey The RSA private key to be used to decrypt the ciphertext + * @param OAEPstring The OAEP string that was used for padding (should be "TCPA") + * @return The decrypted byte array + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws IllegalBlockSizeException + * @throws BadPaddingException + */ + public static byte[] TCGAsymDecrypt(byte[] ciphertext, RSAPrivateKey privKey, String OAEPstring) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{ + Cipher asymCipher = Cipher.getInstance("RSA/ECB/OAEPWithSha1AndMGF1Padding"); + OAEPParameterSpec oaepSpec = new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified(OAEPstring.getBytes())); + asymCipher.init(Cipher.PRIVATE_KEY, privKey, oaepSpec); + asymCipher.update(ciphertext); + byte[] toReturn = asymCipher.doFinal(); + return toReturn; + } + /** + * Decrypt an AES/CBC/PKCS5Paddded symmetrically encrypted blob, using the given key and IV. + * @param ciphertext The encrypted byte array + * @param key The key used to perform the decryption + * @param iv The Initialization Vector used + * @return The decrypted byte array + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws IllegalBlockSizeException + * @throws BadPaddingException + */ + public static byte[] TCGSymDecrypt(byte[] ciphertext, byte[] key, byte[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{ + Cipher symCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + IvParameterSpec ivSpec = new IvParameterSpec(iv); + symCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), ivSpec); + return symCipher.doFinal(ciphertext); + } + /** + * Generate a Hashed Message Authentication Code for TCS function authentication using the given auth blob and concatenation of all *H1 (1H1, 2H1, etc) values for the function. + * @param authBlob 20 byte auth code for the object in question + * @param xH1concat A concatenation of all of the authenticated *H1 parameters for the function, e.g. 1H1, 2H1, 3H1, etc. + * @return The HMAC blob suitable to be used for passing as a TCS parameter + * @throws Exception + */ + public static byte[] HMAC(byte[] authBlob, byte[] xH1concat) throws Exception{ + Mac mac = Mac.getInstance("HmacSha1"); + SecretKey key = new SecretKeySpec(authBlob, "HmacSha1"); + mac.init(key); + mac.update(xH1concat); + return mac.doFinal(); + } + /** + * Returns true if both byte arrays sent in parameters are the same length and have the exact same contents for each respective elements. + * @param array1 + * @param array2 + * @return + */ + public static boolean compareByteArrays(byte[] array1, byte[] array2){ + if(array1.length != array2.length) + return false; + for(int i = 0; i < array1.length; i++) + if(array1[i] != array2[i]) + return false; + return true; + } + /** + * Get the system's Fully Qualified Domain Name as a string + * @return the system's FQDN + */ + public static String getHostname(){ + String hostname = ""; + try{ + hostname = InetAddress.getLocalHost().getHostName(); + } + catch (UnknownHostException u){ + StringTokenizer st = new StringTokenizer(u.getMessage()); + while (st.hasMoreTokens()) hostname = st.nextToken(); + } + return hostname; + } + +} diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/idResponse.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/idResponse.java new file mode 100644 index 0000000..c1100e1 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/idResponse.java @@ -0,0 +1,86 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +/** + *

This class is needed to provide a return type for the utils.processIdentityRequest function that includes + * both the Symmetric and Asymmetric parts of the Privacy CA's response. It is simply a holding container. + * The data is not manipulated in any way, except as needed for formatting.

+ * + * @author schawki + * + */ +public class idResponse { + private TpmAsymCaContents asymPart; + private TpmSymCaAttestation symPart; + /** + * Create a new idResponse of the supplied TPM_ASYM_CA_CONTENTS and TPM_SYM_CA_ATTESTATION structures. + * + * @param asym TPM_ASYM_CA_CONTENTS + * @param sym TPM_SYM_CA_ATTESTATION + */ + public idResponse(TpmAsymCaContents asym, TpmSymCaAttestation sym) { + asymPart = asym; + symPart = sym; + } + /** + * If needed, this function provides a byte array of the Asym and Sym parts of the response concatenated together. + * + * @return Byte array form of the idResponse (asym + sym). + * @throws TpmUtils.TpmUnsignedConversionException Thrown if bad data is encountered when assembling the byte array. + * @throws PrivacyCaException Thrown if either part is not complete and ready to be turned into a byte array. + */ + public byte [] toByteArray() + throws TpmUtils.TpmUnsignedConversionException, + PrivacyCaException { + byte [] asym = asymPart.toByteArray(); + byte [] sym = symPart.toByteArray(); + byte [] returnArray = new byte[asym.length + sym.length]; + System.arraycopy(asym, 0, returnArray, 0, asym.length); + System.arraycopy(sym, 0, returnArray, asym.length, sym.length); + return returnArray; + } + /** + * Asym getter function. + * + * @return Asymmetric portion of idResponse. + */ + public TpmAsymCaContents getAsymPart() { + return asymPart; + } + /** + * Sym getter function. + * + * @return Symmetric portion of idResponse. + */ + public TpmSymCaAttestation getSymPart() { + return symPart; + } + /** + * Asym setter function. + * + * @param newPart + */ + public void setAsymPart(TpmAsymCaContents newPart) { + asymPart = newPart; + } + /** + * Sym setter function. + * + * @param newPart + */ + public void setSymPart(TpmSymCaAttestation newPart) { + symPart = newPart; + } +} diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/IHisPrivacyCAWebService2.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/IHisPrivacyCAWebService2.java new file mode 100644 index 0000000..62e0c80 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/IHisPrivacyCAWebService2.java @@ -0,0 +1,35 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.webservices.hisPrivacyCAWebService2; + +/** + *

This interface defines the web service functions.

+ * + * @author schawki + * + */ +public interface IHisPrivacyCAWebService2 { + /** + * + * + * @param identityRequest + * @param endorsementCertificate + * @return + */ + public byte[] identityRequestGetChallenge(byte[] identityRequest, byte[] endorsementCertificate); + + public byte[] identityRequestSubmitResponse(byte[] identityRequestResponseToChallenge); + + public byte[] requestGetEC(byte[] encryptedEkMod, byte[] encryptedDeskey, int ecValidDays); +} \ No newline at end of file diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/client/HisPrivacyCAWebServices2ClientInvoker.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/client/HisPrivacyCAWebServices2ClientInvoker.java new file mode 100644 index 0000000..f63d48e --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/client/HisPrivacyCAWebServices2ClientInvoker.java @@ -0,0 +1,74 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.webservices.hisPrivacyCAWebService2.client; + +import gov.niarl.his.webservices.hisPrivacyCAWebService2.IHisPrivacyCAWebService2; +import gov.niarl.his.webservices.hisPrivacyCAWebServices2.clientWsImport.ByteArray; +import gov.niarl.his.webservices.hisPrivacyCAWebServices2.clientWsImport.HisPrivacyCAWebService2; +import gov.niarl.his.webservices.hisPrivacyCAWebServices2.clientWsImport.HisPrivacyCAWebService2FactoryService; +import gov.niarl.his.webservices.hisPrivacyCAWebServices2.clientWsImport.HisPrivacyCAWebService2FactoryServiceService; +import gov.niarl.his.webservices.hisPrivacyCAWebServices2.clientWsImport.HisPrivacyCAWebService2Service; + +import java.net.MalformedURLException; +import java.net.URL; + +import javax.xml.namespace.QName; + +public class HisPrivacyCAWebServices2ClientInvoker { + + public static IHisPrivacyCAWebService2 getHisPrivacyCAWebService2(String url) { + try { + HisPrivacyCAWebService2FactoryServiceService hisPrivacyCAWebService2FactoryServiceService = new HisPrivacyCAWebService2FactoryServiceService(new URL(url + "/hisPrivacyCAWebService2FactoryService?wsdl"), new QName("http://server.hisPrivacyCAWebService2.webservices.his.niarl.gov/", "HisPrivacyCAWebService2FactoryServiceService")); + HisPrivacyCAWebService2FactoryService hisPrivacyCAWebService2FactoryService = hisPrivacyCAWebService2FactoryServiceService.getHisPrivacyCAWebService2FactoryServicePort(); + HisPrivacyCAWebService2Service hisPrivacyCAWebService2Service = new HisPrivacyCAWebService2Service(new URL(url + "/hisPrivacyCAWebService2?wsdl"), new QName("http://server.hisPrivacyCAWebService2.webservices.his.niarl.gov/", "HisPrivacyCAWebService2Service")); + return new HisPrivacyCAWebServices2ClientImpl(hisPrivacyCAWebService2Service.getPort(hisPrivacyCAWebService2FactoryService.getHisPrivacyCAWebService2(), HisPrivacyCAWebService2.class)); + } catch (MalformedURLException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + +} + +class HisPrivacyCAWebServices2ClientImpl implements IHisPrivacyCAWebService2 { + + HisPrivacyCAWebService2 hisPrivacyCAWebService2; + + public HisPrivacyCAWebServices2ClientImpl(HisPrivacyCAWebService2 hisPrivacyCAWebService2) { + this.hisPrivacyCAWebService2 = hisPrivacyCAWebService2; + } + + public byte[] identityRequestGetChallenge(byte[] identityRequest, byte[] endorsementCertificate) { + ByteArray identityRequestByteArray = new ByteArray(); + identityRequestByteArray.setBytes(identityRequest); + ByteArray endorsementCertificateByteArray = new ByteArray(); + endorsementCertificateByteArray.setBytes(endorsementCertificate); + return hisPrivacyCAWebService2.identityRequestGetChallenge(identityRequestByteArray, endorsementCertificateByteArray).getBytes(); + } + + public byte[] identityRequestSubmitResponse(byte[] identityRequestResponseToChallenge) { + ByteArray identityRequestResponseToChallengeByteArray = new ByteArray(); + identityRequestResponseToChallengeByteArray.setBytes(identityRequestResponseToChallenge); + return hisPrivacyCAWebService2.identityRequestSubmitResponse(identityRequestResponseToChallengeByteArray).getBytes(); + } + + public byte [] requestGetEC(byte [] encryptedEkMod, byte [] encryptedSessionKey, int ecValidDays){ + ByteArray eKModulusByteArray = new ByteArray(); + eKModulusByteArray.setBytes(encryptedEkMod); + ByteArray sessionKeyArray = new ByteArray(); + sessionKeyArray.setBytes(encryptedSessionKey); + return hisPrivacyCAWebService2.requestGetEC(eKModulusByteArray, sessionKeyArray, ecValidDays).getBytes(); + } + +} \ No newline at end of file diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/client/package-info.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/client/package-info.java new file mode 100644 index 0000000..89c3481 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/client/package-info.java @@ -0,0 +1,4 @@ +/** +

This package contains the client code for connecting to the version 2 HIS Privacy CA.

+*/ +package gov.niarl.his.webservices.hisPrivacyCAWebService2.client; diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/package-info.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/package-info.java new file mode 100644 index 0000000..9f52147 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/package-info.java @@ -0,0 +1,4 @@ +/** +

This package contains the interface and function definitions for version 2 of the HIS Privacy CA.

+*/ +package gov.niarl.his.webservices.hisPrivacyCAWebService2; diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/ByteArray.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/ByteArray.java new file mode 100644 index 0000000..7d8ff1d --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/ByteArray.java @@ -0,0 +1,35 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.webservices.hisPrivacyCAWebService2.server; + +public class ByteArray { + byte[] bytes; + + public ByteArray() { + super(); + } + + public ByteArray(byte[] bytes) { + super(); + this.bytes = bytes; + } + + public byte[] getBytes() { + return bytes; + } + + public void setBytes(byte[] bytes) { + this.bytes = bytes; + } +} \ No newline at end of file diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/HisPrivacyCAWebService2.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/HisPrivacyCAWebService2.java new file mode 100644 index 0000000..cea1b94 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/HisPrivacyCAWebService2.java @@ -0,0 +1,66 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.webservices.hisPrivacyCAWebService2.server; + +import gov.niarl.his.webservices.hisPrivacyCAWebService2.IHisPrivacyCAWebService2; + +import javax.jws.WebMethod; +import javax.jws.WebParam; +import javax.jws.WebResult; +import javax.jws.WebService; +import javax.xml.ws.soap.Addressing; + +import com.sun.xml.ws.developer.Stateful; +import com.sun.xml.ws.developer.StatefulWebServiceManager; + +@Stateful +@WebService +@Addressing +public class HisPrivacyCAWebService2 { + /** + * Needed for stateful web services. StatefulWebServiceManager javadoc + */ + public static StatefulWebServiceManager manager; + + IHisPrivacyCAWebService2 hisPrivacyCAWebService2 = new HisPrivacyCAWebService2Impl(); + + @WebResult(name = "identityRequestChallenge") + public ByteArray identityRequestGetChallenge(@WebParam(name = "identityRequest") ByteArray identityRequest, @WebParam(name = "endorsementCertificate") ByteArray endorsementCertificate) { + return new ByteArray(hisPrivacyCAWebService2.identityRequestGetChallenge(identityRequest.getBytes(), endorsementCertificate.getBytes())); + } + + @WebResult(name = "encryptedCertificate") + public ByteArray identityRequestSubmitResponse(@WebParam(name = "identityRequestResponseToChallenge") ByteArray identityRequestResponseToChallenge) { + try { + return new ByteArray(hisPrivacyCAWebService2.identityRequestSubmitResponse(identityRequestResponseToChallenge.getBytes())); + } finally { + manager.unexport(this); + } + } + + @WebMethod(exclude = true) + public static StatefulWebServiceManager getManager() { + return manager; + } + + @WebMethod(exclude = true) + public static void setManager(StatefulWebServiceManager manager) { + HisPrivacyCAWebService2.manager = manager; + } + + @WebResult(name = "requestGetEC") + public ByteArray requestGetEC(@WebParam(name = "encryptedEkMod") ByteArray encryptedEkMod, ByteArray encryptedSessionKey, int ecValidDays) { + return new ByteArray(hisPrivacyCAWebService2.requestGetEC(encryptedEkMod.getBytes(), encryptedSessionKey.getBytes(), ecValidDays));} + +} \ No newline at end of file diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/HisPrivacyCAWebService2FactoryService.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/HisPrivacyCAWebService2FactoryService.java new file mode 100644 index 0000000..8e13ab5 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/HisPrivacyCAWebService2FactoryService.java @@ -0,0 +1,33 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.webservices.hisPrivacyCAWebService2.server; + +import javax.jws.WebService; +import javax.xml.ws.wsaddressing.W3CEndpointReference; + +@WebService +public class HisPrivacyCAWebService2FactoryService { + static boolean setTimeout = false; + + public W3CEndpointReference getHisPrivacyCAWebService2() { + + if (!setTimeout) { + // 180 second timeout + HisPrivacyCAWebService2 hisPrivacyCAWebService2 = new HisPrivacyCAWebService2(); + hisPrivacyCAWebService2.manager.setTimeout(180 * 1000, null); + setTimeout = true; + } + return HisPrivacyCAWebService2.manager.export(new HisPrivacyCAWebService2()); + } +} \ No newline at end of file diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/HisPrivacyCAWebService2Impl.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/HisPrivacyCAWebService2Impl.java new file mode 100644 index 0000000..50bfdab --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/HisPrivacyCAWebService2Impl.java @@ -0,0 +1,334 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.webservices.hisPrivacyCAWebService2.server; + +import java.io.*; +import java.security.*; +import java.security.cert.*; +import java.security.interfaces.*; +import java.util.*; + +import javax.crypto.*; + +import gov.niarl.his.privacyca.*; +import gov.niarl.his.privacyca.TpmUtils.*; +import gov.niarl.his.webservices.hisPrivacyCAWebService2.IHisPrivacyCAWebService2; +import org.bouncycastle.x509.*; +import org.bouncycastle.asn1.x509.*; +import org.bouncycastle.jce.provider.*; + +import java.math.*; +import javax.security.auth.x500.X500Principal; +import javax.crypto.spec.*; + +public class HisPrivacyCAWebService2Impl implements IHisPrivacyCAWebService2 { + + private byte[] identityRequestChallenge = null; + private RSAPrivateKey caPrivKey = null; + private X509Certificate caPubCert = null; + private int validityDays = 0; + private boolean propFileLoaded = false; + private Hashtable endorsementCerts; + private X509Certificate ekCert = null; + TpmIdentityProof idProof = null; + + public byte[] identityRequestGetChallenge(byte[] identityRequest, byte[] endorsementCertificate) { + try { + if(!propFileLoaded) + propFileLoaded = readPropertiesFile(); + //decrypt identityRequest and endorsementCertificate + TpmIdentityRequest idReq = new TpmIdentityRequest(identityRequest); + idProof = idReq.decrypt(caPrivKey); + TpmIdentityRequest tempEC = new TpmIdentityRequest(endorsementCertificate); + ekCert = TpmUtils.certFromBytes(tempEC.decryptRaw(caPrivKey)); + //check out the endorsement certificate + //if the cert is good, issue challenge; if not return dud + try{ + if (prepEndorsementCaHashMap()) + ekCert.verify(endorsementCerts.get(ekCert.getIssuerDN())); + this.identityRequestChallenge = TpmUtils.createRandomBytes(32); + System.out.println("Endorsement Certificate passed validity check"); + } catch (SignatureException se){ + this.identityRequestChallenge = TpmUtils.hexStringToByteArray("00"); + System.out.println("Endorsement Certificate did not pass validity check"); + } + //check the rest of the identity proof + if(!idProof.checkValidity((RSAPublicKey)caPubCert.getPublicKey())){ + this.identityRequestChallenge = TpmUtils.hexStringToByteArray("00"); + System.out.println("Identity Request did not pass validity check"); + } + //encrypt the challenge and return + System.out.println("Phase 1 details:"); + System.out.println(" AIK blob: " + TpmUtils.byteArrayToHexString(idProof.getAik().toByteArray())); + System.out.println(" challenge: " + TpmUtils.byteArrayToHexString(this.identityRequestChallenge)); + byte[] toReturn = createReturn(idProof.getAik(), (RSAPublicKey)ekCert.getPublicKey(), this.identityRequestChallenge); + System.out.println(" toReturn: " + TpmUtils.byteArrayToHexString(toReturn)); + return toReturn; + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + public byte[] identityRequestSubmitResponse(byte[] identityRequestResponseToChallenge) { + try{ + if(!propFileLoaded) + propFileLoaded = readPropertiesFile(); + + //decrypt response + TpmIdentityRequest returnedIR = new TpmIdentityRequest(identityRequestResponseToChallenge); + byte[] returned = returnedIR.decryptRaw(caPrivKey); + //compare decrypted response to challenge + //if match, create AIC; else create failure code + byte[] preReturn = null; + if (TpmUtils.compareByteArrays(returned, this.identityRequestChallenge)){ + preReturn = TpmUtils.makeCert(idProof, caPrivKey, caPubCert, validityDays, 0).getEncoded(); + }else{ + preReturn = TpmUtils.hexStringToByteArray("00"); + } + //encrypt response and return + return createReturn(idProof.getAik(), (RSAPublicKey)ekCert.getPublicKey(), preReturn); + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + /** + * To be implement + */ + public byte [] requestGetEC(byte [] encryptedEkMod, byte [] encryptedSessionKey, int ecValidDays){ + try { + if(!propFileLoaded) + propFileLoaded = readPropertiesFile(); + + //Get endorsement p12 file from ClientFiles directory, should be optimized in the future + //String filePath = System.getProperty("catalina.base") + "/webapps/HisPrivacyCAWebServices2/"; + String filePath = "/var/lib/oat-appraiser/"; + String propertiesFileName = filePath + "ClientFiles/" + "OATprovisioner.properties"; + String EC_P12_FILE = "TpmEndorsmentP12"; + String EC_P12_PASSWORD = "EndorsementP12Pass"; + FileInputStream PropertyFile = null; + String TpmEndorsmentP12 = ""; + String EndorsementP12Pass = ""; + String FileLocation = ""; + String configPath = "/etc/oat-appraiser/"; + + Security.addProvider(new BouncyCastleProvider()); + try { + PropertyFile = new FileInputStream(propertiesFileName); + Properties HisProvisionerProperties = new Properties(); + HisProvisionerProperties.load(PropertyFile); + TpmEndorsmentP12 = HisProvisionerProperties.getProperty(EC_P12_FILE, ""); + EndorsementP12Pass = HisProvisionerProperties.getProperty(EC_P12_PASSWORD, ""); + } catch (FileNotFoundException e) { + System.out.println("Error finding HIS Provisioner properties file (HISprovisionier.properties)"); + } catch (IOException e) { + System.out.println("Error loading HIS Provisioner properties file (HISprovisionier.properties)"); + } + catch (NumberFormatException e) { + e.printStackTrace(); + } + + String errorString = "Properties file \"" + propertiesFileName + "\" contains errors:\n"; + boolean hasErrors = false; + if(TpmEndorsmentP12.length() == 0){ + errorString += " - \"TpmEndorsmentP12\" value must be the name of a valid PKCS#12 file\n"; + hasErrors = true; + } + if(EndorsementP12Pass.length() == 0){ + errorString += " - \"EndorsementP12Pass\" value must be the password for the TpmEndorsementP12 file\n"; + hasErrors = true; + } + + if(hasErrors){ + System.out.println(errorString); + System.exit(99); + return null; //need to be optimized here; + } + + //Generate Endorsement certificate + FileLocation = filePath + "ClientFiles"; + X509Certificate endorsementCert = TpmUtils.certFromP12(FileLocation + "/" + TpmEndorsmentP12, EndorsementP12Pass); + //X509Certificate endorsementCert = TpmUtils.certFromP12(TpmEndorsmentP12, EndorsementP12Pass); + RSAPrivateKey privKey = TpmUtils.privKeyFromP12(FileLocation + "/" + TpmEndorsmentP12, EndorsementP12Pass); + + byte[] ekMod = new byte[256]; + PropertyFile = new FileInputStream( configPath + "PrivacyCA.properties"); + Properties HisProvisionerProperties = new Properties(); + HisProvisionerProperties.load(PropertyFile); + EC_P12_FILE = "P12filename"; + EC_P12_PASSWORD = "P12password"; + String PrivacyCAP12 = HisProvisionerProperties.getProperty(EC_P12_FILE, ""); + String PrivacyCAP12Pass = HisProvisionerProperties.getProperty(EC_P12_PASSWORD, ""); + RSAPrivateKey privacyKey = TpmUtils.privKeyFromP12(filePath + "/" + PrivacyCAP12, PrivacyCAP12Pass); + + //phase 1: construct sessionKey + byte[] deskey = decryptRSA(encryptedSessionKey, privacyKey); + SecretKey sessionKey = new SecretKeySpec(deskey, 0, deskey.length, "DES"); + + //phase2: recover EK modular + System.out.println("before invoke........................"); + ekMod = decryptDES(encryptedEkMod, sessionKey); + + X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); + certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); + certGen.setIssuerDN(endorsementCert.getSubjectX500Principal()); + certGen.setNotBefore(new java.sql.Time(System.currentTimeMillis())); + Calendar expiry = Calendar.getInstance(); + expiry.add(Calendar.DAY_OF_YEAR, validityDays); + certGen.setNotAfter(expiry.getTime()); + certGen.setSubjectDN(new X500Principal("")); + byte [] pubExp = new byte[3]; + pubExp[0] = (byte)(0x01 & 0xff); + pubExp[1] = (byte)(0x00); + pubExp[2] = (byte)(0x01 & 0xff); + RSAPublicKey pubEk = TpmUtils.makePubKey(ekMod, pubExp); + certGen.setPublicKey(pubEk); + certGen.setSignatureAlgorithm("SHA1withRSA"); + certGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.SubjectAlternativeName, true, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "TPM EK Credential"))); + X509Certificate cert = certGen.generate(privKey, "BC"); + + //encrypt endorsement certification by session key, here we propose to use 3DES algorithm + byte[] encryptEndorsementCer = encryptDES(cert.getEncoded(), sessionKey); + return encryptEndorsementCer; + } catch (Exception e){ + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + private boolean readPropertiesFile () + throws UnrecoverableKeyException, + KeyStoreException, + NoSuchAlgorithmException, + CertificateException, + IOException, + javax.security.cert.CertificateException { + final String P12_FILE_NAME = "P12filename"; + final String P12_PASSWORD = "P12password"; + final String PRIVCA_CERT_VALIDITYDAYS = "PrivCaCertValiditydays"; + String P12filename = null; + String P12password = null; + int PrivCaCertValiditydays = 0; + String configPath = "/etc/oat-appraiser/"; + String filePath = "/var/lib/oat-appraiser/"; + String propertiesFileName = configPath + "PrivacyCA.properties"; + InputStream PropertyFile = null; + try { + PropertyFile = new FileInputStream(propertiesFileName); + Properties PrivacyCaProperties = new Properties(); + File checkFile = new File(propertiesFileName); + if (!checkFile.exists()){ + System.out.println("Error finding Privacy CA properties file: cannot continue. Please place properties file in: " + configPath + "/."); + return false; + } + checkFile = null; + PrivacyCaProperties.load(PropertyFile); + P12filename = filePath + PrivacyCaProperties.getProperty(P12_FILE_NAME, null); + P12password = PrivacyCaProperties.getProperty(P12_PASSWORD, null); + PrivCaCertValiditydays = Integer.parseInt(PrivacyCaProperties.getProperty(PRIVCA_CERT_VALIDITYDAYS, "0")); + } catch (FileNotFoundException e) { + System.out.println("Error finding Privacy CA properties file: cannot continue. Please place properties file in: " + configPath + "/."); + System.out.println(e.toString()); + return false; + } catch (IOException e) { + System.out.println("Error loading Privacy CA properties file: cannot continue."); + return false; + } + finally{ + try { + if (PropertyFile != null) + PropertyFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + //check to see if defaults are in use + boolean parameterMissing = false; + if (P12filename == null){ + System.out.println("Parameter \"P12filename\" missing from properties file: cannot continue."); + parameterMissing = true; + } + if (P12password == null){ + System.out.println("Parameter \"P12password\" missing from properties file: cannot continue."); + parameterMissing = true; + } + if (PrivCaCertValiditydays == 0){ + System.out.println("Parameter \"PrivcaCertValiditydays\" missing from properties file: cannot continue."); + parameterMissing = true; + } + if (parameterMissing){ + return false; + } + caPrivKey = TpmUtils.privKeyFromP12(P12filename, P12password); + caPubCert = TpmUtils.certFromP12(P12filename, P12password); + validityDays = PrivCaCertValiditydays; + return true; + } + private boolean prepEndorsementCaHashMap() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, javax.security.cert.CertificateException{ + //File endorsementCaDir = new File(System.getProperty("catalina.base") + "/webapps/HisPrivacyCAWebServices2/CaCerts"); + File endorsementCaDir = new File("/var/lib/oat-appraiser/CaCerts"); + String[] certList = endorsementCaDir.list(); + if(certList == null){ + System.out.println("Problem reading CaCerts directory!"); + return false; + } + endorsementCerts = new Hashtable(); + for(int i = 0; i < certList.length; i++){ + X509Certificate tempCert = TpmUtils.certFromFile(endorsementCaDir + "/" + certList[i]); + endorsementCerts.put((Principal)tempCert.getSubjectDN(), (RSAPublicKey)tempCert.getPublicKey()); + } + return true; + } + private static byte[] createReturn(TpmPubKey aik, RSAPublicKey pubEk, byte[] challengeRaw) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, TpmUnsignedConversionException, IOException{ + byte [] key = TpmUtils.createRandomBytes(16); + byte [] iv = TpmUtils.createRandomBytes(16); + byte [] encryptedBlob = TpmUtils.concat(iv, TpmUtils.TCGSymEncrypt(challengeRaw, key, iv)); + byte [] credSize = TpmUtils.intToByteArray(encryptedBlob.length); + + TpmSymmetricKey symKey = new TpmSymmetricKey(); + symKey.setKeyBlob(key); + symKey.setAlgorithmId(TpmKeyParams.TPM_ALG_AES); + symKey.setEncScheme(TpmKeyParams.TPM_ES_SYM_CBC_PKCS5PAD); + TpmKeyParams keyParms = new TpmKeyParams(); + keyParms.setAlgorithmId(TpmKeyParams.TPM_ALG_AES); + keyParms.setEncScheme(TpmKeyParams.TPM_ES_NONE); + keyParms.setSigScheme((short)0); + keyParms.setSubParams(null); + keyParms.setTrouSerSmode(true); + + byte [] asymBlob = TpmUtils.TCGAsymEncrypt(TpmUtils.concat(symKey.toByteArray(), TpmUtils.sha1hash(aik.toByteArray())), pubEk); + byte [] symBlob = TpmUtils.concat(TpmUtils.concat(credSize, keyParms.toByteArray()), encryptedBlob); + return TpmUtils.concat(asymBlob, symBlob); + } + + private static byte[] decryptRSA(byte[] src, PrivateKey rk) throws Exception { + Cipher cipher = Cipher.getInstance("RSA", new BouncyCastleProvider()); + cipher.init(Cipher.DECRYPT_MODE, rk); + return cipher.doFinal(src); + } + + private static byte[] decryptDES(byte[] text, SecretKey key) throws Exception { + Cipher cipher = Cipher.getInstance("DESede"); + cipher.init(Cipher.DECRYPT_MODE, key); + return cipher.doFinal(text); + } + + private static byte[] encryptDES(byte[] text, SecretKey key) throws Exception { + Cipher c = Cipher.getInstance("DESede"); + c.init(Cipher.ENCRYPT_MODE, key); + return c.doFinal(text); + } +} diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/HisPrivacyCAWebServices2LoadOnStartup.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/HisPrivacyCAWebServices2LoadOnStartup.java new file mode 100644 index 0000000..15a8851 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/HisPrivacyCAWebServices2LoadOnStartup.java @@ -0,0 +1,110 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * 锟�Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 锟�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. + * 锟�Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.webservices.hisPrivacyCAWebService2.server; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.security.KeyStore; +import java.security.cert.X509Certificate; +import java.util.Enumeration; +import java.util.StringTokenizer; + +import gov.niarl.his.privacyca.HisSetup; +import gov.niarl.his.privacyca.TpmUtils; +import gov.niarl.sal.webservices.hisWebService.client.HisWebServicesClientInvoker; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.HisEnrollmentWebService; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; + +/** + * This class allows code to be run when Tomcat first runs the HisPrivacyCAWebServices2 webapp. + * + * @author schawki + * + */ +public class HisPrivacyCAWebServices2LoadOnStartup extends HttpServlet{ + + private static final long serialVersionUID = 1L; + + @Override + /** + * This function will always run upon startup of the web service. The focus of the startup + * routine is to determine if this is the very first time the web service has run. It does + * this by looking for a PrivacyCA.p12 file, the holder of the private key and associated + * CA certificate used for signing AICs. If this file exists, nothing more is done. If the + * file does not exist, new files are created using the system's random number generator. + * + * The list of files generated is:
+ * - endorsement p12
+ * - Privacy CA p12
+ * - Privacy CA certificate
+ * - Privacy CA properties
+ * - HIS provisioner properties
+ * + * The trust store is copied from within Tomcat's directory structure and placed with the generated files. + */ + public void init() throws ServletException { + System.out.println("HisPrivacyCAWebServices2LoadOnStartup init()"); + String tomcatPath = System.getProperty("catalina.base") + "/webapps/HisPrivacyCAWebServices2/"; + String FileLocation = "/var/lib/oat-appraiser/"; + File test = new File(FileLocation + "PrivacyCA.p12"); + if(!test.exists()){ + FileInputStream fis = null; + try{ + // The functionality from the HisSetup class should be rebuilt here to avoid this call. + // Because this function is now only run from here, the HisSetup class is now considered deprecated. + HisSetup.main(null); + System.setProperty("javax.net.ssl.trustStore", FileLocation + "/Certificate/TrustStore.jks"); + KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); + fis = new FileInputStream(FileLocation + "/Certificate/TrustStore.jks"); + ks.load(fis, null); + Enumeration certList = ks.aliases(); + if (certList.hasMoreElements()){ + X509Certificate serverCert = (X509Certificate)ks.getCertificate(certList.nextElement()); + String certDN = serverCert.getSubjectX500Principal().getName("RFC1779"); + StringTokenizer st = new StringTokenizer(certDN, ","); + String certCN = ""; + while(st.hasMoreElements()){ + String line = st.nextToken(); + if(line.startsWith("CN")){ + certCN = line.subSequence(line.indexOf("=") + 1, line.length()).toString(); + break; + } + } + while(certCN.startsWith(" ")){ + certCN = certCN.subSequence(1, certCN.length()).toString(); + } + X509Certificate privCaCert = TpmUtils.certFromFile(FileLocation + "ClientFiles/PrivacyCA.cer"); + HisEnrollmentWebService hisEnrollmentWebService = HisWebServicesClientInvoker.getHisEnrollmentWebService("https://" + certCN + ":8443/HisWebServices"); + hisEnrollmentWebService.enrollHisMachine("_PrivacyCA", TpmUtils.PEMencodeCert(privCaCert)); + } + + }catch(Exception e){ + System.out.println(e.toString()); + } + + finally{ + try { + if (fis != null) + fis.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + super.init(); + } +} diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/package-info.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/package-info.java new file mode 100644 index 0000000..01e0785 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/gov/niarl/his/webservices/hisPrivacyCAWebService2/server/package-info.java @@ -0,0 +1,4 @@ +/** +

This package contains the server code for version 2 of the HIS Privacy CA.

+*/ +package gov.niarl.his.webservices.hisPrivacyCAWebService2.server; diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/src/package-info.java b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/package-info.java new file mode 100644 index 0000000..7676fa1 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/src/package-info.java @@ -0,0 +1,4 @@ +/** +

The default package is just used for holding test files. No code intended for use by the Privacy CA is maintained here.

+*/ + diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2 b/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2 new file mode 100644 index 0000000..549442a --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2 @@ -0,0 +1,34 @@ + + +Web Services + + +

Web Services

+ + + + + + + + + + + + + +
+Endpoint + +Information +
+
Service Name:{http://server.hisPrivacyCAWebService2.webservices.his.niarl.gov/}HisPrivacyCAWebService2FactoryServiceService
Port Name:{http://server.hisPrivacyCAWebService2.webservices.his.niarl.gov/}HisPrivacyCAWebService2FactoryServicePort
+
+
Address:hisPrivacyCAWebService2FactoryService
WSDL:hisPrivacyCAWebService2FactoryService?wsdl
Implementation class:gov.niarl.his.webservices.hisPrivacyCAWebService2.server.HisPrivacyCAWebService2FactoryService
+
+
Service Name:{http://server.hisPrivacyCAWebService2.webservices.his.niarl.gov/}HisPrivacyCAWebService2Service
Port Name:{http://server.hisPrivacyCAWebService2.webservices.his.niarl.gov/}HisPrivacyCAWebService2Port
+
+
Address:hisPrivacyCAWebService2
WSDL:hisPrivacyCAWebService2?wsdl
Implementation class:gov.niarl.his.webservices.hisPrivacyCAWebService2.server.HisPrivacyCAWebService2
+
+ + diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2.wsdl b/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2.wsdl new file mode 100644 index 0000000..f9d1382 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2.wsdl @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2.xsd-1 b/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2.xsd-1 new file mode 100644 index 0000000..5714392 --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2.xsd-1 @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2FactoryService b/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2FactoryService new file mode 100644 index 0000000..549442a --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2FactoryService @@ -0,0 +1,34 @@ + + +Web Services + + +

Web Services

+ + + + + + + + + + + + + +
+Endpoint + +Information +
+
Service Name:{http://server.hisPrivacyCAWebService2.webservices.his.niarl.gov/}HisPrivacyCAWebService2FactoryServiceService
Port Name:{http://server.hisPrivacyCAWebService2.webservices.his.niarl.gov/}HisPrivacyCAWebService2FactoryServicePort
+
+
Address:hisPrivacyCAWebService2FactoryService
WSDL:hisPrivacyCAWebService2FactoryService?wsdl
Implementation class:gov.niarl.his.webservices.hisPrivacyCAWebService2.server.HisPrivacyCAWebService2FactoryService
+
+
Service Name:{http://server.hisPrivacyCAWebService2.webservices.his.niarl.gov/}HisPrivacyCAWebService2Service
Port Name:{http://server.hisPrivacyCAWebService2.webservices.his.niarl.gov/}HisPrivacyCAWebService2Port
+
+
Address:hisPrivacyCAWebService2
WSDL:hisPrivacyCAWebService2?wsdl
Implementation class:gov.niarl.his.webservices.hisPrivacyCAWebService2.server.HisPrivacyCAWebService2
+
+ + diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2FactoryService.wsdl b/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2FactoryService.wsdl new file mode 100644 index 0000000..2b9e44e --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2FactoryService.wsdl @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2FactoryService.xsd-1 b/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2FactoryService.xsd-1 new file mode 100644 index 0000000..6febf6e --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/hisPrivacyCAWebService2FactoryService.xsd-1 @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/ws-addr.xsd b/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/ws-addr.xsd new file mode 100644 index 0000000..47362ed --- /dev/null +++ b/OpenAttestation/Source/HisPrivacyCAWebServices2/wsdl/ws-addr.xsd @@ -0,0 +1,137 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisWebServices/WEB-INF/sun-jaxws.xml b/OpenAttestation/Source/HisWebServices/WEB-INF/sun-jaxws.xml new file mode 100644 index 0000000..bfc0aaa --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/WEB-INF/sun-jaxws.xml @@ -0,0 +1,22 @@ + + + + + + + diff --git a/OpenAttestation/Source/HisWebServices/WEB-INF/web.xml b/OpenAttestation/Source/HisWebServices/WEB-INF/web.xml new file mode 100644 index 0000000..efe8b50 --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/WEB-INF/web.xml @@ -0,0 +1,41 @@ + + + + DB Connection + jdbc/oat + com.mchange.v2.c3p0.ComboPooledDataSource + Container + + + HisWebServices + + + + + com.sun.xml.ws.transport.http.servlet.WSServletContextListener + + + + + jaxWsServlet + + com.sun.xml.ws.transport.http.servlet.WSServlet + + 1 + + + + jaxWsServlet + + /* + + + + + HisWebServicesLoadOnStartup + + gov.niarl.sal.webservices.hisWebService.server.HisWebServicesLoadOnStartup + + 100 + + diff --git a/OpenAttestation/Source/HisWebServices/build.xml b/OpenAttestation/Source/HisWebServices/build.xml new file mode 100644 index 0000000..1908edd --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/build.xml @@ -0,0 +1,185 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisWebServices/src/OpenAttestation.properties b/OpenAttestation/Source/HisWebServices/src/OpenAttestation.properties new file mode 100644 index 0000000..760e58c --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/src/OpenAttestation.properties @@ -0,0 +1,9 @@ +ManifestWebServicesUrl=https://:8443/OpenAttestationManifestWebServices/V1.0/PCR +AttestationWebServicesUrl=https://:8443/OpenAttestationWebServices/V1.0 +DownloadIRWebServiceUrl=https://:8443/HisWebServices/hisDownloadReportService?wsdl +anticipationFactor=1.5 +minAttestInterval=300000 +maxIdleTime=7 +default_attest_interval=60000 +default_attest_timeout=60000 +TrustStore=/usr/lib/apache-tomcat-6.0.29/Certificate/TrustStore.jks diff --git a/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/client/HisWebServicesClientInvoker.java b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/client/HisWebServicesClientInvoker.java new file mode 100644 index 0000000..ab0d407 --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/client/HisWebServicesClientInvoker.java @@ -0,0 +1,121 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.sal.webservices.hisWebService.client; + +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.HisDownloadReportService; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.HisDownloadReportServiceService; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.HisEnrollmentWebService; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.HisEnrollmentWebServiceService; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.HisPollingWebService; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.HisPollingWebServiceService; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.HisWebService; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.HisWebServiceFactoryService; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.HisWebServiceFactoryServiceService; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.HisWebServiceService; + +import java.net.MalformedURLException; +import java.net.URL; + +import javax.xml.namespace.QName; + +/** + * Convenience class for clients to create web service objects. + * @author syelama + * @version Crossbow + * + */ +public class HisWebServicesClientInvoker { + HisWebService hisWebService; + + /** + * Creates a stateful HisWebService object. + * @param url The URL of the web application. + * @return A stateful HisWebService instance. + */ + public static HisWebService getHisWebService(String url) { + try { + HisWebServiceFactoryServiceService hisWebServiceFactoryServiceService = new HisWebServiceFactoryServiceService(new URL(url + "/hisWebServiceFactoryService?wsdl"), new QName("http://server.hisWebService.webservices.sal.niarl.gov/", "HisWebServiceFactoryServiceService")); + HisWebServiceFactoryService hisWebServiceFactoryService = hisWebServiceFactoryServiceService.getHisWebServiceFactoryServicePort(); + HisWebServiceService hisWebServiceService = new HisWebServiceService(new URL(url + "/hisWebService?wsdl"), new QName("http://server.hisWebService.webservices.sal.niarl.gov/", "HisWebServiceService")); + return hisWebServiceService.getPort(hisWebServiceFactoryService.getHisWebService(), HisWebService.class); + } catch (MalformedURLException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + /** + * Creates a HisEnrollmentWebService instance. + * @param url The URL of the web application. + * @return A HisEnrollmentWebService instance. + */ + public static HisEnrollmentWebService getHisEnrollmentWebService(String url) { + try { + HisEnrollmentWebServiceService hisEnrollmentWebServiceService = new HisEnrollmentWebServiceService(new URL(url + "/hisEnrollmentWebService?wsdl"), new QName("http://server.hisWebService.webservices.sal.niarl.gov/", "HisEnrollmentWebServiceService")); + return hisEnrollmentWebServiceService.getHisEnrollmentWebServicePort(); + } catch (MalformedURLException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + /** + * Creates a HisPollingWebService instance. + * @param url The URL of the web application. + * @return A HisPollingWebService instance. + */ + public static HisPollingWebService getHisPollingWebService(String url) { + try { + HisPollingWebServiceService hisPollingWebService = new HisPollingWebServiceService(new URL(url + "/hisPollingWebService?wsdl"), new QName("http://server.hisWebService.webservices.sal.niarl.gov/", "HisPollingWebServiceService")); + return hisPollingWebService.getHisPollingWebServicePort(); + } catch (MalformedURLException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + /** + * Creates a HisDownloadReportService instance. + * @param url The URL of the web application. + * @return A HisDownloadReportService instance. + */ + public static HisDownloadReportService getHisDownloadReportService(String url) { + try { + HisDownloadReportServiceService hisDownloadReportServiceService = new HisDownloadReportServiceService(new URL(url + "/hisDownloadReportService?wsdl"), new QName("http://server.hisWebService.webservices.sal.niarl.gov/", "HisDownloadReportServiceService")); + return hisDownloadReportServiceService.getHisDownloadReportServicePort(); + } catch (MalformedURLException e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } +} diff --git a/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/client/package-info.java b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/client/package-info.java new file mode 100644 index 0000000..117f45a --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/client/package-info.java @@ -0,0 +1,6 @@ +/** + * This package holds client utilities for web services. + * + * @version Crossbow + */ +package gov.niarl.sal.webservices.hisWebService.client; \ No newline at end of file diff --git a/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisDownloadReportService.java b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisDownloadReportService.java new file mode 100644 index 0000000..e163965 --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisDownloadReportService.java @@ -0,0 +1,106 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * (copyright) 2013 Politecnico di Torino, Italy + * TORSEC group -- http://security.polito.it + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.sal.webservices.hisWebService.server; + +import gov.niarl.hisAppraiser.hibernate.dao.HisAuditDao; +import gov.niarl.hisAppraiser.hibernate.domain.AuditLog; +import gov.niarl.hisAppraiser.hibernate.util.HibernateUtilHis; +import gov.niarl.hisAppraiser.integrityReport.HisReportUtil; +import gov.niarl.hisAppraiser.util.HisUtil; + +import java.io.IOException; +import java.io.FileNotFoundException; +import java.security.NoSuchAlgorithmException; +import java.util.InputMismatchException; + +import javax.annotation.Resource; +import javax.jws.WebParam; +import javax.jws.WebResult; +import javax.jws.WebService; +import javax.servlet.http.HttpServletResponse; +import javax.xml.ws.handler.MessageContext; +import javax.xml.ws.WebServiceContext; + +import org.apache.log4j.Logger; + +/** + * The HisDownloadReportService answers clients with the integrity + * report having the requested ID. + * @author Nicola Barresi + */ +@WebService +public class HisDownloadReportService { + private static Logger logger = Logger.getLogger(HisDownloadReportService.class); + + @Resource + private WebServiceContext ctx; + + /** + * This function returns the integrity report having the given ID. + * @param reportId ID of the report in DB + * @return The string of report having the given ID. + */ + @WebResult(name = "reportString") + public String fetchReport(@WebParam(name = "reportId") Long reportId, @WebParam(name = "partial") Boolean partial) { + logger.debug("fetchReport called with reportId:" + reportId); + String reportXML = ""; + HibernateUtilHis.beginTransaction(); + + MessageContext msgCtx = ctx.getMessageContext(); + HttpServletResponse response = (HttpServletResponse) msgCtx.get(MessageContext.SERVLET_RESPONSE); + + try { + reportXML = HisReportUtil.fetchReport(reportId, (partial == null) ? false : partial); + if (reportXML.equals("")) { + response.sendError(HttpServletResponse.SC_NOT_FOUND); + } + + HibernateUtilHis.commitTransaction(); + return reportXML; + } catch (Exception exception) { + HibernateUtilHis.rollbackTransaction(); + exception.printStackTrace(); + try { + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + } catch (IOException ex) { + ex.printStackTrace(); + } + throw new RuntimeException(exception); + } finally { + HibernateUtilHis.closeSession(); + } + } +} diff --git a/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisEnrollmentWebService.java b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisEnrollmentWebService.java new file mode 100644 index 0000000..3b41c9b --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisEnrollmentWebService.java @@ -0,0 +1,73 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.sal.webservices.hisWebService.server; + +import gov.niarl.hisAppraiser.hibernate.dao.HisMachineCertDao; +import gov.niarl.hisAppraiser.hibernate.util.HibernateUtilHis; + +import javax.jws.WebParam; +import javax.jws.WebService; + +/** + * The HisEnrollmentWebService enrolls clients into the machine table and + * enables integrity reports to be received and validated from the client. + * @author syelama + * @version Crossbow + * + */ +@WebService +public class HisEnrollmentWebService { + /** + * Enrolls a machine. + * @param machineName Name of the machine to be enrolled. + * @param machineCertPEM Machine AIK certificate used for integrity + * reports. + */ + public void enrollHisMachine(@WebParam(name = "machineName") String machineName, @WebParam(name = "machineCertPEM") String machineCertPEM) { + try { + HibernateUtilHis.beginTransaction(); + + machineName = machineName.toLowerCase(); + HisMachineCertDao hisMachineCertDao = new HisMachineCertDao(); + hisMachineCertDao.createMachineCert(machineName, machineCertPEM); + + HibernateUtilHis.commitTransaction(); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e.toString()); + } finally { + HibernateUtilHis.closeSession(); + } + } +} diff --git a/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisPollingWebService.java b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisPollingWebService.java new file mode 100644 index 0000000..33772b5 --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisPollingWebService.java @@ -0,0 +1,134 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.sal.webservices.hisWebService.server; + +import gov.niarl.hisAppraiser.hibernate.dao.*; +import gov.niarl.hisAppraiser.hibernate.domain.AttestRequest; +import gov.niarl.hisAppraiser.hibernate.util.HibernateUtilHis; +import gov.niarl.sal.webservices.hisWebService.server.domain.ActionConverter; +import gov.niarl.sal.webservices.hisWebService.server.domain.ActionDelay; +import gov.niarl.sal.webservices.hisWebService.server.domain.ActionDelay.Action; + +import java.util.Date; + +import javax.jws.WebParam; +import javax.jws.WebResult; +import javax.jws.WebService; + +import org.apache.log4j.Logger; + +/** + * The HisPollingWebService answers clients polls with their next actions. + * @author syelama + * @version Crossbow + * + */ +@WebService +public class HisPollingWebService { + private static Logger logger = Logger.getLogger(HisPollingWebService.class); + + /** + * This function returns the pending action to machines and resets + * the fields in the database. + * @param machineName Name of the machine + * @return An object containing information about the action to be taken. + */ + @WebResult(name = "nextAction") + public ActionDelay getNextAction(@WebParam(name = "machineName") String machineName) { + logger.debug("getNextAction called with arguments machineName=" + machineName); + Action action = Action.DO_NOTHING; + String args = ""; + try { + HibernateUtilHis.beginTransaction(); + AttestDao attestDao = new AttestDao(); + attestDao.disableUnusedRequests(machineName); + AttestRequest attestRequest = attestDao.getPendingRequests(machineName, false).get(0); + action = ActionConverter.getActionFromInt(attestRequest.getNextAction() == null? ActionConverter.getIntFromAction(Action.DO_NOTHING) : attestRequest.getNextAction()); + + if (attestRequest.getId()!= null){ + /* + * If the attestation request is periodic two + * operation are needed: + * - action must be set to SEND_REPORT, because + * periodic request don't use action written on DB; + * - requestTime must be updated in order to known + * the time needed for attesting the host + * (validateTime - requestTime). + */ + if (attestRequest.getThreshold() != null) { + attestRequest.setRequestTime(new Date()); + action = Action.SEND_REPORT; + } + attestRequest.setNextAction(ActionConverter.getIntFromAction(Action.DO_NOTHING)); + attestRequest.setIsConsumedByPollingWS(true); + attestDao.updateRequest(attestRequest); + } + HibernateUtilHis.commitTransaction(); + }catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e.toString()); + }finally{ + HibernateUtilHis.closeSession(); + } + return new ActionDelay(action, HisSystemConstants.DEFAULT_DELAY, args); + } + + /** + * Below is the original polling code from NIARL. + */ +// Action action = Action.DO_NOTHING; +// String args = ""; +// try { +// HibernateUtilHis.beginTransaction(); +// +// HisMachineCertDao hisMachineCertDao = new HisMachineCertDao(); +// MachineCert machineCert = hisMachineCertDao.getMachineCert(machineName); +// action = ActionConverter.getActionFromInt(machineCert.getNextAction() == null ? ActionConverter.getIntFromAction(Action.DO_NOTHING) : machineCert.getNextAction()); +// args = machineCert.getPollArgs() == null ? "" : machineCert.getPollArgs(); +// +// machineCert.setNextAction(ActionConverter.getIntFromAction(Action.DO_NOTHING)); +// machineCert.setLastPoll(new Date()); +// machineCert.setPollArgs(""); +// +// HibernateUtilHis.commitTransaction(); +// } catch (Exception e) { +// HibernateUtilHis.rollbackTransaction(); +// e.printStackTrace(); +// throw new RuntimeException(e.toString()); +// } finally { +// HibernateUtilHis.closeSession(); +// } +// return new ActionDelay(action, HisSystemConstants.DEFAULT_DELAY, args); +// } +} diff --git a/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisWebService.java b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisWebService.java new file mode 100644 index 0000000..d0cf82b --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisWebService.java @@ -0,0 +1,143 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.sal.webservices.hisWebService.server; + +import gov.niarl.hisAppraiser.Constants; +import gov.niarl.hisAppraiser.hibernate.dao.AttestDao; +import gov.niarl.hisAppraiser.hibernate.dao.HisAuditDao; +import gov.niarl.hisAppraiser.hibernate.domain.AuditLog; +import gov.niarl.hisAppraiser.hibernate.util.HibernateUtilHis; +import gov.niarl.hisAppraiser.integrityReport.HisReportUtil; +import gov.niarl.hisAppraiser.util.HisUtil; +import gov.niarl.sal.webservices.hisWebService.server.domain.NonceSelect; + +import javax.jws.WebMethod; +import javax.jws.WebParam; +import javax.jws.WebResult; +import javax.jws.WebService; +import javax.xml.ws.soap.Addressing; + +import org.apache.log4j.Logger; + +import com.sun.xml.ws.developer.Stateful; +import com.sun.xml.ws.developer.StatefulWebServiceManager; + +/** + * Stateful web service to request and consume integrity reports. + * enables integrity reports to be received and validated from the client. + * @author syelama + * @version Crossbow + * + */ +@Stateful +@WebService +@Addressing +public class HisWebService { + private static Logger logger = Logger.getLogger(HisWebService.class); + /** + * Needed for stateful web services. StatefulWebServiceManager javadoc + */ + public static StatefulWebServiceManager manager; + + String machineName; + String userName; + NonceSelect nonceSelect; + + /** + * Generates information needed by the clients to generate reports. + * @param machineName Name of the machine. + * @param userName User's ID or name. + * @return Information needed by the clients to submit an integrity + * report. + */ + @WebResult(name = "nonceSelect") + public NonceSelect getNonce(@WebParam(name = "machineName") String machineName, @WebParam(name = "userName") String userName) { + logger.debug("getNonce called with machine name:" + machineName + " userName:" + userName); + HisAuditDao auditLogDao = new HisAuditDao(); + AuditLog lastAuditLog = auditLogDao.getLastAuditLog(machineName); + this.machineName = machineName; + this.userName = userName; + nonceSelect = new NonceSelect(); + nonceSelect.setNonce(HisUtil.generateSecureRandom(20)); + nonceSelect.setSelect(HisUtil.unHexString(Constants.PCR_SELECT)); + nonceSelect.setQuote(NonceSelect.Quote.QUOTE1); + + String currentIMLMask = new AttestDao().getPcrIMLMask(machineName); + nonceSelect.setReportType("start"); + if (Constants.SCALABILITY && lastAuditLog != null && lastAuditLog.getReport() != null + && !lastAuditLog.getFirstReport().equals((long) -1) && lastAuditLog.getPcrIMLMask().equals(currentIMLMask)) { + nonceSelect.setReportType("continue"); + } + return nonceSelect; + } + + /** + * Receives and processes an integrity report. + * @param integrityReport XML integrity report sent by the clients. + */ + public void postIntegrityReport(@WebParam(name = "integrityReport") String integrityReport) { + logger.debug("postIntegrityReport called with integrityReport:" + integrityReport); + HibernateUtilHis.beginTransaction(); + try { + + HisReportUtil.submitReport(userName, integrityReport, nonceSelect.getNonce(), nonceSelect.getSelect(), machineName); + + HibernateUtilHis.commitTransaction(); + } catch (Exception exception) { + HibernateUtilHis.rollbackTransaction(); + exception.printStackTrace(); + throw new RuntimeException(exception); + } finally { + HibernateUtilHis.closeSession(); + manager.unexport(this); + } + } + + /** + * Needed for stateful web services. + * @return Related StatefulWebServiceManager. + */ + @WebMethod(exclude = true) + public static StatefulWebServiceManager getManager() { + return manager; + } + + /** + * Needed for stateful web services. + * @param manager Related StatefulWebServiceManager. + */ + @WebMethod(exclude = true) + public static void setManager(StatefulWebServiceManager manager) { + HisWebService.manager = manager; + } +} diff --git a/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisWebServiceFactoryService.java b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisWebServiceFactoryService.java new file mode 100644 index 0000000..4a3cf9a --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisWebServiceFactoryService.java @@ -0,0 +1,62 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.sal.webservices.hisWebService.server; + +import javax.jws.WebService; +import javax.xml.ws.wsaddressing.W3CEndpointReference; + +/** + * Class needed to create the stateful HisWebService. + * @author syelama + * @version Crossbow + * + */ +@WebService +public class HisWebServiceFactoryService { + static boolean setTimeout = false; + + /** + * Creates a W3CEndpointReference needed by JAX-WS web services. + * @return A reference to a stateful HisWebService. + */ + public W3CEndpointReference getHisWebService() { + + if (!setTimeout) { + // 180 second timeout + HisWebService hisWebService = new HisWebService(); + hisWebService.manager.setTimeout(180 * 1000, null); + setTimeout = true; + } + return HisWebService.manager.export(new HisWebService()); + } +} \ No newline at end of file diff --git a/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisWebServicesLoadOnStartup.java b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisWebServicesLoadOnStartup.java new file mode 100644 index 0000000..d07532e --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/HisWebServicesLoadOnStartup.java @@ -0,0 +1,64 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.sal.webservices.hisWebService.server; + +import gov.niarl.hisAppraiser.Constants; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServlet; + +import org.apache.log4j.Logger; + +/** + * This class does functions needed at web server startup. + * @author syelama + * @version Crossbow + * + */ +public class HisWebServicesLoadOnStartup extends HttpServlet { + + private static Logger logger = Logger.getLogger(HisWebServicesLoadOnStartup.class); + private static final long serialVersionUID = 1L; + + /* (non-Javadoc) + * @see javax.servlet.GenericServlet#init() + */ + @Override + public void init() throws ServletException { + logger.info("Loading HIS web services."); + logger.info("Loading constants including PCR alert configuration."); + Constants.ALERT_CONFIGURATION.printSummary(); + super.init(); + } + +} diff --git a/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/domain/ActionConverter.java b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/domain/ActionConverter.java new file mode 100644 index 0000000..4c5dafa --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/domain/ActionConverter.java @@ -0,0 +1,81 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.sal.webservices.hisWebService.server.domain; + +import gov.niarl.sal.webservices.hisWebService.server.domain.ActionDelay.Action; + +import java.util.HashMap; + +/** + * Utility class to help with Action enumeration serialization and + * de-serialization. + * @author syelama + * @version Crossbow + * + */ +public class ActionConverter { + private static HashMap integerActionHashMap = new HashMap() { + { + put(0, Action.DO_NOTHING); + put(1, Action.SEND_REPORT); + put(2, Action.REBOOT); + put(3, Action.VERIFY_CLIENT); + put(4, Action.CLEAN_CLIENT); + } + }; + + private static HashMap actionIntegerHashMap = new HashMap(); + static { + for (Integer integer : integerActionHashMap.keySet()) { + actionIntegerHashMap.put(integerActionHashMap.get(integer), integer); + } + } + + /** + * Converts a integer into an Action enumeration. + * @param i Integer linked to an action. + * @return Action enumeration related to an integer. + */ + public static Action getActionFromInt(int i) { + return integerActionHashMap.get(i) == null ? Action.DO_NOTHING : integerActionHashMap.get(i); + } + + /** + * Converts an Action enumeration into the related integer. + * @param action Enumeration value. + * @return Integer related to the enumeration. + */ + public static int getIntFromAction(Action action) { + return actionIntegerHashMap.get(action); + } +} \ No newline at end of file diff --git a/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/domain/ActionDelay.java b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/domain/ActionDelay.java new file mode 100644 index 0000000..79ea5f9 --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/domain/ActionDelay.java @@ -0,0 +1,116 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.sal.webservices.hisWebService.server.domain; + +/** + * ActionDelay is returned by the HisPollingWebService and contains + * information to be acted on by the clients. + * @author syelama + * @version Crossbow + * + */ +public class ActionDelay { + /** + * Enumeration containing actions to be taken by the clients. + */ + public static enum Action { + DO_NOTHING, SEND_REPORT, REBOOT, VERIFY_CLIENT, CLEAN_CLIENT + } + + Action action; + long delayMilliseconds; + String args; + + /** + * Default constructor with zero arguments. + */ + public ActionDelay() { + super(); + } + + /** + * Creates an ActionDelay and sets all elements at once. + * @param action An action from the action enumeration. + * @param delayMilliseconds Milliseconds for the client to wait for + * doing another poll. + * @param args Arguments the client may need to complete an action. + */ + public ActionDelay(Action action, long delayMilliseconds, String args) { + super(); + this.action = action; + this.delayMilliseconds = delayMilliseconds; + this.args = args; + } + + /** + * @return the action + */ + public Action getAction() { + return action; + } + + /** + * @param action the action to set + */ + public void setAction(Action action) { + this.action = action; + } + + /** + * @return the delayMilliseconds + */ + public long getDelayMilliseconds() { + return delayMilliseconds; + } + + /** + * @param delayMilliseconds the delayMilliseconds to set + */ + public void setDelayMilliseconds(long delayMilliseconds) { + this.delayMilliseconds = delayMilliseconds; + } + + /** + * @return the args + */ + public String getArgs() { + return args; + } + + /** + * @param args the args to set + */ + public void setArgs(String args) { + this.args = args; + } +} diff --git a/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/domain/NonceSelect.java b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/domain/NonceSelect.java new file mode 100644 index 0000000..67b13a9 --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/domain/NonceSelect.java @@ -0,0 +1,110 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 gov.niarl.sal.webservices.hisWebService.server.domain; + +/** + * This class is return from the HisWebService and contains information + * needed by the client to generate integrity reports. + * @author syelama + * @version Crossbow + * + */ +public class NonceSelect { + /** + * Enumeration containing quote format. + */ + public static enum Quote { + QUOTE1, QUOTE2 + }; + + Quote quote; + byte[] nonce; + byte[] select; + String reportType; + + /** + * @return the quote + */ + public Quote getQuote() { + return quote; + } + + /** + * @param quote the quote to set + */ + public void setQuote(Quote quote) { + this.quote = quote; + } + + /** + * @return the nonce + */ + public byte[] getNonce() { + return nonce; + } + + /** + * @param nonce the nonce to set + */ + public void setNonce(byte[] nonce) { + this.nonce = nonce; + } + + /** + * @return the select + */ + public byte[] getSelect() { + return select; + } + + /** + * @param select the select to set + */ + public void setSelect(byte[] select) { + this.select = select; + } + + /** + * @return the reportType flag + */ + public String getReportType() { + return reportType; + } + + /** + * @param reportType the reportType to set + */ + public void setReportType(String reportType) { + this.reportType = reportType; + } +} diff --git a/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/domain/package-info.java b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/domain/package-info.java new file mode 100644 index 0000000..06ffa6b --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/domain/package-info.java @@ -0,0 +1,6 @@ +/** + * This package holds beans used in parameters and returns for web services. + * + * @version Crossbow + */ +package gov.niarl.sal.webservices.hisWebService.server.domain; \ No newline at end of file diff --git a/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/package-info.java b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/package-info.java new file mode 100644 index 0000000..47401de --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/src/gov/niarl/sal/webservices/hisWebService/server/package-info.java @@ -0,0 +1,6 @@ +/** + * This package holds definitions of the JAX-WS web services used for HIS. + * + * @version Crossbow + */ +package gov.niarl.sal.webservices.hisWebService.server; \ No newline at end of file diff --git a/OpenAttestation/Source/HisWebServices/src/overview.html b/OpenAttestation/Source/HisWebServices/src/overview.html new file mode 100644 index 0000000..b49753e --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/src/overview.html @@ -0,0 +1,9 @@ + + +This project creates a web application archive and a Java archive to be +used by clients attempting to invoke the JAX-WS web services produced in +the .war file. The web services in this project serve as the +presentation layer for the functionality introduced in the other +appraiser projects. + + diff --git a/OpenAttestation/Source/HisWebServices/wsdl/hisDownloadReportService b/OpenAttestation/Source/HisWebServices/wsdl/hisDownloadReportService new file mode 100644 index 0000000..f329efc --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/wsdl/hisDownloadReportService @@ -0,0 +1,58 @@ + + +Web Services + + +

Web Services

+ + + + + + + + + + + + + + + + + + + + + + + + + +
+Endpoint + +Information +
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServiceFactoryServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServiceFactoryServicePort
+
+
Address:hisWebServiceFactoryService
WSDL:hisWebServiceFactoryService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisWebServiceFactoryService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServicePort
+
+
Address:hisWebService
WSDL:hisWebService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisWebService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisEnrollmentWebServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisEnrollmentWebServicePort
+
+
Address:hisEnrollmentWebService
WSDL:hisEnrollmentWebService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisEnrollmentWebService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisPollingWebServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisPollingWebServicePort
+
+
Address:hisPollingWebService
WSDL:hisPollingWebService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisPollingWebService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisDownloadReportService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisDownloadReportService
+
+
Address:hisDownloadReportService
WSDL:hisDownloadReportService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisDownloadReportService
+
+ + diff --git a/OpenAttestation/Source/HisWebServices/wsdl/hisDownloadReportService.wsdl b/OpenAttestation/Source/HisWebServices/wsdl/hisDownloadReportService.wsdl new file mode 100644 index 0000000..29ec9ee --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/wsdl/hisDownloadReportService.wsdl @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisWebServices/wsdl/hisDownloadReportService.xsd=1 b/OpenAttestation/Source/HisWebServices/wsdl/hisDownloadReportService.xsd=1 new file mode 100644 index 0000000..4bd4538 --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/wsdl/hisDownloadReportService.xsd=1 @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisWebServices/wsdl/hisEnrollmentWebService b/OpenAttestation/Source/HisWebServices/wsdl/hisEnrollmentWebService new file mode 100644 index 0000000..f329efc --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/wsdl/hisEnrollmentWebService @@ -0,0 +1,58 @@ + + +Web Services + + +

Web Services

+ + + + + + + + + + + + + + + + + + + + + + + + + +
+Endpoint + +Information +
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServiceFactoryServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServiceFactoryServicePort
+
+
Address:hisWebServiceFactoryService
WSDL:hisWebServiceFactoryService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisWebServiceFactoryService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServicePort
+
+
Address:hisWebService
WSDL:hisWebService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisWebService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisEnrollmentWebServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisEnrollmentWebServicePort
+
+
Address:hisEnrollmentWebService
WSDL:hisEnrollmentWebService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisEnrollmentWebService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisPollingWebServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisPollingWebServicePort
+
+
Address:hisPollingWebService
WSDL:hisPollingWebService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisPollingWebService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisDownloadReportService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisDownloadReportService
+
+
Address:hisDownloadReportService
WSDL:hisDownloadReportService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisDownloadReportService
+
+ + diff --git a/OpenAttestation/Source/HisWebServices/wsdl/hisEnrollmentWebService.wsdl b/OpenAttestation/Source/HisWebServices/wsdl/hisEnrollmentWebService.wsdl new file mode 100644 index 0000000..e6b2ceb --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/wsdl/hisEnrollmentWebService.wsdl @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisWebServices/wsdl/hisEnrollmentWebService.xsd=1 b/OpenAttestation/Source/HisWebServices/wsdl/hisEnrollmentWebService.xsd=1 new file mode 100644 index 0000000..61b0972 --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/wsdl/hisEnrollmentWebService.xsd=1 @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisWebServices/wsdl/hisPollingWebService b/OpenAttestation/Source/HisWebServices/wsdl/hisPollingWebService new file mode 100644 index 0000000..f329efc --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/wsdl/hisPollingWebService @@ -0,0 +1,58 @@ + + +Web Services + + +

Web Services

+ + + + + + + + + + + + + + + + + + + + + + + + + +
+Endpoint + +Information +
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServiceFactoryServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServiceFactoryServicePort
+
+
Address:hisWebServiceFactoryService
WSDL:hisWebServiceFactoryService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisWebServiceFactoryService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServicePort
+
+
Address:hisWebService
WSDL:hisWebService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisWebService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisEnrollmentWebServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisEnrollmentWebServicePort
+
+
Address:hisEnrollmentWebService
WSDL:hisEnrollmentWebService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisEnrollmentWebService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisPollingWebServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisPollingWebServicePort
+
+
Address:hisPollingWebService
WSDL:hisPollingWebService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisPollingWebService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisDownloadReportService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisDownloadReportService
+
+
Address:hisDownloadReportService
WSDL:hisDownloadReportService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisDownloadReportService
+
+ + diff --git a/OpenAttestation/Source/HisWebServices/wsdl/hisPollingWebService.wsdl b/OpenAttestation/Source/HisWebServices/wsdl/hisPollingWebService.wsdl new file mode 100644 index 0000000..2d5d1a3 --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/wsdl/hisPollingWebService.wsdl @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisWebServices/wsdl/hisPollingWebService.xsd=1 b/OpenAttestation/Source/HisWebServices/wsdl/hisPollingWebService.xsd=1 new file mode 100644 index 0000000..0e15e52 --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/wsdl/hisPollingWebService.xsd=1 @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/HisWebServices/wsdl/hisWebService b/OpenAttestation/Source/HisWebServices/wsdl/hisWebService new file mode 100644 index 0000000..f329efc --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/wsdl/hisWebService @@ -0,0 +1,58 @@ + + +Web Services + + +

Web Services

+ + + + + + + + + + + + + + + + + + + + + + + + + +
+Endpoint + +Information +
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServiceFactoryServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServiceFactoryServicePort
+
+
Address:hisWebServiceFactoryService
WSDL:hisWebServiceFactoryService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisWebServiceFactoryService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServicePort
+
+
Address:hisWebService
WSDL:hisWebService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisWebService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisEnrollmentWebServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisEnrollmentWebServicePort
+
+
Address:hisEnrollmentWebService
WSDL:hisEnrollmentWebService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisEnrollmentWebService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisPollingWebServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisPollingWebServicePort
+
+
Address:hisPollingWebService
WSDL:hisPollingWebService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisPollingWebService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisDownloadReportService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisDownloadReportService
+
+
Address:hisDownloadReportService
WSDL:hisDownloadReportService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisDownloadReportService
+
+ + diff --git a/OpenAttestation/Source/HisWebServices/wsdl/hisWebService.wsdl b/OpenAttestation/Source/HisWebServices/wsdl/hisWebService.wsdl new file mode 100644 index 0000000..21d2500 --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/wsdl/hisWebService.wsdl @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisWebServices/wsdl/hisWebService.xsd=1 b/OpenAttestation/Source/HisWebServices/wsdl/hisWebService.xsd=1 new file mode 100644 index 0000000..31b018a --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/wsdl/hisWebService.xsd=1 @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisWebServices/wsdl/hisWebServiceFactoryService b/OpenAttestation/Source/HisWebServices/wsdl/hisWebServiceFactoryService new file mode 100644 index 0000000..f329efc --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/wsdl/hisWebServiceFactoryService @@ -0,0 +1,58 @@ + + +Web Services + + +

Web Services

+ + + + + + + + + + + + + + + + + + + + + + + + + +
+Endpoint + +Information +
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServiceFactoryServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServiceFactoryServicePort
+
+
Address:hisWebServiceFactoryService
WSDL:hisWebServiceFactoryService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisWebServiceFactoryService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisWebServicePort
+
+
Address:hisWebService
WSDL:hisWebService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisWebService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisEnrollmentWebServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisEnrollmentWebServicePort
+
+
Address:hisEnrollmentWebService
WSDL:hisEnrollmentWebService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisEnrollmentWebService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisPollingWebServiceService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisPollingWebServicePort
+
+
Address:hisPollingWebService
WSDL:hisPollingWebService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisPollingWebService
+
+
Service Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisDownloadReportService
Port Name:{http://server.hisWebService.webservices.sal.niarl.gov/}HisDownloadReportService
+
+
Address:hisDownloadReportService
WSDL:hisDownloadReportService.wsdl
Implementation class:gov.niarl.sal.webservices.hisWebService.server.HisDownloadReportService
+
+ + diff --git a/OpenAttestation/Source/HisWebServices/wsdl/hisWebServiceFactoryService.wsdl b/OpenAttestation/Source/HisWebServices/wsdl/hisWebServiceFactoryService.wsdl new file mode 100644 index 0000000..a37d652 --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/wsdl/hisWebServiceFactoryService.wsdl @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisWebServices/wsdl/hisWebServiceFactoryService.xsd=1 b/OpenAttestation/Source/HisWebServices/wsdl/hisWebServiceFactoryService.xsd=1 new file mode 100644 index 0000000..a8f827e --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/wsdl/hisWebServiceFactoryService.xsd=1 @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/HisWebServices/wsdl/ws-addr.xsd b/OpenAttestation/Source/HisWebServices/wsdl/ws-addr.xsd new file mode 100644 index 0000000..47362ed --- /dev/null +++ b/OpenAttestation/Source/HisWebServices/wsdl/ws-addr.xsd @@ -0,0 +1,137 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/Portal/Portal_build.txt b/OpenAttestation/Source/Portal/Portal_build.txt new file mode 100644 index 0000000..7e0dcba --- /dev/null +++ b/OpenAttestation/Source/Portal/Portal_build.txt @@ -0,0 +1,11 @@ +************** +* Web Portal * +************** + +BUILD INSTRUCTIONS + +The HIS Web Portal needs to be placed in /var/www/html on a Linux server. It depends on the installation of the HIS Appraiser to operate. The HIS Appraiser sets up the MySQL database, installs Apache, and installs PHP. + +Following the installation of a HIS Appraiser the Web Portal can be placed in /var/www/html. The only change that is needed is to edit the dbconnect.php file in the includes folder. This file needs to be populated with MySQL access information. + +Optionally, htaccess files can be loaded into folders created by the HIS Web Portal. These files are not provided by default. The HIS Appraiser does turn on the various Apache configuration flags that enable their use. diff --git a/OpenAttestation/Source/Portal/admin/updatealert.php b/OpenAttestation/Source/Portal/admin/updatealert.php new file mode 100644 index 0000000..370ca2b --- /dev/null +++ b/OpenAttestation/Source/Portal/admin/updatealert.php @@ -0,0 +1,94 @@ + + + + + HIS Alert Update Page + + + 0 AND strlen($_POST["assignedTo"]) < 24) + { + $assignedTo = mysql_real_escape_string($_POST["assignedTo"]); //combat SQL injection attacks with mysql_real_escape_string() + } + else + { + die("Assigned To is invalid."); + } + + //CHECK THE COMMENTS FIELD + $comments = mysql_real_escape_string($_POST["comments"]); //really can't validate these because it's free-form text so just protect against SQL injection + + //UPDATE DATABASE + $result = mysql_query('UPDATE alerts SET assignedTo = "' . $assignedTo . '", status = "' . $status . '", comments = "' . $comments . '" WHERE id = ' . $id); + if(!$result) + { + die("Error updating database."); //SQL query failed so stop execution + } + echo "

Database updated successfully. Please wait to be redirected or use your browser's back button.

"; + + header("refresh: 2; ../alerts.php"); //automatically forward user to the main alerts page + } + else + { + //A FIELD IS MISSING SO REJECT ALL INPUTS + echo "

Form submission is invalid. Please use your browser's back button.

"; + } + ?> + + + diff --git a/OpenAttestation/Source/Portal/ajax_load.php b/OpenAttestation/Source/Portal/ajax_load.php new file mode 100644 index 0000000..2b011be --- /dev/null +++ b/OpenAttestation/Source/Portal/ajax_load.php @@ -0,0 +1,127 @@ + need all three paramters"; + exit (0); +} +?> + + + + No record found for $CN "; + } else { + $analysis_request = $row['analysis_request']; + $host_name = $row['host_name']; + $analysis_results = $row['analysis_results']; + $validate_time = strtotime($row['validate_time']); + $now = strtotime(date('Y-m-d H:i:s')); + $diff = $now - $validate_time; + + $unknow_dgsts = getUnknownDigests($report["id"]); + foreach ($unknow_dgsts as $line){ + $image = explode(" ", $line); + if(stristr($image[1],"load)")){ + $res_level = $image[3]; + } + } + + if (strcmp($DGST,$cert['description'])!=0) { + echo "

Certificates dismatch

"; + } else if ($diff > 25 or empty($analysis_results)){ + echo "

Stale result!

"; + echo "

Last validate on " . $row['validate_time'] . "

"; + } else { + if (((stristr($row['analysis_results'], "|true|")) and (stristr($row['analysis_results'],"|ANALYSIS_COMPLETED|0|"))) or $LEVEL<=$res_level){ + echo "

" . $CN . " is TRUSTED!

"; + echo "

Last validate on " . $row['validate_time'] . "

"; + } else { + echo "

" . $CN . " is UNTRUSTED!

"; + echo "

Last validate on " . $row['validate_time'] . "

"; + } + + echo ""; + echo ""; + echo ""; + echo ""; + + echo ""; + echo ""; + echo ""; + + echo ""; + echo ""; + echo ""; + + echo ""; + echo ""; + echo ""; + echo "
" . $row['host_name'] . "
" . $row['analysis_request'] . "
" . $row['analysis_results'] . "
" . $row['validate_time'] . "
"; + echo " Integrity Report "; + } + } +} +?> + + diff --git a/OpenAttestation/Source/Portal/alert.php b/OpenAttestation/Source/Portal/alert.php new file mode 100644 index 0000000..9aacd8b --- /dev/null +++ b/OpenAttestation/Source/Portal/alert.php @@ -0,0 +1,225 @@ + 0 AND $_GET["id"] < 4294967295) +{ + //alert id has validated so set up the variable + $id = $_GET["id"]; +} +else +{ + //don't set a default if the alert id is bad. Just stop execution and show an error + die("Invalid ID number."); +} + +//query the alerts and reports table for the data relating to this alert id +$row = mysql_fetch_array(mysql_query("SELECT alerts.id AS aid, alerts.*, audit_log.* FROM alerts JOIN audit_log ON alerts.audit_fk = audit_log.id WHERE alerts.id = " . $id)); + +//now go query for the details of the report submitted before the id number of the one above so we can get the previous pcr values +$previous = mysql_fetch_array(mysql_query("SELECT * FROM audit_log WHERE machine_name = '" . $row["machine_name"] . "' AND id < " . $row["audit_fk"] . " ORDER BY id DESC LIMIT 0,1")); +?> + + + + + HIS Alert Details + + + +
+ +
+
+
+
+

Alert Details

+
+ + + + + + + + + + + + + + + + + +
IDStatusAssigned To
" />" />
Comments
+
+ + + +
+
+ +

Report Details

+ + + + + + + + + + + + + + + + + + + \n"; + +//DISPLAY PCR ANALYSIS SECTION IFF THERE ARE PREVIOUS DIFFERENCES +if($row["previous_differences"] != NULL) +{ + echo " + + + + \n"; + + //DISPLAY PCR ANALYSIS SECTION SPECIFIC CHANGES + $token = strtok($row["previous_differences"], "|"); //use a token to parse through the list of previous differences. This is in the format |n| for each difference where n is the PCR index + while ($token !== false) + { + echo " \n"; + + //DISPLAY PCR INDEX WITH HELPFUL TOOLTIP + switch($token) + { + case 0: + case 1: + echo " \n"; + break; + case 2: + case 3: + echo " \n"; + break; + case 4: + echo " \n"; + break; + case 5: + echo " \n"; + break; + case 8: + case 9: + echo " \n"; + break; + case 10: + echo " \n"; + break; + case 11: + echo " \n"; + break; + case 12: + echo " \n"; + break; + case 13: + echo " \n"; + break; + case 14: + echo " \n"; + break; + case 17: + echo " \n"; + break; + case 18: + echo " \n"; + break; + default: + echo " \n"; + } + + //display the current PCR value followed by the previous value + echo " + + \n"; + $token = strtok("|"); //move to the next token in previous_differences iff it exists + } +} +else +{ + echo " + + \n"; +} + +//DISPLAY SIGNATURE INFORMATION +echo " + + \n"; + +//display the correct message based on if the signature validated or not +if(!$row["signature_verified"]) +{ //signature did not validate + echo " + + \n"; +} +else +{ //signature is valid + echo " + + \n"; +} +?> +
ReportTimestampMachineUser
">report icon">machine icon">user icon
PCR Analysis
PCRCurrent ValuePrevious Value
" . $token . "" . $token . "" . $token . "" . $token . "" . $token . "" . $token . "" . $token . "" . $token . "" . $token . "" . $token . "" . $token . "" . $token . "" . $token . "" . $row["pcr" . $token] . "" . $previous["pcr" . $token] . "
No PCR Changes
Signature Analysis
The signature was not validated. This means the identity and measurement information that triggered this alert is not trustworthy. Signature errors can be a result of several things. Benign explanations are machine re-enrollment, service calls requiring motherboard replacement, changes in the Trusted Software Stack (TSS like NTru or Trousers), or network errors. Malicious explanations are identity key manipulation, firmware tampering, or hardware tampering. A signature error requires investigation to determine if the change is benign or malicious.
Signature Validated
+
+
+ +
+ + + diff --git a/OpenAttestation/Source/Portal/alerts.php b/OpenAttestation/Source/Portal/alerts.php new file mode 100644 index 0000000..6a3c04d --- /dev/null +++ b/OpenAttestation/Source/Portal/alerts.php @@ -0,0 +1,349 @@ + + + + + + HIS Alerts + + + +
+ +
+
+ +
  • New
  • +
  • In Progress
  • +
  • Closed
  • +
  • Cancelled
  • +
  • All
  • + \n"; +?> +
    +
    +

    Alerts

    + + +\n"; +if($sort == "sort=iddesc") +{ + echo " \n"; +} +else +{ + if($sort == "sort=idasc") + { + echo " \n"; + } + else + { + echo " \n"; + } +} + +//display the STATUS column +if($sort == "sort=statusdesc") +{ + echo " \n"; +} +else +{ + if($sort == "sort=statusasc") + { + echo " \n"; + } + else + { + echo " \n"; + } +} + +//display the ASSIGNEDTO column +if($sort == "sort=assigneddesc") +{ +echo " \n"; +} +else +{ + if($sort == "sort=assignedasc") + { + echo " \n"; + } + else + { + echo " \n"; + } +} + +//display thhe PCR and SIGNATURE columns together because they cannot be sorted -- a filter is required instead +echo " + \n"; + +//display the REPORT ID column +if($sort == "sort=reportdesc") +{ + echo " \n"; +} +else +{ + if($sort == "sort=reportasc") + { + echo " \n"; + } + else + { + echo " \n"; + } +} + +//display the TIMESTAMP column +if($sort == "sort=timestampdesc") +{ + echo " \n"; +} +else +{ + if($sort == "sort=timestampasc") + { + echo " \n"; + } + else + { + echo " \n"; + } +} + +//display the MACHINE NAME column +if($sort == "sort=machinedesc") +{ + echo " \n"; +} +else +{ + if($sort == "sort=machineasc") + { + echo " \n"; + } + else + { + echo " \n"; + } +} + +//display the USER NAME column +if($sort == "sort=userdesc") +{ + echo " \n"; +} +else +{ + if($sort == "sort=userasc") + { + echo " \n"; + } + else + { + echo " \n"; + } +} + +echo " \n"; + +//QUERY DATABASE FOR TABLE CONTENTS +$result = mysql_query("SELECT alerts.*, audit_log.timestamp, audit_log.SID, audit_log.machine_name, audit_log.previous_differences, audit_log.signature_verified FROM alerts JOIN audit_log ON alerts.audit_fk = audit_log.id" . $where . $order . " LIMIT " . (($limit - 1) * 100) . ",100"); + +//DISPLAY QUERY RESULTS IN TABLE +if(!mysql_num_rows($result)) +{ //no results returned from the query so display a notice and close off the table + echo " + + \n"; +} +else +{ //there are results to display so loop over them + while($row = mysql_fetch_array($result)) + { + echo " + + + + + \n"; + + if($row["previous_differences"] == NULL) + { //if there are no previous differences then display an acceptable icon + echo " \n"; + } + else + { //if there are previous differences show an error icon + echo " \n"; + } + + if($row["signature_verified"] == "1") + { //if the signature validated display a check mark icon + echo " \n"; + } + else + { //invalid signature so display an error icon + echo " \n"; + } + + echo " + + + + + + + \n"; + } +} +?> +
    ID \"ascendingID \"descendingIDStatus \"ascendingStatus \"descendingStatusAssigned \"ascendingAssigned \"descendingAssignedPCRSigReport \"ascendingReport \"descendingReportTimestamp \"ascendingTimestamp \"descendingTimestampMachine \"ascendingMachine \"descendingMachineUser \"ascendingUser \"descendingUser
    No Results
    \"alert" . $row["id"] . "" . $row["status"] . "" . $row["assignedTo"] . "\"ok\"exclamation\"ok\"exclamation\"report" . $row["audit_fk"] . "" . $row["timestamp"] . "" . $row["machine_name"] . "" . $row["SID"] . "
    +
    +
    + +
    + + + diff --git a/OpenAttestation/Source/Portal/assigned.php b/OpenAttestation/Source/Portal/assigned.php new file mode 100644 index 0000000..9ce6c40 --- /dev/null +++ b/OpenAttestation/Source/Portal/assigned.php @@ -0,0 +1,243 @@ + + + + + + HIS Alerts + + + +
    + +
    +
    + +
  • All
  • +
  • New
  • +
  • In Progress
  • +
  • Closed
  • +
  • Cancelled
  • + \n"; +?> +
    +
    +Alerts Assigned To " . $name . "\n"; + +//NEED A COUNT OF TOTAL RECORDS FOR THE PAGINATION SCRIPT +$count = mysql_fetch_row(mysql_query("SELECT COUNT(id) FROM alerts" . $where)); + +//NEED A FILE LINK FOR THE PAGINATION SCRIPT +$link = "assigned.php"; + +//INVOKE PAGINATION +include("includes/paginate.php"); +?> + +\n"; +if($sort == "sort=iddesc") { echo "";} +else { if($sort == "sort=idasc") { echo "";} +else { echo "";}} +if($sort == "sort=statusdesc") { echo "";} +else { if($sort == "sort=statusasc") { echo "";} +else { echo "";}} +if($sort == "sort=assigneddesc") { echo "";} +else { if($sort == "sort=assignedasc") { echo "";} +else { echo "";}} +echo " +\n"; +if($sort == "sort=reportdesc") { echo "";} +else { if($sort == "sort=reportasc") { echo "";} +else { echo "";}} +if($sort == "sort=timestampdesc") { echo "";} +else { if($sort == "sort=timestampasc") { echo "";} +else { echo "";}} +if($sort == "sort=machinedesc") { echo "";} +else { if($sort == "sort=machineasc") { echo "";} +else { echo "";}} +if($sort == "sort=userdesc") { echo "";} +else { if($sort == "sort=userasc") { echo "";} +else { echo "";}} +echo "\n"; + +//QUERY DATABASE FOR TABLE CONTENTS +$result = mysql_query("SELECT alerts.*, audit_log.timestamp, audit_log.SID, audit_log.machine_name, audit_log.previous_differences, audit_log.signature_verified FROM alerts JOIN audit_log ON alerts.audit_fk = audit_log.id" . $where . $order . " LIMIT " . (($limit - 1) * 100) . ",100"); + +//DISPLAY QUERY RESULTS IN TABLE +if(!mysql_num_rows($result)) +{ +echo ""; +} +else +{ +while($row = mysql_fetch_array($result)) +{ +echo " + + + + +\n"; +if($row["previous_differences"] == NULL) { echo "";} +else { echo "";} +if($row["signature_verified"] == "1") { echo "";} +else { echo "";} +echo " + + + + + + +\n"; +} +} +?> +
    ID \"ascendingID \"descendingIDStatus \"ascendingStatus \"descendingStatusAssigned \"ascendingAssigned \"descendingAssignedPCRSigReport \"ascendingReport \"descendingReportTimestamp \"ascendingTimestamp \"descendingTimestampMachine \"ascendingMachine \"descendingMachineUser \"ascendingUser \"descendingUser
    No Results
    \"alert" . $row["id"] . "" . $row["status"] . "" . $row["assignedTo"] . "\"ok\"exclamation\"ok\"exclamation\"report" . $row["audit_fk"] . "" . $row["timestamp"] . "" . $row["machine_name"] . "" . $row["SID"] . "
    +
    +
    + +
    + + + diff --git a/OpenAttestation/Source/Portal/attest.php b/OpenAttestation/Source/Portal/attest.php new file mode 100644 index 0000000..ff7df12 --- /dev/null +++ b/OpenAttestation/Source/Portal/attest.php @@ -0,0 +1,69 @@ + "success", "code" => 200); + $analysis = explode(",", $post_data["analysisType"]); + + $cert = ""; + if (stristr($post_data["analysisType"],"check-cert")){ + $cert = explode("=", $analysis[2])[1]; + } + + $req_level = explode("|", explode("=l", $analysis[1])[1])[0]; + $result = doAnalysis($post_data["hosts"], $cert, $req_level); + $response["results"] = $result; + } else { + $response = array("status" => "error", "code" => 400, "msg" => "malformed body"); + } + + echo json_encode($response); + +?> diff --git a/OpenAttestation/Source/Portal/certificate.php b/OpenAttestation/Source/Portal/certificate.php new file mode 100644 index 0000000..30e4a2b --- /dev/null +++ b/OpenAttestation/Source/Portal/certificate.php @@ -0,0 +1,41 @@ + diff --git a/OpenAttestation/Source/Portal/css.php b/OpenAttestation/Source/Portal/css.php new file mode 100644 index 0000000..95c331c --- /dev/null +++ b/OpenAttestation/Source/Portal/css.php @@ -0,0 +1,71 @@ + + + + + + + +HIS + + + +
    + +
    +
    +

    Left Column

    +
    +
    +

    Header 1

    +

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    +

    Header 2

    +

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    +

    Header 3

    +

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    +

    Header 4

    +

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    +
    Header 5
    +

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    +
    Header 6
    +

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    +
      +
    • List
    • +
    • List
    • +
    +

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    +
      +
    1. List
    2. +
    3. List
    4. +
    +

    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    +
    +
    + +
    + + diff --git a/OpenAttestation/Source/Portal/files/HIS_Portal_Guide_Crossbow.pdf b/OpenAttestation/Source/Portal/files/HIS_Portal_Guide_Crossbow.pdf new file mode 100644 index 0000000..a71d1be Binary files /dev/null and b/OpenAttestation/Source/Portal/files/HIS_Portal_Guide_Crossbow.pdf differ diff --git a/OpenAttestation/Source/Portal/help.php b/OpenAttestation/Source/Portal/help.php new file mode 100644 index 0000000..f0da092 --- /dev/null +++ b/OpenAttestation/Source/Portal/help.php @@ -0,0 +1,51 @@ + + + + + +HIS + + + +
    + +
    +
    +
    +
    +

    Help

    +

    User Guide

    +

    pdf icon Click to view PDF user guide.

    +

    Client Files

    +

    client files icon Click to download client files.

    +

    PCR Guide

    +

    Not ready yet.

    +
    +
    + +
    + + diff --git a/OpenAttestation/Source/Portal/images/bg_black_80.png b/OpenAttestation/Source/Portal/images/bg_black_80.png new file mode 100644 index 0000000..8c85a3c Binary files /dev/null and b/OpenAttestation/Source/Portal/images/bg_black_80.png differ diff --git a/OpenAttestation/Source/Portal/images/bg_black_85.png b/OpenAttestation/Source/Portal/images/bg_black_85.png new file mode 100644 index 0000000..fc51801 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/bg_black_85.png differ diff --git a/OpenAttestation/Source/Portal/images/bg_black_90.png b/OpenAttestation/Source/Portal/images/bg_black_90.png new file mode 100644 index 0000000..87b0822 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/bg_black_90.png differ diff --git a/OpenAttestation/Source/Portal/images/bg_red_80.png b/OpenAttestation/Source/Portal/images/bg_red_80.png new file mode 100644 index 0000000..ece3400 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/bg_red_80.png differ diff --git a/OpenAttestation/Source/Portal/images/bg_red_85.png b/OpenAttestation/Source/Portal/images/bg_red_85.png new file mode 100644 index 0000000..4875287 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/bg_red_85.png differ diff --git a/OpenAttestation/Source/Portal/images/bg_red_90.png b/OpenAttestation/Source/Portal/images/bg_red_90.png new file mode 100644 index 0000000..114e03a Binary files /dev/null and b/OpenAttestation/Source/Portal/images/bg_red_90.png differ diff --git a/OpenAttestation/Source/Portal/images/bg_white_80.png b/OpenAttestation/Source/Portal/images/bg_white_80.png new file mode 100644 index 0000000..87bd70d Binary files /dev/null and b/OpenAttestation/Source/Portal/images/bg_white_80.png differ diff --git a/OpenAttestation/Source/Portal/images/bg_white_85.png b/OpenAttestation/Source/Portal/images/bg_white_85.png new file mode 100644 index 0000000..31a0c58 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/bg_white_85.png differ diff --git a/OpenAttestation/Source/Portal/images/bg_white_90.png b/OpenAttestation/Source/Portal/images/bg_white_90.png new file mode 100644 index 0000000..f4e951e Binary files /dev/null and b/OpenAttestation/Source/Portal/images/bg_white_90.png differ diff --git a/OpenAttestation/Source/Portal/images/bg_white_95.png b/OpenAttestation/Source/Portal/images/bg_white_95.png new file mode 100644 index 0000000..9078a7b Binary files /dev/null and b/OpenAttestation/Source/Portal/images/bg_white_95.png differ diff --git a/OpenAttestation/Source/Portal/images/his/his_button_x128.png b/OpenAttestation/Source/Portal/images/his/his_button_x128.png new file mode 100644 index 0000000..3bd23ef Binary files /dev/null and b/OpenAttestation/Source/Portal/images/his/his_button_x128.png differ diff --git a/OpenAttestation/Source/Portal/images/his/his_button_x16.png b/OpenAttestation/Source/Portal/images/his/his_button_x16.png new file mode 100644 index 0000000..a52c1cf Binary files /dev/null and b/OpenAttestation/Source/Portal/images/his/his_button_x16.png differ diff --git a/OpenAttestation/Source/Portal/images/his/his_button_x32.png b/OpenAttestation/Source/Portal/images/his/his_button_x32.png new file mode 100644 index 0000000..89fe4b4 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/his/his_button_x32.png differ diff --git a/OpenAttestation/Source/Portal/images/his/his_button_x64.png b/OpenAttestation/Source/Portal/images/his/his_button_x64.png new file mode 100644 index 0000000..f4a8d8b Binary files /dev/null and b/OpenAttestation/Source/Portal/images/his/his_button_x64.png differ diff --git a/OpenAttestation/Source/Portal/images/his/his_button_x92.png b/OpenAttestation/Source/Portal/images/his/his_button_x92.png new file mode 100644 index 0000000..c51206a Binary files /dev/null and b/OpenAttestation/Source/Portal/images/his/his_button_x92.png differ diff --git a/OpenAttestation/Source/Portal/images/his/his_text_x128.png b/OpenAttestation/Source/Portal/images/his/his_text_x128.png new file mode 100644 index 0000000..38ac55f Binary files /dev/null and b/OpenAttestation/Source/Portal/images/his/his_text_x128.png differ diff --git a/OpenAttestation/Source/Portal/images/his/his_text_x32.png b/OpenAttestation/Source/Portal/images/his/his_text_x32.png new file mode 100644 index 0000000..d7f7c67 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/his/his_text_x32.png differ diff --git a/OpenAttestation/Source/Portal/images/his/his_text_x64.png b/OpenAttestation/Source/Portal/images/his/his_text_x64.png new file mode 100644 index 0000000..e3c4b86 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/his/his_text_x64.png differ diff --git a/OpenAttestation/Source/Portal/images/his/his_text_x92.png b/OpenAttestation/Source/Portal/images/his/his_text_x92.png new file mode 100644 index 0000000..12cfce8 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/his/his_text_x92.png differ diff --git a/OpenAttestation/Source/Portal/images/niarl/niarl_plain_x128.png b/OpenAttestation/Source/Portal/images/niarl/niarl_plain_x128.png new file mode 100644 index 0000000..510919a Binary files /dev/null and b/OpenAttestation/Source/Portal/images/niarl/niarl_plain_x128.png differ diff --git a/OpenAttestation/Source/Portal/images/niarl/niarl_plain_x16.png b/OpenAttestation/Source/Portal/images/niarl/niarl_plain_x16.png new file mode 100644 index 0000000..b947ef7 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/niarl/niarl_plain_x16.png differ diff --git a/OpenAttestation/Source/Portal/images/niarl/niarl_plain_x32.png b/OpenAttestation/Source/Portal/images/niarl/niarl_plain_x32.png new file mode 100644 index 0000000..9ba2fbf Binary files /dev/null and b/OpenAttestation/Source/Portal/images/niarl/niarl_plain_x32.png differ diff --git a/OpenAttestation/Source/Portal/images/niarl/niarl_plain_x64.png b/OpenAttestation/Source/Portal/images/niarl/niarl_plain_x64.png new file mode 100644 index 0000000..85c87d7 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/niarl/niarl_plain_x64.png differ diff --git a/OpenAttestation/Source/Portal/images/niarl/niarl_plain_x92.png b/OpenAttestation/Source/Portal/images/niarl/niarl_plain_x92.png new file mode 100644 index 0000000..7078f8e Binary files /dev/null and b/OpenAttestation/Source/Portal/images/niarl/niarl_plain_x92.png differ diff --git a/OpenAttestation/Source/Portal/images/nsa/nsa_x128.png b/OpenAttestation/Source/Portal/images/nsa/nsa_x128.png new file mode 100644 index 0000000..cdee750 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/nsa/nsa_x128.png differ diff --git a/OpenAttestation/Source/Portal/images/nsa/nsa_x16.png b/OpenAttestation/Source/Portal/images/nsa/nsa_x16.png new file mode 100644 index 0000000..e639363 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/nsa/nsa_x16.png differ diff --git a/OpenAttestation/Source/Portal/images/nsa/nsa_x32.png b/OpenAttestation/Source/Portal/images/nsa/nsa_x32.png new file mode 100644 index 0000000..3d2a5f4 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/nsa/nsa_x32.png differ diff --git a/OpenAttestation/Source/Portal/images/nsa/nsa_x64.png b/OpenAttestation/Source/Portal/images/nsa/nsa_x64.png new file mode 100644 index 0000000..9f836ef Binary files /dev/null and b/OpenAttestation/Source/Portal/images/nsa/nsa_x64.png differ diff --git a/OpenAttestation/Source/Portal/images/nsa/nsa_x92.png b/OpenAttestation/Source/Portal/images/nsa/nsa_x92.png new file mode 100644 index 0000000..ffd4c95 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/nsa/nsa_x92.png differ diff --git a/OpenAttestation/Source/Portal/images/public/crossbow_c9.jpg b/OpenAttestation/Source/Portal/images/public/crossbow_c9.jpg new file mode 100644 index 0000000..7e675de Binary files /dev/null and b/OpenAttestation/Source/Portal/images/public/crossbow_c9.jpg differ diff --git a/OpenAttestation/Source/Portal/images/public/crossbow_desat.jpg b/OpenAttestation/Source/Portal/images/public/crossbow_desat.jpg new file mode 100644 index 0000000..6069ca9 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/public/crossbow_desat.jpg differ diff --git a/OpenAttestation/Source/Portal/images/public/crossbow_std.jpg b/OpenAttestation/Source/Portal/images/public/crossbow_std.jpg new file mode 100644 index 0000000..7354d30 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/public/crossbow_std.jpg differ diff --git a/OpenAttestation/Source/Portal/images/secured_logo.png b/OpenAttestation/Source/Portal/images/secured_logo.png new file mode 100644 index 0000000..4511eaf Binary files /dev/null and b/OpenAttestation/Source/Portal/images/secured_logo.png differ diff --git a/OpenAttestation/Source/Portal/images/wikimedia/vibrantspirit/pistolcrossbow122.jpg b/OpenAttestation/Source/Portal/images/wikimedia/vibrantspirit/pistolcrossbow122.jpg new file mode 100644 index 0000000..869ef9c Binary files /dev/null and b/OpenAttestation/Source/Portal/images/wikimedia/vibrantspirit/pistolcrossbow122.jpg differ diff --git a/OpenAttestation/Source/Portal/images/wikimedia/vibrantspirit/pistolcrossbow122_92.png b/OpenAttestation/Source/Portal/images/wikimedia/vibrantspirit/pistolcrossbow122_92.png new file mode 100644 index 0000000..8cc5de6 Binary files /dev/null and b/OpenAttestation/Source/Portal/images/wikimedia/vibrantspirit/pistolcrossbow122_92.png differ diff --git a/OpenAttestation/Source/Portal/includes/classification.php b/OpenAttestation/Source/Portal/includes/classification.php new file mode 100644 index 0000000..c135961 --- /dev/null +++ b/OpenAttestation/Source/Portal/includes/classification.php @@ -0,0 +1,3 @@ +
    +

    +
    diff --git a/OpenAttestation/Source/Portal/includes/dbclose.php b/OpenAttestation/Source/Portal/includes/dbclose.php new file mode 100644 index 0000000..07ede78 --- /dev/null +++ b/OpenAttestation/Source/Portal/includes/dbclose.php @@ -0,0 +1,17 @@ + diff --git a/OpenAttestation/Source/Portal/includes/dbconnect.php b/OpenAttestation/Source/Portal/includes/dbconnect.php new file mode 100644 index 0000000..c669d91 --- /dev/null +++ b/OpenAttestation/Source/Portal/includes/dbconnect.php @@ -0,0 +1,32 @@ + diff --git a/OpenAttestation/Source/Portal/includes/footer.php b/OpenAttestation/Source/Portal/includes/footer.php new file mode 100644 index 0000000..1b00330 --- /dev/null +++ b/OpenAttestation/Source/Portal/includes/footer.php @@ -0,0 +1,2 @@ + diff --git a/OpenAttestation/Source/Portal/includes/header.php b/OpenAttestation/Source/Portal/includes/header.php new file mode 100644 index 0000000..3549b34 --- /dev/null +++ b/OpenAttestation/Source/Portal/includes/header.php @@ -0,0 +1,10 @@ + diff --git a/OpenAttestation/Source/Portal/includes/navigation.php b/OpenAttestation/Source/Portal/includes/navigation.php new file mode 100644 index 0000000..0c607b6 --- /dev/null +++ b/OpenAttestation/Source/Portal/includes/navigation.php @@ -0,0 +1,25 @@ + + diff --git a/OpenAttestation/Source/Portal/includes/pagenumber.php b/OpenAttestation/Source/Portal/includes/pagenumber.php new file mode 100644 index 0000000..9c1fe58 --- /dev/null +++ b/OpenAttestation/Source/Portal/includes/pagenumber.php @@ -0,0 +1,30 @@ += 1 && $_GET["page"] <= 4294967295) +{ + //page number has been validated so set it based on the url parameter + $limit = $_GET["page"]; //limit variable is for the MYSQL query + $page = "page=" . $_GET["page"]; //url parameter for links +} +else +{ + //page number has failed validation so set it to defaults + $limit = 1; + $page = "page=1"; +} +?> diff --git a/OpenAttestation/Source/Portal/includes/paginate.php b/OpenAttestation/Source/Portal/includes/paginate.php new file mode 100644 index 0000000..8d2014c --- /dev/null +++ b/OpenAttestation/Source/Portal/includes/paginate.php @@ -0,0 +1,52 @@ + +
    + 0) //if there are multiple pages to display then we can procede +{ + echo "
      \n"; //begin the unordered list + //DISPLAY FIRST PAGE LINK + if($limit > 1) { echo "
    • \"first
    • \n";} + //DISPLAY LEFT BUTTON + if(($limit - 1) > 1) { echo "
    • \"previous
    • \n";} + + //DISPLAY LEFT BUFFER PAGES + if(($limit - 2) >= 1) { echo "
    • " . ($limit - 2) . "
    • \n";} + if(($limit - 1) >= 1) { echo "
    • " . ($limit - 1) . "
    • \n";} + + //DISPLAY CURRENT PAGE + echo "
    • " . $limit . "
    • \n"; + + //DISPLAY RIGHT BUFFER PAGES + if(($limit + 1) <= $last) { echo "
    • " . ($limit + 1) . "
    • \n";} + if(($limit + 2) <= $last) { echo "
    • " . ($limit + 2) . "
    • \n";} + + //DISPLAY RIGHT BUTTON + if(($limit + 1) < $last) { echo "
    • \"next
    • \n";} + + //DISPLAY LAST PAGE LINK + if($limit < $last) { echo "
    • \"last
    • \n";} + echo "
    \n"; //end unordered list + } +?> +
    diff --git a/OpenAttestation/Source/Portal/includes/styles.php b/OpenAttestation/Source/Portal/includes/styles.php new file mode 100644 index 0000000..2fbb98c --- /dev/null +++ b/OpenAttestation/Source/Portal/includes/styles.php @@ -0,0 +1,16 @@ + + diff --git a/OpenAttestation/Source/Portal/includes/wsutils.php b/OpenAttestation/Source/Portal/includes/wsutils.php new file mode 100644 index 0000000..46b9285 --- /dev/null +++ b/OpenAttestation/Source/Portal/includes/wsutils.php @@ -0,0 +1,126 @@ + WSDL_CACHE_NONE)); + return $client->fetchReport(array('reportId' => $id, 'partial' => true)); +} + +function getUnknownDigests($id){ + $log_dir = '/var/www/html/OAT/unknown_log'; + $log_unknown = fopen($log_dir."/unknown_log_". $id, "r") or die("Unable to open file!"); + $unknow_dgsts=array(); + while (($line = fgets($log_unknown)) !== false) { + if ((strpos($line,'Info: Digest ') !== false) or (strpos($line,'Info: load') !== false)) { + array_push($unknow_dgsts,$line); + } + } + fclose($log_unknown); + return $unknow_dgsts; +} + +function doAnalysis($hosts, $req_cert, $req_level){ + include("includes/dbconnect.php"); + date_default_timezone_set('Europe/Rome'); + + // for each host in hosts + $results=array(); + + $count = 0; + foreach( $hosts as $host ) { + $result = mysql_query("select host_name, analysis_request, analysis_results, validate_time from attest_request where host_name='$host' ORDER BY validate_time DESC LIMIT 1;"); + $cert = mysql_query("select host_name, description from HOST where host_name='$host';"); + $reports = mysql_query("select id, machine_name from audit_log where machine_name='$host' ORDER BY id DESC LIMIT 1;"); + + if (!$result or !$cert or !$reports) { + die('Invalid query: ' . mysql_error()); + } else{ + //$results = array(); + $row = mysql_fetch_array($result); + $cert = mysql_fetch_array($cert); + $report = mysql_fetch_array($reports); + + if(empty($row['host_name']) or empty($cert['host_name']) or empty($report['machine_name'])){ + $_r = array( + "host_name" => $host, + "trust_lvl" => "unknown", + ); + } else { + $analysis_results = $row['analysis_results']; + $validate_time = strtotime($row['validate_time']); + $now = strtotime(date('Y-m-d H:i:s')); + $diff = $now - $validate_time; + + $unknow_dgsts = getUnknownDigests($report["id"]); + foreach ($unknow_dgsts as $line){ + $image = explode(" ", $line); + if(stristr($image[1],"load)")){ + $res_level = $image[3]; + } else { + $res_level = 4; + } + } + $_r = array( + "host_name" => $host, + ); + if (strcmp($req_cert, $cert['description'])!=0) { + $_r["trust_lvl"] = "cert-err"; + } else if ($diff > 30) { + $_r["trust_lvl"] = "vtime-err"; + } else if (((stristr($row['analysis_results'], "|true|")) and (stristr($row['analysis_results'],"|ANALYSIS_COMPLETED|0|"))) or $LEVEL<=$res_level) { + $_r["trust_lvl"] = "trusted"; + } else { + $_r["trust_lvl"] = "untrusted"; + } + $_r["validate_time"] = $row["validate_time"]; + + } + } + $results[$count] = $_r; + $count++; + } + include("includes/dbclose.php"); + + return $results; +} + + +?> diff --git a/OpenAttestation/Source/Portal/index.php b/OpenAttestation/Source/Portal/index.php new file mode 100644 index 0000000..948ef9a --- /dev/null +++ b/OpenAttestation/Source/Portal/index.php @@ -0,0 +1,18 @@ + diff --git a/OpenAttestation/Source/Portal/ir.php b/OpenAttestation/Source/Portal/ir.php new file mode 100644 index 0000000..8fd9b6c --- /dev/null +++ b/OpenAttestation/Source/Portal/ir.php @@ -0,0 +1,119 @@ +faultstring == "Not Found") { + echo "

    " . $fault->faultstring . "

    "; + header('HTTP/1.0 404 Not Found'); + echo "

    The requested report (" . $id . ") does not exist.

    "; + } else if ($fault->faultstring == "Internal Server Error") { + echo "

    " . $fault->faultstring . "

    "; + header('HTTP/1.0 500 Internal Server Error'); + echo "

    An error occurred while retrieving requested report (" . $id . ").

    "; + } else { + echo "

    SOAP Exception

    "; + echo "

    " . $fault->faultstring . "

    "; + } + echo "
    Apache Server at " . $_SERVER['HTTP_HOST'] . " Port " . $_SERVER['SERVER_PORT'] . "
    "; + exit(); +} + +foreach ($result as $key=>$value) { + if ($key == 'reportString') { + $xml = simplexml_load_string("$value"); + $values = $xml->xpath("/*[local-name()='Report']/*[local-name()='SnapshotCollection']/*[local-name()='Values']"); + + echo "

    Integrity Report

    "; + foreach ( $values as $value_list ) { + $type = $value_list->xpath("//*[local-name()='SimpleObject']/*[local-name()='Objects']/@Type"); + $image = $value_list->xpath("//*[local-name()='SimpleObject']/*[local-name()='Objects']/@Image"); + #$dgst = $value_list->xpath("//*[local-name()='SimpleObject']/*[local-name()='Objects']/*[local-name()='Hash']/text()"); + + for($x = 0; $x < count($image); $x++) { + if ($type[$x] == "ima"){ + $binary = base64_decode($image[$x]); + #$imageDgst = base64_decode($imageDgst64[$x]); + # hex data seems correct, but it look like unrelevant. + #$hex = bin2hex($imageDgst); + $dgst = substr($binary, 0, 20); + $dgsthex = bin2hex($dgst); + $name=substr($binary, 20); + echo "

    " . $name . "

    "; + echo "

    ". $dgsthex . "



    "; + } + } + break; + } + break; + } +} + +# here to find the id of the file and write it in the web page. +$unknow_dgsts = getUnknownDigests($id); +if (count($unknow_dgsts) > 0) + echo "

    unknown digests

    "; +foreach ($unknow_dgsts as $line){ + $image = explode(" ", $line); + if(stristr($image[1],"Digest")) { + $binary_name = rtrim(ltrim($image[3],'('),')'); + $hex = $image[2]; + echo "

    " . $binary_name . "

    "; + echo "

    " . $hex . "

    "; + } +} +?> diff --git a/OpenAttestation/Source/Portal/machine.php b/OpenAttestation/Source/Portal/machine.php new file mode 100644 index 0000000..af1ef90 --- /dev/null +++ b/OpenAttestation/Source/Portal/machine.php @@ -0,0 +1,192 @@ + + + + + +HIS Reports + + + +
    + +
    + +
    +Integrity Reports From " . $name . "\n"; +//NEED A COUNT OF TOTAL RECORDS FOR THE PAGINATION SCRIPT +$count = mysql_fetch_row(mysql_query("SELECT COUNT(id) FROM audit_log" . $where)); + +//NEED A FILE LINK FOR THE PAGINATION SCRIPT +$link = "machine.php"; + +//INVOKE PAGINATION +include("includes/paginate.php"); +?> + +\n"; +if($sort == "sort=reportdesc") { echo "";} +else { if($sort == "sort=reportasc") { echo "";} +else { echo "";}} +echo " +\n"; +if($sort == "sort=timestampdesc") { echo "";} +else { if($sort == "sort=timestampasc") { echo "";} +else { echo "";}} +if($sort == "sort=machinedesc") { echo "";} +else { if($sort == "sort=machineasc") { echo "";} +else { echo "";}} +if($sort == "sort=userdesc") { echo "";} +else { if($sort == "sort=userasc") { echo "";} +else { echo "";}} +echo "\n"; + +//QUERY DATABASE FOR TABLE CONTENTS +$result = mysql_query("SELECT id, previous_differences, signature_verified, machine_name, SID, timestamp FROM audit_log" . $where . $order . " LIMIT " . (($limit - 1) * 100) . ",100"); + +//DISPLAY QUERY RESULTS IN TABLE +while($row = mysql_fetch_array($result)) +{ +echo " + +\n"; +if($row["previous_differences"] == NULL) { echo "";} +else { echo "";} +if($row["signature_verified"] == "1") { echo "";} +else { echo "";} +echo " + + + + +\n"; +} +?> +
    Report \"ascendingReport \"descendingReportPCRSigTimestamp \"ascendingTimestamp \"descendingTimestampMachine \"ascendingMachine \"descendingMachineUser \"ascendingUser \"descendingUser
    \"report" . $row["id"] . "\"ok\"exclamation\"ok\"exclamation" . $row["timestamp"] . "" . $row["machine_name"] . "" . $row["SID"] . "
    +
    +
    + +
    + + + diff --git a/OpenAttestation/Source/Portal/machines.php b/OpenAttestation/Source/Portal/machines.php new file mode 100644 index 0000000..5ef9d3e --- /dev/null +++ b/OpenAttestation/Source/Portal/machines.php @@ -0,0 +1,183 @@ + + + + + +HIS Machines + + + +
    + +
    +
    + +
  • Active
  • +
  • Inactive
  • +
  • All
  • +\n"; +?> +
    +
    +

    Enrolled Machines

    +

    Note: Due to the complex nature of the last check in query this page may be slow to load and upate.

    + + +\n"; +if($sort == "sort=machinedesc") { echo "";} +else { if($sort == "sort=machineasc") { echo "";} +else { echo "";}} +if($sort == "sort=timestampdesc") { echo "";} +else { if($sort == "sort=timestampasc") { echo "";} +else { echo "";}} +echo " +\n"; +if($sort == "sort=lastrepdesc") { echo "";} +else { if($sort == "sort=lastrepasc") { echo "";} +else { echo "";}} +if($sort == "sort=reportdesc") { echo "";} +else { if($sort == "sort=reportasc") { echo "";} +else { echo "";}} +echo "\n"; + +//QUERY DATABASE FOR TABLE CONTENTS +$result = mysql_query("SELECT machine_cert.id AS mid, machine_cert.machine_name, machine_cert.timestamp, machine_cert.active, MAX(audit_log.timestamp) AS lastrep, MAX(audit_log.id) AS aid FROM machine_cert LEFT JOIN audit_log ON machine_cert.id = audit_log.machine_id" . $where . " GROUP BY machine_cert.id" . $order . " LIMIT " . (($limit - 1) * 100) . ",100"); + +//DISPLAY QUERY RESULTS IN TABLE +if(!mysql_num_rows($result)) +{ +echo ""; +} +else +{ +while($row = mysql_fetch_array($result)) +{ +echo " + + + +\n"; +if($row["active"] == 1) { echo "\n";} +else { echo "\n";} +echo " + +\n"; +echo "\n"; +} +} +?> +
    Machine \"ascendingMachine \"descendingMachineEnrolled \"ascendingEnrolled \"descendingEnrolledCertActiveLast Check In \"ascendingLast Check In \"descendingLast Check InLast Report \"ascendingLast Report \"descendingLast Report
    No Results
    " . $row["machine_name"] . "" . $row["timestamp"] . "\"certificate\"active\"inactive" . $row["lastrep"] . "\"report" . $row["aid"] . "
    +
    +
    + +
    + + + diff --git a/OpenAttestation/Source/Portal/pcrs.php b/OpenAttestation/Source/Portal/pcrs.php new file mode 100644 index 0000000..99ebec3 --- /dev/null +++ b/OpenAttestation/Source/Portal/pcrs.php @@ -0,0 +1,113 @@ += 0) +{ +$index = $_GET["index"]; +} +else +{ +$index = -1; +} +?> + + + + +HIS + + + +
    + +
    +
    + +
    +
    +

    PCR Measurement Stats

    +

    Most Common Values Per Index

    +Displaying all unique values from index " . $index . ".\n";} +?> + + + + + + + + + + + +\n"; +} +} +else +{ +//OUTPUT ALL UNIQUE RESULTS FOR THE SELECTED PCR INDEX +$result = mysql_query("SELECT pcr" . $index . ", count(pcr" . $index . ") AS pcount FROM audit_log WHERE pcr" . $index . " != '' GROUP BY pcr" . $index . " ORDER BY pcount DESC"); +while($row = mysql_fetch_array($result)) +{ +echo " + + + + +\n"; +} +} +?> +
    IndexValueCount
    \"chart" . $counter . "" . $row["pcr" . $counter] . "" . $row["pcount"] . "
     " . $index . "" . $row["pcr" . $index] . "" . $row["pcount"] . "
    +
    +
    + +
    + + + diff --git a/OpenAttestation/Source/Portal/report.php b/OpenAttestation/Source/Portal/report.php new file mode 100644 index 0000000..ecc0ae3 --- /dev/null +++ b/OpenAttestation/Source/Portal/report.php @@ -0,0 +1,63 @@ +faultstring == "Not Found") { + echo "

    " . $fault->faultstring . "

    "; + header('HTTP/1.0 404 Not Found'); + echo "

    The requested report (" . $id . ") does not exist.

    "; + } else if ($fault->faultstring == "Internal Server Error") { + echo "

    " . $fault->faultstring . "

    "; + header('HTTP/1.0 500 Internal Server Error'); + echo "

    An error occurred while retrieving requested report (" . $id . ").

    "; + } else { + echo "

    SOAP Exception

    "; + echo "

    " . $fault->faultstring . "

    "; + } + echo "
    Apache Server at " . $_SERVER['HTTP_HOST'] . " Port " . $_SERVER['SERVER_PORT'] . "
    "; + exit(); +} + +//PRINT OUT ALL THE XML +foreach ($result as $key=>$value) { + if ($key == 'reportString') { + echo $value; + break; + } +} + +?> diff --git a/OpenAttestation/Source/Portal/reports.php b/OpenAttestation/Source/Portal/reports.php new file mode 100644 index 0000000..cebfc21 --- /dev/null +++ b/OpenAttestation/Source/Portal/reports.php @@ -0,0 +1,189 @@ + + + + + +HIS Reports + + + +
    + +
    + +
    +

    Integrity Reports

    + + +\n"; +if($sort == "sort=reportdesc") { echo "";} +else { if($sort == "sort=reportasc") { echo "";} +else { echo "";}} +echo " +\n"; +if($sort == "sort=timestampdesc") { echo "";} +else { if($sort == "sort=timestampasc") { echo "";} +else { echo "";}} +if($sort == "sort=machinedesc") { echo "";} +else { if($sort == "sort=machineasc") { echo "";} +else { echo "";}} +if($sort == "sort=userdesc") { echo "";} +else { if($sort == "sort=userasc") { echo "";} +else { echo "";}} +echo "\n"; + +//QUERY DATABASE FOR TABLE CONTENTS +$result = mysql_query("SELECT id, previous_differences, signature_verified, machine_name, SID, timestamp FROM audit_log" . $where . $order . " LIMIT " . (($limit - 1) * 100) . ",100"); + +//DISPLAY QUERY RESULTS IN TABLE +if(!mysql_num_rows($result)) +{ +echo ""; +} +else +{ +while($row = mysql_fetch_array($result)) +{ +echo " + +\n"; +if($row["previous_differences"] == NULL) { echo "";} +else { echo "";} +if($row["signature_verified"] == "1") { echo "";} +else { echo "";} +echo " + + + + +\n"; +} +} +?> +
    Report \"ascendingReport \"descendingReportPCRSigTimestamp \"ascendingTimestamp \"descendingTimestampMachine \"ascendingMachine \"descendingMachineUser \"ascendingUser \"descendingUser
    No Results
    \"report" . $row["id"] . "\"ok\"exclamation\"ok\"exclamation" . $row["timestamp"] . "" . $row["machine_name"] . "" . $row["SID"] . "
    +
    +
    + +
    + + + diff --git a/OpenAttestation/Source/Portal/result.php b/OpenAttestation/Source/Portal/result.php new file mode 100644 index 0000000..7cb40c7 --- /dev/null +++ b/OpenAttestation/Source/Portal/result.php @@ -0,0 +1,118 @@ + need all three paramters"; + exit (0); +} + +if ($LEVEL > 4){ + echo "

    invalid level requirement, maximum trust level is 4"; + exit(0); +} +?> + + +Attestation Result of <?php echo $CN; ?> + + + + +
    +

    + secured_logo +

    +

    +

    NED name:

    +
    +

    Required trust level: L

    +
    +

    Received certificate digest (SHA1):

    +
    +

    +
    + + + + + + +
    + +
    + diff --git a/OpenAttestation/Source/Portal/stats.php b/OpenAttestation/Source/Portal/stats.php new file mode 100644 index 0000000..e8c84ad --- /dev/null +++ b/OpenAttestation/Source/Portal/stats.php @@ -0,0 +1,208 @@ + + + + + +HIS Statistics + + + +
    + +
    +
    +
    +
    +

    Statistics

    +

    Alerts

    + + + + + + + + + + + + + + + +\n"; +?> +
    Total AlertsUnassignedNewIn ProgressClosedCancelled
    " . $total[0] . "" . $unassigned[0] . "" . $new[0] . "" . $inprogress[0] . "" . $closed[0] . "" . $cancelled[0] . "
    +

    Reports

    + + + + + + + + + + + + + +" . $reportsalltime[0] . " + + + + + +\n"; +?> + + + +" . $pcrreportsalltime[0] . " + + + + + +\n"; +?> + + + +" . $sigreportsalltime[0] . " + + + + + +\n"; +?> + + + +" . $freereportsalltime[0] . " + + + + + +\n"; +?> + +
     All TimeTodayYesterdayThis MonthLast MonthThis YearLast Year
    Total Reports" . $reportstoday[0] . "" . $reportsyesterday[0] . "" . $reportsthismonth[0] . "" . $reportslastmonth[0] . "" . $reportsthisyear[0] . "" . $reportslastyear[0] . "
    PCR Errors" . $pcrreportstoday[0] . "" . $pcrreportsyesterday[0] . "" . $pcrreportsthismonth[0] . "" . $pcrreportslastmonth[0] . "" . $pcrreportsthisyear[0] . "" . $pcrreportslastyear[0] . "
    Invalid Signatures" . $sigreportstoday[0] . "" . $sigreportsyesterday[0] . "" . $sigreportsthismonth[0] . "" . $sigreportslastmonth[0] . "" . $sigreportsthisyear[0] . "" . $sigreportslastyear[0] . "
    Error-Free" . $freereportstoday[0] . "" . $freereportsyesterday[0] . "" . $freereportsthismonth[0] . "" . $freereportslastmonth[0] . "" . $freereportsthisyear[0] . "" . $freereportslastyear[0] . "
    +

    Machines

    + + + + + + + + + + +\n"; +?> +
    EnrollmentsActiveInactive
    " . $enrollments[0] . "" . $active[0] . "" . $inactive[0] . "
    +
    +
    + +
    + + diff --git a/OpenAttestation/Source/Portal/styles/screen.css b/OpenAttestation/Source/Portal/styles/screen.css new file mode 100644 index 0000000..c431f8a --- /dev/null +++ b/OpenAttestation/Source/Portal/styles/screen.css @@ -0,0 +1,272 @@ +/*2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + +This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +- 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. + +- Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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.*/ + +/* GLOBAL STYLES */ +* { +margin:0; +padding:0; +font-family: Arial, Helvetica, sans-serif; +} + +html { +background-color: gray; +} + +a img { +border: none; +vertical-align: middle; +} + +td img { +display: block; +margin: 0 auto; +} + +button img { +vertical-align: text-top; +} + +/* CLASSIFICATION STYLES */ +#classification .ufouo { +color: yellow; +background-color: green; +text-align: center; +width: 100%; +font-size: small; +font-variant: small-caps; +} + +/* WRAPPER STYLES */ +#wrapper { +margin: 2%; +min-width: 900px; +} + +/* HEADER STYLES */ +#header { +color: white; +background-color: maroon; +clear: both; +min-height: 116px; +-moz-border-radius: 9px; +-webkit-border-radius: 9px; +border-radius: 9px; +} + +#header .leftcol { +float: left; +padding: 12px; +} + +#header .rightcol { +margin-left: 258px; +padding: 12px; +} + +#header h1 { +margin-bottom: 9px; +} + +#header h2 { +margin-bottom: 9px; +} + +#header p { +margin-bottom: 6px; +} + +/* NAVIGATION STYLES */ +#navigation { +color: white; +border: 3px solid white; +-moz-border-radius: 9px; +-webkit-border-radius: 9px; +border-radius: 9px; +background-color: black; +clear: both; +margin: 12px; +} + +#navigation li { +margin-top: 12px; +margin-bottom: 12px; +display: inline-block; +list-style-type: none; +} + +#navigation a { +padding: 12px; +color: white; +text-decoration: none; +} + +#navigation a:hover { +-moz-border-radius: 9px; +-webkit-border-radius: 9px; +border-radius: 9px; +background-color: #333333; +} + +/* PAGE SELECTOR STYLES */ +#pageselector { +text-align: center; +margin: 12px; +font-weight: bold; +min-height: 46px; +} + +#pageselector li { +margin-top: 12px; +margin-bottom: 12px; +display: inline; +list-style-type: none; +} + +#pageselector .currentpage { +padding: 12px; +border: 3px solid maroon; +-moz-border-radius: 9px; +-webkit-border-radius: 9px; +border-radius: 9px; +} + +#pageselector a { +color: black; +padding: 12px; +border: 3px solid #dddddd; +-moz-border-radius: 9px; +-webkit-border-radius: 9px; +border-radius: 9px; +} + +#pageselector a:hover { +background-color: #dddddd; +} + +/* CONTENT STYLES */ +#content { +background-color: white; +clear: both; +-moz-border-radius: 9px; +-webkit-border-radius: 9px; +border-radius: 9px; +} + +#content table { +width: 100%; +} + +#content .leftcol { +float: left; +width: 120px; +} + +#content .leftcol li { +list-style-type: none; +} + +#content .leftcol a { +color: black; +display: block; +float: left; +width: 100%; +padding: 12px; +text-decoration: none; +} + +#content .leftcol a:hover { +background-color: #dddddd; +-moz-border-radius: 9px; +-webkit-border-radius: 9px; +border-radius: 9px; +} + +#content .rightcol { +margin-left: 144px; +padding: 12px; +} + +#content th { +padding: 8px; +background-color: maroon; +color: white; +} + +#content th a { +color:white; +} + +#content td { +padding: 4px; +background-color: #dddddd; +} + +#content h1, #content h2, #content h3, #content h4, #content h5, #content h6 { +margin-bottom: 12px; +} + +#content h6 { +text-align: right; +} + +#content p, #content table { +margin-bottom: 8px; +} + +#content textarea { +width: 99%; +} + +#content .controlbuttons { +text-align: center; +margin:12px; +} + +/* FOOTER STYLES */ +#footer { +margin:12px; +border: 3px solid white; +-moz-border-radius: 9px; +-webkit-border-radius: 9px; +border-radius: 9px; +color: white; +background-color: black; +clear: both; +min-height: 116px; +} + +#footer .leftcol { +float: left; +padding: 12px; +} + +#footer .rightcol { +margin-left: 258px; +padding:12px; +font-family: Arial, Helvetica, sans-serif; +} + +#footer h1 { +font-size: large; +margin-bottom: 9px; +} + +#footer h2 { +font-size: medium; +margin-bottom: 9px; +} + +#footer a { +color: white; +} diff --git a/OpenAttestation/Source/Portal/unknown_log/README b/OpenAttestation/Source/Portal/unknown_log/README new file mode 100644 index 0000000..484f4ff --- /dev/null +++ b/OpenAttestation/Source/Portal/unknown_log/README @@ -0,0 +1 @@ +To store the logs of ra_verifier, then to read them in the web page. diff --git a/OpenAttestation/Source/Portal/user.php b/OpenAttestation/Source/Portal/user.php new file mode 100644 index 0000000..eb50d0a --- /dev/null +++ b/OpenAttestation/Source/Portal/user.php @@ -0,0 +1,199 @@ + + + + + +HIS Reports + + + +
    + +
    + +
    +Integrity Reports From " . $name . "

    \n"; +//NEED A COUNT OF TOTAL RECORDS FOR THE PAGINATION SCRIPT +$count = mysql_fetch_row(mysql_query("SELECT COUNT(id) FROM audit_log" . $where)); + +//NEED A FILE LINK FOR THE PAGINATION SCRIPT +$link = "user.php"; + +//INVOKE PAGINATION +include("includes/paginate.php"); +?> + +\n"; +if($sort == "sort=reportdesc") { echo "";} +else { if($sort == "sort=reportasc") { echo "";} +else { echo "";}} +echo " +\n"; +if($sort == "sort=timestampdesc") { echo "";} +else { if($sort == "sort=timestampasc") { echo "";} +else { echo "";}} +if($sort == "sort=machinedesc") { echo "";} +else { if($sort == "sort=machineasc") { echo "";} +else { echo "";}} +if($sort == "sort=userdesc") { echo "";} +else { if($sort == "sort=userasc") { echo "";} +else { echo "";}} +echo "\n"; + +//QUERY DATABASE FOR TABLE CONTENTS +$result = mysql_query("SELECT id, previous_differences, signature_verified, machine_name, SID, timestamp FROM audit_log" . $where . $order . " LIMIT " . (($limit - 1) * 100) . ",100"); + +//DISPLAY QUERY RESULTS IN TABLE +if(!mysql_num_rows($result)) +{ +echo ""; +} +else +{ +while($row = mysql_fetch_array($result)) +{ +echo " + +\n"; +if($row["previous_differences"] == NULL) { echo "";} +else { echo "";} +if($row["signature_verified"] == "1") { echo "";} +else { echo "";} +echo " + + + + +\n"; +} +} +?> +
    Report \"ascendingReport \"descendingReportPCRSigTimestamp \"ascendingTimestamp \"descendingTimestampMachine \"ascendingMachine \"descendingMachineUser \"ascendingUser \"descendingUser
    No Results
    \"report" . $row["id"] . "\"ok\"exclamation\"ok\"exclamation" . $row["timestamp"] . "" . $row["machine_name"] . "" . $row["SID"] . "
    + + + + + + + diff --git a/OpenAttestation/Source/PrivacyCA/TPMModule.properties b/OpenAttestation/Source/PrivacyCA/TPMModule.properties new file mode 100644 index 0000000..327e1c2 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/TPMModule.properties @@ -0,0 +1,4 @@ +TpmModuleExePath = ./exe/ +ExeName = NIARL_TPM_Module +TrousersMode = True +DebugMode = True diff --git a/OpenAttestation/Source/PrivacyCA/build.xml b/OpenAttestation/Source/PrivacyCA/build.xml new file mode 100644 index 0000000..dd42bb1 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/build.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/PrivacyCA/provisioner.sh b/OpenAttestation/Source/PrivacyCA/provisioner.sh new file mode 100644 index 0000000..7544c95 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/provisioner.sh @@ -0,0 +1,43 @@ +pushd ./exe 1>/dev/null +./NIARL_TPM_Module -mode 14 -owner_auth 1111111111111111111111111111111111111111 -cred_type EC +popd 1>/dev/null + +#echo %LoadVersion% | find "x64" > nul +#IF %ERRORLEVEL%==0 ( +# set status64=\Wow6432Node\ +#) ELSE ( +# set status64=\ +#) +# +#reg add "HKLM\SOFTWARE%status64%NTRU Cryptosystems\TSS" /v allowSOAPTCS /t REG_DWORD /d 0x00000001 /f +#net stop tcsd_win32.exe +#net start tcsd_win32.exe +#set status64= + +export provclasspath=".:./lib/activation.jar:./lib/axis.jar:./lib/bcprov-jdk15-141.jar:./lib/commons-discovery-0.2.jar:./lib/commons-logging-1.0.4.jar:./lib/FastInfoset.jar:./lib/HisPrivacyCAWebServices-client.jar:./lib/HisPrivacyCAWebServices2-client.jar:./lib/HisWebServices-client.jar:./lib/http.jar:./lib/jaxb-api.jar:./lib/jaxb-impl.jar:./lib/jaxb-xjc.jar:./lib/jaxrpc.jar:./lib/jaxws-api.jar:./lib/jaxws-rt.jar:./lib/jaxws-tools.jar:./lib/jsr173_api.jar:./lib/jsr181-api.jar:./lib/jsr250-api.jar:./lib/mail.jar:./lib/mimepull.jar:./lib/PrivacyCA.jar:./lib/resolver.jar:./lib/saaj-api.jar:./lib/saaj-impl.jar:./lib/SALlib_hibernate3.jar:./lib/stax-ex.jar:./lib/streambuffer.jar:./lib/TSSCoreService.jar:./lib/woodstox.jar:./lib/wsdl4j-1.5.1.jar" + +java -cp $provclasspath gov.niarl.his.privacyca.HisTpmProvisioner +ret=$? +if [ $ret == 0 ] ; then + echo "Successfully initialized TPM" >> provisioning.log +else + echo "Failed to initialize the TPM, error $ret" >> provisioning.log + exit +fi + +java -cp $provclasspath gov.niarl.his.privacyca.HisIdentityProvisioner +ret=$? +if [ $ret == 0 ]; then + echo "Successfully received AIC from Privacy CA" >> provisioning.log +else + echo "Failed to receive AIC from Privacy CA, error $ret" >> provisioning.log + exit +fi + +java -cp $provclasspath gov.niarl.his.privacyca.HisRegisterIdentity +ret=$? +if [ $ret == 0 ]; then + echo "Successfully registered identity with appraiser" >> provisioning.log +else + echo "Failed to register identity with appraiser, error $ret" >> provisioning.log +fi diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/.HisIdentityProvisioner.java.swp b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/.HisIdentityProvisioner.java.swp new file mode 100644 index 0000000..3a35e38 Binary files /dev/null and b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/.HisIdentityProvisioner.java.swp differ diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/HisIdentityProvisioner.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/HisIdentityProvisioner.java new file mode 100644 index 0000000..66a62f6 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/HisIdentityProvisioner.java @@ -0,0 +1,329 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * 锟�Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 锟�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. + * 锟�Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.security.cert.X509Certificate; +import java.security.interfaces.RSAPublicKey; +import java.util.Properties; + +import gov.niarl.his.webservices.hisPrivacyCAWebService2.IHisPrivacyCAWebService2; +import gov.niarl.his.webservices.hisPrivacyCAWebService2.client.HisPrivacyCAWebServices2ClientInvoker; + +//import gov.niarl.sal.webservices.hisPrivacyCAWebService.clientWsImport.EncryptedCAResponse; + +/** + *

    + * This is part 2 of 3 for fully provisioning HIS on a Windows client. This part provisions the identity key (AIK) and + * certificate (AIC) for a HIS client. Prior to running this client, the HisTpmProvisioner must be run. Following + * this client, the HisRegisterIdentity must be run. + *

    + * + *

    + * This class utilizes the TpmModuleJava class, which depends on the NTRU TCS Service running SOAP services on TCP port + * 30003. Because of the NTRU requirement, this class wil not work with Linux using TrouSerS. + *

    + * + *

    + * This class utilizes a properties file. It looks for a file by the name of "HISprovisioner.properties" in the + * directory from which Java was invoked. + *

    + * The following values must be in the properties file: + *
      + *
    • TpmOwnerAuth This must be a 40 digit (20 byte) hex code representing the owner auth data which was + * assigned during TPM provisioning. Owner auth is required for generating a new AIK.
      + *
    • + *
    • HisIdentityLabel This is the name (text string) that will appear as the Alternate Subject Name, as + * requested to the Privacy CA.
      + *
    • + *
    • HisIdentityIndex This is an integer (generally 1) that will be used for storing the AIK. The HIS + * Standalone will need to know this value.
      + *
    • + *
    • HisIdentityAuth This must be a 40 digit (20 byte) hex code representing the auth data to be assigned for + * the AIK. The HIS Standalone will need to know this value.
      + *
    • + *
    • PrivacyCaCertFile This must be the path to and name of the Privacy CA's certificate. The public key in + * this certificate will be what is used to encrypt the Identity Request, so it must match the key used by the Privacy + * CA.
      + *
    • + *
    • PrivacyCaUrl This is the entire path to the Privacy CA web service. This class assumes the use of + * HisPrivacyCAWebServices2.
    • + *
    • TrustStore This is the path to and name of the trust store used to encrypt the web service connection. + * This file must be provided by the web server hosting the Privacy CA.
      + *
    • + *
    • ClientPath This is the path for the HIS client installation. The AIC (aic.cer) file will be placed there.
    • + *
    + * + *

    + * If there are problems with the properties file, context-specific errors will be shown, and an exit code of 99 will be + * returned. + *

    + *

    + * If the path specified by the ClientPath variable in the properties file cannot be created, an exit code of 2 will be + * returned. + *

    + *

    + * If there are any problems encountered when running the main function, the stack trace will be displayed and an exit + * code of 1 will be returned. + *

    + *

    + * If the program runs successfully, an error code of 0 will be returned. + *

    + * + *

    + * This application assumes the the WELL KNOWN AUTH VALUE (20 bytes of zeros) is used as the SRK auth value! Though this + * is normal, a TPM which was owned using version 1 of the NIARL_TPM_Module or using some other low level tool may not + * be using this auth value. + *

    + * + *

    + * Once the AIC is received from the Privacy CA, it is placed at c:\his\aik.cer. + *

    + * + * @author schawki + * + */ +public class HisIdentityProvisioner { + + /** + * Entry point into the program. See class description for required properties file elements. + * + */ + public static void main(String[] args) { + // Define properties file strings + final String OWNER_AUTH = "TpmOwnerAuth"; + final String HIS_IDENTITY_LABEL = "HisIdentityLabel"; + final String HIS_IDENTITY_INDEX = "HisIdentityIndex"; + final String HIS_IDENTITY_AUTH = "HisIdentityAuth"; + final String PRIVACY_CA_CERT = "PrivacyCaCertFile"; + final String PRIVACY_CA_URL = "PrivacyCaUrl"; + final String TRUST_STORE = "TrustStore"; + final String CLIENT_PATH = "ClientPath"; + final String EC_STORAGE = "ecStorage"; + final String propertiesFileName = "OATprovisioner.properties"; + final String ecStorageFileName = "EC.cer"; + + // Instantiate variables to be set by properties file + byte[] TpmOwnerAuth = null; + byte[] HisIdentityAuth = null; + int HisIdentityIndex = 0; + + String PrivacyCaCertFile = ""; + String PrivacyCaUrl = ""; + String TrustStore = ""; + String ClientPath = ""; + String ecStorage = ""; + String HisIdentityLabel = ""; + + // Read the properties file, setting any defaults where it makes sense + FileInputStream PropertyFile = null; + try { + PropertyFile = + new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + propertiesFileName); + Properties HisProvisionerProperties = new Properties(); + HisProvisionerProperties.load(PropertyFile); + TpmOwnerAuth = TpmUtils.hexStringToByteArray(HisProvisionerProperties.getProperty(OWNER_AUTH)); + HisIdentityLabel = HisProvisionerProperties.getProperty(HIS_IDENTITY_LABEL, ""); + HisIdentityIndex = Integer.parseInt(HisProvisionerProperties.getProperty(HIS_IDENTITY_INDEX, "0")); + HisIdentityAuth = TpmUtils.hexStringToByteArray(HisProvisionerProperties.getProperty(HIS_IDENTITY_AUTH, "")); + PrivacyCaCertFile = HisProvisionerProperties.getProperty(PRIVACY_CA_CERT, ""); + PrivacyCaUrl = HisProvisionerProperties.getProperty(PRIVACY_CA_URL, ""); + TrustStore = HisProvisionerProperties.getProperty(TRUST_STORE, "TrustStore.jks"); + ClientPath = HisProvisionerProperties.getProperty(CLIENT_PATH, ""); + ecStorage = HisProvisionerProperties.getProperty(EC_STORAGE, "NVRAM"); + } catch (FileNotFoundException e) { // If the properties file is not found, display error + System.out.println("Error finding HIS Provisioner properties file (OATprovisioner.properties); using defaults."); + } catch (IOException e) { // If propertied file cannot be read, display error + System.out.println("Error loading HIS Provisioner properties file (OATprovisioner.properties); using defaults."); + } catch (NumberFormatException e) { + System.out.println("Error while reading HisIdentityIndex from OATprovisioner.properties" + e.getMessage()); + System.exit(1); + } finally { + if (PropertyFile != null) + try { + PropertyFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + // Check to see if any of the values were not populated with acceptable values + String errorString = "Properties file \"" + propertiesFileName + "\" contains errors:\n"; + boolean hasErrors = false; + if (TpmOwnerAuth == null || TpmOwnerAuth.length != 20) { + errorString += + " - \"TpmOwnerAuth\" value must be a 40 hexidecimal digit (20 byte) value representing the TPM owner authentication\n"; + hasErrors = true; + } + if (HisIdentityLabel.length() == 0) { + errorString += " - \"HisIdentityLabel\" value must be the subject name for the AIK certificate\n"; + hasErrors = true; + } + if (HisIdentityIndex == 0) { + errorString += " - \"HisIdentityIndex\" value must be the index for AIK storage\n"; + hasErrors = true; + } + if (HisIdentityAuth == null || HisIdentityAuth.length != 20) { + errorString += + " - \"HisIdentityAuth\" value must be a 40 hexidecimal digit (20 byte) value representing the AIK authentication\n"; + hasErrors = true; + } + if (PrivacyCaCertFile.length() == 0) { + errorString += " - \"PrivacyCaCertFile\" value must be the name of the Privacy CA certificate file\n"; + hasErrors = true; + } + if (PrivacyCaUrl.length() == 0) { + errorString += " - \"PrivacyCaUrl\" value must be the name of the URL of the Privacy CA web service\n"; + hasErrors = true; + } + if (TrustStore.length() == 0) { + errorString += + " - \"TrustStore\" value must be the name of the trust store for using the registration web service\n"; + hasErrors = true; + } + if (ClientPath.length() == 0) { + errorString += " - \"ClientPath\" value must be the path that will be used for installing the HIS Client\n"; + hasErrors = true; + } + // If there were errors that prevent the rest of the class from running, display the error specifics and exit + // with an error code. + if (hasErrors) { + System.out.println(errorString); + System.exit(99); + } + System.setProperty("javax.net.ssl.trustStore", "./" + TrustStore); + + // Provision an identity for HIS + System.out.println("Performing HIS identity provisioning..."); + + FileOutputStream pcaFileOut = null; + try { + boolean requiresAuthSha = false; + byte[] ownerAuthRaw = TpmOwnerAuth; + byte[] keyAuthRaw = HisIdentityAuth; + if (requiresAuthSha) { + ownerAuthRaw = TpmUtils.sha1hash(TpmOwnerAuth); + keyAuthRaw = TpmUtils.sha1hash(HisIdentityAuth); + } + X509Certificate pcaCert = TpmUtils.certFromFile(PrivacyCaCertFile); + boolean shortcut = true; + + if (TpmOwnerAuth == null) { + System.exit(99); + return; + } + byte[] ekCert = null; + if (ecStorage.equalsIgnoreCase("file")) + { + try { + File ecFile = + new File(System.getProperty("user.dir") + System.getProperty("file.separator") + ecStorageFileName); + FileInputStream ecFileIn = new FileInputStream(ecFile); + ekCert = new byte[ecFileIn.available()]; + ecFileIn.read(ekCert); + System.out.println("\n--read EC from file--"); + ecFileIn.close(); + } catch (Exception e) { + System.out.println("Failed to read EC from file: " + e.toString()); + System.exit(1); + } + } else { + ekCert = TpmModule.getCredential(TpmOwnerAuth, "EC"); + } + TpmIdentityRequest encryptedEkCert = + new TpmIdentityRequest(ekCert, (RSAPublicKey) pcaCert.getPublicKey(), false); + if (HisIdentityAuth == null) { + System.exit(99); + return; + } + TpmIdentity newId = + TpmModule.collateIdentityRequest(TpmOwnerAuth, + HisIdentityAuth, + HisIdentityLabel, + new TpmPubKey((RSAPublicKey) pcaCert.getPublicKey(), 3, 1).toByteArray(), + HisIdentityIndex, + (X509Certificate) null, + !shortcut); + + IHisPrivacyCAWebService2 hisPrivacyCAWebService2 = + HisPrivacyCAWebServices2ClientInvoker.getHisPrivacyCAWebService2(PrivacyCaUrl); + byte[] encrypted1 = + hisPrivacyCAWebService2.identityRequestGetChallenge(newId.getIdentityRequest(), + encryptedEkCert.toByteArray()); + if (encrypted1.length == 1) { + System.out.println("Identity request was rejected by Privacy CA in phase 1 of process"); + System.exit(1); + } + int os = IdentityOS.osType();// return os type. win:0; linux:1; other:-1 + + byte[] asym1 = new byte[256]; + System.arraycopy(encrypted1, 0, asym1, 0, asym1.length); + byte[] sym1 = new byte[encrypted1.length - 256]; + System.arraycopy(encrypted1, 256, sym1, 0, sym1.length); + byte[] decrypted1; + if (os == 1)// linux + decrypted1 = TpmModule.activateIdentity(ownerAuthRaw, keyAuthRaw, asym1, sym1, HisIdentityIndex); + else + //decrypted1 = TpmModuleJava.ActivateIdentity(asym1, sym1, aik, keyAuthRaw, srkAuthRaw, ownerAuthRaw); //Comments temporarily due to TSSCoreService.jar compiling issue + decrypted1 = TpmModule.activateIdentity(ownerAuthRaw, keyAuthRaw, asym1, sym1, HisIdentityIndex); + TpmIdentityRequest encryptedChallenge = + new TpmIdentityRequest(decrypted1, (RSAPublicKey) pcaCert.getPublicKey(), false); + byte[] encrypted2 = hisPrivacyCAWebService2.identityRequestSubmitResponse(encryptedChallenge.toByteArray()); + if (encrypted2.length == 1) { + System.out.println("Identity request was rejected by Privacy CA in phase 2 of process"); + System.exit(2); + return; + } + byte[] asym2 = new byte[256]; + System.arraycopy(encrypted2, 0, asym2, 0, asym2.length); + byte[] sym2 = new byte[encrypted2.length - 256]; + System.arraycopy(encrypted2, 256, sym2, 0, sym2.length); + byte[] decrypted2; + if (os == 1)// linux + decrypted2 = TpmModule.activateIdentity(ownerAuthRaw, keyAuthRaw, asym2, sym2, HisIdentityIndex); + else + //decrypted1 = TpmModuleJava.ActivateIdentity(asym1, sym1, aik, keyAuthRaw, srkAuthRaw, ownerAuthRaw); + //decrypted2 = TpmModuleJava.ActivateIdentity(asym2, sym2, aik, keyAuthRaw, srkAuthRaw, ownerAuthRaw);//Comments temporarily due to TSSCoreService.jar compiling issue + decrypted2 = TpmModule.activateIdentity(ownerAuthRaw, keyAuthRaw, asym2, sym2, HisIdentityIndex); + File outPath = new File(ClientPath); + File outFile = new File(ClientPath + "/aik.cer"); + if (!outPath.isDirectory()) { + if (!outPath.mkdirs()) { + System.out.println("Failed to create client installation path!"); + System.exit(5); + } + } + pcaFileOut = new FileOutputStream(outFile); + pcaFileOut.write(decrypted2); + pcaFileOut.flush(); + pcaFileOut.close(); + } catch (Exception e) { + System.out.println("FAILED, error message is: " + e.toString()); + e.printStackTrace(); + System.exit(1); + } finally { + if (pcaFileOut != null) + try { + pcaFileOut.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + System.out.println("DONE"); + return; + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/HisRegisterIdentity.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/HisRegisterIdentity.java new file mode 100644 index 0000000..0d70f9e --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/HisRegisterIdentity.java @@ -0,0 +1,119 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import gov.niarl.sal.webservices.hisWebService.client.HisWebServicesClientInvoker; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.HisEnrollmentWebService; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.security.cert.X509Certificate; +import java.util.Properties; + +/** + *

    + * This is part 3 of 3 for fully provisioning HIS on a Windows client. This class will register an identity provisioned + * using HisIdentityProvisioner and register that identity with an appraiser. + *

    + *

    + * This class utilizes a properties file. It looks for a file by the name of "HISprovisioner.properties" in the + * directory from which Java was invoked. + *

    + * The following values must be in the properties file: + *
      + *
    • HisRegistrationUrl This is the entire path to the registration service.
    • + *
    • TrustStore This is the name of the trust store used to encrypt the web service connection. This file must + * be provided by the web server hosting the appraiser and placed into the path that the provisioner is run from ("./"). + *
    • + *
    • ClientPath This is the path for the HIS client installation. The AIC (aic.cer) must be in this directory + * for registration to take place.
    • + *
    + * + * @author schawki + * + */ +public class HisRegisterIdentity { + + /** + * Entry point for the class + */ + public static void main(String[] args) { + final String HIS_REGISTRATION_URL = "HisRegistrationUrl"; + final String TRUST_STORE = "TrustStore"; + final String CLIENT_PATH = "ClientPath"; + + String HisRegistrationUrl = ""; + String TrustStore = ""; + String ClientPath = ""; + + String propertiesFileName = "OATprovisioner.properties"; + + FileInputStream PropertyFile = null; + try { + PropertyFile = + new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + propertiesFileName); + Properties HisProvisionerProperties = new Properties(); + HisProvisionerProperties.load(PropertyFile); + HisRegistrationUrl = HisProvisionerProperties.getProperty(HIS_REGISTRATION_URL, ""); + TrustStore = HisProvisionerProperties.getProperty(TRUST_STORE, "TrustStore.jks"); + ClientPath = HisProvisionerProperties.getProperty(CLIENT_PATH, ""); + } catch (FileNotFoundException e) { + System.out.println("Error finding HIS Provisioner properties file (OATprovisioner.properties)"); + } catch (IOException e) { + System.out.println("Error loading HIS Provisioner properties file (OATprovisioner.properties)"); + } finally { + if (PropertyFile != null) + try { + PropertyFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + String errorString = "Properties file \"" + propertiesFileName + "\" contains errors:\n"; + boolean hasErrors = false; + if (HisRegistrationUrl.length() == 0) { + errorString += " - \"HisRegistrationUrl\" value must be the URL of the HIS registrtion web service\n"; + hasErrors = true; + } + if (TrustStore.length() == 0) { + errorString += + " - \"TrustStore\" value must be the name of the trust store for using the registration web service\n"; + hasErrors = true; + } + if (ClientPath.length() == 0) { + errorString += " - \"ClientPath\" value must be the path that will be used for installing the HIS Client\n"; + hasErrors = true; + } + if (hasErrors) { + System.out.println(errorString); + System.exit(99); + } + System.setProperty("javax.net.ssl.trustStore", "./" + TrustStore); + + System.out.print("Registering identity with server..."); + try { + X509Certificate aikCert = TpmUtils.certFromFile(ClientPath + "/aik.cer"); + + HisEnrollmentWebService hisEnrollmentWebService = + HisWebServicesClientInvoker.getHisEnrollmentWebService(HisRegistrationUrl); + hisEnrollmentWebService.enrollHisMachine(TpmUtils.getHostname(), TpmUtils.PEMencodeCert(aikCert)); + } catch (Exception e) { + System.out.println("FAILED, error message is: " + e.toString()); + System.exit(1); + } + System.out.println("DONE"); + return; + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/HisSetup.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/HisSetup.java new file mode 100644 index 0000000..123c110 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/HisSetup.java @@ -0,0 +1,495 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.io.*; +import java.security.KeyStore; +import java.security.cert.X509Certificate; +import java.util.Enumeration; +import java.util.Properties; +import java.util.StringTokenizer; + +/** + * @deprecated + * + * This method will create all new files for a HIS deployment. + * + * The setup of the HisPrivacyCAWebServices2 Privacy CA replaces the functionality + * of this class. It currently does this by using this class. + * + * @author schawki + * + */ +public class HisSetup { + + /** + * @param args + */ + public static void main(String[] args) { + /* + * File needed to run: setup.properties + * Files needed as output: + * - endorsement p12 + * - Privacy CA p12 + * - Privacy CA certificate + * - Privacy CA properties + * - HIS provisioner properties + * + * Additional items needed (external): + * - trust store jks for web apps + */ + + // Read the properties file + /* + * PrivacyCaSubjectName = HIS_Privacy_CA + * PrivacyCaFileName = PrivCA.p12 + * PrivacyCaPassword = replace + * EndorsementCaSubjectame = Endorsement_CA_Rev_1 + * EndorsementCaFileName = EndorseCA.p12 + * EndorsementCaPassword = replace + * HisRegistrationUrl = https://replace + * PrivacyCaUrl = https://replace + * CertValidityDays = 3652 + * PrivacyCaCertFileName = PricCa.cer + * FileLocation = ./HIS_Setup + */ + FileOutputStream fos = null; + try { + System.out.print("Reading properties file..."); + final String PRIVACY_CA_SUBJECT_NAME = "PrivacyCaSubjectName"; + //final String PRIVACY_CA_FILE_NAME = "PrivacyCaFileName"; + final String PRIVACY_CA_PASSWORD = "PrivacyCaPassword"; + final String ENDORSEMENT_CA_SUBJECT_NAME = "EndorsementCaSubjectName"; + //final String ENDORSEMENT_CA_FILE_NAME = "EndorsementCaFileName"; + final String ENDORSEMENT_CA_PASSWORD = "EndorsementCaPassword"; + final String HIS_REGISTRATION_URL = "HisRegistrationUrl"; + final String PRIVACY_CA_URL = "PrivacyCaUrl"; + final String CERT_VALIDITY_DAYS = "CertValidityDays"; + //final String PRIVACY_CA_CERTIFICATE_FILE_NAME = "PrivacyCaCertFileName"; + final String FILE_LOCATION = "FileLocation"; + final String CLIENT_PATH = "ClientPath"; + final String AIK_AUTH = "AikAuth"; + final String EC_SIGNING_KEY_SIZE = "ecSigningKeySize"; + final String EC_STORAGE = "ecStorage"; + + FileInputStream PropertyFile = null; + String PrivacyCaSubjectName = "null"; + String PrivacyCaFileName = "PrivacyCA.p12"; + String PrivacyCaPassword = "null"; + String EndorsementCaSubjectName = "null"; + String EndorsementCaFileName = "endorsement.p12"; + String EndorsementCaPassword = "null"; + String HisRegistrationUrl = "null"; + String PrivacyCaUrl = "null"; + String CertValidityDays = "null"; + String PrivacyCaCertFileName = "PrivacyCA.cer"; + String EndorsementCaCertFileName = "EndorsementCA.cer"; + String FileLocation = ""; + String CredentialLocation = "/var/lib/oat-appraiser/"; + int ValidityDays; + String ClientPath = ""; + String AikAuth = ""; + String ecSigningKeySize = ""; + String ecStorage = ""; + String tomcatPath = System.getProperty("catalina.base"); + String configPath = "/etc/oat-appraiser/"; + /* + if (tomcatPath != null){ + configPath = tomcatPath + "/webapps/HisPrivacyCAWebServices2/"; + + } + */ + try { + PropertyFile = new FileInputStream(configPath + "setup.properties"); + Properties SetupProperties = new Properties(); + SetupProperties.load(PropertyFile); + PrivacyCaSubjectName = SetupProperties.getProperty(PRIVACY_CA_SUBJECT_NAME, "null"); + //PrivacyCaFileName = SetupProperties.getProperty(PRIVACY_CA_FILE_NAME, "null"); + PrivacyCaPassword = SetupProperties.getProperty(PRIVACY_CA_PASSWORD, "null"); + EndorsementCaSubjectName = SetupProperties.getProperty(ENDORSEMENT_CA_SUBJECT_NAME, "null"); + //EndorsementCaFileName = SetupProperties.getProperty(ENDORSEMENT_CA_FILE_NAME, "null"); + EndorsementCaPassword = SetupProperties.getProperty(ENDORSEMENT_CA_PASSWORD, "null"); + HisRegistrationUrl = SetupProperties.getProperty(HIS_REGISTRATION_URL, "null"); + PrivacyCaUrl = SetupProperties.getProperty(PRIVACY_CA_URL, "null"); + CertValidityDays = SetupProperties.getProperty(CERT_VALIDITY_DAYS, "null"); + //PrivacyCaCertFileName = SetupProperties.getProperty(PRIVACY_CA_CERTIFICATE_FILE_NAME, "null"); + FileLocation = SetupProperties.getProperty(FILE_LOCATION, "null"); + ClientPath = SetupProperties.getProperty(CLIENT_PATH, "C:/Program Files/NIARL/HIS"); + AikAuth = SetupProperties.getProperty(AIK_AUTH, "1111111111111111111111111111111111111111"); + ecSigningKeySize = SetupProperties.getProperty(EC_SIGNING_KEY_SIZE,"2048"); + ecStorage = SetupProperties.getProperty(EC_STORAGE, "NVRAM"); + System.out.println("ecSigningKeySize = " + ecSigningKeySize + "\n"); + System.out.println("ecStorage = " + ecStorage + "\n"); + + } catch (FileNotFoundException e) { + System.out.println("Error finding setup.properties file. Setup cannot continue without the information in this file."); + return; + } catch (IOException e) { + System.out.println("Error loading setup.properties file. Setup cannot continue without the information in this file."); + return; + } + finally{ + if (PropertyFile != null) + try { + PropertyFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + // Populate some strings if running from Tomcat + if (CredentialLocation != null){ + // Look for TrustStore.jks in tomcatPath + "/Certificate" + KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); +// FileInputStream fis = new FileInputStream(tomcatPath + "/Certificate/TrustStore.jks"); + FileInputStream fis = new FileInputStream(CredentialLocation + "Certificate/TrustStore.jks"); + + try { + ks.load(fis, null); + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (fis != null){ + fis.close(); + } + } + + Enumeration certList = ks.aliases(); + if (certList.hasMoreElements()){ + X509Certificate test = (X509Certificate)ks.getCertificate(certList.nextElement()); + String certDN = test.getSubjectX500Principal().getName("RFC1779"); + + StringTokenizer st = new StringTokenizer(certDN, ","); + String certCN = ""; + while(st.hasMoreElements()){ + String line = st.nextToken(); + if(line.startsWith("CN")){ + certCN = line.subSequence(line.indexOf("=") + 1, line.length()).toString(); + break; + } + } + while(certCN.startsWith(" ")){ + certCN = certCN.subSequence(1, certCN.length()).toString(); + } + // If there, it can be copied later, but now should be used to extract the url! + PrivacyCaUrl = "https://" + certCN + ":8443/HisPrivacyCAWebServices2"; + HisRegistrationUrl = "https://" + certCN + ":8443/HisWebServices"; + } + + } + // Continue processing properties file + if (PrivacyCaSubjectName.equals("null")){ + System.out.println("Error finding element \"PrivacyCaSubjectName\" in properties file. Setup cannot continue without this information."); + return; + } + /*if (PrivacyCaFileName.equals("null")){ + System.out.println("Error finding element \"PrivacyCaFileName\" in properties file. Setup cannot continue without this information."); + return; + }*/ + if (PrivacyCaPassword.equals("null")){ + System.out.println("Error finding element \"PrivacyCaPassword\" in properties file. Setup cannot continue without this information."); + return; + } + if (EndorsementCaSubjectName.equals("null")){ + System.out.println("Error finding element \"EndorsementCaSubjectName\" in properties file. Setup cannot continue without this information."); + return; + } + /*if (EndorsementCaFileName.equals("null")){ + System.out.println("Error finding element \"EndorsementCaFileName\" in properties file. Setup cannot continue without this information."); + return; + }*/ + if (EndorsementCaPassword.equals("null")){ + System.out.println("Error finding element \"EndorsementCaPassword\" in properties file. Setup cannot continue without this information."); + return; + } + if (HisRegistrationUrl.equals("null")){ + System.out.println("Error finding element \"HisRegistrationUrl\" in properties file. Setup cannot continue without this information."); + return; + } + if (PrivacyCaUrl.equals("null")){ + System.out.println("Error finding element \"PrivacyCaUrl\" in properties file. Setup cannot continue without this information."); + return; + } + if (CertValidityDays.equals("null")){ + System.out.println("Error finding element \"CertValidityDays\" in properties file. Setup cannot continue without this information."); + return; + } + /*if (PrivacyCaCertFileName.equals("null")){ + System.out.println("Error finding element \"PrivacyCaCertFileName\" in properties file. Setup cannot continue without this information."); + return; + }*/ + if (FileLocation.equals("null")){ + System.out.println("Error finding element \"FileLocation\" in properties file. Setup cannot continue without this information."); + return; + } + + //create random passwords! + if(PrivacyCaPassword.equals("***replace***")) + PrivacyCaPassword = TpmUtils.byteArrayToHexString(TpmUtils.createRandomBytes(16)); + if(EndorsementCaPassword.equals("***replace***")) + EndorsementCaPassword = TpmUtils.byteArrayToHexString(TpmUtils.createRandomBytes(16)); + String clientPath = ""; + String ecCaPath = ""; + int KeySize = 2048; + if (tomcatPath != null){ + InputStream in = null; + OutputStream out = null; + try { + //FileLocation = tomcatPath + "/webapps/HisPrivacyCAWebServices2/"; + //FileLocation = "/var/lib/oat-appraiser/"; + clientPath = "ClientFiles"; + ecCaPath = "CaCerts"; + //copy the TrustStore: FileLocation + "/Certificate/TrustStore.jks" + //in = new FileInputStream(new File(tomcatPath + "/Certificate/TrustStore.jks")); + in = new FileInputStream(new File(CredentialLocation + "Certificate/TrustStore.jks")); + out = new FileOutputStream(new File(CredentialLocation + clientPath + "/TrustStore.jks")); + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) > 0) + out.write(buf, 0, len); + in.close(); + out.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (in != null){ + try { + in.close(); + } catch (Exception e2) { + if (out != null) + out.close(); + } + + } + if (out != null){ + out.close(); + } + } + + } else { + tomcatPath = ""; + } + + ValidityDays = Integer.parseInt(CertValidityDays); + System.out.println("DONE"); + // Create the p12 files (2) + /* + * PrivacyCaSubjectName = HIS_Privacy_CA + * PrivacyCaFileName = PrivacyCA.p12 + * PrivacyCaPassword = replace + * EndorsementCaSubjectName = Endorsement_CA_Rev_1 + * EndorsementCaFileName = EndorseCA.p12 + * EndorsementCaPassword = replace + * HisRegistrationUrl = https://replace + * PrivacyCaUrl = https://replace + * CertValidityDays = 3652 + * PrivacyCaCertFileName = PrivCa.cer + * FileLocation = ./HIS_Setup .equals + */ + System.out.print("Creating p12 files..."); + // if(Integer.parseInt(ecSigningKeySize) == 1024 || Integer.parseInt(ecSigningKeySize) == 3072) + if(ecSigningKeySize.equals("1024") || ecSigningKeySize.equals("2048") || ecSigningKeySize.equals("3072")) + { + KeySize = Integer.parseInt(ecSigningKeySize); + } + TpmUtils.createCaP12(2048, PrivacyCaSubjectName, PrivacyCaPassword, CredentialLocation + PrivacyCaFileName, ValidityDays); + TpmUtils.createCaP12(KeySize, EndorsementCaSubjectName, EndorsementCaPassword, CredentialLocation + clientPath + "/" + EndorsementCaFileName, ValidityDays); + + + System.out.println("DONE"); + // Create the Privacy CA certificate file + System.out.print("Creating Privacy CA certificate..."); + X509Certificate pcaCert = TpmUtils.certFromP12(CredentialLocation + PrivacyCaFileName, PrivacyCaPassword); + FileOutputStream pcaFileOut = new FileOutputStream(new File(CredentialLocation + clientPath + "/" + PrivacyCaCertFileName)); + try { + if (pcaCert != null) + pcaFileOut.write(pcaCert.getEncoded()); + pcaFileOut.flush(); + pcaFileOut.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (pcaFileOut != null) + pcaFileOut.close(); + } + System.out.println("DONE"); + + // Create the Endorsement CA certificate file + System.out.print("Creating Endorsement CA certificate..."); + X509Certificate ecCert = TpmUtils.certFromP12(CredentialLocation + clientPath + "/" + EndorsementCaFileName, EndorsementCaPassword); + FileOutputStream ecFileOut = new FileOutputStream(new File(CredentialLocation + ecCaPath + "/" + EndorsementCaCertFileName)); + try { + if (ecCert != null) + ecFileOut.write(ecCert.getEncoded()); + ecFileOut.flush(); + ecFileOut.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (ecFileOut != null) + ecFileOut.close(); + } + + System.out.println("DONE"); + + // Create the other properties files (HISprovisioner and PrivacyCA) + System.out.print("Creating properties files..."); + String PrivacyCaPropertiesFile = "PrivacyCA.properties"; + String HisProvisionerPropertiesFile = "OATprovisioner.properties"; + String HisStandalonePropertiesFile = "OAT.properties"; + + /* + * + */ + //fos = new FileOutputStream(FileLocation + "/" + PrivacyCaPropertiesFile); + fos = new FileOutputStream(configPath + PrivacyCaPropertiesFile); + /* + * #Privacy CA Operation + * P12filename = PrivacyCA.p12 + * P12password = ***replace*** + * PrivCaCertValiditydays = 3652 + * #Privacy CA Registration + * HisRegistrationUrl = ***replace*** + * TrustStore = TrustStore.jks + */ + String toWrite = + "#Privacy CA Operation\r\n" + + "P12filename = " + PrivacyCaFileName + "\r\n" + + "P12password = " + PrivacyCaPassword + "\r\n" + + "PrivCaCertValiditydays = " + CertValidityDays + "\r\n" + + "#Privacy CA Registration\r\n" + + "HisRegistrationUrl = " + HisRegistrationUrl + "\r\n" + + "TrustStore = TrustStore.jks"; + try { + fos.write(toWrite.getBytes("US-ASCII")); + fos.flush(); + fos.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (fos != null) + fos.close(); + } + + + /* + * File: OATprovisioner.properties + * Used by: HisTpmProvisioner, HisIdentityProvisioner, HisRegisterIdentity + */ + fos = new FileOutputStream(CredentialLocation + clientPath + "/" + HisProvisionerPropertiesFile); + toWrite = + "#TPM Provisioning Data\r\n" + + "TpmEndorsmentP12 = " + EndorsementCaFileName + "\r\n" + + "EndorsementP12Pass = " + EndorsementCaPassword + "\r\n" + + "EcValidityDays = " + CertValidityDays + "\r\n" + + "TpmOwnerAuth = 1111111111111111111111111111111111111111\r\n" + + "##########HIS Identity Provisioning Data############\r\n" + + "HisIdentityLabel = HIS Identity Key\r\n" + + "HisIdentityIndex = 1\r\n" + + "HisIdentityAuth = " + AikAuth + "\r\n" + + "PrivacyCaCertFile = " + PrivacyCaCertFileName + "\r\n" + + "PrivacyCaUrl = " + PrivacyCaUrl + "\r\n" + + "HisRegistrationUrl = " + HisRegistrationUrl + "\r\n" + + "TrustStore = TrustStore.jks\r\n" + + "NtruBypass = true\r\n" + + "ClientPath = " + ClientPath + "\r\n" + + "ecStorage = " + ecStorage + "\r\n" + + "ecSigningKeySize = " + ecSigningKeySize + "\r\n"; + + try { + fos.write(toWrite.getBytes("US-ASCII")); + fos.flush(); + fos.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (fos != null) + fos.close(); + } + + + /* + * File: HIS.properties + * Used by: HIS Standalone (client reporter) + */ + fos = new FileOutputStream(CredentialLocation + clientPath + "/" + HisStandalonePropertiesFile); + toWrite = + "WebServiceUrl=" + HisRegistrationUrl + "\r\n" + + "KeyAuth=" + AikAuth + "\r\n" + + "KeyIndex=1\r\n" + + "TpmQuoteExecutableName=NIARL_TPM_Module.exe\r\n" + + "SplashImage=HIS07.jpg\r\n" + + "TrustStore=TrustStore.jks\r\n"; + + try { + fos.write(toWrite.getBytes("US-ASCII")); + fos.flush(); + fos.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (fos != null) + fos.close(); + } + + + /* + * File: install.bat + * Used by: not a properties file, but... assembles a batch file for the client installer + */ + String WinClientPath = CredentialLocation.replace("/", "\\"); + fos = new FileOutputStream(CredentialLocation + clientPath + "/install.bat"); + toWrite = + "rem DO NOT EDIT THIS FILE!\r\n" + + "rem This file is generated by the Privacy CA installation utility in Java\r\n" + + "call UninstallUSW.bat\r\n" + + "HIS-Standalone-Setup-v3.0a.exe /VERYSILENT /SUPPRESSMSGBOXES /LOG=\"tpminstall.log\" /DIR=\"" + ClientPath + "/\"\r\n" + + "copy /Y OAT.properties \"" + WinClientPath + "\\HIS.properties\"\r\n" + + "copy /Y trustStore.jks \"" + WinClientPath + "\\\"\r\n" + + "copy /Y NIARL_TPM_Module.exe \"" + WinClientPath + "\\\"\r\n" + + "rem cd \"HIS Provisioner\" \r\n" + + "call provisioner.bat\r\n" + + "cd \"" + WinClientPath + "\\service\\\"\r\n" + + "call \"replaceUSW.bat\"\r\n"; + try { + fos.write(toWrite.getBytes("US-ASCII")); + fos.flush(); + fos.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (fos != null) + fos.close(); + } + + System.out.println("DONE"); + } catch (Exception e) { + System.out.println(e.toString()); + } + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/HisTpmProvisioner.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/HisTpmProvisioner.java new file mode 100644 index 0000000..c72c8c2 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/HisTpmProvisioner.java @@ -0,0 +1,283 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import gov.niarl.his.privacyca.TpmModule.TpmModuleException; +import gov.niarl.his.webservices.hisPrivacyCAWebService2.IHisPrivacyCAWebService2; +import gov.niarl.his.webservices.hisPrivacyCAWebService2.client.HisPrivacyCAWebServices2ClientInvoker; + +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.File; +import java.io.FileOutputStream; + +import java.security.NoSuchAlgorithmException; +import java.security.Security; +import java.security.PublicKey; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.util.Properties; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.security.cert.CertificateException; +import java.security.interfaces.RSAPublicKey; + +import org.bouncycastle.jce.provider.BouncyCastleProvider; + +/** + *

    This is part 1 of 3 for fully provisioning HIS on a Windows client. This class does the initial provisioning of the TPM.

    + * This provisioning includes: + *
      + *
    • Taking ownership of the TPM
    • + *
    • Creating an Endorsement Certificate
    • + *
    • Storing the Endorsement Certificate in the TPM's NVRAM
    • + *
    + * + *

    This class utilizes a properties file. It looks for a file by the name of "HISprovisioner.properties" in the directory from which Java was invoked.

    + * The following values must be in the properties file:
    + *
      + *
    • TpmEndorsmentP12
    • + *
    • EndorsementP12Pass
    • + *
    • EcValidityDays
    • + *
    • TpmOwnerAuth This must be a 40 digit (20 byte) hex code representing the owner auth data to be assigned.
    • + *
    + * + * @author schawki + * + */ +public class HisTpmProvisioner { + + /** + * Entry point into the program + */ + public static void main(String[] args){// throws InvalidKeyException, CertificateEncodingException, UnrecoverableKeyException, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, NoSuchProviderException, KeyStoreException, CertificateException, IOException, javax.security.cert.CertificateException { + //get properties file info + final String EC_VALIDITY = "EcValidityDays"; + final String OWNER_AUTH = "TpmOwnerAuth"; + final String PRIVACY_CA_URL = "PrivacyCaUrl"; + final String TRUST_STORE = "TrustStore"; + final String EC_STORAGE = "ecStorage"; + final String PRIVACY_CA_CERT = "PrivacyCaCertFile"; + final String propertiesFileName = "OATprovisioner.properties"; + final String ecStorageFileName = "EC.cer"; + int EcValidityDays = 0; + byte [] TpmOwnerAuth = null; + byte [] encryptCert = null; + byte [] pubEkMod = null; + String TrustStore = ""; + String ecStorage = ""; + String PrivacyCaCertFile = ""; + String PrivacyCaUrl = ""; + X509Certificate pcaCert = null; + PublicKey publicKey = null; + FileInputStream PropertyFile = null; + + try { + PropertyFile = new FileInputStream(System.getProperty("user.dir") + System.getProperty("file.separator") + propertiesFileName); + Properties HisProvisionerProperties = new Properties(); + HisProvisionerProperties.load(PropertyFile); + EcValidityDays = Integer.parseInt(HisProvisionerProperties.getProperty(EC_VALIDITY, "")); + TpmOwnerAuth = TpmUtils.hexStringToByteArray(HisProvisionerProperties.getProperty(OWNER_AUTH, "")); + PrivacyCaUrl = HisProvisionerProperties.getProperty(PRIVACY_CA_URL, ""); + PrivacyCaCertFile = HisProvisionerProperties.getProperty(PRIVACY_CA_CERT, ""); + TrustStore = HisProvisionerProperties.getProperty(TRUST_STORE, "TrustStore.jks"); + ecStorage = HisProvisionerProperties.getProperty(EC_STORAGE, "NVRAM"); + //TODO, it not a good manner to always print out the message into console + //keep here as it will help user get some direct message + System.out.println("### ecStorage = " + ecStorage + "###"); + } catch (FileNotFoundException e) { + System.out.println("Error finding HIS Provisioner properties file (OATprovisioner.properties)"); + } catch (IOException e) { + System.out.println("Error loading HIS Provisioner properties file (OATprovisioner.properties)"); + } + catch (NumberFormatException e) { + e.printStackTrace(); + } finally{ + if (PropertyFile != null){ + try { + PropertyFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + String errorString = "Properties file \"" + propertiesFileName + "\" contains errors:\n"; + boolean hasErrors = false; + if(EcValidityDays == 0){ + errorString += " - \"EcValidityDays\" value must be the number of validity days for the Endorsement Credential\n"; + hasErrors = true; + } + if(TpmOwnerAuth ==null || TpmOwnerAuth.length != 20){ + errorString += " - \"TpmOwnerAuth\" value must be a 40 hexidecimal digit (20 byte) value representing the TPM owner auth\n"; + hasErrors = true; + } + if(PrivacyCaCertFile.length() == 0){ + errorString += "There is a improper configuration within properties file, please check the file first\n"; + hasErrors = true; + } + if(hasErrors){ + System.out.println(errorString); + System.exit(99); + return; + } + + //Provision the TPM + System.out.print("Performing TPM provisioning..."); + + /* + * The following actions must be performed during the TPM Provisioning process: + * 1. Take ownership of the TPM + * - owner auth + * 2. Create an Endorsement Certificate (EC) + * - public EK + * - owner auth (should already have from above) + * - private key and cert for CA to create new cert + * - validity period of EC cert + * 3. Store the newly created EC in the TPM's NV-RAM + */ + SecretKey deskey = null; + KeyGenerator keygen; + Security.addProvider(new BouncyCastleProvider()); + // Take Ownership + byte [] nonce = null; + try { + nonce = TpmUtils.createRandomBytes(20); + TpmModule.takeOwnership(TpmOwnerAuth, nonce); + } catch (TpmModuleException e){ + if(e.toString().contains(".takeOwnership returned nonzero error: 4")){ + System.out.println("Ownership is already taken"); + } else { + System.out.println("Error while taking ownership: " + e.toString()); + System.exit(1); + } + } catch (IOException e) { + e.printStackTrace(); + System.exit(1); + } + + // Generate security key via 3DES algorithm + try { + keygen = KeyGenerator.getInstance("DESede"); + deskey = keygen.generateKey(); + } catch (NoSuchAlgorithmException e) { + System.out.println("Error while generating 3DES key" + e.toString()); + e.printStackTrace(); + System.exit(1); + } + + // Create Endorsement Certificate + try { + nonce = TpmUtils.createRandomBytes(20); + pubEkMod = TpmModule.getEndorsementKeyModulus(TpmOwnerAuth, nonce); + } catch (TpmModuleException e){ + System.out.println("Error while getting PubEK: " + e.toString()); + System.exit(1); + } catch (Exception e){ + System.out.println("Error while getting PubEK: " + e.toString()); + System.exit(1); + } + + try { + pcaCert = TpmUtils.certFromFile(PrivacyCaCertFile); + if (pcaCert != null){ + publicKey = (RSAPublicKey)pcaCert.getPublicKey(); + } + } catch (Exception e){ + System.out.println("Error while getting PCA public key: " + e.toString()); + System.exit(1); + } + + + System.setProperty("javax.net.ssl.trustStore", "./" + TrustStore); + try { + IHisPrivacyCAWebService2 hisPrivacyCAWebService2 = HisPrivacyCAWebServices2ClientInvoker.getHisPrivacyCAWebService2(PrivacyCaUrl); + encryptCert = hisPrivacyCAWebService2.requestGetEC(encryptDES(pubEkMod, deskey), encryptRSA(deskey.getEncoded(), publicKey), EcValidityDays); + } catch (Exception e){ + System.out.println("Failed to sign EC on PCA, error message is: " + e.getMessage()); + System.exit(1); + } + + //Decrypt and generate endorsement certificate + X509Certificate ekCert = null; + try { + if (encryptCert != null){ + ekCert = TpmUtils.certFromBytes(decryptDES(encryptCert, deskey)); + } + } catch (java.security.cert.CertificateException e) { + System.out.println("Error while decrypting endorsement certificate, error message is: " + e.getMessage()); + System.exit(1); + } catch (CertificateException e) { + e.printStackTrace(); + System.exit(1); + } catch (Exception e) { + e.printStackTrace(); + System.exit(1); + } + + // Store the new EC in NV-RAM + if (ecStorage.equalsIgnoreCase("file")) { + System.out.println("\n--store EC in file--"); + try{ + File ecFile = new File(System.getProperty("user.dir") + System.getProperty("file.separator") + ecStorageFileName); + FileOutputStream ecFileOut = new FileOutputStream(ecFile); + ecFileOut.write(ekCert.getEncoded()); + ecFileOut.flush(); + ecFileOut.close(); + } catch(Exception e) { + System.out.println("Failed to write EC into file, error message is: " + e.getMessage()); + e.printStackTrace(); + System.exit(1); + } + } else { + try{ + TpmModule.setCredential(TpmOwnerAuth, "EC", ekCert.getEncoded()); + System.out.println("The size of endorsement certificate: " + ekCert.getEncoded().length); + } catch (TpmModuleException e){ + System.out.println("Error while seting credential: " + e.toString()); + System.exit(1); + } catch (CertificateEncodingException e) { + //TODO we'd better reduce the frequency of printing stack trace; + e.printStackTrace(); + System.exit(1); + } catch (IOException e) { + e.printStackTrace(); + System.exit(1); + } + } + System.out.println("DONE"); + return; + } + + //we cannot always rely on JDK itself, specify the provide as "BC" to compatible with server side; + private static byte[] encryptDES(byte[] text, SecretKey key) throws Exception { + Cipher c = Cipher.getInstance("DESede/ECB/PKCS7Padding", "BC"); + c.init(Cipher.ENCRYPT_MODE, key); + return c.doFinal(text); + } + + private static byte[] encryptRSA(byte[] text, PublicKey pubRSA) throws Exception { + Cipher cipher = Cipher.getInstance("RSA", "BC"); + cipher.init(Cipher.ENCRYPT_MODE, pubRSA); + return cipher.doFinal(text); + } + + private static byte[] decryptDES(byte[] text, SecretKey key) throws Exception { + Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS7Padding", "BC"); + cipher.init(Cipher.DECRYPT_MODE, key); + return cipher.doFinal(text); + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/IdentityOS.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/IdentityOS.java new file mode 100644 index 0000000..ee3ec4e --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/IdentityOS.java @@ -0,0 +1,58 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 gov.niarl.his.privacyca; +import java.util.*; +import java.net.InetAddress; + +/* + * win : return 0; + * nix/nux: return 1; + * other: return -1 + */ +public class IdentityOS { + +// public static void main(String[] args){ +// System.out.println("dgag"); +// } + + public static int osType(){ + if(isWindows()){ +// System.out.println("This is Windows"); + return 0; + }else if(isUnix()){ +// System.out.println("This is Unix or Linux"); + return 1; + }else{ +// System.out.println("Your OS is not support!!"); + return -1; + } + } + + public static boolean isWindows(){ + + String os = System.getProperty("os.name").toLowerCase(); + //windows + return (os.indexOf( "win" ) >= 0); + + } + + public static boolean isUnix(){ + + String os = System.getProperty("os.name").toLowerCase(); + //linux or unix + return (os.indexOf( "nix") >=0 || os.indexOf( "nux") >=0); + + } + + +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/LPSliveCdPrep.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/LPSliveCdPrep.java new file mode 100644 index 0000000..0c63cca --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/LPSliveCdPrep.java @@ -0,0 +1,156 @@ +/* + * 2011, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +//import gov.niarl.sal.webservices.hisWebService.client.HisWebServicesClientInvoker; +//import gov.niarl.sal.webservices.hisWebServices.clientWsImport.HisEnrollmentWebService; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.util.Properties; +import java.util.zip.CRC32; + +/** + *

    This class is used to setup an LPS bootable CD. This should be run during the boot + * process. No unique data for any particular machine is stored on the LPS CD, as the CD + * may be used on many different machines. the HIS client requires that each machine + * have a unique machine name, which must be associated with a particular TPM. The client + * must have provisioned an AIK and registered the corresponding AIC with the HIS appraiser + * using the unique machine name. This is true for all HIS clients. LPS/bootable-CD HIS + * clients differ from traditional HIS clients in that the unique name is derived from the + * TPM's Endorsement Key (EK), and the AIK is stored in the TPM's NVRAM. The main function + * in this class is supposed to set the hostname on the system, extract the AIK from the + * TPM's NVRAM, and set that AIK for use by the normal HIS Standalone Client.

    + * + *

    This class is designed to run even if the machine booting to the LPS CD has not been + * provisioned. However, if this is done the AIK will not be properly registered. The + * failure to load and register an AIK on the system will not be obvious to a user on the + * system. Even though the hostname could be derived without being provisioned, this + * program will set the hostname to "LPS-NoProvision" if the AIK could not be found. This + * should indicate to the user that the machine must be provisioned for HIS.

    + * + *

    Registration can be performed by running the LPSprovisioner class.

    + * + * @author schawki + * + */ +public class LPSliveCdPrep { + /** + * Entry point into the program. + */ + public static void main(String[] args) { + //TPM Provisioning Data + final String OWNER_AUTH = "TpmOwnerAuth"; + + //HIS Identity Provisioning Data + final String HIS_IDENTITY_INDEX = "HisIdentityIndex"; + final String HIS_IDENTITY_AUTH = "HisIdentityAuth"; + + //Properties variables with defaults: + byte [] TpmOwnerAuth = TpmUtils.hexStringToByteArray("1111111111111111111111111111111111111111"); + int HisIdentityIndex = 1; + byte [] HisIdentityAuth = TpmUtils.hexStringToByteArray("1111111111111111111111111111111111111111"); + + String propertiesFileName = "./HISprovisioner.properties"; + + FileInputStream PropertyFile = null; + try { + PropertyFile = new FileInputStream(propertiesFileName); + Properties HisProvisionerProperties = new Properties(); + HisProvisionerProperties.load(PropertyFile); + + TpmOwnerAuth = TpmUtils.hexStringToByteArray(HisProvisionerProperties.getProperty(OWNER_AUTH, "1111111111111111111111111111111111111111")); + HisIdentityIndex = Integer.parseInt(HisProvisionerProperties.getProperty(HIS_IDENTITY_INDEX, "1")); + HisIdentityAuth = TpmUtils.hexStringToByteArray(HisProvisionerProperties.getProperty(HIS_IDENTITY_AUTH, "1111111111111111111111111111111111111111")); + } catch (FileNotFoundException e) { + System.out.println("Error finding HIS Provisioner properties file (HISprovisionier.properties); using defaults."); + } catch (IOException e) { + System.out.println("Error loading HIS Provisioner properties file (HISprovisionier.properties); using defaults."); + } + catch (NumberFormatException e) { + e.printStackTrace(); + } + finally{ + if (PropertyFile != null){ + try { + PropertyFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + try{ + // pull the AIK key blob from the TPM's NVRAM + byte[] aikRawBlob = null; + try { + aikRawBlob = TpmModule.getCredential(TpmOwnerAuth, "PCC"); + }catch(Exception g){ + g.printStackTrace(); + //do nothing -- This is run on every boot of the LPS CD, including the first boot -- where there should be no AIK stored in the TPM anyway + } + + String hostname = ""; + if (aikRawBlob != null){ + // set the AIK using the blob that should be stored in the TPM's NVRAM + byte[] aikBlob = new byte[aikRawBlob.length - 4]; + System.arraycopy(aikRawBlob, 4, aikBlob, 0, aikBlob.length); + try{ + TpmModule.clearKey("identity", HisIdentityAuth, HisIdentityIndex); + }catch(Exception f){ + f.printStackTrace(); + //do nothing -- it may be that there is no key there to clear! (this is hopefully the case) + } + TpmModule.setKey("identity", HisIdentityAuth, aikBlob, HisIdentityIndex); + + //re-create the hostname in a standard way, by concatenating "LPS-" with the CRC32 of the public Endorsement Key + CRC32 crc = new CRC32(); + crc.update(TpmModule.getEndorsementKeyModulus(TpmOwnerAuth, TpmOwnerAuth)); + hostname = "LPS-" + Long.toHexString(crc.getValue()).toUpperCase(); + } else { + hostname = "LPS-NoProvision"; + } + System.out.print(hostname); // dump to screen + + //set the hostname on the system + Runtime.getRuntime().exec("hostname " + hostname); + //place the hostname in the local hosts file, associated with the loopback adapter + File hostfile = new File("/etc/hosts"); + FileOutputStream hostfileStream = new FileOutputStream(hostfile); + try { + OutputStreamWriter hfile = new OutputStreamWriter(hostfileStream); + hfile.append("127.0.0.1\tlocalhost " + hostname + "\n"); + hfile.flush(); + hfile.close(); + + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (hostfileStream != null) + hostfileStream.close(); + } + + + } catch (Exception e) { + e.printStackTrace(); + } + + } + +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/PrivacyCaException.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/PrivacyCaException.java new file mode 100644 index 0000000..0f69790 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/PrivacyCaException.java @@ -0,0 +1,32 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +/** + *

    This exception is intended to be used to throw Privacy CA-specific exceptions.

    + * + * @author schawki + * + */ +public class PrivacyCaException extends Exception { + private static final long serialVersionUID = 0; + /** + * Create the exception using a message string. + * + * @param msg Custom message for the exception + */ + public PrivacyCaException(String msg) { + super(msg); + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/RegisterPrivacyCa.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/RegisterPrivacyCa.java new file mode 100644 index 0000000..69ebdf1 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/RegisterPrivacyCa.java @@ -0,0 +1,110 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import gov.niarl.sal.webservices.hisWebService.client.*; +import gov.niarl.sal.webservices.hisWebServices.clientWsImport.*; + +import java.io.*; +import java.security.cert.X509Certificate; +import java.util.Properties; + +/** + * @deprecated + *

    This class is to be used for registration of the Privacy CA to the HIS appraiser.

    + *

    The HisPrivacyCAWebServices2 auto-enrolls itself. This can still be used with the first-generation Privacy CA.

    + * Properties file named "HISprovisioner.properties" is expected with the following values: + *
      + *
    • HisRegistrationUrl The complete URL to the appraiser's web service.
    • + *
    • TrustStore The path and file name of the trust store, often named "TrustStore.jks."
    • + *
    • PrivacyCaCertFile The path to and file name of the Privacy CA's certificate, in X.509 form. This is usually a ".cer" or ".crt" file.
    • + *
    + * @author schawki + * + */ +public class RegisterPrivacyCa { + /** + * Entry point into the program. + */ + public static void main(String[] args) { + final String HIS_REGISTRATION_URL = "HisRegistrationUrl"; + final String TRUST_STORE = "TrustStore"; + final String PRIVACY_CA_CERT = "PrivacyCaCertFile"; + + String HisRegistrationUrl = ""; + String TrustStore = ""; + String PrivacyCaCertFile = ""; + + String propertiesFileName = "./HISprovisioner.properties"; + + FileInputStream PropertyFile = null; + try { + PropertyFile = new FileInputStream(propertiesFileName); + Properties HisProvisionerProperties = new Properties(); + HisProvisionerProperties.load(PropertyFile); + + HisRegistrationUrl = HisProvisionerProperties.getProperty(HIS_REGISTRATION_URL, ""); + TrustStore = HisProvisionerProperties.getProperty(TRUST_STORE, "TrustStore.jks"); + PrivacyCaCertFile = HisProvisionerProperties.getProperty(PRIVACY_CA_CERT, ""); + } catch (FileNotFoundException e) { + System.out.println("Error finding HIS Provisioner properties file (HISprovisionier.properties)"); + } catch (IOException e) { + System.out.println("Error loading HIS Provisioner properties file (HISprovisionier.properties)"); + } + finally{ + if (PropertyFile != null){ + try { + PropertyFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + String errorString = "Properties file \"" + propertiesFileName + "\" contains errors:\n"; + boolean hasErrors = false; + if(HisRegistrationUrl.length() == 0){ + errorString += " - \"HisRegistrationUrl\" value must be the URL of the HIS registrtion web service\n"; + hasErrors = true; + } + if(TrustStore.length() == 0){ + errorString += " - \"TrustStore\" value must be the name of the trust store for using the registration web service\n"; + hasErrors = true; + } + if(PrivacyCaCertFile.length() == 0){ + errorString += " - \"PrivacyCaCertFile\" value must be the name of the Privacy CA certificate file\n"; + hasErrors = true; + } + if(hasErrors){ + System.out.println(errorString); + System.exit(99); + return; + } + System.setProperty("javax.net.ssl.trustStore", "./" + TrustStore); + + System.out.print("Registering Privacy CA with server..."); + try{ + X509Certificate privCaCert = TpmUtils.certFromFile(PrivacyCaCertFile); + + HisEnrollmentWebService hisEnrollmentWebService = HisWebServicesClientInvoker.getHisEnrollmentWebService(HisRegistrationUrl); + hisEnrollmentWebService.enrollHisMachine("_PrivacyCA", TpmUtils.PEMencodeCert(privCaCert)); + } catch (Exception e){ + System.out.println(e.toString()); + System.exit(1); + } + + System.out.println("DONE"); + System.exit(0); + return; + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmAsymCaContents.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmAsymCaContents.java new file mode 100644 index 0000000..d6783a0 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmAsymCaContents.java @@ -0,0 +1,129 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.security.*; +import java.security.spec.*; +import java.security.interfaces.*; +import javax.crypto.*; +import javax.crypto.spec.*; + +/** + *

    This class is the Java version of the C-style structure TPM_ASYM_CA_CONTENTS, + * as specified by the TCG. It contains all of the member variables specified by + * the TCG, and any applicable functions. This structure is normally created by + * the Privacy CA, is encrypted using a TPM's public EK, and holds the symmetric + * key needed to decrypt a paired TpmSymCaAttestation.

    + * + * @author schawki + * + */ +public class TpmAsymCaContents { + private TpmSymmetricKey symKey = null; + private byte [] tpmDigest = null; + private byte [] encrypted = null; + public TpmAsymCaContents(){} + /** + * Set the TpmSymmetricKey member data. + * + * @param newKey + */ + public void setSymmetricKey(TpmSymmetricKey newKey) { + symKey = newKey; + } + /** + * Set the TPM digest. This is required before the TpmAsymCaContents structure can be encrypted. + * + * @param aik The AIK in the form of a TpmPubKeu. + * @throws NoSuchAlgorithmException Thrown if the MessageDigest class doesn't know what "SHA-1" means. + * @throws TpmUtils.TpmUnsignedConversionException Thrown if there is a problem converting the AIK to a byte array. + */ + public void setDigest(TpmPubKey aik) + throws NoSuchAlgorithmException, + TpmUtils.TpmUnsignedConversionException { + MessageDigest md; + md = MessageDigest.getInstance("SHA-1"); + md.update(aik.toByteArray()); + tpmDigest = md.digest(); + } + /** + * Encrypt the TpmAsymCaContents for return to the TPM. The symmetric key and digest must be set for this function to run without Exception. + * + * @param ekPubKey The EK public key, extracted form the EK certificate included in the identity request/proof. + * @throws NoSuchPaddingException Encryption error. + * @throws NoSuchAlgorithmException Encryption error. + * @throws InvalidKeyException Encryption error. + * @throws InvalidAlgorithmParameterException Encryption error. + * @throws IllegalBlockSizeException Encryption error. + * @throws BadPaddingException Encryption error. + * @throws TpmUtils.TpmUnsignedConversionException Error in converting structures to byte arrays (bad data, most likely). + * @throws PrivacyCaException All required prerequisites were not met. + */ + public void encrypt(RSAPublicKey ekPubKey, boolean TrousersModeBlankOeap) // use the TPM's EK + throws NoSuchPaddingException, + NoSuchAlgorithmException, + InvalidKeyException, + InvalidAlgorithmParameterException, + IllegalBlockSizeException, + BadPaddingException, + TpmUtils.TpmUnsignedConversionException, + PrivacyCaException { + OAEPParameterSpec oaepSpec; + if (!TrousersModeBlankOeap) + oaepSpec = new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified("TCPA".getBytes())); + else + oaepSpec = new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified("".getBytes())); + Cipher asymCipher = Cipher.getInstance("RSA/ECB/OAEPWithSha1AndMGF1Padding"); + asymCipher.init(Cipher.PUBLIC_KEY, ekPubKey, oaepSpec); + byte[] newbytes = this.toPlaintextByteArray(); + asymCipher.update(newbytes); + encrypted = asymCipher.doFinal(); + } + /** + * Get the encrypted TpmAsymCaContents as a byte array suitable for delivery to the TPM with TPM_ActivateIdentity. + * + * @return A byte array form of the TpmAsymCaContents. + * @throws PrivacyCaException Throws if the structure is not ready to be sent back to the TPM. + */ + public byte [] toByteArray() + throws PrivacyCaException { + if (encrypted == null) { + throw new PrivacyCaException("Cannot access encrypted TpmAsymCaContents until encryption process has been run."); + } + return encrypted; + } + /** + * Return a byte array of the plaintext structure suitable for encryption. All prerequisites must be met, + * which are just populating all of the private member variables. + * + * @return the plaintext byte array. + * @throws TpmUtils.TpmUnsignedConversionException Thrown if there is a problem in assembling the array. + * @throws PrivacyCaException If the prereqs are not met. + */ + private byte [] toPlaintextByteArray() + throws TpmUtils.TpmUnsignedConversionException, + PrivacyCaException { + if (symKey == null) { + throw new PrivacyCaException("Cannot convert TpmAsymCaContents to byte array until TpmSymmetricKey is set."); + } + if (tpmDigest == null) { + throw new PrivacyCaException("Cannot convert TpmAsymCaContents to byte array until TPM digest has been created."); + } + byte [] symKeyBytes = symKey.toByteArray(); + byte [] returnArray = new byte[symKeyBytes.length + tpmDigest.length]; + System.arraycopy(symKeyBytes, 0, returnArray, 0, symKeyBytes.length); + System.arraycopy(tpmDigest, 0, returnArray, symKeyBytes.length, tpmDigest.length); + return returnArray; + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmClient.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmClient.java new file mode 100644 index 0000000..ddfa971 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmClient.java @@ -0,0 +1,139 @@ +/* + * 2011, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import gov.niarl.his.privacyca.TpmModule.TpmModuleException; +import java.io.IOException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.SignatureException; +import java.security.cert.*; +import java.security.interfaces.*; +import java.security.spec.InvalidKeySpecException; + +/** + *

    This class provides macro-level client provisioning functions, such + * as taking ownership, provisioning the EC, and creating a new identity key. + * All functions are statically called.

    + * + * @author schawki + * + */ +public class TpmClient { + /** + * This function combines taking ownership and creating an endorsement key (EK) certificate (EC). This function essentially serves as the Certificate Authority for the EC. + * + * @param ownerAuth 20-byte owner auth string, needed to retrieve the EK. + * @param caPrivKey The RSA private key needed to sign the EC. + * @param caCert The CA certificate associated with the caPrivKey. + * @param ecValidDays The number of days before EC expires. This should be about the same time as the expected lifetime/use of the computer holding the TPM. + * @throws IOException Thrown for a number of reasons dealing with communication to the TPM, creation of random numbers, and file access. + * @throws TpmModuleException Thrown if there is a problem communicating to the TPM through the TPM Module. + * @throws InvalidKeyException Error when creating the EC. + * @throws CertificateEncodingException Error when creating the EC. + * @throws NoSuchAlgorithmException Error when creating the EC. + * @throws InvalidKeySpecException Error when creating the EC. + * @throws SignatureException Error when creating the EC. + * @throws NoSuchProviderException Error using the BouncyCastle provider, needed for creation of the certificate. + */ + public static void provisionTpm(byte [] ownerAuth, RSAPrivateKey caPrivKey, X509Certificate caCert, int ecValidDays) + throws IOException, + TpmModuleException, + InvalidKeyException, + CertificateEncodingException, + NoSuchAlgorithmException, + InvalidKeySpecException, + SignatureException, + NoSuchProviderException{ + /* + * The following actions must be performed during the TPM Provisioning process: + * 1. Take ownership of the TPM + * - owner auth + * 2. Create an Endorsement Certificate (EC) + * - public EK + * - owner auth (should already have from above) + * - private key and cert for CA to create new cert + * - validity period of EC cert + * 3. Store the newly created EC in the TPM's NV-RAM + */ + // Take Ownership + byte [] nonce = TpmUtils.createRandomBytes(20); + try { + TpmModule.takeOwnership(ownerAuth, nonce); + } catch (TpmModuleException e){ + //System.out.println("Error taking ownership: " + e.toString()); + } + // Create Endorsement Certificate + nonce = TpmUtils.createRandomBytes(20); + try { + byte [] pubEkMod = TpmModule.getEndorsementKeyModulus(ownerAuth, nonce); + X509Certificate ekCert = TpmUtils.makeEkCert(pubEkMod, caPrivKey, caCert, ecValidDays); + TpmModule.setCredential(ownerAuth, "EC", ekCert.getEncoded()); + } catch (TpmModuleException e){ + System.out.println("Error getting PubEK: " + e.toString()); + } + // Store the new EC in NV-RAM + } + /** + * @deprecated + * Creates a new AIK and contacts a Privacy CA for an AIC. + * + * @param ownerAuth 20-byte owner auth, needed to do CollateIdentityRequest. + * @param pcaCert X.509 certificate for the Privacy CA, used to extract the public key. + * @param aikIndex Index to store the AIK key blob. + * @param keyAuth 20-byte auth data to assign to the new AIK. + * @param idLabel String to use in request for AIC. If the Privacy CA accepts the string, it sill be used as the SubjectAlternativeName in the AIC. + * @param pcaUrl The URL for the PrivacyCA web service. This does not work for HisPrivacyCAWebServices2. + * @param shortcut Must be TRUE (due flaws in the TSS implementations). + * @return The AIK in X.509 certificate format. + * @throws IOException + * @throws TpmModuleException + * @throws TpmUnsignedConversionException + * @throws CertificateException + * @throws javax.security.cert.CertificateException + */ +// public static X509Certificate provisionIdentity(byte [] ownerAuth, X509Certificate pcaCert, int aikIndex, byte [] keyAuth, String idLabel, String pcaUrl, boolean shortcut) +// throws IOException, +// TpmModuleException, +// TpmUnsignedConversionException, +// CertificateException, +// javax.security.cert.CertificateException{ +// /* +// * The following actions must be performed during the Identity Provisioning process: +// * 1. Perform a CollateIdentity +// * 2. Contact the Privacy CA (must know if performing full procedure) +// * 3. Perform ActivateIdentity (if doing full procedure) +// */ +// // CollateIdentity +// TpmIdentity newId = TpmModule.collateIdentityRequest(ownerAuth, keyAuth, idLabel, new TpmPubKey((RSAPublicKey)pcaCert.getPublicKey(), 3, 1).toByteArray(), aikIndex, (X509Certificate)null, !shortcut); +// X509Certificate toReturn = null; +// if (shortcut){ +// //System.out.println("Shortcut"); +// HisPrivacyCAWebService hisPrivacyCAWebService = HisPrivacyCAWebServicesClientInvoker.getHisPrivacyCAWebService(pcaUrl); +// //System.out.println("\n" + TpmUtils.byteArrayToHexString(newId.getIdentityRequest()) + "\n"); +// byte [] tempBytes = hisPrivacyCAWebService.partialIdentityRequest(newId.getIdentityRequest()); +// //System.out.println("Privacy CA response: " + TpmUtils.byteArrayToHexString(tempBytes)); +// toReturn = TpmUtils.certFromBytes(tempBytes); +// } else { +// System.out.println("Identity Request: " + TpmUtils.byteArrayToHexString(newId.getIdentityRequest())); +// +// //System.out.println("NO Shortcut"); +// HisPrivacyCAWebService hisPrivacyCAWebService = HisPrivacyCAWebServicesClientInvoker.getHisPrivacyCAWebService(pcaUrl); +// EncryptedCAResponse pcaResponse = hisPrivacyCAWebService.identityRequest(newId.getIdentityRequest()); +// toReturn = TpmUtils.certFromBytes(TpmModule.activateIdentity(ownerAuth, keyAuth, pcaResponse.getEncryptedKey(), pcaResponse.getEncryptedCert(), aikIndex)); +// } +// return toReturn; +// } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmIdentity.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmIdentity.java new file mode 100644 index 0000000..202aef9 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmIdentity.java @@ -0,0 +1,93 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +/** + *

    This class was created to hole all return values for running collateIdentityRequest.

    + * + * @author schawki + * + */ +public class TpmIdentity { + private byte [] identityRequestBytes = null; + private byte [] aikModulus = null; + private byte [] aikKeyBytes = null; + /** + * Create a new TpmIdentity with no data set. + * + */ + public TpmIdentity(){ + // default constructor + } + /** + * Create a new TpmIdentity, setting the Identity Request, AIK modulus, and AIK key blob. + * + * @param idReq The Identity Request, as returned from CollateIdentityRequest, in raw byte form. + * @param aikMod The AIK modulus. + * @param aikBlob The AIK in the form of a TPM_KEY. + */ + public TpmIdentity(byte[] idReq, byte [] aikMod, byte [] aikBlob){ + identityRequestBytes = idReq; + aikModulus = aikMod; + aikKeyBytes = aikBlob; + } + /** + * Set the Identity Request. + * + * @param idReq Identity Request in raw byte form. + */ + public void setIdentityRequest(byte [] idReq){ + identityRequestBytes = idReq; + } + /** + * Set the AIK modulus. + * + * @param aikMod AIK modulus in byte form. + */ + public void setAikModulus(byte [] aikMod){ + aikModulus = aikMod; + } + /** + * Set the AIK key blob in raw byte form. + * + * @param aikBlob + */ + public void setAikBlob(byte [] aikBlob){ + aikKeyBytes = aikBlob; + } + /** + * Get the stored Identity Request. + * + * @return Stored Identity Request in raw bytes, or null + */ + public byte [] getIdentityRequest(){ + return identityRequestBytes; + } + /** + * Get the stored AIK modulus. + * + * @return Stored AIK modulus in raw byte form, or null. + */ + public byte [] getAikModulus(){ + return aikModulus; + } + /** + * Get the store AIK key blob. + * + * @return Stored AIK key blob in raw byte form, or null. + */ + public byte [] getAikBlob(){ + return aikKeyBytes; + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmIdentityProof.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmIdentityProof.java new file mode 100644 index 0000000..573a797 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmIdentityProof.java @@ -0,0 +1,415 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.security.*; +import java.security.spec.*; +import java.security.interfaces.*; +import java.io.*; +import javax.security.cert.*; + +/** + * See TPM_IDENTITY_PROOF

    + * + *

    The TpmIdentityProof is the plain-text incarnation of a TPM's request for an + * AIK credential. The data contained in the identity proof is used to verify the + * integrity of the request, and to construct an AIK credential.

    + * + * The TPM_IDENTITY_PROOF structure, as defined by the TCG, contains the following elements: + *
      + *
    • TPM_STRUCT_VER, which is a byte array always equal to 0x01010000
    • + *
    • AIK in the form of a TPM_PUBKEY (TpmPubKey class)
    • + *
    • Identity label The requested name for the identity. This will (probably) be placed in the Subject Alternative Name field in the AIC by the Privacy CA, per specification.
    • + *
    • Identity binding This is the signature, made using the private AIK, of a hash made of the TPM_IDENTITY_CONTENTS structure (see note below).
    • + *
    • Endorsement Certificate (optional) This really should be a required item, but isn't.
    • + *
    • Platform Certificate (optional)
    • + *
    • Conformance Certificate (optional)
    • + *
    + * + * This class adds additional flags to clarify discrepancies that have been observed among TSS implementations. These flags include: + *
      + *
    • TrousersModeIV (boolean) Though both NTRU and TrouSerS place the initialization vector for symmetrically encrypted data within, but at the beginning of, the encrypted data blob, the specification states that the IV should be recorded within the TPM_KEY_PARMS structure for the symmetric key. Setting this boolean to TRUE indicates the use of "TrouSerS-style placement.
    • + *
    • TrousersModeSymkeyEncscheme (boolean) TrouSerS (but not NTRU) incorrectly sets the symmetric encryption scheme to TPM_ES_NONE. The correct scheme to use is TPM_ES_SYM_CBC_PKCS5PAD. Both NTRU and TrouSerS use this scheme for encryption, but TrouSerS records it as otherwise.
    • + *
    • TrousersModeBlankOeap (boolean) TrouSerS incorrectly encrypts the asymmetric blob, as it uses a blank OEAP password. The password should be "TCPA".
    • + *
    + * + *

    Developer note: Methods in this class are responsible for working with all aspects of the + * TPM_IDENTITY_CONTENTS structure. A future version of the TPM support code may include + * a TpmIdentityContents class, which would greatly simplify the code in this class.

    + * + *

    This class can be used by a Privacy CA for parsing an incoming request, but + * it can also be used by a client for constructing a new request.

    + * + * @author schawki + * @see TpmIdentityRequest + */ +public class TpmIdentityProof { + private byte [] structVer; + private TpmPubKey Aik; + private byte [] idLabelBytes; + private byte [] idBindingBytes; + private byte [] ekCredBytes; + private byte [] platformCredBytes; + private byte [] conformCredBytes; + private boolean TrousersModeIV = false; + private boolean TrousersModeSymkeyEncscheme = false; + private boolean TrousersModeBlankOeap = false; + /** + * Get the TrousersModeIV status. A value of TRUE indicates that the IV placement is inside, and at the beginning of, the symmetrically encrypted blob and not in the symmetric key parameters. This will almost always be set at TRUE. + * + * @return The status of the flag. + */ + public boolean getIVmode(){ + return TrousersModeIV; + } + /** + * Set the TrousersModeIV status. A value of TRUE indicates that the IV placement is inside, and at the beginning of, the symmetrically encrypted blob and not in the symmetric key parameters. This will almost always be set at TRUE. + * + * @param newMode Set to TRUE for greatest compatibility; set to FALSE for compliance to specification. + */ + public void setIVmode(boolean newMode) { + TrousersModeIV = newMode; + } + /** + * Get the TrousersModeSymkeyEncscheme status. A value of TRUE indicates that the identity proof was constructed by TrouSerS, and is not compliant with the specification. + * + * @return The status of the flag. + */ + public boolean getSymkeyEncscheme() { + return TrousersModeSymkeyEncscheme; + } + /** + * Set the TrousersModeSymkeyEncscheme flag. This should always be set to FALSE. + * + * @param newScheme Set to TRUE to emulate an identity proof created by TrouSerS; set to FALSE to comply with the specification. + */ + public void setSymkeyEncscheme(boolean newScheme) { + TrousersModeSymkeyEncscheme = newScheme; + } + /** + * Get the TrousersModeBlankOeap flag. A value of TRUE indicates that the identity proof was constructed by TrouSerS, and is not compliant with the specification. + * + * @return The status of the flag. + */ + public boolean getOeapMode () { + return TrousersModeBlankOeap; + } + /** + * Set the TrousersModeBlankOeap flag. A value of TRUE indicates that the identity proof was constructed by TrouSerS, and is not compliant with the specification. + * + * @param newMode Set to TRUE to emulate an identity proof constructed by TrouSerS; set to FALSE to comply with the specification. + */ + public void getOeapMode(boolean newMode) { + TrousersModeBlankOeap = newMode; + } + /** + * Create new TpmIdentityProof object by parsing the decrypted data from a + * TPM_IDENTITY_REQ. Information gathered while parsing and decrypting the + * Identity Request is needed to properly parse the Ideneity Proof. Also, + * that information may be useful when crafting the response to the client. + * + * @param blob The decrypted form of the sym blob from the Identity Request. + * @param IV Set to TRUE if the IV was placed at the beginning of the symblob of the Identity Request instead of in the key parameters. + * @param symKey Set to TRUE if the symmetric encryption scheme was set to TPM_ES_NONE in the Identity Request. + * @param oaep Set to TRUE if the OAEP password was blank. + * @throws PrivacyCaException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public TpmIdentityProof(byte[] blob, boolean IV, boolean symKey, boolean oaep) + throws PrivacyCaException, + TpmUtils.TpmUnsignedConversionException, + TpmUtils.TpmBytestreamResouceException { + TrousersModeIV = IV; + TrousersModeSymkeyEncscheme = symKey; + TrousersModeBlankOeap = oaep; + ByteArrayInputStream bs = new ByteArrayInputStream(blob); + structVer = new byte[4]; + structVer = TpmUtils.getBytes(bs, 4); + int labelSize = TpmUtils.getUINT32(bs); + int identBindingSize = TpmUtils.getUINT32(bs); + int ekCredSize = TpmUtils.getUINT32(bs); + //This is where things go wrong with no EK certificate!! + //if (ekCredSize == 0) throw new PrivacyCaException("PrivacyCaException: Error parsing TPM_IDENTITY_PROOF: there is no endorsement credential."); + int platformCredSize = TpmUtils.getUINT32(bs); + int conformCredSize = TpmUtils.getUINT32(bs); + Aik = new TpmPubKey(bs); + idLabelBytes = TpmUtils.getBytes(bs, labelSize); + idBindingBytes = TpmUtils.getBytes(bs, identBindingSize); + ekCredBytes = TpmUtils.getBytes(bs, ekCredSize); + platformCredBytes = TpmUtils.getBytes(bs, platformCredSize); + conformCredBytes = TpmUtils.getBytes(bs, conformCredSize); + } + /** + * Create a new TpmIdentityProof by supplying all of the necessary elements to construct one from scratch. + * + * @param idLabel The requested Identity Label. This is usually assigned as the Subject Alternative Name in the AIC. Supply as ASCII string in byte array. + * @param idBinding The identity binding is supplied from the TPM by running TPM_MakeIdentity (available via TCS, not TSP). Should be 256 byte (signature made using 2048 bit AIK). + * @param AIK The AIK in TpmPubKey form. This should also be supplied from the TPM using TPM_MakeIdentity. + * @param ekCertBytes (Optional) Endorsement Certificate (EC), usually as an X.509 certificate, as a byte array. Null is acceptable. + * @param platformCertBytes (Optional) Platform Certificate, usually as an X.509 certificate, as a byte array. Null is acceptable. + * @param conformanceCertBytes (Optional) Conformance Certificate, usually as an X.509 certificate, as a byte array. Null is acceptable. + * @param IV TrouSerS IV placement mode flag. Recommended setting is TRUE. + * @param symKey TrouSerS symmetric encryption scheme flag. Recommended setting is FALSE. + * @param oaep TrouSerS use of blank OAEP password flag. Recommended setting is FALSE. + */ + public TpmIdentityProof(byte [] idLabel, byte [] idBinding, TpmPubKey AIK, byte [] ekCertBytes, byte [] platformCertBytes, byte [] conformanceCertBytes, boolean IV, boolean symKey, boolean oaep) { + TrousersModeIV = IV; + TrousersModeSymkeyEncscheme = symKey; + TrousersModeBlankOeap = oaep; + byte [] temp = {(byte)0x01, (byte)0x01, (byte)0x00, (byte)0x00}; + structVer = temp; + Aik = AIK; + idLabelBytes = idLabel; + idBindingBytes = idBinding; + ekCredBytes = ekCertBytes; + platformCredBytes = platformCertBytes; + conformCredBytes = conformanceCertBytes; + } + /** + * Get the Identity Proof in the form of a byte array. + * + * @return Entire Identity Proof in the form of a byte array. + * @throws TpmUtils.TpmUnsignedConversionException Thrown if there are any out-of-bounds problems converting from (signed) Java long to UINT32. + */ + public byte [] toByteArray() + throws TpmUtils.TpmUnsignedConversionException { + // Get byte elements of the proof + //byte [] structVer - already exists in final form + byte [] labelSize = TpmUtils.intToByteArray(idLabelBytes.length); + byte [] idBindingSize = TpmUtils.intToByteArray(idBindingBytes.length); + byte [] endorsementSize = TpmUtils.intToByteArray(ekCredBytes.length); + byte [] platformSize = TpmUtils.intToByteArray(ekCredBytes.length); + byte [] conformanceSize = TpmUtils.intToByteArray(ekCredBytes.length); + byte [] identityKey = Aik.toByteArray(); + //byte [] idLabelBytes - already exists in final form + //byte [] idBindingBytes - already exists in final form + //byte [] ekCredBytes - already exists in final form + //byte [] platformCredBytes - already exists in final form + //byte [] conformCredBytes - already exists in final form + // Assemble the return array + byte [] toReturn = new byte[structVer.length + labelSize.length + idBindingSize.length + endorsementSize.length + platformSize.length + conformanceSize.length + + identityKey.length + idLabelBytes.length + idBindingBytes.length + ekCredBytes.length + platformCredBytes.length + conformCredBytes.length]; + int copyOffset = 0; + System.arraycopy(structVer, 0, toReturn, copyOffset, structVer.length); + copyOffset += structVer.length; + System.arraycopy(labelSize, 0, toReturn, copyOffset, labelSize.length); + copyOffset += labelSize.length; + System.arraycopy(idBindingSize, 0, toReturn, copyOffset, idBindingSize.length); + copyOffset += idBindingSize.length; + System.arraycopy(endorsementSize, 0, toReturn, copyOffset, endorsementSize.length); + copyOffset += endorsementSize.length; + System.arraycopy(platformSize, 0, toReturn, copyOffset, platformSize.length); + copyOffset += platformSize.length; + System.arraycopy(conformanceSize, 0, toReturn, copyOffset, conformanceSize.length); + copyOffset += conformanceSize.length; + System.arraycopy(identityKey, 0, toReturn, copyOffset, identityKey.length); + copyOffset += identityKey.length; + System.arraycopy(idLabelBytes, 0, toReturn, copyOffset, idLabelBytes.length); + copyOffset += idLabelBytes.length; + System.arraycopy(idBindingBytes, 0, toReturn, copyOffset, idBindingBytes.length); + copyOffset += idBindingBytes.length; + System.arraycopy(ekCredBytes, 0, toReturn, copyOffset, ekCredBytes.length); + copyOffset += ekCredBytes.length; + System.arraycopy(platformCredBytes, 0, toReturn, copyOffset, platformCredBytes.length); + copyOffset += platformCredBytes.length; + System.arraycopy(conformCredBytes, 0, toReturn, copyOffset, conformCredBytes.length); + return toReturn; + } + /** + * Display the parsed contents of the request in a form suitable for display on console or in log file. This is intended to be used when troubleshooting. + * + * @return Multi-line human readable breakdown of identity proof contents + */ + public String toString() { + String returnVal = ""; + returnVal += "TpmIdentityProof:\n"; + returnVal += " StructVer: " + TpmUtils.byteArrayToString(structVer, 16) + "\n"; + returnVal += " Aik:\n" + Aik.toString() + "\n"; + String junk = new String(idLabelBytes); + returnVal += " idLabel:\n" + junk + "\n"; + returnVal += " idBinding:\n" + TpmUtils.byteArrayToString(idBindingBytes, 16) + "\n"; + returnVal += " ekCred:\n" + TpmUtils.byteArrayToString(ekCredBytes, 16) + "\n"; + returnVal += " platformCred:\n" + TpmUtils.byteArrayToString(platformCredBytes, 16) + "\n"; + returnVal += " conformCred:\n" + TpmUtils.byteArrayToString(conformCredBytes, 16) + "\n"; + return returnVal; + } + /** + * Use the identity binding (the signature value of the TPM_IDENTITY_CONTENTS structure) to determine the validity of the request.

    + * The TPM_IDENTITY_CONTENTS structure contains the public AIK and a hash of the idLabel and the Privacy CA's public key.

    + * + * @param caPubKey The Privacy CA's public key. + * @return True if the identity binding checks out, false if it does not. + * @throws NoSuchAlgorithmException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws InvalidKeyException + * @throws InvalidKeySpecException + * @throws SignatureException + */ + public boolean checkValidity(RSAPublicKey caPubKey) + throws NoSuchAlgorithmException, + TpmUtils.TpmUnsignedConversionException, + InvalidKeyException, + InvalidKeySpecException, + SignatureException { + TpmPubKey pca = new TpmPubKey(caPubKey, 3, 1); + MessageDigest md = MessageDigest.getInstance("SHA1"); + byte [] pcaBytes = pca.toByteArray(); + byte [] chosenId = new byte[idLabelBytes.length + pcaBytes.length]; + System.arraycopy(idLabelBytes, 0, chosenId, 0, idLabelBytes.length); + System.arraycopy(pcaBytes, 0, chosenId, idLabelBytes.length, pcaBytes.length); + md.update(chosenId); + byte [] chosenIdHash = md.digest(); + byte [] tpmMakeIdOrd = TpmUtils.intToByteArray(0x79); + byte [] aikPubKey = Aik.toByteArray(); + //Structver in new (NTru) requests is appearing as 01 02 04 1E. Strange. (9/8/2009). + //To compensate, using a shim copy of structver populated with the correct values. + // + //In this case, the problem is that the structver included as cleartext in the identity proof is + //placed by the TSS, but the identity binding is created by the TPM independently. If one value of + //structver is used during the creation of the identity binding signature but a different structver + //is used when performing verification, the result will always be a failure to verify. + byte [] thisStructVer = structVer; + byte [] traditionalStructVer = {(byte)0x01, (byte)0x01, (byte)0x00, (byte)0x00}; + thisStructVer = traditionalStructVer; + byte [] identityContents = new byte[thisStructVer.length + tpmMakeIdOrd.length + chosenIdHash.length + aikPubKey.length]; + System.arraycopy(thisStructVer, 0, identityContents, 0, thisStructVer.length); + System.arraycopy(tpmMakeIdOrd, 0, identityContents, thisStructVer.length, tpmMakeIdOrd.length); + System.arraycopy(chosenIdHash, 0, identityContents, thisStructVer.length + tpmMakeIdOrd.length, chosenIdHash.length); + System.arraycopy(aikPubKey, 0, identityContents, thisStructVer.length + tpmMakeIdOrd.length + chosenIdHash.length, aikPubKey.length); + Signature sig = Signature.getInstance("SHA1withRSA"); + sig.initVerify(Aik.getKey()); + sig.update(identityContents); + boolean bindingCheck = sig.verify(idBindingBytes); + //if (bindingCheck) System.out.println("bindingCheck is TRUE"); else System.out.println("bindingCheck is FALSE"); + return bindingCheck; + } + /** + * Get the AIK stored in the request. + * + * @return The AIK as a TpmPubKey. + */ + public TpmPubKey getAik() { + return Aik; + } + /** + * Get the TPM_STRUCT_VER. Should always be 0x01010000. + * + * @return The four-byte TpmStructVer. + */ + public byte [] getVer() { + return structVer; + } + /** + * Get the Identity Label string (in ASCII byte array) as stored in the Identity Proof. + * + * @return The identity label as a byte string (ASCII). + */ + public byte [] getIdLableBytes() { + return idLabelBytes; + } + /** + * Return the Identity Binding. It should be the signature of the Identity Contents made using the AIK. Should always be 256 bytes. + * + * @return The identity binding, as extracted directly from the identity proof. + */ + public byte [] getIdBindingBytes() { + return idBindingBytes; + } + /** + * EC stored in the Identity Proof, if present, in the form of raw bytes. + * + * @return The X509 Endorsement Key Certificate as a byte array. This must be present to complete the Privacy CA process. + */ + public byte [] getEkCredBytes() { + return ekCredBytes; + } + /** + * EC stored in the Identity Proof, if present, in the form of an X509Certificate object. + * + * @return The EK certificate as a java X509Certificate. + * @throws CertificateException + */ + public X509Certificate getEkCred() + throws CertificateException { + return X509Certificate.getInstance(ekCredBytes); + } + /** + * PC stored in the Identity Proof, if present, in the form of raw bytes. + * + * @return The Platform Certificate as a byte array. May be null. + */ + public byte [] getPlatformCredBytes() { + return platformCredBytes; + } + /** + * PC stored in the Identity Proof, if present, in the form of an X509Certificate object. + * + * @return The Platform Certificate as a Java X509Certificate. If not present, will throw exception. + * @throws CertificateException + * @throws java.security.cert.CertificateException + * @throws java.security.cert.CertificateEncodingException + */ + public X509Certificate getPlatformCred() + throws CertificateException, + java.security.cert.CertificateException, + java.security.cert.CertificateEncodingException { + return getCertFromBytes(platformCredBytes); + } + /** + * CC stored in the Identity Proof, if present, in the form of raw bytes. + * + * @return The Conformance Credential as a byte array. May be null. + */ + public byte [] getConformCredBytes() { + return conformCredBytes; + } + /** + * CC stored in the Identity Proof, if present, in the form of an X509Certificate object. + * + * @return The Conformance Credential as a Java X509Certificate. If not present, will throw exception. + * @throws CertificateException + * @throws java.security.cert.CertificateException + * @throws java.security.cert.CertificateEncodingException + */ + public X509Certificate getConformCred() + throws CertificateException, + java.security.cert.CertificateException, + java.security.cert.CertificateEncodingException { + return getCertFromBytes(conformCredBytes); + } + /** + * Convert from a byte array to a Java X509 Certificate. By default, all of the Privacy CA functions use + * javax.security.cert.X509Certificate. The conversion process requires the creation of a + * java.security.cert.X509Certificate. Although these two are identitical in structure, their member + * functions are different, and are seen by Java as different. This function performs the conversion process + * between the two. + * + * @param certBytes The byte array to convert. + * @return A javax.security.cert.X509Certificate. + * @throws CertificateException + * @throws java.security.cert.CertificateException + * @throws java.security.cert.CertificateEncodingException + */ + private X509Certificate getCertFromBytes(byte [] certBytes) + throws CertificateException, + java.security.cert.CertificateException, + java.security.cert.CertificateEncodingException { + ByteArrayInputStream bs = new ByteArrayInputStream(certBytes); + java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509"); + java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate)cf.generateCertificate(bs); + X509Certificate xcert = javax.security.cert.X509Certificate.getInstance(cert.getEncoded()); + return xcert; + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmIdentityRequest.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmIdentityRequest.java new file mode 100644 index 0000000..74d3183 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmIdentityRequest.java @@ -0,0 +1,656 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import javax.crypto.Cipher; +import java.security.interfaces.*; +import java.security.spec.*; +import java.security.*; +import javax.crypto.*; +import javax.crypto.spec.*; + +import java.io.*; + +/** + *

    The TpmIdentityRequest class is based on the TPM_IDENTITY_REQUEST structure and includes + * associated methods. An identity request is generally created by running the TSS function + * Tspi_TPM_CollateIdentityRequest. The request contains two parts: a symmetrically + * encrypted identity proof (TPM_IDENTITY_PROOF); and an asymmetrically encrypted portion + * containing the key used to encrypt the symmetric portion. This class contains + * functionality to decode and decrypt the identity request and return an identity proof. + * There is also functionality to create a new request, given an identity proof and the key + * needed to encrypt it.

    + *

    Different implementations of the TSS create slightly different formats of identity requests. + * The two version of TSS researched in the development of this class were NTru's CTSS v1.2.1.29 + * and IBM's TrouSerS v

    + * + * @author schawki + * + */ +public class TpmIdentityRequest { + private byte[] asymBlob; + private byte[] symBlob; + private TpmKeyParams asymAlgorithm; + private TpmKeyParams symAlgorithm; + private boolean TrousersModeIV = false; + private boolean TrousersModeSymkeyEncscheme = false; + private boolean TrousersModeBlankOeap = false; + + public byte[] getAsymBlob(){ + return asymBlob; + } + public byte[] getSymBlob(){ + return symBlob; + } + + /** + * Get a copy of the flag used to indicate the placement of the initialization vector used for this request. + * + * @return True indicates that the placement is the first part of the symmetrically encrypted blob; false indicates that the placement is within the TPM_SYMMETRIC_KEY_PARMS portion of the TPM_KEY_PARMS structure used to describe the symmetric key usage. + */ + public boolean getIVmode(){ + return TrousersModeIV; + } + /** + * Set the flag used to dictate the placement of the initialization vector for this request. + * + * @param newMode True indicates that the placement be the first part of the symmetrically encrypted blob; false indicates that the placement be within the TPM_SYMMETRIC_KEY_PARMS portion of the TPM_KEY_PARMS structure used to describe the symmetric key usage. + */ + public void setIVmode(boolean newMode) { + TrousersModeIV = newMode; + } + /** + * Get a status of the flag that indicates the usage of the encryption mode used for symmetric encryption. Based on observation, all TSS implementations use + * + * @return TRUE if TrouSerS use of TPM_ES_NONE is used; FALSE if consistent with the specification. + */ + public boolean getSymkeyEncscheme() { + return TrousersModeSymkeyEncscheme; + } + /** + * Set the status of the TrouSerS encryption scheme flag. + * + * @param newScheme Set to TRUE to emulate TrouSerS' use of TPM_ES_NONE; set to FALSE to comply with the specification. + */ + public void setSymkeyEncscheme(boolean newScheme) { + TrousersModeSymkeyEncscheme = newScheme; + } + /** + * Get the status of the TrouSerS OEAP flag. TrouSerS (at least in the version available through Yum) uses a blank OEAP password when performing asymmetric encryption. The password should be "TCPA". + * + * @return TRUE if TrouSerS use of a blank OEAP password is in use; FALSE if the correct password is used. + */ + public boolean getOeapMode () { + return TrousersModeBlankOeap; + } + /** + * Set the status of the TrouSerS OEAP flag. + * + * @param newMode Set to TRUE to emulate TrouSerS use of a blank OEAP password; set to FALSE to comply with the specification. + */ + public void getOeapMode(boolean newMode) { + TrousersModeBlankOeap = newMode; + } + + /** + * Create a new TpmIdentityRequest object by initializing with a byte blob from the output of + * Tspi_TPM_CollateIdentityRequest. + * + * @param blob The byte blob form of the identity request. + * @throws TpmUtils.TpmUnsignedConversionException + * @throws TpmUtils.TpmBytestreamResouceException + * @throws PrivacyCaException + */ + public TpmIdentityRequest(byte[] blob) + throws TpmUtils.TpmUnsignedConversionException, + TpmUtils.TpmBytestreamResouceException, + PrivacyCaException { + ByteArrayInputStream bs = new ByteArrayInputStream(blob); + int asymSize = TpmUtils.getUINT32(bs); + int symSize = TpmUtils.getUINT32(bs); + asymAlgorithm = new TpmKeyParams(bs); + symAlgorithm = new TpmKeyParams(bs); + TrousersModeIV = symAlgorithm.getTrouSerSmode(); + asymBlob = TpmUtils.getBytes(bs, asymSize); + symBlob = TpmUtils.getBytes(bs, symSize); + findIv(); + } + /** + * Create a new TpmIdentityRequest by supplying a TpmIdentityProof and the Privacy CA's public key. A symmetric key and IV will be randomly created. + * + * @param newIdProof A TpmIdentityProof object + * @param caKey The Privacy CA's private key + * @throws IOException + * @throws IllegalBlockSizeException + * @throws BadPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws TpmUtils.TpmUnsignedConversionException + */ + public TpmIdentityRequest(TpmIdentityProof newIdProof, RSAPublicKey caKey) + throws IOException, + IllegalBlockSizeException, + BadPaddingException, + InvalidKeyException, + InvalidAlgorithmParameterException, + NoSuchAlgorithmException, + NoSuchPaddingException, + TpmUtils.TpmUnsignedConversionException { + this(newIdProof, caKey, TpmUtils.createRandomBytes(16), TpmUtils.createRandomBytes(16)); + } + /** + * Create a new TpmIdentityRequest by supplying a TpmIdentityProof, the Privacy CA's public key, a symmetric key, and an IV. + * + * @param newIdProof A TpmIdentityProof object + * @param caKey The Privacy CA's private key + * @param key Symmetric key to use for encrypting the request (will itself be encrypted using the Privacy CA public key) + * @param iv Initialization Vector to be used for symmetric encryption + * @throws IllegalBlockSizeException + * @throws BadPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws TpmUtils.TpmUnsignedConversionException + */ + public TpmIdentityRequest(TpmIdentityProof newIdProof, RSAPublicKey caKey, byte [] key, byte [] iv) + throws IllegalBlockSizeException, + BadPaddingException, + InvalidKeyException, + InvalidAlgorithmParameterException, + NoSuchAlgorithmException, + NoSuchPaddingException, + TpmUtils.TpmUnsignedConversionException { + this(newIdProof, caKey, createDefaultAsymAlgorithm(), createDefaultSymAlgorithm(iv), key); + } + /** + * Create a new TpmIdentityRequest by supplying a TpmIdentityProof, the Privacy CA's public key, a symmetric key, and an IV. + * + * @param newIdProof A TpmIdentityProof object + * @param caKey The Privacy CA's private key + * @param newAsymAlgorithm Asymmetric encryption information in the form of a TpmKeyParams object + * @param newSymAlgorithm Symmetric encryption information in the form of a TpmKeyParams object + * @throws IOException + * @throws IllegalBlockSizeException + * @throws BadPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws TpmUtils.TpmUnsignedConversionException + */ + public TpmIdentityRequest(TpmIdentityProof newIdProof, RSAPublicKey caKey, TpmKeyParams newAsymAlgorithm, TpmKeyParams newSymAlgorithm) + throws IOException, + IllegalBlockSizeException, + BadPaddingException, + InvalidKeyException, + InvalidAlgorithmParameterException, + NoSuchAlgorithmException, + NoSuchPaddingException, + TpmUtils.TpmUnsignedConversionException { + this(newIdProof, caKey, newAsymAlgorithm, newSymAlgorithm, TpmUtils.createRandomBytes(16)); + } + public TpmIdentityRequest(TpmIdentityProof newIdProof, RSAPublicKey caKey, TpmKeyParams newAsymAlgorithm, TpmKeyParams newSymAlgorithm, byte [] key) + throws IllegalBlockSizeException, + BadPaddingException, + InvalidKeyException, + InvalidAlgorithmParameterException, + NoSuchAlgorithmException, + NoSuchPaddingException, + TpmUtils.TpmUnsignedConversionException { + TrousersModeIV = newIdProof.getIVmode(); + asymAlgorithm = newAsymAlgorithm; + symAlgorithm = newSymAlgorithm; + symAlgorithm.setTrouSerSmode(TrousersModeIV); + TrousersModeSymkeyEncscheme = newIdProof.getSymkeyEncscheme(); + TrousersModeBlankOeap = newIdProof.getOeapMode(); + encryptAsym(encryptSym(newIdProof.toByteArray(), key, symAlgorithm.getSubParams().getByteData()), caKey); + if (TrousersModeIV) { + //symAlgorithm.setSubParams(null); //taken care of by TpmKeyParams + byte [] newSymblob = new byte[symAlgorithm.getSubParams().getByteData().length + symBlob.length]; + System.arraycopy(symAlgorithm.getSubParams().getByteData(), 0, newSymblob, 0, symAlgorithm.getSubParams().getByteData().length); + System.arraycopy(symBlob, 0, newSymblob, symAlgorithm.getSubParams().getByteData().length, symBlob.length); + symBlob = newSymblob; + } + } + /** + * Create a new Identity Request using an arbitrary byte blob as an Identity Proof and random AES 256 key and IV. This function is intended to be used to wrap data in the form of an Identity Request that may not be an Identity Proof. An example of this may be an Endorsement Credential. + * + * @param newIdProof Arbitrary byte blob to take the position of an Identity Proof. + * @param caKey Privacy CA's public key + * @param TrouSerS true if request should be structured like one TrouSerS would create, false if request should be structured like one NTRU would create. + * @throws IllegalBlockSizeException + * @throws BadPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws IOException + */ + public TpmIdentityRequest(byte[] newIdProof, RSAPublicKey caKey, boolean TrouSerS) + throws IllegalBlockSizeException, + BadPaddingException, + InvalidKeyException, + InvalidAlgorithmParameterException, + NoSuchAlgorithmException, + NoSuchPaddingException, + TpmUtils.TpmUnsignedConversionException, IOException { + TrousersModeIV = true; + asymAlgorithm = createDefaultAsymAlgorithm(); + symAlgorithm = createDefaultSymAlgorithm(TpmUtils.createRandomBytes(16)); + symAlgorithm.setTrouSerSmode(TrousersModeIV); + if(TrouSerS){ + TrousersModeSymkeyEncscheme = true; + TrousersModeBlankOeap = true; + }else{ + TrousersModeSymkeyEncscheme = false; + TrousersModeBlankOeap = false; + } + encryptAsym(encryptSym(newIdProof, TpmUtils.createRandomBytes(16), symAlgorithm.getSubParams().getByteData()), caKey); + if (TrousersModeIV) { + byte [] newSymblob = new byte[symAlgorithm.getSubParams().getByteData().length + symBlob.length]; + System.arraycopy(symAlgorithm.getSubParams().getByteData(), 0, newSymblob, 0, symAlgorithm.getSubParams().getByteData().length); + System.arraycopy(symBlob, 0, newSymblob, symAlgorithm.getSubParams().getByteData().length, symBlob.length); + symBlob = newSymblob; + } + } + /** + * Create a default TpmKeyParams for the asym portion of the request. + * + * @return + */ + private static TpmKeyParams createDefaultAsymAlgorithm() { + TpmKeyParams toReturn = new TpmKeyParams(); + toReturn.setAlgorithmId(TpmKeyParams.TPM_ALG_RSA);//1 + toReturn.setEncScheme((short)TpmKeyParams.TPM_ES_RSAESOAEP_SHA1_MGF1);//3 + toReturn.setSigScheme((short)TpmKeyParams.TPM_SS_NONE);//1 + TpmRsaKeyParams newRsaKeyParams = new TpmRsaKeyParams(); + newRsaKeyParams.setKeyLength(2048); + newRsaKeyParams.setValueData(2); + newRsaKeyParams.setByteData(null); + toReturn.setSubParams(newRsaKeyParams); + return toReturn; + } + /** + * Create a default TpmKeyParams for the sym portion of the request. This will include the IV, as per the specification, but this IV will most likely be moved to a TrouSerS-like location when the request is encrypted. + * + * @param iv 128-bit (16 byte) initialization vector + * @return + */ + private static TpmKeyParams createDefaultSymAlgorithm(byte [] iv) { + TpmKeyParams toReturn = new TpmKeyParams(); + toReturn.setAlgorithmId(TpmKeyParams.TPM_ALG_AES);//6 + toReturn.setEncScheme((short)TpmKeyParams.TPM_ES_SYM_CBC_PKCS5PAD);//255=FF + toReturn.setSigScheme((short)TpmKeyParams.TPM_SS_NONE);//1 + TpmSymmetricKeyParams newSymmetricKeyParams = new TpmSymmetricKeyParams(); + newSymmetricKeyParams.setKeyLength(128); + newSymmetricKeyParams.setValueData(128); + newSymmetricKeyParams.setByteData(iv); + toReturn.setSubParams(newSymmetricKeyParams); + return toReturn; + } + /** + * Encrypt the TpmIdentityProof using a specified key and IV; return the TpmSymmetricKey object. The encrypted portion will be stored in this object's symblob variable. + * + * @param proof This is the TpmIdentityProof as a byte array (or anything else to encrypt as if it is an identity proof -- useful for sending encrypted data to a Privacy CA outside of the specification). + * @param key 128-bit (16 byte) AES key + * @param iv 128-bit (16 byte) initialization vector + * @return TpmSymmetricKey containing the used key + * @throws NoSuchPaddingException + * @throws NoSuchAlgorithmException + * @throws InvalidAlgorithmParameterException + * @throws InvalidKeyException + * @throws BadPaddingException + * @throws IllegalBlockSizeException + */ + private TpmSymmetricKey encryptSym(byte [] proof, byte [] key, byte [] iv) + throws NoSuchPaddingException, + NoSuchAlgorithmException, + InvalidAlgorithmParameterException, + InvalidKeyException, + BadPaddingException, + IllegalBlockSizeException{ + //encrypt + Cipher symCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + IvParameterSpec ivSpec = new IvParameterSpec(iv); + SecretKeySpec symKey = new SecretKeySpec(key, "AES"); + symCipher.init(Cipher.ENCRYPT_MODE, symKey, ivSpec); + symBlob = symCipher.doFinal(proof); + //set the TpmSymmetricKey for return + TpmSymmetricKey encryptKey = new TpmSymmetricKey(); + encryptKey.setAlgorithmId(TpmKeyParams.TPM_ALG_AES); + encryptKey.setEncScheme(TpmKeyParams.TPM_ES_SYM_CBC_PKCS5PAD); + encryptKey.setSecretKey(symKey); + if (TrousersModeSymkeyEncscheme) { + encryptKey.setEncScheme(TpmKeyParams.TPM_ES_NONE); + } + return encryptKey; + } + /** + * Encrypt a TpmSymmetricKey, as returned from the private encryptSym() function, and store in the asymblob variable for this object. + * + * @param symKey The TpmSymmetricKey as returned from encryptSym() + * @param caKey The Privacy CA's public key + * @throws NoSuchPaddingException + * @throws NoSuchAlgorithmException + * @throws InvalidAlgorithmParameterException + * @throws InvalidKeyException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws BadPaddingException + * @throws IllegalBlockSizeException + */ + private void encryptAsym(TpmSymmetricKey symKey, RSAPublicKey caKey) + throws NoSuchPaddingException, + NoSuchAlgorithmException, + InvalidAlgorithmParameterException, + InvalidKeyException, + TpmUtils.TpmUnsignedConversionException, + BadPaddingException, + IllegalBlockSizeException { + OAEPParameterSpec oaepSpec; + if (TrousersModeBlankOeap) + oaepSpec = new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified("".getBytes())); + else + oaepSpec = new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified("TCPA".getBytes())); + Cipher asymCipher = Cipher.getInstance("RSA/ECB/OAEPWithSha1AndMGF1Padding"); + asymCipher.init(Cipher.PUBLIC_KEY, caKey, oaepSpec); + asymCipher.update(symKey.toByteArray()); + asymBlob = asymCipher.doFinal(); + } + /** + * Dump the Identity Request as a byte array in the form that it can be sent to a Privacy CA (or as it came from the client, assembled by a TSS) + * + * @return Byte array containing the Identity Request + * @throws TpmUtils.TpmUnsignedConversionException + */ + public byte [] toByteArray() + throws TpmUtils.TpmUnsignedConversionException { + byte [] asymSize = TpmUtils.intToByteArray(asymBlob.length); + byte [] symSize = TpmUtils.intToByteArray(symBlob.length); + byte [] asymAlgorithmBytes = asymAlgorithm.toByteArray(); + byte [] symAlgorithmBytes = symAlgorithm.toByteArray(); + byte [] toReturn = new byte[asymSize.length + symSize.length + asymAlgorithmBytes.length + symAlgorithmBytes.length + asymBlob.length + symBlob.length]; + System.arraycopy(asymSize, 0, toReturn, 0, asymSize.length); + System.arraycopy(symSize, 0, toReturn, asymSize.length, symSize.length); + System.arraycopy(asymAlgorithmBytes, 0, toReturn, asymSize.length + symSize.length, asymAlgorithmBytes.length); + System.arraycopy(symAlgorithmBytes, 0, toReturn, asymSize.length + symSize.length + asymAlgorithmBytes.length, symAlgorithmBytes.length); + System.arraycopy(asymBlob, 0, toReturn, asymSize.length + symSize.length + asymAlgorithmBytes.length + symAlgorithmBytes.length, asymBlob.length); + System.arraycopy(symBlob, 0, toReturn, asymSize.length + symSize.length + asymAlgorithmBytes.length + symAlgorithmBytes.length + asymBlob.length, symBlob.length); + return toReturn; + } + /** + * + * @return The asym key_parms. + */ + public TpmKeyParams getAsymKeyParams() { + return asymAlgorithm; + } + /** + * + * @return The sym algorithm key_parms. + */ + public TpmKeyParams getSymKeyParams() { + return symAlgorithm; + } + /** + * + * @return A textual report of the contents of the identity request. + */ + public String toString() { + String returnVal = ""; + returnVal += "TpmIdentityRequest:\n"; + returnVal += " asymAlgorithm:"; + if (TrousersModeBlankOeap) + returnVal += " (blank OAEP parameter)"; + returnVal += "\n" + asymAlgorithm.toString() + "\n"; + returnVal += " symAlgorithm:"; + if (TrousersModeSymkeyEncscheme) + returnVal += " (bad symmetric enc-scheme)"; + returnVal += "\n" + symAlgorithm.toString() + "\n"; + returnVal += " asymBlob:\n" + TpmUtils.byteArrayToString(asymBlob, 16) + "\n"; + returnVal += " symBlob:\n" + TpmUtils.byteArrayToString(symBlob, 16); + return returnVal; + } + /** + * Decrypt the asymmetric portion of the request to get the key needed to decrypt the symmetric portion. + * + * @param privCaKey The Privacy CA's private key. + * @return + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws BadPaddingException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws NoSuchAlgorithmException + * @throws IllegalBlockSizeException + * @throws InvalidAlgorithmParameterException + * @throws TpmUtils.TpmBytestreamResouceException + */ + private TpmSymmetricKey decryptAsym(RSAPrivateKey privCaKey) + throws NoSuchPaddingException, + InvalidKeyException, + BadPaddingException, + TpmUtils.TpmUnsignedConversionException, + NoSuchAlgorithmException, + IllegalBlockSizeException, + InvalidAlgorithmParameterException, + TpmUtils.TpmBytestreamResouceException, + PrivacyCaException { + TpmSymmetricKey symKey = new TpmSymmetricKey(); + switch (asymAlgorithm.getEncScheme()) { + case 0x3: // <-- most likely with NTRU, TrouSerS + Cipher asymCipher = Cipher.getInstance("RSA/ECB/OAEPWithSha1AndMGF1Padding"); + OAEPParameterSpec oaepSpec = new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified("TCPA".getBytes())); + asymCipher.init(Cipher.PRIVATE_KEY, privCaKey, oaepSpec); + asymCipher.update(asymBlob); + byte[] temparray = null; + try { + temparray = asymCipher.doFinal(); + } catch (BadPaddingException e) { //<- TrouSerS does not use an OAEP parameter string of "TCPA", per 1.1b spec. This results in a BadPaddingException -- try again without! + oaepSpec = new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified("".getBytes())); + asymCipher.init(Cipher.PRIVATE_KEY, privCaKey, oaepSpec); + asymCipher.update(asymBlob); + temparray = asymCipher.doFinal(); + TrousersModeBlankOeap = true; + } + if (temparray == null) + throw new PrivacyCaException("Unable to decrypt asym blob from incoming request."); + symKey = new TpmSymmetricKey(temparray); + break; + default: + asymCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); + asymCipher.init(Cipher.DECRYPT_MODE, privCaKey); + symKey = new TpmSymmetricKey(asymCipher.doFinal(asymBlob)); + break; + } + if ((symKey.getAlgorithmId() == TpmKeyParams.TPM_ALG_AES) && (symKey.getEncScheme() == TpmKeyParams.TPM_ES_NONE)) { + TrousersModeSymkeyEncscheme = true; + symKey.setEncScheme(TpmKeyParams.TPM_ES_SYM_CBC_PKCS5PAD); + } + return symKey; + } + /** + * Decrypt the symmetric portion of the request to get the identity proof. + * + * @param symKey The output of decryptAsym. + * @return + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidAlgorithmParameterException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws InvalidKeyException + * @throws BadPaddingException + * @throws IllegalBlockSizeException + * @throws PrivacyCaException + * @throws TpmUtils.TpmBytestreamResouceException + */ + private TpmIdentityProof decryptSym(TpmSymmetricKey symKey) + throws NoSuchAlgorithmException, + NoSuchPaddingException, + InvalidAlgorithmParameterException, + TpmUtils.TpmUnsignedConversionException, + InvalidKeyException, + BadPaddingException, + IllegalBlockSizeException, + PrivacyCaException, + TpmUtils.TpmBytestreamResouceException { + String instance = symKey.getAlgorithmStr() + "/" + symKey.getEncSchemeStr(); + //System.out.println("Instance: " + instance); + Cipher symCipher = Cipher.getInstance(instance); + IvParameterSpec ivSpec = new IvParameterSpec(symAlgorithm.getSubParams().getByteData()); + symCipher.init(Cipher.DECRYPT_MODE, symKey.getSecretKey(), ivSpec); + TpmIdentityProof identProof = new TpmIdentityProof(symCipher.doFinal(symBlob), TrousersModeIV, TrousersModeSymkeyEncscheme, TrousersModeBlankOeap); + return identProof; + } + /** + * If the byte blob captured as an Identity Request was not an encrypted Identity Proof (which could be done to transfer data from client to Privacy CA outside of the specification), then this method of decrypting the symblob may be preferable. + * + * @param symKey The TpmSymmetricKey as returned from decryptAsym() + * @return Decrypted byte blob + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidAlgorithmParameterException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws InvalidKeyException + * @throws BadPaddingException + * @throws IllegalBlockSizeException + * @throws PrivacyCaException + * @throws TpmUtils.TpmBytestreamResouceException + */ + private byte[] decryptSymRaw(TpmSymmetricKey symKey) + throws NoSuchAlgorithmException, + NoSuchPaddingException, + InvalidAlgorithmParameterException, + TpmUtils.TpmUnsignedConversionException, + InvalidKeyException, + BadPaddingException, + IllegalBlockSizeException, + PrivacyCaException, + TpmUtils.TpmBytestreamResouceException { + String instance = symKey.getAlgorithmStr() + "/" + symKey.getEncSchemeStr(); + //System.out.println("Instance: " + instance); + Cipher symCipher = Cipher.getInstance(instance); + IvParameterSpec ivSpec = new IvParameterSpec(symAlgorithm.getSubParams().getByteData()); + symCipher.init(Cipher.DECRYPT_MODE, symKey.getSecretKey(), ivSpec); + return symCipher.doFinal(symBlob); + } + /** + * Decrypt the identity request to get the identity proof. + * + * @param privCaKey The Privacy CA's private key. + * @return An identity proof. + * @throws InvalidKeyException + * @throws IllegalBlockSizeException + * @throws InvalidAlgorithmParameterException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws NoSuchAlgorithmException + * @throws BadPaddingException + * @throws NoSuchPaddingException + * @throws PrivacyCaException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public TpmIdentityProof decrypt(RSAPrivateKey privCaKey) + throws InvalidKeyException, + IllegalBlockSizeException, + InvalidAlgorithmParameterException, + TpmUtils.TpmUnsignedConversionException, + NoSuchAlgorithmException, + BadPaddingException, + NoSuchPaddingException, + PrivacyCaException, + TpmUtils.TpmBytestreamResouceException { + TpmSymmetricKey tempKey = decryptAsym(privCaKey); + return decryptSym(tempKey); + } + /** + * Decrypts the Identity Request, and DOES NOT assume the contents are an Identity Proof. + * + * @param privCaKey Privacy CA's private key + * @return Raw byte blob + * @throws InvalidKeyException + * @throws IllegalBlockSizeException + * @throws InvalidAlgorithmParameterException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws NoSuchAlgorithmException + * @throws BadPaddingException + * @throws NoSuchPaddingException + * @throws PrivacyCaException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public byte[] decryptRaw(RSAPrivateKey privCaKey) + throws InvalidKeyException, + IllegalBlockSizeException, + InvalidAlgorithmParameterException, + TpmUtils.TpmUnsignedConversionException, + NoSuchAlgorithmException, + BadPaddingException, + NoSuchPaddingException, + PrivacyCaException, + TpmUtils.TpmBytestreamResouceException { + TpmSymmetricKey tempKey = decryptAsym(privCaKey); + return decryptSymRaw(tempKey); + } + /** + * This must be run to properly identity the location of the symmetric encryption Initialization Vector. If TrouSerS-style + * formatting is used on the request, the IV is not in the symmetric key parameters, but rather at the head of the + * symmetrically encrypted blob. In order to decrypt consistently, regardless of the format use, this procedure will adjust + * from TrouSerS-style to 1.2 spec compliant style. A flag is set when parsing (in the constructor) so that the particular + * style is recorded. This will be used when constructing a response. + * + * @throws PrivacyCaException + */ + private void findIv() + throws PrivacyCaException { //must be called at this level to have access to symBlob + //Because TrouSerS-style might be in effect, we may have to find the IV and adjust the symBlob + //Also, based on this populate other values (keyLength, blockSize) + if (symAlgorithm.getSubParams().getValueData() == 0) { + TrousersModeIV = true; + //This indicates TrouSerS mode is active. + //Set the key length and block size to the value for the symmetric algorithm + switch (symAlgorithm.getAlgorithmId()) { + case 0x2: //TPM_ALG_DES + symAlgorithm.getSubParams().setKeyLength(56); + symAlgorithm.getSubParams().setValueData(64); //set block size, assume in bits (not specified in TCG documentation) + break; + case 0x3: //TPM_ALG_3DES + symAlgorithm.getSubParams().setKeyLength(192); + symAlgorithm.getSubParams().setValueData(64); //set block size, assume in bits (not specified in TCG documentation) + break; + case 0x6: //TPM_ALG_AES/AES128* most likely to occur + symAlgorithm.getSubParams().setKeyLength(128); + symAlgorithm.getSubParams().setValueData(128); //set block size, assume in bits (not specified in TCG documentation) + break; + case 0x8: //TPM_ALG_AES192 + symAlgorithm.getSubParams().setKeyLength(192); + symAlgorithm.getSubParams().setValueData(128); //set block size, assume in bits (not specified in TCG documentation) + break; + case 0x9: //TPM_ALG_AES256 + symAlgorithm.getSubParams().setKeyLength(256); + symAlgorithm.getSubParams().setValueData(128); //set block size, assume in bits (not specified in TCG documentation) + break; + default: + throw new PrivacyCaException("Unexpected symmetric algorithm ID: " + Integer.toHexString(symAlgorithm.getAlgorithmId())); + } + //snag the first (blocksize) bits from the symBlob + byte [] newIv = new byte[symAlgorithm.getSubParams().getValueData() / 8]; + System.arraycopy(symBlob, 0, newIv, 0, newIv.length); + symAlgorithm.getSubParams().setByteData(newIv); + byte [] newSymBlob = new byte[symBlob.length - newIv.length]; + System.arraycopy(symBlob, newIv.length, newSymBlob, 0, newSymBlob.length); + symBlob = newSymBlob; + } + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmIntegrityReport.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmIntegrityReport.java new file mode 100644 index 0000000..49fd951 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmIntegrityReport.java @@ -0,0 +1,208 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + + +//import gov.niarl.his.privacyca.TpmUtils.TpmBytestreamResouceException; +//import gov.niarl.his.privacyca.TpmUtils.TpmUnsignedConversionException; + +//import java.io.ByteArrayInputStream; +import java.security.*; +import java.security.interfaces.*; +import java.util.*; + +/** + * This class was created to test the functionality the TPM Module quote routine. Although there may not be a production need for this function, + * it does contain a routine that can determine the validity of a quote and signature by recreating the quote using nonce, and raw PCR values, + * then verify using the public key in the AIK certificate. + * + * @author schawki + * + */ +public class TpmIntegrityReport { + private Vector PCRlist = new Vector(); + private byte[] quote; + private byte[] signature; + /** + * Create a new TpmIntegrityReport, ready to accept data. + */ + public TpmIntegrityReport() { + PCRlist.trimToSize(); + } + /** + * Add a PCR value (these should be added in the order that they were requested from the TPM). + * + * @param newPCRbytes The new PCR value as a 20-byte array. + */ + public void addPCR(byte[] newPCRbytes) { + PCR newPcr = new PCR(newPCRbytes); + PCRlist.add(newPcr); + } + /** + * Add a PCR value (these should be added in the order that they were requested from the TPM). + * + * @param newPCR The new PCR vale as a PCR structure. + */ + public void addPCR(PCR newPCR) { + PCRlist.add(newPCR); + } + /** + * Set the quote. + * + * @param newQuote The 48 byte quote. + */ + public void setQuote(byte[] newQuote) { + quote = newQuote; + } + /** + * Set the quote signature. + * + * @param newSig The 256 byte signature. + */ + public void setSignature(byte[] newSig) { + signature = newSig; + } + public static class TpmIntegrityReportException extends Exception { + private static final long serialVersionUID = 0; + public TpmIntegrityReportException(String msg) { + super(msg); + } + } + private int countbits(byte[] mask){ + int count = 0; + int pcrnumber = 0; + //count the '1' bits in each byte + for(int i = 0; i < mask.length; i++){ + //count the '1' bits in each byte + int bitMask = 0x000100; + for(int j = 0; j < 8; j++){ + bitMask = bitMask/2; + if ((bitMask & mask[i])==bitMask){ + count++; + //System.out.println("PCR" + pcrnumber + " is set"); //for testing + } + pcrnumber++; + } + } + return count; + } + /** + * Check the integrity report for both consistency and validity. The Quote is reconstructed using the PCR + * values and nonce that should have been used by the TPM to generate the original quote. Also, validate + * the signature using the AIK certificate of the TPM that generated the report. If either the consistency + * or validity fails, false is returned. + * + * @param aik The AIK public key from the AIK certificate. + * @param nonce The nonce passed to the TPM. + * @param pcrBitMask The PRC bitmask that defines the registers requested. + * @return True if both consistency and validity tests pass, false otherwise. + * @throws TpmIntegrityReportException Thrown if the bitmask is not 3 bytes long. + * @throws TpmUtils.TpmUnsignedConversionException + * @throws NoSuchAlgorithmException + * @throws InvalidKeyException + * @throws SignatureException + */ + public boolean checkSignature(RSAPublicKey aik, byte[] nonce, byte[] pcrBitMask, boolean printResults) + throws TpmIntegrityReportException, + TpmUtils.TpmUnsignedConversionException, + NoSuchAlgorithmException, + InvalidKeyException, + SignatureException { + //check to see that the PCRs match the hash in the quote + PCRlist.trimToSize(); + //System.out.println(countbits(pcrBitMask)); + int bitcount = countbits(pcrBitMask); + byte[] PCRlongList = new byte[20 * bitcount]; + //byte[] PCRlongList = new byte[20 * PCRlist.size()]; //TODO: should we check to see that the number of PCRs requested (per the mask) matches those provided via the PCRlist? + // add PCRs to the long list + int count = 0; + /*while (!PCRlist.isEmpty()) { + PCR tempPCR = (PCR)PCRlist.remove(0); + System.arraycopy(tempPCR.getBytes(), 0, PCRlongList, (20 * count), 20); + count++; + }*/ + for (int i = 0; i < bitcount; i++) { + PCR tempPCR = (PCR)PCRlist.remove(0); + System.arraycopy(tempPCR.getBytes(), 0, PCRlongList, (20 * count), 20); + count++; + } + //if (pcrBitMask.length != 3) throw new TpmIntegrityReportException("PCR bit mask must be 24 bits (3 byte) long."); + short bitMaskLength = (short)pcrBitMask.length; + byte[] bitMaskLengthBytes = TpmUtils.shortToByteArray(bitMaskLength); + byte[] pcrSelect = new byte[bitMaskLengthBytes.length + pcrBitMask.length]; //should be 5 + System.arraycopy(bitMaskLengthBytes, 0, pcrSelect, 0, bitMaskLengthBytes.length); + System.arraycopy(pcrBitMask, 0, pcrSelect, bitMaskLengthBytes.length, pcrBitMask.length); + byte[] listSize = TpmUtils.intToByteArray(PCRlongList.length); + byte[] pcrComposite = new byte[pcrSelect.length + listSize.length + PCRlongList.length]; + System.arraycopy(pcrSelect, 0, pcrComposite, 0, pcrSelect.length); + System.arraycopy(listSize, 0, pcrComposite, pcrSelect.length, listSize.length); + System.arraycopy(PCRlongList, 0, pcrComposite, pcrSelect.length + listSize.length, PCRlongList.length); + // perform hash + MessageDigest md = MessageDigest.getInstance("SHA1"); + md.update(pcrComposite); + byte [] newQuote = md.digest(); + // compare + boolean pcrsMatch = true; + for (int i = 0; i < 20; i++) { + if (newQuote[i] != quote[i+8]) pcrsMatch = false; + } + //compare nonces + boolean noncesMatch = true; + for (int i = 0; i < 20; i++) { + if (nonce[i] != quote[i+28]) noncesMatch = false; + } + //check to see that the quote is verified by the signature + Signature sig = Signature.getInstance("SHA1withRSA"); + sig.initVerify(aik); + sig.update(quote); + boolean sigCheck = sig.verify(signature); + //boolean printResults = true; + if(printResults){ + if(pcrsMatch) + System.out.println("PCR Composite reconstruction: PASS"); + else{ + System.out.println("PCR Composite reconstruction: FAIL"); + byte [] receivedQuote = new byte [20]; + System.arraycopy(quote, 8, receivedQuote, 0, 20); + System.out.println(" Received: " + TpmUtils.byteArrayToHexString(receivedQuote) + "; Expected: " + TpmUtils.byteArrayToHexString(newQuote)); + } + if(noncesMatch) + System.out.println("Nonce check: PASS"); + else + System.out.println("Nonce check: FAIL"); + if(sigCheck) + System.out.println("Signature check: PASS"); + else + System.out.println("Signature check: FAIL"); + } + return (pcrsMatch && noncesMatch && sigCheck); + } + /** + * This holds a single PCR value. + * @author schawki + * + */ + public static class PCR { + private byte[] value; + public PCR(byte[] newValue) { + value = newValue; + } + public byte[] getBytes() { + return value; + } + public void setBytes(byte[] newValue) { + value = newValue; + } + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmKey.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmKey.java new file mode 100644 index 0000000..931ee8e --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmKey.java @@ -0,0 +1,238 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import gov.niarl.his.privacyca.TpmUtils.TpmBytestreamResouceException; +import gov.niarl.his.privacyca.TpmUtils.TpmUnsignedConversionException; + +import java.io.ByteArrayInputStream; + +/** + *

    This class is for the TCG's TPM_KEY structure.

    + * @author schawki + * + */ +public class TpmKey { + private byte [] structVer = {(byte)0x01, (byte)0x01, (byte)0x00, (byte)0x00}; + private short tpmKeyUsage = 0;//UINT16 + private int tpmKeyFlags = 0;//UINT32 + private byte tpmAuthDataUsage = (byte)0x00;//BYTE (just 1) + private TpmKeyParams keyParms= null; + //pcrInfoSize UINT32 + private byte [] pcrInfo = null; + //UINT32 size, see below + private byte [] tpmStorePubkey = null; //actually TPM_STORE_PUBKEY, which is a UINT32 size plus key data, usually the modulus + //encryptedDataSize UINT32 + private byte [] encryptedData = null; + + /** + * Create a new TpmKey with no default values. + */ + public TpmKey(){ + // + } + /** + * Create a new TpmKey by extracting values from a byte blob. + * @param blob Raw blob representing a TPM_KEY. + * @throws TpmBytestreamResouceException + * @throws TpmUnsignedConversionException + */ + public TpmKey(byte [] blob) + throws TpmBytestreamResouceException, + TpmUnsignedConversionException{ + ByteArrayInputStream bs = new ByteArrayInputStream(blob); + structVer = TpmUtils.getBytes(bs, 4); //4 bytes + tpmKeyUsage = TpmUtils.getUINT16(bs); //uint16 + tpmKeyFlags = TpmUtils.getUINT32(bs); //uint32 + tpmAuthDataUsage = TpmUtils.getBytes(bs, 1)[0]; //byte + keyParms = new TpmKeyParams(bs); //TpmKeyParams + int tempSize = TpmUtils.getUINT32(bs); //uint32 + pcrInfo = TpmUtils.getBytes(bs, tempSize); // bytes + tempSize = TpmUtils.getUINT32(bs); //uint32 + tpmStorePubkey = TpmUtils.getBytes(bs, tempSize); // bytes + tempSize = TpmUtils.getUINT32(bs); //uint32 + encryptedData = TpmUtils.getBytes(bs, tempSize); // bytes + } + /** + * Get the stored key modulus. + * @return + */ + public byte [] getModulus(){ + return tpmStorePubkey; + } + /** + * Set the TPM_STRUCT_VER, should always be 0x01010000. + * @param newStructVer + */ + public void setStructVer(byte [] newStructVer){ + structVer = newStructVer; + } + /** + * Get the TPM_STRUCT_VER. + * @return + */ + public byte [] getStructVer(){ + return structVer; + } + /** + * Set the key usage. See the TPM Main Specification Part 2: Structures, section 5.8 for detailed information about TPM_KEY_USAGE. + * @param newTpmKeyUsage + */ + public void setTpmKeyUsage(short newTpmKeyUsage){ + tpmKeyUsage = newTpmKeyUsage; + } + /** + * Get the key usage value. + * @return + */ + public short getTpmKeyUsage(){ + return tpmKeyUsage; + } + /** + * Set the key flags. See the TPM Main Specification Part 2: Structures, section 5.9 for detailed information about TPM_KEY_FLAGS. + * @param newTpmKeyFlags + */ + public void setTpmKeyFlags(int newTpmKeyFlags){ + tpmKeyFlags = newTpmKeyFlags; + } + /** + * Get the key flags. + * @return + */ + public int getTpmKeyFlags(){ + return tpmKeyFlags; + } + /** + * Set the key auth data usage. See the TPM Main Specification Part 2: Structures, section 5.9 for detailed information about TPM_AUTH_DATA_USAGE. + * @param newTpmAuthDataUsage + */ + public void setTpmAuthDataUsage(byte newTpmAuthDataUsage){ + tpmAuthDataUsage = newTpmAuthDataUsage; + } + /** + * Get the key auth data usage. + * @return + */ + public byte getTpmAuthDataUsage(){ + return tpmAuthDataUsage; + } + /** + * Set the TPM_KEY_PARMS using a TpmKeyParams object. + * @param newKeyParms + */ + public void setKeyParms(TpmKeyParams newKeyParms){ + keyParms = newKeyParms; + } + /** + * Get the TPM_KEY_PARMS for the key. + * @return + */ + public TpmKeyParams getKeyParms(){ + return keyParms; + } + /** + * Set the PCR info for the key. As per the spec, if the key is not bound by PCR info, this should be null (size 0). If the key is bound by PCR info, the newPcrInfo parameter should be set as the serialized form of TPM_PCR_INFO, as defined in section 8.3 of the TPM Main Part 2: Structures document. + * @param newPcrInfo + */ + public void setPcrInfo(byte [] newPcrInfo){ + pcrInfo = newPcrInfo; + } + /** + * Get the PCR info. If null, the key is not bound to PCR info. + * @return + */ + public byte [] getPcrInfo(){ + return pcrInfo; + } + /** + * Set the raw public key information. This is the modulus only, as the public exponent is stored in the TPM_KEY_PARMS section. + * @param newTpmStorePubkey + */ + public void setTpmStorePubkey(byte [] newTpmStorePubkey){ + tpmStorePubkey = newTpmStorePubkey; + } + /** + * Get the stored TPM_STORE_PUBKEY. + * @return + */ + public byte [] getTpmStorePubkey(){ + return tpmStorePubkey; + } + /** + * Set the encrypted data portion of the key. This should generally be provided by the TPM itself. + * @param newEncryptedData + */ + public void setEncryptedData(byte [] newEncryptedData){ + encryptedData = newEncryptedData; + } + /** + * Get the encrytped portion of the key. + * @return + */ + public byte [] getEncryptedData(){ + return encryptedData; + } + /** + * Serialize the TpmKey object in the form of a TPM_KEY structure. + * @return + * @throws TpmUnsignedConversionException + */ + public byte [] toByteArray() + throws TpmUnsignedConversionException{ + byte [] keyParmsBytes = keyParms.toByteArray(); + byte [] toReturn = new byte[4 + 2 + 4 + 1 + keyParmsBytes.length + 4 + pcrInfo.length + 4 + tpmStorePubkey.length + 4 + encryptedData.length]; + byte [] tempBytes = null; + int copyPos = 0; + //structver: 4 + System.arraycopy(structVer, 0, toReturn, copyPos, structVer.length); + copyPos += structVer.length; + //tpm key usage: uint16/short + tempBytes = TpmUtils.shortToByteArray(tpmKeyUsage); + System.arraycopy(tempBytes, 0, toReturn, copyPos, tempBytes.length); + copyPos += tempBytes.length; + //tpm key flags: uint32/int + tempBytes = TpmUtils.intToByteArray(tpmKeyFlags); + System.arraycopy(tempBytes, 0, toReturn, copyPos, tempBytes.length); + copyPos += tempBytes.length; + //tpm auth data usage: byte[1] + tempBytes = new byte[1]; + tempBytes[0] = tpmAuthDataUsage; + System.arraycopy(tempBytes, 0, toReturn, copyPos, tempBytes.length); + copyPos += tempBytes.length; + //tpm key parms: above + System.arraycopy(keyParmsBytes, 0, toReturn, copyPos, keyParmsBytes.length); + copyPos += keyParmsBytes.length; + //size of pcr info + tempBytes = TpmUtils.intToByteArray(pcrInfo.length); + System.arraycopy(tempBytes, 0, toReturn, copyPos, tempBytes.length); + copyPos += tempBytes.length; + //pcr info + System.arraycopy(pcrInfo, 0, toReturn, copyPos, pcrInfo.length); + copyPos += pcrInfo.length; + //size of modulus + tempBytes = TpmUtils.intToByteArray(tpmStorePubkey.length); + System.arraycopy(tempBytes, 0, toReturn, copyPos, tempBytes.length); + copyPos += tempBytes.length; + //modulus + System.arraycopy(tpmStorePubkey, 0, toReturn, copyPos, tpmStorePubkey.length); + copyPos += tpmStorePubkey.length; + //enc data size + tempBytes = TpmUtils.intToByteArray(encryptedData.length); + System.arraycopy(tempBytes, 0, toReturn, copyPos, tempBytes.length); + copyPos += tempBytes.length; + //enc data + System.arraycopy(encryptedData, 0, toReturn, copyPos, encryptedData.length); + return toReturn; + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmKeyParams.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmKeyParams.java new file mode 100644 index 0000000..b1c62c5 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmKeyParams.java @@ -0,0 +1,332 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.io.*; + +/** + *

    This class is for the TCG's TPM_KEY_PARMS structure. Several other TCG values are defined here, as it seems appropriate to do so at the time.

    + * @author schawki + * + */ +public class TpmKeyParams { + public static final int TPM_ALG_RSA = 0x1; + public static final int TPM_ALG_DES = 0x2; + public static final int TPM_ALG_3DES = 0x3; + public static final int TPM_ALG_SHA = 0x4; + public static final int TPM_ALG_HMAC = 0x5; + public static final int TPM_ALG_AES = 0x6; + public static final int TPM_ALG_AES128 = TPM_ALG_AES; + public static final int TPM_ALG_MGF1 = 0x7; + public static final int TPM_ALG_AES192 = 0x8; + public static final int TPM_ALG_AES256 = 0x9; + public static final int TPM_ALG_XOR = 0xa; + public static final short TPM_ES_NONE = 0x1; + public static final short TPM_ES_RSAESPKCSv15 = 0x2; + public static final short TPM_ES_RSAESOAEP_SHA1_MGF1 = 0x3; + public static final short TPM_ES_SYM_CNT = 0x4; + public static final short TPM_ES_SYM_OFB = 0x5; + public static final short TPM_ES_SYM_CBC_PKCS5PAD = 0xff; + public static final short TPM_SS_NONE = 0x1; + public static final short TPM_SS_RSASAPKCS1v15_SHA1 = 2; + public static final short TPM_SS_RSASAPKCS1v15_DER = 3; + public static final short TPM_SS_RSASAPKCS1v15_INFO = 4; + + private int algorithmId; + private short encScheme; + private short sigScheme; + private TpmKeySubParams subParams = null; + private boolean TrouSerSmode = false; + + /** + * Given an algorithm, return the text string. Useful for debugging and logging. + * @param alg + * @return + */ + public static String algToString(int alg) { + String returnVal = ""; + switch (alg) { + case TPM_ALG_RSA: + returnVal = "TPM_ALG_RSA"; + break; + case TPM_ALG_DES: + returnVal = "TPM_ALG_DES"; + break; + case TPM_ALG_3DES: + returnVal = "TPM_ALG_3DES"; + break; + case TPM_ALG_SHA: + returnVal = "TPM_ALG_SHA"; + break; + case TPM_ALG_HMAC: + returnVal = "TPM_ALG_HMAC"; + break; + case TPM_ALG_AES: + returnVal = "TPM_ALG_AES/TPM_ALG_AES128"; + break; + case TPM_ALG_MGF1: + returnVal = "TPM_ALG_MGF1"; + break; + case TPM_ALG_AES192: + returnVal = "TPM_ALG_AES192"; + break; + case TPM_ALG_AES256: + returnVal = "TPM_ALG_AES256"; + break; + case TPM_ALG_XOR: + returnVal = "TPM_ALG_XOR"; + break; + default: + returnVal = "UNKNOWN ALG VALUE! (" + Integer.toString(alg) + ")"; + break; + } + return returnVal; + } + /** + * Given an encryption scheme, return the string. Useful for debugging and logging. + * @param es + * @param TrouSerSmode + * @return + */ + public static String esToString(short es, boolean TrouSerSmode) { + String returnVal = ""; + switch (es) { + case TPM_ES_NONE: + returnVal = "TPM_ES_NONE"; + if (TrouSerSmode) + returnVal += " (should be TPM_ES_SYM_CBC_PKCS5PAD)"; + break; + case TPM_ES_RSAESPKCSv15: + returnVal = "TPM_ES_RSAESPKCSv15"; + break; + case TPM_ES_RSAESOAEP_SHA1_MGF1: + returnVal = "TPM_ES_RSAESOAEP_SHA1_MGF1"; + break; + case TPM_ES_SYM_CNT: + returnVal = "TPM_ES_SYM_CNT"; + break; + case TPM_ES_SYM_OFB: + returnVal = "TPM_ES_SYM_OFB"; + break; + case TPM_ES_SYM_CBC_PKCS5PAD: + returnVal = "TPM_ES_SYM_CBC_PKCS5PAD"; + break; + default: + returnVal = "UNKNOWN ENCSCHEME VALUE! (" + Short.toString(es) + ")"; + break; + } + return returnVal; + } + /** + * Given a signature scheme, return the string. Useful for debugging and logging. + * @param ss + * @return + */ + public static String ssToString(short ss) { + String returnVal = ""; + switch (ss) { + case TPM_SS_NONE: + returnVal = "TPM_SS_NONE"; + break; + case TPM_SS_RSASAPKCS1v15_SHA1: + returnVal = "TPM_SS_RSASAPKCS1v15_SHA1"; + break; + case TPM_SS_RSASAPKCS1v15_DER: + returnVal = "TPM_SS_RSASAPKCS1v15_DER"; + break; + case TPM_SS_RSASAPKCS1v15_INFO: + returnVal = "TPM_SS_RSASAPKCS1v15_INFO"; + break; + default: + returnVal = "UNKNOWN SIGSCHEME VALUE! (" + Short.toString(ss) + ")"; + break; + } + return returnVal; + } + /** + * Create a new TpmKeyParms with no default values set. + */ + public TpmKeyParams(){} + /** + * Create a new TpmKeyParams by extracting values from a ByteArrayInputStream. + * + * @param source The InputStream. + * @throws TpmUtils.TpmUnsignedConversionException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public TpmKeyParams(ByteArrayInputStream source) + throws TpmUtils.TpmUnsignedConversionException, + TpmUtils.TpmBytestreamResouceException { + algorithmId = TpmUtils.getUINT32(source); + encScheme = TpmUtils.getUINT16(source); + sigScheme = TpmUtils.getUINT16(source); + int subParamSize = TpmUtils.getUINT32(source); + if ((algorithmId != TPM_ALG_RSA) && (subParamSize == 0)) { + TrouSerSmode = true; + } + switch (algorithmId) { + case TPM_ALG_RSA: + subParams = new TpmRsaKeyParams(source, subParamSize); + break; + case TPM_ALG_DES: + case TPM_ALG_3DES: + case TPM_ALG_AES: //same as TPM_ALG_AES128; most likely to occur + case TPM_ALG_AES192: + case TPM_ALG_AES256: + subParams = new TpmSymmetricKeyParams(source, subParamSize); + break; + default: //?could be an issue if something other than RSA or a DES/AES variant? + if (subParamSize > 0) + TpmUtils.getBytes(source, subParamSize); //just throw it away -- what else to do with it?? + break; + } + } + /** + * Manually set TrouSerS mode. True means that the symmetric IV will appear at the beginning of a symmetrically + * encrypted blob, while false means that it will appear within a SymmetricKeyParams structure. This value is + * used when determining the format of the byte arrays that are passed back from the Privacy CA. By default the Privacy + * CA will set this value based on the format of the incoming identity request. + * + * @param state + */ + public void setTrouSerSmode(boolean state) { + TrouSerSmode = state; + } + /** + * + * @return The current state of TrouSerS mode for this key params structure. + */ + public boolean getTrouSerSmode() { + return TrouSerSmode; + } + /** + * Assemble the KeyParams structure into a byte array. + * + * @return The byte array. + * @throws TpmUtils.TpmUnsignedConversionException + */ + public byte [] toByteArray() + throws TpmUtils.TpmUnsignedConversionException { + byte [] algoId = TpmUtils.intToByteArray(algorithmId); + byte [] encSchm = TpmUtils.shortToByteArray(encScheme); + byte [] sigSchm = TpmUtils.shortToByteArray(sigScheme); + byte [] size; + byte [] subParms; + int x; + if (TrouSerSmode && (algorithmId != 1)) { + size = TpmUtils.intToByteArray(0); + subParms = null; + x = algoId.length + encSchm.length + sigSchm.length + size.length; + } + else { + if (subParams != null) { + subParms = subParams.toByteArray(); + size = TpmUtils.intToByteArray(subParms.length); + x = algoId.length + encSchm.length + sigSchm.length + size.length + subParms.length; + } + else { + subParms = null; + size = TpmUtils.intToByteArray(0); + x = algoId.length + encSchm.length + sigSchm.length + size.length; + } + } + byte [] returnArray = new byte[x]; + System.arraycopy(algoId, 0, returnArray, 0, algoId.length); + System.arraycopy(encSchm, 0, returnArray, algoId.length, encSchm.length); + System.arraycopy(sigSchm, 0, returnArray, algoId.length + encSchm.length, sigSchm.length); + System.arraycopy(size, 0, returnArray, algoId.length + encSchm.length + sigSchm.length, size.length); + if (subParms != null) System.arraycopy(subParms, 0, returnArray, algoId.length + encSchm.length + sigSchm.length + size.length, subParms.length); + return returnArray; + } + /** + * + * @return A String representing a human-readable report of the Key Params. + */ + public String toString() { + String returnVal = ""; + returnVal += "TpmKeyParams:\n"; + //returnVal += " algorithmId: " + Integer.toString(algorithmId) + "\n"; + //returnVal += " encScheme: " + Short.toString(encScheme) + "\n"; + //returnVal += " sigScheme: " + Short.toString(sigScheme) + "\n"; + returnVal += " algorithmId: " + TpmKeyParams.algToString(algorithmId) + "\n"; + returnVal += " encScheme: " + TpmKeyParams.esToString(encScheme, TrouSerSmode) + "\n"; + returnVal += " sigScheme: " + TpmKeyParams.ssToString(sigScheme) + "\n"; + returnVal += " subParameters:";//\n"; + if (TrouSerSmode) { + returnVal += " (fabricated: TrouSerS-style IV placement)"; + } + returnVal += "\n" + subParams.toString(); + return returnVal; + } + /** + * + * @return The current algorithm ID value. + */ + public int getAlgorithmId() { + return algorithmId; + } + /** + * Set a new algorithm ID value; + * + * @param newAlgId The new value. + */ + public void setAlgorithmId(int newAlgId) { + algorithmId = newAlgId; + } + /** + * + * @return The current encryption scheme value. + */ + public short getEncScheme() { + return encScheme; + } + /** + * Set a new encryption scheme value; + * + * @param newEncScheme The new value. + */ + public void setEncScheme(short newEncScheme) { + encScheme = newEncScheme; + } + /** + * + * @return The current signature scheme. + */ + public short getSigScheme() { + return sigScheme; + } + /** + * Set a new signature scheme value. + * + * @param newSigScheme The new value. + */ + public void setSigScheme(short newSigScheme) { + sigScheme = newSigScheme; + } + /** + * + * @return The currently assigned TpmKeySubParams. Will be null, or a TpmRsaKeyParams or TpmSymmetricKeyParams structure. + */ + public TpmKeySubParams getSubParams() { + return subParams; + } + /** + * Set a new TpmKeySubParams structure. + * + * @param newSubParams The new TpmRsaKeyParams or TpmSymmetricKeyParams structure. + */ + public void setSubParams(TpmKeySubParams newSubParams) { + subParams = newSubParams; + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmKeySubParams.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmKeySubParams.java new file mode 100644 index 0000000..e67926f --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmKeySubParams.java @@ -0,0 +1,30 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +/** + *

    Interface for the sub-parameters, as used in a TPM_KEY_PARMS structure. This interface is implemented by TpmRsaKeyParams and TpmSymmetricKeyParams.

    + * @author schawki + * + */ +public interface TpmKeySubParams { + public int getKeyLength(); + public void setKeyLength(int newValue); + public int getValueData(); //The value data is different for RsaKeyParams (number of primes) and SymmetricKeyParams (block size) + public void setValueData(int newValue); + public byte [] getByteData(); //The byte data is different for RsaKeyParams (public exponent) and SymmetricKeyParams (IV) + public void setByteData(byte [] newValue); + public byte [] toByteArray() throws TpmUtils.TpmUnsignedConversionException; + public String toString(); +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmModule.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmModule.java new file mode 100644 index 0000000..3805998 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmModule.java @@ -0,0 +1,805 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * 锟�Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 锟�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. + * 锟�Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import gov.niarl.his.privacyca.TpmUtils.TpmBytestreamResouceException; +import gov.niarl.his.privacyca.TpmUtils.TpmUnsignedConversionException; + +import java.io.*; +import java.util.*; +import java.security.cert.*; + +/** + *

    The TpmModule class is a Java front end for C++ utilities that work directly with the TSS for interfacing with the TPM.

    + * + * @author schawki + * + */ + +//TODO: +//TODO: +//TODO: Add Javadoc for the public functions +//TODO: This is probably the most usable class of everything in this package, so this is more important than normal +//TODO: Make sure to describe the use of the properties file +//TODO: +//TODO: +public class TpmModule { + /** + * + * @author schawki + * + */ + public static class TpmModuleException extends Exception { + private static final long serialVersionUID = 0; + /** + * + * @param msg + */ + public TpmModuleException(String msg) { + super(msg); + } + } + /** + * + * @author schawki + * + */ + private static class commandLineResult { + private int returnCode = 0; + private String [] results = null; + /** + * + * @param newReturnCode + * @param numResults + */ + public commandLineResult(int newReturnCode, int numResults){ + returnCode = newReturnCode; + results = new String[numResults]; + } + /** + * + * @return + */ + public int getReturnCode(){ + return returnCode; + } + /** + * + * @param index + * @param result + * @throws IllegalArgumentException + */ + public void setResult(int index, String result) + throws IllegalArgumentException { + if (index + 1 > results.length) + throw new IllegalArgumentException("Array index out of bounds."); + results[index] = result; + } + /** + * + * @return + */ + public int getResultCount(){ + return results.length; + } + /** + * + * @param index + * @return + * @throws IllegalArgumentException + */ + public String getResult(int index) + throws IllegalArgumentException { + if (index + 1 > results.length) + throw new IllegalArgumentException("Array index out of bounds."); + return results[index]; + } + + } + /** + * + * @param mode + * @param args + * @param returnCount + * @param useTrousersMode + * @return + * @throws IOException + */ + private static commandLineResult executeVer2Command(int mode, String args, int returnCount, boolean useTrousersMode) + throws IOException { + int returnCode = 0; + final String new_TPM_MODULE_EXE_PATH = "TpmModuleExePath"; + final String new_EXE_NAME = "ExeName"; + final String new_TROUSERS_MODE = "TrousersMode"; + final String DEBUG_MODE = "DebugMode"; + FileInputStream PropertyFile = null; + String newTpmModuleExePath = "./exe"; + String newExeName = "NIARL_TPM_Module"; + String newTrousersMode = "False"; + String debugMode = "False"; + try { + PropertyFile = new FileInputStream("TPMModule.properties"); + Properties TpmModuleProperties = new Properties(); + TpmModuleProperties.load(PropertyFile); + newTpmModuleExePath = TpmModuleProperties.getProperty(new_TPM_MODULE_EXE_PATH, ".\\exe"); + newExeName = TpmModuleProperties.getProperty(new_EXE_NAME, "NIARL_TPM_Module"); + newTrousersMode = TpmModuleProperties.getProperty(new_TROUSERS_MODE, "False"); + debugMode = TpmModuleProperties.getProperty(DEBUG_MODE, "False"); + } catch (FileNotFoundException e) { + System.out.println("Error finding TPM Module properties file; using defaults."); + } catch (IOException e) { + System.out.println("Error loading TPM Module properties file; using defaults."); + } + finally{ + if (PropertyFile != null){ + try { + PropertyFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + boolean TrousersMode = false; + if (newTrousersMode.toLowerCase().equals("true")) + TrousersMode = true; + boolean DebugMode = false; + if (debugMode.toLowerCase().equals("true")) + DebugMode = true; + String commandLine = newTpmModuleExePath + newExeName + " -mode " + mode + " " + args; + if (TrousersMode && useTrousersMode) + commandLine += " -trousers"; + if (DebugMode) System.out.println("\"" + commandLine + "\""); + Process p = Runtime.getRuntime().exec(commandLine); + String line = ""; + if (returnCount != 0){ + BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); + String newLine = ""; + try { + while ((newLine = input.readLine()) != null) { + line = newLine; + } + input.close(); + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + if (input != null) + input.close(); + } + + } + if (DebugMode) System.out.println("\"" + line + "\""); + + //do a loop to wait for an exit value + + boolean isRunning; + int timeout = 300000; //any need to add this to the properties file? + int countToTimeout = 0; + do { + countToTimeout++; + isRunning = false; + try { + returnCode = p.exitValue(); + }catch(IllegalThreadStateException e1) { + isRunning = true; + try { + Thread.sleep(1); + //if (countToTimeout%5000 == 0) System.out.print("."); + } catch (InterruptedException e2) { + isRunning = false; + } + } + } while(isRunning && (countToTimeout < timeout)); + if (countToTimeout == timeout){ + System.out.println("Timeout reached"); + p.destroy(); + } + + returnCode = p.exitValue(); + commandLineResult toReturn = new commandLineResult(returnCode, returnCount); + if ((returnCode == 0)&&(returnCount != 0)) { + StringTokenizer st = new StringTokenizer(line); + for (int i = 0; i < returnCount; i++) { + toReturn.setResult(i, st.nextToken()); + } + } + return toReturn; + } + /** + * + * @param ownerAuth + * @param nonce + * @throws IOException + * @throws TpmModuleException + */ + public static void takeOwnership(byte [] ownerAuth, byte [] nonce) + throws IOException, + TpmModuleException { + /* + * Take Ownership + * NIARL_TPM_Module -mode 1 -owner_auth <40 char hex blob> -nonce <40 char hex blob> + * return: no return *** + */ + String argument = "-owner_auth " + TpmUtils.byteArrayToHexString(ownerAuth) + " -nonce " + TpmUtils.byteArrayToHexString(nonce); + commandLineResult result = executeVer2Command(1, argument, 0, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.takeOwnership returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return; + } + /** + * + * @param ownerAuth + * @throws IOException + * @throws TpmModuleException + */ + public static void clearOwnership(byte [] ownerAuth) + throws IOException, + TpmModuleException { + /* + * Clear Ownership + * NIARL_TPM_Module -mode 2 -owner_auth <40 char hex blob> + * return: no return *** + */ + String argument = "-owner_auth " + TpmUtils.byteArrayToHexString(ownerAuth); + commandLineResult result = executeVer2Command(2, argument, 0, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.clearOwnership returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return; + } + /** + * + * @param ownerAuth + * @param keyAuth + * @param keyLabel + * @param pcaPubKeyBlob + * @param keyIndex + * @param endorsmentCredential + * @param useECinNvram + * @return + * @throws IOException + * @throws TpmModuleException + * @throws CertificateEncodingException + */ + public static TpmIdentity collateIdentityRequest(byte [] ownerAuth, byte [] keyAuth, String keyLabel, byte [] pcaPubKeyBlob, int keyIndex, X509Certificate endorsmentCredential, boolean useECinNvram) + throws IOException, + TpmModuleException, + CertificateEncodingException { + /* + * Collate Identity Request + * NIARL_TPM_Module -mode 3 -owner_auth <40 char hex blob> -key_auth <40 char hex blob> -key_label -pcak -key_index [-ec_blob -ec_nvram -trousers] + * return: + */ + String argument = "-owner_auth " + TpmUtils.byteArrayToHexString(ownerAuth) + + " -key_auth " + TpmUtils.byteArrayToHexString(keyAuth) + + " -key_label " + TpmUtils.byteArrayToHexString(keyLabel.getBytes()) + + " -pcak " + TpmUtils.byteArrayToHexString(pcaPubKeyBlob) + + " -key_index " + keyIndex; + if (endorsmentCredential != null) + argument += " -ec_blob " + TpmUtils.byteArrayToHexString(endorsmentCredential.getEncoded()); + if (useECinNvram) + argument += " -ec_nvram"; + // TROUSERS MODE OPTIONAL + commandLineResult result = executeVer2Command(3, argument, 3, true); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.collateIdentityRequest returned nonzero error: " + result.getReturnCode() + "(" + ")"); + byte [] identityRequest = TpmUtils.hexStringToByteArray(result.getResult(0)); + byte [] aikModulus = TpmUtils.hexStringToByteArray(result.getResult(1)); + byte [] aikKeyBlob = TpmUtils.hexStringToByteArray(result.getResult(2)); + TpmIdentity toReturn = new TpmIdentity(identityRequest, aikModulus, aikKeyBlob); + return toReturn; + } + /** + * + * @param ownerAuth + * @param keyAuth + * @param asymCaContents + * @param symCaAttestation + * @param keyIndex + * @return + * @throws IOException + * @throws TpmModuleException + */ + public static byte [] activateIdentity(byte [] ownerAuth, byte [] keyAuth, byte [] asymCaContents, byte [] symCaAttestation, int keyIndex) + throws IOException, + TpmModuleException { + /* + * Activate Identity + * NIARL_TPM_Module -mode 4 -owner_auth <40 char hex blob> -key_auth <40 char hex blob> -asym <> -sym <> -key_index + * return: + */ + String argument = "-owner_auth " + TpmUtils.byteArrayToHexString(ownerAuth) + + " -key_auth " + TpmUtils.byteArrayToHexString(keyAuth) + + " -asym " + TpmUtils.byteArrayToHexString(asymCaContents) + + " -sym " + TpmUtils.byteArrayToHexString(symCaAttestation) + + " -key_index " + keyIndex; + commandLineResult result = executeVer2Command(4, argument, 1, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.activateIdentity returned nonzero error: " + result.getReturnCode() + "(" + ")"); + byte [] identityCredential = TpmUtils.hexStringToByteArray(result.getResult(0)); + return identityCredential; + } + /** + * + * @param keyAuth + * @param nonce + * @param mask + * @param keyIndex + * @return + * @throws IllegalArgumentException + * @throws IOException + * @throws TpmModuleException + */ + public static TpmIntegrityReport quote(byte [] keyAuth, byte [] nonce, byte [] mask, int keyIndex) + throws IllegalArgumentException, + IOException, + TpmModuleException { + /* + * Quote + * NIARL_TPM_Module -mode 5 -key_auth <40 char hex blob> -nonce <40 char hex blob> -mask <> -key_index + * return: + */ + //check the mask + if ((mask.length > 3)||(mask.length == 0)) { + throw new IllegalArgumentException ("TpmModule.quote: Mask must be between 1 and 3 bytes in length."); + } + int pcrCount = 0; + for (int i = 0; i < mask.length; i++) { + for (int j = 0; j < 8; j++) { + if ((0x80>>j&mask[i])==(0x80>>j)) + pcrCount++; //count the bits! + } + } + String argument = "-key_auth " + TpmUtils.byteArrayToHexString(keyAuth) + + " -nonce " + TpmUtils.byteArrayToHexString(nonce) + + " -mask " + TpmUtils.byteArrayToHexString(mask) + + " -key_index " + keyIndex; + commandLineResult result = executeVer2Command(5, argument, pcrCount + 3, false); + // command line app should return pcrs, (1 nonce,) 1 quote, and 1 signature + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.quote returned nonzero error: " + result.getReturnCode() + "(" + ")"); + if (result.getResultCount() != pcrCount + 3) throw new TpmModuleException("TpmModule.quote returned the wrong number of results."); + TpmIntegrityReport toReturn = new TpmIntegrityReport(); + for (int i = 0; i < pcrCount; i++) + toReturn.addPCR(TpmUtils.hexStringToByteArray(result.getResult(i))); + toReturn.setQuote(TpmUtils.hexStringToByteArray(result.getResult(pcrCount + 1))); + //skip getting the nonce + toReturn.setSignature(TpmUtils.hexStringToByteArray(result.getResult(pcrCount + 2))); + return toReturn; + } + /** + * + * @param ownerAuth + * @param resetData + * @param nonce + * @param keyIndex + * @return + * @throws IOException + * @throws TpmModuleException + */ + public static byte [] createRevocableEndorsementKey(byte [] ownerAuth, byte [] resetData, byte [] nonce, int keyIndex) + throws IOException, + TpmModuleException { + /* + * Create Revocable Endorsement Key + * NIARL_TPM_Module -mode 6 -owner_auth <40 char hex blob> -reset <> -nonce <40 char hex blob> -key_index + * return: + * + * What is the key index for?? + */ + String argument = "-owner_auth " + TpmUtils.byteArrayToHexString(ownerAuth) + + " -reset " + TpmUtils.byteArrayToHexString(resetData) + + " -nonce " + TpmUtils.byteArrayToHexString(nonce) + + " -key_index " + keyIndex; + commandLineResult result = executeVer2Command(6, argument, 1, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.createRevocableEndorsementKey returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return TpmUtils.hexStringToByteArray(result.getResult(0)); + } + /** + * + * @param ownerAuth + * @param resetData + * @throws IOException + * @throws TpmModuleException + */ + public static void revokeRevocableEndorsementKey(byte [] ownerAuth, byte [] resetData) + throws IOException, + TpmModuleException { + /* + * Revoke Revocable Endorsement Key + * NIARL_TPM_Module -mode 7 -owner_auth <40 char hex blob> -reset <> + * return: no return *** + */ + String argument = "-owner_auth " + TpmUtils.byteArrayToHexString(ownerAuth) + + " -reset " + TpmUtils.byteArrayToHexString(resetData); + commandLineResult result = executeVer2Command(7, argument, 0, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.revokeRevocableEndorsementKey returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return; + } + /** + * + * @param keyType + * @param keyAuth + * @param keyIndex + * @return + * @throws IOException + * @throws TpmModuleException + * @throws TpmBytestreamResouceException + * @throws TpmUnsignedConversionException + */ + public static TpmKey createKey(String keyType, byte [] keyAuth, int keyIndex) + throws IOException, + TpmModuleException, + TpmBytestreamResouceException, + TpmUnsignedConversionException { + /* + * Create Key (sign or bind) + * NIARL_TPM_Module -mode 8 -key_type <"sign" | "bind"> -key_auth <40 char hex blob> -key_index + * return: + */ + if (!(keyType.equals("sign") || keyType.equals("bind"))) throw new TpmModuleException("TpmModule.createKey: key type parameter must be \"sign\" or \"bind\"."); + String argument = "-key_type " + keyType + " -key_auth " + TpmUtils.byteArrayToHexString(keyAuth) + " -key_index " + keyIndex; + commandLineResult result = executeVer2Command(8, argument, 2, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.createKey returned nonzero error: " + result.getReturnCode() + "(" + ")"); + byte [] tempArray = TpmUtils.hexStringToByteArray(result.getResult(0)); //modulus - discard in favor of blob + tempArray = TpmUtils.hexStringToByteArray(result.getResult(1)); //modulus - discard in favor of blob + TpmKey toReturn = new TpmKey(tempArray); + return toReturn; + } + /** + * + * @param keyType + * @param keyAuth + * @param keyBlob + * @param keyIndex + * @throws IOException + * @throws TpmModuleException + */ + public static void setKey(String keyType, byte [] keyAuth, byte [] keyBlob, int keyIndex) + throws IOException, + TpmModuleException { + /* + * Set Key (sign, bind, or identity) + * NIARL_TPM_Module -mode 9 -key_type <"sign" | "bind" | "identity"> -key_auth <40 char hex blob> -key_blob -key_index + * return: no return *** + */ + if (!(keyType.equals("sign") || keyType.equals("bind") || keyType.equals("identity"))) throw new TpmModuleException("TpmModule.setKey: key type parameter must be \"sign\", \"bind\", or \"identity\"."); + String argument = "-key_type " + keyType + " -key_auth " + TpmUtils.byteArrayToHexString(keyAuth) + " -key_blob " + TpmUtils.byteArrayToHexString(keyBlob) + " -key_index " + keyIndex; + commandLineResult result = executeVer2Command(9, argument, 0, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.setKey returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return; + } + /** + * + * @param keyType + * @param keyIndex + * @param keyAuth + * @return + * @throws IOException + * @throws TpmModuleException + * @throws TpmBytestreamResouceException + * @throws TpmUnsignedConversionException + */ + public static TpmKey getKey(String keyType, int keyIndex, byte [] keyAuth) + throws IOException, + TpmModuleException, + TpmBytestreamResouceException, + TpmUnsignedConversionException { + /* + * Get Key (sign, bind, or identity) * + * NIARL_TPM_Module -mode 10 -key_type <"sign" | "bind" | "identity"> -key_index -key_auth <40 char hex blob> + * return: + */ + if (!(keyType.equals("sign") || keyType.equals("bind") || keyType.equals("identity"))) throw new TpmModuleException("TpmModule.getKey: key type parameter must be \"sign\", \"bind\", or \"identity\"."); + String argument = "-key_type " + keyType + " -key_index " + keyIndex + " -key_auth " + TpmUtils.byteArrayToHexString(keyAuth); + commandLineResult result = executeVer2Command(10, argument, 2, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.getKey returned nonzero error: " + result.getReturnCode() + "(" + ")"); + byte [] tempArray = TpmUtils.hexStringToByteArray(result.getResult(0)); //modulus - discard in favor of blob + tempArray = TpmUtils.hexStringToByteArray(result.getResult(1)); //modulus - discard in favor of blob + TpmKey toReturn = new TpmKey(tempArray); + return toReturn; + } + /** + * + * @param ownerAuth + * @param nonce + * @return + * @throws IOException + * @throws TpmModuleException + */ + public static byte [] getEndorsementKeyModulus(byte [] ownerAuth, byte [] nonce) + throws IOException, + TpmModuleException { + /* + * Get Key (EK) * + * NIARL_TPM_Module -mode 10 -key_type EK -owner_auth <40 char hex blob> -nonce <40 char hex blob> + * return: + */ + String argument = "-key_type ek -owner_auth " + TpmUtils.byteArrayToHexString(ownerAuth) + " -nonce " + TpmUtils.byteArrayToHexString(nonce); + commandLineResult result = executeVer2Command(10, argument, 1, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.getPublicEndorsementKey returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return TpmUtils.hexStringToByteArray(result.getResult(0)); + } + /** + * + * @param keyType + * @param keyAuth + * @param keyIndex + * @throws IOException + * @throws TpmModuleException + */ + public static void clearKey(String keyType, byte [] keyAuth, int keyIndex) + throws IOException, + TpmModuleException { + /* + * Clear Key (sign, bind, or identity) + * NIARL_TPM_Module -mode 11 -key_type <"sign" | "bind" | "identity"> -key_auth <40 char hex blob> -key_index + * return: no return *** + */ + if (!(keyType.equals("sign") || keyType.equals("bind") || keyType.equals("identity"))) throw new TpmModuleException("TpmModule.clearKey: key type parameter must be \"sign\", \"bind\", or \"identity\"."); + String argument = "-key_type " + keyType + " -key_auth " + TpmUtils.byteArrayToHexString(keyAuth) + " -key_index " + keyIndex; + commandLineResult result = executeVer2Command(11, argument, 0, true); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.clearKey returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return; + } + /** + * + * @param ownerAuth + * @param credType + * @param credBlob + * @throws IOException + * @throws TpmModuleException + */ + public static void setCredential(byte [] ownerAuth, String credType, byte [] credBlob) + throws IOException, + TpmModuleException { + /* + * Set Credential (EC, PC, CC, and PCC) + * NIARL_TPM_Module -mode 12 -owner_auth <40 char hex blob> -cred_type <"EC" | "CC" | "PC" | "PCC"> -blob <>[-trousers] + * return: no return *** + */ + if (!(credType.equals("EC") || credType.equals("CC") || credType.equals("PC")|| credType.equals("PCC"))) throw new TpmModuleException("TpmModule.setCredential: credential type parameter must be \"EC\", \"CC\", \"PC\", or \"PCC\"."); + String argument = "-owner_auth " + TpmUtils.byteArrayToHexString(ownerAuth) + " -cred_type " + credType + " -blob " + TpmUtils.byteArrayToHexString(credBlob); + // TROUSERS MODE OPTIONAL + commandLineResult result = executeVer2Command(12, argument, 0, true); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.setCredential returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return; + } + /** + * + * @param ownerAuth + * @param credType + * @return + * @throws IOException + * @throws TpmModuleException + */ + public static byte [] getCredential(byte [] ownerAuth, String credType) + throws IOException, + TpmModuleException { + /* + * Get Credential (EC, PC, CC, and PCC) + * NIARL_TPM_Module -mode 13 -owner_auth <40 char hex blob> -cred_type <"EC" | "CC" | "PC" | "PCC"> [-trousers] + * return: + */ + if (!(credType.equals("EC") || credType.equals("CC") || credType.equals("PC")|| credType.equals("PCC"))) throw new TpmModuleException("TpmModule.getCredential: credential type parameter must be \"EC\", \"CC\", \"PC\", or \"PCC\"."); + String argument = "-owner_auth " + TpmUtils.byteArrayToHexString(ownerAuth) + " -cred_type " + credType; + // TROUSERS MODE OPTIONAL + commandLineResult result = executeVer2Command(13, argument, 1, true); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.getCredential returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return TpmUtils.hexStringToByteArray(result.getResult(0)); + } + /** + * + * @param ownerAuth + * @param credType + * @throws IOException + * @throws TpmModuleException + */ + public static void clearCredential(byte [] ownerAuth, String credType) + throws IOException, + TpmModuleException { + /* + * Clear Credential (EC, PC, CC, and PCC) + * NIARL_TPM_Module -mode 14 -owner_auth <40 char hex blob> -cred_type <"EC" | "CC" | "PC" | "PCC"> + * return: no return *** + */ + if (!(credType.equals("EC") || credType.equals("CC") || credType.equals("PC")|| credType.equals("PCC"))) throw new TpmModuleException("TpmModule.clearCredential: credential type parameter must be \"EC\", \"CC\", \"PC\", or \"PCC\"."); + String argument = "-owner_auth " + TpmUtils.byteArrayToHexString(ownerAuth) + " -cred_type " + credType; + commandLineResult result = executeVer2Command(14, argument, 0, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.clearCredential returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return; + } + /** + * + * @param blob + * @param blobAuth + * @param mask + * @return + * @throws IOException + * @throws TpmModuleException + */ + public static byte [] seal(byte [] blob, byte [] blobAuth, byte [] mask) + throws IOException, + TpmModuleException { + /* + * Seal + * NIARL_TPM_Module -mode 15 -blob <> -blob_auth <40 char hex blob> -mask <> + * return: + */ + if ((mask.length > 3)||(mask.length == 0)) { + throw new IllegalArgumentException ("TpmModule.seal: Mask must be between 1 and 3 bytes in length."); + } + String argument = "-blob " + TpmUtils.byteArrayToHexString(blob) + " -blob_auth " + TpmUtils.byteArrayToHexString(blobAuth) + " -mask " + TpmUtils.byteArrayToHexString(mask); + commandLineResult result = executeVer2Command(15, argument, 1, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.seal returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return TpmUtils.hexStringToByteArray(result.getResult(0)); + } + /** + * + * @param blob + * @param blobAuth + * @return + * @throws IOException + * @throws TpmModuleException + */ + public static byte [] unseal(byte [] blob, byte [] blobAuth) + throws IOException, + TpmModuleException { + /* + * Unseal + * NIARL_TPM_Module -mode 16 -blob <> -blob_auth <40 char hex blob> + * return: + */ + String argument = "-blob " + TpmUtils.byteArrayToHexString(blob) + " -blob_auth " + TpmUtils.byteArrayToHexString(blobAuth); + commandLineResult result = executeVer2Command(16, argument, 1, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.unseal returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return TpmUtils.hexStringToByteArray(result.getResult(0)); + } + /** + * + * @param blob + * @param blobAuth + * @param keyAuth + * @param keyIndex + * @return + * @throws IOException + * @throws TpmModuleException + */ + public static byte [] bind(byte [] blob, byte [] blobAuth, byte [] keyAuth, int keyIndex) + throws IOException, + TpmModuleException { + /* + * Bind + * NIARL_TPM_Module -mode 17 -blob <> -blob_auth <40 char hex blob> -key_auth <40 char hex blob> -key_index + * return: + */ + String argument = "-blob " + TpmUtils.byteArrayToHexString(blob) + " -blob_auth " + TpmUtils.byteArrayToHexString(blobAuth) + " -key_auth " + TpmUtils.byteArrayToHexString(keyAuth) + " -key_index " + keyIndex; + commandLineResult result = executeVer2Command(17, argument, 1, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.bind returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return TpmUtils.hexStringToByteArray(result.getResult(0)); + } + /** + * + * @param blob + * @param blobAuth + * @param keyAuth + * @param keyIndex + * @return + * @throws IOException + * @throws TpmModuleException + */ + public static byte [] unbind(byte [] blob, byte [] blobAuth, byte [] keyAuth, int keyIndex) + throws IOException, + TpmModuleException { + /* + * Unbind + * NIARL_TPM_Module -mode 18 -blob <> -blob_auth <40 char hex blob> -key_auth <40 char hex blob> -key_index + * return: + */ + String argument = "-blob " + TpmUtils.byteArrayToHexString(blob) + " -blob_auth " + TpmUtils.byteArrayToHexString(blobAuth) + " -key_auth " + TpmUtils.byteArrayToHexString(keyAuth) + " -key_index " + keyIndex; + commandLineResult result = executeVer2Command(18, argument, 1, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.unbind returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return TpmUtils.hexStringToByteArray(result.getResult(0)); + } + /** + * + * @param blob + * @param blobAuth + * @param keyAuth + * @param keyIndex + * @param mask + * @return + * @throws IOException + * @throws TpmModuleException + */ + public static byte [] sealBind(byte [] blob, byte [] blobAuth, byte [] keyAuth, int keyIndex, byte [] mask) + throws IOException, + TpmModuleException { + /* + * Seal Bind + * NIARL_TPM_Module -mode 19 -blob <> -blob_auth <40 char hex blob> -key_auth <40 char hex blob> -key_index -mask <> + * return: + */ + //check the mask + if ((mask.length > 3)||(mask.length == 0)) { + throw new IllegalArgumentException ("TpmModule.sealBind: Mask must be between 1 and 3 bytes in length."); + } + String argument = "-blob " + TpmUtils.byteArrayToHexString(blob) + " -blob_auth " + TpmUtils.byteArrayToHexString(blobAuth) + " -key_auth " + TpmUtils.byteArrayToHexString(keyAuth) + " -key_index " + keyIndex + " -mask " + TpmUtils.byteArrayToHexString(mask); + commandLineResult result = executeVer2Command(19, argument, 1, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.sealBind returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return TpmUtils.hexStringToByteArray(result.getResult(0)); + } + /** + * + * @param blob + * @param blobAuth + * @param keyAuth + * @param keyIndex + * @return + * @throws IOException + * @throws TpmModuleException + */ + public static byte [] unsealUnbind(byte [] blob, byte [] blobAuth, byte [] keyAuth, int keyIndex) + throws IOException, + TpmModuleException { + /* + * Unseal Unbind + * NIARL_TPM_Module -mode 20 -blob <> -blob_auth <40 char hex blob> -key_auth <40 char hex blob> -key_index + * return: + */ + String argument = "-blob " + TpmUtils.byteArrayToHexString(blob) + " -blob_auth " + TpmUtils.byteArrayToHexString(blobAuth) + " -key_auth " + TpmUtils.byteArrayToHexString(keyAuth) + " -key_index " + keyIndex; + commandLineResult result = executeVer2Command(20, argument, 1, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.unsealUnbind returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return TpmUtils.hexStringToByteArray(result.getResult(0)); + } + /** + * + * @param numBytes + * @return + * @throws IOException + * @throws TpmModuleException + */ + public static byte [] getRandomInteger(int numBytes) + throws IOException, + TpmModuleException { + /* + * Get Random Integer + * NIARL_TPM_Module -mode 21 -bytes + * return: + */ + if (numBytes < 0) { + throw new IllegalArgumentException ("TpmModule.getRandomInteger: number of bytes requested must be a positive number."); + } + String argument = "-bytes " + numBytes; + commandLineResult result = executeVer2Command(21, argument, 1, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.getRandomInteger returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return TpmUtils.hexStringToByteArray(result.getResult(0)); + } + /** + * + * @param blob + * @param keyAuth + * @param keyIndex + * @return + * @throws IOException + * @throws TpmModuleException + */ + public static byte [] sign(byte [] blob, byte [] keyAuth, int keyIndex) + throws IOException, + TpmModuleException { + /* + * Sign + * NIARL_TPM_Module -mode 22 -blob <> -key_auth <40 char hex blob> -key_index + * return: + */ + String argument = "-blob " + TpmUtils.byteArrayToHexString(blob) + " -key_auth " + TpmUtils.byteArrayToHexString(keyAuth) + " -key_index " + keyIndex; + commandLineResult result = executeVer2Command(22, argument, 1, false); + if (result.getReturnCode() != 0) throw new TpmModuleException("TpmModule.sign returned nonzero error: " + result.getReturnCode() + "(" + ")"); + return TpmUtils.hexStringToByteArray(result.getResult(0)); + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmPubKey.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmPubKey.java new file mode 100644 index 0000000..505cfcb --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmPubKey.java @@ -0,0 +1,137 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.io.*; +import java.security.*; +import java.security.spec.*; +import java.security.interfaces.*; +import java.math.*; + +/** + *

    This class is for the TCG's TPM_PUBKEY structure.

    + * @author schawki + * + */ +public class TpmPubKey { + private TpmKeyParams algorithm; + private byte [] key; //just the modulus!! + + public TpmPubKey() {} + /** + * Create new TPM_PUBKEY by specifying the public key, encryption scheme and signature scheme. + * + * @param pubKey The RSA public key structure, containing the modulus and public exponent. + * @param encScheme The defined encryption scheme value. + * @param sigscheme The defined signature scheme value. + */ + public TpmPubKey(RSAPublicKey pubKey, int encScheme, int sigscheme) { + BigInteger keyBI = pubKey.getModulus(); + key = keyBI.toByteArray(); + if ((key.length == 257)&&(key[0]==0x00)) { + byte [] newKey = new byte[256]; + for (int i = 0; i < 256; i++) + newKey[i] = key[i+1]; + key = newKey; + } + algorithm = new TpmKeyParams(); + algorithm.setAlgorithmId(1); + algorithm.setEncScheme((short)encScheme); + algorithm.setSigScheme((short)sigscheme); + algorithm.setSubParams(new TpmRsaKeyParams()); + algorithm.getSubParams().setByteData(pubKey.getPublicExponent().toByteArray()); + algorithm.getSubParams().setValueData(2); //numPrimes + algorithm.getSubParams().setKeyLength(2048); + } + /** + * Create a TPM_PUBKEY using the specified modulus. An default encryption scheme of 1 (TPM_ES_NONE) and signature scheme + * of 2 (TPM_SS_RSASSAPKCS1v15_SHA1) will be used. + * + * @param newKey The new modulus in the form of a byte array. + */ + public TpmPubKey(byte [] newKey) { + key = newKey; + algorithm = new TpmKeyParams(); + algorithm.setAlgorithmId(1); + algorithm.setEncScheme((short)1); + algorithm.setSigScheme((short)2); + algorithm.setSubParams(new TpmRsaKeyParams()); + byte [] pubExp = {0x01, 0x00, 0x01}; + algorithm.getSubParams().setByteData(pubExp); + algorithm.getSubParams().setValueData(2); //numPrimes + algorithm.getSubParams().setKeyLength(2048); + } + /** + * Create a new TPM_PUBKEY by extracting it from a byte stream. + * + * @param source The ByteArrayInputStream from which to extract the TPM_PUBKEY. + * @throws TpmUtils.TpmUnsignedConversionException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public TpmPubKey(ByteArrayInputStream source) throws TpmUtils.TpmUnsignedConversionException, TpmUtils.TpmBytestreamResouceException { + algorithm = new TpmKeyParams(source); + int storeKeyLength = TpmUtils.getUINT32(source); + key = TpmUtils.getBytes(source, storeKeyLength); + } + /** + * Get the RSA key modulus. + * + * @return The modulus as a byte array. + */ + public byte [] getKeybytes() { + return key; + } + /** + * Return an RSAPublicKey structure representing the key stored in this TPM_PUBKEY. + * + * @return The RSAPublicKey. + * @throws NoSuchAlgorithmException + * @throws InvalidKeySpecException + */ + public RSAPublicKey getKey() throws NoSuchAlgorithmException, InvalidKeySpecException { + byte [] pubExp = new byte[3]; + pubExp[0] = (byte)(0x01 & 0xff); +// pubExp[1] = (byte)(0x00 & 0xff); + pubExp[1] = (byte)(0x00); + pubExp[2] = (byte)(0x01 & 0xff); + return TpmUtils.makePubKey(key, pubExp); + } + /** + * Return a human-readable report of the TPM_PUBKEY. + * + * @return The key report. + */ + public String toString() { + String returnVal = ""; + returnVal += "TpmPubKey:\n"; + returnVal += " " + algorithm.toString() + "\n"; + returnVal += " key:\n" + TpmUtils.byteArrayToString(key, 16); + return returnVal; + } + /** + * + * @return The serialized TPM_PUBKEY. + * @throws TpmUtils.TpmUnsignedConversionException + */ + public byte [] toByteArray() throws TpmUtils.TpmUnsignedConversionException { + byte[] algo = algorithm.toByteArray(); + byte[] keySize = TpmUtils.intToByteArray(key.length); + int x = algo.length + keySize.length + key.length; + byte [] returnArray = new byte[x]; + System.arraycopy(algo, 0, returnArray, 0, algo.length); + System.arraycopy(keySize, 0, returnArray, algo.length, keySize.length); + System.arraycopy(key, 0, returnArray, algo.length + keySize.length, key.length); + return returnArray; + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmRsaKeyParams.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmRsaKeyParams.java new file mode 100644 index 0000000..954d451 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmRsaKeyParams.java @@ -0,0 +1,139 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.io.ByteArrayInputStream; + +/** + *

    This class is for the TCG's TPM_RSA_KEY_PARMS structure. It extends the TpmKeySubParams interface.

    + * @author schawki + * + */ +public class TpmRsaKeyParams implements TpmKeySubParams{ + public int keyLength; + public int numPrimes; //number of primes + public byte[] exponent; //exponent + + public TpmRsaKeyParams() {} + /** + * Create a new RSAKeyParams by extracting it from a byte stream. + * + * @param source The byte stream from which to extract. + * @param length The length of the RSA key params (just used to see if over 0). + * @throws TpmUtils.TpmUnsignedConversionException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public TpmRsaKeyParams(ByteArrayInputStream source, int length) throws TpmUtils.TpmUnsignedConversionException, TpmUtils.TpmBytestreamResouceException { + if (length > 0) { + keyLength = TpmUtils.getUINT32(source); + numPrimes = TpmUtils.getUINT32(source); + int temp = TpmUtils.getUINT32(source); + exponent = TpmUtils.getBytes(source, temp); + } + } + /** + * Serialize the structure. + * + * @return The serialized RSA key params structure. + * @throws TpmUtils.TpmUnsignedConversionException + */ + public byte[] toByteArray() + throws TpmUtils.TpmUnsignedConversionException { + byte [] keyLngth = TpmUtils.intToByteArray(keyLength); + byte [] numPrms = TpmUtils.intToByteArray(numPrimes); + byte [] size; + byte [] exponentOut; + if (defaultExponent()) { + size = TpmUtils.intToByteArray(0); + exponentOut = null; + } else { + size = TpmUtils.intToByteArray(exponent.length); + exponentOut = exponent; + } + int x = keyLngth.length + numPrms.length + size.length; + if (exponentOut != null) x += exponentOut.length; + byte [] returnArray = new byte[x]; + System.arraycopy(keyLngth, 0, returnArray, 0, keyLngth.length); + System.arraycopy(numPrms, 0, returnArray, keyLngth.length, numPrms.length); + System.arraycopy(size, 0, returnArray, keyLngth.length + numPrms.length, size.length); + if (exponentOut != null) System.arraycopy(exponentOut, 0, returnArray, keyLngth.length + numPrms.length + size.length, exponentOut.length); + return returnArray; + } + /** + * Determine if the TCG-defined "default" public exponent is used for this key. + * + * @return True if the exponent defined is 2^16 + 1 (65537 or 0x01 0x00 0x01). + */ + private boolean defaultExponent() { + if (exponent == null) return true; + byte [] defaultExp = {0x01, 0x00, 0x01}; + for (int i = 0; i < exponent.length; i++) + if (exponent[i] != defaultExp[i]) + return false; + return true; + } + /** + * @return The length of the RSA key. + */ + public int getKeyLength() { + return keyLength; + } + /** + * Set the RSA key length. + * + * @param newValue The new key length, in bits. + */ + public void setKeyLength(int newValue) { + keyLength = newValue; + } + /** + * @return The number of primes. + */ + public int getValueData() { + return numPrimes; + } + /** + * Set the number of primes for this RSA key params structure. + * + * @param newValue The new number of primes. + */ + public void setValueData(int newValue) { + numPrimes = newValue; + } + /** + * @return The exponent for this RSA key. + */ + public byte [] getByteData() { + return exponent; + } + /** + * @param newValue Set the RSA exponent to this byte array. + */ + public void setByteData(byte [] newValue) { + exponent = newValue; + } + /** + * Creates a human-readable report of the RSA key parameters structure. + * + * @return The report. + */ + public String toString() { + String returnVal = ""; + returnVal += "TpmRsaKeyParams:\n"; + returnVal += " keyLength: " + Integer.toString(keyLength) + "\n"; + returnVal += " numPrimes: " + Integer.toString(numPrimes) + "\n"; + returnVal += " exponent: " + TpmUtils.byteArrayToString(exponent, 16); + return returnVal; + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmSymCaAttestation.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmSymCaAttestation.java new file mode 100644 index 0000000..063be12 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmSymCaAttestation.java @@ -0,0 +1,152 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.io.ByteArrayInputStream; +import java.security.cert.*; +//import java.util.*; +import java.io.*; +import java.security.*; +import javax.crypto.*; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +/** + *

    This class is for the TCG's TPM_SYM_CA_ATTESTATION structure.

    + * @author schawki + * + */ +public class TpmSymCaAttestation { + private TpmKeyParams algorithm; + private byte [] plainAikCred = null; + private byte [] encAikCred; + + public TpmSymCaAttestation(){} + /** + * Set the AIK certificate to be encrypted. + * + * @param cred The AIK certificate in byte array form. + */ + public void setAikCredential(byte [] cred) { + plainAikCred = cred; + } + /** + * Set the AIK certificate to be encrypted. + * + * @param cred The AIK certificate in X509Certificate form. + * @throws CertificateEncodingException + */ + public void setAikCredential(X509Certificate cred) throws CertificateEncodingException { + plainAikCred = cred.getEncoded(); + } + /** + * @return The stored AIK certificate in X509Certificate form. + * @throws CertificateException + */ + public X509Certificate getAikCredential() + throws CertificateException { + ByteArrayInputStream bs = new ByteArrayInputStream(plainAikCred); + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + return (X509Certificate)cf.generateCertificate(bs); + } + /** + * Encrypt the stored certificate using the specified options. A random key and IV are created. + * + * @param algMode Not used. This parameter is left here to maintain compatibility. This value is hard coded to TPM_ALG_AES. + * @param encScheme Not used. This parameter is left here to maintain compatibility. This value is hard coded to TPM_ES_CBC_PKCS5PAD. + * @param TrousersModeIV Set to TRUE to use a TrouSerS-style initialization vector placement. + * @param TrousersModeSymkeyEncscheme Set to TRUE to set the encryption scheme to TPM_ES_NONE. (Not all versions of TrouSerS use this scheme, but the only ones available in RedHat Yum repositories do.) + * @return The symmetric key used to encrypt the certificate in the form of a TpmSymmetricKey. The encrypted certificate itself is retrieved in raw byte format by running the toByteArray() function. + * @throws IOException + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidAlgorithmParameterException + * @throws InvalidKeyException + * @throws IllegalBlockSizeException + * @throws BadPaddingException + * @throws PrivacyCaException + */ + public TpmSymmetricKey encrypt(int algMode, short encScheme, boolean TrousersModeIV, boolean TrousersModeSymkeyEncscheme) + throws IOException, + NoSuchAlgorithmException, + NoSuchPaddingException, + InvalidAlgorithmParameterException, + InvalidKeyException, + IllegalBlockSizeException, + BadPaddingException, + PrivacyCaException { + if (plainAikCred == null) { + throw new PrivacyCaException("TpmSymCaAttestation: Must store certificate prior to encrypting."); + } + algorithm = new TpmKeyParams(); + algorithm.setAlgorithmId(TpmKeyParams.TPM_ALG_AES); + algorithm.setEncScheme(TpmKeyParams.TPM_ES_SYM_CBC_PKCS5PAD); + algorithm.setSigScheme(TpmKeyParams.TPM_SS_NONE); + algorithm.setSubParams(new TpmSymmetricKeyParams()); + algorithm.getSubParams().setKeyLength(128); + algorithm.getSubParams().setValueData(16); + //create a random IV (16 byte) + byte [] newIv = TpmUtils.createRandomBytes(16); + algorithm.getSubParams().setByteData(newIv); //copy IV into params + algorithm.setTrouSerSmode(TrousersModeIV); //set trousers mode + //create a random key for AES (128 bit = 16 byte) + byte [] newKey = TpmUtils.createRandomBytes(16); + //System.out.println("The symmetric key is " + newKey.length + " bytes long"); + //encrypt + Cipher symCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + IvParameterSpec ivSpec = new IvParameterSpec(newIv); + SecretKeySpec symKey = new SecretKeySpec(newKey, "AES"); + symCipher.init(Cipher.ENCRYPT_MODE, symKey, ivSpec); + encAikCred = symCipher.doFinal(plainAikCred); + if (TrousersModeIV) { //copy iv to from of encrypted portion + byte [] temp = new byte[newIv.length + encAikCred.length]; + System.arraycopy(newIv, 0, temp, 0, newIv.length); + System.arraycopy(encAikCred, 0, temp, newIv.length, encAikCred.length); + encAikCred = temp; + } + else { + algorithm.setSubParams(new TpmSymmetricKeyParams()); + algorithm.getSubParams().setByteData(newIv); + algorithm.getSubParams().setValueData(16); + algorithm.getSubParams().setKeyLength(128); + } + //set the Symkey for return + TpmSymmetricKey encryptKey = new TpmSymmetricKey(); + encryptKey.setAlgorithmId(TpmKeyParams.TPM_ALG_AES); + encryptKey.setEncScheme(TpmKeyParams.TPM_ES_SYM_CBC_PKCS5PAD); + encryptKey.setSecretKey(symKey); + if (TrousersModeSymkeyEncscheme) + encryptKey.setEncScheme(TpmKeyParams.TPM_ES_NONE); + return encryptKey; + } + /** + * Serialize the structure. + * + * @return A byte array form of the TpmSymCaAttestation structure. + * @throws TpmUtils.TpmUnsignedConversionException + */ + public byte [] toByteArray() + throws TpmUtils.TpmUnsignedConversionException { + byte [] credSize = TpmUtils.intToByteArray(encAikCred.length); //credSize.length must be 4! + byte [] tempAlgo = algorithm.toByteArray(); + int x = credSize.length + tempAlgo.length + encAikCred.length; + byte [] returnArray = new byte[x]; + System.arraycopy(credSize, 0, returnArray, 0, credSize.length); + System.arraycopy(tempAlgo, 0, returnArray, credSize.length, tempAlgo.length); + System.arraycopy(encAikCred, 0, returnArray, credSize.length + tempAlgo.length, encAikCred.length); + return returnArray; + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmSymmetricKey.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmSymmetricKey.java new file mode 100644 index 0000000..7c23bf0 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmSymmetricKey.java @@ -0,0 +1,171 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import javax.crypto.spec.*; +import java.io.*; + +/** + *

    This class is for the TCG's TPM_SYMMETRIC_KEY structure.

    + * @author schawki + * + */ +public class TpmSymmetricKey { + private byte[] keyBlob; + private int algorithmId; + private short encScheme; + + public TpmSymmetricKey() { + keyBlob = TpmUtils.hexStringToByteArray(""); + } + /** + * Instantiate a new TpmSymmetricKey from a byte array. + * + * @param blob The key bytes to use. + * @throws TpmUtils.TpmUnsignedConversionException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public TpmSymmetricKey(byte [] blob) + throws TpmUtils.TpmUnsignedConversionException, + TpmUtils.TpmBytestreamResouceException { + ByteArrayInputStream bs = new ByteArrayInputStream(blob); + algorithmId = TpmUtils.getUINT32(bs); + encScheme = TpmUtils.getUINT16(bs); + short temp = TpmUtils.getUINT16(bs); + keyBlob = TpmUtils.getBytes(bs, (int)temp); + } + /** + * + * @return The secret key in the form of a SecretKeySpec. + */ + public SecretKeySpec getSecretKey() { + String algorithm = this.getAlgorithmStr(); + SecretKeySpec symKey = new SecretKeySpec(keyBlob, algorithm); + return symKey; + } + /** + * Set the secret key with a SecretKeySpec. + * + * @param newKeySpec New secret key. + */ + public void setSecretKey(SecretKeySpec newKeySpec) { + keyBlob = newKeySpec.getEncoded(); + } + /** + * + * @return The algorithm ID defined for this symmetric key. + */ + public int getAlgorithmId() { + return algorithmId; + } + /** + * Set the algorithm ID for this symmetric key. + * + * @param newAlgId New algorithm ID. + */ + public void setAlgorithmId(int newAlgId) { + algorithmId = newAlgId; + } + /** + * + * @return Human-readable report of the TpmSymmetricKey. + */ + public String getAlgorithmStr(){ + String returnVal = ""; + switch (algorithmId){ + case TpmKeyParams.TPM_ALG_DES: + returnVal = "DES"; + break; + case TpmKeyParams.TPM_ALG_3DES: + returnVal = "DESede"; + break; + case TpmKeyParams.TPM_ALG_AES: + case TpmKeyParams.TPM_ALG_AES192: + case TpmKeyParams.TPM_ALG_AES256: + returnVal = "AES"; + break; + default: + returnVal = "Error"; + break; + } + return returnVal; + } + /** + * + * @return The set encryption scheme. + */ + public short getEncScheme() { + return encScheme; + } + /** + * Set the encryption scheme. + * + * @param newEncScheme New encryption scheme. + */ + public void setEncScheme(short newEncScheme) { + encScheme = newEncScheme; + } + /** + * + * @return The encryption scheme as a string. + */ + public String getEncSchemeStr(){ + String returnVal = ""; + switch (encScheme){ + case TpmKeyParams.TPM_ES_NONE: + returnVal = "NONE/NoPadding"; + break; + case TpmKeyParams.TPM_ES_SYM_CBC_PKCS5PAD: + returnVal = "CBC/PKCS5Padding"; + break; + default: + returnVal = "Error"; + break; + } + return returnVal; + } + /** + * + * @return Symmetric key blob, as a byte array. + */ + public byte [] getKeyBlob() { + return keyBlob; + } + /** + * Set a new key symmetric key by byte blob. + * + * @param newKeyBlob New key. + */ + public void setKeyBlob(byte [] newKeyBlob) { + keyBlob = newKeyBlob; + } + /** + * Serialize the TpmSymmetricKey structure. + * + * @return Byte array form of TpmSymmetricKey. + * @throws TpmUtils.TpmUnsignedConversionException + */ + public byte [] toByteArray() throws TpmUtils.TpmUnsignedConversionException { + byte[] algoId = TpmUtils.intToByteArray(algorithmId); + byte[] encSchm = TpmUtils.shortToByteArray(encScheme); + byte[] size = TpmUtils.shortToByteArray((short)keyBlob.length); + int x = algoId.length + encSchm.length + size.length + keyBlob.length; //calculate # of bytes in structure + byte [] returnArray = new byte[x]; + System.arraycopy(algoId, 0, returnArray, 0, algoId.length); + System.arraycopy(encSchm, 0, returnArray, algoId.length, encSchm.length); + System.arraycopy(size, 0, returnArray, algoId.length + encSchm.length, size.length); + System.arraycopy(keyBlob, 0, returnArray, algoId.length + encSchm.length + size.length, keyBlob.length); + return returnArray; + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmSymmetricKeyParams.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmSymmetricKeyParams.java new file mode 100644 index 0000000..9a7a59d --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmSymmetricKeyParams.java @@ -0,0 +1,122 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.io.ByteArrayInputStream; + +/** + *

    This class is for the TCG's TPM_SYMMETRIC_KEY_PARMS structure.

    + * @author schawki + * + */ +public class TpmSymmetricKeyParams implements TpmKeySubParams{ + private int keyLength = 0; + private int blockSize = 0; + private byte[] iv; + + public TpmSymmetricKeyParams() {} + /** + * Create a new TpmSymmetricKeyParams by extracting from a byte stream. + * + * @param source The ByteArrayInputStream from which to extract the TpmSymmetricKey. + * @param length The number of bytes to extract + * @throws TpmUtils.TpmUnsignedConversionException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public TpmSymmetricKeyParams(ByteArrayInputStream source, int length) + throws TpmUtils.TpmUnsignedConversionException, + TpmUtils.TpmBytestreamResouceException { + if (length > 0) { + keyLength = TpmUtils.getUINT32(source); + blockSize = TpmUtils.getUINT32(source); + int temp = TpmUtils.getUINT32(source); + iv = TpmUtils.getBytes(source, temp); + } + } + /** + * @return Key length in bytes. + */ + public int getKeyLength() { + return keyLength; + } + /** + * Set a new key length. + * + * @param newValue New key length in bytes. + */ + public void setKeyLength(int newValue) { + keyLength = newValue; + } + /** + * @return Encryption block size in bytes. + */ + public int getValueData() { + return blockSize; + } + /** + * Set encryption block size. + * + * @param newValue New block size in bytes. + */ + public void setValueData(int newValue) { + blockSize = newValue; + } + /** + * @return Initialization vector. + */ + public byte [] getByteData() { + return iv; + } + /** + * Set initialization vector. + * + * @param newValue New initialization vector. + */ + public void setByteData(byte [] newValue) { + iv = newValue; + } + /** + * @return Human readable report of TpmSymmetricKeyParams. + */ + public String toString() { + String returnVal = ""; + returnVal += "TpmSymmetricKeyParams:\n"; + returnVal += " keyLength: " + Integer.toString(keyLength) + "\n"; + returnVal += " blockSize: " + Integer.toString(blockSize) + "\n"; + returnVal += " iv: " + TpmUtils.byteArrayToString(iv, 16); + return returnVal; + } + /** + * @return Serialized byte array form of TpmSymmetricKeyParams. + * @throws TpmUtils.TpmUnsignedConversionException + */ + public byte [] toByteArray() + throws TpmUtils.TpmUnsignedConversionException { + byte [] keyLngth = TpmUtils.intToByteArray(keyLength); + byte [] blkSize = TpmUtils.intToByteArray(blockSize); + int ivLength = 0; + if (iv != null) + ivLength = iv.length; + byte [] size = TpmUtils.intToByteArray(ivLength); + int x = keyLngth.length + blkSize.length + size.length + ivLength; + byte [] returnArray = new byte[x]; + + System.arraycopy(keyLngth, 0, returnArray, 0, keyLngth.length); + System.arraycopy(blkSize, 0, returnArray, keyLngth.length, blkSize.length); + System.arraycopy(size, 0, returnArray, keyLngth.length + blkSize.length, size.length); + if (iv != null) + System.arraycopy(iv, 0, returnArray, keyLngth.length + blkSize.length + size.length, iv.length); + return returnArray; + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmUtils.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmUtils.java new file mode 100644 index 0000000..ee32a94 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/TpmUtils.java @@ -0,0 +1,1107 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +import java.io.*; +import java.math.*; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.text.SimpleDateFormat; +import java.util.*; +import java.security.*; +import java.security.cert.*; +import java.security.cert.Certificate; +import java.security.spec.*; +import java.security.interfaces.*; +import java.security.interfaces.RSAPublicKey; + +import javax.security.auth.x500.X500Principal; +import javax.security.cert.CertificateException; +import org.bouncycastle.util.encoders.Base64; +import org.bouncycastle.x509.*; +import org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure; +import org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure; +import org.bouncycastle.asn1.x509.*; +import org.bouncycastle.jce.provider.*; + +import javax.crypto.*; +import javax.crypto.spec.*; + +//import java.security.interfaces.RSAPublicKey; + +/** + *

    The utils class contains functions that fall into two categories: those that provide + * utility to other classes in this package; and those that perform some cross-class + * functionality that is specific to this package.

    + *

    This package was created for performing as a Privacy Certification Authority (Privacy CA), + * as specified by the Trusted Computing Group. The function ProcessIdentityRequest encompasses + * the role of a Privacy CA by taking an identity request, processing it with a CA signing key, + * and producing the specified data blobs containing a certificate.

    + *

    The function makeEkCert works similarly to create a certificate for a TPM's Endorsement + * Key (EK certificate). This is not a defined role of a Privacy CA, however the process of + * creating an EK certificate is not covered in any TCG documentation, and the process of + * creating such a certificate is very similar to that used for processing an identity request.

    + *

    The creation of an identity request is generally performed by the TSS function + * Tspi_TPM_CollateIdentityRequest. There are times, however, when it may be necessary to + * fabricate an identity request from its basic components. The function createIdentityRequest + * can be used to do just that. It is flexible enough to create a request in the format of any + * of the popular flavors of TSS.

    + * + *

    Some of the functions provided in this class require the BouncyCastle security provider library, version 141 (for Java 1.5, this is the library named bcprov-jdk15-141.jar).

    + * + * @author schawki + * + */ +public class TpmUtils { + /** + * Converts an integer to a four-byte array. + * + * @param integer The integer to convert. + * @return A byte array with a length of 4 representing the integer as a UINT32. + * @throws TpmUnsignedConversionException This function does not work if the integer to convert is a negative number. + */ + public static byte[] intToByteArray (final int integer) + throws TpmUnsignedConversionException { + if (integer < 0) throw new TpmUnsignedConversionException("Cannot convert negative integer to UINT32 array: " + integer); + byte [] toReturn = new byte[4]; + toReturn[3] = (byte)((integer >> 0)&0x000000ff); + toReturn[2] = (byte)((integer >> 8)&0x000000ff); + toReturn[1] = (byte)((integer >>16)&0x000000ff); + toReturn[0] = (byte)((integer >>24)&0x000000ff); + return toReturn; + } + /** + * Converts a short integer to a two-byte array. + * + * @param shortInt The short integer to convert. + * @return A byte array with a length of 2 representing the integer as a UINT16. + * @throws TpmUnsignedConversionException This function does not work if the integer to convert is a negative number. + */ + public static byte[] shortToByteArray (final short shortInt) + throws TpmUnsignedConversionException { + if (shortInt < 0) throw new TpmUnsignedConversionException("Cannot convert negative short to UINT16 array: " + shortInt); + byte [] toReturn = new byte[2]; + toReturn[1] = (byte)(shortInt&0x000000ff); + toReturn[0] = (byte)((shortInt >> 8)&0x000000ff); + return toReturn; + } + /** + * Extracts four bytes in the form of a UINT32 from a ByteArrayInputStream and converts it to an integer. The byte stream will be reduced + * by four bytes. Note: the Java integer is signed, but the UINT32 is not (by definition). The integer was chosen to hold the value of a UINT32 + * because both are four bytes in size, even though the Java integer has a positive max value half that of the UINT32. As this conversion + * function converts from a UINT32, there sill never be a negative value extracted. The possibility exists that a UINT32 with a value greater + * than the integer MAX_VALUE will attempt to be extracted using this function. In that case, an exception will be thrown. This situation + * is not likely to occur, as UINT32 values are used for two purposes by the TCG: defined attributes/flags, and size values. When a UINT32 is + * used as an attribute or flag, the value is not as important as is the bit order. (Also, there are no attributes of flags in which the most + * significant bit is set.) As a size, the value is usually in numbers of bytes, and occasionally in number of bits. In either case, there is + * not likely to be a size, even in bits, that comes near to approaching the max value of integer. + * + * @param source The ByteArrayInputStream from which the UINT32 is to be extracted. + * @return An integer with the value of the UINT32. + * @throws TpmUnsignedConversionException The UINT32 being extracted is too large to be stored in an integer. + * @throws TpmBytestreamResouceException A UINT32 is four bytes in length, this exception is throws in there are not at least 4 bytes available to extract. + */ + public static int getUINT32(ByteArrayInputStream source) + throws TpmUnsignedConversionException, + TpmBytestreamResouceException { + if (source.available() < 4) { + throw new TpmBytestreamResouceException("There is not enough room in the bytestream to extract a UINT32."); + } + int retval = 0; + byte[] temp = new byte[4]; + int k =source.read(temp, 0, 4); + if ((temp[0]&0x80) == 0x80) throw new TpmUnsignedConversionException("Cannot convert UINT32 to signed Integer: too large - would be converted to negative."); + retval = (int)((temp[0]<<24&0xff000000) + + (int) (temp[1]<<16&0x00ff0000) + + (int) (temp[2]<< 8&0x0000ff00) + + (int) (temp[3]<< 0&0x000000ff)); + return retval; + } + /** + * Extracts a UINT16 from a bytestream and stores is as a short. See getUINT32 for issues that apply to this function. + * + * @param source The ByteArrayInputStream from which the UINT16 will be extracted. + * @return A short with the value of the UINT16 extracted. + * @throws TpmUnsignedConversionException Thrown if the UINT16 is too large to be stored as a short. + * @throws TpmBytestreamResouceException Thrown if there are not at least two bytes available in the bytestream to extract. + */ + public static short getUINT16(ByteArrayInputStream source) + throws TpmUnsignedConversionException, + TpmBytestreamResouceException { + if (source.available() < 2) { + throw new TpmBytestreamResouceException("There is not enough room in the bytestream to extract a UINT32."); + } + int retval = 0; + byte[] temp = new byte[2]; + int k = source.read(temp, 0, 2); + if ((temp[0]&0x80) == 0x80) throw new TpmUnsignedConversionException("Cannot convert UINT16 to signed Short: too large - would be converted to negative."); + retval = (int)((temp[0]<<8)&0x0000ff00) + + (int)((temp[1]<<0)&0x000000ff); + return (short)retval; + } + /** + * This exception is thrown to indicate an error in converting between a signed and an unsigned + * number of equal bit-lengths. This can be a result of attempting to convert an unsigned number + * of capacity greater than that of an equal-length signed number, or attempting to convert a + * negative signed number to an unsigned number. + * + * @author schawki + * + */ + public static class TpmUnsignedConversionException extends Exception { + private static final long serialVersionUID = 0; + public TpmUnsignedConversionException(String msg) { + super(msg); + } + } + /** + * This error is thrown when attempting to read more bytes from a bytestream or array than are + * available to read. For example, attempting to pull a four-byte UINT32 from a stream containing + * only three bytes. + * + * @author schawki + * + */ + public static class TpmBytestreamResouceException extends Exception { + private static final long serialVersionUID = 0; + public TpmBytestreamResouceException(String msg) { + super(msg); + } + } + /** + * Extracts a specified number of bytes from a ByteArrayInputStream and places them into a byte array. + * + * @param source The ByteArrayInputStream from which to extract the requested number of bytes. + * @param size The number of bytes to extract. + * @return A byte array of size size. + * @throws TpmBytestreamResouceException Thrown if the number of bytes requested exceeds the number of available bytes in the bytestream. + */ + public static byte[] getBytes(ByteArrayInputStream source, int size) + throws TpmBytestreamResouceException { + if (source.available() < size) { + throw new TpmBytestreamResouceException("There are not enough available bytes in the bytestream to extract the requested number."); + } + byte[] retval = new byte[size]; + int k = source.read(retval, 0, size); + return retval; + } + /** + * Creates a new X509 V3 certificate for use as an Attestation Identity Key (AIK) using the BouncyCastle provider. The certificate is designed in the + * direction of the Trusted Computing Group's specification of certificates for the Trusted Platform Module, although in its current form this + * function does not meet the standard. To that extent, the Subject Name field is left blank, and the V3 Subject Alternative Name field is marked + * critical and populated with the ID Label specified in the supplied TPM_Identity_Proof structure. + * + * @param idProof The TPM_Identity_Proof structure, used for the identity label field. + * @param privKey The Privacy CA's private key for signing the certificate. + * @param caCert The Privacy CA's public key certificate. + * @param validityDays The number of days until the created certificate expires, from the time this function is run. + * @param level Currently not used. + * @return An AIK certificate. + * @throws InvalidKeySpecException Passed on from the BouncyCastle certificate generator. + * @throws NoSuchAlgorithmException Passed on from the BouncyCastle certificate generator. + * @throws CertificateEncodingException Passed on from the BouncyCastle certificate generator. + * @throws NoSuchProviderException Thrown if the BouncyCastle provider cannot be found. + * @throws SignatureException Passed on from the BouncyCastle certificate generator. + * @throws InvalidKeyException Passed on from the BouncyCastle certificate generator. + */ + public static X509Certificate makeCert(TpmIdentityProof idProof, RSAPrivateKey privKey, X509Certificate caCert, int validityDays, int level) + throws InvalidKeySpecException, + NoSuchAlgorithmException, + CertificateEncodingException, + NoSuchProviderException, + SignatureException, + InvalidKeyException { + Security.addProvider(new BouncyCastleProvider()); + X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); + certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); + certGen.setIssuerDN(caCert.getSubjectX500Principal()); + certGen.setNotBefore(new java.sql.Time(System.currentTimeMillis())); + Calendar expiry = Calendar.getInstance(); + expiry.add(Calendar.DAY_OF_YEAR, validityDays); + certGen.setNotAfter(expiry.getTime()); + certGen.setSubjectDN(new X500Principal("")); + certGen.setPublicKey(idProof.getAik().getKey()); + certGen.setSignatureAlgorithm("SHA1withRSA"); + certGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.SubjectAlternativeName, true, new GeneralNames(new GeneralName(GeneralName.rfc822Name, new String(idProof.getIdLableBytes())))); + X509Certificate cert = certGen.generate(privKey, "BC"); + return cert; + } + /** + * Pulls the system time in "MMM d, yyyy h:mm:ss a" format as a string, suitable for use in a log file. + * @return String as described above. + */ + public static String getTime() { + Calendar time = Calendar.getInstance(); + SimpleDateFormat formatter = new SimpleDateFormat("MMM d, yyyy h:mm:ss a"); + String newString = formatter.format(time.getTime()); + return newString; + } + /** + * Creates a key pair and associated certificate for a certificate authority. An RSA key pair + * of specified size is stored with the self-signed certificate in an encrypted PKCS 12 key + * store file. The format of the certificate and PKCS 12 file are a replica of what is created + * by OpenSSL. + * + * @param keySize The size (in bits) of the RSA key to create + * @param caName The subject name for the new Certificate Authority (do not include "CN=") + * @param newP12Pass The password for encrypting the PKCS 12 file + * @param p12FileName The name for the PKCS 12 key store file (should end with .p12) + * @param validityDays The number of days the certificate should be valid before expiring + * @throws NoSuchAlgorithmException + * @throws InvalidKeyException + * @throws IllegalStateException + * @throws SignatureException + * @throws KeyStoreException + * @throws java.security.cert.CertificateException + * @throws IOException + */ + public static void createCaP12(int keySize, String caName, String newP12Pass, String p12FileName, int validityDays) + throws NoSuchAlgorithmException, + InvalidKeyException, + IllegalStateException, + SignatureException, + KeyStoreException, + java.security.cert.CertificateException, + IOException{ + Security.addProvider(new BouncyCastleProvider()); + KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); + keyGen.initialize(keySize); + KeyPair keyPair = keyGen.generateKeyPair(); + RSAPrivateKey privKey = (RSAPrivateKey)keyPair.getPrivate(); + RSAPublicKey pubKey = (RSAPublicKey)keyPair.getPublic(); + X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); + certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); + certGen.setIssuerDN(new X500Principal("CN=" + caName)); + certGen.setNotBefore(new java.sql.Time(System.currentTimeMillis())); + Calendar expiry = Calendar.getInstance(); + expiry.add(Calendar.DAY_OF_YEAR, validityDays); + certGen.setNotAfter(expiry.getTime()); + certGen.setSubjectDN(new X500Principal("CN=" + caName)); + certGen.setPublicKey(pubKey); + certGen.setSignatureAlgorithm("SHA1withRSA"); + certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); + certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true)); + X509Certificate caCert = certGen.generate(privKey); + certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); + caCert = certGen.generate(privKey); + FileOutputStream newp12 = new FileOutputStream(p12FileName); + + try { + KeyStore keystore = KeyStore.getInstance("PKCS12"); + keystore.load(null, newP12Pass.toCharArray()); + Certificate [] chain = {caCert}; + keystore.setKeyEntry("1", privKey, newP12Pass.toCharArray(), chain); + keystore.store(newp12, newP12Pass.toCharArray()); + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + newp12.close(); + } + + } + /** + * This function creates a p12 file for a client, creating a new RSA key pair of specified size. A certificate generated, signed by a the CA using the specified private key and CA certificate file. Both the client and CA certificates are stored as a chain in the p12 file. The client certificate's serial number is a system time in miliseconds. + * + * @param keySize Size of the key to generate + * @param subjectName Subject name for the client certificate + * @param newP12Pass Password to use for encrypting the p12 file + * @param p12FileName name for the generated file + * @param validityDays number of days the client certificate should be valid + * @param caCert The CA's certificate + * @param caPrivKey The CA's private key, for signing the client certificate + * @throws NoSuchAlgorithmException + * @throws InvalidKeyException + * @throws IllegalStateException + * @throws SignatureException + * @throws KeyStoreException + * @throws java.security.cert.CertificateException + * @throws IOException + */ + public static void createClientP12(int keySize, String subjectName, String newP12Pass, String p12FileName, int validityDays, X509Certificate caCert, RSAPrivateKey caPrivKey) + throws NoSuchAlgorithmException, + InvalidKeyException, + IllegalStateException, + SignatureException, + KeyStoreException, + java.security.cert.CertificateException, + IOException{ + Security.addProvider(new BouncyCastleProvider()); + KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); + keyGen.initialize(keySize); + KeyPair keyPair = keyGen.generateKeyPair(); + RSAPrivateKey privKey = (RSAPrivateKey)keyPair.getPrivate(); + RSAPublicKey pubKey = (RSAPublicKey)keyPair.getPublic(); + X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); + certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); + certGen.setIssuerDN(caCert.getSubjectX500Principal()); + certGen.setNotBefore(new java.sql.Time(System.currentTimeMillis())); + Calendar expiry = Calendar.getInstance(); + expiry.add(Calendar.DAY_OF_YEAR, validityDays); + certGen.setNotAfter(expiry.getTime()); + certGen.setSubjectDN(new X500Principal("CN=" + subjectName)); + certGen.setPublicKey(pubKey); + certGen.setSignatureAlgorithm("SHA1withRSA"); + certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); + certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); + certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false)); + X509Certificate clientCert = certGen.generate(caPrivKey); + FileOutputStream newp12 = new FileOutputStream(p12FileName); + + try { + KeyStore keystore = KeyStore.getInstance("PKCS12"); + keystore.load(null, newP12Pass.toCharArray()); + System.out.println(clientCert.toString()); + System.out.println(caCert.toString()); + Certificate [] chain = {clientCert, caCert}; + keystore.setKeyEntry("1", privKey, newP12Pass.toCharArray(), chain); + keystore.store(newp12, newP12Pass.toCharArray()); + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + newp12.close(); + } + + } + /** + * Creates an Endorsement Key (EK) Certificate. This certificate is not fully meet Trusted Computing Group specifications. Aside from the key and label source, the + * certificate is basically identical to the AIK certificate made by the makeCert function. The label used is "TPM EK Credential". Ideally, an EK certificate should + * only be created once per TPM and stored in the TPM's NVRAM, but this function can be used to provide the certificate while a method is being researched for the + * permanent storage of the EK certificate in NVRAM. + * + * @param pubEkMod The modulus of the public Endorsement Key (EK) in the form of a byte array. + * @param privKey The Privacy CA's private signing key. + * @param caCert The Privacy CA's public key certificate. + * @param validityDays The number of days until expiration, from the time this function is run. + * @return An EK certificate for the specified TPM's EK. + * @throws NoSuchAlgorithmException Passed on from the BouncyCastle certificate generator. + * @throws InvalidKeySpecException Passed on from the BouncyCastle certificate generator. + * @throws SignatureException Passed on from the BouncyCastle certificate generator. + * @throws NoSuchProviderException Thrown if the BouncyCastle provider cannot be found. + * @throws InvalidKeyException Passed on from the BouncyCastle certificate generator. + * @throws CertificateEncodingException Passed on from the BouncyCastle certificate generator. + */ + + public static X509Certificate makeEkCert(byte [] pubEkMod, RSAPrivateKey privKey, X509Certificate caCert, int validityDays) + throws NoSuchAlgorithmException, + InvalidKeySpecException, + SignatureException, + NoSuchProviderException, + InvalidKeyException, + CertificateEncodingException { + Security.addProvider(new BouncyCastleProvider()); + X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); + certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis())); + certGen.setIssuerDN(caCert.getSubjectX500Principal()); + certGen.setNotBefore(new java.sql.Time(System.currentTimeMillis())); + Calendar expiry = Calendar.getInstance(); + expiry.add(Calendar.DAY_OF_YEAR, validityDays); + certGen.setNotAfter(expiry.getTime()); + certGen.setSubjectDN(new X500Principal("")); + byte [] pubExp = new byte[3]; + pubExp[0] = (byte)(0x01 & 0xff); +// pubExp[1] = (byte)(0x00 & 0xff); + pubExp[1] = (byte)(0x00); + pubExp[2] = (byte)(0x01 & 0xff); + RSAPublicKey pubEk = TpmUtils.makePubKey(pubEkMod, pubExp); + certGen.setPublicKey(pubEk); + certGen.setSignatureAlgorithm("SHA1withRSA"); + certGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.SubjectAlternativeName, true, new GeneralNames(new GeneralName(GeneralName.rfc822Name, "TPM EK Credential"))); + X509Certificate cert = certGen.generate(privKey, "BC"); + return cert; + } + + + /** + * Create a Java RSAPublicKey using the specified modulus and public exponent in byte array form. + * + * @param modulus The RSA key modulus in the form of a byte array. + * @param exponent The RSA public exponent in the form of a byte array. + * @return An RSAPublicKey. + * @throws NoSuchAlgorithmException Thrown if the Java KeyFactory doesn't know what "RSA" is. + * @throws InvalidKeySpecException Thrown if the key material is bad. + */ + public static RSAPublicKey makePubKey(byte[] modulus, byte[] exponent) + throws NoSuchAlgorithmException, + InvalidKeySpecException { + BigInteger modulusBI = byteArrayToBigInt(modulus); + BigInteger exponentBI = byteArrayToBigInt(exponent); + RSAPublicKeySpec newKeySpec = new RSAPublicKeySpec(modulusBI, exponentBI); + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + RSAPublicKey newKey = (RSAPublicKey)keyFactory.generatePublic(newKeySpec); + return newKey; + } + /** + * Generate an RSAPrivateKey object using a modulus and exponent, where both are provided as byte arrays. + * + * @param modulus + * @param exponent + * @return + * @throws NoSuchAlgorithmException + * @throws InvalidKeySpecException + */ + public static RSAPrivateKey makePrivKey(byte[] modulus, byte[] exponent) + throws NoSuchAlgorithmException, + InvalidKeySpecException { + BigInteger modulusBI = byteArrayToBigInt(modulus); + BigInteger exponentBI = byteArrayToBigInt(exponent); + RSAPrivateKeySpec newKeySpec = new RSAPrivateKeySpec(modulusBI, exponentBI); + KeyFactory keyFactory = KeyFactory.getInstance("RSA"); + RSAPrivateKey newKey = (RSAPrivateKey)keyFactory.generatePrivate(newKeySpec); + return newKey; + } + /** + * Create a Java Big Integer from a specified byte array. Intended for converting an RSA modulus or exponent, which is often + * specified in the form of a byte array for TPM activities. This function properly accounts for the highest-order bit set to + * avoid any complications arising from a conversion to the signed Big Integer. + * + * @param incoming The byte array to convert. + * @return The Big Integer with the value of the byte array. + */ + private static BigInteger byteArrayToBigInt(byte[] incoming) { + byte [] tempArray = null; + if ((incoming[0]&0x80) == 0x80) { + tempArray = new byte[incoming.length + 1]; + tempArray[0] = (byte)0x00; + for (int i = 0; i < incoming.length; i++) + tempArray[i+1] = incoming[i]; + } + else { + tempArray = incoming; + } + return new BigInteger(tempArray); + } + /** + * This function is not yet implemented. The intended purpose is to check the validity of an EK certificate supplied in an identity + * request. A valid certificate is one signed by a trusted entity. Another potential version of validity is the EK being present in + * a database of known TPMs. + * + * @param ekCred The EK certificate from the identity proof. + * @return True, if EK certificate passes verification. + */ + public static boolean verifyTPM(X509Certificate ekCred) { + return true; // TODO: check the EK certificate for authenticity. Only EK certificates signed by trusted sources should be trusted. + } + /** + * Creates a string of uppercase hexidecimal duples representing the supplied byte array. They are placed in lines containing a specified number of duples.. + * + * @param blob The byte array to turn into a string. + * @param perLine The number of hexidecimal duples to place on each line. + * @return A String, perhaps multi-line. + */ + public static String byteArrayToString(byte [] blob, int perLine) { + String returnVal = ""; + StringBuffer sb = new StringBuffer(); + for(int i = 0; i < blob.length; i++) { + String hexDigit = Integer.toHexString((int)blob[i] & 0xff).toUpperCase(); + if (hexDigit.length() == 1) + hexDigit = "0" + hexDigit; +// hexDigit = sb.append("0").append(hexDigit).toString(); + returnVal = sb.append(hexDigit).append(" ").toString(); + if (((i+1)%perLine == 0) && (i < (blob.length - 1))) + returnVal = sb.append("\n").toString(); + } + return returnVal; + } + /** + * Retrieve a private key from a PKCS #12 store. It is expected that the P12 file will contain only one private key and one public key certificate. + * + * @param filename The name of the P12 file. + * @param password The password needed to extract from the specified P12 file. + * @return The private key. + * @throws KeyStoreException Passed on from called functions. + * @throws IOException Passed on from called functions. + * @throws NoSuchAlgorithmException Passed on from called functions. + * @throws UnrecoverableKeyException Passed on from called functions. + * @throws javax.security.cert.CertificateException Passed on from called functions. + * @throws java.security.cert.CertificateException Passed on from called functions. + */ + public static RSAPrivateKey privKeyFromP12(String filename, String password) + throws KeyStoreException, + IOException, + NoSuchAlgorithmException, + UnrecoverableKeyException, + javax.security.cert.CertificateException, + java.security.cert.CertificateException { + KeyStore caKs = KeyStore.getInstance("PKCS12"); + FileInputStream fis = new FileInputStream(filename); + try { + caKs.load(fis, password.toCharArray()); + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + fis.close(); + } + + //caKs.load(ConfigHelper.getResourceAsStream(filename), password.toCharArray()); + Enumeration aliases = caKs.aliases(); + RSAPrivateKey privKey = null; + while(aliases.hasMoreElements()) { + String name = aliases.nextElement(); + privKey = (RSAPrivateKey)caKs.getKey(name, password.toCharArray()); + } + return privKey; + } + /** + * Retrieve a public key certificate from a PKCS #12 store. It is expected that the P12 file will contain only one private key and one public key certificate. + * + * @param filename The name of the P12 file. + * @param password The password needed to extract from the specified P12 file. + * @return The private key. + * @throws IOException Passed on from called functions. + * @throws NoSuchAlgorithmException Passed on from called functions. + * @throws UnrecoverableKeyException Passed on from called functions. + * @throws javax.security.cert.CertificateException Passed on from called functions. + * @throws java.security.cert.CertificateException Passed on from called functions. + */ + public static X509Certificate certFromP12(String filename, String password) + throws KeyStoreException, + IOException, + NoSuchAlgorithmException, + javax.security.cert.CertificateException, + java.security.cert.CertificateException { + KeyStore caKs = KeyStore.getInstance("PKCS12"); + FileInputStream fis =new FileInputStream(filename); + try { + caKs.load(fis, password.toCharArray()); + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + fis.close(); + } + + + Enumeration aliases = caKs.aliases(); + X509Certificate cert = null; + while(aliases.hasMoreElements()) { + String name = aliases.nextElement(); + cert = (X509Certificate)caKs.getCertificate(name); + } + return cert; + } + /** + * Retrieve a certificate as an X509Certificate object from a file (generally .cer or .crt using DER or PEM encoding) + * @param filename + * @return + * @throws KeyStoreException + * @throws IOException + * @throws NoSuchAlgorithmException + * @throws javax.security.cert.CertificateException + * @throws java.security.cert.CertificateException + */ + public static X509Certificate certFromFile(String filename) + throws KeyStoreException, + IOException, + NoSuchAlgorithmException, + javax.security.cert.CertificateException, + java.security.cert.CertificateException { + InputStream certStream = new FileInputStream(filename); +// byte [] certBytes = new byte[certStream.available()]; + byte[] certBytes = new byte[2048]; + try { + int k = certStream.read(certBytes); + + } catch (Exception e) { + e.printStackTrace(); + } + finally{ + certStream.close(); + } + javax.security.cert.X509Certificate cert = javax.security.cert.X509Certificate.getInstance(certBytes); + return convertX509Cert(cert); + } + /** + * Retrieve a certificate as an X509Certificate object from a byte string, assuming DER encoding. + * @param certBytes + * @return + * @throws CertificateException + * @throws CertificateEncodingException + * @throws java.security.cert.CertificateException + */ + public static X509Certificate certFromBytes(byte [] certBytes) + throws CertificateException, + CertificateEncodingException, + java.security.cert.CertificateException{ + java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509"); + return (java.security.cert.X509Certificate)cf.generateCertificate(new ByteArrayInputStream(certBytes)); + } + /** + * Take an incoming identity request, unpack the contents, create an identity certificate, and return it in the properly formated form. + * + * @param idRequestBlob The TPM_Identity_Request, as a byte array, as received from the output of the Tspi_TPM_CollateIdentityRequest TSS function. + * @param caPrivKey The Privacy CA's private signing key. + * @param caPubCert The Privacy CA's public key certificate. + * @param validityDays The number of validity days, after which the certificate will expire. + * @return An idResponse, containing both TPM_ASYM_CA_CONTENTS and TPM_SYM_CA_ATTESTATION structures, suitable as input for the Tspi_TPM_ActivateIdentity function. + * @throws PrivacyCaException Thrown if an error occurs when processing the request. + * @throws TpmUtils.TpmUnsignedConversionException Passed from called functions, this most likely reflects a poorly constructed Identity Request or its base Identity Proof. + * @throws BadPaddingException Passed if an encryption/decryption error occurs. + * @throws IllegalBlockSizeException Passed if an encryption/decryption error occurs. + * @throws InvalidAlgorithmParameterException Passed if an encryption/decryption error occurs. + * @throws NoSuchPaddingException Passed if an encryption/decryption error occurs. + * @throws NoSuchAlgorithmException Passed if an encryption/decryption error occurs. + * @throws InvalidKeyException Passed if an encryption/decryption error occurs. + * @throws CertificateEncodingException Passed if an certificate creation error occurs. + * @throws IOException Passed if an certificate creation error occurs. + * @throws InvalidKeySpecException Passed if an certificate creation error occurs. + * @throws SignatureException Passed if an certificate creation error occurs. + * @throws NoSuchProviderException Passed if an certificate creation error occurs. + * @throws javax.security.cert.CertificateException Passed if an certificate creation error occurs. + * @throws java.security.cert.CertificateException Passed if an certificate creation error occurs. + * @throws TpmUtils.TpmBytestreamResouceException Passed from called functions, this most likely reflects a poorly constructed Identity Request or its base Identity Proof. + */ + public static idResponse ProcessIdentityRequest (byte [] idRequestBlob, RSAPrivateKey caPrivKey, X509Certificate caPubCert, int validityDays) + throws PrivacyCaException, + TpmUtils.TpmUnsignedConversionException, + BadPaddingException, + IllegalBlockSizeException, + InvalidAlgorithmParameterException, + NoSuchPaddingException, + NoSuchAlgorithmException, + InvalidKeyException, + CertificateEncodingException, + IOException, + InvalidKeySpecException, + SignatureException, + NoSuchProviderException, + javax.security.cert.CertificateException, + java.security.cert.CertificateException, + TpmUtils.TpmBytestreamResouceException { + TpmIdentityRequest request = new TpmIdentityRequest(idRequestBlob); + TpmIdentityProof idProof = request.decrypt(caPrivKey); + if (idProof.getEkCredBytes().length == 0) throw new PrivacyCaException("PrivacyCaException: Error parsing TPM_IDENTITY_PROOF: there is no endorsement credential."); + if (!idProof.checkValidity((RSAPublicKey)caPubCert.getPublicKey())) throw new PrivacyCaException("Request does not pass integrity check: identity binding does not pass verification."); + TpmSymCaAttestation symPart = new TpmSymCaAttestation(); + symPart.setAikCredential(TpmUtils.makeCert(idProof, caPrivKey, caPubCert, validityDays, 0)); + TpmAsymCaContents asymPart = new TpmAsymCaContents(); + //pass symmetric encryption mode here + TpmSymmetricKey temp = symPart.encrypt(TpmKeyParams.TPM_ALG_AES, TpmKeyParams.TPM_ES_SYM_CBC_PKCS5PAD, request.getSymKeyParams().getTrouSerSmode(), !request.getSymkeyEncscheme()); //see the ! + asymPart.setSymmetricKey(temp); + asymPart.setDigest(idProof.getAik()); + //pass asymmetric encryption mode here + asymPart.encrypt((RSAPublicKey)idProof.getEkCred().getPublicKey(), !request.getOeapMode());//see the ! + idResponse returnval = new idResponse(asymPart, symPart); + return returnval; + } + /** + * Used by the Privacy CA (version 1) to process Identity Requests that do not contain an EC. The EC is not validated, and the AIC is returned in plaintext. The client can then get the AIC without using ActivateIdentity. This is here because the Windows (NTRU) TSS client is broken, and cannot include the EC in an Identity Request, and also cannot perform an ActivateIdentity properly. + * + * @param idRequestBlob The incomming Identity Request with no EC + * @param caPrivKey The Privacy CA's private key + * @param caPubCert The Privacy CA's certificate + * @param validityDays The number of days before AIC expiration + * @return the AIC in the form of an X509Certificate + * @throws PrivacyCaException + * @throws TpmUtils.TpmUnsignedConversionException + * @throws BadPaddingException + * @throws IllegalBlockSizeException + * @throws InvalidAlgorithmParameterException + * @throws NoSuchPaddingException + * @throws NoSuchAlgorithmException + * @throws InvalidKeyException + * @throws CertificateEncodingException + * @throws IOException + * @throws InvalidKeySpecException + * @throws SignatureException + * @throws NoSuchProviderException + * @throws javax.security.cert.CertificateException + * @throws java.security.cert.CertificateException + * @throws TpmUtils.TpmBytestreamResouceException + */ + public static X509Certificate PartiallyProcessIdentityRequest (byte [] idRequestBlob, RSAPrivateKey caPrivKey, X509Certificate caPubCert, int validityDays) + throws PrivacyCaException, + TpmUtils.TpmUnsignedConversionException, + BadPaddingException, + IllegalBlockSizeException, + InvalidAlgorithmParameterException, + NoSuchPaddingException, + NoSuchAlgorithmException, + InvalidKeyException, + CertificateEncodingException, + IOException, + InvalidKeySpecException, + SignatureException, + NoSuchProviderException, + javax.security.cert.CertificateException, + java.security.cert.CertificateException, + TpmUtils.TpmBytestreamResouceException { + TpmIdentityRequest request = new TpmIdentityRequest(idRequestBlob); + TpmIdentityProof idProof = request.decrypt(caPrivKey); + if (!idProof.checkValidity((RSAPublicKey)caPubCert.getPublicKey())) throw new PrivacyCaException("Request does not pass integrity check: identity binding does not pass verification."); + return TpmUtils.makeCert(idProof, caPrivKey, caPubCert, validityDays, 0); + } + /** + * Generate a new identity request. User supplied data for a new request is the identity label + * and the Privacy CA's public key. This function relies upon a method to obtain the public key + * of a newly-created identity key (to be certified by the Privacy CA), an identity binding + * signed by the TPM, and any certificates available from the TPM's non-volatile storage + * (Endorsement, Platform, and/or Conformance certificates). Note: the endorsement certificate + * must be present to have a complete request! The functionality to get this TPM-supplied + * data is currently not available. + * + * @param idLabel A string, to be submitted in ASCII, to be used as the subject alternative name for the identity certificate + * @param caPubKey The public key of the Privacy CA + * @param IV A boolean flag to specify the placement of the symmetric encryption initialization vector (true indicates that IV should be placed at the beginning of symmetrically encrypted blob instead of the symmetric key parameters) + * @param symKey A boolean flag to specify the symmetric key encryption scheme flag (true indicates the encryption scheme should be specified as "TSS_ES_NONE") + * @param oaep A boolean flag to indicate if the asymmetric OAEP padding will use the string specified in the TSS 1.1b "Main" document (true indicates that the string should be left blank) + * @return + * @throws TpmUtils.TpmUnsignedConversionException + * @throws NoSuchPaddingException + * @throws NoSuchAlgorithmException + * @throws InvalidAlgorithmParameterException + * @throws InvalidKeyException + * @throws BadPaddingException + * @throws IllegalBlockSizeException + * @throws IOException + */ + public static TpmIdentityRequest createIdentityRequest(String idLabel, RSAPublicKey caPubKey, boolean IV, boolean symKey, boolean oaep) + throws TpmUtils.TpmUnsignedConversionException, + NoSuchPaddingException, + NoSuchAlgorithmException, + InvalidAlgorithmParameterException, + InvalidKeyException, + BadPaddingException, + IllegalBlockSizeException, + IOException { + //TODO: Get the following from Tcsip_MakeIdentity + byte [] identityBinding = "".getBytes(); + byte [] identityKey = "".getBytes(); //must be just the modulus!!! + //TODO: Get the following from the NV-RAM, if desired + byte [] endorsementCert = "".getBytes(); + byte [] platformCert = "".getBytes(); + byte [] conformanceCert = "".getBytes(); + // Assemble Identity Proof + TpmIdentityProof idProof = new TpmIdentityProof(idLabel.getBytes(), identityBinding, new TpmPubKey(identityKey), endorsementCert, platformCert, conformanceCert, IV, symKey, oaep); + // Encrypt Identity Proof into Identity Request using Privacy CA public key + TpmIdentityRequest idReq = new TpmIdentityRequest(idProof, caPubKey); + return idReq; + } + /** + * Fills a 16 byte array with random data, using nanoTime. + * + * @return A byte array of length 16 containing new random data. + * @throws IOException + */ + public static byte [] createRandomBytes(int numBytes) + throws IOException { + Random random = new Random(System.nanoTime()); + //byte [] randomBytes = longToByteArray(random.nextLong()); + byte [] randomBytes = new byte[numBytes]; + random.nextBytes(randomBytes); + return randomBytes; + } + /** + * Encode an X509 Certificate in the PEM (base64) encoding format. + * + * @param cert The certificate to encode. + * @return A String with the base64 encoded certificate. + * @throws CertificateEncodingException Thrown if there is a problem with the certificate. + */ + public static String PEMencodeCert(X509Certificate cert) + throws CertificateEncodingException { + return "-----BEGIN CERTIFICATE-----" + base64encode(cert.getEncoded(), false) + "-----END CERTIFICATE-----"; + } + /** + * Base64 encode a byte array. + * + * @param toEncode The byte array to encode. + * @param breakLines Set true if it is desired to place line break at every 76 characters, per spec (not done often). + * @return The String of the encoded array. + */ + public static String base64encode(byte [] toEncode, boolean breakLines) { + StringBuffer sb =new StringBuffer(); + char[] charArray = new String(Base64.encode(toEncode)).toCharArray(); + String toReturn = ""; + for (int i = 0; i < charArray.length; i++){ + if(breakLines){if((i%64 == 0)) toReturn = sb.append("\n").toString(); } + toReturn = sb.append(charArray[i]).toString(); + } + return toReturn; + } + public static byte[] base64decode(String encoded){ + return Base64.decode(encoded); + } + /** + * Convert a javax X509Certificate to a java X509Certificate. + * + * @param cert A certificate in javax.security.cert.X509Certificate format + * @return A certificate in java.security.cert.X509Certificate format + */ + public static java.security.cert.X509Certificate convertX509Cert(javax.security.cert.X509Certificate cert) + throws java.security.cert.CertificateEncodingException, + javax.security.cert.CertificateEncodingException, + java.security.cert.CertificateException, + javax.security.cert.CertificateException { + java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509"); + return (java.security.cert.X509Certificate)cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded())); + } + /** + * Convert a java X509Certificate to a javax X509Certificate. + * + * @param cert A certificate in java.security.cert.X509Certificate format + * @return A certificate in javax.security.cert.X509Certificate format + */ + public static javax.security.cert.X509Certificate convertX509Cert(java.security.cert.X509Certificate cert) + throws java.security.cert.CertificateEncodingException, + javax.security.cert.CertificateEncodingException, + java.security.cert.CertificateException, + javax.security.cert.CertificateException { + return javax.security.cert.X509Certificate.getInstance(cert.getEncoded()); + } + /** + * Given a string of hexadecimal characters, convert to a byte array. No checks are performed to ensure that the string is all valid hexidecimal characters (0-9, a-f, A-F) or that there is an even number of characters. + * @param s The hexadecimal string + * @return A byte array + */ + public static byte[] hexStringToByteArray(String s) { + int sizeInt = s.length()/2; + byte [] returnArray = new byte[sizeInt]; + String byteVal; + for (int i = 0; i < sizeInt; i++) { + int index = 2 * i; + byteVal = s.substring(index, index + 2); + returnArray[i] = (byte)(Integer.parseInt(byteVal, 16)); +// returnArray[i] = (byte)(Integer.parseInt(byteVal, 16) & 0xff); + } + return returnArray; + } + /** + * Convert a byte array to a hexidecimal character string. The string will have no delimeter between hexidecimal duples, and has no line breaks. + * @param b Byte array to convert + * @return A string of hexidecimal characters + */ + public static String byteArrayToHexString(byte[] b) { + StringBuffer sb = new StringBuffer(); + String returnStr = ""; + for (int i = 0; i < b.length; i++) { + String singleByte = Integer.toHexString(b[i] & 0xff); + if (singleByte.length() != 2) singleByte = "0" + singleByte; +// returnStr += singleByte; + returnStr = sb.append(singleByte).toString(); + } + return returnStr; + } + /** + * Convert a byte array to a hexidecimal character string, in a format that can be placed as a parameter in C++. The hexidecimal byte duples are each prefixed with "0x" and delimted with a comma and space (", "). Example: "0x0a, 0xbc, " + * @param b Byte array to convert + * @return String in the format described above + */ + public static String byteArrayToCppHexString(byte[] b){ + StringBuffer sb =new StringBuffer(); + String returnStr = ""; + for (int i = 0; i < b.length; i++) { + String singleByte = Integer.toHexString(b[i] & 0xff); + if (singleByte.length() != 2) singleByte = "0" + singleByte; + returnStr = sb.append("0x").append(singleByte).append(", ").toString(); + } + return returnStr; + } + /** + * Concatenate two byte arrays into one, in the order they are specified. + * @param blob1 Byte array to be placed first in the concatenation + * @param blob2 Byte array to be placed last in the concatenation + * @return + */ + public static byte[] concat(byte[] blob1, byte[] blob2){ + byte[] toReturn = new byte[blob1.length + blob2.length]; + System.arraycopy(blob1, 0, toReturn, 0, blob1.length); + System.arraycopy(blob2, 0, toReturn, blob1.length, blob2.length); + return toReturn; + } + /** + * Perform a SHA-1 hash of a given byte array + * @param blob Byte array to hash + * @return SHA-1 hash of the specified byte array. Should always be 20 bytes in length + * @throws NoSuchAlgorithmException + */ + public static byte[] sha1hash(byte[] blob) + throws NoSuchAlgorithmException{ + byte[] toReturn = null; + MessageDigest md = MessageDigest.getInstance("SHA1"); + md.update(blob); + toReturn = md.digest(); + return toReturn; + } + /** + * Perform an asymmetric encryption of a byte array in the way specified by the TCG for all TPM-related operations, using the given OAEP string (in case it is not the TCG-specified "TCPA") + * @param payload Byte array to encrypt + * @param pubKey RSA public key to use for encryption + * @param OAEPstring The OAEP string to use for padding + * @return An encrypted blob of the length of the pubKey's modulus + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws IllegalBlockSizeException + * @throws BadPaddingException + */ + public static byte[] TCGAsymEncrypt(byte[] payload, RSAPublicKey pubKey, String OAEPstring) + throws NoSuchAlgorithmException, + NoSuchPaddingException, + InvalidKeyException, + InvalidAlgorithmParameterException, + IllegalBlockSizeException, + BadPaddingException{ + OAEPParameterSpec oaepSpec = new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified(OAEPstring.getBytes())); + Cipher asymCipher = Cipher.getInstance("RSA/ECB/OAEPWithSha1AndMGF1Padding"); + asymCipher.init(Cipher.PUBLIC_KEY, pubKey, oaepSpec); + asymCipher.update(payload); + byte [] toReturn = asymCipher.doFinal(); + return toReturn; + } + /** + * Perform an asymmetric encryption of a byte array in the way specified by the TCG for all TPM-related operations, using the OAEP string "TCPA" as specified. + * @param payload Byte array to encrypt + * @param pubKey RSA public key to use for encryption + * @return The encrypted blob of the length of the pubKey's modulus + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws IllegalBlockSizeException + * @throws BadPaddingException + */ + public static byte[] TCGAsymEncrypt(byte[] payload, RSAPublicKey pubKey) + throws NoSuchAlgorithmException, + NoSuchPaddingException, + InvalidKeyException, + InvalidAlgorithmParameterException, + IllegalBlockSizeException, + BadPaddingException{ + return TCGAsymEncrypt(payload, pubKey, "TCPA"); + } + /** + * Perform a symmetric encryption of a byte array in the way specified by the TCG for all TPM-related symmetric encryption activities. The given key and IV are used. + * @param payload Byte array to encrypt + * @param key Symmetric (AES) key to use. Exception will be thrown if key is an invalid length. + * @param iv Initialization Vector to use. Exception will be thrown if IV is an invalid length. + * @return Encrypted byte blob. + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws IllegalBlockSizeException + * @throws BadPaddingException + */ + public static byte[] TCGSymEncrypt(byte[] payload, byte[] key, byte[] iv) + throws NoSuchAlgorithmException, + NoSuchPaddingException, + InvalidKeyException, + InvalidAlgorithmParameterException, + IllegalBlockSizeException, + BadPaddingException{ + Cipher symCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + IvParameterSpec ivSpec = new IvParameterSpec(iv); + SecretKeySpec symKey = new SecretKeySpec(key, "AES"); + symCipher.init(Cipher.ENCRYPT_MODE, symKey, ivSpec); + byte [] toReturn = symCipher.doFinal(payload); + return toReturn; + } + /** + * Create a random 128-bit value that can be used as an AES key or IV. + * @return + * @throws IOException + */ + public static byte[] newRandomAESValue() //key or iv + throws IOException{ + return TpmUtils.createRandomBytes(16); + } + /** + * Decrypt an TCG-style asymmetrically encrypted byte blob, given the correct RSA private key and OAEP string. If properly encrypted, the OAEP string should be "TCPA" (less the quotes). + * @param ciphertext Asymmetrically encrypted byte array + * @param privKey The RSA private key to be used to decrypt the ciphertext + * @param OAEPstring The OAEP string that was used for padding (should be "TCPA") + * @return The decrypted byte array + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws IllegalBlockSizeException + * @throws BadPaddingException + */ + public static byte[] TCGAsymDecrypt(byte[] ciphertext, RSAPrivateKey privKey, String OAEPstring) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{ + Cipher asymCipher = Cipher.getInstance("RSA/ECB/OAEPWithSha1AndMGF1Padding"); + OAEPParameterSpec oaepSpec = new OAEPParameterSpec("Sha1", "MGF1", MGF1ParameterSpec.SHA1, new PSource.PSpecified(OAEPstring.getBytes())); + asymCipher.init(Cipher.PRIVATE_KEY, privKey, oaepSpec); + asymCipher.update(ciphertext); + byte[] toReturn = asymCipher.doFinal(); + return toReturn; + } + /** + * Decrypt an AES/CBC/PKCS5Paddded symmetrically encrypted blob, using the given key and IV. + * @param ciphertext The encrypted byte array + * @param key The key used to perform the decryption + * @param iv The Initialization Vector used + * @return The decrypted byte array + * @throws NoSuchAlgorithmException + * @throws NoSuchPaddingException + * @throws InvalidKeyException + * @throws InvalidAlgorithmParameterException + * @throws IllegalBlockSizeException + * @throws BadPaddingException + */ + public static byte[] TCGSymDecrypt(byte[] ciphertext, byte[] key, byte[] iv) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{ + Cipher symCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + IvParameterSpec ivSpec = new IvParameterSpec(iv); + symCipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), ivSpec); + return symCipher.doFinal(ciphertext); + } + /** + * Generate a Hashed Message Authentication Code for TCS function authentication using the given auth blob and concatenation of all *H1 (1H1, 2H1, etc) values for the function. + * @param authBlob 20 byte auth code for the object in question + * @param xH1concat A concatenation of all of the authenticated *H1 parameters for the function, e.g. 1H1, 2H1, 3H1, etc. + * @return The HMAC blob suitable to be used for passing as a TCS parameter + * @throws Exception + */ + public static byte[] HMAC(byte[] authBlob, byte[] xH1concat) throws Exception{ + Mac mac = Mac.getInstance("HmacSha1"); + SecretKey key = new SecretKeySpec(authBlob, "HmacSha1"); + mac.init(key); + mac.update(xH1concat); + return mac.doFinal(); + } + /** + * Returns true if both byte arrays sent in parameters are the same length and have the exact same contents for each respective elements. + * @param array1 + * @param array2 + * @return + */ + public static boolean compareByteArrays(byte[] array1, byte[] array2){ + if(array1.length != array2.length) + return false; + for(int i = 0; i < array1.length; i++) + if(array1[i] != array2[i]) + return false; + return true; + } + /** + * Get the system's Fully Qualified Domain Name as a string + * @return the system's FQDN + */ + public static String getHostname(){ + String hostname = ""; + try{ + hostname = InetAddress.getLocalHost().getHostName(); + } + catch (UnknownHostException u){ + StringTokenizer st = new StringTokenizer(u.getMessage()); + while (st.hasMoreTokens()) hostname = st.nextToken(); + } + return hostname; + } + +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/idResponse.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/idResponse.java new file mode 100644 index 0000000..c1100e1 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/idResponse.java @@ -0,0 +1,86 @@ +/* + * 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + * �Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * �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. + * �Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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 gov.niarl.his.privacyca; + +/** + *

    This class is needed to provide a return type for the utils.processIdentityRequest function that includes + * both the Symmetric and Asymmetric parts of the Privacy CA's response. It is simply a holding container. + * The data is not manipulated in any way, except as needed for formatting.

    + * + * @author schawki + * + */ +public class idResponse { + private TpmAsymCaContents asymPart; + private TpmSymCaAttestation symPart; + /** + * Create a new idResponse of the supplied TPM_ASYM_CA_CONTENTS and TPM_SYM_CA_ATTESTATION structures. + * + * @param asym TPM_ASYM_CA_CONTENTS + * @param sym TPM_SYM_CA_ATTESTATION + */ + public idResponse(TpmAsymCaContents asym, TpmSymCaAttestation sym) { + asymPart = asym; + symPart = sym; + } + /** + * If needed, this function provides a byte array of the Asym and Sym parts of the response concatenated together. + * + * @return Byte array form of the idResponse (asym + sym). + * @throws TpmUtils.TpmUnsignedConversionException Thrown if bad data is encountered when assembling the byte array. + * @throws PrivacyCaException Thrown if either part is not complete and ready to be turned into a byte array. + */ + public byte [] toByteArray() + throws TpmUtils.TpmUnsignedConversionException, + PrivacyCaException { + byte [] asym = asymPart.toByteArray(); + byte [] sym = symPart.toByteArray(); + byte [] returnArray = new byte[asym.length + sym.length]; + System.arraycopy(asym, 0, returnArray, 0, asym.length); + System.arraycopy(sym, 0, returnArray, asym.length, sym.length); + return returnArray; + } + /** + * Asym getter function. + * + * @return Asymmetric portion of idResponse. + */ + public TpmAsymCaContents getAsymPart() { + return asymPart; + } + /** + * Sym getter function. + * + * @return Symmetric portion of idResponse. + */ + public TpmSymCaAttestation getSymPart() { + return symPart; + } + /** + * Asym setter function. + * + * @param newPart + */ + public void setAsymPart(TpmAsymCaContents newPart) { + asymPart = newPart; + } + /** + * Sym setter function. + * + * @param newPart + */ + public void setSymPart(TpmSymCaAttestation newPart) { + symPart = newPart; + } +} diff --git a/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/package-info.java b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/package-info.java new file mode 100644 index 0000000..e314695 --- /dev/null +++ b/OpenAttestation/Source/PrivacyCA/src/gov/niarl/his/privacyca/package-info.java @@ -0,0 +1,4 @@ +/** +

    This package contains all base classes that are used by the HIS Privacy CA and Client Provisioner.

    +*/ +package gov.niarl.his.privacyca; \ No newline at end of file diff --git a/OpenAttestation/Source/TPMModule/NTPM_build.txt b/OpenAttestation/Source/TPMModule/NTPM_build.txt new file mode 100644 index 0000000..b2eaf16 --- /dev/null +++ b/OpenAttestation/Source/TPMModule/NTPM_build.txt @@ -0,0 +1,19 @@ +******************** +* NIARL_TPM_Module * +******************** + +BUILD INSTRUCTIONS + +LINUX + +Build requires the installation of automake, the GCC C++ compiler, and Trousers development files. On Red Hat automake and GCC C++ are normally installed by default. Trousers development files can be acquired by having yum install trousers-devel. + +NIARL_TPM_Module includes a makefil and supporting files automatically generated by Eclipse. Simply type make into a terminal window after navigating to the folder in which the NIARL_TPM_Module source has been extraced. This will generate an executable suitable for your system. + +Note that Trousers (tcsd) is required to be installed and operating before using the NIARL_TPM_Module. + +WINDOWS + +Visual Studio project files are included for Windows clients. However, the TCG TSS header files and TSS library are NOT included. The TSS header files can be acquired from the TCG's website. The TSS library must be licensed from a TSS vendor. Trousers exists on Linux as a free and open source TPM interface. No such equivalent exists on Windows. While some TSS vendors like NTru and Infineon make their software available licenses to develop against that software may require additional investment. + +Visual Studio needs to know the include directory for the TSS header files and the location of the TSS development library before compilation. \ No newline at end of file diff --git a/OpenAttestation/Source/TPMModule/plain/linux/NIARL_TPM_ModuleV2.cpp b/OpenAttestation/Source/TPMModule/plain/linux/NIARL_TPM_ModuleV2.cpp new file mode 100644 index 0000000..42b4396 --- /dev/null +++ b/OpenAttestation/Source/TPMModule/plain/linux/NIARL_TPM_ModuleV2.cpp @@ -0,0 +1,5577 @@ +/** + * Copyright (C) 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * 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) Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. + */ + +#include "NIARL_TPM_ModuleV2.h" + +NIARL_TPM_ModuleV2::NIARL_TPM_ModuleV2(int argc, char* argv[]) +{ + //set defaults + b_debug = false; + b_log = false; + b_help = false; + b_infile = false; + b_outfile = false; + i_mode = 0; + i_return = 0; + + //setup local copy of argument array + i_argc = argc; + s_argv = new string[i_argc]; + + for(short i = 0; i < i_argc; i++) + { + if(strcmp(argv[i], "-debug") == 0) + { + b_debug = true; + continue; + } + + if(strcmp(argv[i], "-log") == 0) + { + b_log = true; + continue; + } + + if(strcmp(argv[i], "-help") == 0) + { + b_help = true; + continue; + } + + if(strcmp(argv[i], "-mode") == 0) + { + if(++i >= i_argc) return; + i_mode = atoi(argv[i]); + continue; + } + +/* if(strcmp(argv[i], "-infile") == 0) + { + b_infile = true; + infile.open(s_argv[(++i)].c_str(), ios::in); + if(infile.is_open()) + cin.rdbuf(infile.rdbuf()); + else + return_code = -1 * ERROR_ARG_INFILE; + continue; + } +*/ + if(strcmp(argv[i], "-outfile") == 0) + { + b_outfile = true; + if(++i >= i_argc) return; + outfile.open(s_argv[(i)].c_str(), ios::out); + if(outfile.is_open()) + cout.rdbuf(outfile.rdbuf()); + else + return_code = -1 * ERROR_ARG_OUTFILE; + continue; + } + + //convert function-specific c-string data to c++ strings + s_argv[i] = argv[i]; + } + + if(b_debug || b_log) + { + //record the start time and output appropriate messages + time_t rawtime; + struct tm* timeinfo; + time(&rawtime); + timeinfo = localtime(&rawtime); + + if(b_debug) + { + cerr << "START --- NIARL TPM Module (v2.5 11-24-2010) --- " << asctime(timeinfo); + cerr << ' ' << i_mode << " mode selection" << endl; + cerr << ' ' << b_debug << " debug toggle" << endl; + cerr << ' ' << logfile.is_open() << " logging" << endl; + cerr << ' ' << infile.is_open() << " input file" << endl; + cerr << ' ' << outfile.is_open() << " output file" << endl; + } + + if(b_log) + { + clog << "START --- NIARL TPM Module (v2.5 11-24-2010) --- " << asctime(timeinfo); + clog << ' ' << i_mode << " mode selection" << endl; + clog << ' ' << b_debug << " debug toggle" << endl; + clog << ' ' << logfile.is_open() << " logging" << endl; + clog << ' ' << infile.is_open() << " input file" << endl; + clog << ' ' << outfile.is_open() << " output file" << endl; + } + } + + if(b_help && i_mode == 0) + { + cout << endl << "NIARL TPM MODULE (Version 2.5, Build Date 11-25-2010) PLAIN, SYM-FIX, SEG-FIX" << endl; + cout << endl << "MODE LIST" << endl; + cout << " 1 --- Take Ownership" << endl; + cout << " 2 --- Clear Ownership" << endl; + cout << " 3 --- Collate Identity Request" << endl; + cout << " 4 --- Activate Identity" << endl; + cout << " 5 --- Quote" << endl; + cout << " 6 --- Create Revokable Endorsement Key" << endl; + cout << " 7 --- Revoke Revokable Endorsement Key" << endl; + cout << " 8 --- Create Key (sign or bind)" << endl; + cout << " 9 --- Set Key (sign, bind, or identity)" << endl; + cout << " 10 --- Get Key (sign, bind, identity, or EK)" << endl; + cout << " 11 --- Clear Key (sign, bind, or identity)" << endl; + cout << " 12 --- Set Credential (EC, PC, CC, and PCC)" << endl; + cout << " 13 --- Get Credential (EC, PC, CC, and PCC)" << endl; + cout << " 14 --- Clear Credential (EC, PC, CC, and PCC)" << endl; + cout << " 15 --- Seal" << endl; + cout << " 16 --- Unseal" << endl; + cout << " 17 --- Bind" << endl; + cout << " 18 --- Unbind" << endl; + cout << " 19 --- Seal Bind" << endl; + cout << " 20 --- Unseal Unbind" << endl; + cout << " 21 --- Get Random Integer" << endl; + cout << " 22 --- Sign" << endl; + cout << " 23 --- Create Endorsement Key" << endl; + cout << " 24 --- Quote2" << endl; + + cout << endl << "INPUT FLAGS" << endl; + cout << " -mode integer (mode selection flag)" << endl; + cout << " -debug (debugging output displayed to cerr)" << endl; + cout << " -outfile name.txt (standard output redirected to file named)" << endl; + + cout << endl << "ERROR CODES" << endl; + cout << " TSS errors are positive integers. TPM Module errors are negative integers." << endl; + cout << " -" << ERROR_UNKNOWN << " --- Unspecified error" << endl; + cout << " -" << ERROR_ARG_MISSING << " --- Argument missing" << endl; + cout << " -" << ERROR_ARG_INFILE << " --- Invalid or inaccessible input file" << endl; + cout << " -" << ERROR_ARG_OUTFILE << " --- Invalid or inaccessible output file" << endl; + cout << " -" << ERROR_ARG_MODE << " --- Invalid mode selection" << endl; + cout << " -" << ERROR_ARG_VALIDATION << " --- Argument validation error" << endl; + cout << " -" << ERROR_ARG_HELP << " --- Help toggle detected" << endl; + cout << " -" << ERROR_MODE_DISABLED << " --- Mode selection disabled" << endl; + } +} + +NIARL_TPM_ModuleV2::~NIARL_TPM_ModuleV2() +{ + //delete dynamic arrays + delete [] s_argv; + + //close logfile + if(logfile.is_open()) + logfile.close(); + +/* //close input file + if(infile.is_open()) + infile.close(); +*/ + //close output file + if(outfile.is_open()) + outfile.close(); + + if(b_debug || b_log) + { + //record the end time and output appropriate messages + time_t rawtime; + struct tm* timeinfo; + time(&rawtime); + timeinfo = localtime(&rawtime); + + if(b_debug) + cerr << "END --- NIARL TPM Module --- " << asctime(timeinfo); + + if(b_log) + clog << "END --- NIARL TPM Module --- " << asctime(timeinfo); + } +} + +void NIARL_TPM_ModuleV2::run_mode() +{ + switch(i_mode) + { + case MODE_TAKE_OWNERSHIP: + take_ownership(); + break; + case MODE_CLEAR_OWNERSHIP: + clear_ownership(); + break; + case MODE_COLLATE_IDENTITY: + collate_identity(); + break; + case MODE_ACTIVATE_IDENTITY: + activate_identity(); + break; + case MODE_QUOTE: + quote(); + break; + case MODE_CREATE_REK: + create_revokable_ek(); + break; + case MODE_REVOKE_REK: + revoke_ek(); + break; + case MODE_CREATE_KEY: + create_key(); + break; + case MODE_SET_KEY: + set_key(); + break; + case MODE_GET_KEY: + get_key(); + break; + case MODE_CLEAR_KEY: + clear_key(); + break; + case MODE_SET_CREDENTIAL: + set_credential(); + break; + case MODE_GET_CREDENTIAL: + get_credential(); + break; + case MODE_CLEAR_CREDENTIAL: + clear_credential(); + break; + case MODE_SEAL: + seal(); + break; + case MODE_UNSEAL: + unseal(); + break; + case MODE_BIND: + bind(); + break; + case MODE_UNBIND: + unbind(); + break; + case MODE_SEAL_BIND: + seal_bind(); + break; + case MODE_UNSEAL_UNBIND: + unseal_unbind(); + break; + case MODE_GET_RAND: + get_rand_int(); + break; + case MODE_SIGN: + sign(); + break; + case MODE_CREATE_EK: + create_ek(); + break; + case MODE_QUOTE2: + quote2(); + break; + default: + return_code = -1 * ERROR_ARG_MODE; + return; + } +} + +/********************************************************************************************** + Take Ownership + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::take_ownership() +{ + if(b_help) + { + cout << "Take Ownership (" << i_mode << ") --- Takes ownership of the TPM and establishes a Storage Root Key (SRK)" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -nonce (hex blob, anti-replay nonce)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string s_nonce; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-nonce") == 0) + { + if(++i >= i_argc) return; + s_nonce = s_argv[i]; + i_success++; + } + } + if(i_success != 2) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + NIARL_Util_ByteBlob nonce(s_nonce); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_PLAIN, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//SRK OPERATIONS (NOT SET YET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//EK SECTION + TSS_HKEY ek; + TSS_HPOLICY policy_ek; + TSS_VALIDATION validation; + + if(b_debug) cerr << "EK Section" << endl; + if(b_log) clog << "EK Section" << endl; + + memset(&validation, 0, sizeof(TSS_VALIDATION)); + validation.versionInfo.bMajor = 0x01; + validation.versionInfo.bMinor = 0x02; + validation.versionInfo.bRevMajor = 0x01; + validation.versionInfo.bRevMinor = 0x25; + validation.ulExternalDataLength = sizeof(TSS_NONCE); + validation.rgbExternalData = nonce.blob; + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_SIZE_DEFAULT, &ek); + if(b_debug) cerr << ' ' << result << " create ek object" << endl; + if(b_log) cerr << ' ' << result << " create ek object" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_ek); + if(b_debug) cerr << ' ' << result << " create ek policy" << endl; + if(b_log) cerr << ' ' << result << " create ek policy" << endl; + + result = Tspi_Policy_SetSecret(policy_ek, TSS_SECRET_MODE_PLAIN, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " set auth" << endl; + if(b_log) cerr << ' ' << result << " set auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_ek, ek); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_TPM_GetPubEndorsementKey(tpm, false, &validation, &ek); + if(b_debug) cerr << ' ' << result << " get the ek (false flag)" << endl; + if(b_log) cerr << ' ' << result << " get the ek (false flag)" << endl; + + +//TAKE OWNERSHIP + if(b_debug) cerr << "Take Ownership Section" << endl; + if(b_log) clog << "Take Ownership Section" << endl; + + result = Tspi_TPM_TakeOwnership(tpm, srk, ek); + if(b_debug) cerr << ' ' << result << " TAKE OWNERSHIP" << endl; + if(b_log) cerr << ' ' << result << " TAKE OWNERSHIP" << endl; + return_code = result; + + if(result == 0) + { + //LOAD KEYS + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " save the srk" << endl; + if(b_log) cerr << ' ' << result << " save the srk" << endl; + return_code = result; + } + + +//CLEANUP + result = Tspi_Context_FreeMemory(context, validation.rgbData); + result = Tspi_Context_FreeMemory(context, validation.rgbValidationData); + result = Tspi_Context_FreeMemory(context, validation.rgbExternalData); + + result = Tspi_Context_CloseObject(context, policy_tpm); + result = Tspi_Context_CloseObject(context, policy_ek); + result = Tspi_Context_CloseObject(context, srk); + result = Tspi_Context_CloseObject(context, ek); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Clear Ownership + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::clear_ownership() +{ + if(b_help) + { + cout << "Clear Ownership (" << i_mode << ") --- Clears ownership data and deactivates TPM" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + } + if(i_success != 1) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_PLAIN, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//CLEAR OWNERSHIP + if(b_debug) cerr << "Clear Ownership Section" << endl; + if(b_log) clog << "Clear Ownership Section" << endl; + + result = Tspi_TPM_ClearOwner(tpm, FALSE); + if(b_debug) cerr << ' ' << result << " CLEAR OWNERSHIP" << endl; + if(b_log) cerr << ' ' << result << " CLEAR OWNERSHIP" << endl; + return_code = result; + + +//CLEANUP + result = Tspi_Context_CloseObject(context, policy_tpm); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Collate Identity + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::collate_identity() +{ + if(b_help) + { + cout << "Collate Identity (" << i_mode << ") --- Creates an Attestation Identity Key (AIK)" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -key_auth (hex blob, identity key authorization data)" << endl; + cout << " -key_label (hex blob, hex representation of aik label)" << endl; + cout << " -pcak (hex blob, privacy CA key)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -ec_blob (hex blob, endorsement credential)" << endl; + cout << " -ec_nvram (flag, forces endorsement credential to load from NVRAM)" << endl; + cout << " -trousers (flag, manually determines credential size from DER x509 size header)" << endl; + cout << " OUTPUTS" << endl; + cout << " identity request (hex blob)" << endl; + cout << " modulus (hex blob, key modulus)" << endl; + cout << " key blob (hex blob, key blob)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string s_pcak; + string s_aiklabel; + string s_aikauth; + string s_ec; + int i_keyindex = 0; + bool ec_nvram = false; + bool ec_blob = false; + bool b_trousers = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-pcak") == 0) + { + if(++i >= i_argc) return; + s_pcak = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_label") == 0) + { + if(++i >= i_argc) return; + s_aiklabel = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_aikauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + + //explicitly load endorsement credential via hex blob + if(s_argv[i].compare("-ec_blob") == 0) + { + if(++i >= i_argc) return; + s_ec = s_argv[i]; + ec_blob = true; + } + + //explicitly load endorsement credential through NVRAM + if(s_argv[i].compare("-ec_nvram") == 0) + { + ec_nvram = true; + } + + if(s_argv[i].compare("-trousers") == 0) + { + b_trousers = true; + } + } + if(i_success != 5) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + NIARL_Util_ByteBlob pcakblob(s_pcak); + NIARL_Util_ByteBlob aiklabel(s_aiklabel); + NIARL_Util_ByteBlob aikauth(s_aikauth); + NIARL_Util_ByteBlob ec(s_ec); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_aik = TSS_UUID_USK2; + uuid_aik.rgbNode[5] = (BYTE)i_keyindex; + uuid_aik.rgbNode[0] = 0x04; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_PLAIN, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//PRIVACY CA SECTION + TSS_HKEY pcak; + TSS_HPOLICY policy_pcak; + + if(b_debug) cerr << "PCAK Section" << endl; + if(b_log) clog << "PCAK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_SIZE_DEFAULT, &pcak); + if(b_debug) cerr << ' ' << result << " create pcak object" << endl; + if(b_log) cerr << ' ' << result << " create pcak object" << endl; + + result = Tspi_SetAttribData(pcak, TSS_TSPATTRIB_KEY_BLOB, TSS_TSPATTRIB_KEYBLOB_PUBLIC_KEY, pcakblob.size, pcakblob.blob); + if(b_debug) cerr << ' ' << result << " set pcak blob" << endl; + if(b_log) cerr << ' ' << result << " set pcak blob" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_pcak); + if(b_debug) cerr << ' ' << result << " create pcak policy" << endl; + if(b_log) cerr << ' ' << result << " create pcak policy" << endl; + + result = Tspi_Policy_SetSecret(policy_pcak, TSS_SECRET_MODE_PLAIN, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " set auth" << endl; + if(b_log) cerr << ' ' << result << " set auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_pcak, pcak); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//AIK OPERATIONS (NOT SET YET) + TSS_HKEY aik; + TSS_HPOLICY policy_aik; + UINT32 init_flags = TSS_KEY_TYPE_IDENTITY | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "AIK Section" << endl; + if(b_log) clog << "AIK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &aik); + if(b_debug) cerr << ' ' << result << " create aik object" << endl; + if(b_log) cerr << ' ' << result << " create aik object" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_aik); + if(b_debug) cerr << ' ' << result << " create aik policy" << endl; + if(b_log) cerr << ' ' << result << " create aik policy" << endl; + + result = Tspi_Policy_SetSecret(policy_aik, TSS_SECRET_MODE_PLAIN, aikauth.size, aikauth.blob); + if(b_debug) cerr << ' ' << result << " set aik auth" << endl; + if(b_log) cerr << ' ' << result << " set aik auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_aik, aik); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//ENDORSEMENT CREDENTIAL COMMANDS + if(ec_blob) + { + //explicitly load the endorsement credential from command line + result = Tspi_SetAttribData(tpm, TSS_TSPATTRIB_TPM_CREDENTIAL, TSS_TPMATTRIB_EKCERT, ec.size, ec.blob); + if(b_debug) cerr << ' ' << result << " load endorsement credential by command line" << endl; + if(b_log) cerr << ' ' << result << " load endorsement credential by command line" << endl; + } + else if(ec_nvram) + { + //NVSTORE SECTION + TSS_HNVSTORE nvstore; + UINT32 cred_size; + BYTE* cred_blob; + + if(b_debug) cerr << "NVStore Section" << endl; + if(b_log) clog << "NVStore Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_NV, NULL, &nvstore); + if(b_debug) cerr << ' ' << result << " create nvstore object" << endl; + if(b_log) cerr << ' ' << result << " create nvstore object" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, nvstore); + if(b_debug) cerr << ' ' << result << " assign owner auth" << endl; + if(b_log) cerr << ' ' << result << " assign owner auth" << endl; + + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_EKCert); + if(b_debug) cerr << " EK cert selected" << endl; + if(b_log) clog << " EK cert selected" << endl; + + if(b_trousers) + {//Trousers mode. Size cannot be automatically determined + if(b_debug) cerr << " Trousers mode activated" << endl; + if(b_log) clog << " Trousers mode activated" << endl; + + UINT32 counter = 0; + + cred_size = 10; //allow enough space to get DER x509 size header + result = Tspi_NV_ReadValue(nvstore, 0, &cred_size, &cred_blob); + + if((int)cred_blob[1] >= 128) //size is too big for [1] + { + counter = (int)cred_blob[1] - 128; + cred_size = 0; //reset cred size + + for(UINT32 i = 0; i < counter; i++) + { + cred_size *= 256; //base multiplier + cred_size += (int)cred_blob[2 + i]; //accumulator + } + } + else + { + cred_size = (int)cred_blob[1]; + } + + cred_size += 4; + + if(b_debug) cerr << " Credential size is " << cred_size << endl; + if(b_log) clog << " Credential size is " << cred_size << endl; + } + else + {//NTru mode + result = Tspi_GetAttribUint32(nvstore, TSS_TSPATTRIB_NV_DATASIZE, NULL, &cred_size); + if(b_debug) cerr << ' ' << result << " get nvstore size of " << cred_size << endl; + if(b_log) cerr << ' ' << result << " get nvstore size of " << cred_size << endl; + } + + result = Tspi_NV_ReadValue(nvstore, 0, &cred_size, &cred_blob); + if(b_debug) cerr << ' ' << result << " nv read" << endl; + if(b_log) cerr << ' ' << result << " nv read" << endl; + + //explicitly load the endorsement credential from NVRAM + result = Tspi_SetAttribData(tpm, TSS_TSPATTRIB_TPM_CREDENTIAL, TSS_TPMATTRIB_EKCERT, cred_size, cred_blob); + if(b_debug) cerr << ' ' << result << " load endorsement credential by NVRAM" << endl; + if(b_log) cerr << ' ' << result << " load endorsement credential by NVRAM" << endl; + + result = Tspi_Context_FreeMemory(context, cred_blob); + } + + +//COLLATE IDENTITY REQUEST + UINT32 idr_size; + BYTE* idr_blob; + + if(b_debug) cerr << "Collate Identity Request Section" << endl; + if(b_log) clog << "Collate Identity Request Section" << endl; + + result = Tspi_TPM_CollateIdentityRequest(tpm, srk, pcak, aiklabel.size, aiklabel.blob, aik, TSS_ALG_AES, &idr_size, &idr_blob); + if(b_debug) cerr << ' ' << result << " COLLATE IDENTITY" << endl; + if(b_log) cerr << ' ' << result << " COLLATE IDENTITY" << endl; + + if(result == 0) + { + for(UINT32 i = 0; i < idr_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)idr_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, idr_blob); + } + + +//OUTPUT AIK MODULUS AND BLOB + UINT32 mod_size; + UINT32 blob_size; + BYTE* mod_blob; + BYTE* blob_blob; + + if(b_debug) cerr << "AIK Output Section" << endl; + if(b_log) clog << "AIK Output Section" << endl; + + result = Tspi_GetAttribData(aik, TSS_TSPATTRIB_RSAKEY_INFO, TSS_TSPATTRIB_KEYINFO_RSA_MODULUS, &mod_size, &mod_blob); + if(b_debug) cerr << ' ' << result << " get modulus" << endl; + if(b_log) cerr << ' ' << result << " get modulus" << endl; + + if(result == 0) + { + if(!b_debug && !b_log) if(!b_debug && !b_log) cout << ' '; + + for(UINT32 i = 0; i < mod_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)mod_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, mod_blob); + } + + result = Tspi_GetAttribData(aik, TSS_TSPATTRIB_KEY_BLOB, TSS_TSPATTRIB_KEYBLOB_BLOB, &blob_size, &blob_blob); + if(b_debug) cerr << ' ' << result << " get key blob" << endl; + if(b_log) cerr << ' ' << result << " get key blob" << endl; + + if(result == 0) + { + if(!b_debug && !b_log) if(!b_debug && !b_log) cout << ' '; + + for(UINT32 i = 0; i < blob_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)blob_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, blob_blob); + } + + +//SAVE THE AIK + TSS_HKEY key_blank; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_SIZE_DEFAULT, &key_blank); + if(b_debug) cerr << ' ' << result << " create blank key" << endl; + if(b_log) cerr << ' ' << result << " create blank key" << endl; + + result = Tspi_Key_LoadKey(aik, srk); + if(b_debug) cerr << ' ' << result << " load the aik" << endl; + if(b_log) cerr << ' ' << result << " load the aik" << endl; + + result = Tspi_Context_RegisterKey(context, aik, TSS_PS_TYPE_SYSTEM, uuid_aik, TSS_PS_TYPE_SYSTEM, uuid_srk); + if(b_debug) cerr << ' ' << result << " register aik" << endl; + if(b_log) cerr << ' ' << result << " register aik" << endl; + return_code = result; + + if(result != 0) + { + result = Tspi_Context_UnregisterKey(context, TSS_PS_TYPE_SYSTEM, uuid_aik, &key_blank); + if(b_debug) cerr << ' ' << result << " unregister blank key" << endl; + if(b_log) cerr << ' ' << result << " unregister blank key" << endl; + + result = Tspi_Context_RegisterKey(context, aik, TSS_PS_TYPE_SYSTEM, uuid_aik, TSS_PS_TYPE_SYSTEM, uuid_srk); + if(b_debug) cerr << ' ' << result << " register aik" << endl; + if(b_log) cerr << ' ' << result << " register aik" << endl; + return_code = result; + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_tpm); + result = Tspi_Context_CloseObject(context, policy_aik); + result = Tspi_Context_CloseObject(context, policy_pcak); + result = Tspi_Context_CloseObject(context, aik); + result = Tspi_Context_CloseObject(context, pcak); + result = Tspi_Context_CloseObject(context, srk); + result = Tspi_Context_CloseObject(context, key_blank); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Activate Identity + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::activate_identity() +{ + if(b_help) + { + cout << "Activate Identity (" << i_mode << ") --- Creates an Attestation Identity Credential (AIC)" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -key_auth (hex blob, identity key authorization data)" << endl; + cout << " -asym (hex blob, CA asymmetric response)" << endl; + cout << " -sym (hex blob, CA symmetric response)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OUTPUTS" << endl; + cout << " attestation identity credential (AIC, hex blob)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string s_asym; + string s_sym; + string s_aikauth; + int i_keyindex = 0; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-asym") == 0) + { + if(++i >= i_argc) return; + s_asym = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-sym") == 0) + { + if(++i >= i_argc) return; + s_sym = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_aikauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success != 5) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + NIARL_Util_ByteBlob aikauth(s_aikauth); + NIARL_Util_ByteBlob ca_sym(s_sym); + NIARL_Util_ByteBlob ca_asym(s_asym); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_aik = TSS_UUID_USK2; + uuid_aik.rgbNode[5] = (BYTE)i_keyindex; + uuid_aik.rgbNode[0] = 0x04; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_PLAIN, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//AIK OPERATIONS (SET) + TSS_HKEY aik; + TSS_HPOLICY policy_aik; + UINT32 init_flags = TSS_KEY_TYPE_IDENTITY | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "AIK Section" << endl; + if(b_log) clog << "AIK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &aik); + if(b_debug) cerr << ' ' << result << " create aik object" << endl; + if(b_log) cerr << ' ' << result << " create aik object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_aik, &aik); + if(b_debug) cerr << ' ' << result << " get uuid" << endl; + if(b_log) cerr << ' ' << result << " get uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_aik); + if(b_debug) cerr << ' ' << result << " create aik policy" << endl; + if(b_log) cerr << ' ' << result << " create aik policy" << endl; + + result = Tspi_Policy_SetSecret(policy_aik, TSS_SECRET_MODE_PLAIN, aikauth.size, aikauth.blob); + if(b_debug) cerr << ' ' << result << " set aik auth" << endl; + if(b_log) cerr << ' ' << result << " set aik auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_aik, aik); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(aik, srk); + if(b_debug) cerr << ' ' << result << " load aik" << endl; + if(b_log) cerr << ' ' << result << " load aik" << endl; + + +//ACTIVATE IDENTITY + UINT32 aic_size; + BYTE* aic_blob; + + if(b_debug) cerr << "Activate Identity Section" << endl; + if(b_log) clog << "Activate Identity Section" << endl; + + result = Tspi_TPM_ActivateIdentity(tpm, aik, ca_asym.size, ca_asym.blob, ca_sym.size, ca_sym.blob, &aic_size, &aic_blob); + if(b_debug) cerr << ' ' << result << " ACTIVATE IDENTITY" << endl; + if(b_log) cerr << ' ' << result << " ACTIVATE IDENTITY" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < aic_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)aic_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, aic_blob); + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_tpm); + result = Tspi_Context_CloseObject(context, policy_aik); + result = Tspi_Context_CloseObject(context, aik); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Quote + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::quote() +{ + if(b_help) + { + cout << "Quote (" << i_mode << ") --- Provides a system integrity quote with signature" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -key_auth (hex blob, identity key authorization data)" << endl; + cout << " -nonce (hex blob, anti-replay nonce)" << endl; + cout << " -mask (hex string, controls PCR index selection)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OUTPUTS" << endl; + cout << " quote (hex blob, quote digest)" << endl; + cout << " signature (hex blob, quote signature)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_pcrs; + string s_aikauth; + string s_nonce; + int i_keyindex = 0; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-nonce") == 0) + { + if(++i >= i_argc) return; + s_nonce = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_aikauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-mask") == 0) + { + if(++i >= i_argc) return; + s_pcrs = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success != 4) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob aikauth(s_aikauth); + NIARL_Util_ByteBlob nonce(s_nonce); + NIARL_Util_Mask pcrmask(s_pcrs); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_aik = TSS_UUID_USK2; + uuid_aik.rgbNode[5] = (BYTE)i_keyindex; + uuid_aik.rgbNode[0] = 0x04; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//AIK OPERATIONS (SET) + TSS_HKEY aik; + TSS_HPOLICY policy_aik; + UINT32 init_flags = TSS_KEY_TYPE_IDENTITY | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "AIK Section" << endl; + if(b_log) clog << "AIK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &aik); + if(b_debug) cerr << ' ' << result << " create aik object" << endl; + if(b_log) cerr << ' ' << result << " create aik object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_aik, &aik); + if(b_debug) cerr << ' ' << result << " get uuid" << endl; + if(b_log) cerr << ' ' << result << " get uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_aik); + if(b_debug) cerr << ' ' << result << " create aik policy" << endl; + if(b_log) cerr << ' ' << result << " create aik policy" << endl; + + result = Tspi_Policy_SetSecret(policy_aik, TSS_SECRET_MODE_PLAIN, aikauth.size, aikauth.blob); + if(b_debug) cerr << ' ' << result << " set aik auth" << endl; + if(b_log) cerr << ' ' << result << " set aik auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_aik, aik); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(aik, srk); + if(b_debug) cerr << ' ' << result << " load aik" << endl; + if(b_log) cerr << ' ' << result << " load aik" << endl; + + +//PCR OPERATIONS + TSS_HPCRS pcr; + UINT32 pcr_size; + BYTE* pcr_blob; + + if(b_debug) cerr << "PCR Section" << endl; + if(b_log) clog << "PCR Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_PCRS, 0, &pcr); + if(b_debug) cerr << ' ' << result << " create pcr object" << endl; + if(b_log) cerr << ' ' << result << " create pcr object" << endl; + + for(UINT32 i = 0; i < pcrmask.size; i++) + { + result = Tspi_PcrComposite_SelectPcrIndex(pcr, pcrmask.index[i]); + if(b_debug) cerr << ' ' << result << " select composite index" << endl; + if(b_log) cerr << ' ' << result << " select composite index" << endl; + } + + +//QUOTE OPERATIONS + TSS_VALIDATION validation; + + if(b_debug) cerr << "Quote Section" << endl; + if(b_log) clog << "Quote Section" << endl; + + memset(&validation, 0, sizeof(TSS_VALIDATION)); + validation.versionInfo.bMajor = 0x01; + validation.versionInfo.bMinor = 0x02; + validation.versionInfo.bRevMajor = 0x01; + validation.versionInfo.bRevMinor = 0x25; + validation.ulExternalDataLength = sizeof(TSS_NONCE); + validation.rgbExternalData = nonce.blob; + + result = Tspi_TPM_Quote(tpm, aik, pcr, &validation); + if(b_debug) cerr << ' ' << result << " QUOTE" << endl; + if(b_log) cerr << ' ' << result << " QUOTE" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < pcrmask.size; i++) + { + result = Tspi_PcrComposite_GetPcrValue(pcr, pcrmask.index[i], &pcr_size, &pcr_blob); + if(b_debug) cerr << ' ' << result << " set pcr value" << endl; + if(b_log) cerr << ' ' << result << " set pcr value" << endl; + + for(UINT32 j = 0; j < pcr_size; j++) + cout << setw(2) << setfill('0') << setbase(16) << (int)pcr_blob[j]; + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, pcr_blob); + if(b_debug) cerr << ' ' << result << " clear dynamic array" << endl; + if(b_log) cerr << ' ' << result << " clear dynamic array" << endl; + } + + for(UINT32 i = 0; i < validation.ulExternalDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbExternalData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < validation.ulDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < validation.ulValidationDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbValidationData[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + } + + +//CLEANUP SECTION + result = Tspi_Context_FreeMemory(context, validation.rgbData); + result = Tspi_Context_FreeMemory(context, validation.rgbValidationData); + result = Tspi_Context_FreeMemory(context, validation.rgbExternalData); + + result = Tspi_Context_CloseObject(context, policy_aik); + result = Tspi_Context_CloseObject(context, aik); + result = Tspi_Context_CloseObject(context, srk); + result = Tspi_Context_CloseObject(context, pcr); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Create Revocable EK + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::create_revokable_ek() +{ + if(b_help) + { + cout << "Create Revocable EK (" << i_mode << ") --- Creates a revocable EK" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -reset (hex blob, reset authorization blob)" << endl; + cout << " -nonce (hex blob, anti-replay nonce)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OUTPUTS" << endl; + cout << " Validation data?" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +/******************** + MODE DISABLED +********************/ +throw ERROR_MODE_DISABLED; + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string s_nonce; + string s_reset; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-nonce") == 0) + { + if(++i >= i_argc) return; + s_nonce = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-reset") == 0) + { + if(++i >= i_argc) return; + s_reset = s_argv[i]; + i_success++; + } + } + if(i_success != 3) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + NIARL_Util_ByteBlob nonce(s_nonce); + NIARL_Util_ByteBlob reset(s_reset); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_PLAIN, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//REK SECTION + TSS_HKEY rek; + TSS_HPOLICY policy_rek; + + if(b_debug) cerr << "REK Section" << endl; + if(b_log) clog << "REK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_SIZE_DEFAULT, &rek); + if(b_debug) cerr << ' ' << result << " create rek object" << endl; + if(b_log) cerr << ' ' << result << " create rek object" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_rek); + if(b_debug) cerr << ' ' << result << " create rek policy" << endl; + if(b_log) cerr << ' ' << result << " create rek policy" << endl; + + result = Tspi_Policy_SetSecret(policy_rek, TSS_SECRET_MODE_PLAIN, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " set rek auth" << endl; + if(b_log) cerr << ' ' << result << " set rek auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_rek, rek); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//CREATE REVOCABLE EK + TSS_VALIDATION validation; + + if(b_debug) cerr << "Create REK Section" << endl; + if(b_log) clog << "Create REK Section" << endl; + + memset(&validation, 0, sizeof(TSS_VALIDATION)); + validation.versionInfo.bMajor = 0x01; + validation.versionInfo.bMinor = 0x02; + validation.versionInfo.bRevMajor = 0x01; + validation.versionInfo.bRevMinor = 0x25; + validation.ulExternalDataLength = sizeof(TSS_NONCE); + validation.rgbExternalData = nonce.blob; + + result = Tspi_TPM_CreateRevocableEndorsementKey(tpm, rek, &validation, &reset.size, &reset.blob); + if(b_debug) cerr << ' ' << result << " CREATE REK" << endl; + if(b_log) cerr << ' ' << result << " CREATE REK" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < validation.ulExternalDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbExternalData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < validation.ulDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < validation.ulValidationDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbValidationData[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + } + + +//CLEANUP SECTION + result = Tspi_Context_FreeMemory(context, validation.rgbData); + result = Tspi_Context_FreeMemory(context, validation.rgbValidationData); + result = Tspi_Context_FreeMemory(context, validation.rgbExternalData); + + result = Tspi_Context_CloseObject(context, policy_tpm); + result = Tspi_Context_CloseObject(context, policy_rek); + result = Tspi_Context_CloseObject(context, rek); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Revoke EK + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::revoke_ek() +{ + if(b_help) + { + cout << "Revoke EK (" << i_mode << ") --- Revokes a revocable EK" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -reset (hex blob, reset authorization blob)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +/******************** + MODE DISABLED +********************/ +throw ERROR_MODE_DISABLED; + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string s_reset; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-reset") == 0) + { + + if(++i >= i_argc) return; + s_reset = s_argv[i]; + i_success++; + } + } + if(i_success != 2) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + NIARL_Util_ByteBlob reset(s_reset); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_PLAIN, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//CREATE REVOCABLE EK + + if(b_debug) cerr << "Revoke REK Section" << endl; + if(b_log) clog << "Revoke REK Section" << endl; + + result = Tspi_TPM_RevokeEndorsementKey(tpm, reset.size, reset.blob); + if(b_debug) cerr << ' ' << result << " REVOKE REK" << endl; + if(b_log) cerr << ' ' << result << " REVOKE REK" << endl; + return_code = result; + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_tpm); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Create Key + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::create_key() +{ + if(b_help) + { + cout << "Create Key (" << i_mode << ") --- Creates and stores (no overwrite) a binding or signing key" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -key_type (string, sign or bind)" << endl; + cout << " -key_auth (hex blob, key authorization data)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + cout << " -pkcs (flag, switches encoding from OAEP to PKCS for more space)" << endl; + cout << " OUTPUTS" << endl; + cout << " modulus (hex blob, key modulus)" << endl; + cout << " key blob (hex blob, key blob)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string keytype; + string s_keyauth; + int i_keyindex = 0; + bool b_1024 = false; + bool b_pkcs = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-pkcs") == 0) + { + b_pkcs = true; + } + + if(s_argv[i].compare("-key_type") == 0) + { + if(++i >= i_argc) return; + keytype = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success != 3) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob keyauth(s_keyauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_key = TSS_UUID_USK2; + uuid_key.rgbNode[5] = (BYTE)i_keyindex; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//KEY OPERATIONS (NOT SET YET) + TSS_HKEY key; + TSS_HPOLICY policy_key; + UINT32 init_flags; + + if(b_debug) cerr << "Key Section" << endl; + if(b_log) clog << "Key Section" << endl; + + if(keytype.compare("bind") == 0) + { + //uuid_key.rgbNode[5] = 0x05; + uuid_key.rgbNode[0] = 0x05; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << " binding key selected" << endl; + if(b_log) cerr << " binding key selected" << endl; + } + else if(keytype.compare("sign") == 0) + { + //uuid_key.rgbNode[5] = 0x06; + uuid_key.rgbNode[0] = 0x06; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << " signing key selected" << endl; + if(b_log) cerr << " signing key selected" << endl; + } + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &key); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_key); + if(b_debug) cerr << ' ' << result << " create key policy" << endl; + if(b_log) cerr << ' ' << result << " create key policy" << endl; + + result = Tspi_Policy_SetSecret(policy_key, TSS_SECRET_MODE_PLAIN, keyauth.size, keyauth.blob); + if(b_debug) cerr << ' ' << result << " set key auth" << endl; + if(b_log) cerr << ' ' << result << " set key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_key, key); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + if(b_pkcs) + { + result = Tspi_SetAttribUint32(key, TSS_TSPATTRIB_KEY_INFO, TSS_TSPATTRIB_KEYINFO_ENCSCHEME, TSS_ES_RSAESPKCSV15); + if(b_debug) cerr << ' ' << result << " set encryption scheme to PKCS" << endl; + if(b_log) cerr << ' ' << result << " set encryption scheme to PKCS" << endl; + } + + +//CREATE KEY + UINT32 mod_size; + UINT32 blob_size; + BYTE* mod_blob; + BYTE* blob_blob; + + if(b_debug) cerr << "Create Key Section" << endl; + if(b_log) clog << "Create Key Section" << endl; + + result = Tspi_Key_CreateKey(key, srk, NULL); + if(b_debug) cerr << ' ' << result << " CREATE KEY" << endl; + if(b_log) cerr << ' ' << result << " CREATE KEY" << endl; + + result = Tspi_GetAttribData(key, TSS_TSPATTRIB_RSAKEY_INFO, TSS_TSPATTRIB_KEYINFO_RSA_MODULUS, &mod_size, &mod_blob); + if(b_debug) cerr << ' ' << result << " get modulus" << endl; + if(b_log) cerr << ' ' << result << " get modulus" << endl; + + if(result == 0) + { + for(UINT32 i = 0; i < mod_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)mod_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, mod_blob); + } + + result = Tspi_GetAttribData(key, TSS_TSPATTRIB_KEY_BLOB, TSS_TSPATTRIB_KEYBLOB_BLOB, &blob_size, &blob_blob); + if(b_debug) cerr << ' ' << result << " get key blob" << endl; + if(b_log) cerr << ' ' << result << " get key blob" << endl; + + if(result == 0) + { + if(!b_debug && !b_log) if(!b_debug && !b_log) cout << ' '; + + for(UINT32 i = 0; i < blob_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)blob_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, blob_blob); + } + + +//SAVE THE KEY + result = Tspi_Key_LoadKey(key, srk); + if(b_debug) cerr << ' ' << result << " load the new key" << endl; + if(b_log) cerr << ' ' << result << " load the new key" << endl; + + result = Tspi_Context_RegisterKey(context, key, TSS_PS_TYPE_SYSTEM, uuid_key, TSS_PS_TYPE_SYSTEM, uuid_srk); + if(b_debug) cerr << ' ' << result << " register new key" << endl; + if(b_log) cerr << ' ' << result << " register new key" << endl; + return_code = result; + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_key); + result = Tspi_Context_CloseObject(context, key); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Set Key + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::set_key() +{ + if(b_help) + { + cout << "Set Key (" << i_mode << ") --- Creates and stores (no overwrite) a signing, binding, or identity via a key blob" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -key_type (string, sign or bind or identity)" << endl; + cout << " -key_auth (hex blob, key authorization data)" << endl; + cout << " -key_blob (hex blob, key blob)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string keytype; + string s_keyauth; + string s_keyblob; + int i_keyindex = 0; + bool b_1024 = false; + bool b_pkcs = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-pkcs") == 0) + { + b_pkcs = true; + } + + if(s_argv[i].compare("-key_type") == 0) + { + if(++i >= i_argc) return; + keytype = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_blob") == 0) + { + if(++i >= i_argc) return; + s_keyblob = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success != 4) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob keyauth(s_keyauth); + NIARL_Util_ByteBlob keyblob(s_keyblob); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_key = TSS_UUID_USK2; + uuid_key.rgbNode[5] = (BYTE)i_keyindex; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//KEY OPERATIONS (NOT SET YET) + TSS_HKEY key; + TSS_HPOLICY policy_key; + UINT32 init_flags; + + if(b_debug) cerr << "Key Section" << endl; + if(b_log) clog << "Key Section" << endl; + + if(keytype.compare("identity") == 0) + { + //uuid_key.rgbNode[5] = 0x04; + uuid_key.rgbNode[0] = 0x04; + init_flags = TSS_KEY_TYPE_IDENTITY | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + if(b_debug) cerr << "aik selected" << endl; + if(b_log) clog << "aik selected" << endl; + } + else if(keytype.compare("bind") == 0) + { + //uuid_key.rgbNode[5] = 0x05; + uuid_key.rgbNode[0] = 0x05; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << " binding key selected" << endl; + if(b_log) cerr << " binding key selected" << endl; + } + else if(keytype.compare("sign") == 0) + { + //uuid_key.rgbNode[5] = 0x06; + uuid_key.rgbNode[0] = 0x06; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << " signing key selected" << endl; + if(b_log) cerr << " signing key selected" << endl; + } + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &key); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_SetAttribData(key, TSS_TSPATTRIB_KEY_BLOB, TSS_TSPATTRIB_KEYBLOB_BLOB, keyblob.size, keyblob.blob); + if(b_debug) cerr << ' ' << result << " set key blob" << endl; + if(b_log) cerr << ' ' << result << " set key blob" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_key); + if(b_debug) cerr << ' ' << result << " create key policy" << endl; + if(b_log) cerr << ' ' << result << " create key policy" << endl; + + result = Tspi_Policy_SetSecret(policy_key, TSS_SECRET_MODE_PLAIN, keyauth.size, keyauth.blob); + if(b_debug) cerr << ' ' << result << " set key auth" << endl; + if(b_log) cerr << ' ' << result << " set key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_key, key); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + if(b_pkcs) + { + result = Tspi_SetAttribUint32(key, TSS_TSPATTRIB_KEY_INFO, TSS_TSPATTRIB_KEYINFO_ENCSCHEME, TSS_ES_RSAESPKCSV15); + if(b_debug) cerr << ' ' << result << " set encryption scheme to PKCS" << endl; + if(b_log) cerr << ' ' << result << " set encryption scheme to PKCS" << endl; + } + + +//SAVE THE KEY + result = Tspi_Key_LoadKey(key, srk); + if(b_debug) cerr << ' ' << result << " load the new key" << endl; + if(b_log) cerr << ' ' << result << " load the new key" << endl; + + result = Tspi_Context_RegisterKey(context, key, TSS_PS_TYPE_SYSTEM, uuid_key, TSS_PS_TYPE_SYSTEM, uuid_srk); + if(b_debug) cerr << ' ' << result << " register new key" << endl; + if(b_log) cerr << ' ' << result << " register new key" << endl; + return_code = result; + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_key); + result = Tspi_Context_CloseObject(context, key); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Get Key + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::get_key() +{ + if(b_help) + { + cout << "Get Key (" << i_mode << ") --- Gets the modulus and blob of an identity, signing, or binding key" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -key_type (string, sign or bind or identity or ek)" << endl; + cout << " EK PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -nonce (hex blob, anti-replay nonce, REQUIRED FOR EK)" << endl; + cout << " BIND, SIGN, AND AIK PARAMETERS" << endl; + cout << " -key_index (integer, index number for key, REQUIRED FOR KEY)" << endl; + cout << " -key_auth (hex blob, key authorization data, owner auth for ek)" << endl; + cout << " OPTIONAL PARAMETERS FOR BIND AND SIGN" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + cout << " OUTPUTS" << endl; + cout << " modulus (hex blob, key modulus)" << endl; + cout << " key blob (hex blob, key blob)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string keytype; + string s_keyauth; + string s_nonce; + int i_keyindex = 0; + bool b_1024 = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_type") == 0) + { + if(++i >= i_argc) return; + keytype = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-nonce") == 0) + { + if(++i >= i_argc) return; + s_nonce = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success < 3) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + NIARL_Util_ByteBlob keyauth(s_keyauth); + NIARL_Util_ByteBlob nonce(s_nonce); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_key = TSS_UUID_USK2; + uuid_key.rgbNode[5] = (BYTE)i_keyindex; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + if(keytype.compare("ek") == 0) + { //ek only commands + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_PLAIN, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + } + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//KEY OPERATIONS (SET) + TSS_VALIDATION validation; + TSS_HKEY key; + TSS_HPOLICY policy_key; + UINT32 init_flags; + + if(b_debug) cerr << "Key Section" << endl; + if(b_log) clog << "Key Section" << endl; + + if(keytype.compare("identity") == 0) + { + //uuid_key.rgbNode[5] = 0x04; + uuid_key.rgbNode[0] = 0x04; + init_flags = TSS_KEY_TYPE_IDENTITY | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + if(b_debug) cerr << "aik selected" << endl; + if(b_log) clog << "aik selected" << endl; + } + else if(keytype.compare("bind") == 0) + { + //uuid_key.rgbNode[5] = 0x05; + uuid_key.rgbNode[0] = 0x05; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "binding key selected" << endl; + if(b_log) clog << "binding key selected" << endl; + } + else if(keytype.compare("sign") == 0) + { + //uuid_key.rgbNode[5] = 0x06; + uuid_key.rgbNode[0] = 0x06; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "signing key selected" << endl; + if(b_log) clog << "signing key selected" << endl; + } + + if(keytype.compare("ek") == 0) + { //ek only commands + memset(&validation, 0, sizeof(TSS_VALIDATION)); + validation.versionInfo.bMajor = 0x01; + validation.versionInfo.bMinor = 0x02; + validation.versionInfo.bRevMajor = 0x01; + validation.versionInfo.bRevMinor = 0x25; + validation.ulExternalDataLength = sizeof(TSS_NONCE); + validation.rgbExternalData = nonce.blob; + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_SIZE_DEFAULT, &key); + if(b_debug) cerr << ' ' << result << " create ek object" << endl; + if(b_log) cerr << ' ' << result << " create ek object" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, key); + if(b_debug) cerr << ' ' << result << " assign owner auth to ek" << endl; + if(b_log) cerr << ' ' << result << " assign owner auth to ek" << endl; + + result = Tspi_TPM_GetPubEndorsementKey(tpm, true, &validation, &key); + if(b_debug) cerr << ' ' << result << " get public ek" << endl; + if(b_log) cerr << ' ' << result << " get public ek" << endl; + } + else + { //commands for aik, signing, and binding keys + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &key); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_key, &key); + if(b_debug) cerr << ' ' << result << " load key by uuid" << endl; + if(b_log) cerr << ' ' << result << " load key by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_key); + if(b_debug) cerr << ' ' << result << " create key policy" << endl; + if(b_log) cerr << ' ' << result << " create key policy" << endl; + + result = Tspi_Policy_SetSecret(policy_key, TSS_SECRET_MODE_PLAIN, keyauth.size, keyauth.blob); + if(b_debug) cerr << ' ' << result << " set key auth" << endl; + if(b_log) cerr << ' ' << result << " set key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_key, key); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(key, srk); + if(b_debug) cerr << ' ' << result << " load key" << endl; + if(b_log) cerr << ' ' << result << " load key" << endl; + } + + +//GET KEY + UINT32 mod_size; + UINT32 blob_size; + BYTE* mod_blob; + BYTE* blob_blob; + + if(b_debug) cerr << "Get Key Section" << endl; + if(b_log) clog << "Get Key Section" << endl; + + result = Tspi_GetAttribData(key, TSS_TSPATTRIB_RSAKEY_INFO, TSS_TSPATTRIB_KEYINFO_RSA_MODULUS, &mod_size, &mod_blob); + if(b_debug) cerr << ' ' << result << " get modulus" << endl; + if(b_log) cerr << ' ' << result << " get modulus" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < mod_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)mod_blob[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) cerr << endl; + + result = Tspi_Context_FreeMemory(context, mod_blob); + } + + if(keytype.compare("ek") != 0) + { + result = Tspi_GetAttribData(key, TSS_TSPATTRIB_KEY_BLOB, TSS_TSPATTRIB_KEYBLOB_BLOB, &blob_size, &blob_blob); + if(b_debug) cerr << ' ' << result << " get key blob" << endl; + if(b_log) cerr << ' ' << result << " get key blob" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < blob_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)blob_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, blob_blob); + } + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_tpm); + result = Tspi_Context_CloseObject(context, policy_key); + result = Tspi_Context_CloseObject(context, key); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Clear Key + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::clear_key() +{ + if(b_help) + { + cout << "Clear Key (" << i_mode << ") --- Clears an existing identity, signing, or binding key" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -key_type (string, sign or bind or identity)" << endl; + cout << " -key_auth (hex blob, key authorization data)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string keytype; + string s_keyauth; + int i_keyindex = 0; + bool b_1024 = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-key_type") == 0) + { + if(++i >= i_argc) return; + keytype = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success != 3) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob keyauth(s_keyauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_key = TSS_UUID_USK2; + uuid_key.rgbNode[5] = (BYTE)i_keyindex; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//KEY OPERATIONS (SET) + TSS_HKEY key; + TSS_HPOLICY policy_key; + UINT32 init_flags; + + if(b_debug) cerr << "Key Section" << endl; + if(b_log) clog << "Key Section" << endl; + + if(keytype.compare("identity") == 0) + { + //uuid_key.rgbNode[5] = 0x04; + uuid_key.rgbNode[0] = 0x04; + init_flags = TSS_KEY_TYPE_IDENTITY | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + if(b_debug) cerr << "aik selected" << endl; + if(b_log) clog << "aik selected" << endl; + } + else if(keytype.compare("bind") == 0) + { + //uuid_key.rgbNode[5] = 0x05; + uuid_key.rgbNode[0] = 0x05; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "binding key selected" << endl; + if(b_log) clog << "binding key selected" << endl; + } + else if(keytype.compare("sign") == 0) + { + //uuid_key.rgbNode[5] = 0x06; + uuid_key.rgbNode[0] = 0x06; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "signing key selected" << endl; + if(b_log) clog << "signing key selected" << endl; + } + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &key); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_key, &key); + if(b_debug) cerr << ' ' << result << " load key by uuid" << endl; + if(b_log) cerr << ' ' << result << " load key by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_key); + if(b_debug) cerr << ' ' << result << " create key policy" << endl; + if(b_log) cerr << ' ' << result << " create key policy" << endl; + + result = Tspi_Policy_SetSecret(policy_key, TSS_SECRET_MODE_PLAIN, keyauth.size, keyauth.blob); + if(b_debug) cerr << ' ' << result << " set key auth" << endl; + if(b_log) cerr << ' ' << result << " set key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_key, key); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(key, srk); + if(b_debug) cerr << ' ' << result << " load key" << endl; + if(b_log) cerr << ' ' << result << " load key" << endl; + + +//CLEAR KEY + TSS_HKEY key_blank; + + if(b_debug) cerr << "Clear Key Section" << endl; + if(b_log) clog << "Clear Key Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_SIZE_DEFAULT, &key_blank); + if(b_debug) cerr << ' ' << result << " create blank key" << endl; + if(b_log) cerr << ' ' << result << " create blank key" << endl; + + result = Tspi_Context_UnregisterKey(context, TSS_PS_TYPE_SYSTEM, uuid_key, &key_blank); + if(b_debug) cerr << ' ' << result << " UNREGISTER" << endl; + if(b_log) cerr << ' ' << result << " UNREGISTER" << endl; + return_code = result; + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_key); + result = Tspi_Context_CloseObject(context, key); + result = Tspi_Context_CloseObject(context, key_blank); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Set Credential + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::set_credential() +{ + if(b_help) + { + cout << "Set Credential (" << i_mode << ") --- Sets a TPM credential (no overwrite)" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -cred_type (string, EC or CC or PC or PCC)" << endl; + cout << " -blob (hex blob, credential)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string s_credtype; + string s_blob; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-cred_type") == 0) + { + if(++i >= i_argc) return; + s_credtype = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-blob") == 0) + { + if(++i >= i_argc) return; + s_blob = s_argv[i]; + i_success++; + } + } + if(i_success != 3) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + NIARL_Util_ByteBlob credential(s_blob); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_PLAIN, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//NVSTORE SECTION + TSS_HNVSTORE nvstore; + + if(b_debug) cerr << "NVStore Section" << endl; + if(b_log) clog << "NVStore Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_NV, NULL, &nvstore); + if(b_debug) cerr << ' ' << result << " create nvstore object" << endl; + if(b_log) cerr << ' ' << result << " create nvstore object" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, nvstore); + if(b_debug) cerr << ' ' << result << " assign owner auth" << endl; + if(b_log) cerr << ' ' << result << " assign owner auth" << endl; + + if(s_credtype.compare("EC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_EKCert); + if(b_debug) cerr << " EK cert selected" << endl; + if(b_log) clog << " EK cert selected" << endl; + } + + else if(s_credtype.compare("CC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_TPM_CC); + if(b_debug) cerr << " Conformance cert selected" << endl; + if(b_log) clog << " Conformance cert selected" << endl; + } + + else if(s_credtype.compare("PC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_PlatformCert); + if(b_debug) cerr << " Platform cert selected" << endl; + if(b_log) clog << " Platform cert selected" << endl; + } + + else if(s_credtype.compare("PCC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_Platform_CC); + if(b_debug) cerr << "Platform Conformance cert selected" << endl; + if(b_log) clog << "Platform Conformance cert selected" << endl; + } + + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_PERMISSIONS, NULL, TPM_NV_PER_OWNERREAD | TPM_NV_PER_OWNERWRITE); + if(b_debug) cerr << ' ' << result << " set nvstore permissions" << endl; + if(b_log) cerr << ' ' << result << " set nvstore permissions" << endl; + + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_DATASIZE, NULL, credential.size); + if(b_debug) cerr << ' ' << result << " set nvstore size" << endl; + if(b_log) cerr << ' ' << result << " set nvstore size" << endl; + + result = Tspi_NV_DefineSpace(nvstore, NULL, NULL); + if(b_debug) cerr << ' ' << result << " define space" << endl; + if(b_log) cerr << ' ' << result << " define space" << endl; + + result = Tspi_NV_WriteValue(nvstore, 0, credential.size, credential.blob); + if(b_debug) cerr << ' ' << result << " nv write" << endl; + if(b_log) cerr << ' ' << result << " nv write" << endl; + return_code = result; + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_tpm); + result = Tspi_Context_CloseObject(context, nvstore); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Get Credential + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::get_credential() +{ + if(b_help) + { + cout << "Get Credential (" << i_mode << ") --- Gets an existing TPM credential" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -cred_type (string, EC or CC or PC or PCC)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -trousers (flag, manually determines credential size from DER x509 size header)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string s_credtype; + bool b_trousers = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-cred_type") == 0) + { + if(++i >= i_argc) return; + s_credtype = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-trousers") == 0) + { + b_trousers = true; + } + } + if(i_success != 2) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_PLAIN, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//NVSTORE SECTION + TSS_HNVSTORE nvstore; + UINT32 cred_size; + BYTE* cred_blob; + + if(b_debug) cerr << "NVStore Section" << endl; + if(b_log) clog << "NVStore Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_NV, NULL, &nvstore); + if(b_debug) cerr << ' ' << result << " create nvstore object" << endl; + if(b_log) cerr << ' ' << result << " create nvstore object" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, nvstore); + if(b_debug) cerr << ' ' << result << " assign owner auth" << endl; + if(b_log) cerr << ' ' << result << " assign owner auth" << endl; + + if(s_credtype.compare("EC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_EKCert); + if(b_debug) cerr << " EK cert selected" << endl; + if(b_log) clog << " EK cert selected" << endl; + } + + else if(s_credtype.compare("CC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_TPM_CC); + if(b_debug) cerr << " Conformance cert selected" << endl; + if(b_log) clog << " Conformance cert selected" << endl; + } + + else if(s_credtype.compare("PC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_PlatformCert); + if(b_debug) cerr << " Platform cert selected" << endl; + if(b_log) clog << " Platform cert selected" << endl; + } + + else if(s_credtype.compare("PCC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_Platform_CC); + if(b_debug) cerr << " Platform Conformance cert selected" << endl; + if(b_log) clog << " Platform Conformance cert selected" << endl; + } + + if(b_trousers) + {//Trousers mode. Size cannot be automatically determined + if(b_debug) cerr << " Trousers mode activated" << endl; + if(b_log) clog << " Trousers mode activated" << endl; + + UINT32 counter = 0; + + cred_size = 10; //allow enough space to get DER x509 size header + result = Tspi_NV_ReadValue(nvstore, 0, &cred_size, &cred_blob); + + if((int)cred_blob[1] >= 128) //size is too big for [1] + { + counter = (int)cred_blob[1] - 128; + cred_size = 0; //reset cred size + + for(UINT32 i = 0; i < counter; i++) + { + cred_size *= 256; //base multiplier + cred_size += (int)cred_blob[2 + i]; //accumulator + } + } + else + { + cred_size = (int)cred_blob[1]; + } + + cred_size += 4; + + if(b_debug) cerr << " Credential size is " << cred_size << endl; + if(b_log) clog << " Credential size is " << cred_size << endl; + } + else + {//NTru mode + result = Tspi_GetAttribUint32(nvstore, TSS_TSPATTRIB_NV_DATASIZE, NULL, &cred_size); + if(b_debug) cerr << ' ' << result << " get nvstore size of " << cred_size << endl; + if(b_log) cerr << ' ' << result << " get nvstore size of " << cred_size << endl; + } + + result = Tspi_NV_ReadValue(nvstore, 0, &cred_size, &cred_blob); + if(b_debug) cerr << ' ' << result << " nv read" << endl; + if(b_log) cerr << ' ' << result << " nv read" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < cred_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)cred_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, cred_blob); + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_tpm); + result = Tspi_Context_CloseObject(context, nvstore); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Clear Credential + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::clear_credential() +{ + if(b_help) + { + cout << "Clear Credential (" << i_mode << ") --- Clears an existing TPM credential" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -cred_type (string, EC or CC or PC or PCC)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string s_credtype; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-cred_type") == 0) + { + if(++i >= i_argc) return; + s_credtype = s_argv[i]; + i_success++; + } + } + if(i_success != 2) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_PLAIN, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//NVSTORE SECTION + TSS_HNVSTORE nvstore; + + if(b_debug) cerr << "NVStore Section" << endl; + if(b_log) clog << "NVStore Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_NV, NULL, &nvstore); + if(b_debug) cerr << ' ' << result << " create nvstore object" << endl; + if(b_log) cerr << ' ' << result << " create nvstore object" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, nvstore); + if(b_debug) cerr << ' ' << result << " assign owner auth" << endl; + if(b_log) cerr << ' ' << result << " assign owner auth" << endl; + + if(s_credtype.compare("EC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_EKCert); + if(b_debug) cerr << " EK cert selected" << endl; + if(b_log) clog << " EK cert selected" << endl; + } + + else if(s_credtype.compare("CC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_TPM_CC); + if(b_debug) cerr << " Conformance cert selected" << endl; + if(b_log) clog << " Conformance cert selected" << endl; + } + + else if(s_credtype.compare("PC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_PlatformCert); + if(b_debug) cerr << " Platform cert selected" << endl; + if(b_log) clog << " Platform cert selected" << endl; + } + + else if(s_credtype.compare("PCC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_Platform_CC); + if(b_debug) cerr << " Platform Conformance cert selected" << endl; + if(b_log) clog << " Platform Conformance cert selected" << endl; + } + + result = Tspi_NV_ReleaseSpace(nvstore); + if(b_debug) cerr << ' ' << result << " nv release" << endl; + if(b_log) cerr << ' ' << result << " nv release" << endl; + return_code = result; + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_tpm); + result = Tspi_Context_CloseObject(context, nvstore); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Seal + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::seal() +{ + if(b_help) + { + cout << "Seal (" << i_mode << ") --- Encrypts data based on machine state" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -blob (hex blob, data to encrypt)" << endl; + cout << " -blob_auth (hex blob, data blob authorization data)" << endl; + cout << " -mask (hex string, controls PCR index selection)" << endl; + cout << " OUTPUTS" << endl; + cout << " sealed data blob (hex blob, encrypted blob)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_blob; + string s_pcrs; + string s_encauth; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-blob") == 0) + { + if(++i >= i_argc) return; + s_blob = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-mask") == 0) + { + if(++i >= i_argc) return; + s_pcrs = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-blob_auth") == 0) + { + if(++i >= i_argc) return; + s_encauth = s_argv[i]; + i_success++; + } + } + if(i_success != 3) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob datablob(s_blob); + NIARL_Util_Mask pcrmask(s_pcrs); + NIARL_Util_ByteBlob encauth(s_encauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//ENCDATA SECTION + TSS_HENCDATA encdata; + TSS_HPOLICY policy_encdata; + + if(b_debug) cerr << "EncData Section" << endl; + if(b_log) clog << "EncData Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_ENCDATA, TSS_ENCDATA_SEAL, &encdata); + if(b_debug) cerr << ' ' << result << " create encdata" << endl; + if(b_log) cerr << ' ' << result << " create encdata" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_encdata); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_encdata, TSS_SECRET_MODE_PLAIN, encauth.size, encauth.blob); + if(b_debug) cerr << ' ' << result << " encdata auth" << endl; + if(b_log) cerr << ' ' << result << " encdata auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_encdata, encdata); + if(b_debug) cerr << ' ' << result << " assign encdata authorization" << endl; + if(b_log) cerr << ' ' << result << " assign encdata authorization" << endl; + + +//PCR OPERATIONS + TSS_HPCRS pcr; + UINT32 pcr_size; + BYTE* pcr_blob; + + if(b_debug) cerr << "PCR Section" << endl; + if(b_log) clog << "PCR Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_PCRS, 0, &pcr); + if(b_debug) cerr << ' ' << result << " create pcr object" << endl; + if(b_log) cerr << ' ' << result << " create pcr object" << endl; + + for(UINT32 i = 0; i < pcrmask.size; i++) + { + result = Tspi_TPM_PcrRead(tpm, pcrmask.index[i], &pcr_size, &pcr_blob); + if(b_debug) cerr << ' ' << result << " read pcr index " << pcrmask.index[i] << endl; + if(b_log) cerr << ' ' << result << " read pcr index " << pcrmask.index[i] << endl; + + result = Tspi_PcrComposite_SelectPcrIndex(pcr, pcrmask.index[i]); + if(b_debug) cerr << ' ' << result << " select composite index" << endl; + if(b_log) cerr << ' ' << result << " select composite index" << endl; + + result = Tspi_PcrComposite_SetPcrValue(pcr, pcrmask.index[i], pcr_size, pcr_blob); + if(b_debug) cerr << ' ' << result << " set pcr value" << endl; + if(b_log) cerr << ' ' << result << " set pcr value" << endl; + +// for(UINT32 j = 0; j < pcr_size; j++) +// cout << setw(2) << setfill('0') << setbase(16) << (int)pcr_blob[j]; +// if(b_debug) cerr << endl; +// if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, pcr_blob); + if(b_debug) cerr << ' ' << result << " clear dynamic array" << endl; + if(b_log) cerr << ' ' << result << " clear dynamic array" << endl; + } + + +//SEAL OPERATIONS + UINT32 enc_size; + BYTE* enc_blob; + + if(b_debug) cerr << "Seal Section" << endl; + if(b_log) clog << "Seal Section" << endl; + + result = Tspi_Data_Seal(encdata, srk, datablob.size, datablob.blob, pcr); + if(b_debug) cerr << ' ' << result << " SEAL" << endl; + if(b_log) cerr << ' ' << result << " SEAL" << endl; + return_code = result; + + if(result == 0) + { + result = Tspi_GetAttribData(encdata, TSS_TSPATTRIB_ENCDATA_BLOB, TSS_TSPATTRIB_ENCDATABLOB_BLOB, &enc_size, &enc_blob); + if(b_debug) cerr << ' ' << result << " get sealed blob" << endl; + if(b_log) cerr << ' ' << result << " get sealed blob" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < enc_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)enc_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, enc_blob); + } + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_encdata); + result = Tspi_Context_CloseObject(context, encdata); + result = Tspi_Context_CloseObject(context, srk); + result = Tspi_Context_CloseObject(context, pcr); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Unseal + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::unseal() +{ + if(b_help) + { + cout << "Unseal (" << i_mode << ") --- Decrypts data based on machine state" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -blob (hex blob, data to decrypt)" << endl; + cout << " -blob_auth (hex blob, data blob authorization data)" << endl; + cout << " OUTPUTS" << endl; + cout << " unsealed data blob (hex blob, decrypted data)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_blob; + string s_encauth; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-blob") == 0) + { + if(++i >= i_argc) return; + s_blob = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-blob_auth") == 0) + { + if(++i >= i_argc) return; + s_encauth = s_argv[i]; + i_success++; + } + } + if(i_success != 2) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob datablob(s_blob); + NIARL_Util_ByteBlob encauth(s_encauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//ENCDATA SECTION + TSS_HENCDATA encdata; + TSS_HPOLICY policy_encdata; + + if(b_debug) cerr << "EncData Section" << endl; + if(b_log) clog << "EncData Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_ENCDATA, TSS_ENCDATA_SEAL, &encdata); + if(b_debug) cerr << ' ' << result << " create encdata" << endl; + if(b_log) cerr << ' ' << result << " create encdata" << endl; + + result = Tspi_SetAttribData(encdata, TSS_TSPATTRIB_ENCDATA_BLOB, TSS_TSPATTRIB_ENCDATABLOB_BLOB, datablob.size, datablob.blob); + if(b_debug) cerr << ' ' << result << " load data blob" << endl; + if(b_log) cerr << ' ' << result << " load data blob" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_encdata); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_encdata, TSS_SECRET_MODE_PLAIN, encauth.size, encauth.blob); + if(b_debug) cerr << ' ' << result << " encdata auth" << endl; + if(b_log) cerr << ' ' << result << " encdata auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_encdata, encdata); + if(b_debug) cerr << ' ' << result << " assign encdata authorization" << endl; + if(b_log) cerr << ' ' << result << " assign encdata authorization" << endl; + + +//UNSEAL OPERATIONS + UINT32 enc_size; + BYTE* enc_blob; + + if(b_debug) cerr << "Unseal Section" << endl; + if(b_log) clog << "Unseal Section" << endl; + + result = Tspi_Data_Unseal(encdata, srk, &enc_size, &enc_blob); + if(b_debug) cerr << ' ' << result << " UNSEAL" << endl; + if(b_log) cerr << ' ' << result << " UNSEAL" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < enc_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)enc_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, enc_blob); + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_encdata); + result = Tspi_Context_CloseObject(context, encdata); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Bind + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::bind() +{ + if(b_help) + { + cout << "Bind (" << i_mode << ") --- Encrypts data based on a binding key" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -blob (hex blob, data to encrypt)" << endl; + cout << " -blob_auth (hex blob, data blob authorization data)" << endl; + cout << " -key_auth (hex blob, binding key authorization data)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + cout << " OUTPUTS" << endl; + cout << " binded data blob (hex blob, encrypted data)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_blob; + string s_keyauth; + string s_encauth; + int i_keyindex = 0; + bool b_1024 = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-blob") == 0) + { + if(++i >= i_argc) return; + s_blob = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + + if(s_argv[i].compare("-blob_auth") == 0) + { + if(++i >= i_argc) return; + s_encauth = s_argv[i]; + i_success++; + } + } + if(i_success != 4) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob datablob(s_blob); + NIARL_Util_ByteBlob bindauth(s_keyauth); + NIARL_Util_ByteBlob encauth(s_encauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_bind = TSS_UUID_USK2; + uuid_bind.rgbNode[5] = (BYTE)i_keyindex; + uuid_bind.rgbNode[0] = 0x05; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//BIND OPERATIONS (SET) + TSS_HKEY bind; + TSS_HPOLICY policy_bind; + UINT32 init_flags; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "Bind Key Section" << endl; + if(b_log) clog << "Bind Key Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &bind); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_bind, &bind); + if(b_debug) cerr << ' ' << result << " load by UUID" << endl; + if(b_log) cerr << ' ' << result << " load by UUID" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_bind); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_bind, TSS_SECRET_MODE_PLAIN, bindauth.size, bindauth.blob); + if(b_debug) cerr << ' ' << result << " key auth" << endl; + if(b_log) cerr << ' ' << result << " key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_bind, bind); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(bind, srk); + if(b_debug) cerr << ' ' << result << " load key" << endl; + if(b_log) cerr << ' ' << result << " load key" << endl; + + +//ENCDATA SECTION + TSS_HENCDATA encdata; + TSS_HPOLICY policy_encdata; + + if(b_debug) cerr << "EncData Section" << endl; + if(b_log) clog << "EncData Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_ENCDATA, TSS_ENCDATA_BIND, &encdata); + if(b_debug) cerr << ' ' << result << " create encdata" << endl; + if(b_log) cerr << ' ' << result << " create encdata" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_encdata); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_encdata, TSS_SECRET_MODE_PLAIN, encauth.size, encauth.blob); + if(b_debug) cerr << ' ' << result << " encdata auth" << endl; + if(b_log) cerr << ' ' << result << " encdata auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_encdata, encdata); + if(b_debug) cerr << ' ' << result << " assign encdata authorization" << endl; + if(b_log) cerr << ' ' << result << " assign encdata authorization" << endl; + + +//BIND OPERATIONS + UINT32 enc_size; + BYTE* enc_blob; + + if(b_debug) cerr << "Bind Section" << endl; + if(b_log) clog << "Bind Section" << endl; + + result = Tspi_Data_Bind(encdata, bind, datablob.size, datablob.blob); + if(b_debug) cerr << ' ' << result << " BIND" << endl; + if(b_log) cerr << ' ' << result << " BIND" << endl; + return_code = result; + + if(result == 0) + { + result = Tspi_GetAttribData(encdata, TSS_TSPATTRIB_ENCDATA_BLOB, TSS_TSPATTRIB_ENCDATABLOB_BLOB, &enc_size, &enc_blob); + if(b_debug) cerr << ' ' << result << " get bound data blob" << endl; + if(b_log) cerr << ' ' << result << " get bound data blob" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < enc_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)enc_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, enc_blob); + } + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_bind); + result = Tspi_Context_CloseObject(context, bind); + result = Tspi_Context_CloseObject(context, policy_encdata); + result = Tspi_Context_CloseObject(context, encdata); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Unbind + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::unbind() +{ + if(b_help) + { + cout << "Unbind (" << i_mode << ") --- Decrypts data based on a binding key" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -blob (hex blob, data to decrypt)" << endl; + cout << " -blob_auth (hex blob, data blob authorization data)" << endl; + cout << " -key_auth (hex blob, binding key authorization data)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + cout << " OUTPUTS" << endl; + cout << " unbound data blob (hex blob, unencrypted data)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_blob; + string s_keyauth; + string s_encauth; + int i_keyindex = 0; + bool b_1024 = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-blob") == 0) + { + if(++i >= i_argc) return; + s_blob = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + + if(s_argv[i].compare("-blob_auth") == 0) + { + if(++i >= i_argc) return; + s_encauth = s_argv[i]; + i_success++; + } + } + if(i_success != 4) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob datablob(s_blob); + NIARL_Util_ByteBlob bindauth(s_keyauth); + NIARL_Util_ByteBlob encauth(s_encauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_bind = TSS_UUID_USK2; + uuid_bind.rgbNode[5] = (BYTE)i_keyindex; + uuid_bind.rgbNode[0] = 0x05; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//BIND OPERATIONS (SET) + TSS_HKEY bind; + TSS_HPOLICY policy_bind; + UINT32 init_flags; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "Bind Key Section" << endl; + if(b_log) clog << "Bind Key Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &bind); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_bind, &bind); + if(b_debug) cerr << ' ' << result << " load by UUID" << endl; + if(b_log) cerr << ' ' << result << " load by UUID" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_bind); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_bind, TSS_SECRET_MODE_PLAIN, bindauth.size, bindauth.blob); + if(b_debug) cerr << ' ' << result << " key auth" << endl; + if(b_log) cerr << ' ' << result << " key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_bind, bind); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(bind, srk); + if(b_debug) cerr << ' ' << result << " load key" << endl; + if(b_log) cerr << ' ' << result << " load key" << endl; + + +//ENCDATA SECTION + TSS_HENCDATA encdata; + TSS_HPOLICY policy_encdata; + + if(b_debug) cerr << "EncData Section" << endl; + if(b_log) clog << "EncData Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_ENCDATA, TSS_ENCDATA_BIND, &encdata); + if(b_debug) cerr << ' ' << result << " create encdata" << endl; + if(b_log) cerr << ' ' << result << " create encdata" << endl; + + result = Tspi_SetAttribData(encdata, TSS_TSPATTRIB_ENCDATA_BLOB, TSS_TSPATTRIB_ENCDATABLOB_BLOB, datablob.size, datablob.blob); + if(b_debug) cerr << ' ' << result << " load encrypted blob" << endl; + if(b_log) cerr << ' ' << result << " load encrypted blob" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_encdata); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_encdata, TSS_SECRET_MODE_PLAIN, encauth.size, encauth.blob); + if(b_debug) cerr << ' ' << result << " encdata auth" << endl; + if(b_log) cerr << ' ' << result << " encdata auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_encdata, encdata); + if(b_debug) cerr << ' ' << result << " assign encdata authorization" << endl; + if(b_log) cerr << ' ' << result << " assign encdata authorization" << endl; + + +//UNBIND OPERATIONS + UINT32 enc_size; + BYTE* enc_blob; + + if(b_debug) cerr << "Unbind Section" << endl; + if(b_log) clog << "Unbind Section" << endl; + + result = Tspi_Data_Unbind(encdata, bind, &(datablob.size), &(datablob.blob)); + if(b_debug) cerr << ' ' << result << " UNBIND" << endl; + if(b_log) cerr << ' ' << result << " UNBIND" << endl; + return_code = result; + + if(result == 0) + { + result = Tspi_GetAttribData(encdata, TSS_TSPATTRIB_ENCDATA_BLOB, TSS_TSPATTRIB_ENCDATABLOB_BLOB, &enc_size, &enc_blob); + if(b_debug) cerr << ' ' << result << " get unbound data blob" << endl; + if(b_log) cerr << ' ' << result << " get unbound data blob" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < enc_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)enc_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, enc_blob); + } + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_bind); + result = Tspi_Context_CloseObject(context, bind); + result = Tspi_Context_CloseObject(context, policy_encdata); + result = Tspi_Context_CloseObject(context, encdata); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Seal Bind + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::seal_bind() +{ + if(b_help) + { + cout << "Seal Bind (" << i_mode << ") --- Encrypts data using a binding key and platform state" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -blob (hex blob, data to encrypt)" << endl; + cout << " -blob_auth (hex blob, data blob authorization data)" << endl; + cout << " -key_auth (hex blob, binding key authorization data)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " -mask (hex string, controls PCR index selection)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + cout << " OUTPUTS" << endl; + cout << " sealed bound data blob (hex blob, encrypted data)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_blob; + string s_keyauth; + string s_pcrs; + string s_encauth; + int i_keyindex = 0; + bool b_1024 = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-blob") == 0) + { + if(++i >= i_argc) return; + s_blob = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + + if(s_argv[i].compare("-mask") == 0) + { + if(++i >= i_argc) return; + s_pcrs = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-blob_auth") == 0) + { + if(++i >= i_argc) return; + s_encauth = s_argv[i]; + i_success++; + } + } + if(i_success != 5) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob datablob(s_blob); + NIARL_Util_ByteBlob bindauth(s_keyauth); + NIARL_Util_Mask pcrmask(s_pcrs); + NIARL_Util_ByteBlob encauth(s_encauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_bind = TSS_UUID_USK2; + uuid_bind.rgbNode[5] = (BYTE)i_keyindex; + uuid_bind.rgbNode[0] = 0x05; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//BIND OPERATIONS (SET) + TSS_HKEY bind; + TSS_HPOLICY policy_bind; + UINT32 init_flags; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "Bind Key Section" << endl; + if(b_log) clog << "Bind Key Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &bind); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_bind, &bind); + if(b_debug) cerr << ' ' << result << " load by UUID" << endl; + if(b_log) cerr << ' ' << result << " load by UUID" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_bind); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_bind, TSS_SECRET_MODE_PLAIN, bindauth.size, bindauth.blob); + if(b_debug) cerr << ' ' << result << " key auth" << endl; + if(b_log) cerr << ' ' << result << " key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_bind, bind); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(bind, srk); + if(b_debug) cerr << ' ' << result << " load key" << endl; + if(b_log) cerr << ' ' << result << " load key" << endl; + + +//ENCDATA SECTION + TSS_HENCDATA encdata; + TSS_HPOLICY policy_encdata; + + if(b_debug) cerr << "EncData Section" << endl; + if(b_log) clog << "EncData Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_ENCDATA, TSS_ENCDATA_SEAL, &encdata); + if(b_debug) cerr << ' ' << result << " create encdata" << endl; + if(b_log) cerr << ' ' << result << " create encdata" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_encdata); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_encdata, TSS_SECRET_MODE_PLAIN, encauth.size, encauth.blob); + if(b_debug) cerr << ' ' << result << " encdata auth" << endl; + if(b_log) cerr << ' ' << result << " encdata auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_encdata, encdata); + if(b_debug) cerr << ' ' << result << " assign encdata authorization" << endl; + if(b_log) cerr << ' ' << result << " assign encdata authorization" << endl; + + +//PCR OPERATIONS + TSS_HPCRS pcr; + UINT32 pcr_size; + BYTE* pcr_blob; + + if(b_debug) cerr << "PCR Section" << endl; + if(b_log) clog << "PCR Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_PCRS, 0, &pcr); + if(b_debug) cerr << ' ' << result << " create pcr object" << endl; + if(b_log) cerr << ' ' << result << " create pcr object" << endl; + + for(UINT32 i = 0; i < pcrmask.size; i++) + { + result = Tspi_TPM_PcrRead(tpm, pcrmask.index[i], &pcr_size, &pcr_blob); + if(b_debug) cerr << ' ' << result << " read pcr index " << pcrmask.index[i] << endl; + if(b_log) cerr << ' ' << result << " read pcr index " << pcrmask.index[i] << endl; + + result = Tspi_PcrComposite_SelectPcrIndex(pcr, pcrmask.index[i]); + if(b_debug) cerr << ' ' << result << " select composite index" << endl; + if(b_log) cerr << ' ' << result << " select composite index" << endl; + + result = Tspi_PcrComposite_SetPcrValue(pcr, pcrmask.index[i], pcr_size, pcr_blob); + if(b_debug) cerr << ' ' << result << " set pcr value" << endl; + if(b_log) cerr << ' ' << result << " set pcr value" << endl; + +// for(UINT32 j = 0; j < pcr_size; j++) +// cout << setw(2) << setfill('0') << setbase(16) << (int)pcr_blob[j]; +// if(!b_debug && !b_log) cout << ' '; +// if(b_debug) cerr << endl; +// if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, pcr_blob); + if(b_debug) cerr << ' ' << result << " clear dynamic array" << endl; + if(b_log) cerr << ' ' << result << " clear dynamic array" << endl; + } + + +//SEAL OPERATIONS + UINT32 enc_size; + BYTE* enc_blob; + + if(b_debug) cerr << "Seal Bind Section" << endl; + if(b_log) clog << "Seal Bind Section" << endl; + + result = Tspi_Data_Seal(encdata, bind, datablob.size, datablob.blob, pcr); + if(b_debug) cerr << ' ' << result << " SEAL BIND" << endl; + if(b_log) cerr << ' ' << result << " SEAL BIND" << endl; + return_code = result; + + if(result == 0) + { + result = Tspi_GetAttribData(encdata, TSS_TSPATTRIB_ENCDATA_BLOB, TSS_TSPATTRIB_ENCDATABLOB_BLOB, &enc_size, &enc_blob); + if(b_debug) cerr << ' ' << result << " get sealed bound blob" << endl; + if(b_log) cerr << ' ' << result << " get sealed bound blob" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < enc_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)enc_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, enc_blob); + } + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_bind); + result = Tspi_Context_CloseObject(context, bind); + result = Tspi_Context_CloseObject(context, policy_encdata); + result = Tspi_Context_CloseObject(context, encdata); + result = Tspi_Context_CloseObject(context, srk); + result = Tspi_Context_CloseObject(context, pcr); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Unseal Unbind + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::unseal_unbind() +{ + if(b_help) + { + cout << "Unseal Unbind (" << i_mode << ") --- Dencrypts data using a binding key and platform state" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -blob (hex blob, data to decrypt)" << endl; + cout << " -blob_auth (hex blob, data blob authorization data)" << endl; + cout << " -key_auth (hex blob, binding key authorization data)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + cout << " OUTPUTS" << endl; + cout << " unsealed unbound data blob (hex blob, unencrypted data)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_blob; + string s_keyauth; + string s_encauth; + int i_keyindex = 0; + bool b_1024 = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-blob") == 0) + { + if(++i >= i_argc) return; + s_blob = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + + if(s_argv[i].compare("-blob_auth") == 0) + { + if(++i >= i_argc) return; + s_encauth = s_argv[i]; + i_success++; + } + } + if(i_success != 4) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob datablob(s_blob); + NIARL_Util_ByteBlob bindauth(s_keyauth); + NIARL_Util_ByteBlob encauth(s_encauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_bind = TSS_UUID_USK2; + uuid_bind.rgbNode[5] = (BYTE)i_keyindex; + uuid_bind.rgbNode[0] = 0x05; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//BIND OPERATIONS (SET) + TSS_HKEY bind; + TSS_HPOLICY policy_bind; + UINT32 init_flags; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "Bind Key Section" << endl; + if(b_log) clog << "Bind Key Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &bind); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_bind, &bind); + if(b_debug) cerr << ' ' << result << " load by UUID" << endl; + if(b_log) cerr << ' ' << result << " load by UUID" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_bind); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_bind, TSS_SECRET_MODE_PLAIN, bindauth.size, bindauth.blob); + if(b_debug) cerr << ' ' << result << " key auth" << endl; + if(b_log) cerr << ' ' << result << " key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_bind, bind); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(bind, srk); + if(b_debug) cerr << ' ' << result << " load key" << endl; + if(b_log) cerr << ' ' << result << " load key" << endl; + + +//ENCDATA SECTION + TSS_HENCDATA encdata; + TSS_HPOLICY policy_encdata; + + if(b_debug) cerr << "EncData Section" << endl; + if(b_log) clog << "EncData Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_ENCDATA, TSS_ENCDATA_BIND, &encdata); + if(b_debug) cerr << ' ' << result << " create encdata" << endl; + if(b_log) cerr << ' ' << result << " create encdata" << endl; + + result = Tspi_SetAttribData(encdata, TSS_TSPATTRIB_ENCDATA_BLOB, TSS_TSPATTRIB_ENCDATABLOB_BLOB, datablob.size, datablob.blob); + if(b_debug) cerr << ' ' << result << " load encrypted blob" << endl; + if(b_log) cerr << ' ' << result << " load encrypted blob" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_encdata); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_encdata, TSS_SECRET_MODE_PLAIN, encauth.size, encauth.blob); + if(b_debug) cerr << ' ' << result << " encdata auth" << endl; + if(b_log) cerr << ' ' << result << " encdata auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_encdata, encdata); + if(b_debug) cerr << ' ' << result << " assign encdata authorization" << endl; + if(b_log) cerr << ' ' << result << " assign encdata authorization" << endl; + + +//UNSEAL OPERATIONS + UINT32 enc_size; + BYTE* enc_blob; + + if(b_debug) cerr << "Unseal Unbind Section" << endl; + if(b_log) clog << "Unseal Unbind Section" << endl; + + result = Tspi_SetAttribData(encdata, TSS_TSPATTRIB_ENCDATA_BLOB, TSS_TSPATTRIB_ENCDATABLOB_BLOB, datablob.size, datablob.blob); + if(b_debug) cerr << ' ' << result << " UNSEAL UNBIND" << endl; + if(b_log) cerr << ' ' << result << " UNSEAL UNBIND" << endl; + + result = Tspi_Data_Unseal(encdata, bind, &enc_size, &enc_blob); + if(b_debug) cerr << ' ' << result << " get unsealed unbound data blob" << endl; + if(b_log) cerr << ' ' << result << " get unsealed unbound data blob" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < enc_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)enc_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, enc_blob); + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_bind); + result = Tspi_Context_CloseObject(context, bind); + result = Tspi_Context_CloseObject(context, policy_encdata); + result = Tspi_Context_CloseObject(context, encdata); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Get Random Integer + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::get_rand_int() +{ + if(b_help) + { + cout << "Get Random Integer (" << i_mode << ") --- Generates a random positive number" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -bytes (positive integer, max random number size in bytes)" << endl; + cout << " OUTPUTS" << endl; + cout << " integer (integer, random number)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + UINT32 numbytes = 0; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-bytes") == 0) + { + if(++i >= i_argc) return; + numbytes = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success != 1) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//GET RANDOM NUMBER + BYTE* randbytes; + + if(b_debug) cerr << "Get Random Section" << endl; + if(b_log) clog << "Get Random Section" << endl; + + result = Tspi_TPM_GetRandom(tpm, numbytes, &randbytes); + if(b_debug) cerr << ' ' << result << " GET RANDOM" << endl; + if(b_log) cerr << ' ' << result << " GET RANDOM" << endl; + return_code = result; + + for(UINT32 i = 0; i < numbytes; i++) + { + cout << setbase(16) << setw(2) << setfill('0') << (int)randbytes[i]; + } + +//CLEANUP SECTION + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Sign + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::sign() +{ + if(b_help) + { + cout << "Sign (" << i_mode << ") --- Signs a data blob" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -blob (hex blob, data to sign)" << endl; + cout << " -key_auth (hex blob, key authorization data)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + cout << " OUTPUTS" << endl; + cout << " signature (hex blob, signature)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_blob; + string s_keyauth; + int i_keyindex = 0; + bool b_1024 = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-blob") == 0) + { + if(++i >= i_argc) return; + s_blob = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success != 3) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob datablob(s_blob); + NIARL_Util_ByteBlob signauth(s_keyauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_sign = TSS_UUID_USK2; + uuid_sign.rgbNode[5] = (BYTE)i_keyindex; + uuid_sign.rgbNode[0] = 0x06; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//SIGNING OPERATIONS (SET) + TSS_HKEY sign; + TSS_HPOLICY policy_sign; + UINT32 init_flags; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + + if(b_debug) cerr << "Signing Key Section" << endl; + if(b_log) clog << "Signing Key Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &sign); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_sign, &sign); + if(b_debug) cerr << ' ' << result << " load by UUID" << endl; + if(b_log) cerr << ' ' << result << " load by UUID" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_sign); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_sign, TSS_SECRET_MODE_PLAIN, signauth.size, signauth.blob); + if(b_debug) cerr << ' ' << result << " key auth" << endl; + if(b_log) cerr << ' ' << result << " key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_sign, sign); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(sign, srk); + if(b_debug) cerr << ' ' << result << " load key" << endl; + if(b_log) cerr << ' ' << result << " load key" << endl; + + +//HASH SECTION + TSS_HHASH hash; + + if(b_debug) cerr << "Hash Section" << endl; + if(b_log) clog << "Hash Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_HASH, TSS_HASH_SHA1, &hash); + if(b_debug) cerr << ' ' << result << " create hash object" << endl; + if(b_log) cerr << ' ' << result << " create hash object" << endl; + + result = Tspi_Hash_UpdateHashValue(hash, datablob.size, datablob.blob); + if(b_debug) cerr << ' ' << result << " update hash value" << endl; + if(b_log) cerr << ' ' << result << " update hash value" << endl; + + +//SIGNING OPERATIONS + UINT32 sig_size; + BYTE* sig_blob; + + if(b_debug) cerr << "Sign Section" << endl; + if(b_log) clog << "Sign Section" << endl; + + result = Tspi_Hash_Sign(hash, sign, &sig_size, &sig_blob); + if(b_debug) cerr << ' ' << result << " SIGN" << endl; + if(b_log) cerr << ' ' << result << " SIGN" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < sig_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)sig_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, sig_blob); + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_sign); + result = Tspi_Context_CloseObject(context, sign); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Create EK + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::create_ek() +{ + if(b_help) + { + cout << "Create Endorsement Key (" << i_mode << ") --- Creates a default endorsement key in the absence of a manufacturer endorsement key" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -nonce (hex blob, anti-replay nonce)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_nonce; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-nonce") == 0) + { + if(++i >= i_argc) return; + s_nonce = s_argv[i]; + i_success++; + } + } + if(i_success != 1) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob nonce(s_nonce); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//EK SECTION + TSS_HKEY ek; + TSS_VALIDATION validation; + + if(b_debug) cerr << "EK Section" << endl; + if(b_log) clog << "EK Section" << endl; + + memset(&validation, 0, sizeof(TSS_VALIDATION)); + validation.versionInfo.bMajor = 0x01; + validation.versionInfo.bMinor = 0x02; + validation.versionInfo.bRevMajor = 0x01; + validation.versionInfo.bRevMinor = 0x25; + validation.ulExternalDataLength = sizeof(TSS_NONCE); + validation.rgbExternalData = nonce.blob; + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_SIZE_DEFAULT, &ek); + if(b_debug) cerr << ' ' << result << " create ek object" << endl; + if(b_log) cerr << ' ' << result << " create ek object" << endl; + + +//TAKE OWNERSHIP + if(b_debug) cerr << "Create EK Section" << endl; + if(b_log) clog << "Create EK Section" << endl; + + result = Tspi_TPM_CreateEndorsementKey(tpm, ek, &validation); + if(b_debug) cerr << ' ' << result << " CREATE EK" << endl; + if(b_log) cerr << ' ' << result << " CREATE EK" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < validation.ulExternalDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbExternalData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < validation.ulDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < validation.ulValidationDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbValidationData[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + } + + +//CLEANUP + result = Tspi_Context_FreeMemory(context, validation.rgbData); + result = Tspi_Context_FreeMemory(context, validation.rgbValidationData); + result = Tspi_Context_FreeMemory(context, validation.rgbExternalData); + + result = Tspi_Context_CloseObject(context, ek); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Quote2 + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::quote2() +{ + if(b_help) + { + cout << "Quote2 (" << i_mode << ") --- Provides a system integrity quote with signature" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -key_auth (hex blob, identity key authorization data)" << endl; + cout << " -nonce (hex blob, anti-replay nonce)" << endl; + cout << " -mask (hex string, controls PCR index selection)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OUTPUTS" << endl; + cout << " quote (hex blob, quote digest)" << endl; + cout << " signature (hex blob, quote signature)" << endl; + cout << " version_info (hex blob, TCPA_VERSION_INFO)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_pcrs; + string s_aikauth; + string s_nonce; + int i_keyindex = 0; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-nonce") == 0) + { + if(++i >= i_argc) return; + s_nonce = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_aikauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-mask") == 0) + { + if(++i >= i_argc) return; + s_pcrs = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success != 4) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob aikauth(s_aikauth); + NIARL_Util_ByteBlob nonce(s_nonce); + NIARL_Util_Mask pcrmask(s_pcrs); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_aik = TSS_UUID_USK2; + uuid_aik.rgbNode[5] = (BYTE)i_keyindex; + uuid_aik.rgbNode[0] = 0x04; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//AIK OPERATIONS (SET) + TSS_HKEY aik; + TSS_HPOLICY policy_aik; + UINT32 init_flags = TSS_KEY_TYPE_IDENTITY | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "AIK Section" << endl; + if(b_log) clog << "AIK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &aik); + if(b_debug) cerr << ' ' << result << " create aik object" << endl; + if(b_log) cerr << ' ' << result << " create aik object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_aik, &aik); + if(b_debug) cerr << ' ' << result << " get uuid" << endl; + if(b_log) cerr << ' ' << result << " get uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_aik); + if(b_debug) cerr << ' ' << result << " create aik policy" << endl; + if(b_log) cerr << ' ' << result << " create aik policy" << endl; + + result = Tspi_Policy_SetSecret(policy_aik, TSS_SECRET_MODE_PLAIN, aikauth.size, aikauth.blob); + if(b_debug) cerr << ' ' << result << " set aik auth" << endl; + if(b_log) cerr << ' ' << result << " set aik auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_aik, aik); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(aik, srk); + if(b_debug) cerr << ' ' << result << " load aik" << endl; + if(b_log) cerr << ' ' << result << " load aik" << endl; + + +//PCR OPERATIONS + TSS_HPCRS pcr; + UINT32 pcr_size; + BYTE* pcr_blob; + + if(b_debug) cerr << "PCR Section" << endl; + if(b_log) clog << "PCR Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_PCRS, TSS_PCRS_STRUCT_INFO_SHORT, &pcr); + if(b_debug) cerr << ' ' << result << " create pcr object" << endl; + if(b_log) cerr << ' ' << result << " create pcr object" << endl; + + for(UINT32 i = 0; i < pcrmask.size; i++) + { + result = Tspi_PcrComposite_SelectPcrIndexEx(pcr, pcrmask.index[i], TSS_PCRS_DIRECTION_RELEASE); + if(b_debug) cerr << ' ' << result << " select composite index" << endl; + if(b_log) cerr << ' ' << result << " select composite index" << endl; + } + + +//QUOTE OPERATIONS + TSS_VALIDATION validation; + + if(b_debug) cerr << "Quote Section" << endl; + if(b_log) clog << "Quote Section" << endl; + + memset(&validation, 0, sizeof(TSS_VALIDATION)); + validation.versionInfo.bMajor = 0x01; + validation.versionInfo.bMinor = 0x02; + validation.versionInfo.bRevMajor = 0x01; + validation.versionInfo.bRevMinor = 0x25; + validation.ulExternalDataLength = sizeof(TSS_NONCE); + validation.rgbExternalData = nonce.blob; + + BYTE* versionvalue; + UINT32 versionsize; + + result = Tspi_TPM_Quote2(tpm, aik, FALSE, pcr, &validation, &versionsize, &versionvalue); + if(b_debug) cerr << ' ' << result << " QUOTE" << endl; + if(b_log) cerr << ' ' << result << " QUOTE" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < pcrmask.size; i++) + { + result = Tspi_PcrComposite_GetPcrValue(pcr, pcrmask.index[i], &pcr_size, &pcr_blob); + if(b_debug) cerr << ' ' << result << " set pcr value" << endl; + if(b_log) cerr << ' ' << result << " set pcr value" << endl; + + for(UINT32 j = 0; j < pcr_size; j++) + cout << setw(2) << setfill('0') << setbase(16) << (int)pcr_blob[j]; + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, pcr_blob); + if(b_debug) cerr << ' ' << result << " clear dynamic array" << endl; + if(b_log) cerr << ' ' << result << " clear dynamic array" << endl; + } + + for(UINT32 i = 0; i < validation.ulExternalDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbExternalData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < validation.ulDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < validation.ulValidationDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbValidationData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < versionsize; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)versionvalue[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + delete [] versionvalue; + } + + +//CLEANUP SECTION + result = Tspi_Context_FreeMemory(context, validation.rgbData); + result = Tspi_Context_FreeMemory(context, validation.rgbValidationData); + result = Tspi_Context_FreeMemory(context, validation.rgbExternalData); + + result = Tspi_Context_CloseObject(context, policy_aik); + result = Tspi_Context_CloseObject(context, aik); + result = Tspi_Context_CloseObject(context, srk); + result = Tspi_Context_CloseObject(context, pcr); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} diff --git a/OpenAttestation/Source/TPMModule/plain/linux/NIARL_TPM_ModuleV2.h b/OpenAttestation/Source/TPMModule/plain/linux/NIARL_TPM_ModuleV2.h new file mode 100644 index 0000000..751b3b4 --- /dev/null +++ b/OpenAttestation/Source/TPMModule/plain/linux/NIARL_TPM_ModuleV2.h @@ -0,0 +1,130 @@ +/** + * Copyright (C) 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * 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) Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. + */ + +#ifndef NIARL_TPM_ModuleV2_H +#define NIARL_TPM_ModuleV2_H + +// ************ MODULE HEADERS ************ // +#include "NIARL_Util_ByteBlob.h" +#include "NIARL_Util_Mask.h" + +// ************ TSS HEADERS ************ // +#include +#include +#include +//#include "tspi.h" +//#include "tss_error.h" +//#include "tss_defines.h" + +// ************ STANDARD HEADERS ************ // +#include +#include +#include +#include +#include +#include +using namespace std; + +class NIARL_TPM_ModuleV2 +{ +public: + enum MODULE_ERROR { + ERROR_ZEROFILL, + ERROR_UNKNOWN, + ERROR_ARG_MISSING, + ERROR_ARG_INFILE, + ERROR_ARG_OUTFILE, + ERROR_ARG_MODE, + ERROR_ARG_VALIDATION, + ERROR_ARG_HELP, + ERROR_MODE_DISABLED}; + + enum MODULE_MODE { + MODE_ZEROFILL, + MODE_TAKE_OWNERSHIP, + MODE_CLEAR_OWNERSHIP, + MODE_COLLATE_IDENTITY, + MODE_ACTIVATE_IDENTITY, + MODE_QUOTE, + MODE_CREATE_REK, + MODE_REVOKE_REK, + MODE_CREATE_KEY, + MODE_SET_KEY, + MODE_GET_KEY, + MODE_CLEAR_KEY, + MODE_SET_CREDENTIAL, + MODE_GET_CREDENTIAL, + MODE_CLEAR_CREDENTIAL, + MODE_SEAL, + MODE_UNSEAL, + MODE_BIND, + MODE_UNBIND, + MODE_SEAL_BIND, + MODE_UNSEAL_UNBIND, + MODE_GET_RAND, + MODE_SIGN, + MODE_CREATE_EK, + MODE_QUOTE2}; + + bool b_debug, + b_log, + b_help, + b_infile, + b_outfile; + + int i_mode, + i_argc, + i_return; + + string* s_argv; + + ofstream logfile, + outfile; + + ifstream infile; + + TSS_RESULT return_code; + + NIARL_TPM_ModuleV2(int argc, char* argv[]); + ~NIARL_TPM_ModuleV2(); + + void run_mode(); + + void take_ownership(); + void clear_ownership(); + void collate_identity(); + void activate_identity(); + void quote(); + void create_revokable_ek(); + void revoke_ek(); + void create_key(); + void set_key(); + void get_key(); + void clear_key(); + void set_credential(); + void get_credential(); + void clear_credential(); + void seal(); + void unseal(); + void bind(); + void unbind(); + void seal_bind(); + void unseal_unbind(); + void get_rand_int(); + void sign(); + void encrypt(); + void decrypt(); + void create_ek(); + void quote2(); +}; + +#endif diff --git a/OpenAttestation/Source/TPMModule/plain/linux/NIARL_Util_ByteBlob.cpp b/OpenAttestation/Source/TPMModule/plain/linux/NIARL_Util_ByteBlob.cpp new file mode 100644 index 0000000..de6e83d --- /dev/null +++ b/OpenAttestation/Source/TPMModule/plain/linux/NIARL_Util_ByteBlob.cpp @@ -0,0 +1,109 @@ +/** + * Copyright (C) 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * 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) Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. + */ + +#include "NIARL_Util_ByteBlob.h" + +NIARL_Util_ByteBlob::NIARL_Util_ByteBlob(string in_var) +{ + short temp_size = in_var.size(); //get the full string length + if(temp_size % 2 == 1) + throw NIARL_TPM_ModuleV2::ERROR_ARG_VALIDATION; + + size = temp_size / 2; //base 16 takes 2 digits so reduce length to show real size + blob = new BYTE[size]; //create the byte array + + UINT32 hex_value = 0; //accumulates 2 hex characters to load into blob + short index; //index that points at correct byte blob index (truncation intentional) + + for(short i = 0; i < temp_size; i++) + { + switch(in_var[i]) + { + case 'F': + case 'f': + hex_value += 15; + break; + case 'E': + case 'e': + hex_value += 14; + break; + case 'D': + case 'd': + hex_value += 13; + break; + case 'C': + case 'c': + hex_value += 12; + break; + case 'B': + case 'b': + hex_value += 11; + break; + case 'A': + case 'a': + hex_value += 10; + break; + case '9': + hex_value += 9; + break; + case '8': + hex_value += 8; + break; + case '7': + hex_value += 7; + break; + case '6': + hex_value += 6; + break; + case '5': + hex_value += 5; + break; + case '4': + hex_value += 4; + break; + case '3': + hex_value += 3; + break; + case '2': + hex_value += 2; + break; + case '1': + hex_value += 1; + break; + case '0': + hex_value += 0; + break; + default: + throw NIARL_TPM_ModuleV2::ERROR_ARG_VALIDATION; + } + + index = i / 2; //allow truncation so we get the right spot in the byte array + if(i % 2 == 0) //even characters are the first of two hex characters + hex_value *= 16; + else + { + blob[index] = hex_value; //we now have 2 hex characters so load them into the byte array + hex_value = 0; //reset the accumulator + } + } +} + +NIARL_Util_ByteBlob::~NIARL_Util_ByteBlob() +{ + delete [] blob; +} + +void NIARL_Util_ByteBlob::Print() +{ + for(UINT32 i = 0; i < size; i++) + cout << setbase(16) << setw(2) << setfill('0') << (int)blob[i]; +} diff --git a/OpenAttestation/Source/TPMModule/plain/linux/NIARL_Util_ByteBlob.h b/OpenAttestation/Source/TPMModule/plain/linux/NIARL_Util_ByteBlob.h new file mode 100644 index 0000000..990e03f --- /dev/null +++ b/OpenAttestation/Source/TPMModule/plain/linux/NIARL_Util_ByteBlob.h @@ -0,0 +1,46 @@ +/** + * Copyright (C) 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * 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) Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. + */ + +#ifndef NIARL_UTIL_BYTEBLOB_H +#define NIARL_UTIL_BYTEBLOB_H + +// ************ MODULE HEADERS ************ // +#include "NIARL_TPM_ModuleV2.h" + +// ************ TSS HEADERS ************ // +#include +#include +#include +//#include "tspi.h" +//#include "tss_error.h" +//#include "tss_defines.h" + +// ************ STANDARD HEADERS ************ // +#include +#include +#include +#include +using namespace std; + +class NIARL_Util_ByteBlob +{ +public: + UINT32 size; + BYTE* blob; + + NIARL_Util_ByteBlob(string in_var); + ~NIARL_Util_ByteBlob(); + + void Print(); +}; + +#endif diff --git a/OpenAttestation/Source/TPMModule/plain/linux/NIARL_Util_Mask.cpp b/OpenAttestation/Source/TPMModule/plain/linux/NIARL_Util_Mask.cpp new file mode 100644 index 0000000..85790d9 --- /dev/null +++ b/OpenAttestation/Source/TPMModule/plain/linux/NIARL_Util_Mask.cpp @@ -0,0 +1,158 @@ +/** + * Copyright (C) 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * 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) Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. + */ + +#include "NIARL_Util_Mask.h" + +NIARL_Util_Mask::NIARL_Util_Mask(string in_var) +{ + short temp_size = in_var.size(); + vector temp_array; + + int bumper = 0; + + for(short i = 0; i < temp_size; i++) + { + switch(in_var[i]) + { + case 'F': + case 'f': + temp_array.push_back(bumper + 0); + temp_array.push_back(bumper + 1); + temp_array.push_back(bumper + 2); + temp_array.push_back(bumper + 3); + //Bitmask 1111 + break; + case 'E': + case 'e': + temp_array.push_back(bumper + 0); + temp_array.push_back(bumper + 1); + temp_array.push_back(bumper + 2); + //temp_array.push_back(bumper + 3); + //Bitmask 1110 + break; + case 'D': + case 'd': + temp_array.push_back(bumper + 0); + temp_array.push_back(bumper + 1); + //temp_array.push_back(bumper + 2); + temp_array.push_back(bumper + 3); + //Bitmask 1101 + break; + case 'C': + case 'c': + temp_array.push_back(bumper + 0); + temp_array.push_back(bumper + 1); + //temp_array.push_back(bumper + 2); + //temp_array.push_back(bumper + 3); + //Bitmask 1100 + break; + case 'B': + case 'b': + temp_array.push_back(bumper + 0); + //temp_array.push_back(bumper + 1); + temp_array.push_back(bumper + 2); + temp_array.push_back(bumper + 3); + //Bitmask 1011 + break; + case 'A': + case 'a': + temp_array.push_back(bumper + 0); + //temp_array.push_back(bumper + 1); + temp_array.push_back(bumper + 2); + //temp_array.push_back(bumper + 3); + //Bitmask 1010 + break; + case '9': + temp_array.push_back(bumper + 0); + //temp_array.push_back(bumper + 1); + //temp_array.push_back(bumper + 2); + temp_array.push_back(bumper + 3); + //Bitmask 1001 + break; + case '8': + temp_array.push_back(bumper + 0); + //temp_array.push_back(bumper + 1); + //temp_array.push_back(bumper + 2); + //temp_array.push_back(bumper + 3); + //Bitmask 1000 + break; + case '7': + //temp_array.push_back(bumper + 0); + temp_array.push_back(bumper + 1); + temp_array.push_back(bumper + 2); + temp_array.push_back(bumper + 3); + //Bitmask 0111 + break; + case '6': + //temp_array.push_back(bumper + 0); + temp_array.push_back(bumper + 1); + temp_array.push_back(bumper + 2); + //temp_array.push_back(bumper + 3); + //Bitmask 0110 + break; + case '5': + //temp_array.push_back(bumper + 0); + temp_array.push_back(bumper + 1); + //temp_array.push_back(bumper + 2); + temp_array.push_back(bumper + 3); + //Bitmask 0101 + break; + case '4': + //temp_array.push_back(bumper + 0); + temp_array.push_back(bumper + 1); + //temp_array.push_back(bumper + 2); + //temp_array.push_back(bumper + 3); + //Bitmask 0100 + break; + case '3': + //temp_array.push_back(bumper + 0); + //temp_array.push_back(bumper + 1); + temp_array.push_back(bumper + 2); + temp_array.push_back(bumper + 3); + //Bitmask 0011 + break; + case '2': + //temp_array.push_back(bumper + 0); + //temp_array.push_back(bumper + 1); + temp_array.push_back(bumper + 2); + //temp_array.push_back(bumper + 3); + //Bitmask 0010 + break; + case '1': + //temp_array.push_back(bumper + 0); + //temp_array.push_back(bumper + 1); + //temp_array.push_back(bumper + 2); + temp_array.push_back(bumper + 3); + //Bitmask 0001 + break; + case '0': + break; + default: + throw NIARL_TPM_ModuleV2::ERROR_ARG_VALIDATION; + } + bumper += 4; + } + + size = temp_array.size(); + index = new int[size]; + + for(int i = (size - 1); i > -1; i--) + { + index[i] = temp_array.back(); + temp_array.pop_back(); + } +} + +NIARL_Util_Mask::~NIARL_Util_Mask() +{ + delete [] index; +} diff --git a/OpenAttestation/Source/TPMModule/plain/linux/NIARL_Util_Mask.h b/OpenAttestation/Source/TPMModule/plain/linux/NIARL_Util_Mask.h new file mode 100644 index 0000000..658991b --- /dev/null +++ b/OpenAttestation/Source/TPMModule/plain/linux/NIARL_Util_Mask.h @@ -0,0 +1,43 @@ +/** + * Copyright (C) 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * 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) Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. + */ + +#ifndef NIARL_UTIL_MASK_H +#define NIARL_UTIL_MASK_H + +// ************ MODULE HEADERS ************ // +#include "NIARL_TPM_ModuleV2.h" + +// ************ TSS HEADERS ************ // +#include +#include +#include +//#include "tspi.h" +//#include "tss_error.h" +//#include "tss_defines.h" + +// ************ STANDARD HEADERS ************ // +#include +#include +#include +using namespace std; + +class NIARL_Util_Mask +{ +public: + UINT32 size; + int* index; + + NIARL_Util_Mask(string in_var); + ~NIARL_Util_Mask(); +}; + +#endif diff --git a/OpenAttestation/Source/TPMModule/plain/linux/main.cpp b/OpenAttestation/Source/TPMModule/plain/linux/main.cpp new file mode 100644 index 0000000..b64415d --- /dev/null +++ b/OpenAttestation/Source/TPMModule/plain/linux/main.cpp @@ -0,0 +1,43 @@ +/** + * Copyright (C) 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * 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) Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. + */ + +// ************ TSS HEADERS ************ // +#include +#include +#include +//#include "tspi.h" +//#include "tss_error.h" +//#include "tss_defines.h" + +// ************ MODULE HEADERS ************ // +#include "NIARL_TPM_ModuleV2.h" + +// ************ STANDARD HEADERS ************ // +using namespace std; + +int main(int argc, char* argv[]) +{ + UINT32 rcode = 0; + + try + { + NIARL_TPM_ModuleV2 test(argc, argv); + test.run_mode(); + rcode = test.return_code; + } + catch(...) + { + return (-1); + } + + return rcode; +} diff --git a/OpenAttestation/Source/TPMModule/plain/linux/makefile b/OpenAttestation/Source/TPMModule/plain/linux/makefile new file mode 100644 index 0000000..370b4b2 --- /dev/null +++ b/OpenAttestation/Source/TPMModule/plain/linux/makefile @@ -0,0 +1,58 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C++_DEPS)),) +-include $(C++_DEPS) +endif +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +ifneq ($(strip $(CC_DEPS)),) +-include $(CC_DEPS) +endif +ifneq ($(strip $(CPP_DEPS)),) +-include $(CPP_DEPS) +endif +ifneq ($(strip $(CXX_DEPS)),) +-include $(CXX_DEPS) +endif +ifneq ($(strip $(C_UPPER_DEPS)),) +-include $(C_UPPER_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: NIARL_TPM_Module + +# Tool invocations +NIARL_TPM_Module: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C++ Linker' + g++ -o"NIARL_TPM_Module" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C++_DEPS)$(C_DEPS)$(CC_DEPS)$(CPP_DEPS)$(EXECUTABLES)$(CXX_DEPS)$(C_UPPER_DEPS) NIARL_TPM_Module + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/OpenAttestation/Source/TPMModule/plain/linux/mkout b/OpenAttestation/Source/TPMModule/plain/linux/mkout new file mode 100644 index 0000000..de3257b --- /dev/null +++ b/OpenAttestation/Source/TPMModule/plain/linux/mkout @@ -0,0 +1,5 @@ +g++ -g -c -o NIARL_TPM_ModuleV2.o NIARL_TPM_ModuleV2.cpp +g++ -g -c -o NIARL_Util_ByteBlob.o NIARL_Util_ByteBlob.cpp +g++ -g -c -o NIARL_Util_Mask.o NIARL_Util_Mask.cpp +g++ -g -c -o main.o main.cpp +g++ -g -o"NIARL_TPM_Module" ./NIARL_TPM_ModuleV2.o ./NIARL_Util_ByteBlob.o ./NIARL_Util_Mask.o ./main.o -ltspi diff --git a/OpenAttestation/Source/TPMModule/plain/linux/objects.mk b/OpenAttestation/Source/TPMModule/plain/linux/objects.mk new file mode 100644 index 0000000..d05063c --- /dev/null +++ b/OpenAttestation/Source/TPMModule/plain/linux/objects.mk @@ -0,0 +1,7 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +USER_OBJS := + +LIBS := -ltspi diff --git a/OpenAttestation/Source/TPMModule/plain/linux/subdir.mk b/OpenAttestation/Source/TPMModule/plain/linux/subdir.mk new file mode 100644 index 0000000..1fbfb99 --- /dev/null +++ b/OpenAttestation/Source/TPMModule/plain/linux/subdir.mk @@ -0,0 +1,33 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../NIARL_TPM_ModuleV2.cpp \ +../NIARL_Util_ByteBlob.cpp \ +../NIARL_Util_Mask.cpp \ +../main.cpp + +OBJS += \ +./NIARL_TPM_ModuleV2.o \ +./NIARL_Util_ByteBlob.o \ +./NIARL_Util_Mask.o \ +./main.o + +CPP_DEPS += \ +./NIARL_TPM_ModuleV2.d \ +./NIARL_Util_ByteBlob.d \ +./NIARL_Util_Mask.d \ +./main.d + + +# Each subdirectory must supply rules for building sources it contributes +%.o: ../%.cpp + @echo 'Building file: $<' + @echo 'Invoking: GCC C++ Compiler' + g++ -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o"$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_TPM_ModuleV2.cpp b/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_TPM_ModuleV2.cpp new file mode 100644 index 0000000..48fb79a --- /dev/null +++ b/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_TPM_ModuleV2.cpp @@ -0,0 +1,5576 @@ +/** + * Copyright (C) 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * 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) Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. + */ + +#include "NIARL_TPM_ModuleV2.h" + +NIARL_TPM_ModuleV2::NIARL_TPM_ModuleV2(int argc, char* argv[]) +{ + //set defaults + b_debug = false; + b_log = false; + b_help = false; + b_infile = false; + b_outfile = false; + i_mode = 0; + i_return = 0; + + //setup local copy of argument array + i_argc = argc; + s_argv = new string[i_argc]; + + for(short i = 0; i < i_argc; i++) + { + if(strcmp(argv[i], "-debug") == 0) + { + b_debug = true; + continue; + } + + if(strcmp(argv[i], "-log") == 0) + { + b_log = true; + continue; + } + + if(strcmp(argv[i], "-help") == 0) + { + b_help = true; + continue; + } + + if(strcmp(argv[i], "-mode") == 0) + { + if(++i >= i_argc) return; + i_mode = atoi(argv[i]); + continue; + } + +/* if(strcmp(argv[i], "-infile") == 0) + { + b_infile = true; + infile.open(s_argv[(++i)].c_str(), ios::in); + if(infile.is_open()) + cin.rdbuf(infile.rdbuf()); + else + return_code = -1 * ERROR_ARG_INFILE; + continue; + } +*/ + if(strcmp(argv[i], "-outfile") == 0) + { + b_outfile = true; + if(++i >= i_argc) return; + outfile.open(s_argv[(i)].c_str(), ios::out); + if(outfile.is_open()) + cout.rdbuf(outfile.rdbuf()); + else + return_code = -1 * ERROR_ARG_OUTFILE; + continue; + } + + //convert function-specific c-string data to c++ strings + s_argv[i] = argv[i]; + } + + if(b_debug || b_log) + { + //record the start time and output appropriate messages + time_t rawtime; + struct tm* timeinfo; + time(&rawtime); + timeinfo = localtime(&rawtime); + + if(b_debug) + { + cerr << "START --- NIARL TPM Module (v2.5 11-24-2010) --- " << asctime(timeinfo); + cerr << ' ' << i_mode << " mode selection" << endl; + cerr << ' ' << b_debug << " debug toggle" << endl; + cerr << ' ' << logfile.is_open() << " logging" << endl; + cerr << ' ' << infile.is_open() << " input file" << endl; + cerr << ' ' << outfile.is_open() << " output file" << endl; + } + + if(b_log) + { + clog << "START --- NIARL TPM Module (v2.5 11-24-2010) --- " << asctime(timeinfo); + clog << ' ' << i_mode << " mode selection" << endl; + clog << ' ' << b_debug << " debug toggle" << endl; + clog << ' ' << logfile.is_open() << " logging" << endl; + clog << ' ' << infile.is_open() << " input file" << endl; + clog << ' ' << outfile.is_open() << " output file" << endl; + } + } + + if(b_help && i_mode == 0) + { + cout << endl << "NIARL TPM MODULE (Version 2.5, Build Date 11-25-2010) PLAIN, SYM-FIX, SEG-FIX" << endl; + cout << endl << "MODE LIST" << endl; + cout << " 1 --- Take Ownership" << endl; + cout << " 2 --- Clear Ownership" << endl; + cout << " 3 --- Collate Identity Request" << endl; + cout << " 4 --- Activate Identity" << endl; + cout << " 5 --- Quote" << endl; + cout << " 6 --- Create Revokable Endorsement Key" << endl; + cout << " 7 --- Revoke Revokable Endorsement Key" << endl; + cout << " 8 --- Create Key (sign or bind)" << endl; + cout << " 9 --- Set Key (sign, bind, or identity)" << endl; + cout << " 10 --- Get Key (sign, bind, identity, or EK)" << endl; + cout << " 11 --- Clear Key (sign, bind, or identity)" << endl; + cout << " 12 --- Set Credential (EC, PC, CC, and PCC)" << endl; + cout << " 13 --- Get Credential (EC, PC, CC, and PCC)" << endl; + cout << " 14 --- Clear Credential (EC, PC, CC, and PCC)" << endl; + cout << " 15 --- Seal" << endl; + cout << " 16 --- Unseal" << endl; + cout << " 17 --- Bind" << endl; + cout << " 18 --- Unbind" << endl; + cout << " 19 --- Seal Bind" << endl; + cout << " 20 --- Unseal Unbind" << endl; + cout << " 21 --- Get Random Integer" << endl; + cout << " 22 --- Sign" << endl; + cout << " 23 --- Create Endorsement Key" << endl; + cout << " 24 --- Quote2" << endl; + + cout << endl << "INPUT FLAGS" << endl; + cout << " -mode integer (mode selection flag)" << endl; + cout << " -debug (debugging output displayed to cerr)" << endl; + cout << " -outfile name.txt (standard output redirected to file named)" << endl; + + cout << endl << "ERROR CODES" << endl; + cout << " TSS errors are positive integers. TPM Module errors are negative integers." << endl; + cout << " -" << ERROR_UNKNOWN << " --- Unspecified error" << endl; + cout << " -" << ERROR_ARG_MISSING << " --- Argument missing" << endl; + cout << " -" << ERROR_ARG_INFILE << " --- Invalid or inaccessible input file" << endl; + cout << " -" << ERROR_ARG_OUTFILE << " --- Invalid or inaccessible output file" << endl; + cout << " -" << ERROR_ARG_MODE << " --- Invalid mode selection" << endl; + cout << " -" << ERROR_ARG_VALIDATION << " --- Argument validation error" << endl; + cout << " -" << ERROR_ARG_HELP << " --- Help toggle detected" << endl; + cout << " -" << ERROR_MODE_DISABLED << " --- Mode selection disabled" << endl; + } +} + +NIARL_TPM_ModuleV2::~NIARL_TPM_ModuleV2() +{ + //delete dynamic arrays + delete [] s_argv; + + //close logfile + if(logfile.is_open()) + logfile.close(); + +/* //close input file + if(infile.is_open()) + infile.close(); +*/ + //close output file + if(outfile.is_open()) + outfile.close(); + + if(b_debug || b_log) + { + //record the end time and output appropriate messages + time_t rawtime; + struct tm* timeinfo; + time(&rawtime); + timeinfo = localtime(&rawtime); + + if(b_debug) + cerr << "END --- NIARL TPM Module --- " << asctime(timeinfo); + + if(b_log) + clog << "END --- NIARL TPM Module --- " << asctime(timeinfo); + } +} + +void NIARL_TPM_ModuleV2::run_mode() +{ + switch(i_mode) + { + case MODE_TAKE_OWNERSHIP: + take_ownership(); + break; + case MODE_CLEAR_OWNERSHIP: + clear_ownership(); + break; + case MODE_COLLATE_IDENTITY: + collate_identity(); + break; + case MODE_ACTIVATE_IDENTITY: + activate_identity(); + break; + case MODE_QUOTE: + quote(); + break; + case MODE_CREATE_REK: + create_revokable_ek(); + break; + case MODE_REVOKE_REK: + revoke_ek(); + break; + case MODE_CREATE_KEY: + create_key(); + break; + case MODE_SET_KEY: + set_key(); + break; + case MODE_GET_KEY: + get_key(); + break; + case MODE_CLEAR_KEY: + clear_key(); + break; + case MODE_SET_CREDENTIAL: + set_credential(); + break; + case MODE_GET_CREDENTIAL: + get_credential(); + break; + case MODE_CLEAR_CREDENTIAL: + clear_credential(); + break; + case MODE_SEAL: + seal(); + break; + case MODE_UNSEAL: + unseal(); + break; + case MODE_BIND: + bind(); + break; + case MODE_UNBIND: + unbind(); + break; + case MODE_SEAL_BIND: + seal_bind(); + break; + case MODE_UNSEAL_UNBIND: + unseal_unbind(); + break; + case MODE_GET_RAND: + get_rand_int(); + break; + case MODE_SIGN: + sign(); + break; + case MODE_CREATE_EK: + create_ek(); + break; + case MODE_QUOTE2: + quote2(); + break; + default: + return_code = -1 * ERROR_ARG_MODE; + return; + } +} + +/********************************************************************************************** + Take Ownership + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::take_ownership() +{ + if(b_help) + { + cout << "Take Ownership (" << i_mode << ") --- Takes ownership of the TPM and establishes a Storage Root Key (SRK)" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -nonce (hex blob, anti-replay nonce)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string s_nonce; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-nonce") == 0) + { + if(++i >= i_argc) return; + s_nonce = s_argv[i]; + i_success++; + } + } + if(i_success != 2) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + NIARL_Util_ByteBlob nonce(s_nonce); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_SHA1, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//SRK OPERATIONS (NOT SET YET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//EK SECTION + TSS_HKEY ek; + TSS_HPOLICY policy_ek; + TSS_VALIDATION validation; + + if(b_debug) cerr << "EK Section" << endl; + if(b_log) clog << "EK Section" << endl; + + memset(&validation, 0, sizeof(TSS_VALIDATION)); + validation.versionInfo.bMajor = 0x01; + validation.versionInfo.bMinor = 0x02; + validation.versionInfo.bRevMajor = 0x01; + validation.versionInfo.bRevMinor = 0x25; + validation.ulExternalDataLength = sizeof(TSS_NONCE); + validation.rgbExternalData = nonce.blob; + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_SIZE_DEFAULT, &ek); + if(b_debug) cerr << ' ' << result << " create ek object" << endl; + if(b_log) cerr << ' ' << result << " create ek object" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_ek); + if(b_debug) cerr << ' ' << result << " create ek policy" << endl; + if(b_log) cerr << ' ' << result << " create ek policy" << endl; + + result = Tspi_Policy_SetSecret(policy_ek, TSS_SECRET_MODE_SHA1, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " set auth" << endl; + if(b_log) cerr << ' ' << result << " set auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_ek, ek); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_TPM_GetPubEndorsementKey(tpm, false, &validation, &ek); + if(b_debug) cerr << ' ' << result << " get the ek (false flag)" << endl; + if(b_log) cerr << ' ' << result << " get the ek (false flag)" << endl; + + +//TAKE OWNERSHIP + if(b_debug) cerr << "Take Ownership Section" << endl; + if(b_log) clog << "Take Ownership Section" << endl; + + result = Tspi_TPM_TakeOwnership(tpm, srk, ek); + if(b_debug) cerr << ' ' << result << " TAKE OWNERSHIP" << endl; + if(b_log) cerr << ' ' << result << " TAKE OWNERSHIP" << endl; + return_code = result; + + if(result == 0) + { + //LOAD KEYS + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " save the srk" << endl; + if(b_log) cerr << ' ' << result << " save the srk" << endl; + return_code = result; + } + + +//CLEANUP + result = Tspi_Context_FreeMemory(context, validation.rgbData); + result = Tspi_Context_FreeMemory(context, validation.rgbValidationData); + result = Tspi_Context_FreeMemory(context, validation.rgbExternalData); + + result = Tspi_Context_CloseObject(context, policy_tpm); + result = Tspi_Context_CloseObject(context, policy_ek); + result = Tspi_Context_CloseObject(context, srk); + result = Tspi_Context_CloseObject(context, ek); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Clear Ownership + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::clear_ownership() +{ + if(b_help) + { + cout << "Clear Ownership (" << i_mode << ") --- Clears ownership data and deactivates TPM" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + } + if(i_success != 1) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_SHA1, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//CLEAR OWNERSHIP + if(b_debug) cerr << "Clear Ownership Section" << endl; + if(b_log) clog << "Clear Ownership Section" << endl; + + result = Tspi_TPM_ClearOwner(tpm, FALSE); + if(b_debug) cerr << ' ' << result << " CLEAR OWNERSHIP" << endl; + if(b_log) cerr << ' ' << result << " CLEAR OWNERSHIP" << endl; + return_code = result; + + +//CLEANUP + result = Tspi_Context_CloseObject(context, policy_tpm); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Collate Identity + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::collate_identity() +{ + if(b_help) + { + cout << "Collate Identity (" << i_mode << ") --- Creates an Attestation Identity Key (AIK)" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -key_auth (hex blob, identity key authorization data)" << endl; + cout << " -key_label (hex blob, hex representation of aik label)" << endl; + cout << " -pcak (hex blob, privacy CA key)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -ec_blob (hex blob, endorsement credential)" << endl; + cout << " -ec_nvram (flag, forces endorsement credential to load from NVRAM)" << endl; + cout << " -trousers (flag, manually determines credential size from DER x509 size header)" << endl; + cout << " OUTPUTS" << endl; + cout << " identity request (hex blob)" << endl; + cout << " modulus (hex blob, key modulus)" << endl; + cout << " key blob (hex blob, key blob)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string s_pcak; + string s_aiklabel; + string s_aikauth; + string s_ec; + int i_keyindex = 0; + bool ec_nvram = false; + bool ec_blob = false; + bool b_trousers = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-pcak") == 0) + { + if(++i >= i_argc) return; + s_pcak = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_label") == 0) + { + if(++i >= i_argc) return; + s_aiklabel = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_aikauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + + //explicitly load endorsement credential via hex blob + if(s_argv[i].compare("-ec_blob") == 0) + { + if(++i >= i_argc) return; + s_ec = s_argv[i]; + ec_blob = true; + } + + //explicitly load endorsement credential through NVRAM + if(s_argv[i].compare("-ec_nvram") == 0) + { + ec_nvram = true; + } + + if(s_argv[i].compare("-trousers") == 0) + { + b_trousers = true; + } + } + if(i_success != 5) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + NIARL_Util_ByteBlob pcakblob(s_pcak); + NIARL_Util_ByteBlob aiklabel(s_aiklabel); + NIARL_Util_ByteBlob aikauth(s_aikauth); + NIARL_Util_ByteBlob ec(s_ec); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_aik = TSS_UUID_USK2; + uuid_aik.rgbNode[5] = (BYTE)i_keyindex; + uuid_aik.rgbNode[0] = 0x04; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_SHA1, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//PRIVACY CA SECTION + TSS_HKEY pcak; + TSS_HPOLICY policy_pcak; + + if(b_debug) cerr << "PCAK Section" << endl; + if(b_log) clog << "PCAK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_SIZE_DEFAULT, &pcak); + if(b_debug) cerr << ' ' << result << " create pcak object" << endl; + if(b_log) cerr << ' ' << result << " create pcak object" << endl; + + result = Tspi_SetAttribData(pcak, TSS_TSPATTRIB_KEY_BLOB, TSS_TSPATTRIB_KEYBLOB_PUBLIC_KEY, pcakblob.size, pcakblob.blob); + if(b_debug) cerr << ' ' << result << " set pcak blob" << endl; + if(b_log) cerr << ' ' << result << " set pcak blob" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_pcak); + if(b_debug) cerr << ' ' << result << " create pcak policy" << endl; + if(b_log) cerr << ' ' << result << " create pcak policy" << endl; + + result = Tspi_Policy_SetSecret(policy_pcak, TSS_SECRET_MODE_SHA1, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " set auth" << endl; + if(b_log) cerr << ' ' << result << " set auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_pcak, pcak); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//AIK OPERATIONS (NOT SET YET) + TSS_HKEY aik; + TSS_HPOLICY policy_aik; + UINT32 init_flags = TSS_KEY_TYPE_IDENTITY | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "AIK Section" << endl; + if(b_log) clog << "AIK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &aik); + if(b_debug) cerr << ' ' << result << " create aik object" << endl; + if(b_log) cerr << ' ' << result << " create aik object" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_aik); + if(b_debug) cerr << ' ' << result << " create aik policy" << endl; + if(b_log) cerr << ' ' << result << " create aik policy" << endl; + + result = Tspi_Policy_SetSecret(policy_aik, TSS_SECRET_MODE_SHA1, aikauth.size, aikauth.blob); + if(b_debug) cerr << ' ' << result << " set aik auth" << endl; + if(b_log) cerr << ' ' << result << " set aik auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_aik, aik); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//ENDORSEMENT CREDENTIAL COMMANDS + if(ec_blob) + { + //explicitly load the endorsement credential from command line + result = Tspi_SetAttribData(tpm, TSS_TSPATTRIB_TPM_CREDENTIAL, TSS_TPMATTRIB_EKCERT, ec.size, ec.blob); + if(b_debug) cerr << ' ' << result << " load endorsement credential by command line" << endl; + if(b_log) cerr << ' ' << result << " load endorsement credential by command line" << endl; + } + else if(ec_nvram) + { + //NVSTORE SECTION + TSS_HNVSTORE nvstore; + UINT32 cred_size; + BYTE* cred_blob; + + if(b_debug) cerr << "NVStore Section" << endl; + if(b_log) clog << "NVStore Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_NV, NULL, &nvstore); + if(b_debug) cerr << ' ' << result << " create nvstore object" << endl; + if(b_log) cerr << ' ' << result << " create nvstore object" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, nvstore); + if(b_debug) cerr << ' ' << result << " assign owner auth" << endl; + if(b_log) cerr << ' ' << result << " assign owner auth" << endl; + + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_EKCert); + if(b_debug) cerr << " EK cert selected" << endl; + if(b_log) clog << " EK cert selected" << endl; + + if(b_trousers) + {//Trousers mode. Size cannot be automatically determined + if(b_debug) cerr << " Trousers mode activated" << endl; + if(b_log) clog << " Trousers mode activated" << endl; + + UINT32 counter = 0; + + cred_size = 10; //allow enough space to get DER x509 size header + result = Tspi_NV_ReadValue(nvstore, 0, &cred_size, &cred_blob); + + if((int)cred_blob[1] >= 128) //size is too big for [1] + { + counter = (int)cred_blob[1] - 128; + cred_size = 0; //reset cred size + + for(UINT32 i = 0; i < counter; i++) + { + cred_size *= 256; //base multiplier + cred_size += (int)cred_blob[2 + i]; //accumulator + } + } + else + { + cred_size = (int)cred_blob[1]; + } + + cred_size += 4; + + if(b_debug) cerr << " Credential size is " << cred_size << endl; + if(b_log) clog << " Credential size is " << cred_size << endl; + } + else + {//NTru mode + result = Tspi_GetAttribUint32(nvstore, TSS_TSPATTRIB_NV_DATASIZE, NULL, &cred_size); + if(b_debug) cerr << ' ' << result << " get nvstore size of " << cred_size << endl; + if(b_log) cerr << ' ' << result << " get nvstore size of " << cred_size << endl; + } + + result = Tspi_NV_ReadValue(nvstore, 0, &cred_size, &cred_blob); + if(b_debug) cerr << ' ' << result << " nv read" << endl; + if(b_log) cerr << ' ' << result << " nv read" << endl; + + //explicitly load the endorsement credential from NVRAM + result = Tspi_SetAttribData(tpm, TSS_TSPATTRIB_TPM_CREDENTIAL, TSS_TPMATTRIB_EKCERT, cred_size, cred_blob); + if(b_debug) cerr << ' ' << result << " load endorsement credential by NVRAM" << endl; + if(b_log) cerr << ' ' << result << " load endorsement credential by NVRAM" << endl; + + result = Tspi_Context_FreeMemory(context, cred_blob); + } + + +//COLLATE IDENTITY REQUEST + UINT32 idr_size; + BYTE* idr_blob; + + if(b_debug) cerr << "Collate Identity Request Section" << endl; + if(b_log) clog << "Collate Identity Request Section" << endl; + + result = Tspi_TPM_CollateIdentityRequest(tpm, srk, pcak, aiklabel.size, aiklabel.blob, aik, TSS_ALG_AES, &idr_size, &idr_blob); + if(b_debug) cerr << ' ' << result << " COLLATE IDENTITY" << endl; + if(b_log) cerr << ' ' << result << " COLLATE IDENTITY" << endl; + + if(result == 0) + { + for(UINT32 i = 0; i < idr_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)idr_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, idr_blob); + } + + +//OUTPUT AIK MODULUS AND BLOB + UINT32 mod_size; + UINT32 blob_size; + BYTE* mod_blob; + BYTE* blob_blob; + + if(b_debug) cerr << "AIK Output Section" << endl; + if(b_log) clog << "AIK Output Section" << endl; + + result = Tspi_GetAttribData(aik, TSS_TSPATTRIB_RSAKEY_INFO, TSS_TSPATTRIB_KEYINFO_RSA_MODULUS, &mod_size, &mod_blob); + if(b_debug) cerr << ' ' << result << " get modulus" << endl; + if(b_log) cerr << ' ' << result << " get modulus" << endl; + + if(result == 0) + { + if(!b_debug && !b_log) if(!b_debug && !b_log) cout << ' '; + + for(UINT32 i = 0; i < mod_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)mod_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, mod_blob); + } + + result = Tspi_GetAttribData(aik, TSS_TSPATTRIB_KEY_BLOB, TSS_TSPATTRIB_KEYBLOB_BLOB, &blob_size, &blob_blob); + if(b_debug) cerr << ' ' << result << " get key blob" << endl; + if(b_log) cerr << ' ' << result << " get key blob" << endl; + + if(result == 0) + { + if(!b_debug && !b_log) if(!b_debug && !b_log) cout << ' '; + + for(UINT32 i = 0; i < blob_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)blob_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, blob_blob); + } + + +//SAVE THE AIK + TSS_HKEY key_blank; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_SIZE_DEFAULT, &key_blank); + if(b_debug) cerr << ' ' << result << " create blank key" << endl; + if(b_log) cerr << ' ' << result << " create blank key" << endl; + + result = Tspi_Key_LoadKey(aik, srk); + if(b_debug) cerr << ' ' << result << " load the aik" << endl; + if(b_log) cerr << ' ' << result << " load the aik" << endl; + + result = Tspi_Context_RegisterKey(context, aik, TSS_PS_TYPE_SYSTEM, uuid_aik, TSS_PS_TYPE_SYSTEM, uuid_srk); + if(b_debug) cerr << ' ' << result << " register aik" << endl; + if(b_log) cerr << ' ' << result << " register aik" << endl; + return_code = result; + + if(result != 0) + { + result = Tspi_Context_UnregisterKey(context, TSS_PS_TYPE_SYSTEM, uuid_aik, &key_blank); + if(b_debug) cerr << ' ' << result << " unregister blank key" << endl; + if(b_log) cerr << ' ' << result << " unregister blank key" << endl; + + result = Tspi_Context_RegisterKey(context, aik, TSS_PS_TYPE_SYSTEM, uuid_aik, TSS_PS_TYPE_SYSTEM, uuid_srk); + if(b_debug) cerr << ' ' << result << " register aik" << endl; + if(b_log) cerr << ' ' << result << " register aik" << endl; + return_code = result; + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_tpm); + result = Tspi_Context_CloseObject(context, policy_aik); + result = Tspi_Context_CloseObject(context, policy_pcak); + result = Tspi_Context_CloseObject(context, aik); + result = Tspi_Context_CloseObject(context, pcak); + result = Tspi_Context_CloseObject(context, srk); + result = Tspi_Context_CloseObject(context, key_blank); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Activate Identity + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::activate_identity() +{ + if(b_help) + { + cout << "Activate Identity (" << i_mode << ") --- Creates an Attestation Identity Credential (AIC)" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -key_auth (hex blob, identity key authorization data)" << endl; + cout << " -asym (hex blob, CA asymmetric response)" << endl; + cout << " -sym (hex blob, CA symmetric response)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OUTPUTS" << endl; + cout << " attestation identity credential (AIC, hex blob)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string s_asym; + string s_sym; + string s_aikauth; + int i_keyindex = 0; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-asym") == 0) + { + if(++i >= i_argc) return; + s_asym = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-sym") == 0) + { + if(++i >= i_argc) return; + s_sym = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_aikauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success != 5) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + NIARL_Util_ByteBlob aikauth(s_aikauth); + NIARL_Util_ByteBlob ca_sym(s_sym); + NIARL_Util_ByteBlob ca_asym(s_asym); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_aik = TSS_UUID_USK2; + uuid_aik.rgbNode[5] = (BYTE)i_keyindex; + uuid_aik.rgbNode[0] = 0x04; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_SHA1, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//AIK OPERATIONS (SET) + TSS_HKEY aik; + TSS_HPOLICY policy_aik; + UINT32 init_flags = TSS_KEY_TYPE_IDENTITY | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "AIK Section" << endl; + if(b_log) clog << "AIK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &aik); + if(b_debug) cerr << ' ' << result << " create aik object" << endl; + if(b_log) cerr << ' ' << result << " create aik object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_aik, &aik); + if(b_debug) cerr << ' ' << result << " get uuid" << endl; + if(b_log) cerr << ' ' << result << " get uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_aik); + if(b_debug) cerr << ' ' << result << " create aik policy" << endl; + if(b_log) cerr << ' ' << result << " create aik policy" << endl; + + result = Tspi_Policy_SetSecret(policy_aik, TSS_SECRET_MODE_SHA1, aikauth.size, aikauth.blob); + if(b_debug) cerr << ' ' << result << " set aik auth" << endl; + if(b_log) cerr << ' ' << result << " set aik auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_aik, aik); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(aik, srk); + if(b_debug) cerr << ' ' << result << " load aik" << endl; + if(b_log) cerr << ' ' << result << " load aik" << endl; + + +//ACTIVATE IDENTITY + UINT32 aic_size; + BYTE* aic_blob; + + if(b_debug) cerr << "Activate Identity Section" << endl; + if(b_log) clog << "Activate Identity Section" << endl; + + result = Tspi_TPM_ActivateIdentity(tpm, aik, ca_asym.size, ca_asym.blob, ca_sym.size, ca_sym.blob, &aic_size, &aic_blob); + if(b_debug) cerr << ' ' << result << " ACTIVATE IDENTITY" << endl; + if(b_log) cerr << ' ' << result << " ACTIVATE IDENTITY" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < aic_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)aic_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, aic_blob); + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_tpm); + result = Tspi_Context_CloseObject(context, policy_aik); + result = Tspi_Context_CloseObject(context, aik); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Quote + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::quote() +{ + if(b_help) + { + cout << "Quote (" << i_mode << ") --- Provides a system integrity quote with signature" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -key_auth (hex blob, identity key authorization data)" << endl; + cout << " -nonce (hex blob, anti-replay nonce)" << endl; + cout << " -mask (hex string, controls PCR index selection)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OUTPUTS" << endl; + cout << " quote (hex blob, quote digest)" << endl; + cout << " signature (hex blob, quote signature)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_pcrs; + string s_aikauth; + string s_nonce; + int i_keyindex = 0; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-nonce") == 0) + { + if(++i >= i_argc) return; + s_nonce = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_aikauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-mask") == 0) + { + if(++i >= i_argc) return; + s_pcrs = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success != 4) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob aikauth(s_aikauth); + NIARL_Util_ByteBlob nonce(s_nonce); + NIARL_Util_Mask pcrmask(s_pcrs); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_aik = TSS_UUID_USK2; + uuid_aik.rgbNode[5] = (BYTE)i_keyindex; + uuid_aik.rgbNode[0] = 0x04; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//AIK OPERATIONS (SET) + TSS_HKEY aik; + TSS_HPOLICY policy_aik; + UINT32 init_flags = TSS_KEY_TYPE_IDENTITY | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "AIK Section" << endl; + if(b_log) clog << "AIK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &aik); + if(b_debug) cerr << ' ' << result << " create aik object" << endl; + if(b_log) cerr << ' ' << result << " create aik object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_aik, &aik); + if(b_debug) cerr << ' ' << result << " get uuid" << endl; + if(b_log) cerr << ' ' << result << " get uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_aik); + if(b_debug) cerr << ' ' << result << " create aik policy" << endl; + if(b_log) cerr << ' ' << result << " create aik policy" << endl; + + result = Tspi_Policy_SetSecret(policy_aik, TSS_SECRET_MODE_SHA1, aikauth.size, aikauth.blob); + if(b_debug) cerr << ' ' << result << " set aik auth" << endl; + if(b_log) cerr << ' ' << result << " set aik auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_aik, aik); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(aik, srk); + if(b_debug) cerr << ' ' << result << " load aik" << endl; + if(b_log) cerr << ' ' << result << " load aik" << endl; + + +//PCR OPERATIONS + TSS_HPCRS pcr; + UINT32 pcr_size; + BYTE* pcr_blob; + + if(b_debug) cerr << "PCR Section" << endl; + if(b_log) clog << "PCR Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_PCRS, 0, &pcr); + if(b_debug) cerr << ' ' << result << " create pcr object" << endl; + if(b_log) cerr << ' ' << result << " create pcr object" << endl; + + for(UINT32 i = 0; i < pcrmask.size; i++) + { + result = Tspi_PcrComposite_SetPcrValue(pcr, pcrmask.index[i], pcr_size, pcr_blob); + if(b_debug) cerr << ' ' << result << " set pcr value" << endl; + if(b_log) cerr << ' ' << result << " set pcr value" << endl; + } + + +//QUOTE OPERATIONS + TSS_VALIDATION validation; + + if(b_debug) cerr << "Quote Section" << endl; + if(b_log) clog << "Quote Section" << endl; + + memset(&validation, 0, sizeof(TSS_VALIDATION)); + validation.versionInfo.bMajor = 0x01; + validation.versionInfo.bMinor = 0x02; + validation.versionInfo.bRevMajor = 0x01; + validation.versionInfo.bRevMinor = 0x25; + validation.ulExternalDataLength = sizeof(TSS_NONCE); + validation.rgbExternalData = nonce.blob; + + result = Tspi_TPM_Quote(tpm, aik, pcr, &validation); + if(b_debug) cerr << ' ' << result << " QUOTE" << endl; + if(b_log) cerr << ' ' << result << " QUOTE" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < pcrmask.size; i++) + { + result = Tspi_PcrComposite_GetPcrValue(pcr, pcrmask.index[i], &pcr_size, &pcr_blob); + if(b_debug) cerr << ' ' << result << " set pcr value" << endl; + if(b_log) cerr << ' ' << result << " set pcr value" << endl; + + for(UINT32 j = 0; j < pcr_size; j++) + cout << setw(2) << setfill('0') << setbase(16) << (int)pcr_blob[j]; + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, pcr_blob); + if(b_debug) cerr << ' ' << result << " clear dynamic array" << endl; + if(b_log) cerr << ' ' << result << " clear dynamic array" << endl; + } + + for(UINT32 i = 0; i < validation.ulExternalDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbExternalData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < validation.ulDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < validation.ulValidationDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbValidationData[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + } + + +//CLEANUP SECTION + result = Tspi_Context_FreeMemory(context, validation.rgbData); + result = Tspi_Context_FreeMemory(context, validation.rgbValidationData); + result = Tspi_Context_FreeMemory(context, validation.rgbExternalData); + + result = Tspi_Context_CloseObject(context, policy_aik); + result = Tspi_Context_CloseObject(context, aik); + result = Tspi_Context_CloseObject(context, srk); + result = Tspi_Context_CloseObject(context, pcr); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Create Revocable EK + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::create_revokable_ek() +{ + if(b_help) + { + cout << "Create Revocable EK (" << i_mode << ") --- Creates a revocable EK" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -reset (hex blob, reset authorization blob)" << endl; + cout << " -nonce (hex blob, anti-replay nonce)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OUTPUTS" << endl; + cout << " Validation data?" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +/******************** + MODE DISABLED +********************/ +throw ERROR_MODE_DISABLED; + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string s_nonce; + string s_reset; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-nonce") == 0) + { + if(++i >= i_argc) return; + s_nonce = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-reset") == 0) + { + if(++i >= i_argc) return; + s_reset = s_argv[i]; + i_success++; + } + } + if(i_success != 3) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + NIARL_Util_ByteBlob nonce(s_nonce); + NIARL_Util_ByteBlob reset(s_reset); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_SHA1, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//REK SECTION + TSS_HKEY rek; + TSS_HPOLICY policy_rek; + + if(b_debug) cerr << "REK Section" << endl; + if(b_log) clog << "REK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_SIZE_DEFAULT, &rek); + if(b_debug) cerr << ' ' << result << " create rek object" << endl; + if(b_log) cerr << ' ' << result << " create rek object" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_rek); + if(b_debug) cerr << ' ' << result << " create rek policy" << endl; + if(b_log) cerr << ' ' << result << " create rek policy" << endl; + + result = Tspi_Policy_SetSecret(policy_rek, TSS_SECRET_MODE_SHA1, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " set rek auth" << endl; + if(b_log) cerr << ' ' << result << " set rek auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_rek, rek); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//CREATE REVOCABLE EK + TSS_VALIDATION validation; + + if(b_debug) cerr << "Create REK Section" << endl; + if(b_log) clog << "Create REK Section" << endl; + + memset(&validation, 0, sizeof(TSS_VALIDATION)); + validation.versionInfo.bMajor = 0x01; + validation.versionInfo.bMinor = 0x02; + validation.versionInfo.bRevMajor = 0x01; + validation.versionInfo.bRevMinor = 0x25; + validation.ulExternalDataLength = sizeof(TSS_NONCE); + validation.rgbExternalData = nonce.blob; + + result = Tspi_TPM_CreateRevocableEndorsementKey(tpm, rek, &validation, &reset.size, &reset.blob); + if(b_debug) cerr << ' ' << result << " CREATE REK" << endl; + if(b_log) cerr << ' ' << result << " CREATE REK" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < validation.ulExternalDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbExternalData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < validation.ulDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < validation.ulValidationDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbValidationData[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + } + + +//CLEANUP SECTION + result = Tspi_Context_FreeMemory(context, validation.rgbData); + result = Tspi_Context_FreeMemory(context, validation.rgbValidationData); + result = Tspi_Context_FreeMemory(context, validation.rgbExternalData); + + result = Tspi_Context_CloseObject(context, policy_tpm); + result = Tspi_Context_CloseObject(context, policy_rek); + result = Tspi_Context_CloseObject(context, rek); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Revoke EK + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::revoke_ek() +{ + if(b_help) + { + cout << "Revoke EK (" << i_mode << ") --- Revokes a revocable EK" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -reset (hex blob, reset authorization blob)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +/******************** + MODE DISABLED +********************/ +throw ERROR_MODE_DISABLED; + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string s_reset; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-reset") == 0) + { + if(++i >= i_argc) return; + s_reset = s_argv[i]; + i_success++; + } + } + if(i_success != 2) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + NIARL_Util_ByteBlob reset(s_reset); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_SHA1, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//CREATE REVOCABLE EK + + if(b_debug) cerr << "Revoke REK Section" << endl; + if(b_log) clog << "Revoke REK Section" << endl; + + result = Tspi_TPM_RevokeEndorsementKey(tpm, reset.size, reset.blob); + if(b_debug) cerr << ' ' << result << " REVOKE REK" << endl; + if(b_log) cerr << ' ' << result << " REVOKE REK" << endl; + return_code = result; + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_tpm); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Create Key + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::create_key() +{ + if(b_help) + { + cout << "Create Key (" << i_mode << ") --- Creates and stores (no overwrite) a binding or signing key" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -key_type (string, sign or bind)" << endl; + cout << " -key_auth (hex blob, key authorization data)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + cout << " -pkcs (flag, switches encoding from OAEP to PKCS for more space)" << endl; + cout << " OUTPUTS" << endl; + cout << " modulus (hex blob, key modulus)" << endl; + cout << " key blob (hex blob, key blob)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string keytype; + string s_keyauth; + int i_keyindex = 0; + bool b_1024 = false; + bool b_pkcs = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-pkcs") == 0) + { + b_pkcs = true; + } + + if(s_argv[i].compare("-key_type") == 0) + { + if(++i >= i_argc) return; + keytype = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success != 3) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob keyauth(s_keyauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_key = TSS_UUID_USK2; + uuid_key.rgbNode[5] = (BYTE)i_keyindex; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//KEY OPERATIONS (NOT SET YET) + TSS_HKEY key; + TSS_HPOLICY policy_key; + UINT32 init_flags; + + if(b_debug) cerr << "Key Section" << endl; + if(b_log) clog << "Key Section" << endl; + + if(keytype.compare("bind") == 0) + { + //uuid_key.rgbNode[5] = 0x05; + uuid_key.rgbNode[0] = 0x05; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << " binding key selected" << endl; + if(b_log) cerr << " binding key selected" << endl; + } + else if(keytype.compare("sign") == 0) + { + //uuid_key.rgbNode[5] = 0x06; + uuid_key.rgbNode[0] = 0x06; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << " signing key selected" << endl; + if(b_log) cerr << " signing key selected" << endl; + } + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &key); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_key); + if(b_debug) cerr << ' ' << result << " create key policy" << endl; + if(b_log) cerr << ' ' << result << " create key policy" << endl; + + result = Tspi_Policy_SetSecret(policy_key, TSS_SECRET_MODE_SHA1, keyauth.size, keyauth.blob); + if(b_debug) cerr << ' ' << result << " set key auth" << endl; + if(b_log) cerr << ' ' << result << " set key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_key, key); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + if(b_pkcs) + { + result = Tspi_SetAttribUint32(key, TSS_TSPATTRIB_KEY_INFO, TSS_TSPATTRIB_KEYINFO_ENCSCHEME, TSS_ES_RSAESPKCSV15); + if(b_debug) cerr << ' ' << result << " set encryption scheme to PKCS" << endl; + if(b_log) cerr << ' ' << result << " set encryption scheme to PKCS" << endl; + } + + +//CREATE KEY + UINT32 mod_size; + UINT32 blob_size; + BYTE* mod_blob; + BYTE* blob_blob; + + if(b_debug) cerr << "Create Key Section" << endl; + if(b_log) clog << "Create Key Section" << endl; + + result = Tspi_Key_CreateKey(key, srk, NULL); + if(b_debug) cerr << ' ' << result << " CREATE KEY" << endl; + if(b_log) cerr << ' ' << result << " CREATE KEY" << endl; + + result = Tspi_GetAttribData(key, TSS_TSPATTRIB_RSAKEY_INFO, TSS_TSPATTRIB_KEYINFO_RSA_MODULUS, &mod_size, &mod_blob); + if(b_debug) cerr << ' ' << result << " get modulus" << endl; + if(b_log) cerr << ' ' << result << " get modulus" << endl; + + if(result == 0) + { + for(UINT32 i = 0; i < mod_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)mod_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, mod_blob); + } + + result = Tspi_GetAttribData(key, TSS_TSPATTRIB_KEY_BLOB, TSS_TSPATTRIB_KEYBLOB_BLOB, &blob_size, &blob_blob); + if(b_debug) cerr << ' ' << result << " get key blob" << endl; + if(b_log) cerr << ' ' << result << " get key blob" << endl; + + if(result == 0) + { + if(!b_debug && !b_log) if(!b_debug && !b_log) cout << ' '; + + for(UINT32 i = 0; i < blob_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)blob_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, blob_blob); + } + + +//SAVE THE KEY + result = Tspi_Key_LoadKey(key, srk); + if(b_debug) cerr << ' ' << result << " load the new key" << endl; + if(b_log) cerr << ' ' << result << " load the new key" << endl; + + result = Tspi_Context_RegisterKey(context, key, TSS_PS_TYPE_SYSTEM, uuid_key, TSS_PS_TYPE_SYSTEM, uuid_srk); + if(b_debug) cerr << ' ' << result << " register new key" << endl; + if(b_log) cerr << ' ' << result << " register new key" << endl; + return_code = result; + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_key); + result = Tspi_Context_CloseObject(context, key); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Set Key + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::set_key() +{ + if(b_help) + { + cout << "Set Key (" << i_mode << ") --- Creates and stores (no overwrite) a signing, binding, or identity via a key blob" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -key_type (string, sign or bind or identity)" << endl; + cout << " -key_auth (hex blob, key authorization data)" << endl; + cout << " -key_blob (hex blob, key blob)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string keytype; + string s_keyauth; + string s_keyblob; + int i_keyindex = 0; + bool b_1024 = false; + bool b_pkcs = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-pkcs") == 0) + { + b_pkcs = true; + } + + if(s_argv[i].compare("-key_type") == 0) + { + if(++i >= i_argc) return; + keytype = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_blob") == 0) + { + if(++i >= i_argc) return; + s_keyblob = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success != 4) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob keyauth(s_keyauth); + NIARL_Util_ByteBlob keyblob(s_keyblob); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_key = TSS_UUID_USK2; + uuid_key.rgbNode[5] = (BYTE)i_keyindex; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//KEY OPERATIONS (NOT SET YET) + TSS_HKEY key; + TSS_HPOLICY policy_key; + UINT32 init_flags; + + if(b_debug) cerr << "Key Section" << endl; + if(b_log) clog << "Key Section" << endl; + + if(keytype.compare("identity") == 0) + { + //uuid_key.rgbNode[5] = 0x04; + uuid_key.rgbNode[0] = 0x04; + init_flags = TSS_KEY_TYPE_IDENTITY | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + if(b_debug) cerr << "aik selected" << endl; + if(b_log) clog << "aik selected" << endl; + } + else if(keytype.compare("bind") == 0) + { + //uuid_key.rgbNode[5] = 0x05; + uuid_key.rgbNode[0] = 0x05; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << " binding key selected" << endl; + if(b_log) cerr << " binding key selected" << endl; + } + else if(keytype.compare("sign") == 0) + { + //uuid_key.rgbNode[5] = 0x06; + uuid_key.rgbNode[0] = 0x06; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << " signing key selected" << endl; + if(b_log) cerr << " signing key selected" << endl; + } + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &key); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_SetAttribData(key, TSS_TSPATTRIB_KEY_BLOB, TSS_TSPATTRIB_KEYBLOB_BLOB, keyblob.size, keyblob.blob); + if(b_debug) cerr << ' ' << result << " set key blob" << endl; + if(b_log) cerr << ' ' << result << " set key blob" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_key); + if(b_debug) cerr << ' ' << result << " create key policy" << endl; + if(b_log) cerr << ' ' << result << " create key policy" << endl; + + result = Tspi_Policy_SetSecret(policy_key, TSS_SECRET_MODE_SHA1, keyauth.size, keyauth.blob); + if(b_debug) cerr << ' ' << result << " set key auth" << endl; + if(b_log) cerr << ' ' << result << " set key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_key, key); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + if(b_pkcs) + { + result = Tspi_SetAttribUint32(key, TSS_TSPATTRIB_KEY_INFO, TSS_TSPATTRIB_KEYINFO_ENCSCHEME, TSS_ES_RSAESPKCSV15); + if(b_debug) cerr << ' ' << result << " set encryption scheme to PKCS" << endl; + if(b_log) cerr << ' ' << result << " set encryption scheme to PKCS" << endl; + } + + +//SAVE THE KEY + result = Tspi_Key_LoadKey(key, srk); + if(b_debug) cerr << ' ' << result << " load the new key" << endl; + if(b_log) cerr << ' ' << result << " load the new key" << endl; + + result = Tspi_Context_RegisterKey(context, key, TSS_PS_TYPE_SYSTEM, uuid_key, TSS_PS_TYPE_SYSTEM, uuid_srk); + if(b_debug) cerr << ' ' << result << " register new key" << endl; + if(b_log) cerr << ' ' << result << " register new key" << endl; + return_code = result; + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_key); + result = Tspi_Context_CloseObject(context, key); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Get Key + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::get_key() +{ + if(b_help) + { + cout << "Get Key (" << i_mode << ") --- Gets the modulus and blob of an identity, signing, or binding key" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -key_type (string, sign or bind or identity or ek)" << endl; + cout << " EK PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -nonce (hex blob, anti-replay nonce, REQUIRED FOR EK)" << endl; + cout << " BIND, SIGN, AND AIK PARAMETERS" << endl; + cout << " -key_index (integer, index number for key, REQUIRED FOR KEY)" << endl; + cout << " -key_auth (hex blob, key authorization data, owner auth for ek)" << endl; + cout << " OPTIONAL PARAMETERS FOR BIND AND SIGN" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + cout << " OUTPUTS" << endl; + cout << " modulus (hex blob, key modulus)" << endl; + cout << " key blob (hex blob, key blob)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string keytype; + string s_keyauth; + string s_nonce; + int i_keyindex = 0; + bool b_1024 = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_type") == 0) + { + if(++i >= i_argc) return; + keytype = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-nonce") == 0) + { + if(++i >= i_argc) return; + s_nonce = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success < 3) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + NIARL_Util_ByteBlob keyauth(s_keyauth); + NIARL_Util_ByteBlob nonce(s_nonce); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_key = TSS_UUID_USK2; + uuid_key.rgbNode[5] = (BYTE)i_keyindex; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + if(keytype.compare("ek") == 0) + { //ek only commands + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_SHA1, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + } + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//KEY OPERATIONS (SET) + TSS_VALIDATION validation; + TSS_HKEY key; + TSS_HPOLICY policy_key; + UINT32 init_flags; + + if(b_debug) cerr << "Key Section" << endl; + if(b_log) clog << "Key Section" << endl; + + if(keytype.compare("identity") == 0) + { + //uuid_key.rgbNode[5] = 0x04; + uuid_key.rgbNode[0] = 0x04; + init_flags = TSS_KEY_TYPE_IDENTITY | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + if(b_debug) cerr << "aik selected" << endl; + if(b_log) clog << "aik selected" << endl; + } + else if(keytype.compare("bind") == 0) + { + //uuid_key.rgbNode[5] = 0x05; + uuid_key.rgbNode[0] = 0x05; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "binding key selected" << endl; + if(b_log) clog << "binding key selected" << endl; + } + else if(keytype.compare("sign") == 0) + { + //uuid_key.rgbNode[5] = 0x06; + uuid_key.rgbNode[0] = 0x06; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "signing key selected" << endl; + if(b_log) clog << "signing key selected" << endl; + } + + if(keytype.compare("ek") == 0) + { //ek only commands + memset(&validation, 0, sizeof(TSS_VALIDATION)); + validation.versionInfo.bMajor = 0x01; + validation.versionInfo.bMinor = 0x02; + validation.versionInfo.bRevMajor = 0x01; + validation.versionInfo.bRevMinor = 0x25; + validation.ulExternalDataLength = sizeof(TSS_NONCE); + validation.rgbExternalData = nonce.blob; + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_SIZE_DEFAULT, &key); + if(b_debug) cerr << ' ' << result << " create ek object" << endl; + if(b_log) cerr << ' ' << result << " create ek object" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, key); + if(b_debug) cerr << ' ' << result << " assign owner auth to ek" << endl; + if(b_log) cerr << ' ' << result << " assign owner auth to ek" << endl; + + result = Tspi_TPM_GetPubEndorsementKey(tpm, true, &validation, &key); + if(b_debug) cerr << ' ' << result << " get public ek" << endl; + if(b_log) cerr << ' ' << result << " get public ek" << endl; + } + else + { //commands for aik, signing, and binding keys + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &key); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_key, &key); + if(b_debug) cerr << ' ' << result << " load key by uuid" << endl; + if(b_log) cerr << ' ' << result << " load key by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_key); + if(b_debug) cerr << ' ' << result << " create key policy" << endl; + if(b_log) cerr << ' ' << result << " create key policy" << endl; + + result = Tspi_Policy_SetSecret(policy_key, TSS_SECRET_MODE_SHA1, keyauth.size, keyauth.blob); + if(b_debug) cerr << ' ' << result << " set key auth" << endl; + if(b_log) cerr << ' ' << result << " set key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_key, key); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(key, srk); + if(b_debug) cerr << ' ' << result << " load key" << endl; + if(b_log) cerr << ' ' << result << " load key" << endl; + } + + +//GET KEY + UINT32 mod_size; + UINT32 blob_size; + BYTE* mod_blob; + BYTE* blob_blob; + + if(b_debug) cerr << "Get Key Section" << endl; + if(b_log) clog << "Get Key Section" << endl; + + result = Tspi_GetAttribData(key, TSS_TSPATTRIB_RSAKEY_INFO, TSS_TSPATTRIB_KEYINFO_RSA_MODULUS, &mod_size, &mod_blob); + if(b_debug) cerr << ' ' << result << " get modulus" << endl; + if(b_log) cerr << ' ' << result << " get modulus" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < mod_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)mod_blob[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) cerr << endl; + + result = Tspi_Context_FreeMemory(context, mod_blob); + } + + if(keytype.compare("ek") != 0) + { + result = Tspi_GetAttribData(key, TSS_TSPATTRIB_KEY_BLOB, TSS_TSPATTRIB_KEYBLOB_BLOB, &blob_size, &blob_blob); + if(b_debug) cerr << ' ' << result << " get key blob" << endl; + if(b_log) cerr << ' ' << result << " get key blob" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < blob_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)blob_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, blob_blob); + } + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_tpm); + result = Tspi_Context_CloseObject(context, policy_key); + result = Tspi_Context_CloseObject(context, key); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Clear Key + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::clear_key() +{ + if(b_help) + { + cout << "Clear Key (" << i_mode << ") --- Clears an existing identity, signing, or binding key" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -key_type (string, sign or bind or identity)" << endl; + cout << " -key_auth (hex blob, key authorization data)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string keytype; + string s_keyauth; + int i_keyindex = 0; + bool b_1024 = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-key_type") == 0) + { + if(++i >= i_argc) return; + keytype = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success != 3) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob keyauth(s_keyauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_key = TSS_UUID_USK2; + uuid_key.rgbNode[5] = (BYTE)i_keyindex; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//KEY OPERATIONS (SET) + TSS_HKEY key; + TSS_HPOLICY policy_key; + UINT32 init_flags; + + if(b_debug) cerr << "Key Section" << endl; + if(b_log) clog << "Key Section" << endl; + + if(keytype.compare("identity") == 0) + { + //uuid_key.rgbNode[5] = 0x04; + uuid_key.rgbNode[0] = 0x04; + init_flags = TSS_KEY_TYPE_IDENTITY | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + if(b_debug) cerr << "aik selected" << endl; + if(b_log) clog << "aik selected" << endl; + } + else if(keytype.compare("bind") == 0) + { + //uuid_key.rgbNode[5] = 0x05; + uuid_key.rgbNode[0] = 0x05; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "binding key selected" << endl; + if(b_log) clog << "binding key selected" << endl; + } + else if(keytype.compare("sign") == 0) + { + //uuid_key.rgbNode[5] = 0x06; + uuid_key.rgbNode[0] = 0x06; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "signing key selected" << endl; + if(b_log) clog << "signing key selected" << endl; + } + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &key); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_key, &key); + if(b_debug) cerr << ' ' << result << " load key by uuid" << endl; + if(b_log) cerr << ' ' << result << " load key by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_key); + if(b_debug) cerr << ' ' << result << " create key policy" << endl; + if(b_log) cerr << ' ' << result << " create key policy" << endl; + + result = Tspi_Policy_SetSecret(policy_key, TSS_SECRET_MODE_SHA1, keyauth.size, keyauth.blob); + if(b_debug) cerr << ' ' << result << " set key auth" << endl; + if(b_log) cerr << ' ' << result << " set key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_key, key); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(key, srk); + if(b_debug) cerr << ' ' << result << " load key" << endl; + if(b_log) cerr << ' ' << result << " load key" << endl; + + +//CLEAR KEY + TSS_HKEY key_blank; + + if(b_debug) cerr << "Clear Key Section" << endl; + if(b_log) clog << "Clear Key Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_SIZE_DEFAULT, &key_blank); + if(b_debug) cerr << ' ' << result << " create blank key" << endl; + if(b_log) cerr << ' ' << result << " create blank key" << endl; + + result = Tspi_Context_UnregisterKey(context, TSS_PS_TYPE_SYSTEM, uuid_key, &key_blank); + if(b_debug) cerr << ' ' << result << " UNREGISTER" << endl; + if(b_log) cerr << ' ' << result << " UNREGISTER" << endl; + return_code = result; + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_key); + result = Tspi_Context_CloseObject(context, key); + result = Tspi_Context_CloseObject(context, key_blank); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Set Credential + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::set_credential() +{ + if(b_help) + { + cout << "Set Credential (" << i_mode << ") --- Sets a TPM credential (no overwrite)" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -cred_type (string, EC or CC or PC or PCC)" << endl; + cout << " -blob (hex blob, credential)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string s_credtype; + string s_blob; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-cred_type") == 0) + { + if(++i >= i_argc) return; + s_credtype = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-blob") == 0) + { + if(++i >= i_argc) return; + s_blob = s_argv[i]; + i_success++; + } + } + if(i_success != 3) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + NIARL_Util_ByteBlob credential(s_blob); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_SHA1, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//NVSTORE SECTION + TSS_HNVSTORE nvstore; + + if(b_debug) cerr << "NVStore Section" << endl; + if(b_log) clog << "NVStore Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_NV, NULL, &nvstore); + if(b_debug) cerr << ' ' << result << " create nvstore object" << endl; + if(b_log) cerr << ' ' << result << " create nvstore object" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, nvstore); + if(b_debug) cerr << ' ' << result << " assign owner auth" << endl; + if(b_log) cerr << ' ' << result << " assign owner auth" << endl; + + if(s_credtype.compare("EC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_EKCert); + if(b_debug) cerr << " EK cert selected" << endl; + if(b_log) clog << " EK cert selected" << endl; + } + + else if(s_credtype.compare("CC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_TPM_CC); + if(b_debug) cerr << " Conformance cert selected" << endl; + if(b_log) clog << " Conformance cert selected" << endl; + } + + else if(s_credtype.compare("PC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_PlatformCert); + if(b_debug) cerr << " Platform cert selected" << endl; + if(b_log) clog << " Platform cert selected" << endl; + } + + else if(s_credtype.compare("PCC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_Platform_CC); + if(b_debug) cerr << "Platform Conformance cert selected" << endl; + if(b_log) clog << "Platform Conformance cert selected" << endl; + } + + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_PERMISSIONS, NULL, TPM_NV_PER_OWNERREAD | TPM_NV_PER_OWNERWRITE); + if(b_debug) cerr << ' ' << result << " set nvstore permissions" << endl; + if(b_log) cerr << ' ' << result << " set nvstore permissions" << endl; + + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_DATASIZE, NULL, credential.size); + if(b_debug) cerr << ' ' << result << " set nvstore size" << endl; + if(b_log) cerr << ' ' << result << " set nvstore size" << endl; + + result = Tspi_NV_DefineSpace(nvstore, NULL, NULL); + if(b_debug) cerr << ' ' << result << " define space" << endl; + if(b_log) cerr << ' ' << result << " define space" << endl; + + result = Tspi_NV_WriteValue(nvstore, 0, credential.size, credential.blob); + if(b_debug) cerr << ' ' << result << " nv write" << endl; + if(b_log) cerr << ' ' << result << " nv write" << endl; + return_code = result; + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_tpm); + result = Tspi_Context_CloseObject(context, nvstore); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Get Credential + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::get_credential() +{ + if(b_help) + { + cout << "Get Credential (" << i_mode << ") --- Gets an existing TPM credential" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -cred_type (string, EC or CC or PC or PCC)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -trousers (flag, manually determines credential size from DER x509 size header)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string s_credtype; + bool b_trousers = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-cred_type") == 0) + { + if(++i >= i_argc) return; + s_credtype = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-trousers") == 0) + { + b_trousers = true; + } + } + if(i_success != 2) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_SHA1, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//NVSTORE SECTION + TSS_HNVSTORE nvstore; + UINT32 cred_size; + BYTE* cred_blob; + + if(b_debug) cerr << "NVStore Section" << endl; + if(b_log) clog << "NVStore Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_NV, NULL, &nvstore); + if(b_debug) cerr << ' ' << result << " create nvstore object" << endl; + if(b_log) cerr << ' ' << result << " create nvstore object" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, nvstore); + if(b_debug) cerr << ' ' << result << " assign owner auth" << endl; + if(b_log) cerr << ' ' << result << " assign owner auth" << endl; + + if(s_credtype.compare("EC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_EKCert); + if(b_debug) cerr << " EK cert selected" << endl; + if(b_log) clog << " EK cert selected" << endl; + } + + else if(s_credtype.compare("CC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_TPM_CC); + if(b_debug) cerr << " Conformance cert selected" << endl; + if(b_log) clog << " Conformance cert selected" << endl; + } + + else if(s_credtype.compare("PC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_PlatformCert); + if(b_debug) cerr << " Platform cert selected" << endl; + if(b_log) clog << " Platform cert selected" << endl; + } + + else if(s_credtype.compare("PCC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_Platform_CC); + if(b_debug) cerr << " Platform Conformance cert selected" << endl; + if(b_log) clog << " Platform Conformance cert selected" << endl; + } + + if(b_trousers) + {//Trousers mode. Size cannot be automatically determined + if(b_debug) cerr << " Trousers mode activated" << endl; + if(b_log) clog << " Trousers mode activated" << endl; + + UINT32 counter = 0; + + cred_size = 10; //allow enough space to get DER x509 size header + result = Tspi_NV_ReadValue(nvstore, 0, &cred_size, &cred_blob); + + if((int)cred_blob[1] >= 128) //size is too big for [1] + { + counter = (int)cred_blob[1] - 128; + cred_size = 0; //reset cred size + + for(UINT32 i = 0; i < counter; i++) + { + cred_size *= 256; //base multiplier + cred_size += (int)cred_blob[2 + i]; //accumulator + } + } + else + { + cred_size = (int)cred_blob[1]; + } + + cred_size += 4; + + if(b_debug) cerr << " Credential size is " << cred_size << endl; + if(b_log) clog << " Credential size is " << cred_size << endl; + } + else + {//NTru mode + result = Tspi_GetAttribUint32(nvstore, TSS_TSPATTRIB_NV_DATASIZE, NULL, &cred_size); + if(b_debug) cerr << ' ' << result << " get nvstore size of " << cred_size << endl; + if(b_log) cerr << ' ' << result << " get nvstore size of " << cred_size << endl; + } + + result = Tspi_NV_ReadValue(nvstore, 0, &cred_size, &cred_blob); + if(b_debug) cerr << ' ' << result << " nv read" << endl; + if(b_log) cerr << ' ' << result << " nv read" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < cred_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)cred_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, cred_blob); + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_tpm); + result = Tspi_Context_CloseObject(context, nvstore); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Clear Credential + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::clear_credential() +{ + if(b_help) + { + cout << "Clear Credential (" << i_mode << ") --- Clears an existing TPM credential" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -owner_auth (hex blob, owner authorization)" << endl; + cout << " -cred_type (string, EC or CC or PC or PCC)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_ownerauth; + string s_credtype; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-owner_auth") == 0) + { + if(++i >= i_argc) return; + s_ownerauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-cred_type") == 0) + { + if(++i >= i_argc) return; + s_credtype = s_argv[i]; + i_success++; + } + } + if(i_success != 2) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob ownerauth(s_ownerauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + TSS_HPOLICY policy_tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_tpm); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_tpm, TSS_SECRET_MODE_SHA1, ownerauth.size, ownerauth.blob); + if(b_debug) cerr << ' ' << result << " owner auth" << endl; + if(b_log) cerr << ' ' << result << " owner auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, tpm); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + +//NVSTORE SECTION + TSS_HNVSTORE nvstore; + + if(b_debug) cerr << "NVStore Section" << endl; + if(b_log) clog << "NVStore Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_NV, NULL, &nvstore); + if(b_debug) cerr << ' ' << result << " create nvstore object" << endl; + if(b_log) cerr << ' ' << result << " create nvstore object" << endl; + + result = Tspi_Policy_AssignToObject(policy_tpm, nvstore); + if(b_debug) cerr << ' ' << result << " assign owner auth" << endl; + if(b_log) cerr << ' ' << result << " assign owner auth" << endl; + + if(s_credtype.compare("EC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_EKCert); + if(b_debug) cerr << " EK cert selected" << endl; + if(b_log) clog << " EK cert selected" << endl; + } + + + else if(s_credtype.compare("CC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_TPM_CC); + if(b_debug) cerr << " Conformance cert selected" << endl; + if(b_log) clog << " Conformance cert selected" << endl; + } + + else if(s_credtype.compare("PC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_PlatformCert); + if(b_debug) cerr << " Platform cert selected" << endl; + if(b_log) clog << " Platform cert selected" << endl; + } + + else if(s_credtype.compare("PCC") == 0) + { + result = Tspi_SetAttribUint32(nvstore, TSS_TSPATTRIB_NV_INDEX, NULL, TPM_NV_INDEX_Platform_CC); + if(b_debug) cerr << " Platform Conformance cert selected" << endl; + if(b_log) clog << " Platform Conformance cert selected" << endl; + } + + result = Tspi_NV_ReleaseSpace(nvstore); + if(b_debug) cerr << ' ' << result << " nv release" << endl; + if(b_log) cerr << ' ' << result << " nv release" << endl; + return_code = result; + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_tpm); + result = Tspi_Context_CloseObject(context, nvstore); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Seal + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::seal() +{ + if(b_help) + { + cout << "Seal (" << i_mode << ") --- Encrypts data based on machine state" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -blob (hex blob, data to encrypt)" << endl; + cout << " -blob_auth (hex blob, data blob authorization data)" << endl; + cout << " -mask (hex string, controls PCR index selection)" << endl; + cout << " OUTPUTS" << endl; + cout << " sealed data blob (hex blob, encrypted blob)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_blob; + string s_pcrs; + string s_encauth; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-blob") == 0) + { + if(++i >= i_argc) return; + s_blob = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-mask") == 0) + { + if(++i >= i_argc) return; + s_pcrs = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-blob_auth") == 0) + { + if(++i >= i_argc) return; + s_encauth = s_argv[i]; + i_success++; + } + } + if(i_success != 3) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob datablob(s_blob); + NIARL_Util_Mask pcrmask(s_pcrs); + NIARL_Util_ByteBlob encauth(s_encauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//ENCDATA SECTION + TSS_HENCDATA encdata; + TSS_HPOLICY policy_encdata; + + if(b_debug) cerr << "EncData Section" << endl; + if(b_log) clog << "EncData Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_ENCDATA, TSS_ENCDATA_SEAL, &encdata); + if(b_debug) cerr << ' ' << result << " create encdata" << endl; + if(b_log) cerr << ' ' << result << " create encdata" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_encdata); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_encdata, TSS_SECRET_MODE_SHA1, encauth.size, encauth.blob); + if(b_debug) cerr << ' ' << result << " encdata auth" << endl; + if(b_log) cerr << ' ' << result << " encdata auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_encdata, encdata); + if(b_debug) cerr << ' ' << result << " assign encdata authorization" << endl; + if(b_log) cerr << ' ' << result << " assign encdata authorization" << endl; + + +//PCR OPERATIONS + TSS_HPCRS pcr; + UINT32 pcr_size; + BYTE* pcr_blob; + + if(b_debug) cerr << "PCR Section" << endl; + if(b_log) clog << "PCR Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_PCRS, 0, &pcr); + if(b_debug) cerr << ' ' << result << " create pcr object" << endl; + if(b_log) cerr << ' ' << result << " create pcr object" << endl; + + for(UINT32 i = 0; i < pcrmask.size; i++) + { + result = Tspi_TPM_PcrRead(tpm, pcrmask.index[i], &pcr_size, &pcr_blob); + if(b_debug) cerr << ' ' << result << " read pcr index " << pcrmask.index[i] << endl; + if(b_log) cerr << ' ' << result << " read pcr index " << pcrmask.index[i] << endl; + + result = Tspi_PcrComposite_SelectPcrIndex(pcr, pcrmask.index[i]); + if(b_debug) cerr << ' ' << result << " select composite index" << endl; + if(b_log) cerr << ' ' << result << " select composite index" << endl; + + result = Tspi_PcrComposite_SetPcrValue(pcr, pcrmask.index[i], pcr_size, pcr_blob); + if(b_debug) cerr << ' ' << result << " set pcr value" << endl; + if(b_log) cerr << ' ' << result << " set pcr value" << endl; + +// for(UINT32 j = 0; j < pcr_size; j++) +// cout << setw(2) << setfill('0') << setbase(16) << (int)pcr_blob[j]; +// if(b_debug) cerr << endl; +// if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, pcr_blob); + if(b_debug) cerr << ' ' << result << " clear dynamic array" << endl; + if(b_log) cerr << ' ' << result << " clear dynamic array" << endl; + } + + +//SEAL OPERATIONS + UINT32 enc_size; + BYTE* enc_blob; + + if(b_debug) cerr << "Seal Section" << endl; + if(b_log) clog << "Seal Section" << endl; + + result = Tspi_Data_Seal(encdata, srk, datablob.size, datablob.blob, pcr); + if(b_debug) cerr << ' ' << result << " SEAL" << endl; + if(b_log) cerr << ' ' << result << " SEAL" << endl; + return_code = result; + + if(result == 0) + { + result = Tspi_GetAttribData(encdata, TSS_TSPATTRIB_ENCDATA_BLOB, TSS_TSPATTRIB_ENCDATABLOB_BLOB, &enc_size, &enc_blob); + if(b_debug) cerr << ' ' << result << " get sealed blob" << endl; + if(b_log) cerr << ' ' << result << " get sealed blob" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < enc_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)enc_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, enc_blob); + } + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_encdata); + result = Tspi_Context_CloseObject(context, encdata); + result = Tspi_Context_CloseObject(context, srk); + result = Tspi_Context_CloseObject(context, pcr); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Unseal + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::unseal() +{ + if(b_help) + { + cout << "Unseal (" << i_mode << ") --- Decrypts data based on machine state" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -blob (hex blob, data to decrypt)" << endl; + cout << " -blob_auth (hex blob, data blob authorization data)" << endl; + cout << " OUTPUTS" << endl; + cout << " unsealed data blob (hex blob, decrypted data)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_blob; + string s_encauth; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-blob") == 0) + { + if(++i >= i_argc) return; + s_blob = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-blob_auth") == 0) + { + if(++i >= i_argc) return; + s_encauth = s_argv[i]; + i_success++; + } + } + if(i_success != 2) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob datablob(s_blob); + NIARL_Util_ByteBlob encauth(s_encauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//ENCDATA SECTION + TSS_HENCDATA encdata; + TSS_HPOLICY policy_encdata; + + if(b_debug) cerr << "EncData Section" << endl; + if(b_log) clog << "EncData Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_ENCDATA, TSS_ENCDATA_SEAL, &encdata); + if(b_debug) cerr << ' ' << result << " create encdata" << endl; + if(b_log) cerr << ' ' << result << " create encdata" << endl; + + result = Tspi_SetAttribData(encdata, TSS_TSPATTRIB_ENCDATA_BLOB, TSS_TSPATTRIB_ENCDATABLOB_BLOB, datablob.size, datablob.blob); + if(b_debug) cerr << ' ' << result << " load data blob" << endl; + if(b_log) cerr << ' ' << result << " load data blob" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_encdata); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_encdata, TSS_SECRET_MODE_SHA1, encauth.size, encauth.blob); + if(b_debug) cerr << ' ' << result << " encdata auth" << endl; + if(b_log) cerr << ' ' << result << " encdata auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_encdata, encdata); + if(b_debug) cerr << ' ' << result << " assign encdata authorization" << endl; + if(b_log) cerr << ' ' << result << " assign encdata authorization" << endl; + + +//UNSEAL OPERATIONS + UINT32 enc_size; + BYTE* enc_blob; + + if(b_debug) cerr << "Unseal Section" << endl; + if(b_log) clog << "Unseal Section" << endl; + + result = Tspi_Data_Unseal(encdata, srk, &enc_size, &enc_blob); + if(b_debug) cerr << ' ' << result << " UNSEAL" << endl; + if(b_log) cerr << ' ' << result << " UNSEAL" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < enc_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)enc_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, enc_blob); + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_encdata); + result = Tspi_Context_CloseObject(context, encdata); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Bind + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::bind() +{ + if(b_help) + { + cout << "Bind (" << i_mode << ") --- Encrypts data based on a binding key" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -blob (hex blob, data to encrypt)" << endl; + cout << " -blob_auth (hex blob, data blob authorization data)" << endl; + cout << " -key_auth (hex blob, binding key authorization data)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + cout << " OUTPUTS" << endl; + cout << " binded data blob (hex blob, encrypted data)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_blob; + string s_keyauth; + string s_encauth; + int i_keyindex = 0; + bool b_1024 = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-blob") == 0) + { + if(++i >= i_argc) return; + s_blob = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + + if(s_argv[i].compare("-blob_auth") == 0) + { + if(++i >= i_argc) return; + s_encauth = s_argv[i]; + i_success++; + } + } + if(i_success != 4) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob datablob(s_blob); + NIARL_Util_ByteBlob bindauth(s_keyauth); + NIARL_Util_ByteBlob encauth(s_encauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_bind = TSS_UUID_USK2; + uuid_bind.rgbNode[5] = (BYTE)i_keyindex; + uuid_bind.rgbNode[0] = 0x05; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//BIND OPERATIONS (SET) + TSS_HKEY bind; + TSS_HPOLICY policy_bind; + UINT32 init_flags; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "Bind Key Section" << endl; + if(b_log) clog << "Bind Key Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &bind); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_bind, &bind); + if(b_debug) cerr << ' ' << result << " load by UUID" << endl; + if(b_log) cerr << ' ' << result << " load by UUID" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_bind); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_bind, TSS_SECRET_MODE_SHA1, bindauth.size, bindauth.blob); + if(b_debug) cerr << ' ' << result << " key auth" << endl; + if(b_log) cerr << ' ' << result << " key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_bind, bind); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(bind, srk); + if(b_debug) cerr << ' ' << result << " load key" << endl; + if(b_log) cerr << ' ' << result << " load key" << endl; + + +//ENCDATA SECTION + TSS_HENCDATA encdata; + TSS_HPOLICY policy_encdata; + + if(b_debug) cerr << "EncData Section" << endl; + if(b_log) clog << "EncData Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_ENCDATA, TSS_ENCDATA_BIND, &encdata); + if(b_debug) cerr << ' ' << result << " create encdata" << endl; + if(b_log) cerr << ' ' << result << " create encdata" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_encdata); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_encdata, TSS_SECRET_MODE_SHA1, encauth.size, encauth.blob); + if(b_debug) cerr << ' ' << result << " encdata auth" << endl; + if(b_log) cerr << ' ' << result << " encdata auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_encdata, encdata); + if(b_debug) cerr << ' ' << result << " assign encdata authorization" << endl; + if(b_log) cerr << ' ' << result << " assign encdata authorization" << endl; + + +//BIND OPERATIONS + UINT32 enc_size; + BYTE* enc_blob; + + if(b_debug) cerr << "Bind Section" << endl; + if(b_log) clog << "Bind Section" << endl; + + result = Tspi_Data_Bind(encdata, bind, datablob.size, datablob.blob); + if(b_debug) cerr << ' ' << result << " BIND" << endl; + if(b_log) cerr << ' ' << result << " BIND" << endl; + return_code = result; + + if(result == 0) + { + result = Tspi_GetAttribData(encdata, TSS_TSPATTRIB_ENCDATA_BLOB, TSS_TSPATTRIB_ENCDATABLOB_BLOB, &enc_size, &enc_blob); + if(b_debug) cerr << ' ' << result << " get bound data blob" << endl; + if(b_log) cerr << ' ' << result << " get bound data blob" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < enc_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)enc_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, enc_blob); + } + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_bind); + result = Tspi_Context_CloseObject(context, bind); + result = Tspi_Context_CloseObject(context, policy_encdata); + result = Tspi_Context_CloseObject(context, encdata); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Unbind + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::unbind() +{ + if(b_help) + { + cout << "Unbind (" << i_mode << ") --- Decrypts data based on a binding key" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -blob (hex blob, data to decrypt)" << endl; + cout << " -blob_auth (hex blob, data blob authorization data)" << endl; + cout << " -key_auth (hex blob, binding key authorization data)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + cout << " OUTPUTS" << endl; + cout << " unbound data blob (hex blob, unencrypted data)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_blob; + string s_keyauth; + string s_encauth; + int i_keyindex = 0; + bool b_1024 = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-blob") == 0) + { + if(++i >= i_argc) return; + s_blob = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + + if(s_argv[i].compare("-blob_auth") == 0) + { + if(++i >= i_argc) return; + s_encauth = s_argv[i]; + i_success++; + } + } + if(i_success != 4) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob datablob(s_blob); + NIARL_Util_ByteBlob bindauth(s_keyauth); + NIARL_Util_ByteBlob encauth(s_encauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_bind = TSS_UUID_USK2; + uuid_bind.rgbNode[5] = (BYTE)i_keyindex; + uuid_bind.rgbNode[0] = 0x05; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//BIND OPERATIONS (SET) + TSS_HKEY bind; + TSS_HPOLICY policy_bind; + UINT32 init_flags; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "Bind Key Section" << endl; + if(b_log) clog << "Bind Key Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &bind); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_bind, &bind); + if(b_debug) cerr << ' ' << result << " load by UUID" << endl; + if(b_log) cerr << ' ' << result << " load by UUID" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_bind); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_bind, TSS_SECRET_MODE_SHA1, bindauth.size, bindauth.blob); + if(b_debug) cerr << ' ' << result << " key auth" << endl; + if(b_log) cerr << ' ' << result << " key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_bind, bind); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(bind, srk); + if(b_debug) cerr << ' ' << result << " load key" << endl; + if(b_log) cerr << ' ' << result << " load key" << endl; + + +//ENCDATA SECTION + TSS_HENCDATA encdata; + TSS_HPOLICY policy_encdata; + + if(b_debug) cerr << "EncData Section" << endl; + if(b_log) clog << "EncData Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_ENCDATA, TSS_ENCDATA_BIND, &encdata); + if(b_debug) cerr << ' ' << result << " create encdata" << endl; + if(b_log) cerr << ' ' << result << " create encdata" << endl; + + result = Tspi_SetAttribData(encdata, TSS_TSPATTRIB_ENCDATA_BLOB, TSS_TSPATTRIB_ENCDATABLOB_BLOB, datablob.size, datablob.blob); + if(b_debug) cerr << ' ' << result << " load encrypted blob" << endl; + if(b_log) cerr << ' ' << result << " load encrypted blob" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_encdata); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_encdata, TSS_SECRET_MODE_SHA1, encauth.size, encauth.blob); + if(b_debug) cerr << ' ' << result << " encdata auth" << endl; + if(b_log) cerr << ' ' << result << " encdata auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_encdata, encdata); + if(b_debug) cerr << ' ' << result << " assign encdata authorization" << endl; + if(b_log) cerr << ' ' << result << " assign encdata authorization" << endl; + + +//UNBIND OPERATIONS + UINT32 enc_size; + BYTE* enc_blob; + + if(b_debug) cerr << "Unbind Section" << endl; + if(b_log) clog << "Unbind Section" << endl; + + result = Tspi_Data_Unbind(encdata, bind, &(datablob.size), &(datablob.blob)); + if(b_debug) cerr << ' ' << result << " UNBIND" << endl; + if(b_log) cerr << ' ' << result << " UNBIND" << endl; + return_code = result; + + if(result == 0) + { + result = Tspi_GetAttribData(encdata, TSS_TSPATTRIB_ENCDATA_BLOB, TSS_TSPATTRIB_ENCDATABLOB_BLOB, &enc_size, &enc_blob); + if(b_debug) cerr << ' ' << result << " get unbound data blob" << endl; + if(b_log) cerr << ' ' << result << " get unbound data blob" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < enc_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)enc_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, enc_blob); + } + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_bind); + result = Tspi_Context_CloseObject(context, bind); + result = Tspi_Context_CloseObject(context, policy_encdata); + result = Tspi_Context_CloseObject(context, encdata); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Seal Bind + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::seal_bind() +{ + if(b_help) + { + cout << "Seal Bind (" << i_mode << ") --- Encrypts data using a binding key and platform state" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -blob (hex blob, data to encrypt)" << endl; + cout << " -blob_auth (hex blob, data blob authorization data)" << endl; + cout << " -key_auth (hex blob, binding key authorization data)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " -mask (hex string, controls PCR index selection)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + cout << " OUTPUTS" << endl; + cout << " sealed bound data blob (hex blob, encrypted data)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_blob; + string s_keyauth; + string s_pcrs; + string s_encauth; + int i_keyindex = 0; + bool b_1024 = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-blob") == 0) + { + if(++i >= i_argc) return; + s_blob = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + + if(s_argv[i].compare("-mask") == 0) + { + if(++i >= i_argc) return; + s_pcrs = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-blob_auth") == 0) + { + if(++i >= i_argc) return; + s_encauth = s_argv[i]; + i_success++; + } + } + if(i_success != 5) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob datablob(s_blob); + NIARL_Util_ByteBlob bindauth(s_keyauth); + NIARL_Util_Mask pcrmask(s_pcrs); + NIARL_Util_ByteBlob encauth(s_encauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_bind = TSS_UUID_USK2; + uuid_bind.rgbNode[5] = (BYTE)i_keyindex; + uuid_bind.rgbNode[0] = 0x05; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//BIND OPERATIONS (SET) + TSS_HKEY bind; + TSS_HPOLICY policy_bind; + UINT32 init_flags; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "Bind Key Section" << endl; + if(b_log) clog << "Bind Key Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &bind); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_bind, &bind); + if(b_debug) cerr << ' ' << result << " load by UUID" << endl; + if(b_log) cerr << ' ' << result << " load by UUID" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_bind); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_bind, TSS_SECRET_MODE_SHA1, bindauth.size, bindauth.blob); + if(b_debug) cerr << ' ' << result << " key auth" << endl; + if(b_log) cerr << ' ' << result << " key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_bind, bind); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(bind, srk); + if(b_debug) cerr << ' ' << result << " load key" << endl; + if(b_log) cerr << ' ' << result << " load key" << endl; + + +//ENCDATA SECTION + TSS_HENCDATA encdata; + TSS_HPOLICY policy_encdata; + + if(b_debug) cerr << "EncData Section" << endl; + if(b_log) clog << "EncData Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_ENCDATA, TSS_ENCDATA_SEAL, &encdata); + if(b_debug) cerr << ' ' << result << " create encdata" << endl; + if(b_log) cerr << ' ' << result << " create encdata" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_encdata); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_encdata, TSS_SECRET_MODE_SHA1, encauth.size, encauth.blob); + if(b_debug) cerr << ' ' << result << " encdata auth" << endl; + if(b_log) cerr << ' ' << result << " encdata auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_encdata, encdata); + if(b_debug) cerr << ' ' << result << " assign encdata authorization" << endl; + if(b_log) cerr << ' ' << result << " assign encdata authorization" << endl; + + +//PCR OPERATIONS + TSS_HPCRS pcr; + UINT32 pcr_size; + BYTE* pcr_blob; + + if(b_debug) cerr << "PCR Section" << endl; + if(b_log) clog << "PCR Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_PCRS, 0, &pcr); + if(b_debug) cerr << ' ' << result << " create pcr object" << endl; + if(b_log) cerr << ' ' << result << " create pcr object" << endl; + + for(UINT32 i = 0; i < pcrmask.size; i++) + { + result = Tspi_TPM_PcrRead(tpm, pcrmask.index[i], &pcr_size, &pcr_blob); + if(b_debug) cerr << ' ' << result << " read pcr index " << pcrmask.index[i] << endl; + if(b_log) cerr << ' ' << result << " read pcr index " << pcrmask.index[i] << endl; + + result = Tspi_PcrComposite_SelectPcrIndex(pcr, pcrmask.index[i]); + if(b_debug) cerr << ' ' << result << " select composite index" << endl; + if(b_log) cerr << ' ' << result << " select composite index" << endl; + + result = Tspi_PcrComposite_SetPcrValue(pcr, pcrmask.index[i], pcr_size, pcr_blob); + if(b_debug) cerr << ' ' << result << " set pcr value" << endl; + if(b_log) cerr << ' ' << result << " set pcr value" << endl; + +// for(UINT32 j = 0; j < pcr_size; j++) +// cout << setw(2) << setfill('0') << setbase(16) << (int)pcr_blob[j]; +// if(!b_debug && !b_log) cout << ' '; +// if(b_debug) cerr << endl; +// if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, pcr_blob); + if(b_debug) cerr << ' ' << result << " clear dynamic array" << endl; + if(b_log) cerr << ' ' << result << " clear dynamic array" << endl; + } + + +//SEAL OPERATIONS + UINT32 enc_size; + BYTE* enc_blob; + + if(b_debug) cerr << "Seal Bind Section" << endl; + if(b_log) clog << "Seal Bind Section" << endl; + + result = Tspi_Data_Seal(encdata, bind, datablob.size, datablob.blob, pcr); + if(b_debug) cerr << ' ' << result << " SEAL BIND" << endl; + if(b_log) cerr << ' ' << result << " SEAL BIND" << endl; + return_code = result; + + if(result == 0) + { + result = Tspi_GetAttribData(encdata, TSS_TSPATTRIB_ENCDATA_BLOB, TSS_TSPATTRIB_ENCDATABLOB_BLOB, &enc_size, &enc_blob); + if(b_debug) cerr << ' ' << result << " get sealed bound blob" << endl; + if(b_log) cerr << ' ' << result << " get sealed bound blob" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < enc_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)enc_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, enc_blob); + } + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_bind); + result = Tspi_Context_CloseObject(context, bind); + result = Tspi_Context_CloseObject(context, policy_encdata); + result = Tspi_Context_CloseObject(context, encdata); + result = Tspi_Context_CloseObject(context, srk); + result = Tspi_Context_CloseObject(context, pcr); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Unseal Unbind + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::unseal_unbind() +{ + if(b_help) + { + cout << "Unseal Unbind (" << i_mode << ") --- Dencrypts data using a binding key and platform state" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -blob (hex blob, data to decrypt)" << endl; + cout << " -blob_auth (hex blob, data blob authorization data)" << endl; + cout << " -key_auth (hex blob, binding key authorization data)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + cout << " OUTPUTS" << endl; + cout << " unsealed unbound data blob (hex blob, unencrypted data)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_blob; + string s_keyauth; + string s_encauth; + int i_keyindex = 0; + bool b_1024 = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-blob") == 0) + { + if(++i >= i_argc) return; + s_blob = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + + if(s_argv[i].compare("-blob_auth") == 0) + { + if(++i >= i_argc) return; + s_encauth = s_argv[i]; + i_success++; + } + } + if(i_success != 4) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob datablob(s_blob); + NIARL_Util_ByteBlob bindauth(s_keyauth); + NIARL_Util_ByteBlob encauth(s_encauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_bind = TSS_UUID_USK2; + uuid_bind.rgbNode[5] = (BYTE)i_keyindex; + uuid_bind.rgbNode[0] = 0x05; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//BIND OPERATIONS (SET) + TSS_HKEY bind; + TSS_HPOLICY policy_bind; + UINT32 init_flags; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_BIND | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "Bind Key Section" << endl; + if(b_log) clog << "Bind Key Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &bind); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_bind, &bind); + if(b_debug) cerr << ' ' << result << " load by UUID" << endl; + if(b_log) cerr << ' ' << result << " load by UUID" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_bind); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_bind, TSS_SECRET_MODE_SHA1, bindauth.size, bindauth.blob); + if(b_debug) cerr << ' ' << result << " key auth" << endl; + if(b_log) cerr << ' ' << result << " key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_bind, bind); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(bind, srk); + if(b_debug) cerr << ' ' << result << " load key" << endl; + if(b_log) cerr << ' ' << result << " load key" << endl; + + +//ENCDATA SECTION + TSS_HENCDATA encdata; + TSS_HPOLICY policy_encdata; + + if(b_debug) cerr << "EncData Section" << endl; + if(b_log) clog << "EncData Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_ENCDATA, TSS_ENCDATA_BIND, &encdata); + if(b_debug) cerr << ' ' << result << " create encdata" << endl; + if(b_log) cerr << ' ' << result << " create encdata" << endl; + + result = Tspi_SetAttribData(encdata, TSS_TSPATTRIB_ENCDATA_BLOB, TSS_TSPATTRIB_ENCDATABLOB_BLOB, datablob.size, datablob.blob); + if(b_debug) cerr << ' ' << result << " load encrypted blob" << endl; + if(b_log) cerr << ' ' << result << " load encrypted blob" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_encdata); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_encdata, TSS_SECRET_MODE_SHA1, encauth.size, encauth.blob); + if(b_debug) cerr << ' ' << result << " encdata auth" << endl; + if(b_log) cerr << ' ' << result << " encdata auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_encdata, encdata); + if(b_debug) cerr << ' ' << result << " assign encdata authorization" << endl; + if(b_log) cerr << ' ' << result << " assign encdata authorization" << endl; + + +//UNSEAL OPERATIONS + UINT32 enc_size; + BYTE* enc_blob; + + if(b_debug) cerr << "Unseal Unbind Section" << endl; + if(b_log) clog << "Unseal Unbind Section" << endl; + + result = Tspi_SetAttribData(encdata, TSS_TSPATTRIB_ENCDATA_BLOB, TSS_TSPATTRIB_ENCDATABLOB_BLOB, datablob.size, datablob.blob); + if(b_debug) cerr << ' ' << result << " UNSEAL UNBIND" << endl; + if(b_log) cerr << ' ' << result << " UNSEAL UNBIND" << endl; + + result = Tspi_Data_Unseal(encdata, bind, &enc_size, &enc_blob); + if(b_debug) cerr << ' ' << result << " get unsealed unbound data blob" << endl; + if(b_log) cerr << ' ' << result << " get unsealed unbound data blob" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < enc_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)enc_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, enc_blob); + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_bind); + result = Tspi_Context_CloseObject(context, bind); + result = Tspi_Context_CloseObject(context, policy_encdata); + result = Tspi_Context_CloseObject(context, encdata); + result = Tspi_Context_CloseObject(context, srk); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Get Random Integer + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::get_rand_int() +{ + if(b_help) + { + cout << "Get Random Integer (" << i_mode << ") --- Generates a random positive number" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -bytes (positive integer, max random number size in bytes)" << endl; + cout << " OUTPUTS" << endl; + cout << " integer (integer, random number)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + UINT32 numbytes = 0; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-bytes") == 0) + { + if(++i >= i_argc) return; + numbytes = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success != 1) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//GET RANDOM NUMBER + BYTE* randbytes; + + if(b_debug) cerr << "Get Random Section" << endl; + if(b_log) clog << "Get Random Section" << endl; + + result = Tspi_TPM_GetRandom(tpm, numbytes, &randbytes); + if(b_debug) cerr << ' ' << result << " GET RANDOM" << endl; + if(b_log) cerr << ' ' << result << " GET RANDOM" << endl; + return_code = result; + + for(UINT32 i = 0; i < numbytes; i++) + { + cout << setbase(16) << setw(2) << setfill('0') << (int)randbytes[i]; + } + +//CLEANUP SECTION + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Sign + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::sign() +{ + if(b_help) + { + cout << "Sign (" << i_mode << ") --- Signs a data blob" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -blob (hex blob, data to sign)" << endl; + cout << " -key_auth (hex blob, key authorization data)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OPTIONAL PARAMETERS" << endl; + cout << " -1024 (flag, uses 1024 keys instead of 2048)" << endl; + cout << " OUTPUTS" << endl; + cout << " signature (hex blob, signature)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_blob; + string s_keyauth; + int i_keyindex = 0; + bool b_1024 = false; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-1024") == 0) + { + b_1024 = true; + } + + if(s_argv[i].compare("-blob") == 0) + { + if(++i >= i_argc) return; + s_blob = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_keyauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success != 3) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob datablob(s_blob); + NIARL_Util_ByteBlob signauth(s_keyauth); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_sign = TSS_UUID_USK2; + uuid_sign.rgbNode[5] = (BYTE)i_keyindex; + uuid_sign.rgbNode[0] = 0x06; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//SIGNING OPERATIONS (SET) + TSS_HKEY sign; + TSS_HPOLICY policy_sign; + UINT32 init_flags; + + if(!b_1024) + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + else + init_flags = TSS_KEY_TYPE_SIGNING | TSS_KEY_SIZE_1024 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + + if(b_debug) cerr << "Signing Key Section" << endl; + if(b_log) clog << "Signing Key Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &sign); + if(b_debug) cerr << ' ' << result << " create key object" << endl; + if(b_log) cerr << ' ' << result << " create key object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_sign, &sign); + if(b_debug) cerr << ' ' << result << " load by UUID" << endl; + if(b_log) cerr << ' ' << result << " load by UUID" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_sign); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Policy_SetSecret(policy_sign, TSS_SECRET_MODE_SHA1, signauth.size, signauth.blob); + if(b_debug) cerr << ' ' << result << " key auth" << endl; + if(b_log) cerr << ' ' << result << " key auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_sign, sign); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(sign, srk); + if(b_debug) cerr << ' ' << result << " load key" << endl; + if(b_log) cerr << ' ' << result << " load key" << endl; + + +//HASH SECTION + TSS_HHASH hash; + + if(b_debug) cerr << "Hash Section" << endl; + if(b_log) clog << "Hash Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_HASH, TSS_HASH_SHA1, &hash); + if(b_debug) cerr << ' ' << result << " create hash object" << endl; + if(b_log) cerr << ' ' << result << " create hash object" << endl; + + result = Tspi_Hash_UpdateHashValue(hash, datablob.size, datablob.blob); + if(b_debug) cerr << ' ' << result << " update hash value" << endl; + if(b_log) cerr << ' ' << result << " update hash value" << endl; + + +//SIGNING OPERATIONS + UINT32 sig_size; + BYTE* sig_blob; + + if(b_debug) cerr << "Sign Section" << endl; + if(b_log) clog << "Sign Section" << endl; + + result = Tspi_Hash_Sign(hash, sign, &sig_size, &sig_blob); + if(b_debug) cerr << ' ' << result << " SIGN" << endl; + if(b_log) cerr << ' ' << result << " SIGN" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < sig_size; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)sig_blob[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, sig_blob); + } + + +//CLEANUP SECTION + result = Tspi_Context_CloseObject(context, policy_sign); + result = Tspi_Context_CloseObject(context, sign); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Create EK + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::create_ek() +{ + if(b_help) + { + cout << "Create Endorsement Key (" << i_mode << ") --- Creates a default endorsement key in the absence of a manufacturer endorsement key" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -nonce (hex blob, anti-replay nonce)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_nonce; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-nonce") == 0) + { + if(++i >= i_argc) return; + s_nonce = s_argv[i]; + i_success++; + } + } + if(i_success != 1) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob nonce(s_nonce); + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//EK SECTION + TSS_HKEY ek; + TSS_VALIDATION validation; + + if(b_debug) cerr << "EK Section" << endl; + if(b_log) clog << "EK Section" << endl; + + memset(&validation, 0, sizeof(TSS_VALIDATION)); + validation.versionInfo.bMajor = 0x01; + validation.versionInfo.bMinor = 0x02; + validation.versionInfo.bRevMajor = 0x01; + validation.versionInfo.bRevMinor = 0x25; + validation.ulExternalDataLength = sizeof(TSS_NONCE); + validation.rgbExternalData = nonce.blob; + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_SIZE_DEFAULT, &ek); + if(b_debug) cerr << ' ' << result << " create ek object" << endl; + if(b_log) cerr << ' ' << result << " create ek object" << endl; + + +//TAKE OWNERSHIP + if(b_debug) cerr << "Create EK Section" << endl; + if(b_log) clog << "Create EK Section" << endl; + + result = Tspi_TPM_CreateEndorsementKey(tpm, ek, &validation); + if(b_debug) cerr << ' ' << result << " CREATE EK" << endl; + if(b_log) cerr << ' ' << result << " CREATE EK" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < validation.ulExternalDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbExternalData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < validation.ulDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < validation.ulValidationDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbValidationData[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + } + + +//CLEANUP + result = Tspi_Context_FreeMemory(context, validation.rgbData); + result = Tspi_Context_FreeMemory(context, validation.rgbValidationData); + result = Tspi_Context_FreeMemory(context, validation.rgbExternalData); + + result = Tspi_Context_CloseObject(context, ek); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} + +/********************************************************************************************** + Quote2 + **********************************************************************************************/ + +void NIARL_TPM_ModuleV2::quote2() +{ + if(b_help) + { + cout << "Quote2 (" << i_mode << ") --- Provides a system integrity quote with signature" << endl; + cout << " REQUIRED PARAMETERS" << endl; + cout << " -key_auth (hex blob, identity key authorization data)" << endl; + cout << " -nonce (hex blob, anti-replay nonce)" << endl; + cout << " -mask (hex string, controls PCR index selection)" << endl; + cout << " -key_index (integer, index number for key)" << endl; + cout << " OUTPUTS" << endl; + cout << " quote (hex blob, quote digest)" << endl; + cout << " signature (hex blob, quote signature)" << endl; + cout << " version_info (hex blob, TCPA_VERSION_INFO)" << endl; + return_code = -1 * ERROR_ARG_HELP; + return; + } + + +//DYNAMIC CONTENT + short i_success = 0; + string s_pcrs; + string s_aikauth; + string s_nonce; + int i_keyindex = 0; + + for(short i = 0; i < i_argc; i++) + { + if(s_argv[i].compare("-nonce") == 0) + { + if(++i >= i_argc) return; + s_nonce = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_auth") == 0) + { + if(++i >= i_argc) return; + s_aikauth = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-mask") == 0) + { + if(++i >= i_argc) return; + s_pcrs = s_argv[i]; + i_success++; + } + + if(s_argv[i].compare("-key_index") == 0) + { + if(++i >= i_argc) return; + i_keyindex = atoi(s_argv[i].c_str()); + i_success++; + } + } + if(i_success != 4) + { + return_code = -1 * ERROR_ARG_MISSING; + return; + } + + NIARL_Util_ByteBlob aikauth(s_aikauth); + NIARL_Util_ByteBlob nonce(s_nonce); + NIARL_Util_Mask pcrmask(s_pcrs); + BYTE wks_blob[] = TSS_WELL_KNOWN_SECRET; + UINT32 wks_size = sizeof(wks_blob); + + TSS_UUID uuid_aik = TSS_UUID_USK2; + uuid_aik.rgbNode[5] = (BYTE)i_keyindex; + uuid_aik.rgbNode[0] = 0x04; + + +//CONTEXT SECTION + TSS_RESULT result; + TSS_HCONTEXT context; + TSS_HPOLICY policy_default; + + if(b_debug) cerr << "Context Section" << endl; + if(b_log) clog << "Context Section" << endl; + + result = Tspi_Context_Create(&context); + if(b_debug) cerr << ' ' << result << " create context" << endl; + if(b_log) cerr << ' ' << result << " create context" << endl; + + result = Tspi_Context_Connect(context, NULL); + if(b_debug) cerr << ' ' << result << " create policy" << endl; + if(b_log) cerr << ' ' << result << " create policy" << endl; + + result = Tspi_Context_GetDefaultPolicy(context, &policy_default); + if(b_debug) cerr << ' ' << result << " default policy" << endl; + if(b_log) cerr << ' ' << result << " default policy" << endl; + + +//TPM SECTION + TSS_HTPM tpm; + + if(b_debug) cerr << "TPM Section" << endl; + if(b_log) clog << "TPM Section" << endl; + + result = Tspi_Context_GetTpmObject(context, &tpm); + if(b_debug) cerr << ' ' << result << " tpm context" << endl; + if(b_log) cerr << ' ' << result << " tpm context" << endl; + + +//SRK OPERATIONS (SET) + TSS_HKEY srk; + TSS_HPOLICY policy_srk; + TSS_UUID uuid_srk = TSS_UUID_SRK; + + if(b_debug) cerr << "SRK Section" << endl; + if(b_log) clog << "SRK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, TSS_KEY_TSP_SRK, &srk); + if(b_debug) cerr << ' ' << result << " create srk object" << endl; + if(b_log) cerr << ' ' << result << " create srk object" << endl; + + result = Tspi_Context_LoadKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_srk, &srk); + if(b_debug) cerr << ' ' << result << " load srk by uuid" << endl; + if(b_log) cerr << ' ' << result << " load srk by uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_srk); + if(b_debug) cerr << ' ' << result << " create srk policy" << endl; + if(b_log) cerr << ' ' << result << " create srk policy" << endl; + + result = Tspi_Policy_SetSecret(policy_srk, TSS_SECRET_MODE_SHA1, wks_size, wks_blob); + if(b_debug) cerr << ' ' << result << " set srk auth" << endl; + if(b_log) cerr << ' ' << result << " set srk auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_srk, srk); + if(b_debug) cerr << ' ' << result << " assign srk policy" << endl; + if(b_log) cerr << ' ' << result << " assign srk policy" << endl; + + +//AIK OPERATIONS (SET) + TSS_HKEY aik; + TSS_HPOLICY policy_aik; + UINT32 init_flags = TSS_KEY_TYPE_IDENTITY | TSS_KEY_SIZE_2048 | TSS_KEY_VOLATILE | TSS_KEY_AUTHORIZATION | TSS_KEY_NOT_MIGRATABLE; + + if(b_debug) cerr << "AIK Section" << endl; + if(b_log) clog << "AIK Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_RSAKEY, init_flags, &aik); + if(b_debug) cerr << ' ' << result << " create aik object" << endl; + if(b_log) cerr << ' ' << result << " create aik object" << endl; + + result = Tspi_Context_GetKeyByUUID(context, TSS_PS_TYPE_SYSTEM, uuid_aik, &aik); + if(b_debug) cerr << ' ' << result << " get uuid" << endl; + if(b_log) cerr << ' ' << result << " get uuid" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_POLICY, TSS_POLICY_USAGE, &policy_aik); + if(b_debug) cerr << ' ' << result << " create aik policy" << endl; + if(b_log) cerr << ' ' << result << " create aik policy" << endl; + + result = Tspi_Policy_SetSecret(policy_aik, TSS_SECRET_MODE_SHA1, aikauth.size, aikauth.blob); + if(b_debug) cerr << ' ' << result << " set aik auth" << endl; + if(b_log) cerr << ' ' << result << " set aik auth" << endl; + + result = Tspi_Policy_AssignToObject(policy_aik, aik); + if(b_debug) cerr << ' ' << result << " assign" << endl; + if(b_log) cerr << ' ' << result << " assign" << endl; + + result = Tspi_Key_LoadKey(aik, srk); + if(b_debug) cerr << ' ' << result << " load aik" << endl; + if(b_log) cerr << ' ' << result << " load aik" << endl; + + +//PCR OPERATIONS + TSS_HPCRS pcr; + UINT32 pcr_size; + BYTE* pcr_blob; + + if(b_debug) cerr << "PCR Section" << endl; + if(b_log) clog << "PCR Section" << endl; + + result = Tspi_Context_CreateObject(context, TSS_OBJECT_TYPE_PCRS, TSS_PCRS_STRUCT_INFO_SHORT, &pcr); + if(b_debug) cerr << ' ' << result << " create pcr object" << endl; + if(b_log) cerr << ' ' << result << " create pcr object" << endl; + + for(UINT32 i = 0; i < pcrmask.size; i++) + { + result = Tspi_PcrComposite_SelectPcrIndexEx(pcr, pcrmask.index[i], TSS_PCRS_DIRECTION_RELEASE); + if(b_debug) cerr << ' ' << result << " select composite index" << endl; + if(b_log) cerr << ' ' << result << " select composite index" << endl; + } + + +//QUOTE OPERATIONS + TSS_VALIDATION validation; + + if(b_debug) cerr << "Quote Section" << endl; + if(b_log) clog << "Quote Section" << endl; + + memset(&validation, 0, sizeof(TSS_VALIDATION)); + validation.versionInfo.bMajor = 0x01; + validation.versionInfo.bMinor = 0x02; + validation.versionInfo.bRevMajor = 0x01; + validation.versionInfo.bRevMinor = 0x25; + validation.ulExternalDataLength = sizeof(TSS_NONCE); + validation.rgbExternalData = nonce.blob; + + BYTE* versionvalue; + UINT32 versionsize; + + result = Tspi_TPM_Quote2(tpm, aik, FALSE, pcr, &validation, &versionsize, &versionvalue); + if(b_debug) cerr << ' ' << result << " QUOTE" << endl; + if(b_log) cerr << ' ' << result << " QUOTE" << endl; + return_code = result; + + if(result == 0) + { + for(UINT32 i = 0; i < pcrmask.size; i++) + { + result = Tspi_PcrComposite_GetPcrValue(pcr, pcrmask.index[i], &pcr_size, &pcr_blob); + if(b_debug) cerr << ' ' << result << " set pcr value" << endl; + if(b_log) cerr << ' ' << result << " set pcr value" << endl; + + for(UINT32 j = 0; j < pcr_size; j++) + cout << setw(2) << setfill('0') << setbase(16) << (int)pcr_blob[j]; + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + result = Tspi_Context_FreeMemory(context, pcr_blob); + if(b_debug) cerr << ' ' << result << " clear dynamic array" << endl; + if(b_log) cerr << ' ' << result << " clear dynamic array" << endl; + } + + for(UINT32 i = 0; i < validation.ulExternalDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbExternalData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < validation.ulDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < validation.ulValidationDataLength; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)validation.rgbValidationData[i]; + + if(!b_debug && !b_log) cout << ' '; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + for(UINT32 i = 0; i < versionsize; i++) + cout << setw(2) << setfill('0') << setbase(16) << (int)versionvalue[i]; + if(b_debug) cerr << endl; + if(b_log) clog << endl; + + delete [] versionvalue; + } + + +//CLEANUP SECTION + result = Tspi_Context_FreeMemory(context, validation.rgbData); + result = Tspi_Context_FreeMemory(context, validation.rgbValidationData); + result = Tspi_Context_FreeMemory(context, validation.rgbExternalData); + + result = Tspi_Context_CloseObject(context, policy_aik); + result = Tspi_Context_CloseObject(context, aik); + result = Tspi_Context_CloseObject(context, srk); + result = Tspi_Context_CloseObject(context, pcr); + + //result = Tspi_Context_FreeMemory(context, NULL); + result = Tspi_Context_Close(context); + + return; +} diff --git a/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_TPM_ModuleV2.h b/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_TPM_ModuleV2.h new file mode 100644 index 0000000..751b3b4 --- /dev/null +++ b/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_TPM_ModuleV2.h @@ -0,0 +1,130 @@ +/** + * Copyright (C) 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * 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) Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. + */ + +#ifndef NIARL_TPM_ModuleV2_H +#define NIARL_TPM_ModuleV2_H + +// ************ MODULE HEADERS ************ // +#include "NIARL_Util_ByteBlob.h" +#include "NIARL_Util_Mask.h" + +// ************ TSS HEADERS ************ // +#include +#include +#include +//#include "tspi.h" +//#include "tss_error.h" +//#include "tss_defines.h" + +// ************ STANDARD HEADERS ************ // +#include +#include +#include +#include +#include +#include +using namespace std; + +class NIARL_TPM_ModuleV2 +{ +public: + enum MODULE_ERROR { + ERROR_ZEROFILL, + ERROR_UNKNOWN, + ERROR_ARG_MISSING, + ERROR_ARG_INFILE, + ERROR_ARG_OUTFILE, + ERROR_ARG_MODE, + ERROR_ARG_VALIDATION, + ERROR_ARG_HELP, + ERROR_MODE_DISABLED}; + + enum MODULE_MODE { + MODE_ZEROFILL, + MODE_TAKE_OWNERSHIP, + MODE_CLEAR_OWNERSHIP, + MODE_COLLATE_IDENTITY, + MODE_ACTIVATE_IDENTITY, + MODE_QUOTE, + MODE_CREATE_REK, + MODE_REVOKE_REK, + MODE_CREATE_KEY, + MODE_SET_KEY, + MODE_GET_KEY, + MODE_CLEAR_KEY, + MODE_SET_CREDENTIAL, + MODE_GET_CREDENTIAL, + MODE_CLEAR_CREDENTIAL, + MODE_SEAL, + MODE_UNSEAL, + MODE_BIND, + MODE_UNBIND, + MODE_SEAL_BIND, + MODE_UNSEAL_UNBIND, + MODE_GET_RAND, + MODE_SIGN, + MODE_CREATE_EK, + MODE_QUOTE2}; + + bool b_debug, + b_log, + b_help, + b_infile, + b_outfile; + + int i_mode, + i_argc, + i_return; + + string* s_argv; + + ofstream logfile, + outfile; + + ifstream infile; + + TSS_RESULT return_code; + + NIARL_TPM_ModuleV2(int argc, char* argv[]); + ~NIARL_TPM_ModuleV2(); + + void run_mode(); + + void take_ownership(); + void clear_ownership(); + void collate_identity(); + void activate_identity(); + void quote(); + void create_revokable_ek(); + void revoke_ek(); + void create_key(); + void set_key(); + void get_key(); + void clear_key(); + void set_credential(); + void get_credential(); + void clear_credential(); + void seal(); + void unseal(); + void bind(); + void unbind(); + void seal_bind(); + void unseal_unbind(); + void get_rand_int(); + void sign(); + void encrypt(); + void decrypt(); + void create_ek(); + void quote2(); +}; + +#endif diff --git a/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_Util_ByteBlob.cpp b/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_Util_ByteBlob.cpp new file mode 100644 index 0000000..de6e83d --- /dev/null +++ b/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_Util_ByteBlob.cpp @@ -0,0 +1,109 @@ +/** + * Copyright (C) 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * 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) Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. + */ + +#include "NIARL_Util_ByteBlob.h" + +NIARL_Util_ByteBlob::NIARL_Util_ByteBlob(string in_var) +{ + short temp_size = in_var.size(); //get the full string length + if(temp_size % 2 == 1) + throw NIARL_TPM_ModuleV2::ERROR_ARG_VALIDATION; + + size = temp_size / 2; //base 16 takes 2 digits so reduce length to show real size + blob = new BYTE[size]; //create the byte array + + UINT32 hex_value = 0; //accumulates 2 hex characters to load into blob + short index; //index that points at correct byte blob index (truncation intentional) + + for(short i = 0; i < temp_size; i++) + { + switch(in_var[i]) + { + case 'F': + case 'f': + hex_value += 15; + break; + case 'E': + case 'e': + hex_value += 14; + break; + case 'D': + case 'd': + hex_value += 13; + break; + case 'C': + case 'c': + hex_value += 12; + break; + case 'B': + case 'b': + hex_value += 11; + break; + case 'A': + case 'a': + hex_value += 10; + break; + case '9': + hex_value += 9; + break; + case '8': + hex_value += 8; + break; + case '7': + hex_value += 7; + break; + case '6': + hex_value += 6; + break; + case '5': + hex_value += 5; + break; + case '4': + hex_value += 4; + break; + case '3': + hex_value += 3; + break; + case '2': + hex_value += 2; + break; + case '1': + hex_value += 1; + break; + case '0': + hex_value += 0; + break; + default: + throw NIARL_TPM_ModuleV2::ERROR_ARG_VALIDATION; + } + + index = i / 2; //allow truncation so we get the right spot in the byte array + if(i % 2 == 0) //even characters are the first of two hex characters + hex_value *= 16; + else + { + blob[index] = hex_value; //we now have 2 hex characters so load them into the byte array + hex_value = 0; //reset the accumulator + } + } +} + +NIARL_Util_ByteBlob::~NIARL_Util_ByteBlob() +{ + delete [] blob; +} + +void NIARL_Util_ByteBlob::Print() +{ + for(UINT32 i = 0; i < size; i++) + cout << setbase(16) << setw(2) << setfill('0') << (int)blob[i]; +} diff --git a/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_Util_ByteBlob.h b/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_Util_ByteBlob.h new file mode 100644 index 0000000..990e03f --- /dev/null +++ b/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_Util_ByteBlob.h @@ -0,0 +1,46 @@ +/** + * Copyright (C) 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * 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) Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. + */ + +#ifndef NIARL_UTIL_BYTEBLOB_H +#define NIARL_UTIL_BYTEBLOB_H + +// ************ MODULE HEADERS ************ // +#include "NIARL_TPM_ModuleV2.h" + +// ************ TSS HEADERS ************ // +#include +#include +#include +//#include "tspi.h" +//#include "tss_error.h" +//#include "tss_defines.h" + +// ************ STANDARD HEADERS ************ // +#include +#include +#include +#include +using namespace std; + +class NIARL_Util_ByteBlob +{ +public: + UINT32 size; + BYTE* blob; + + NIARL_Util_ByteBlob(string in_var); + ~NIARL_Util_ByteBlob(); + + void Print(); +}; + +#endif diff --git a/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_Util_Mask.cpp b/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_Util_Mask.cpp new file mode 100644 index 0000000..85790d9 --- /dev/null +++ b/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_Util_Mask.cpp @@ -0,0 +1,158 @@ +/** + * Copyright (C) 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * 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) Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. + */ + +#include "NIARL_Util_Mask.h" + +NIARL_Util_Mask::NIARL_Util_Mask(string in_var) +{ + short temp_size = in_var.size(); + vector temp_array; + + int bumper = 0; + + for(short i = 0; i < temp_size; i++) + { + switch(in_var[i]) + { + case 'F': + case 'f': + temp_array.push_back(bumper + 0); + temp_array.push_back(bumper + 1); + temp_array.push_back(bumper + 2); + temp_array.push_back(bumper + 3); + //Bitmask 1111 + break; + case 'E': + case 'e': + temp_array.push_back(bumper + 0); + temp_array.push_back(bumper + 1); + temp_array.push_back(bumper + 2); + //temp_array.push_back(bumper + 3); + //Bitmask 1110 + break; + case 'D': + case 'd': + temp_array.push_back(bumper + 0); + temp_array.push_back(bumper + 1); + //temp_array.push_back(bumper + 2); + temp_array.push_back(bumper + 3); + //Bitmask 1101 + break; + case 'C': + case 'c': + temp_array.push_back(bumper + 0); + temp_array.push_back(bumper + 1); + //temp_array.push_back(bumper + 2); + //temp_array.push_back(bumper + 3); + //Bitmask 1100 + break; + case 'B': + case 'b': + temp_array.push_back(bumper + 0); + //temp_array.push_back(bumper + 1); + temp_array.push_back(bumper + 2); + temp_array.push_back(bumper + 3); + //Bitmask 1011 + break; + case 'A': + case 'a': + temp_array.push_back(bumper + 0); + //temp_array.push_back(bumper + 1); + temp_array.push_back(bumper + 2); + //temp_array.push_back(bumper + 3); + //Bitmask 1010 + break; + case '9': + temp_array.push_back(bumper + 0); + //temp_array.push_back(bumper + 1); + //temp_array.push_back(bumper + 2); + temp_array.push_back(bumper + 3); + //Bitmask 1001 + break; + case '8': + temp_array.push_back(bumper + 0); + //temp_array.push_back(bumper + 1); + //temp_array.push_back(bumper + 2); + //temp_array.push_back(bumper + 3); + //Bitmask 1000 + break; + case '7': + //temp_array.push_back(bumper + 0); + temp_array.push_back(bumper + 1); + temp_array.push_back(bumper + 2); + temp_array.push_back(bumper + 3); + //Bitmask 0111 + break; + case '6': + //temp_array.push_back(bumper + 0); + temp_array.push_back(bumper + 1); + temp_array.push_back(bumper + 2); + //temp_array.push_back(bumper + 3); + //Bitmask 0110 + break; + case '5': + //temp_array.push_back(bumper + 0); + temp_array.push_back(bumper + 1); + //temp_array.push_back(bumper + 2); + temp_array.push_back(bumper + 3); + //Bitmask 0101 + break; + case '4': + //temp_array.push_back(bumper + 0); + temp_array.push_back(bumper + 1); + //temp_array.push_back(bumper + 2); + //temp_array.push_back(bumper + 3); + //Bitmask 0100 + break; + case '3': + //temp_array.push_back(bumper + 0); + //temp_array.push_back(bumper + 1); + temp_array.push_back(bumper + 2); + temp_array.push_back(bumper + 3); + //Bitmask 0011 + break; + case '2': + //temp_array.push_back(bumper + 0); + //temp_array.push_back(bumper + 1); + temp_array.push_back(bumper + 2); + //temp_array.push_back(bumper + 3); + //Bitmask 0010 + break; + case '1': + //temp_array.push_back(bumper + 0); + //temp_array.push_back(bumper + 1); + //temp_array.push_back(bumper + 2); + temp_array.push_back(bumper + 3); + //Bitmask 0001 + break; + case '0': + break; + default: + throw NIARL_TPM_ModuleV2::ERROR_ARG_VALIDATION; + } + bumper += 4; + } + + size = temp_array.size(); + index = new int[size]; + + for(int i = (size - 1); i > -1; i--) + { + index[i] = temp_array.back(); + temp_array.pop_back(); + } +} + +NIARL_Util_Mask::~NIARL_Util_Mask() +{ + delete [] index; +} diff --git a/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_Util_Mask.h b/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_Util_Mask.h new file mode 100644 index 0000000..658991b --- /dev/null +++ b/OpenAttestation/Source/TPMModule/sha1/linux/NIARL_Util_Mask.h @@ -0,0 +1,43 @@ +/** + * Copyright (C) 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * 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) Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. + */ + +#ifndef NIARL_UTIL_MASK_H +#define NIARL_UTIL_MASK_H + +// ************ MODULE HEADERS ************ // +#include "NIARL_TPM_ModuleV2.h" + +// ************ TSS HEADERS ************ // +#include +#include +#include +//#include "tspi.h" +//#include "tss_error.h" +//#include "tss_defines.h" + +// ************ STANDARD HEADERS ************ // +#include +#include +#include +using namespace std; + +class NIARL_Util_Mask +{ +public: + UINT32 size; + int* index; + + NIARL_Util_Mask(string in_var); + ~NIARL_Util_Mask(); +}; + +#endif diff --git a/OpenAttestation/Source/TPMModule/sha1/linux/main.cpp b/OpenAttestation/Source/TPMModule/sha1/linux/main.cpp new file mode 100644 index 0000000..b64415d --- /dev/null +++ b/OpenAttestation/Source/TPMModule/sha1/linux/main.cpp @@ -0,0 +1,43 @@ +/** + * Copyright (C) 2012, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + * This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + * 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) Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. + */ + +// ************ TSS HEADERS ************ // +#include +#include +#include +//#include "tspi.h" +//#include "tss_error.h" +//#include "tss_defines.h" + +// ************ MODULE HEADERS ************ // +#include "NIARL_TPM_ModuleV2.h" + +// ************ STANDARD HEADERS ************ // +using namespace std; + +int main(int argc, char* argv[]) +{ + UINT32 rcode = 0; + + try + { + NIARL_TPM_ModuleV2 test(argc, argv); + test.run_mode(); + rcode = test.return_code; + } + catch(...) + { + return (-1); + } + + return rcode; +} diff --git a/OpenAttestation/Source/TPMModule/sha1/linux/makefile b/OpenAttestation/Source/TPMModule/sha1/linux/makefile new file mode 100644 index 0000000..554ed30 --- /dev/null +++ b/OpenAttestation/Source/TPMModule/sha1/linux/makefile @@ -0,0 +1,58 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +-include ../makefile.init + +RM := rm -rf + +# All of the sources participating in the build are defined here +-include sources.mk +-include subdir.mk +-include objects.mk + +ifneq ($(MAKECMDGOALS),clean) +ifneq ($(strip $(C++_DEPS)),) +-include $(C++_DEPS) +endif +ifneq ($(strip $(C_DEPS)),) +-include $(C_DEPS) +endif +ifneq ($(strip $(CC_DEPS)),) +-include $(CC_DEPS) +endif +ifneq ($(strip $(CPP_DEPS)),) +-include $(CPP_DEPS) +endif +ifneq ($(strip $(CXX_DEPS)),) +-include $(CXX_DEPS) +endif +ifneq ($(strip $(C_UPPER_DEPS)),) +-include $(C_UPPER_DEPS) +endif +endif + +-include ../makefile.defs + +# Add inputs and outputs from these tool invocations to the build variables + +# All Target +all: NIARL_TPM_Module + +# Tool invocations +NIARL_TPM_Module: $(OBJS) $(USER_OBJS) + @echo 'Building target: $@' + @echo 'Invoking: GCC C++ Linker' + g++ -o"NIARL_TPM_Module" $(OBJS) $(USER_OBJS) $(LIBS) + @echo 'Finished building target: $@' + @echo ' ' + +# Other Targets +clean: + -$(RM) $(OBJS)$(C++_DEPS)$(C_DEPS)$(CC_DEPS)$(CPP_DEPS)$(EXECUTABLES)$(CXX_DEPS)$(C_UPPER_DEPS) NIARL_TPM_Module + -@echo ' ' + +.PHONY: all clean dependents +.SECONDARY: + +-include ../makefile.targets diff --git a/OpenAttestation/Source/TPMModule/sha1/linux/objects.mk b/OpenAttestation/Source/TPMModule/sha1/linux/objects.mk new file mode 100644 index 0000000..d05063c --- /dev/null +++ b/OpenAttestation/Source/TPMModule/sha1/linux/objects.mk @@ -0,0 +1,7 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +USER_OBJS := + +LIBS := -ltspi diff --git a/OpenAttestation/Source/TPMModule/sha1/linux/subdir.mk b/OpenAttestation/Source/TPMModule/sha1/linux/subdir.mk new file mode 100644 index 0000000..1fbfb99 --- /dev/null +++ b/OpenAttestation/Source/TPMModule/sha1/linux/subdir.mk @@ -0,0 +1,33 @@ +################################################################################ +# Automatically-generated file. Do not edit! +################################################################################ + +# Add inputs and outputs from these tool invocations to the build variables +CPP_SRCS += \ +../NIARL_TPM_ModuleV2.cpp \ +../NIARL_Util_ByteBlob.cpp \ +../NIARL_Util_Mask.cpp \ +../main.cpp + +OBJS += \ +./NIARL_TPM_ModuleV2.o \ +./NIARL_Util_ByteBlob.o \ +./NIARL_Util_Mask.o \ +./main.o + +CPP_DEPS += \ +./NIARL_TPM_ModuleV2.d \ +./NIARL_Util_ByteBlob.d \ +./NIARL_Util_Mask.d \ +./main.d + + +# Each subdirectory must supply rules for building sources it contributes +%.o: ../%.cpp + @echo 'Building file: $<' + @echo 'Invoking: GCC C++ Compiler' + g++ -O3 -Wall -c -fmessage-length=0 -MMD -MP -MF"$(@:%.o=%.d)" -MT"$(@:%.o=%.d)" -o"$@" "$<" + @echo 'Finished building: $<' + @echo ' ' + + diff --git a/OpenAttestation/Source/WLMService/WebContent/META-INF/MANIFEST.MF b/OpenAttestation/Source/WLMService/WebContent/META-INF/MANIFEST.MF new file mode 100644 index 0000000..254272e --- /dev/null +++ b/OpenAttestation/Source/WLMService/WebContent/META-INF/MANIFEST.MF @@ -0,0 +1,3 @@ +Manifest-Version: 1.0 +Class-Path: + diff --git a/OpenAttestation/Source/WLMService/WebContent/WEB-INF/web.xml b/OpenAttestation/Source/WLMService/WebContent/WEB-INF/web.xml new file mode 100644 index 0000000..acdd61f --- /dev/null +++ b/OpenAttestation/Source/WLMService/WebContent/WEB-INF/web.xml @@ -0,0 +1,23 @@ + + + + DB Connection + jdbc/oat + com.mchange.v2.c3p0.ComboPooledDataSource + Container + + WLMService + + jersey Web Application + com.sun.jersey.spi.container.servlet.ServletContainer + + com.sun.jersey.config.property.packages + com.intel.openAttestation.manifest.resource + + 1 + + + jersey Web Application + /* + + diff --git a/OpenAttestation/Source/WLMService/build.xml b/OpenAttestation/Source/WLMService/build.xml new file mode 100644 index 0000000..70ea465 --- /dev/null +++ b/OpenAttestation/Source/WLMService/build.xml @@ -0,0 +1,71 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/bean/AnalysisTypesBean.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/bean/AnalysisTypesBean.java new file mode 100644 index 0000000..108c957 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/bean/AnalysisTypesBean.java @@ -0,0 +1,88 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Copyright (C) 2013 Politecnico di Torino, Italy + * TORSEC group -- http://security.polito.it + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 com.intel.openAttestation.manifest.bean; + +import java.util.List; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class AnalysisTypesBean { + + private String name; + private String module; + private Integer version; + private String url; + private String requiredPcrMask; + + public String getName() { + return name; + } + @XmlElement(name="name") + public void setName(String name) { + this.name = name; + } + public String getModule() { + return module; + } + @XmlElement(name="module") + public void setModule(String module) { + this.module = module; + } + public Integer getVersion() { + return version; + } + @XmlElement(name="version") + public void setVersion(Integer version) { + this.version = version; + } + public String getUrl() { + return url; + } + @XmlElement(name="url") + public void setUrl(String url) { + this.url = url; + } + public String getRequiredPcrMask() { + return requiredPcrMask; + } + @XmlElement(name="requiredPcrMask") + public void setRequiredPcrMask(String requiredPcrMask) { + this.requiredPcrMask = requiredPcrMask; + } + +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/bean/MLEBean.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/bean/MLEBean.java new file mode 100644 index 0000000..a0ba84a --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/bean/MLEBean.java @@ -0,0 +1,103 @@ +package com.intel.openAttestation.manifest.bean; + +import java.util.List; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class MLEBean { + + private String Name; + private String Version; + private String OsName; + private String OsVersion; + private String OemName; + private String OemDescription; + private String Attestation_Type; + private String MLE_Type; + private String Description; + private List MLE_Manifests; + + public String getName() { + return Name; + } + @XmlElement(name="Name") + public void setName(String name) { + Name = name; + } + public String getVersion() { + return Version; + } + @XmlElement(name="Version") + public void setVersion(String version) { + Version = version; + } + public String getOsName() { + return OsName; + } + + @XmlElement(name="OsName") + public void setOsName(String osName) { + OsName = osName; + } + public String getOsVersion() { + return OsVersion; + } + + @XmlElement(name="OsVersion") + public void setOsVersion(String osVersion) { + OsVersion = osVersion; + } + public String getOemName() { + return OemName; + } + + @XmlElement(name="OemName") + public void setOemName(String oemName) { + OemName = oemName; + } + public String getOemDescription() { + return OemDescription; + } + + @XmlElement(name="OemDescription") + public void setOemDescription(String oemDescription) { + OemDescription = oemDescription; + } + public String getAttestation_Type() { + return Attestation_Type; + } + + @XmlElement(name="Attestation_Type") + public void setAttestation_Type(String attestation_Type) { + Attestation_Type = attestation_Type; + } + + public String getMLE_Type() { + return MLE_Type; + } + + @XmlElement(name="MLE_Type") + public void setMLE_Type(String mLE_Type) { + MLE_Type = mLE_Type; + } + + public String getDescription() { + return Description; + } + + @XmlElement(name="Description") + public void setDescription(String description) { + Description = description; + } + + public List getMLE_Manifests() { + return MLE_Manifests; + } + + @XmlElement(name="MLE_Manifests") + public void setMLE_Manifests(List mLE_Manifests) { + MLE_Manifests = mLE_Manifests; + } +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/bean/MLE_Manifest.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/bean/MLE_Manifest.java new file mode 100644 index 0000000..33694b6 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/bean/MLE_Manifest.java @@ -0,0 +1,26 @@ +package com.intel.openAttestation.manifest.bean; + +import javax.xml.bind.annotation.XmlElement; + +public class MLE_Manifest { + + private String Name; + private String Value; + public String getName() { + return Name; + } + @XmlElement(name="Name") + public void setName(String name) { + Name = name; + } + public String getValue() { + return Value; + } + + @XmlElement(name="Value") + public void setValue(String value) { + Value = value; + } + + +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/bean/OpenAttestationResponseFault.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/bean/OpenAttestationResponseFault.java new file mode 100644 index 0000000..5cc86c9 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/bean/OpenAttestationResponseFault.java @@ -0,0 +1,54 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source error_code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.manifest.bean; + +import javax.xml.bind.annotation.XmlRootElement; + + +@XmlRootElement +public class OpenAttestationResponseFault { + int error_code; + String error_message; + + public OpenAttestationResponseFault(){} + + public OpenAttestationResponseFault (int error_code){ + this.error_code= error_code; + } + + + public int getError_code() { + return error_code; + } + public void setError_code(int code) { + this.error_code = code; + } + + public String getError_message() { + return error_message; + } + public void setError_message(String message) { + this.error_message = message; + } + + public static class FaultCode{ + public static int FAULT_1006 = 1006; + public static int FAULT_401 = 401; + public static int FAULT_404 = 404; + public static int FAULT_500 = 500; + public static int FAULT_2001 = 2001; + } + + +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/bean/PcrWhiteListBean.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/bean/PcrWhiteListBean.java new file mode 100644 index 0000000..a2f74f8 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/bean/PcrWhiteListBean.java @@ -0,0 +1,69 @@ +package com.intel.openAttestation.manifest.bean; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement + + +public class PcrWhiteListBean { + + private String pcrName; + public String getPcrName() { + return pcrName; + } + @XmlElement(name = "pcrName") + public void setPcrName(String pcrName) { + this.pcrName = pcrName; + } + public String getPcrDigest() { + return pcrDigest; + } + @XmlElement(name = "pcrDigest") + public void setPcrDigest(String pcrDigest) { + this.pcrDigest = pcrDigest; + } + public String getMLEName() { + return MLEName; + } + @XmlElement(name = "mleName") + public void setMLEName(String mLEName) { + MLEName = mLEName; + } + public String getMLEVersion() { + return MLEVersion; + } + @XmlElement(name = "mleVersion") + public void setMLEVersion(String mLEVersion) { + MLEVersion = mLEVersion; + } + public String getOEMName() { + return OEMName; + } + @XmlElement(name = "oemName") + public void setOEMName(String oEMName) { + OEMName = oEMName; + } + public String getOSName() { + return OSName; + } + @XmlElement(name = "osName") + public void setOSName(String oSName) { + OSName = oSName; + } + public String getOSVersion() { + return OSVersion; + } + @XmlElement(name = "osVersion") + public void setOSVersion(String oSVersion) { + OSVersion = oSVersion; + } + private String pcrDigest; + private String MLEName; + private String MLEVersion; + private String OEMName; + private String OSName; + private String OSVersion; + + +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/dao/AnalysisTypesDao.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/dao/AnalysisTypesDao.java new file mode 100644 index 0000000..e623394 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/dao/AnalysisTypesDao.java @@ -0,0 +1,182 @@ +/* + * (copyright) 2012 United States Government, as represented by the + * Secretary of Defense. All rights reserved. + * + * Copyright (C) 2013 Politecnico di Torino, Italy + * TORSEC group -- http://security.polito.it + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - 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. + * + * - Neither the name of the U.S. Government nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT + * HOLDER OR 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 com.intel.openAttestation.manifest.hibernate.dao; + +import com.intel.openAttestation.manifest.hibernate.util.HibernateUtilHis; +import com.intel.openAttestation.manifest.hibernate.domain.AnalysisTypes; + +import java.util.List; +import java.util.Iterator; + +import org.hibernate.Query; +import org.hibernate.Session; + + +/** + * This class serves as a central location for updates and queries against + * the measures_log table + * @author Nicola Barresi + * @version Crossbow + * + */ +public class AnalysisTypesDao { + + public AnalysisTypesDao() { + } + + /** + * Saves an AnalysisTypes + * @param analysisType AnalysisTypes entry to be saved + */ + public void saveAnalysisType(AnalysisTypes analysisType) { + try { + HibernateUtilHis.beginTransaction(); + HibernateUtilHis.getSession().save(analysisType); + HibernateUtilHis.commitTransaction(); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + } finally { + HibernateUtilHis.closeSession(); + } + } + + /** + * Retrieves an AnalysisTypes entry based on the primary key + * @param id The id or primary key of the needed AnalysisTypes entry + * @return The AnalysisTypes entry retrieved from the database + */ + public AnalysisTypes getAnalysisType(Long id) { + AnalysisTypes result = null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from AnalysisTypes a where a.id = :id"); + query.setLong("id", id); + List list = query.list(); + if (list.size() >= 1) { + result = (AnalysisTypes) list.iterator().next(); + } + HibernateUtilHis.commitTransaction(); + return result; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + } finally { + HibernateUtilHis.closeSession(); + } + } + + /** + * Retrieves a not deleted AnalysisTypes entry based on its name + * @param name The name of the needed AnalysisTypes entry + * @return The AnalysisTypes entry retrieved from the database + */ + public AnalysisTypes getAnalysisTypeByName(String name) { + AnalysisTypes result = null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from AnalysisTypes a where a.name = :name and a.deleted=0"); + query.setString("name", name); + List list = query.list(); + if (list.size() >= 1) { + result = (AnalysisTypes) list.iterator().next(); + } + HibernateUtilHis.commitTransaction(); + return result; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + } finally { + HibernateUtilHis.closeSession(); + } + } + + /** + * Retrieves all the AnalysisTypes entries from the database + * @return The list of AnalysisTypes entries retrieved from + * the database + */ + public List getAllAnalysisType() { + List result = null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from AnalysisTypes a"); + List list = query.list(); + if (list.size() >= 1) { + result = (List) list; + } + HibernateUtilHis.commitTransaction(); + return result; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + } finally { + HibernateUtilHis.closeSession(); + } + } + + /** + * Deletes the AnalysisTypes entry received + * @param analysisType The AnalysisTypes to be deleted + */ + public void deleteAnalysisType (AnalysisTypes analysisType) { + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from AnalysisTypes a where a.id = :id"); + + query.setLong("id", analysisType.getId()); + List list = query.list(); + if (list.size() < 1) { + HibernateUtilHis.rollbackTransaction(); + throw new Exception("Object not found"); + } + AnalysisTypes AnalysisTypesEntry = (AnalysisTypes)list.get(0); + AnalysisTypesEntry.setDeleted(true); + HibernateUtilHis.commitTransaction(); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + } finally { + HibernateUtilHis.closeSession(); + } + } + +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/dao/MLEDAO.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/dao/MLEDAO.java new file mode 100644 index 0000000..5df2364 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/dao/MLEDAO.java @@ -0,0 +1,463 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.manifest.hibernate.dao; + +import java.util.ArrayList; +import java.util.List; +import org.hibernate.Query; +import org.hibernate.Session; +import com.intel.openAttestation.manifest.hibernate.domain.MLE; +import com.intel.openAttestation.manifest.hibernate.domain.OEM; +import com.intel.openAttestation.manifest.hibernate.domain.OS; +import com.intel.openAttestation.manifest.hibernate.util.HibernateUtilHis; +//import de.laliluna.hibernate.SessionFactoryUtil; + + +public class MLEDAO { + + /** + * Constructor to start a hibernate transaction in case one has not + * already been started + */ + public MLEDAO() { + } + + public MLE queryMLEidByNameAndVersionAndOEMid (String Name, String Version, String OEMname){ + List mleList = null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("select a from MLE a, OEM b where a.Name = :name and a.Version = :version and a.oem.OEMID = b.OEMID and b.Name = :oem_name"); + //Query query = HibernateUtilHis.getSession().createQuery("select new MLE(a.Name, a.Version, a.Attestation_Type, a.MLE_Type, a.Description, b) from MLE a, OEM b where a.Name = :name and a.Version = :version and a.oem.OEMID = b.OEMID and b.Name = :oem_name"); + + query.setString("name", Name); + query.setString("version", Version); + query.setString("oem_name", OEMname); + List list = query.list(); + mleList = (List)list; + if (list.size() < 1) + { + HibernateUtilHis.commitTransaction(); + return null; + } else { + HibernateUtilHis.commitTransaction(); + return (MLE)mleList.get(0); + } + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + public MLE queryMLEidByNameAndVersionAndOSid (String Name, String Version, String OSname, String OSversion){ + List mleList = null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("select a from MLE a, OS b where a.Name = :name and a.Version = :version and a.os.ID = b.ID and b.Name = :os_name and b.Version = :os_version"); + query.setString("name", Name); + query.setString("version", Version); + query.setString("os_name", OSname); + query.setString("os_version", OSversion); + List list = query.list(); + mleList = (List)list; + if (list.size() < 1) + { + HibernateUtilHis.commitTransaction(); + return null; + } else { + HibernateUtilHis.commitTransaction(); + return (MLE)mleList.get(0); + } + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + public boolean isOEMExisted(String Name){ + boolean flag =false; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from OEM a where a.Name = :value"); + query.setString("value", Name); + List list = query.list(); + + if (list.size() < 1) { + flag = false; + } else { + flag = true; + } + HibernateUtilHis.commitTransaction(); + return flag; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + public boolean isMLEExisted(String Name,String version){ + boolean flag =false; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from MLE m where m.Name = :mleName and m.Version = :mleVersion"); + query.setString("mleName", Name); + query.setString("mleVersion", version); + List list = query.list(); + if (list.size() > 0 ) + flag = true; + HibernateUtilHis.commitTransaction(); + return flag; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + public OEM addOEMEntry(OEM OEMEntry){ + try { + HibernateUtilHis.beginTransaction(); + HibernateUtilHis.getSession().save(OEMEntry); + HibernateUtilHis.commitTransaction(); + return OEMEntry; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + + public MLE addMLEEntry(MLE MLEEntry){ + try { + HibernateUtilHis.beginTransaction(); + HibernateUtilHis.getSession().save(MLEEntry); + HibernateUtilHis.commitTransaction(); + return MLEEntry; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + + public MLE getMLE(String Name,String Version){ + try{ + MLE mle = null; + Query query = HibernateUtilHis.getSession().createQuery("from MLE m where m.Name = :name and m.Version = :version"); + query.setString("name", Name); + query.setString("version", Version); + List list = query.list(); + if (list.size() >= 1) { + mle=(MLE)list.get(0); + } + return mle; + }catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + public void editMLEDesc(String mleName, String mleVersion, String description){ + try{ + HibernateUtilHis.beginTransaction(); + Session session = HibernateUtilHis.getSession(); + Query query = HibernateUtilHis.getSession().createQuery("from MLE m where m.Name = :name and m.Version = :version"); + query.setString("name",mleName); + query.setString("version", mleVersion); + List list = query.list(); + if (list.size() < 1){ + HibernateUtilHis.rollbackTransaction(); + throw new Exception ("Object not found"); + } + MLE mle = (MLE)list.get(0); + mle.setDescription(description); + session.update(mle); + HibernateUtilHis.commitTransaction(); + }catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + public void DeleteOEMEntry (String OEMName){ + try { + HibernateUtilHis.beginTransaction(); + Session session = HibernateUtilHis.getSession(); + Query query = session.createQuery("from OEM a where a.Name = :NAME"); + query.setString("NAME", OEMName); + List list = query.list(); + if (list.size() < 1){ + HibernateUtilHis.rollbackTransaction(); + throw new Exception ("Object not found"); + } + OEM OEMEntry = (OEM)list.get(0); + session.delete(OEMEntry); + HibernateUtilHis.commitTransaction(); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + + public MLE DeleteMLEEntry (String name,String version){ + try { + HibernateUtilHis.beginTransaction(); + Session session = HibernateUtilHis.getSession(); + Query query = session.createQuery("from MLE a where a.Name = :name and a.Version = :version"); + query.setString("name", name); + query.setString("version",version); + List list = query.list(); + if (list.size() < 1){ + HibernateUtilHis.rollbackTransaction(); + throw new Exception ("Object not found"); + } + MLE MLEEntry = (MLE)list.get(0); + session.delete(MLEEntry); + HibernateUtilHis.commitTransaction(); + return MLEEntry; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + public boolean isMLEExisted(String name, String version, String osName, + String osVersion, String oemName) { + + String[] queryString = new String[2]; + int order =0; + boolean flag= false; + try{ + HibernateUtilHis.beginTransaction(); + queryString[0]="select m from MLE m inner join m.oem o where m.Name=:name and m.Version=:version and o.Name =:oemName";//query oem information + queryString[1]="select m from MLE m inner join m.os o where m.Name=:name and m.Version=:version and o.Name=:osName and o.Version=:osVersion";//query os information + if (oemName!=null) + order = 0; + else if (osName!=null && osVersion !=null) + order =1; + Query query = HibernateUtilHis.getSession().createQuery(queryString[order]); + query.setString("name", name); + query.setString("version", version); + if (order ==0) + query.setString("oemName", oemName); + else if(order ==1){ + query.setString("osName", osName); + query.setString("osVersion", osVersion); + } + + List list = query.list(); + if(list.size()>0) + flag =true; + HibernateUtilHis.commitTransaction(); + return flag; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + public OEM queryOEMByNameAndVersionAndOEMid(String Name, String Version, String OEMname){ + List OEMList = null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("select b from MLE a, OEM b where a.Name = :name and a.Version = :version and a.oem.OEMID = b.OEMID and b.Name = :oem_name"); + query.setString("name", Name); + query.setString("version", Version); + query.setString("oem_name", OEMname); + List list = query.list(); + OEMList = (List)list; + if (list.size() < 1) + { + HibernateUtilHis.commitTransaction(); + return null; + } else { + HibernateUtilHis.commitTransaction(); + return (OEM)OEMList.get(0); + } + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + public OS queryOSByNameAndVersionAndOSid (String Name, String Version, String OSname, String OSversion){ + List OSList = null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("select b from MLE a, OS b where a.Name = :name and a.Version = :version and a.os.ID = b.ID and b.Name = :os_name and b.Version = :os_version"); + query.setString("name", Name); + query.setString("version", Version); + query.setString("os_name", OSname); + query.setString("os_version", OSversion); + List list = query.list(); + OSList = (List)list; + if (list.size() < 1) + { + HibernateUtilHis.commitTransaction(); + return null; + } else { + HibernateUtilHis.commitTransaction(); + return (OS)OSList.get(0); + } + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + public List getAllMLEEntries(){ + try{ + ArrayList MLEList = new ArrayList(); + Query query = HibernateUtilHis.getSession().createQuery("from MLE mle"); + List list = query.list(); + for (int i=0;i OEMList = null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("select a.oem from MLE a inner join a.oem o where a.MLEID = :id"); + query.setLong("id", id); + List list = query.list(); + OEMList = (List)list; + if (list.size() < 1) + { + HibernateUtilHis.commitTransaction(); + return null; + } else { + HibernateUtilHis.commitTransaction(); + return (OEM)OEMList.get(0); + } + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + public OS queryOSByMLEID(long id){ + List OSList = null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("select a.os from MLE a inner join a.os o where a.MLEID = :id"); + query.setLong("id", id); + List list = query.list(); + OSList = (List)list; + if (list.size() < 1) + { + HibernateUtilHis.commitTransaction(); + return null; + } else { + HibernateUtilHis.commitTransaction(); + return (OS)OSList.get(0); + } + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + public MLE queryMLEByCriteria(String criteria, MLE inst, Long mleID){ + List mleList = null; + Query query; + try { + if (inst.getOem() != null){ + query = HibernateUtilHis.getSession().createQuery("select a from MLE a inner join a.oem b where (a.Name like '%"+criteria+"%' or a.Version like '%"+criteria+"%'" + + " or a.Description like '%"+criteria+"%' or a.oem.Name like '%"+criteria+"%') and a.MLEID = :value "); + query.setLong("value", mleID); + } else if (inst.getOs() != null){ + query = HibernateUtilHis.getSession().createQuery("select a from MLE a inner join a.os b where (a.Name like '%"+criteria+"%' or a.Version like '%"+criteria+"%'" + + " or a.Description like '%"+criteria+"%' or a.os.Name like '%"+criteria+"%' or a.os.Version like '%"+criteria+"%') and a.MLEID = :value "); + query.setLong("value", mleID); + } else { + return null; + } + List list = query.list(); + mleList = (List)list; + if (list.size() < 1) + { + return null; + } else { + return (MLE)mleList.get(0); + } + } catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + } + + public void openTransaction(){ + + } +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/dao/OEMDAO.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/dao/OEMDAO.java new file mode 100644 index 0000000..e2b8e2e --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/dao/OEMDAO.java @@ -0,0 +1,193 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.manifest.hibernate.dao; + +import java.util.ArrayList; +import java.util.List; +import org.hibernate.Query; +import org.hibernate.Session; +import com.intel.openAttestation.manifest.hibernate.domain.OEM; +import com.intel.openAttestation.manifest.hibernate.util.HibernateUtilHis; + +/** + * This class serves as a central location for updates and queries against + * the OEM table + * @author intel + * @version OpenAttestation + * + */ +public class OEMDAO { + + /** + * Constructor to start a hibernate transaction in case one has not + * already been started + */ + public OEMDAO() { + } + + public OEM addOEMEntry(OEM OEMEntry){ + try { + HibernateUtilHis.beginTransaction(); + //OEM.setCreateTime(new Date()); + HibernateUtilHis.getSession().save(OEMEntry); + HibernateUtilHis.commitTransaction(); + return OEMEntry; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + public void editOEMEntry (OEM oemEntry){ + try { + HibernateUtilHis.beginTransaction(); + Session session = HibernateUtilHis.getSession(); + + Query query = session.createQuery("from OEM a where a.Name = :name"); + query.setString("name", oemEntry.getName()); + List list = query.list(); + if (list.size() < 1){ + HibernateUtilHis.rollbackTransaction(); + throw new Exception ("Object not found"); + } + OEM oemOld = (OEM)list.get(0); + oemOld.setDescription(oemEntry.getDescription()); + HibernateUtilHis.commitTransaction(); + //return oemEntry; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + + public void DeleteOEMEntry (String Name){ + try { + HibernateUtilHis.beginTransaction(); + Session session = HibernateUtilHis.getSession(); + Query query = session.createQuery("from OEM a where a.Name = :NAME"); + query.setString("NAME", Name); + List list = query.list(); + if (list.size() < 1){ + HibernateUtilHis.rollbackTransaction(); + throw new Exception ("Object not found"); + } + OEM OEMEntry = (OEM)list.get(0); + session.delete(OEMEntry); + HibernateUtilHis.commitTransaction(); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + public boolean isOEMExisted(String Name){ + boolean flag =false; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from OEM a where a.Name = :value"); + query.setString("value", Name); + List list = query.list(); + + if (list.size() < 1) { + flag = false; + } else { + flag = true; + } + HibernateUtilHis.commitTransaction(); + return flag; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + public OEM getOEM(String Name){ + OEM oem =null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from OEM a where a.Name = :value"); + query.setString("value", Name); + List list = query.list(); + if (list.size() >= 1) { + oem = (OEM)list.iterator().next(); + } + HibernateUtilHis.commitTransaction(); + return oem; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + public boolean isRefMle(String name){ + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("select m from MLE m inner join m.oem o where o.Name = :name"); + query.setString("name", name); + List list = query.list(); + if (list.size() >= 1) { + HibernateUtilHis.commitTransaction(); + return true; + } else { + HibernateUtilHis.commitTransaction(); + return false; + } + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + public List getAllOEMEntries(){ + try{ + HibernateUtilHis.beginTransaction(); + ArrayList OEMList = new ArrayList(); + Query query = HibernateUtilHis.getSession().createQuery("from OEM oem"); + System.out.println("query:"+query.toString()); + List list = query.list(); + for (int i=0;i= 1) { + os = (OS)list.iterator().next(); + } + HibernateUtilHis.commitTransaction(); + return os; + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + public boolean isRefMle(String name, String version){ + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("select m from MLE m inner join m.os o where o.Name = :name and o.Version = :version"); + query.setString("name", name); + query.setString("version", version); + List list = query.list(); + if (list.size() >= 1) { + HibernateUtilHis.commitTransaction(); + return true; + } else { + HibernateUtilHis.commitTransaction(); + return false; + } + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + public List getAllOSEntries(){ + try{ + HibernateUtilHis.beginTransaction(); + ArrayList OSList = new ArrayList(); + Query query = HibernateUtilHis.getSession().createQuery("from OS os"); + System.out.println("query:"+query.toString()); + List list = query.list(); + for (int i=0;i pcrList = null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("select c from MLE a, OEM b, PcrWhiteList c where a.Name = :name and a.Version = :version and a.oem.OEMID = b.OEMID and b.Name = :oem_name and a.MLEID = c.mle.MLEID and c.pcrName = :pcr_name"); + query.setString("name", Name); + query.setString("version", Version); + query.setString("oem_name", OEMname); + query.setString("pcr_name", PcrName); + List list = query.list(); + pcrList = (List)list; + if (list.size() < 1) + { + HibernateUtilHis.commitTransaction(); + return null; + } else { + HibernateUtilHis.commitTransaction(); + return (PcrWhiteList)pcrList.get(0); + } + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + public PcrWhiteList queryPcrByOSid (String Name, String Version, String OSname, String OSversion, String PcrName){ + List pcrList = null; + try { + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("select c from MLE a, OS b, PcrWhiteList c where a.Name = :name and a.Version = :version and a.os.ID = b.ID and b.Name = :os_name and b.Version = :os_version and a.MLEID = c.mle.MLEID and c.pcrName = :pcr_name"); + query.setString("name", Name); + query.setString("version", Version); + query.setString("os_name", OSname); + query.setString("os_version", OSversion); + query.setString("pcr_name", PcrName); + List list = query.list(); + pcrList = (List)list; + if (list.size() < 1) + { + HibernateUtilHis.commitTransaction(); + return null; + } else { + HibernateUtilHis.commitTransaction(); + return (PcrWhiteList)pcrList.get(0); + } + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + public void deletePcrByMleID(Long mleId){ + try { + HibernateUtilHis.beginTransaction(); + Session session = HibernateUtilHis.getSession(); + Query query = session.createQuery("from PcrWhiteList a where a.mle.MLEID = :mleid"); + query.setLong("mleid", mleId); + List list = query.list(); + for(int i=0; i < list.size(); i++){ + session.delete((PcrWhiteList)list.get(i)); + } + HibernateUtilHis.commitTransaction(); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + public PcrWhiteList getPcr(String pcrName, Long mleId){ + try { + PcrWhiteList pcr = null; + HibernateUtilHis.beginTransaction(); + Query query = HibernateUtilHis.getSession().createQuery("from PcrWhiteList a where a.pcrName = :name and a.mle.MLEID = :mleid"); + query.setString("name", pcrName); + query.setLong("mleid", mleId); + List list = query.list(); + if (list.size() >= 1) + pcr = (PcrWhiteList)list.iterator().next(); + HibernateUtilHis.commitTransaction(); + return pcr; + + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + } + + public void addPcrList(List pcrList){ + try { + HibernateUtilHis.beginTransaction(); + Session session = HibernateUtilHis.getSession(); + for (PcrWhiteList pcr: pcrList) + session.save(pcr); + HibernateUtilHis.commitTransaction(); + } catch (Exception e) { + HibernateUtilHis.rollbackTransaction(); + e.printStackTrace(); + throw new RuntimeException(e); + }finally{ + HibernateUtilHis.closeSession(); + } + + } + + public List queryPcrByMLEid(long mleID){ + List pcrList = null; + try { + Query query = HibernateUtilHis.getSession().createQuery("select a from PcrWhiteList a where a.mle.MLEID = :mleID"); + query.setLong("mleID", mleID); + List list = query.list(); + pcrList = (List)list; + if (list.size() < 1) + { + return null; + } else { + return pcrList; + } + }catch (Exception e) { + e.printStackTrace(); + throw new RuntimeException(e); + } + + } + +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/AnalysisTypes.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/AnalysisTypes.java new file mode 100644 index 0000000..261d43d --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/AnalysisTypes.java @@ -0,0 +1,90 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Copyright (C) 2013 Politecnico di Torino, Italy + TORSEC group -- http://security.polito.it + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.manifest.hibernate.domain; + +import javax.xml.bind.annotation.XmlRootElement; + + +@XmlRootElement +public class AnalysisTypes { + + private Long id; + + private String name; + + private String module; + + private Integer version; + + private String URL; + + private boolean deleted; + + private String requiredPcrMask; + + public AnalysisTypes() { + } + + public void setId(Long id) { + this.id = id; + } + public Long getId() { + return id; + } + + public void setName(String name) { + this.name = name; + } + public String getName() { + return name; + } + + public void setModule(String module) { + this.module = module; + } + public String getModule() { + return module; + } + + public void setVersion(Integer version) { + this.version = version; + } + public Integer getVersion() { + return version; + } + + public void setURL(String URL) { + this.URL = URL; + } + public String getURL() { + return URL; + } + + public void setDeleted(boolean deleted) { + this.deleted = deleted; + } + public boolean getDeleted() { + return deleted; + } + + public void setRequiredPcrMask(String requiredPcrMask) { + this.requiredPcrMask = requiredPcrMask; + } + public String getRequiredPcrMask() { + return requiredPcrMask; + } +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/HOST.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/HOST.java new file mode 100644 index 0000000..defd856 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/HOST.java @@ -0,0 +1,104 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.manifest.hibernate.domain; + +//import java.util.Date; + +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlElement; + +/** + * Java class linked to the HOST table. + * @author intel + * @version OpenAttestation + * + */ + +@XmlRootElement + +public class HOST { + private Long ID; + private String HostName; + private String IPAddress; + private String Port; + private String Email; + private String AddOn_Connection_String; + private String Description; + private String pcrIMLMask; + public Long getID() { + return ID; + } + public void setID(Long iD) { + ID = iD; + } + public String getHostName() { + return HostName; + } + + @XmlElement(name = "HostName") + public void setHostName(String hostName) { + HostName = hostName; + } + public String getIPAddress() { + return IPAddress; + } + + @XmlElement(name = "IPAddress") + public void setIPAddress(String iPAddress) { + IPAddress = iPAddress; + } + public String getPort() { + return Port; + } + + @XmlElement(name = "Port") + public void setPort(String port) { + Port = port; + } + public String getEmail() { + return Email; + } + + @XmlElement(name = "Email") + public void setEmail(String email) { + Email = email; + } + public String getAddOn_Connection_String() { + return AddOn_Connection_String; + } + + @XmlElement(name = "AddOn_Connection_String") + public void setAddOn_Connection_String(String addOn_Connection_String) { + AddOn_Connection_String = addOn_Connection_String; + } + public String getDescription() { + return Description; + } + + @XmlElement(name = "Description") + public void setDescription(String description) { + Description = description; + } + + + @XmlElement(name = "pcrIMLMask") + public void setPcrIMLMask(String pcrIMLMask) { + this.pcrIMLMask = pcrIMLMask; + } + + public String getPcrIMLMask() { + return pcrIMLMask; + } + +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/MLE.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/MLE.java new file mode 100644 index 0000000..2eb1917 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/MLE.java @@ -0,0 +1,87 @@ +package com.intel.openAttestation.manifest.hibernate.domain; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class MLE { + + private Long MLEID; + private String Name; + private String Version; + private OEM oem; + private OS os; + private String Attestation_Type; + private String MLE_Type; + private String Description; + + + public Long getMLEID() { + return MLEID; + } + + public void setMLEID(Long mLEID) { + MLEID = mLEID; + } + + public String getName() { + return Name; + } + + @XmlElement(name = "Name") + public void setName(String name) { + Name = name; + } + + public String getVersion() { + return Version; + } + + @XmlElement(name = "Version") + public void setVersion(String version) { + Version = version; + } + + public OEM getOem() { + return oem; + } + + public void setOem(OEM oem) { + this.oem = oem; + } + + public OS getOs() { + return os; + } + + public void setOs(OS os) { + this.os = os; + } + + public String getAttestation_Type() { + return Attestation_Type; + } + + @XmlElement(name = "Attestation_Type") + public void setAttestation_Type(String attestation_Type) { + Attestation_Type = attestation_Type; + } + + public String getMLE_Type() { + return MLE_Type; + } + + @XmlElement(name = "MLE_Type") + public void setMLE_Type(String mLE_Type) { + MLE_Type = mLE_Type; + } + + public String getDescription() { + return Description; + } + @XmlElement(name = "Description") + public void setDescription(String description) { + Description = description; + } + +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/OEM.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/OEM.java new file mode 100644 index 0000000..0b02e77 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/OEM.java @@ -0,0 +1,74 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.manifest.hibernate.domain; + +import javax.xml.bind.annotation.XmlRootElement; + +import javax.xml.bind.annotation.XmlElement; + +/** + * Java class linked to the PCR_manifest table. + * @author intel + * @version OpenAttestation + * + */ + +@XmlRootElement + +public class OEM { + Long OEMID; + String Name; + String Description; + + public OEM(){} + + public OEM(Long ID, String name, String desc){ + this.Name = name; + this.Description = desc; + } + + public Long getOEMID() { + return OEMID; + } + + public void setOEMID(Long id) { + OEMID = id; + } + + public String getName() { + return Name; + } + + @XmlElement(name = "Name") + public void setName(String name) { + Name = name; + } + + public String getDescription() { + return Description; + } + + @XmlElement(name = "Description") + public void setDescription(String desc) { + Description = desc; + } + + /** + * validate + * @return + */ + public String validateDataFormat(){ + return ""; + } +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/OS.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/OS.java new file mode 100644 index 0000000..f194a84 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/OS.java @@ -0,0 +1,84 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.manifest.hibernate.domain; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * Java class linked to the PCR_manifest table. + * @author intel + * @version OpenAttestation + * + */ + +@XmlRootElement + +public class OS { + Long ID; + String Name; + String Version; + String Description; + + public OS(){} + + public OS(Long ID, String name, String version, String desc){ + this.Name = name; + this.Version = version; + this.Description = desc; + } + + public Long getID() { + return ID; + } + + public void setID(Long id) { + ID = id; + } + + public String getName() { + return Name; + } + + @XmlElement(name = "Name") + public void setName(String name) { + Name = name; + } + + public String getVersion() { + return Version; + } + + @XmlElement(name = "Version") + public void setVersion(String version) { + Version = version; + } + + public String getDescription() { + return Description; + } + + @XmlElement(name = "Description") + public void setDescription(String desc) { + Description = desc; + } + + /** + * validate + * @return + */ + public String validateDataFormat(){ + return ""; + } +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/PcrWhiteList.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/PcrWhiteList.java new file mode 100644 index 0000000..69d66d0 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/domain/PcrWhiteList.java @@ -0,0 +1,47 @@ +package com.intel.openAttestation.manifest.hibernate.domain; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement + +public class PcrWhiteList { + + private Long PcrWhiteListID; + private String pcrName; + private String pcrDigest; + private MLE mle; + + public Long getPcrWhiteListID() { + return PcrWhiteListID; + } + + public void setPcrWhiteListID(Long pcrWhiteListID) { + PcrWhiteListID = pcrWhiteListID; + } + + public String getPcrName() { + return pcrName; + } + + public void setPcrName(String pcrName) { + this.pcrName = pcrName; + } + + public String getPcrDigest() { + return pcrDigest; + } + + public void setPcrDigest(String pcrDigest) { + this.pcrDigest = pcrDigest; + } + + public MLE getMle() { + return mle; + } + + public void setMle(MLE mle) { + this.mle = mle; + } + +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/HOST.hbm.xml b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/HOST.hbm.xml new file mode 100644 index 0000000..b62acdc --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/HOST.hbm.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/MLE.hbm.xml b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/MLE.hbm.xml new file mode 100644 index 0000000..1621ef4 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/MLE.hbm.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/OEM.hbm.xml b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/OEM.hbm.xml new file mode 100644 index 0000000..e078f99 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/OEM.hbm.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/OS.hbm.xml b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/OS.hbm.xml new file mode 100644 index 0000000..7785c7b --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/OS.hbm.xml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/PcrWhiteList.hbm.xml b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/PcrWhiteList.hbm.xml new file mode 100644 index 0000000..ce027f1 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/PcrWhiteList.hbm.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/analysisTypes.hbm.xml b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/analysisTypes.hbm.xml new file mode 100644 index 0000000..4cbe0d7 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/mapping/analysisTypes.hbm.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/util/HibernateUtilHis.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/util/HibernateUtilHis.java new file mode 100644 index 0000000..eac89b0 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/util/HibernateUtilHis.java @@ -0,0 +1,266 @@ +package com.intel.openAttestation.manifest.hibernate.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.HibernateException; +import org.hibernate.Interceptor; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.cfg.Configuration; + + +/** + * Basic Hibernate helper class, handles SessionFactory, Session and Transaction. + *

    + * Uses a static initializer for the initial SessionFactory creation + * and holds Session and Transactions in thread local variables. All + * exceptions are wrapped in an unchecked InfrastructureException. + * + * @author christian@hibernate.org + */ +public class HibernateUtilHis { + + private static Log log = LogFactory.getLog(HibernateUtilHis.class); + + private static Configuration configuration; + private static SessionFactory sessionFactory; + private static final ThreadLocal threadSession = new ThreadLocal(); + private static final ThreadLocal threadTransaction = new ThreadLocal(); + private static final ThreadLocal threadInterceptor = new ThreadLocal(); + + // Create the initial SessionFactory from the default configuration files + + static { + try { + configuration = new Configuration(); + sessionFactory = configuration.configure("/hibernateOat.cfg.xml").buildSessionFactory(); + // We could also let Hibernate bind it to JNDI: + + // configuration.configure().buildSessionFactory() + } catch (Throwable ex) { + // We have to catch Throwable, otherwise we will miss + // NoClassDefFoundError and other subclasses of Error + log.error("Building SessionFactory failed.", ex); + throw new ExceptionInInitializerError(ex); + } + } + + /** + * Returns the SessionFactory used for this static class. + * + * @return SessionFactory + */ + + public static SessionFactory getSessionFactory() { + /* Instead of a static variable, use JNDI: + SessionFactory sessions = null; + try { + Context ctx = new InitialContext(); + String jndiName = "java:hibernate/HibernateFactory"; + sessions = (SessionFactory)ctx.lookup(jndiName); + } catch (NamingException ex) { + throw new InfrastructureException(ex); + } + return sessions; + */ + synchronized (sessionFactory) { + return sessionFactory; + } + } + + /** + * Returns the original Hibernate configuration. + * + * @return Configuration + */ + + public static Configuration getConfiguration() { + return configuration; + } + + /** + * Rebuild the SessionFactory with the static Configuration. + * + */ + public static void rebuildSessionFactory() throws OATException { + synchronized (sessionFactory) { + try { + sessionFactory = getConfiguration().buildSessionFactory(); + } catch (Exception ex) { + throw new OATException(ex); + } + } + } + + /** + * Rebuild the SessionFactory with the given Hibernate Configuration. + * + * @param cfg + */ + + public static void rebuildSessionFactory(Configuration cfg) throws + OATException { + synchronized (sessionFactory) { + try { + sessionFactory = cfg.buildSessionFactory(); + configuration = cfg; + } catch (Exception ex) { + throw new OATException(ex); + } + } + } + + /** + * Retrieves the current Session local to the thread. + *

    + + * If no Session is open, opens a new Session for the running thread. + * + * @return Session + */ + public static Session getSession() throws OATException { + Session s = (Session) threadSession.get(); + try { + if (s == null) { + log.debug("Opening new Session for this thread."); + if (getInterceptor() != null) { + log.debug("Using interceptor: " + getInterceptor().getClass()); + s = getSessionFactory().openSession(getInterceptor()); + } else { + s = getSessionFactory().openSession(); + } + threadSession.set(s); + } + } catch (HibernateException ex) { + throw new OATException(ex); + } + return s; + } + + /** + * Closes the Session local to the thread. + */ + + public static void closeSession() throws OATException { + try { + Session s = (Session) threadSession.get(); + threadSession.set(null); + if (s != null && s.isOpen()) { + log.debug("Closing Session of this thread."); + s.close(); + } + } catch (HibernateException ex) { + throw new OATException(ex); + } + } + + /** + * Start a new database transaction. + */ + + public static void beginTransaction() throws OATException { + Transaction tx = (Transaction) threadTransaction.get(); + try { + if (tx == null) { + log.debug("Starting new database transaction in this thread."); + tx = getSession().beginTransaction(); + threadTransaction.set(tx); + } + } catch (HibernateException ex) { + throw new OATException(ex); + } + } + + /** + * Commit the database transaction. + */ + + public static void commitTransaction() throws OATException { + Transaction tx = (Transaction) threadTransaction.get(); + try { + if (tx != null && !tx.wasCommitted() + && !tx.wasRolledBack()) { + log.debug("Committing database transaction of this thread."); + tx.commit(); + } + threadTransaction.set(null); + } catch (HibernateException ex) { + rollbackTransaction(); + throw new OATException(ex); + } + } + + /** + * Commit the database transaction. + */ + + public static void rollbackTransaction() throws OATException { + Transaction tx = (Transaction) threadTransaction.get(); + try { + threadTransaction.set(null); + if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) { + log.debug( + "Tyring to rollback database transaction of this thread."); + tx.rollback(); + } + } catch (HibernateException ex) { + throw new OATException(ex); + } finally { + closeSession(); + } + } + + /** + * Reconnects a Hibernate Session to the current Thread. + * + * @param session The Hibernate Session to be reconnected. + */ + + public static void reconnect(Session session) throws + OATException { + try { + session.reconnect(); + threadSession.set(session); + } catch (HibernateException ex) { + throw new OATException(ex); + } + } + + /** + * Disconnect and return Session from current Thread. + * + * @return Session the disconnected Session + */ + + public static Session disconnectSession() throws OATException { + + Session session = getSession(); + try { + threadSession.set(null); + session.disconnect(); + } catch (HibernateException ex) { + throw new OATException(ex); + } + return session; + } + + /** + * Register a Hibernate interceptor with the current thread. + *

    + + * Every Session opened is opened with this interceptor after + * registration. Has no effect if the current Session of the + * thread is already open, effective on next close()/getSession(). + */ + public static void registerInterceptor(Interceptor interceptor) { + threadInterceptor.set(interceptor); + } + + private static Interceptor getInterceptor() { + Interceptor interceptor = + (Interceptor) threadInterceptor.get(); + return interceptor; + } + +} \ No newline at end of file diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/util/OATException.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/util/OATException.java new file mode 100644 index 0000000..ccd20f5 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/hibernate/util/OATException.java @@ -0,0 +1,22 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.manifest.hibernate.util; + +public class OATException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public OATException(Throwable cause) { + super(cause); + } +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/resource/AnalysisTypesResource.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/resource/AnalysisTypesResource.java new file mode 100644 index 0000000..f96fb22 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/resource/AnalysisTypesResource.java @@ -0,0 +1,176 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Copyright (C) 2013 Politecnico di Torino, Italy + TORSEC group -- http://security.polito.it + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +* 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. +* Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.manifest.resource; + +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; +import com.intel.openAttestation.manifest.bean.OpenAttestationResponseFault; +import com.intel.openAttestation.manifest.hibernate.dao.AnalysisTypesDao; +import com.intel.openAttestation.manifest.hibernate.domain.AnalysisTypes; +import com.intel.openAttestation.manifest.hibernate.util.HibernateUtilHis; +import com.intel.openAttestation.manifest.bean.AnalysisTypesBean; + +import java.io.File; + +/** +* RESTful web service interface to work with OEM DB. +* @author xmei1 +* +*/ + +@Path("resources/analysisTypes") +public class AnalysisTypesResource { + static final int MAX_NAME_SIZE = 64; + static final int MAX_MODULE_SIZE = 64; + static final int MAX_URL_SIZE = 256; + + @POST + @Consumes("application/json") + @Produces("application/json") + public Response addAnalysisRequest(@Context UriInfo uriInfo, AnalysisTypesBean analysisTypeBean, + @Context javax.servlet.http.HttpServletRequest request) { + + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(AnalysisTypesResource.class); + Response.Status status = Response.Status.OK; + + try { + AnalysisTypesDao dao = new AnalysisTypesDao(); + + if (analysisTypeBean.getName() == null || + analysisTypeBean.getModule() == null || + analysisTypeBean.getVersion() == null || + analysisTypeBean.getUrl() == null) { + throw new Exception("Missing parameter found."); + } + + if (analysisTypeBean.getName().length() < 1 || + analysisTypeBean.getModule().length() < 1 || + analysisTypeBean.getUrl().length() < 1) { + throw new Exception("Too short parameter found"); + } + + if (analysisTypeBean.getName().length() > MAX_NAME_SIZE || + analysisTypeBean.getModule().length() > MAX_MODULE_SIZE || + analysisTypeBean.getUrl().length() > MAX_URL_SIZE) { + throw new Exception("Too long parameter found"); + } + + if (analysisTypeBean.getName().contains(" ")) { + throw new Exception("Spaces not allowed in field \"name\""); + } + + if (analysisTypeBean.getRequiredPcrMask() != null && + !analysisTypeBean.getRequiredPcrMask().matches("[0-9A-Fa-f]{6}")) { + throw new Exception("Wrong syntax for \"requiredPcrMask\", six hexadecimal numbers expected"); + } + + String analysisName = analysisTypeBean.getName(); + if (analysisName.equals("COMPARE_REPORT") || analysisName.equals("VALIDATE_PCR")) { + throw new Exception("Analysis name '" + analysisName + "' not allowed; built-in analysis."); + } + + String[] splittedURL = analysisTypeBean.getUrl().split(" "); + if (!new File(splittedURL[0]).exists()) { + throw new Exception("Specified script ('" + splittedURL[0] + "') doesn't exist."); + } + + if (dao.getAnalysisTypeByName(analysisTypeBean.getName()) != null) + throw new Exception("AnalysisType " + analysisTypeBean.getName() + " already exists in the database."); + + AnalysisTypes analysisType = new AnalysisTypes(); + analysisType.setName(analysisTypeBean.getName()); + analysisType.setModule(analysisTypeBean.getModule()); + analysisType.setVersion(analysisTypeBean.getVersion()); + analysisType.setURL(analysisTypeBean.getUrl()); + analysisType.setRequiredPcrMask((analysisTypeBean.getRequiredPcrMask() == null) ? "000000" : analysisTypeBean.getRequiredPcrMask()); + analysisType.setDeleted(false); + + dao.saveAnalysisType(analysisType); + + return Response.status(status).header("Location", b.build()).type(MediaType.TEXT_PLAIN).entity("True").build(); + } catch (Exception e) { + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Add AnalysisTypes entry failed. " + e.getMessage()); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + } + + @DELETE + @Produces("application/json") + public Response delAnalysisRequest(@QueryParam("name") String name,@Context UriInfo uriInfo) { + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(AnalysisTypesResource.class); + Response.Status status = Response.Status.OK; + boolean isValidKey = true; + + try { + AnalysisTypesDao dao = new AnalysisTypesDao(); + + if (name == null) + throw new Exception("Missing parameter \"name\"."); + + if (name.length() < 1) + throw new Exception("Too short parameter \"name\"."); + + if (name.length() > MAX_NAME_SIZE) + throw new Exception("Too long parameter \"name\""); + + if (name.contains(" ")) + throw new Exception("Spaces not allowed in field \"name\""); + + if (name.equals("COMPARE_REPORT") || name.equals("VALIDATE_PCR")) + throw new Exception("Analysis name '" + name + "' not allowed; built-in analysis."); + + AnalysisTypes analysisType = dao.getAnalysisTypeByName(name); + if (analysisType == null) + throw new Exception("AnalysisType " + name + " does not exist in the database."); + + dao.deleteAnalysisType(analysisType); + return Response.status(status).type(MediaType.TEXT_PLAIN).entity("True").build(); + } catch (Exception e) { + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Edit AnalysisTypes entry failed. " + e.getMessage()); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + } + + @GET + @Produces("application/json") + public List getAnalysisTypeEntry() { + AnalysisTypesDao dao = new AnalysisTypesDao(); + + return dao.getAllAnalysisType(); + } +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/resource/MLEResource.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/resource/MLEResource.java new file mode 100644 index 0000000..f6f429c --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/resource/MLEResource.java @@ -0,0 +1,498 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.manifest.resource; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; + +import gov.niarl.hisAppraiser.util.HisUtil; + +import com.intel.openAttestation.manifest.bean.MLEBean; +import com.intel.openAttestation.manifest.bean.MLE_Manifest; +import com.intel.openAttestation.manifest.bean.OpenAttestationResponseFault; +import com.intel.openAttestation.manifest.hibernate.dao.MLEDAO; +import com.intel.openAttestation.manifest.hibernate.dao.OEMDAO; +import com.intel.openAttestation.manifest.hibernate.dao.OSDAO; +import com.intel.openAttestation.manifest.hibernate.dao.PcrWhiteListDAO; +import com.intel.openAttestation.manifest.hibernate.domain.MLE; +import com.intel.openAttestation.manifest.hibernate.domain.OEM; +import com.intel.openAttestation.manifest.hibernate.domain.OS; +import com.intel.openAttestation.manifest.hibernate.domain.PcrWhiteList; +import com.intel.openAttestation.manifest.hibernate.util.HibernateUtilHis; +import com.intel.openAttestation.manifest.resource.MLEResource; + + +/** + * RESTful web service interface to work with MLE DB. + * @author + * + */ + +@Path("resources/mles") +public class MLEResource { + @POST + @Consumes("application/json") + @Produces("application/json") + public Response addMLE(@Context UriInfo uriInfo, MLEBean mleBean,@Context javax.servlet.http.HttpServletRequest request){ + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(MLEResource.class); + Response.Status status = Response.Status.OK; + boolean isValidKey = true; + try{ + MLEDAO dao = new MLEDAO(); + PcrWhiteListDAO pcrDao = new PcrWhiteListDAO(); + OSDAO osDao = new OSDAO(); + OEMDAO oemDao = new OEMDAO(); + MLE mle = new MLE(); + OS os = new OS(); + OEM oem = new OEM(); + HashMap parameters = new HashMap(); + + if (mleBean.getName() != null && mleBean.getVersion() != null && mleBean.getAttestation_Type() != null && mleBean.getAttestation_Type().equals("PCR")){ + parameters.put(mleBean.getName(), 50); + parameters.put(mleBean.getVersion(), 100); + parameters.put(mleBean.getAttestation_Type(), 50); + } else { + isValidKey = false; + } + + if (mleBean.getOsName() != null){ + parameters.put(mleBean.getOsName(), 50); + } + + if (mleBean.getOsVersion() != null){ + parameters.put(mleBean.getOsVersion(), 50); + } + + if (mleBean.getOemName() != null){ + parameters.put(mleBean.getOemName(), 50); + } + + if (mleBean.getMLE_Type() != null){ + parameters.put(mleBean.getMLE_Type(), 50); + } + + if (mleBean.getDescription() != null){ + parameters.put(mleBean.getDescription(), 100); + } + + if (mleBean.getMLE_Manifests() != null){ + List pcrList = mleBean.getMLE_Manifests(); + for (MLE_Manifest list : pcrList){ + if(list.getValue() == null || list.getValue().length() == 0 || list.getName() == null + || list.getName().length() == 0) + { + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Invalid put for PCR value"); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + parameters.put(list.getValue(), 100); + } + } + + parameters.put(mleBean.getDescription(), 100); + if (!isValidKey || mleBean.getName().length() < 1 || mleBean.getVersion().length() < 1 || !HisUtil.validParas(parameters)){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + if (mleBean.getAttestation_Type() == null || !mleBean.getAttestation_Type().equals("PCR")){ + fault.setError_message("Invalid put for Attestation type"); + } else { + fault.setError_message("Add MLE entry failed, please check the length for each parameters" + + " and remove all of the unwanted characters belonged to [# & + : " + "\" \']"); + } + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + + if (mleBean.getMLE_Type().equals("VMM")){ + System.out.println("The OS Name exists:" + mleBean.getOsName()); + if ( (os = osDao.getOS(mleBean.getOsName(), mleBean.getOsVersion()))!= null){ + mle.setOs(os); + } + else{ + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(1006); + fault.setError_message("Data Error - OS[" + mleBean.getOsName() + + "] Version[" + mleBean.getOsVersion() +"] does not exist"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + } + else if(mleBean.getMLE_Type().equals("BIOS")){ + if((oem = oemDao.getOEM(mleBean.getOemName())) != null){ + mle.setOem(oem); + } + else{ + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(1006); + fault.setError_message("Data Error - OEM[" + mleBean.getOemName() + "] does not exist"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + + } + } + else{ + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(1006); + fault.setError_message("Data Error - MLE_Type is error:" + mleBean.getMLE_Type()); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + if(dao.isMLEExisted(mleBean.getName(), mleBean.getVersion())){ + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(1006); + fault.setError_message("Data Error - MLE Name " + mleBean.getName()+ " Version "+mleBean.getVersion() + " already exists in the database"); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + + mle.setName(mleBean.getName()); + mle.setVersion(mleBean.getVersion()); + mle.setAttestation_Type(mleBean.getAttestation_Type()); + mle.setDescription(mleBean.getDescription()); + mle.setMLE_Type(mleBean.getMLE_Type()); + dao.addMLEEntry(mle); + if (mleBean.getMLE_Manifests()!=null){ + for(MLE_Manifest mle_manifest:mleBean.getMLE_Manifests()){ + PcrWhiteList pcr = new PcrWhiteList(); + pcr.setPcrName(mle_manifest.getName()); + pcr.setPcrDigest(mle_manifest.getValue()); + pcr.setMle(mle); + pcrDao.addPcrEntry(pcr); + } + } + return Response.status(status).header("Location", b.build()).type(MediaType.TEXT_PLAIN).entity("True").build(); + }catch (Exception e){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Add MLE entry failed." + "Exception:" + e.getMessage()); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + + } + + @PUT + @Consumes("application/json") + @Produces("application/json") + public Response updateMLE(@Context UriInfo uriInfo, MLEBean mleBean, + @Context javax.servlet.http.HttpServletRequest request){ + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(MLEResource.class); + Response.Status status = Response.Status.OK; + boolean isValidKey = true; + try{ + MLEDAO mleDao = new MLEDAO(); + OSDAO osDao = new OSDAO(); + OEMDAO oemDao = new OEMDAO(); + List pcrList = new ArrayList(); + PcrWhiteListDAO pcrDao = new PcrWhiteListDAO(); + HashMap parameters = new HashMap(); + if (mleBean.getName() != null) { + parameters.put(mleBean.getName(), 50); + } else { + isValidKey = false; + } + + if (mleBean.getVersion() != null){ + parameters.put(mleBean.getVersion(), 100); + } else { + isValidKey = false; + } + + if (mleBean.getMLE_Type() != null){ + parameters.put(mleBean.getMLE_Type(), 50); + } + + if (mleBean.getDescription() != null){ + parameters.put(mleBean.getDescription(), 100); + } + + if (!isValidKey || mleBean.getVersion().length() < 1 || mleBean.getName().length() < 1 || !HisUtil.validParas(parameters)){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Update MLE entry failed, please check the length for each parameters" + + " and remove all of the unwanted characters belonged to [# & + : \" \']"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + if (mleBean.getMLE_Type().equals("BIOS") || mleBean.getMLE_Type().equals("VMM")){ + if (!mleDao.isMLEExisted(mleBean.getName(),mleBean.getVersion(),mleBean.getOsName(),mleBean.getOsVersion(),mleBean.getOemName())){ + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(1007); + fault.setError_message("WLM Service Error - MLE not found in attestation data to update"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + MLE mle = mleDao.getMLE(mleBean.getName(),mleBean.getVersion()); + if(mleBean.getDescription()!=null) //update description + mleDao.editMLEDesc(mleBean.getName(),mleBean.getVersion(), mleBean.getDescription()); + if (mleBean.getMLE_Manifests()!=null){ //update whitelist + for (MLE_Manifest mleManifest: mleBean.getMLE_Manifests()){ + parameters.clear(); + if (mleManifest.getName() != null && !mleManifest.getName().trim().equals("")){ + parameters.put(mleManifest.getName(), 10); + } else { + isValidKey = false; + } + + if (mleManifest.getValue() != null && !mleManifest.getValue().trim().equals("")){ + parameters.put(mleManifest.getValue(), 100); + } else { + isValidKey = false; + } + + if (!HisUtil.validParas(parameters) || !isValidKey){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Update MLE entry failed, please check the length for each parameters" + + " and remove all of the unwanted characters belonged to [# & + : \" \']"); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + + pcrDao.deletePcrByMleID(mle.getMLEID()); + PcrWhiteList pcr = new PcrWhiteList(); + pcr.setMle(mle); + pcr.setPcrName(mleManifest.getName()); + pcr.setPcrDigest(mleManifest.getValue()); + pcrList.add(pcr); + } + pcrDao.addPcrList(pcrList); + } + } else { + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Update MLE entry failed, pleae check the type of MLE"); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + + return Response.status(status).header("Location", b.build()).type(MediaType.TEXT_PLAIN).entity("True") + .build(); + }catch (Exception e){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Update MLE entry failed." + "Exception:" + e.getMessage()); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + } + + @DELETE + @Produces("application/json") + public Response delMLEEntry(@QueryParam("mleName") String name, @QueryParam("mleVersion") String version, @QueryParam("osName") String osName, + @QueryParam("osVersion") String osVersion,@QueryParam("oemName") String oemName,@Context UriInfo uriInfo){ + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(MLEResource.class); + Response.Status status = Response.Status.OK; + MLEDAO mleDao = new MLEDAO(); + PcrWhiteListDAO pcrDao = new PcrWhiteListDAO(); + boolean isValidKey = true; + + try{ + HashMap parameters = new HashMap(); + if (name != null && version != null){ + parameters.put(name, 50); + parameters.put(version, 100); + } else { + isValidKey = false; + } + + if (!isValidKey || name.length() < 1 || version.length() < 1 || !HisUtil.validParas(parameters)){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Delete MLE entry failed, please check the length for each parameters" + + " and remove all of the unwanted characters belonged to [# & + : \" \']"); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + + if (!mleDao.isMLEExisted(name,version,osName, osVersion,oemName)){ + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(1007); + fault.setError_message("WLM Service Error - MLE not found in attestation data to delete"); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + + MLE mle= mleDao.DeleteMLEEntry(name, version); + System.out.println("##Check mle id:" + mle.getMLEID()); + pcrDao.deletePcrByMleID(mle.getMLEID()); + return Response.status(status).header("Location", b.build()).type(MediaType.TEXT_PLAIN).entity("True").build(); + }catch (Exception e){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Delete MLE entry failed." + "Exception:" + e.getMessage() + " Possible solution: The specified MLE has a reference with HOST, solve this and try again."); + return Response.status(status).entity(fault).build(); + + } + } + + @GET + @Produces("application/json") + public List searchMLE(@QueryParam("searchCriteria") String criteria){ + MLEDAO mleDao = new MLEDAO(); + List mleList = new ArrayList(); + List mleBeanList = new ArrayList(); + MLEBean mleBean = new MLEBean(); + ArrayList pcrList = new ArrayList(); + PcrWhiteListDAO pcrDao = new PcrWhiteListDAO(); + MLE mle = null; + pcrList = new ArrayList(); + try { + HibernateUtilHis.getSession(); + mleList = mleDao.getAllMLEEntries(); + for (int i=0; i tempList = pcrDao.queryPcrByMLEid(mleList.get(i).getMLEID().longValue()); + if (tempList != null){ + pcrList = new ArrayList(tempList); + } + else{ + pcrList = new ArrayList(); + } + List mleManifest = new ArrayList(); + for (int j=0; j pcrList = new ArrayList(); + MLEDAO mleDao = new MLEDAO(); + PcrWhiteListDAO pcrDao = new PcrWhiteListDAO(); + MLE mle = null; + OEM oem = null; + OS os = null; + MLEBean mleBean = new MLEBean(); + pcrList = new ArrayList(); + try{ + HibernateUtilHis.getSession(); + if (oemName != null){ + mle = mleDao.queryMLEidByNameAndVersionAndOEMid(name, version, oemName); + //query oem + oem = mleDao.queryOEMByNameAndVersionAndOEMid(name, version, oemName); + //oem = mle.getOem(); + + } else if (osName != null && osVersion != null){ + mle = mleDao.queryMLEidByNameAndVersionAndOSid(name, version, osName, osVersion); + //query os + os = mleDao.queryOSByNameAndVersionAndOSid(name, version, osName, osVersion); + //os = mle.getOs(); + } else { + System.out.println("please check the input parameters and provide complete information"); + return mleBean; + } + + if (mle != null){ + mleBean.setName(mle.getName()); + mleBean.setVersion(mle.getVersion()); + mleBean.setDescription(mle.getDescription()); + mleBean.setAttestation_Type(mle.getAttestation_Type()); + if (os != null){ + mleBean.setOsName(os.getName()); + mleBean.setOsVersion(os.getVersion()); + } else { + mleBean.setOsName("null"); + mleBean.setOsVersion("null"); + } + + if (oem != null){ + mleBean.setOemName(oem.getName()); + } else { + mleBean.setOemName("null"); + } + + //Get pcr white list; + List tempList = pcrDao.queryPcrByMLEid(mle.getMLEID().longValue()); + if (tempList != null){ + pcrList = new ArrayList(tempList); + } + + List mleManifest = new ArrayList(); + for (int i=0; i0 ){ + mleBean.setMLE_Manifests(mleManifest); + } else{ + mleBean.setMLE_Manifests(null); + } + + mleBean.setMLE_Type(mle.getMLE_Type()); + } + }catch (Exception e){ + System.out.println("Encountered an exception with detail message: " + e.getMessage()); + }finally{ + HibernateUtilHis.closeSession(); + } + return mleBean; + } + +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/resource/OEMResource.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/resource/OEMResource.java new file mode 100644 index 0000000..601b00b --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/resource/OEMResource.java @@ -0,0 +1,246 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.manifest.resource; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; + +import gov.niarl.hisAppraiser.util.HisUtil; + +import com.intel.openAttestation.manifest.bean.OpenAttestationResponseFault; +import com.intel.openAttestation.manifest.hibernate.dao.OEMDAO; +import com.intel.openAttestation.manifest.hibernate.domain.OEM; +import com.intel.openAttestation.manifest.resource.OEMResource; + +/** + * RESTful web service interface to work with OEM DB. + * @author xmei1 + * + */ + +@Path("resources/oem") +public class OEMResource { + + + @POST + @Consumes("application/json") + @Produces("application/json") + public Response addOEM(@Context UriInfo uriInfo, OEM oem, + @Context javax.servlet.http.HttpServletRequest request){ + System.out.println("Check if the OEM Name exists:" + oem.getName()); + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(OEMResource.class); + Response.Status status = Response.Status.OK; + boolean isValidKey = true; + try{ + OEMDAO dao = new OEMDAO(); + + HashMap parameters = new HashMap(); + if (oem.getName()!=null){ + parameters.put(oem.getName(), 50); + } else { + isValidKey = false; + } + + if (oem.getDescription()!=null){ + parameters.put(oem.getDescription(), 100); + } + + if (!isValidKey || oem.getName().length() < 1 || !HisUtil.validParas(parameters)){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Add OEM entry failed, please check the length for each parameters" + + " and remove all of the unwanted characters belonged to [# & + : \" \']"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + System.out.println("Check if the OEM Name exists:" + oem.getName()); + if (dao.isOEMExisted(oem.getName())){ + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(1006); + fault.setError_message("Data Error - OEM " + oem.getName()+" already exists in the database"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + dao.addOEMEntry(oem); + return Response.status(status).header("Location", b.build()).type(MediaType.TEXT_PLAIN).entity("True") + .build(); + }catch (Exception e){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Add OEM entry failed." + "Exception:" + e.getMessage()); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + } + + @PUT + @Consumes("application/json") + @Produces("application/json") + public Response editOEM(@Context UriInfo uriInfo, OEM oem, + @Context javax.servlet.http.HttpServletRequest request){ + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(OEMResource.class); + Response.Status status = Response.Status.OK; + boolean isValidKey = true; + try{ + OEMDAO dao = new OEMDAO(); + System.out.println("Check if the OEM Name exists:" + oem.getName()); + + HashMap parameters = new HashMap(); + if (oem.getDescription()!=null){ + parameters.put(oem.getDescription(), 100); + } + + if (oem.getName()!=null){ + parameters.put(oem.getName(), 100); + } else { + isValidKey = false; + } + if (!isValidKey || oem.getName().length() < 1 || !HisUtil.validParas(parameters)){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Edit OEM entry failed, please check the length for each parameters" + + " and remove all of the unwanted characters belonged to [# & + : \" \']"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + if (!dao.isOEMExisted(oem.getName())){ + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(1006); + fault.setError_message("Data Error - OEM " + oem.getName()+" don't exists in the database"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + dao.editOEMEntry(oem); + return Response.status(status).header("Location", b.build()).type(MediaType.TEXT_PLAIN).entity("True") + .build(); + }catch (Exception e){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Edit OEM entry failed." + "Exception:" + e.getMessage()); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + } + + @DELETE + @Produces("application/json") + public Response deloemEntry(@QueryParam("Name") String Name, @Context UriInfo uriInfo){ + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(OEMResource.class); + Response.Status status = Response.Status.OK; + boolean isValidKey = true; + + try{ + OEMDAO dao = new OEMDAO(); + + HashMap parameters = new HashMap(); + if (Name !=null){ + parameters.put(Name, 50); + } else { + isValidKey = false; + } + + if (!isValidKey || Name.length() < 1 || !HisUtil.validParas(parameters)){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Delte OEM entry failed, please check the length for each parameters" + + " and remove all of the unwanted characters belonged to [# & + : \" \']"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + System.out.println("Check if the OEM Name exists:" + Name); + + //check if the OEM has the reference with MLE + if (dao.isRefMle(Name)) { + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(2012); + fault.setError_message("Data Error - OEM " + Name +" reference with MLE, delete failed"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + if (dao.isOEMExisted(Name)){ + dao.DeleteOEMEntry(Name); + return Response.status(status).type(MediaType.TEXT_PLAIN).entity("True") + .build(); + } + + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_1006); + fault.setError_message("Data Error - OEM " + Name +" does not exist in the database"); + return Response.status(status).entity(fault) + .build(); + + }catch (Exception e){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Delete OEM entry failed." + "Exception:" + e.getMessage()); + return Response.status(status).entity(fault) + .build(); + + } + } + + @GET + @Produces("application/json") + public List getOEMEntry(@QueryParam("index") String index, + @QueryParam("CompName") String name,@QueryParam("CompDesc") String desc){ + OEMDAO dao = new OEMDAO(); + List emptyList = new ArrayList(); + if (index == null && name == null && desc == null) + return dao.getAllOEMEntries(); + else if ( index != null) + //@TODO + return emptyList; + else if (name != null && desc == null) + //@TODO + return emptyList; + else if (name == null && desc != null) + //@TODO + return emptyList; + else + //@TODO + return emptyList; + } + +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/resource/OSResource.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/resource/OSResource.java new file mode 100644 index 0000000..92fe1d8 --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/resource/OSResource.java @@ -0,0 +1,262 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.manifest.resource; + +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; + +import gov.niarl.hisAppraiser.util.HisUtil; + +import com.intel.openAttestation.manifest.bean.OpenAttestationResponseFault; +import com.intel.openAttestation.manifest.hibernate.dao.OSDAO; +import com.intel.openAttestation.manifest.hibernate.domain.OS; +import com.intel.openAttestation.manifest.resource.OSResource; + +/** + * RESTful web service interface to work with OEM DB. + * @author xmei1 + * + */ + +@Path("resources/os") +public class OSResource { + + @POST + @Consumes("application/json") + @Produces("application/json") + public Response addOS(@Context UriInfo uriInfo, OS os, @Context javax.servlet.http.HttpServletRequest request){ + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(OSResource.class); + Response.Status status = Response.Status.OK; + boolean isValidKey = true; + try{ + OSDAO dao = new OSDAO(); + System.out.println("Check if the OS Name exists:" + os.getName()); + + HashMap parameters = new HashMap(); + if (os.getName() != null){ + parameters.put(os.getName(), 50); + } else { + isValidKey = false; + } + if (os.getVersion() != null){ + parameters.put(os.getVersion(), 50); + } else { + isValidKey = false; + } + if (os.getDescription() != null){ + parameters.put(os.getDescription(), 100); + } + + if ( !isValidKey || os.getName().length() < 1 || os.getVersion().length() < 1 || !HisUtil.validParas(parameters)){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Add OS entry failed, please check the length for each parameters" + + " and remove all of the unwanted characters belonged to [# & + : \" \']"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + + if (dao.isOSExisted(os.getName(), os.getVersion())){ + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(1006); + fault.setError_message("Data Error - OS " + os.getName()+ os.getVersion() + " already exists in the database"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + dao.addOSEntry(os); + return Response.status(status).header("Location", b.build()).type(MediaType.TEXT_PLAIN).entity("True") + .build(); + }catch (Exception e){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Add OS entry failed." + "Exception:" + e.getMessage()); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + } + + @PUT + @Consumes("application/json") + @Produces("application/json") + public Response editOS(@Context UriInfo uriInfo, OS os, @Context javax.servlet.http.HttpServletRequest request){ + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(OSResource.class); + Response.Status status = Response.Status.OK; + boolean isValidKey = true; + try{ + OSDAO dao = new OSDAO(); + + HashMap parameters = new HashMap(); + if (os.getName()!=null){ + parameters.put(os.getName(), 50); + } else { + isValidKey = false; + } + if (os.getVersion()!=null){ + parameters.put(os.getVersion(), 50); + } else { + isValidKey = false; + } + if (os.getDescription()!=null){ + parameters.put(os.getDescription(), 100); + } + + if (!isValidKey || os.getName().length() < 1 || os.getVersion().length() < 1 || !HisUtil.validParas(parameters)){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Edit OS entry failed, please check the length for each parameters" + + " and remove all of the unwanted characters belonged to [# & + : \" \']"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + System.out.println("Check if the OEM Name exists:" + os.getName()); + if (!dao.isOSExisted(os.getName(), os.getVersion())){ + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(1006); + fault.setError_message("Data Error - OS " + os.getName() + os.getVersion() + " don't exists in the database"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + + + dao.editOSEntry(os); + return Response.status(status).header("Location", b.build()).type(MediaType.TEXT_PLAIN).entity("True") + .build(); + }catch (Exception e){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Add OS entry failed." + "Exception:" + e.getMessage()); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + } + + @DELETE + @Produces("application/json") + public Response delOS(@QueryParam("Name") String Name, @QueryParam("Version") String Version,@Context UriInfo uriInfo){ + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(OSResource.class); + Response.Status status = Response.Status.OK; + boolean isValidKey = true; + + try{ + OSDAO dao = new OSDAO(); + + HashMap parameters = new HashMap(); + if (Name != null){ + parameters.put(Name, 50); + } else { + isValidKey = false; + } + + if (Version != null){ + parameters.put(Version, 50); + } else { + isValidKey = false; + } + + if (!isValidKey || Name.length() < 1 || Version.length() < 1 || !HisUtil.validParas(parameters)){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Delete OS entry failed, please check the length for each parameters" + + " and remove all of the unwanted characters belonged to [# & + : \" \']"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + System.out.println("Check if the OS Name exists:" + Name + " " + Version); + + if (dao.isRefMle(Name, Version)) { + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(2012); + fault.setError_message("Data Error - OS " + Name + " & Version & " + Version + " reference with MLE, delete failed"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + + if (dao.isOSExisted(Name, Version)){ + dao.deleteOSEntry(Name, Version); + return Response.status(status).type(MediaType.TEXT_PLAIN).entity("True") + .build(); + } + + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_1006); + fault.setError_message("Data Error - OS " + Name + Version + " does not exist in the database"); + return Response.status(status).entity(fault) + .build(); + + }catch (Exception e){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Delete OS entry failed." + "Exception:" + e.getMessage()); + return Response.status(status).entity(fault) + .build(); + + } + } + + @GET + @Produces("application/json") + public List getOSEntry(@QueryParam("index") String index, + @QueryParam("CompName") String name,@QueryParam("CompDesc") String desc){ + OSDAO dao = new OSDAO(); + List emptyList = new ArrayList(); + if (index == null && name == null && desc == null) + return dao.getAllOSEntries(); + else if ( index != null) + //@TODO + return emptyList; + else if (name != null && desc == null) + //@TODO + return emptyList; + else if (name == null && desc != null) + //@TODO + return emptyList; + else + //@TODO + return emptyList; + } + +} diff --git a/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/resource/PcrWhiteListResource.java b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/resource/PcrWhiteListResource.java new file mode 100644 index 0000000..5d4dd4a --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/com/intel/openAttestation/manifest/resource/PcrWhiteListResource.java @@ -0,0 +1,263 @@ +/* +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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 com.intel.openAttestation.manifest.resource; + +import java.util.HashMap; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriBuilder; +import javax.ws.rs.core.UriInfo; + +import gov.niarl.hisAppraiser.util.HisUtil; + +import com.intel.openAttestation.manifest.bean.OpenAttestationResponseFault; +import com.intel.openAttestation.manifest.bean.PcrWhiteListBean; +import com.intel.openAttestation.manifest.hibernate.dao.*; +import com.intel.openAttestation.manifest.hibernate.domain.PcrWhiteList; +import com.intel.openAttestation.manifest.resource.PcrWhiteListResource; +import com.intel.openAttestation.manifest.hibernate.domain.MLE; + +/** + * RESTful web service interface to work with OEM DB. + * @author xmei1 + * + */ + +@Path("resources/mles/whitelist/pcr") +public class PcrWhiteListResource { + + @POST + @Consumes("application/json") + @Produces("application/json") + public Response addPcrWhiteList(@Context UriInfo uriInfo, PcrWhiteListBean pcrbean, + @Context javax.servlet.http.HttpServletRequest request){ + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(PcrWhiteListResource.class); + Response.Status status = Response.Status.OK; + boolean isValidKey = true; + try{ + PcrWhiteListDAO dao = new PcrWhiteListDAO(); + PcrWhiteList pcr = new PcrWhiteList(); + MLEDAO daoMLE = new MLEDAO(); + MLE mle = null; + HashMap parameters = new HashMap(); + if (pcrbean.getPcrName()!=null){ + parameters.put(pcrbean.getPcrName(), 10); + } else { + isValidKey = false; + } + + if (pcrbean.getPcrDigest()!=null){ + parameters.put(pcrbean.getPcrDigest(), 100); + } + + if (! isValidKey || pcrbean.getPcrName().length() < 1 || !HisUtil.validParas(parameters) || pcrbean.getPcrDigest() == null || pcrbean.getPcrDigest().length() == 0 ){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + if (pcrbean.getPcrDigest() == null || pcrbean.getPcrDigest().length() == 0){ + fault.setError_message("Valid PCR disgest required"); + } else { + fault.setError_message("Add PCR entry failed, please check the length for each parameters" + + " and remove all of the unwanted characters belonged to [# & + : \" \']"); + } + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + + if(pcrbean.getPcrName() != null && pcrbean.getPcrDigest() != null && pcrbean.getMLEName() != null && pcrbean.getMLEVersion() != null && pcrbean.getOEMName() != null) + { + mle = daoMLE.queryMLEidByNameAndVersionAndOEMid(pcrbean.getMLEName(), pcrbean.getMLEVersion(), pcrbean.getOEMName()); + } + else if(pcrbean.getPcrName() != null && pcrbean.getPcrDigest() != null && pcrbean.getMLEName() != null && pcrbean.getMLEVersion() != null && pcrbean.getOSName() != null && pcrbean.getOSVersion() != null) + { + mle = daoMLE.queryMLEidByNameAndVersionAndOSid(pcrbean.getMLEName(), pcrbean.getMLEVersion(), pcrbean.getOSName(), pcrbean.getOSVersion()); + } + if(mle == null || dao.isPcrExisted(pcrbean.getPcrName(), mle.getMLEID())) + { + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(1006); + if(mle == null) + fault.setError_message("Data Error - MLE " + pcrbean.getMLEName() +" does not exist in the database"); + else + fault.setError_message("Data Error - PCR " + pcrbean.getPcrName() +" exists in the database"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + + } + pcr.setPcrName(pcrbean.getPcrName()); + pcr.setPcrDigest(pcrbean.getPcrDigest()); + pcr.setMle(mle); + dao.addPcrEntry(pcr); + return Response.status(status).header("Location", b.build()).type(MediaType.TEXT_PLAIN).entity("True") + .build(); + }catch (Exception e){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Add PCR entry failed." + "Exception:" + e.getMessage()); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + } + + @PUT + @Consumes("application/json") + @Produces("application/json") + public Response editPcrWhiteList(@Context UriInfo uriInfo, PcrWhiteListBean pcrbean, + @Context javax.servlet.http.HttpServletRequest request){ + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(PcrWhiteListResource.class); + Response.Status status = Response.Status.OK; + boolean isValidKey = true; + try{ + PcrWhiteListDAO dao = new PcrWhiteListDAO(); + PcrWhiteList pcr = null; + + HashMap parameters = new HashMap(); + + if (pcrbean.getPcrName()!=null){ + parameters.put(pcrbean.getPcrName(), 10); + } else { + isValidKey = false; + } + + if (pcrbean.getPcrDigest()!=null){ + parameters.put(pcrbean.getPcrDigest(), 100); + } + + if (!isValidKey || pcrbean.getPcrName().length() < 1 || !HisUtil.validParas(parameters) || pcrbean.getPcrDigest() == null || pcrbean.getPcrDigest().length() < 1){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Edit PCR entry failed, please check the length for each parameters" + + " and remove all of the unwanted characters belonged to [# & + : \" \']"); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + } + + if(pcrbean.getPcrName() != null && pcrbean.getPcrDigest() != null && pcrbean.getMLEName() != null && pcrbean.getMLEVersion() != null && pcrbean.getOEMName() != null) + { + pcr = dao.queryPcrByOEMid(pcrbean.getMLEName(), pcrbean.getMLEVersion(), pcrbean.getOEMName(), pcrbean.getPcrName()); + } + else if(pcrbean.getPcrName() != null && pcrbean.getPcrDigest() != null && pcrbean.getMLEName() != null && pcrbean.getMLEVersion() != null && pcrbean.getOSName() != null && pcrbean.getOSVersion() != null) + { + pcr = dao.queryPcrByOSid(pcrbean.getMLEName(), pcrbean.getMLEVersion(), pcrbean.getOSName(), pcrbean.getOSVersion(), pcrbean.getPcrName()); + } + if(pcr == null) + { + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(1006); + fault.setError_message("Data Error - PCR combined with the specified MLE and related information does not exist in the database"); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + + } + pcr.setPcrDigest(pcrbean.getPcrDigest()); + dao.editPcrEntry(pcr); + return Response.status(status).header("Location", b.build()).type(MediaType.TEXT_PLAIN).entity("True") + .build(); + }catch (Exception e){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Update PCR entry failed." + "Exception:" + e.getMessage()); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + } + + @DELETE + @Produces("application/json") + public Response delPcrWhiteList(@QueryParam("pcrName") String pcrName, @QueryParam("mleName") String mleName, + @QueryParam("mleVersion") String mleVersion, @QueryParam("oemName") String oemName, + @QueryParam("osName") String osName, @QueryParam("osVersion") String osVersion, @Context UriInfo uriInfo){ + UriBuilder b = uriInfo.getBaseUriBuilder(); + b = b.path(PcrWhiteListResource.class); + Response.Status status = Response.Status.OK; + boolean isValidKey = true; + + try{ + PcrWhiteListDAO dao = new PcrWhiteListDAO(); + PcrWhiteList pcr = null; + + HashMap parameters = new HashMap(); + if (pcrName!=null){ + parameters.put(pcrName, 10); + } else { + isValidKey = false; + } + + if (mleName!=null){ + parameters.put(mleName, 50); + } + + if(mleVersion!=null){ + parameters.put(mleVersion, 100); + } + + if(oemName !=null){ + parameters.put(oemName, 50); + } + + if (! isValidKey || pcrName.length() < 1 || !HisUtil.validParas(parameters)){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Delete PCR entry failed, please check the length for each parameters" + + " and remove all of the unwanted characters belonged to [# & + : \" \']"); + return Response.status(status).header("Location", b.build()).entity(fault) + .build(); + } + + if(pcrName != null && mleName != null && mleVersion != null && oemName != null) + { + pcr = dao.queryPcrByOEMid(mleName, mleVersion, oemName, pcrName); + } + else if(pcrName != null && mleName != null && mleVersion != null && osName != null && osVersion != null) + { + pcr = dao.queryPcrByOSid(mleName, mleVersion, osName, osVersion, pcrName); + } + + if(pcr == null) + { + status = Response.Status.BAD_REQUEST; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault(1006); + fault.setError_message("Data Error - PCR combined with the specified MLE and related information does not exist in the database"); + return Response.status(status).header("Location", b.build()).entity(fault).build(); + + } + + dao.deletePcrEntry(pcrName, pcr.getMle().getMLEID()); + return Response.status(status).header("Location", b.build()).type(MediaType.TEXT_PLAIN).entity("True").build(); + }catch (Exception e){ + status = Response.Status.INTERNAL_SERVER_ERROR; + OpenAttestationResponseFault fault = new OpenAttestationResponseFault( + OpenAttestationResponseFault.FaultCode.FAULT_500); + fault.setError_message("Delete PCR entry failed." + "Exception:" + e.getMessage()); + return Response.status(status).entity(fault).build(); + + } + } + + +} diff --git a/OpenAttestation/Source/WLMService/src/hibernateOat.cfg.xml b/OpenAttestation/Source/WLMService/src/hibernateOat.cfg.xml new file mode 100644 index 0000000..856c9bc --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/hibernateOat.cfg.xml @@ -0,0 +1,32 @@ + + + + + + + org.hibernate.dialect.MySQLDialect + java:comp/env/jdbc/oat + + thread + org.hibernate.hql.classic.ClassicQueryTranslatorFactory + + org.hibernate.cache.NoCacheProvider + false + true + + + false + + + + + + + + + + + + diff --git a/OpenAttestation/Source/WLMService/src/log4j.properties b/OpenAttestation/Source/WLMService/src/log4j.properties new file mode 100644 index 0000000..b94df8a --- /dev/null +++ b/OpenAttestation/Source/WLMService/src/log4j.properties @@ -0,0 +1,31 @@ +# Set root category priority to INFO and its only appender to CONSOLE. +log4j.rootCategory=INFO, CONSOLE +#log4j.rootCategory=INFO, CONSOLE, LOGFILE + +# Set the enterprise logger category to FATAL and its only appender to CONSOLE. +log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE + +# CONSOLE is set to be a ConsoleAppender using a PatternLayout. +log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.CONSOLE.Threshold=INFO +log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.CONSOLE.layout.ConversionPattern=- %m%n + +# LOGFILE is set to be a File appender using a PatternLayout. +log4j.appender.LOGFILE=org.apache.log4j.FileAppender +log4j.appender.LOGFILE.File=axis.log +log4j.appender.LOGFILE.Append=true +log4j.appender.LOGFILE.Threshold=INFO +log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout +log4j.appender.LOGFILE.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n + +# Set the HisAppraiser logger category +log4j.logger.gov.niarl.hisAppraiser.hibernate=INFO, HisAppraiser_CONSOLE +log4j.logger.gov.niarl.hisAppraiser=ALL, HisAppraiser_CONSOLE +log4j.logger.gov.niarl.his.xsd=ALL, HisAppraiser_CONSOLE + +# CONSOLE is set to be a ConsoleAppender using a PatternLayout. +log4j.appender.HisAppraiser_CONSOLE=org.apache.log4j.ConsoleAppender +log4j.appender.HisAppraiser_CONSOLE.Threshold=ALL +log4j.appender.HisAppraiser_CONSOLE.layout=org.apache.log4j.PatternLayout +log4j.appender.HisAppraiser_CONSOLE.layout.ConversionPattern=%d{dd/MMM/yyyy HH:mm:ss} %p - %m%n \ No newline at end of file diff --git a/OpenAttestation/Source/build.sh b/OpenAttestation/Source/build.sh new file mode 100644 index 0000000..005fb0b --- /dev/null +++ b/OpenAttestation/Source/build.sh @@ -0,0 +1,101 @@ +#!/bin/sh + +#download projects from : http://his.sh.intel.com/hg/OAT/file/d253082ba0d6. put OAT to the workspace +#this script works at root directory of OAT. Just type sh build.sh to run it in a terminal console. +#It builds 6 projects: +# 1.TPMModule 2.HisClient 3.HisPrivacyCAWebServices2 +# 4. HisWebServices 5.PrivacyCA 6.HisAppraiser + +#1. build TPMModule +#type make after navigating to the folder in which the NIARL_TPM_Module +make -C ./TPMModule/plain/linux/ +#chmod +x NIARL_TPM_Module + +#2. build HisAppraiser +ant -file ./HisAppraiser/xml/Integrity_Report_Manifest_v1_0/build.xml +ant -file ./HisAppraiser/xml/PCR_Difference/build.xml +ant -file ./HisAppraiser/build.xml +cp -rf ./HisAppraiser/HisAppraiser.jar ./AttestationService/WebContent/WEB-INF/lib/ +cp -rf ./HisAppraiser/HisAppraiser.jar ./HisWebServices/clientlib/ +cp -rf ./HisAppraiser/HisAppraiser.jar ./HisWebServices/WEB-INF/lib/HisAppraiser.jar +cp -rf ./HisAppraiser/HisAppraiser.jar ./WLMService/WebContent/WEB-INF/lib/ + +#3. build HisWebServices +#cp -rf ./HisAppraiser/HisAppraiser.jar ./HisWebServices/WEB-INF/lib/ +ant -file ./HisWebServices/build.xml server +#cp ./HisWebServices/HisWebServices.war $1/webapps/ +#sh $1/bin/shutdown.sh +#sh $1/bin/startup.sh +## This for loop makes the rpm wait until the .war file has unpacked before attempting to access the files that will be created +#for((i = 1; i < 60; i++)) +#do +# +# rm -f ./warLog +# +# if test -e $1/webapps/HisWebServices;then +# echo the HisWebServices was unpacked! +# rm -f ./warLog +# sleep 5 +# break +# fi +# +# sleep 1 +# +# echo If this file is present after install then unpacking the HisWebServices.war file timed-out >> warLog +# +#done + +ant -file ./HisWebServices/build.xml client +cp -rf ./HisWebServices/clientlib/HisWebServices-client.jar ./PrivacyCA/lib/ +cp -rf ./HisWebServices/clientlib/HisWebServices-client.jar ./HisClient/lib/ +cp -rf ./HisWebServices/clientlib/HisWebServices-client.jar ./HisPrivacyCAWebServices2/ClientFiles/lib/ +cp -rf ./HisWebServices/clientlib/HisWebServices-client.jar ./HisPrivacyCAWebServices2/WEB-INF/lib/ + +#4build TSSCoreService +if test -e ./TSSCoreService;then + ant -file ./TSSCoreService/build.xml + cp -rf ./TSSCoreService/TSSCoreService.jar ./PrivacyCA/lib/ + cp -rf ./TSSCoreService/TSSCoreService.jar ./HisPrivacyCAWebServices2/ClientFiles/lib/ +fi + +#5.build HisPrivacyCAWebServices2 +#just run build.xml +#before run build.xml, you need install ant by typing yum install ant +for f in HisSetup.java TpmIdentityRequest.java TpmSymCaAttestation.java idResponse.java TpmKeyParams.java TpmSymmetricKey.java PrivacyCaException.java TpmKeySubParams.java TpmSymmetricKeyParams.java TpmAsymCaContents.java TpmPubKey.java TpmUtils.java TpmIdentityProof.java TpmRsaKeyParams.java +do + ln -s -f ../../../../../../PrivacyCA/src/gov/niarl/his/privacyca/$f HisPrivacyCAWebServices2/src/gov/niarl/his/privacyca/ +done + +ant -file ./HisPrivacyCAWebServices2/build.xml server +#cp ./HisPrivacyCAWebServices2/HisPrivacyCAWebServices2.war $1/webapps/ +##This is for loop makes the rpm wait until the .war file has unpacked before attempting to access the files that will be created +#for((i = 1; i < 60; i++)) +#do +# +# if test -e $1/webapps/HisPrivacyCAWebServices2;then +# echo the Privacy CA was unpacked! +# rm -f ./warLog +# sleep 5 +# break +# fi +# +# sleep 1 +# +# echo If this file is present after install then unpacking the Privacy CA war file timed-out >> warLog +# +#done +ant -file ./HisPrivacyCAWebServices2/build.xml client +cp -rf ./HisPrivacyCAWebServices2/clientlib/HisPrivacyCAWebServices2-client.jar ./HisPrivacyCAWebServices2/ClientFiles/lib/ +cp -rf ./HisPrivacyCAWebServices2/clientlib/HisPrivacyCAWebServices2-client.jar ./PrivacyCA/lib/ +#sh $1/bin/shutdown.sh + +#6. build PrivacyCA +ant -file ./PrivacyCA/build.xml +cp -rf ./PrivacyCA/PrivacyCA.jar ./HisPrivacyCAWebServices2/ClientFiles/lib/ + + +#6. build HisClient +mkdir ./HisClient/jar +ant -file ./HisClient/xml/Integrity_Report_Manifest_v1_0/build.xml +ant -file ./HisClient/build.xml +#rm -rf $1/webapps/* diff --git a/OpenAttestation/Source/distribute_jar_packages.sh b/OpenAttestation/Source/distribute_jar_packages.sh new file mode 100644 index 0000000..b15552c --- /dev/null +++ b/OpenAttestation/Source/distribute_jar_packages.sh @@ -0,0 +1,922 @@ +#!/bin/bash +# distribute Jar package + +OAT_SOURCE=../Source +JAR_SOURCE=../JAR_SOURCE + +ShowLogOK() +{ + echo -e "$1: --------------\033[32;49;5;1m [ OK ]\033[0m" +} +ShowLogFaild() +{ +echo -e "$1:------------\033[31;49;5;1m [ Failed ]\033[0m" +exit 0 +} + + +mkdir -p $OAT_SOURCE/HisClient/lib +mkdir -p $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib +mkdir -p $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib +mkdir -p $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib +mkdir -p $OAT_SOURCE/HisAppraiser/lib +mkdir -p $OAT_SOURCE/PrivacyCA/lib +mkdir -p $OAT_SOURCE/HisWebServices/clientlib +mkdir -p $OAT_SOURCE/HisWebServices/WEB-INF/lib +mkdir -p $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/jars-compile-only/ +mkdir -p $OAT_SOURCE/HisWebServices/WEB-INF/jars-compile-only/ +mkdir -p $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib +mkdir -p $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib + +if test -e $JAR_SOURCE/activation.jar;then + cp -f $JAR_SOURCE/activation.jar $OAT_SOURCE/HisClient/lib/activation.jar + cp -f $JAR_SOURCE/activation.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/activation.jar + cp -f $JAR_SOURCE/activation.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/activation.jar + cp -f $JAR_SOURCE/activation.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/activation.jar + cp -f $JAR_SOURCE/activation.jar $OAT_SOURCE/HisAppraiser/lib/activation.jar + cp -f $JAR_SOURCE/activation.jar $OAT_SOURCE/PrivacyCA/lib/activation.jar + cp -f $JAR_SOURCE/activation.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/activation.jar + cp -f $JAR_SOURCE/activation.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/activation.jar + cp -f $JAR_SOURCE/activation.jar $OAT_SOURCE/HisWebServices/clientlib/activation.jar + cp -f $JAR_SOURCE/activation.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/activation.jar + if test -d $OAT_SOURCE/TSSCoreService;then + mkdir $OAT_SOURCE/TSSCoreService/lib + cp -f $JAR_SOURCE/activation.jar $OAT_SOURCE/TSSCoreService/lib/activation.jar + fi +else + ShowLogFaild "$JAR_SOURCE/activation.jar" +fi + + +if test -e $JAR_SOURCE/asm.jar;then + cp -f $JAR_SOURCE/asm.jar $OAT_SOURCE/HisAppraiser/lib/asm.jar + cp -f $JAR_SOURCE/asm.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/asm.jar + cp -f $JAR_SOURCE/asm.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/asm.jar + cp -f $JAR_SOURCE/asm.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/asm.jar + if test -d $OAT_SOURCE/TSSCoreService;then + cp -f $JAR_SOURCE/asm.jar $OAT_SOURCE/TSSCoreService/lib/asm.jar + fi +else + ShowLogFaild "$JAR_SOURCE/asm.jar" +fi + + +if test -e $JAR_SOURCE/asm-3.1.jar;then + cp -f $JAR_SOURCE/asm-3.1.jar $OAT_SOURCE/HisAppraiser/lib/asm-3.1.jar + cp -f $JAR_SOURCE/asm-3.1.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/asm-3.1.jar + cp -f $JAR_SOURCE/asm-3.1.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/asm-3.1.jar +else + ShowLogFaild "$JAR_SOURCE/asm-3.1.jar" +fi + + +if test -e $JAR_SOURCE/bcprov-jdk15-141.jar;then + cp -f $JAR_SOURCE/bcprov-jdk15-141.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/bcprov-jdk15-141.jar + cp -f $JAR_SOURCE/bcprov-jdk15-141.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/bcprov-jdk15-141.jar + cp -f $JAR_SOURCE/bcprov-jdk15-141.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/bcprov-jdk15-141.jar + cp -f $JAR_SOURCE/bcprov-jdk15-141.jar $OAT_SOURCE/HisAppraiser/lib/bcprov-jdk15-141.jar + cp -f $JAR_SOURCE/bcprov-jdk15-141.jar $OAT_SOURCE/PrivacyCA/lib/bcprov-jdk15-141.jar + cp -f $JAR_SOURCE/bcprov-jdk15-141.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/bcprov-jdk15-141.jar + cp -f $JAR_SOURCE/bcprov-jdk15-141.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/bcprov-jdk15-141.jar + cp -f $JAR_SOURCE/bcprov-jdk15-141.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/bcprov-jdk15-141.jar +else + ShowLogFaild "$JAR_SOURCE/bcprov-jdk15-141.jar" +fi + + +if test -e $JAR_SOURCE/c3p0-0.9.0.jar;then + cp -f $JAR_SOURCE/c3p0-0.9.0.jar $OAT_SOURCE/HisAppraiser/lib/c3p0-0.9.0.jar + cp -f $JAR_SOURCE/c3p0-0.9.0.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/c3p0-0.9.0.jar + cp -f $JAR_SOURCE/c3p0-0.9.0.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/c3p0-0.9.0.jar + cp -f $JAR_SOURCE/c3p0-0.9.0.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/c3p0-0.9.0.jar +else + ShowLogFaild "$JAR_SOURCE/c3p0-0.9.0.jar" +fi + + +if test -e $JAR_SOURCE/cglib-2.1.3.jar;then + cp -f $JAR_SOURCE/cglib-2.1.3.jar $OAT_SOURCE/HisAppraiser/lib/cglib-2.1.3.jar + cp -f $JAR_SOURCE/cglib-2.1.3.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/cglib-2.1.3.jar + if test -d $OAT_SOURCE/TSSCoreService;then + cp -f $JAR_SOURCE/cglib-2.1.3.jar $OAT_SOURCE/TSSCoreService/lib/cglib-2.1.3.jar + fi + +else + ShowLogFaild "$JAR_SOURCE/cglib-2.1.3.jar" +fi + + +if test -e $JAR_SOURCE/cglib-2.2.jar;then + cp -f $JAR_SOURCE/cglib-2.2.jar $OAT_SOURCE/HisAppraiser/lib/cglib-2.2.jar + cp -f $JAR_SOURCE/cglib-2.2.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/cglib-2.2.jar + cp -f $JAR_SOURCE/cglib-2.2.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/cglib-2.2.jar +else + ShowLogFaild "$JAR_SOURCE/cglib-2.2.jar" +fi + + +if test -e $JAR_SOURCE/commons-beanutils.jar;then + cp -f $JAR_SOURCE/commons-beanutils.jar $OAT_SOURCE/HisClient/lib/commons-beanutils.jar + cp -f $JAR_SOURCE/commons-beanutils.jar $OAT_SOURCE/HisAppraiser/lib/commons-beanutils.jar + cp -f $JAR_SOURCE/commons-beanutils.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/commons-beanutils.jar + cp -f $JAR_SOURCE/commons-beanutils.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/commons-beanutils.jar + cp -f $JAR_SOURCE/commons-beanutils.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/commons-beanutils.jar +else + ShowLogFaild "$JAR_SOURCE/commons-beanutils.jar" +fi + + +if test -e $JAR_SOURCE/commons-cli-1.0.jar;then + cp -f $JAR_SOURCE/commons-cli-1.0.jar $OAT_SOURCE/HisAppraiser/lib/commons-cli-1.0.jar + cp -f $JAR_SOURCE/commons-cli-1.0.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/commons-cli-1.0.jar + cp -f $JAR_SOURCE/commons-cli-1.0.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/commons-cli-1.0.jar + cp -f $JAR_SOURCE/commons-cli-1.0.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/commons-cli-1.0.jar +else + ShowLogFaild "$JAR_SOURCE/commons-cli-1.0.jar" +fi + + +if test -e $JAR_SOURCE/commons-codec-1.3.jar;then + cp -f $JAR_SOURCE/commons-codec-1.3.jar $OAT_SOURCE/HisAppraiser/lib/commons-codec-1.3.jar + cp -f $JAR_SOURCE/commons-codec-1.3.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/commons-codec-1.3.jar + cp -f $JAR_SOURCE/commons-codec-1.3.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/commons-codec-1.3.jar + cp -f $JAR_SOURCE/commons-codec-1.3.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/commons-codec-1.3.jar +else + ShowLogFaild "$JAR_SOURCE/commons-codec-1.3.jar" +fi + + +if test -e $JAR_SOURCE/commons-codec-1.4.jar;then + cp -f $JAR_SOURCE/commons-codec-1.4.jar $OAT_SOURCE/HisAppraiser/lib/commons-codec-1.4.jar + cp -f $JAR_SOURCE/commons-codec-1.4.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/commons-codec-1.4.jar + cp -f $JAR_SOURCE/commons-codec-1.4.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/commons-codec-1.4.jar +else + ShowLogFaild "$JAR_SOURCE/commons-codec-1.4.jar" +fi + + +if test -e $JAR_SOURCE/commons-collections-2.1.1.jar;then + cp -f $JAR_SOURCE/commons-collections-2.1.1.jar $OAT_SOURCE/HisAppraiser/lib/commons-collections-2.1.1.jar + cp -f $JAR_SOURCE/commons-collections-2.1.1.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/commons-codec-1.4.jar + cp -f $JAR_SOURCE/commons-collections-2.1.1.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/commons-codec-1.4.jar + cp -f $JAR_SOURCE/commons-collections-2.1.1.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/commons-collections-2.1.1.jar + if test -d $OAT_SOURCE/TSSCoreService;then + cp -f $JAR_SOURCE/commons-collections-2.1.1.jar $OAT_SOURCE/TSSCoreService/lib/commons-collections-2.1.1.jar + fi +else + ShowLogFaild "$JAR_SOURCE/commons-collections-2.1.1.jar" +fi + + +if test -e $JAR_SOURCE/commons-digester.jar;then + cp -f $JAR_SOURCE/commons-digester.jar $OAT_SOURCE/HisClient/lib/commons-digester.jar + cp -f $JAR_SOURCE/commons-digester.jar $OAT_SOURCE/HisAppraiser/lib/commons-digester.jar + cp -f $JAR_SOURCE/commons-digester.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/commons-digester.jar + cp -f $JAR_SOURCE/commons-digester.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/commons-digester.jar + cp -f $JAR_SOURCE/commons-digester.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/commons-digester.jar +else + ShowLogFaild "$JAR_SOURCE/commons-digester.jar" +fi + + +if test -e $JAR_SOURCE/commons-httpclient-3.0.jar;then + cp -f $JAR_SOURCE/commons-httpclient-3.0.jar $OAT_SOURCE/HisAppraiser/lib/commons-httpclient-3.0.jar + cp -f $JAR_SOURCE/commons-httpclient-3.0.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/commons-httpclient-3.0.jar + cp -f $JAR_SOURCE/commons-httpclient-3.0.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/commons-httpclient-3.0.jar + cp -f $JAR_SOURCE/commons-httpclient-3.0.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/commons-httpclient-3.0.jar +else + ShowLogFaild "$JAR_SOURCE/commons-httpclient-3.0.jar" +fi + + +if test -e $JAR_SOURCE/commons-logging.jar;then + cp -f $JAR_SOURCE/commons-logging.jar $OAT_SOURCE/HisClient/lib/commons-logging.jar + cp -f $JAR_SOURCE/commons-logging.jar $OAT_SOURCE/HisAppraiser/lib/commons-logging.jar + cp -f $JAR_SOURCE/commons-logging.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/commons-logging.jar + cp -f $JAR_SOURCE/commons-logging.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/commons-logging.jar + cp -f $JAR_SOURCE/commons-logging.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/commons-logging.jar + if test -d $OAT_SOURCE/TSSCoreService;then + cp -f $JAR_SOURCE/commons-logging.jar $OAT_SOURCE/TSSCoreService/lib/commons-logging.jar + fi +else + ShowLogFaild "$JAR_SOURCE/commons-logging.jar" +fi + + +if test -e $JAR_SOURCE/commons-logging-1.1.1.jar;then + cp -f $JAR_SOURCE/commons-logging-1.1.1.jar $OAT_SOURCE/HisAppraiser/lib/commons-logging-1.1.1.jar + cp -f $JAR_SOURCE/commons-logging-1.1.1.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/commons-logging-1.1.1.jar + cp -f $JAR_SOURCE/commons-logging-1.1.1.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/commons-logging-1.1.1.jar +else + ShowLogFaild "$JAR_SOURCE/commons-logging-1.1.1.jar" +fi + + +if test -e $JAR_SOURCE/dom4j-1.6.1.jar;then + cp -f $JAR_SOURCE/dom4j-1.6.1.jar $OAT_SOURCE/HisAppraiser/lib/dom4j-1.6.1.jar + cp -f $JAR_SOURCE/dom4j-1.6.1.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/dom4j-1.6.1.jar + cp -f $JAR_SOURCE/dom4j-1.6.1.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/dom4j-1.6.1.jar + cp -f $JAR_SOURCE/dom4j-1.6.1.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/dom4j-1.6.1.jar + if test -d $OAT_SOURCE/TSSCoreService;then + cp -f $JAR_SOURCE/dom4j-1.6.1.jar $OAT_SOURCE/TSSCoreService/lib/dom4j-1.6.1.jar + fi +else + ShowLogFaild "$JAR_SOURCE/dom4j-1.6.1.jar" +fi + + +if test -e $JAR_SOURCE/FastInfoset.jar;then + cp -f $JAR_SOURCE/FastInfoset.jar $OAT_SOURCE/HisClient/lib/FastInfoset.jar + cp -f $JAR_SOURCE/FastInfoset.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/FastInfoset.jar + cp -f $JAR_SOURCE/FastInfoset.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/FastInfoset.jar + cp -f $JAR_SOURCE/FastInfoset.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/FastInfoset.jar + cp -f $JAR_SOURCE/FastInfoset.jar $OAT_SOURCE/HisAppraiser/lib/FastInfoset.jar + cp -f $JAR_SOURCE/FastInfoset.jar $OAT_SOURCE/PrivacyCA/lib/FastInfoset.jar + cp -f $JAR_SOURCE/FastInfoset.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/FastInfoset.jar + cp -f $JAR_SOURCE/FastInfoset.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/FastInfoset.jar + cp -f $JAR_SOURCE/FastInfoset.jar $OAT_SOURCE/HisWebServices/clientlib/FastInfoset.jar + cp -f $JAR_SOURCE/FastInfoset.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/FastInfoset.jar +else + ShowLogFaild "$JAR_SOURCE/FastInfoset.jar" +fi + + +if test -e $JAR_SOURCE/hibernate3.jar;then + cp -f $JAR_SOURCE/hibernate3.jar $OAT_SOURCE/HisAppraiser/lib/hibernate3.jar + cp -f $JAR_SOURCE/hibernate3.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/hibernate3.jar + cp -f $JAR_SOURCE/hibernate3.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/hibernate3.jar + cp -f $JAR_SOURCE/hibernate3.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/hibernate3.jar +else + ShowLogFaild "$JAR_SOURCE/hibernate3.jar" +fi + + +if test -e $JAR_SOURCE/jaas.jar;then + cp -f $JAR_SOURCE/jaas.jar $OAT_SOURCE/HisClient/lib/jaas.jar + cp -f $JAR_SOURCE/jaas.jar $OAT_SOURCE/HisAppraiser/lib/jaas.jar + cp -f $JAR_SOURCE/jaas.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jaas.jar + cp -f $JAR_SOURCE/jaas.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jaas.jar + cp -f $JAR_SOURCE/jaas.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jaas.jar +else + ShowLogFaild "$JAR_SOURCE/jaas.jar" +fi + + +if test -e $JAR_SOURCE/jackson-core-asl-1.8.3.jar;then + cp -f $JAR_SOURCE/jackson-core-asl-1.8.3.jar $OAT_SOURCE/HisAppraiser/lib/jackson-core-asl-1.8.3.jar + cp -f $JAR_SOURCE/jackson-core-asl-1.8.3.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jackson-core-asl-1.8.3.jar + cp -f $JAR_SOURCE/jackson-core-asl-1.8.3.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jackson-core-asl-1.8.3.jar +else + ShowLogFaild "$JAR_SOURCE/jackson-core-asl-1.8.3.jar" +fi + + +if test -e $JAR_SOURCE/jackson-jaxrs-1.8.3.jar;then + cp -f $JAR_SOURCE/jackson-jaxrs-1.8.3.jar $OAT_SOURCE/HisAppraiser/lib/jackson-jaxrs-1.8.3.jar + cp -f $JAR_SOURCE/jackson-jaxrs-1.8.3.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jackson-jaxrs-1.8.3.jar + cp -f $JAR_SOURCE/jackson-jaxrs-1.8.3.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jackson-jaxrs-1.8.3.jar +else + ShowLogFaild "$JAR_SOURCE/jackson-jaxrs-1.8.3.jar" +fi + + +if test -e $JAR_SOURCE/jackson-mapper-asl-1.8.3.jar;then + cp -f $JAR_SOURCE/jackson-mapper-asl-1.8.3.jar $OAT_SOURCE/HisAppraiser/lib/jackson-mapper-asl-1.8.3.jar + cp -f $JAR_SOURCE/jackson-mapper-asl-1.8.3.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jackson-mapper-asl-1.8.3.jar + cp -f $JAR_SOURCE/jackson-mapper-asl-1.8.3.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jackson-mapper-asl-1.8.3.jar +else + ShowLogFaild "$JAR_SOURCE/jackson-mapper-asl-1.8.3.jar" +fi + + +if test -e $JAR_SOURCE/jackson-xc-1.8.3.jar;then + cp -f $JAR_SOURCE/jackson-xc-1.8.3.jar $OAT_SOURCE/HisAppraiser/lib/jackson-xc-1.8.3.jar + cp -f $JAR_SOURCE/jackson-xc-1.8.3.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jackson-xc-1.8.3.jar + cp -f $JAR_SOURCE/jackson-xc-1.8.3.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jackson-xc-1.8.3.jar +else + ShowLogFaild "$JAR_SOURCE/jackson-xc-1.8.3.jar" +fi + + +if test -e $JAR_SOURCE/jaxb-api.jar;then + cp -f $JAR_SOURCE/jaxb-api.jar $OAT_SOURCE/HisClient/lib/jaxb-api.jar + cp -f $JAR_SOURCE/jaxb-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jaxb-api.jar + cp -f $JAR_SOURCE/jaxb-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jaxb-api.jar + cp -f $JAR_SOURCE/jaxb-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jaxb-api.jar + cp -f $JAR_SOURCE/jaxb-api.jar $OAT_SOURCE/HisAppraiser/lib/jaxb-api.jar + cp -f $JAR_SOURCE/jaxb-api.jar $OAT_SOURCE/PrivacyCA/lib/jaxb-api.jar + cp -f $JAR_SOURCE/jaxb-api.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jaxb-api.jar + cp -f $JAR_SOURCE/jaxb-api.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jaxb-api.jar + cp -f $JAR_SOURCE/jaxb-api.jar $OAT_SOURCE/HisWebServices/clientlib/jaxb-api.jar + cp -f $JAR_SOURCE/jaxb-api.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jaxb-api.jar +else + ShowLogFaild "$JAR_SOURCE/jaxb-api.jar" +fi + + +if test -e $JAR_SOURCE/jaxb-impl.jar;then + cp -f $JAR_SOURCE/jaxb-impl.jar $OAT_SOURCE/HisClient/lib/jaxb-impl.jar + cp -f $JAR_SOURCE/jaxb-impl.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jaxb-impl.jar + cp -f $JAR_SOURCE/jaxb-impl.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jaxb-impl.jar + cp -f $JAR_SOURCE/jaxb-impl.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jaxb-impl.jar + cp -f $JAR_SOURCE/jaxb-impl.jar $OAT_SOURCE/HisAppraiser/lib/jaxb-impl.jar + cp -f $JAR_SOURCE/jaxb-impl.jar $OAT_SOURCE/PrivacyCA/lib/jaxb-impl.jar + cp -f $JAR_SOURCE/jaxb-impl.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jaxb-impl.jar + cp -f $JAR_SOURCE/jaxb-impl.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jaxb-impl.jar + cp -f $JAR_SOURCE/jaxb-impl.jar $OAT_SOURCE/HisWebServices/clientlib/jaxb-impl.jar + cp -f $JAR_SOURCE/jaxb-impl.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jaxb-impl.jar +else + ShowLogFaild "$JAR_SOURCE/jaxb-impl.jar" +fi + + +if test -e $JAR_SOURCE/jaxb-xjc.jar;then + cp -f $JAR_SOURCE/jaxb-xjc.jar $OAT_SOURCE/HisClient/lib/jaxb-xjc.jar + cp -f $JAR_SOURCE/jaxb-xjc.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jaxb-xjc.jar + cp -f $JAR_SOURCE/jaxb-xjc.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jaxb-xjc.jar + cp -f $JAR_SOURCE/jaxb-xjc.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jaxb-xjc.jar + cp -f $JAR_SOURCE/jaxb-xjc.jar $OAT_SOURCE/HisAppraiser/lib/jaxb-xjc.jar + cp -f $JAR_SOURCE/jaxb-xjc.jar $OAT_SOURCE/PrivacyCA/lib/jaxb-xjc.jar + cp -f $JAR_SOURCE/jaxb-xjc.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jaxb-xjc.jar + cp -f $JAR_SOURCE/jaxb-xjc.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jaxb-xjc.jar + cp -f $JAR_SOURCE/jaxb-xjc.jar $OAT_SOURCE/HisWebServices/clientlib/jaxb-xjc.jar + cp -f $JAR_SOURCE/jaxb-xjc.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jaxb-xjc.jar +else + ShowLogFaild "$JAR_SOURCE/jaxb-xjc.jar" +fi + + +if test -e $JAR_SOURCE/jax-qname.jar;then + cp -f $JAR_SOURCE/jax-qname.jar $OAT_SOURCE/HisClient/lib/jax-qname.jar + cp -f $JAR_SOURCE/jax-qname.jar $OAT_SOURCE/HisAppraiser/lib/jax-qname.jar + cp -f $JAR_SOURCE/jax-qname.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jax-qname.jar + cp -f $JAR_SOURCE/jax-qname.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jax-qname.jar +else + ShowLogFaild "$JAR_SOURCE/jax-qname.jar" +fi + + +if test -e $JAR_SOURCE/jaxws-api.jar;then + cp -f $JAR_SOURCE/jaxws-api.jar $OAT_SOURCE/HisClient/lib/jaxws-api.jar + cp -f $JAR_SOURCE/jaxws-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jaxws-api.jar + cp -f $JAR_SOURCE/jaxws-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jaxws-api.jar + cp -f $JAR_SOURCE/jaxws-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jaxws-api.jar + cp -f $JAR_SOURCE/jaxws-api.jar $OAT_SOURCE/HisAppraiser/lib/jaxws-api.jar + cp -f $JAR_SOURCE/jaxws-api.jar $OAT_SOURCE/PrivacyCA/lib/jaxws-api.jar + cp -f $JAR_SOURCE/jaxws-api.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jaxws-api.jar + cp -f $JAR_SOURCE/jaxws-api.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jaxws-api.jar + cp -f $JAR_SOURCE/jaxws-api.jar $OAT_SOURCE/HisWebServices/clientlib/jaxws-api.jar + cp -f $JAR_SOURCE/jaxws-api.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jaxws-api.jar +else + ShowLogFaild "$JAR_SOURCE/jaxws-api.jar" +fi + + +if test -e $JAR_SOURCE/jaxws-rt.jar;then + cp -f $JAR_SOURCE/jaxws-rt.jar $OAT_SOURCE/HisClient/lib/jaxws-rt.jar + cp -f $JAR_SOURCE/jaxws-rt.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jaxws-rt.jar + cp -f $JAR_SOURCE/jaxws-rt.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jaxws-rt.jar + cp -f $JAR_SOURCE/jaxws-rt.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jaxws-rt.jar + cp -f $JAR_SOURCE/jaxws-rt.jar $OAT_SOURCE/HisAppraiser/lib/jaxws-rt.jar + cp -f $JAR_SOURCE/jaxws-rt.jar $OAT_SOURCE/PrivacyCA/lib/jaxws-rt.jar + cp -f $JAR_SOURCE/jaxws-rt.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jaxws-rt.jar + cp -f $JAR_SOURCE/jaxws-rt.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jaxws-rt.jar + cp -f $JAR_SOURCE/jaxws-rt.jar $OAT_SOURCE/HisWebServices/clientlib/jaxws-rt.jar + cp -f $JAR_SOURCE/jaxws-rt.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jaxws-rt.jar +else + ShowLogFaild "$JAR_SOURCE/jaxws-rt.jar" +fi + + +if test -e $JAR_SOURCE/jaxws-tools.jar;then + cp -f $JAR_SOURCE/jaxws-tools.jar $OAT_SOURCE/HisClient/lib/jaxws-tools.jar + cp -f $JAR_SOURCE/jaxws-tools.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jaxws-tools.jar + cp -f $JAR_SOURCE/jaxws-tools.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jaxws-tools.jar + cp -f $JAR_SOURCE/jaxws-tools.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jaxws-tools.jar + cp -f $JAR_SOURCE/jaxws-tools.jar $OAT_SOURCE/HisAppraiser/lib/jaxws-tools.jar + cp -f $JAR_SOURCE/jaxws-tools.jar $OAT_SOURCE/PrivacyCA/lib/jaxws-tools.jar + cp -f $JAR_SOURCE/jaxws-tools.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jaxws-tools.jar + cp -f $JAR_SOURCE/jaxws-tools.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jaxws-tools.jar + cp -f $JAR_SOURCE/jaxws-tools.jar $OAT_SOURCE/HisWebServices/clientlib/jaxws-tools.jar + cp -f $JAR_SOURCE/jaxws-tools.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jaxws-tools.jar +else + ShowLogFaild "$JAR_SOURCE/jaxws-tools.jar" +fi + + +if test -e $JAR_SOURCE/jdbc2_0-stdext.jar;then + cp -f $JAR_SOURCE/jdbc2_0-stdext.jar $OAT_SOURCE/HisAppraiser/lib/jdbc2_0-stdext.jar + cp -f $JAR_SOURCE/jdbc2_0-stdext.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jdbc2_0-stdext.jar + cp -f $JAR_SOURCE/jdbc2_0-stdext.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jdbc2_0-stdext.jar + cp -f $JAR_SOURCE/jdbc2_0-stdext.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jdbc2_0-stdext.jar +else + ShowLogFaild "$JAR_SOURCE/jdbc2_0-stdext.jar" +fi + + +if test -e $JAR_SOURCE/jersey-bundle-1.9.1.jar;then + cp -f $JAR_SOURCE/jersey-bundle-1.9.1.jar $OAT_SOURCE/HisAppraiser/lib/jersey-bundle-1.9.1.jar + cp -f $JAR_SOURCE/jersey-bundle-1.9.1.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jersey-bundle-1.9.1.jar + cp -f $JAR_SOURCE/jersey-bundle-1.9.1.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jersey-bundle-1.9.1.jar + cp -f $JAR_SOURCE/jersey-bundle-1.9.1.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jersey-bundle-1.9.1.jar +else + ShowLogFaild "$JAR_SOURCE/jersey-bundle-1.9.1.jar" +fi + + +if test -e $JAR_SOURCE/jersey-client-1.9.1.jar;then + cp -f $JAR_SOURCE/jersey-client-1.9.1.jar $OAT_SOURCE/HisAppraiser/lib/jersey-client-1.9.1.jar + cp -f $JAR_SOURCE/jersey-client-1.9.1.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jersey-client-1.9.1.jar + cp -f $JAR_SOURCE/jersey-client-1.9.1.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jersey-client-1.9.1.jar + cp -f $JAR_SOURCE/jersey-client-1.9.1.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jersey-client-1.9.1.jar +else + ShowLogFaild "$JAR_SOURCE/jersey-client-1.9.1.jar" +fi + + +if test -e $JAR_SOURCE/jersey-core-1.9.1.jar;then + cp -f $JAR_SOURCE/jersey-core-1.9.1.jar $OAT_SOURCE/HisAppraiser/lib/jersey-core-1.9.1.jar + cp -f $JAR_SOURCE/jersey-core-1.9.1.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jersey-core-1.9.1.jar + cp -f $JAR_SOURCE/jersey-core-1.9.1.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jersey-core-1.9.1.jar + cp -f $JAR_SOURCE/jersey-core-1.9.1.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jersey-core-1.9.1.jar +else + ShowLogFaild "$JAR_SOURCE/jersey-core-1.9.1.jar" +fi + + +if test -e $JAR_SOURCE/jersey-json-1.9.1.jar;then + cp -f $JAR_SOURCE/jersey-json-1.9.1.jar $OAT_SOURCE/HisAppraiser/lib/jersey-json-1.9.1.jar + cp -f $JAR_SOURCE/jersey-json-1.9.1.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jersey-json-1.9.1.jar + cp -f $JAR_SOURCE/jersey-json-1.9.1.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jersey-json-1.9.1.jar + cp -f $JAR_SOURCE/jersey-json-1.9.1.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jersey-json-1.9.1.jar +else + ShowLogFaild "$JAR_SOURCE/jersey-json-1.9.1.jar" +fi + + +if test -e $JAR_SOURCE/jersey-server-1.9.1.jar;then + cp -f $JAR_SOURCE/jersey-server-1.9.1.jar $OAT_SOURCE/HisAppraiser/lib/jersey-server-1.9.1.jar + cp -f $JAR_SOURCE/jersey-server-1.9.1.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jersey-server-1.9.1.jar + cp -f $JAR_SOURCE/jersey-server-1.9.1.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jersey-server-1.9.1.jar +else + ShowLogFaild "$JAR_SOURCE/jersey-server-1.9.1.jar" +fi + + +if test -e $JAR_SOURCE/jettison-1.1.jar;then + cp -f $JAR_SOURCE/jettison-1.1.jar $OAT_SOURCE/HisAppraiser/lib/jettison-1.1.jar + cp -f $JAR_SOURCE/jettison-1.1.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jettison-1.1.jar + cp -f $JAR_SOURCE/jettison-1.1.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jettison-1.1.jar +else + ShowLogFaild "$JAR_SOURCE/jettison-1.1.jar" +fi + + +if test -e $JAR_SOURCE/jsr173_api.jar;then + cp -f $JAR_SOURCE/jsr173_api.jar $OAT_SOURCE/HisClient/lib/jsr173_api.jar + cp -f $JAR_SOURCE/jsr173_api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jsr173_api.jar + cp -f $JAR_SOURCE/jsr173_api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jsr173_api.jar + cp -f $JAR_SOURCE/jsr173_api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jsr173_api.jar + cp -f $JAR_SOURCE/jsr173_api.jar $OAT_SOURCE/HisAppraiser/lib/jsr173_api.jar + cp -f $JAR_SOURCE/jsr173_api.jar $OAT_SOURCE/PrivacyCA/lib/jsr173_api.jar + cp -f $JAR_SOURCE/jsr173_api.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jsr173_api.jar + cp -f $JAR_SOURCE/jsr173_api.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jsr173_api.jar + cp -f $JAR_SOURCE/jsr173_api.jar $OAT_SOURCE/HisWebServices/clientlib/jsr173_api.jar + cp -f $JAR_SOURCE/jsr173_api.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jsr173_api.jar +else + ShowLogFaild "$JAR_SOURCE/jsr173_api.jar" +fi + + +if test -e $JAR_SOURCE/jsr181-api.jar;then + cp -f $JAR_SOURCE/jsr181-api.jar $OAT_SOURCE/HisClient/lib/jsr181-api.jar + cp -f $JAR_SOURCE/jsr181-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jsr181-api.jar + cp -f $JAR_SOURCE/jsr181-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jsr181-api.jar + cp -f $JAR_SOURCE/jsr181-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jsr181-api.jar + cp -f $JAR_SOURCE/jsr181-api.jar $OAT_SOURCE/HisAppraiser/lib/jsr181-api.jar + cp -f $JAR_SOURCE/jsr181-api.jar $OAT_SOURCE/PrivacyCA/lib/jsr181-api.jar + cp -f $JAR_SOURCE/jsr181-api.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jsr181-api.jar + cp -f $JAR_SOURCE/jsr181-api.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jsr181-api.jar + cp -f $JAR_SOURCE/jsr181-api.jar $OAT_SOURCE/HisWebServices/clientlib/jsr181-api.jar + cp -f $JAR_SOURCE/jsr181-api.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jsr181-api.jar +else + ShowLogFaild "$JAR_SOURCE/jsr181-api.jar" +fi + + +if test -e $JAR_SOURCE/jsr250-api.jar;then + cp -f $JAR_SOURCE/jsr250-api.jar $OAT_SOURCE/HisClient/lib/jsr250-api.jar + cp -f $JAR_SOURCE/jsr250-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jsr250-api.jar + cp -f $JAR_SOURCE/jsr250-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jsr250-api.jar + cp -f $JAR_SOURCE/jsr250-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jsr250-api.jar + cp -f $JAR_SOURCE/jsr250-api.jar $OAT_SOURCE/HisAppraiser/lib/jsr250-api.jar + cp -f $JAR_SOURCE/jsr250-api.jar $OAT_SOURCE/PrivacyCA/lib/jsr250-api.jar + cp -f $JAR_SOURCE/jsr250-api.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jsr250-api.jar + cp -f $JAR_SOURCE/jsr250-api.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jsr250-api.jar + cp -f $JAR_SOURCE/jsr250-api.jar $OAT_SOURCE/HisWebServices/clientlib/jsr250-api.jar + cp -f $JAR_SOURCE/jsr250-api.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jsr250-api.jar +else + ShowLogFaild "$JAR_SOURCE/jsr250-api.jar" +fi + + +if test -e $JAR_SOURCE/jsr311-api-1.1.1.jar;then + cp -f $JAR_SOURCE/jsr311-api-1.1.1.jar $OAT_SOURCE/HisAppraiser/lib/jsr311-api-1.1.1.jar + cp -f $JAR_SOURCE/jsr311-api-1.1.1.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jsr311-api-1.1.1.jar + cp -f $JAR_SOURCE/jsr311-api-1.1.1.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jsr311-api-1.1.1.jar + cp -f $JAR_SOURCE/jsr311-api-1.1.1.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jsr311-api-1.1.1.jar +else + ShowLogFaild "$JAR_SOURCE/jsr311-api-1.1.1.jar" +fi + + +if test -e $JAR_SOURCE/jta.jar;then + cp -f $JAR_SOURCE/jta.jar $OAT_SOURCE/HisAppraiser/lib/jta.jar + cp -f $JAR_SOURCE/jta.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jta.jar + cp -f $JAR_SOURCE/jta.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jta.jar + cp -f $JAR_SOURCE/jta.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jta.jar +else + ShowLogFaild "$JAR_SOURCE/jta.jar" +fi + + +if test -e $JAR_SOURCE/jtds-1.2.jar;then + cp -f $JAR_SOURCE/jtds-1.2.jar $OAT_SOURCE/HisAppraiser/lib/jtds-1.2.jar + cp -f $JAR_SOURCE/jtds-1.2.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jtds-1.2.jar + cp -f $JAR_SOURCE/jtds-1.2.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jtds-1.2.jar + cp -f $JAR_SOURCE/jtds-1.2.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/jtds-1.2.jar +else + ShowLogFaild "$JAR_SOURCE/jtds-1.2.jar" +fi + + +if test -e $JAR_SOURCE/log4j-1.2.8.jar;then + cp -f $JAR_SOURCE/log4j-1.2.8.jar $OAT_SOURCE/HisAppraiser/lib/log4j-1.2.8.jar + cp -f $JAR_SOURCE/log4j-1.2.8.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/log4j-1.2.8.jar + cp -f $JAR_SOURCE/log4j-1.2.8.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/log4j-1.2.8.jar + cp -f $JAR_SOURCE/log4j-1.2.8.jar $OAT_SOURCE/HisWebServices/clientlib/log4j-1.2.8.jar + cp -f $JAR_SOURCE/log4j-1.2.8.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/log4j-1.2.8.jar +else + ShowLogFaild "$JAR_SOURCE/log4j-1.2.8.jar" +fi + + +if test -e $JAR_SOURCE/mail.jar;then + cp -f $JAR_SOURCE/mail.jar $OAT_SOURCE/HisClient/lib/mail.jar + cp -f $JAR_SOURCE/mail.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/mail.jar + cp -f $JAR_SOURCE/mail.jar $OAT_SOURCE/HisAppraiser/lib/mail.jar + cp -f $JAR_SOURCE/mail.jar $OAT_SOURCE/PrivacyCA/lib/mail.jar + cp -f $JAR_SOURCE/mail.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/mail.jar + cp -f $JAR_SOURCE/mail.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/mail.jar + cp -f $JAR_SOURCE/mail.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/mail.jar + if test -d $OAT_SOURCE/TSSCoreService;then + cp -f $JAR_SOURCE/mail.jar $OAT_SOURCE/TSSCoreService/lib/mail.jar + fi +else + ShowLogFaild "$JAR_SOURCE/mail.jar" +fi + + +if test -e $JAR_SOURCE/mimepull.jar;then + cp -f $JAR_SOURCE/mimepull.jar $OAT_SOURCE/HisClient/lib/mimepull.jar + cp -f $JAR_SOURCE/mimepull.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/mimepull.jar + cp -f $JAR_SOURCE/mimepull.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/mimepull.jar + cp -f $JAR_SOURCE/mimepull.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/mimepull.jar + cp -f $JAR_SOURCE/mimepull.jar $OAT_SOURCE/HisAppraiser/lib/mimepull.jar + cp -f $JAR_SOURCE/mimepull.jar $OAT_SOURCE/PrivacyCA/lib/mimepull.jar + cp -f $JAR_SOURCE/mimepull.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/mimepull.jar + cp -f $JAR_SOURCE/mimepull.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/mimepull.jar + cp -f $JAR_SOURCE/mimepull.jar $OAT_SOURCE/HisWebServices/clientlib/mimepull.jar + cp -f $JAR_SOURCE/mimepull.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/mimepull.jar +else + ShowLogFaild "$JAR_SOURCE/mimepull.jar" +fi + + +if test -e $JAR_SOURCE/mysql-connector-java-5.0.7-bin.jar;then + cp -f $JAR_SOURCE/mysql-connector-java-5.0.7-bin.jar $OAT_SOURCE/HisAppraiser/lib/mysql-connector-java-5.0.7-bin.jar + cp -f $JAR_SOURCE/mysql-connector-java-5.0.7-bin.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/mysql-connector-java-5.0.7-bin.jar + cp -f $JAR_SOURCE/mysql-connector-java-5.0.7-bin.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/mysql-connector-java-5.0.7-bin.jar + cp -f $JAR_SOURCE/mysql-connector-java-5.0.7-bin.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/mysql-connector-java-5.0.7-bin.jar +else + ShowLogFaild "$JAR_SOURCE/mysql-connector-java-5.0.7-bin.jar" +fi + + +if test -e $JAR_SOURCE/org.springframework.context.support-3.0.3.RELEASE.jar;then + cp -f $JAR_SOURCE/org.springframework.context.support-3.0.3.RELEASE.jar $OAT_SOURCE/HisAppraiser/lib/org.springframework.context.support-3.0.3.RELEASE.jar + cp -f $JAR_SOURCE/org.springframework.context.support-3.0.3.RELEASE.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/org.springframework.context.support-3.0.3.RELEASE.jar + cp -f $JAR_SOURCE/org.springframework.context.support-3.0.3.RELEASE.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/org.springframework.context.support-3.0.3.RELEASE.jar +else + ShowLogFaild "$JAR_SOURCE/org.springframework.context.support-3.0.3.RELEASE.jar" +fi + + +if test -e $JAR_SOURCE/relaxngDatatype.jar;then + cp -f $JAR_SOURCE/relaxngDatatype.jar $OAT_SOURCE/HisClient/lib/relaxngDatatype.jar + cp -f $JAR_SOURCE/relaxngDatatype.jar $OAT_SOURCE/HisAppraiser/lib/relaxngDatatype.jar + cp -f $JAR_SOURCE/relaxngDatatype.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/relaxngDatatype.jar + cp -f $JAR_SOURCE/relaxngDatatype.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/relaxngDatatype.jar + cp -f $JAR_SOURCE/relaxngDatatype.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/relaxngDatatype.jar +else + ShowLogFaild "$JAR_SOURCE/relaxngDatatype.jar" +fi + + +if test -e $JAR_SOURCE/resolver.jar;then + cp -f $JAR_SOURCE/resolver.jar $OAT_SOURCE/HisClient/lib/resolver.jar + cp -f $JAR_SOURCE/resolver.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/resolver.jar + cp -f $JAR_SOURCE/resolver.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/resolver.jar + cp -f $JAR_SOURCE/resolver.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/resolver.jar + cp -f $JAR_SOURCE/resolver.jar $OAT_SOURCE/HisAppraiser/lib/resolver.jar + cp -f $JAR_SOURCE/resolver.jar $OAT_SOURCE/PrivacyCA/lib/resolver.jar + cp -f $JAR_SOURCE/resolver.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/resolver.jar + cp -f $JAR_SOURCE/resolver.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/resolver.jar + cp -f $JAR_SOURCE/resolver.jar $OAT_SOURCE/HisWebServices/clientlib/resolver.jar + cp -f $JAR_SOURCE/resolver.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/resolver.jar +else + ShowLogFaild "$JAR_SOURCE/resolver.jar" +fi + + +if test -e $JAR_SOURCE/saaj-api.jar;then + cp -f $JAR_SOURCE/saaj-api.jar $OAT_SOURCE/HisClient/lib/saaj-api.jar + cp -f $JAR_SOURCE/saaj-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/saaj-api.jar + cp -f $JAR_SOURCE/saaj-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/saaj-api.jar + cp -f $JAR_SOURCE/saaj-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/saaj-api.jar + cp -f $JAR_SOURCE/saaj-api.jar $OAT_SOURCE/HisAppraiser/lib/saaj-api.jar + cp -f $JAR_SOURCE/saaj-api.jar $OAT_SOURCE/PrivacyCA/lib/saaj-api.jar + cp -f $JAR_SOURCE/saaj-api.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/saaj-api.jar + cp -f $JAR_SOURCE/saaj-api.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/saaj-api.jar + cp -f $JAR_SOURCE/saaj-api.jar $OAT_SOURCE/HisWebServices/clientlib/saaj-api.jar + cp -f $JAR_SOURCE/saaj-api.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/saaj-api.jar +else + ShowLogFaild "$JAR_SOURCE/saaj-api.jar" +fi + + +if test -e $JAR_SOURCE/saaj-impl.jar;then + cp -f $JAR_SOURCE/saaj-impl.jar $OAT_SOURCE/HisClient/lib/saaj-impl.jar + cp -f $JAR_SOURCE/saaj-impl.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/saaj-impl.jar + cp -f $JAR_SOURCE/saaj-impl.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/saaj-impl.jar + cp -f $JAR_SOURCE/saaj-impl.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/saaj-impl.jar + cp -f $JAR_SOURCE/saaj-impl.jar $OAT_SOURCE/HisAppraiser/lib/saaj-impl.jar + cp -f $JAR_SOURCE/saaj-impl.jar $OAT_SOURCE/PrivacyCA/lib/saaj-impl.jar + cp -f $JAR_SOURCE/saaj-impl.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/saaj-impl.jar + cp -f $JAR_SOURCE/saaj-impl.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/saaj-impl.jar + cp -f $JAR_SOURCE/saaj-impl.jar $OAT_SOURCE/HisWebServices/clientlib/saaj-impl.jar + cp -f $JAR_SOURCE/saaj-impl.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/saaj-impl.jar +else + ShowLogFaild "$JAR_SOURCE/saaj-impl.jar" +fi + + +if test -e $JAR_SOURCE/servlet.jar;then + cp -f $JAR_SOURCE/servlet.jar $OAT_SOURCE/HisAppraiser/lib/servlet.jar + cp -f $JAR_SOURCE/servlet.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/servlet.jar + cp -f $JAR_SOURCE/servlet.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/servlet.jar +else + ShowLogFaild "$JAR_SOURCE/servlet.jar" +fi + + +if test -e $JAR_SOURCE/servlet-api.jar;then + cp -f $JAR_SOURCE/servlet-api.jar $OAT_SOURCE/HisClient/lib/servlet-api.jar + cp -f $JAR_SOURCE/servlet-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/servlet-api.jar + cp -f $JAR_SOURCE/servlet-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/jars-compile-only/servlet-api.jar + cp -f $JAR_SOURCE/servlet-api.jar $OAT_SOURCE/HisAppraiser/lib/servlet-api.jar + cp -f $JAR_SOURCE/servlet-api.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/servlet-api.jar + cp -f $JAR_SOURCE/servlet-api.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/servlet-api.jar + cp -f $JAR_SOURCE/servlet-api.jar $OAT_SOURCE/HisWebServices/clientlib/servlet-api.jar + cp -f $JAR_SOURCE/servlet-api.jar $OAT_SOURCE/HisWebServices/WEB-INF/jars-compile-only/servlet-api.jar +else + ShowLogFaild "$JAR_SOURCE/servlet-api.jar" +fi + + +if test -e $JAR_SOURCE/stax-ex.jar;then + cp -f $JAR_SOURCE/stax-ex.jar $OAT_SOURCE/HisClient/lib/stax-ex.jar + cp -f $JAR_SOURCE/stax-ex.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/stax-ex.jar + cp -f $JAR_SOURCE/stax-ex.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/stax-ex.jar + cp -f $JAR_SOURCE/stax-ex.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/stax-ex.jar + cp -f $JAR_SOURCE/stax-ex.jar $OAT_SOURCE/HisAppraiser/lib/stax-ex.jar + cp -f $JAR_SOURCE/stax-ex.jar $OAT_SOURCE/PrivacyCA/lib/stax-ex.jar + cp -f $JAR_SOURCE/stax-ex.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/stax-ex.jar + cp -f $JAR_SOURCE/stax-ex.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/stax-ex.jar + cp -f $JAR_SOURCE/stax-ex.jar $OAT_SOURCE/HisWebServices/clientlib/stax-ex.jar + cp -f $JAR_SOURCE/stax-ex.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/stax-ex.jar +else + ShowLogFaild "$JAR_SOURCE/stax-ex.jar" +fi + + +if test -e $JAR_SOURCE/streambuffer.jar;then + cp -f $JAR_SOURCE/streambuffer.jar $OAT_SOURCE/HisClient/lib/streambuffer.jar + cp -f $JAR_SOURCE/streambuffer.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/streambuffer.jar + cp -f $JAR_SOURCE/streambuffer.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/streambuffer.jar + cp -f $JAR_SOURCE/streambuffer.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/streambuffer.jar + cp -f $JAR_SOURCE/streambuffer.jar $OAT_SOURCE/HisAppraiser/lib/streambuffer.jar + cp -f $JAR_SOURCE/streambuffer.jar $OAT_SOURCE/PrivacyCA/lib/streambuffer.jar + cp -f $JAR_SOURCE/streambuffer.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/streambuffer.jar + cp -f $JAR_SOURCE/streambuffer.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/streambuffer.jar + cp -f $JAR_SOURCE/streambuffer.jar $OAT_SOURCE/HisWebServices/clientlib/streambuffer.jar + cp -f $JAR_SOURCE/streambuffer.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/streambuffer.jar +else + ShowLogFaild "$JAR_SOURCE/streambuffer.jar" +fi + + +if test -e $JAR_SOURCE/woodstox.jar;then + cp -f $JAR_SOURCE/woodstox.jar $OAT_SOURCE/HisClient/lib/woodstox.jar + cp -f $JAR_SOURCE/woodstox.jar $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/woodstox.jar + cp -f $JAR_SOURCE/woodstox.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/woodstox.jar + cp -f $JAR_SOURCE/woodstox.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/woodstox.jar + cp -f $JAR_SOURCE/woodstox.jar $OAT_SOURCE/HisAppraiser/lib/woodstox.jar + cp -f $JAR_SOURCE/woodstox.jar $OAT_SOURCE/PrivacyCA/lib/woodstox.jar + cp -f $JAR_SOURCE/woodstox.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/woodstox.jar + cp -f $JAR_SOURCE/woodstox.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/woodstox.jar + cp -f $JAR_SOURCE/woodstox.jar $OAT_SOURCE/HisWebServices/clientlib/woodstox.jar + cp -f $JAR_SOURCE/woodstox.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/woodstox.jar +else + ShowLogFaild "$JAR_SOURCE/woodstox.jar" +fi + + +if test -e $JAR_SOURCE/xsdlib.jar;then + cp -f $JAR_SOURCE/xsdlib.jar $OAT_SOURCE/HisClient/lib/xsdlib.jar + cp -f $JAR_SOURCE/xsdlib.jar $OAT_SOURCE/HisAppraiser/lib/xsdlib.jar + cp -f $JAR_SOURCE/xsdlib.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/xsdlib.jar + cp -f $JAR_SOURCE/xsdlib.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/xsdlib.jar + cp -f $JAR_SOURCE/xsdlib.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/xsdlib.jar +else + ShowLogFaild "$JAR_SOURCE/xsdlib.jar" +fi + + +if test -e $JAR_SOURCE/commons-cli-1.0.jar;then + cp -f $JAR_SOURCE/commons-cli-1.0.jar $OAT_SOURCE/HisAppraiser/lib/commons-cli-1.0.jar + cp -f $JAR_SOURCE/commons-cli-1.0.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/commons-cli-1.0.jar + cp -f $JAR_SOURCE/commons-cli-1.0.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/commons-cli-1.0.jar + cp -f $JAR_SOURCE/commons-cli-1.0.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/commons-cli-1.0.jar +else + ShowLogFaild "$JAR_SOURCE/commons-cli-1.0.jar" +fi + + +if test -e $JAR_SOURCE/jsp-api.jar;then + cp -f $JAR_SOURCE/jsp-api.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/jars-compile-only/jsp-api.jar + cp -f $JAR_SOURCE/jsp-api.jar $OAT_SOURCE/HisWebServices/WEB-INF/jars-compile-only/jsp-api.jar +else + ShowLogFaild "$JAR_SOURCE/jsp-api.jar" +fi + + +if test -e $JAR_SOURCE/commons-discovery-0.2.jar;then + cp -f $JAR_SOURCE/commons-discovery-0.2.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/commons-discovery-0.2.jar + cp -f $JAR_SOURCE/commons-discovery-0.2.jar $OAT_SOURCE/PrivacyCA/lib/commons-discovery-0.2.jar + if test -d $OAT_SOURCE/TSSCoreService;then + cp -f $JAR_SOURCE/commons-discovery-0.2.jar $OAT_SOURCE/TSSCoreService/lib/commons-discovery-0.2.jar + fi +else + ShowLogFaild "$JAR_SOURCE/commons-discovery-0.2.jar" +fi + + +if test -e $JAR_SOURCE/wsdl4j-1.5.1.jar;then + cp -f $JAR_SOURCE/wsdl4j-1.5.1.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/wsdl4j-1.5.1.jar + cp -f $JAR_SOURCE/wsdl4j-1.5.1.jar $OAT_SOURCE/PrivacyCA/lib/wsdl4j-1.5.1.jar + if test -d $OAT_SOURCE/TSSCoreService;then + cp -f $JAR_SOURCE/wsdl4j-1.5.1.jar $OAT_SOURCE/TSSCoreService/lib/wsdl4j-1.5.1.jar + fi +else + ShowLogFaild "$JAR_SOURCE/wsdl4j-1.5.1.jar" +fi + + +if test -e $JAR_SOURCE/axis.jar;then + cp -f $JAR_SOURCE/axis.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/axis.jar + cp -f $JAR_SOURCE/axis.jar $OAT_SOURCE/PrivacyCA/lib/axis.jar + if test -d $OAT_SOURCE/TSSCoreService;then + cp -f $JAR_SOURCE/axis.jar $OAT_SOURCE/TSSCoreService/lib/axis.jar + fi +else + ShowLogFaild "$JAR_SOURCE/axis.jar" +fi + + +if test -e $JAR_SOURCE/jaxb-libs.jar;then + cp -f $JAR_SOURCE/jaxb-libs.jar $OAT_SOURCE/HisClient/lib/jaxb-libs.jar +else + ShowLogFaild "$JAR_SOURCE/jaxb-libs.jar" +fi + + +if test -e $JAR_SOURCE/jta-spec1_0_1.jar;then + cp -f $JAR_SOURCE/jta-spec1_0_1.jar $OAT_SOURCE/HisClient/lib/jta-spec1_0_1.jar +else + ShowLogFaild "$JAR_SOURCE/jta-spec1_0_1.jar" +fi + + +if test -e $JAR_SOURCE/log4j-1.2.14.jar;then + cp -f $JAR_SOURCE/log4j-1.2.14.jar $OAT_SOURCE/HisClient/lib/log4j-1.2.14.jar +else + ShowLogFaild "$JAR_SOURCE/log4j-1.2.14.jar" +fi + + +if test -e $JAR_SOURCE/uuid-3.2.jar;then + cp -f $JAR_SOURCE/uuid-3.2.jar $OAT_SOURCE/HisClient/lib/uuid-3.2.jar +else + ShowLogFaild "$JAR_SOURCE/uuid-3.2.jar" +fi + + +if test -e $JAR_SOURCE/jaxb-impl-2.1.12.jar;then + cp -f $JAR_SOURCE/jaxb-impl-2.1.12.jar $OAT_SOURCE/WLMService/WebContent/WEB-INF/lib/jaxb-impl-2.1.12.jar + cp -f $JAR_SOURCE/jaxb-impl-2.1.12.jar $OAT_SOURCE/AttestationService/WebContent/WEB-INF/lib/jaxb-impl-2.1.12.jar +else + ShowLogFaild "$JAR_SOURCE/jaxb-impl-2.1.12.jar" +fi + + +if test -e $JAR_SOURCE/commons-logging-1.0.4.jar;then + cp -f $JAR_SOURCE/commons-logging-1.0.4.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/commons-logging-1.0.4.jar + cp -f $JAR_SOURCE/commons-logging-1.0.4.jar $OAT_SOURCE/PrivacyCA/lib/commons-logging-1.0.4.jar +else + ShowLogFaild "$JAR_SOURCE/commons-logging-1.0.4.jar" +fi + + +if test -e $JAR_SOURCE/commons-collections.jar;then + cp -f $JAR_SOURCE/commons-collections.jar $OAT_SOURCE/HisClient/lib/commons-collections.jar +else + ShowLogFaild "$JAR_SOURCE/commons-collections.jar" +fi + + +if test -e $JAR_SOURCE/bcprov-jdk15-129.jar;then + cp -f $JAR_SOURCE/bcprov-jdk15-129.jar $OAT_SOURCE/HisWebServices/WEB-INF/lib/bcprov-jdk15-129.jar +else + ShowLogFaild "$JAR_SOURCE/bcprov-jdk15-129.jar" +fi + +if test -e $JAR_SOURCE/jaxrpc.jar;then + cp -f $JAR_SOURCE/jaxrpc.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jaxrpc.jar + cp -f $JAR_SOURCE/jaxrpc.jar $OAT_SOURCE/PrivacyCA/lib/jaxrpc.jar + if test -d $OAT_SOURCE/TSSCoreService;then + cp -f $JAR_SOURCE/jaxrpc.jar $OAT_SOURCE/TSSCoreService/lib/jaxrpc.jar + fi +else + ShowLogFaild "$JAR_SOURCE/jaxrpc.jar" +fi + +if test -e $JAR_SOURCE/saaj.jar;then + if test -d $OAT_SOURCE/TSSCoreService;then + cp -f $JAR_SOURCE/saaj.jar $OAT_SOURCE/TSSCoreService/lib/saaj.jar + fi +else + ShowLogFaild "$JAR_SOURCE/saaj.jar" +fi + +if test -e $JAR_SOURCE/ant-antlr-1.6.5.jar;then + if test -d $OAT_SOURCE/TSSCoreService;then + cp -f $JAR_SOURCE/ant-antlr-1.6.5.jar $OAT_SOURCE/TSSCoreService/lib/ant-antlr-1.6.5.jar + fi +else + ShowLogFaild "$JAR_SOURCE/ant-antlr-1.6.5.jar" +fi + +if test -e $JAR_SOURCE/apache-tomcat-6.0.29.tar.gz;then + cp -f $JAR_SOURCE/apache-tomcat-6.0.29.tar.gz ../Installer/FilesForLinux +else + ShowLogFaild "$JAR_SOURCE/apache-tomcat-6.0.29.tar.gz" +fi + +####### SALlib ##### +cp -f $JAR_SOURCE/hibernate3.jar $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/SALlib_hibernate3.jar +cp -f $JAR_SOURCE/log4j-1.2.8.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_log4j-1.2.8.jar +cp -f $JAR_SOURCE/cglib-2.1.3.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_cglib-2.1.3.jar +cp -f $JAR_SOURCE/commons-cli-1.0.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_commons-cli-1.0.jar +cp -f $JAR_SOURCE/jtds-1.2.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_jtds-1.2.jar +cp -f $JAR_SOURCE/jdbc2_0-stdext.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_jdbc2_0-stdext.jar +cp -f $JAR_SOURCE/xsdlib.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_xsdlib.jar +cp -f $JAR_SOURCE/jta.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_jta.jar +cp -f $JAR_SOURCE/mail.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_mail.jar +cp -f $JAR_SOURCE/relaxngDatatype.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_relaxngDatatype.jar +cp -f $JAR_SOURCE/commons-httpclient-3.0.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_commons-httpclient-3.0.jar +cp -f $JAR_SOURCE/hibernate3.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_hibernate3.jar +cp -f $JAR_SOURCE/commons-logging.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_commons-logging.jar +cp -f $JAR_SOURCE/dom4j-1.6.1.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_dom4j-1.6.1.jar +cp -f $JAR_SOURCE/jaas.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_jaas.jar +cp -f $JAR_SOURCE/c3p0-0.9.0.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_c3p0-0.9.0.jar +cp -f $JAR_SOURCE/asm.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_asm.jar +cp -f $JAR_SOURCE/commons-codec-1.3.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_commons-codec-1.3.jar +cp -f $JAR_SOURCE/commons-beanutils.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_commons-beanutils.jar +cp -f $JAR_SOURCE/commons-digester.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_commons-digester.jar +cp -f $JAR_SOURCE/commons-collections-2.1.1.jar $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_commons-collections-2.1.1.jar +cp -f $JAR_SOURCE/hibernate3.jar $OAT_SOURCE/PrivacyCA/lib/SALlib_hibernate3.jar + +####### xsd ##### +cp -f xsd/*.xsd $OAT_SOURCE/HisAppraiser/xml/Integrity_Report_Manifest_v1_0/ +cp -f xsd/*.xsd $OAT_SOURCE/HisClient/xml/Integrity_Report_Manifest_v1_0/ diff --git a/OpenAttestation/Source/download_jar_package_list.txt b/OpenAttestation/Source/download_jar_package_list.txt new file mode 100644 index 0000000..afd9054 --- /dev/null +++ b/OpenAttestation/Source/download_jar_package_list.txt @@ -0,0 +1,73 @@ +activation.jar-----http://www.docjar.com/jar/activation-1.0.2.jar +asm.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/asm/asm/1.5.3/asm-1.5.3.jar +asm-3.1.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/asm/asm/3.1/asm-3.1.jar +bcprov-jdk15-143.jar-----http://www.docjar.com/jar/bcprov-jdk15-143.jar +c3p0-0.9.0.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/c3p0/c3p0/0.9.0/c3p0-0.9.0.jar +cglib-2.1.3.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/cglib/cglib/2.1_3/cglib-2.1_3.jar +cglib-2.2.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/cglib/cglib/2.2/cglib-2.2.jar +commons-beanutils.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/commons-beanutils/commons-beanutils/1.6/commons-beanutils-1.6.jar +commons-cli-1.0.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/commons-cli/commons-cli/1.0/commons-cli-1.0.jar +commons-codec-1.3.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/commons-codec/commons-codec/1.3/commons-codec-1.3.jar +commons-codec-1.4.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/commons-codec/commons-codec/1.4/commons-codec-1.4.jar +commons-collections-2.1.1.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/commons-collections/commons-collections/2.1.1/commons-collections-2.1.1.jar +commons-digester.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven/commons-digester/jars/commons-digester-1.6.jar +commons-httpclient-3.0.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/commons-httpclient/commons-httpclient/3.0/commons-httpclient-3.0.jar +commons-logging-1.0.4.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/commons-logging/commons-logging/1.0.4/commons-logging-1.0.4.jar +commons-logging-1.1.1.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar +dom4j-1.6.1.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar +FastInfoset.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/com/sun/xml/fastinfoset/FastInfoset/1.2.4/FastInfoset-1.2.4.jar +hibernate3.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven/org.hibernate/jars/hibernate-3.1.3.jar +jaas.jar-----http://www.docjar.com/jar/jaas.jar +jackson-core-asl-1.8.3.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/org/codehaus/jackson/jackson-core-asl/1.8.3/jackson-core-asl-1.8.3.jar +jackson-jaxrs-1.8.3.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/org/codehaus/jackson/jackson-jaxrs/1.8.3/jackson-jaxrs-1.8.3.jar +jackson-mapper-asl-1.8.3.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/org/codehaus/jackson/jackson-mapper-asl/1.8.3/jackson-mapper-asl-1.8.3.jar +jackson-xc-1.8.3.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/org/codehaus/jackson/jackson-xc/1.8.3/jackson-xc-1.8.3.jar +jaxb-api.jar-----http://download.java.net/maven/1/javax.xml.bind/jars/jaxb-api-2.1.jar +jaxb-impl-2.1.12.jar-----http://download.java.net/maven/1/com.sun.xml.bind/jars/jaxb-impl-2.1.12.jar +jaxb-xjc.jar-----http://download.java.net/maven/1/com.sun.xml.bind/jars/jaxb-xjc-2.1.11.jar +jax-qname.jar-----http://www.docjar.com/jar/jax-qname.jar +jaxws-api.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/javax/xml/ws/jaxws-api/2.1/jaxws-api-2.1.jar +jaxws-rt.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/com/sun/xml/ws/jaxws-rt/2.1.7/jaxws-rt-2.1.7.jar +jaxws-tools.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/com/sun/xml/ws/jaxws-tools/2.1.7/jaxws-tools-2.1.7.jar +jdbc2_0-stdext.jar-----http://www.docjar.com/jar/jdbc2_0-stdext.jar +jersey-bundle-1.9.1.jar-----http://repo1.maven.org/maven2/com/sun/jersey/jersey-bundle/1.9.1/jersey-bundle-1.9.1.jar +jersey-client-1.9.1.jar-----http://repo1.maven.org/maven2/com/sun/jersey/jersey-client/1.9.1/jersey-client-1.9.1.jar +jersey-core-1.9.1.jar-----https://maven.java.net/service/local/artifact/maven/redirect?r=releases&g=com.sun.jersey&a=jersey-core&v=1.9.1&e=jar +jersey-json-1.9.1.jar-----https://maven.java.net/service/local/artifact/maven/redirect?r=releases&g=com.sun.jersey&a=jersey-json&v=1.9.1&e=jar +jersey-server-1.9.1.jar-----https://maven.java.net/service/local/artifact/maven/redirect?r=releases&g=com.sun.jersey&a=jersey-server&v=1.9.1&e=jar +jettison-1.1.jar-----http://search.maven.org/remotecontent?filepath=org/bluestemsoftware/open/maven/tparty/jettison/1.1/jettison-1.1.jar +jsr173_api.jar-----http://www.docjar.com/jar/jsr173_api.jar +jsr181-api.jar-----http://www.docjar.com/jar/jsr181-api.jar +jsr250-api.jar-----http://www.docjar.com/jar/jsr250-api.jar +jsr311-api-1.1.1.jar-----http://www.docjar.com/jar/jsr311-api-1.1.1.jar +jta.jar-----http://www.docjar.com/jar/jta.jar +jtds-1.2.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/net/sourceforge/jtds/jtds/1.2/jtds-1.2.jar +log4j-1.2.8.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/log4j/log4j/1.2.8/log4j-1.2.8.jar +mail.jar-----http://www.docjar.com/jar/mail-1.3.1.jar +mimepull.jar-----http://www.docjar.com/jar/mimepull-1.2.jar +mysql-connector-java-5.0.7-bin.jar-----http://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/5.0.7/mysql-connector-java-5.0.7.jar +org.springframework.context.support-3.0.3.RELEASE.jar-----http://repository.springsource.com/ivy/bundles/release/org.springframework/org.springframework.context.support/3.0.3.RELEASE/org.springframework.context.support-3.0.3.RELEASE.jar +relaxngDatatype.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/activesoap/relaxngDatatype/1.5/relaxngDatatype-1.5.jar +resolver.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/com/sun/org/apache/xml/internal/resolver/20050927/resolver-20050927.jar +saaj-api.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/xfire/saaj-api/1.3/saaj-api-1.3.jar +saaj-impl.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/xfire/saaj-impl/1.3/saaj-impl-1.3.jar +servlet.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/tomcat/servlet/4.1.36/servlet-4.1.36.jar +servlet-api.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/javax/servlet/servlet-api/2.4/servlet-api-2.4.jar +stax-ex.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/org/jvnet/staxex/stax-ex/1.2/stax-ex-1.2.jar +streambuffer.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/com/sun/xml/stream/buffer/streambuffer/0.8/streambuffer-0.8.jar +woodstox.jar-----http://www.docjar.com/jar/org.apache.servicemix.bundles.woodstox-3.2.7_1.jar +xsdlib.jar-----http://www.docjar.com/jar/xsdlib.jar +jaxb-libs.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/xfire/jaxb-libs/1.0.5/jaxb-libs-1.0.5.jar +jta-spec1_0_1.jar-----http://www.docjar.com/jar/jta-spec1_0_1.jar +log4j-1.2.14.jar-----http://search.maven.org/remotecontent?filepath=org/mod4j/org/eclipse/xtext/log4j/1.2.15/log4j-1.2.15.jar +uuid-3.2.jar-----http://search.maven.org/remotecontent?filepath=com/eaio/uuid/uuid/3.2/uuid-3.2.jar +jsp-api.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/javax/servlet/jsp-api/2.0/jsp-api-2.0.jar +commons-discovery-0.2.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/commons-discovery/commons-discovery/0.2/commons-discovery-0.2.jar +wsdl4j-1.5.1.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/wsdl4j/wsdl4j/1.5.1/wsdl4j-1.5.1.jar +axis.jar-----http://mirrors.ibiblio.org/pub/mirrors/maven2/axis/axis/1.2.1/axis-1.2.1.jar +ant-antlr-1.6.5.jar-----http://www.docjar.com/jar/ant-antlr-1.6.5.jar +saaj.jar-----http://www.docjar.com/jar/saaj.jar +apache-tomcat-6.0.29.tar.gz-----http://archive.apache.org/dist/tomcat/tomcat-6/v6.0.29/bin/apache-tomcat-6.0.29.tar.gz +jaxrpc.jar-----http://www.docjar.com/jar/jaxrpc.jar +Core_Integrity_Manifest_v1_0_1.xsd-----http://www.trustedcomputinggroup.org/files/static_page_files/20FAC57B-1D09-3519-AD4490200F9E7E84/Core_Integrity_Manifest_v1_0_1.xsd +Integrity_Report_Manifest_v1_0.xsd-----http://www.trustedcomputinggroup.org/files/static_page_files/20FB32DB-1D09-3519-ADEF68E9B28F1CF6/Integrity_Report_Manifest_v1_0.xsd diff --git a/OpenAttestation/Source/download_jar_packages.sh b/OpenAttestation/Source/download_jar_packages.sh new file mode 100644 index 0000000..3fec526 --- /dev/null +++ b/OpenAttestation/Source/download_jar_packages.sh @@ -0,0 +1,43 @@ +#!/bin/bash + +JAR_SOURCE_DIRCTORY=../JAR_SOURCE +DOWNLOAD_LOG=Download.log +[[ -d $JAR_SOURCE_DIRCTORY ]] && rm -rf $JAR_SOURCE_DIRCTORY + mkdir $JAR_SOURCE_DIRCTORY + +[[ -f $DOWNLOAD_LOG ]] && rm -f $DOWNLOAD_LOG + touch $DOWNLOAD_LOG + +DOWNLOAD_CONTENT=`cat download_jar_package_list.txt` + +for DOWNLOAD_FILE_NAME in $DOWNLOAD_CONTENT +do + LOCAL_NAME=`echo "$DOWNLOAD_FILE_NAME" | awk -F"-----" '{print $1}'` + DOWNLOAD_PATH=`echo "$DOWNLOAD_FILE_NAME" | awk -F"-----" '{print $2}'` + echo "$LOCAL_NAME $DOWNLOAD_PATH" + #most downlaod times + key=5 + while [ $key -gt 0 ] + do + key=$(expr $key - 1) + wget -t 1 -O ../JAR_SOURCE/$LOCAL_NAME $DOWNLOAD_PATH + STAT=$? + [ $STAT == 0 ] && break + echo "Download file [ $LOCAL_NAME ] $(expr 5 - $key) th" >> $DOWNLOAD_LOG + rm -f $JAR_SOURCE_DIRCTORY/$LOCAL_NAME + done + + if [ $key -eq 0 ];then + echo "Download file [ $LOCAL_NAME ] from [ $DOWNLOAD_PATH ] failed!" >> $DOWNLOAD_LOG + rm -f $JAR_SOURCE_DIRCTORY/$LOCAL_NAME + fi + +done + +cd $JAR_SOURCE_DIRCTORY +cp commons-collections-2.1.1.jar commons-collections.jar +cp commons-logging-1.0.4.jar commons-logging.jar +cp jaxb-impl-2.1.12.jar jaxb-impl.jar +cp bcprov-jdk15-143.jar bcprov-jdk15-129.jar +mv bcprov-jdk15-143.jar bcprov-jdk15-141.jar + diff --git a/OpenAttestation/Source/remove_jar_packages.sh b/OpenAttestation/Source/remove_jar_packages.sh new file mode 100644 index 0000000..3381641 --- /dev/null +++ b/OpenAttestation/Source/remove_jar_packages.sh @@ -0,0 +1,661 @@ +#!/bin/sh +# Remove Jar package +OAT_SOURCE=../Source + +echo "activation.jar" + rm -rf $OAT_SOURCE/HisClient/lib/activation.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/activation.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/activation.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/activation.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/activation.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/activation.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/activation.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/activation.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/activation.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/activation.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/activation.jar + rm -rf $OAT_SOURCE/TSSCoreService/lib/activation.jar + +echo "asm.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/asm.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/asm.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/asm.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/asm.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/asm.jar + rm -rf $OAT_SOURCE/TSSCoreService/lib/asm.jar + +echo "asm-3.1.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/asm-3.1.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/asm-3.1.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/asm-3.1.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/asm-3.1.jar + + +echo "bcprov-jdk15-141.jar" + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/bcprov-jdk15-141.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/bcprov-jdk15-141.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/bcprov-jdk15-141.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/bcprov-jdk15-141.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/bcprov-jdk15-141.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/bcprov-jdk15-141.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/bcprov-jdk15-141.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/bcprov-jdk15-141.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/bcprov-jdk15-141.jar + + +echo "c3p0-0.9.0.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/c3p0-0.9.0.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/c3p0-0.9.0.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/c3p0-0.9.0.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/c3p0-0.9.0.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/c3p0-0.9.0.jar + + +echo "cglib-2.1.3.jar" + rm -rf $OAT_SOURCE/HisAppraiser/lib/cglib-2.1.3.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/cglib-2.1.3.jar + rm -rf $OAT_SOURCE/TSSCoreService/lib/cglib-2.1.3.jar + +echo "cglib-2.2.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/cglib-2.2.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/cglib-2.2.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/cglib-2.2.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/cglib-2.2.jar + + +echo "commons-beanutils.jar" + rm -rf $OAT_SOURCE/HisClient/lib/commons-beanutils.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/commons-beanutils.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/commons-beanutils.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/commons-beanutils.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/commons-beanutils.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/commons-beanutils.jar + + +echo "commons-cli-1.0.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/commons-cli-1.0.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/commons-cli-1.0.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/commons-cli-1.0.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/commons-cli-1.0.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/commons-cli-1.0.jar + + +echo "commons-codec-1.3.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/commons-codec-1.3.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/commons-codec-1.3.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/commons-codec-1.3.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/commons-codec-1.3.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/commons-codec-1.3.jar + + +echo "commons-codec-1.4.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/commons-codec-1.4.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/commons-codec-1.4.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/commons-codec-1.4.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/commons-codec-1.4.jar + + +echo "commons-collections-2.1.1.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/commons-collections-2.1.1.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/commons-collections-2.1.1.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/commons-collections-2.1.1.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/commons-collections-2.1.1.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/commons-collections-2.1.1.jar + rm -rf $OAT_SOURCE/TSSCoreService/lib/commons-collections-2.1.1.jar + +echo "commons-digester.jar" + rm -rf $OAT_SOURCE/HisClient/lib/commons-digester.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/commons-digester.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/commons-digester.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/commons-digester.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/commons-digester.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/commons-digester.jar + + +echo "commons-httpclient-3.0.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/commons-httpclient-3.0.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/commons-httpclient-3.0.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/commons-httpclient-3.0.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/commons-httpclient-3.0.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/commons-httpclient-3.0.jar + + +echo "commons-logging.jar" + rm -rf $OAT_SOURCE/HisClient/lib/commons-logging.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/commons-logging.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/commons-logging.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/commons-logging.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/commons-logging.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/commons-logging.jar + rm -rf $OAT_SOURCE/TSSCoreService/lib/commons-logging.jar + +echo "commons-logging-1.1.1.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/commons-logging-1.1.1.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/commons-logging-1.1.1.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/commons-logging-1.1.1.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/commons-logging-1.1.1.jar + + +echo "dom4j-1.6.1.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/dom4j-1.6.1.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/dom4j-1.6.1.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/dom4j-1.6.1.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/dom4j-1.6.1.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/dom4j-1.6.1.jar + rm -rf $OAT_SOURCE/TSSCoreService/lib/dom4j-1.6.1.jar + +echo "FastInfoset.jar" + rm -rf $OAT_SOURCE/HisClient/lib/FastInfoset.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/FastInfoset.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/FastInfoset.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/FastInfoset.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/FastInfoset.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/FastInfoset.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/FastInfoset.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/FastInfoset.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/FastInfoset.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/FastInfoset.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/FastInfoset.jar + + +echo "hibernate3.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/hibernate3.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/hibernate3.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/hibernate3.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/hibernate3.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/hibernate3.jar + + +echo "jaas.jar" + rm -rf $OAT_SOURCE/HisClient/lib/jaas.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jaas.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jaas.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jaas.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jaas.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jaas.jar + + +echo "jackson-core-asl-1.8.3.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jackson-core-asl-1.8.3.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jackson-core-asl-1.8.3.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jackson-core-asl-1.8.3.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jackson-core-asl-1.8.3.jar + + +echo "jackson-jaxrs-1.8.3.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jackson-jaxrs-1.8.3.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jackson-jaxrs-1.8.3.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jackson-jaxrs-1.8.3.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jackson-jaxrs-1.8.3.jar + + +echo "jackson-mapper-asl-1.8.3.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jackson-mapper-asl-1.8.3.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jackson-mapper-asl-1.8.3.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jackson-mapper-asl-1.8.3.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jackson-mapper-asl-1.8.3.jar + + +echo "jackson-xc-1.8.3.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jackson-xc-1.8.3.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jackson-xc-1.8.3.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jackson-xc-1.8.3.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jackson-xc-1.8.3.jar + + +echo "jaxb-api.jar" + rm -rf $OAT_SOURCE/HisClient/lib/jaxb-api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jaxb-api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jaxb-api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jaxb-api.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jaxb-api.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jaxb-api.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/jaxb-api.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jaxb-api.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/jaxb-api.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jaxb-api.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jaxb-api.jar + + +echo "jaxb-impl.jar" + rm -rf $OAT_SOURCE/HisClient/lib/jaxb-impl.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jaxb-impl.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jaxb-impl.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jaxb-impl.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jaxb-impl.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jaxb-impl.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/jaxb-impl.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jaxb-impl.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/jaxb-impl.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jaxb-impl.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jaxb-impl.jar + + +echo "jaxb-xjc.jar" + rm -rf $OAT_SOURCE/HisClient/lib/jaxb-xjc.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jaxb-xjc.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jaxb-xjc.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jaxb-xjc.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jaxb-xjc.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jaxb-xjc.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/jaxb-xjc.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jaxb-xjc.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/jaxb-xjc.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jaxb-xjc.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jaxb-xjc.jar + + +echo "jax-qname.jar" + rm -rf $OAT_SOURCE/HisClient/lib/jax-qname.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jax-qname.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jax-qname.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jax-qname.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jax-qname.jar + + +echo "jaxws-api.jar" + rm -rf $OAT_SOURCE/HisClient/lib/jaxws-api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jaxws-api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jaxws-api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jaxws-api.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jaxws-api.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jaxws-api.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/jaxws-api.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jaxws-api.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/jaxws-api.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jaxws-api.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jaxws-api.jar + + +echo "jaxws-rt.jar" + rm -rf $OAT_SOURCE/HisClient/lib/jaxws-rt.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jaxws-rt.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jaxws-rt.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jaxws-rt.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jaxws-rt.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jaxws-rt.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/jaxws-rt.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jaxws-rt.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/jaxws-rt.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jaxws-rt.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jaxws-rt.jar + + +echo "jaxws-tools.jar" + rm -rf $OAT_SOURCE/HisClient/lib/jaxws-tools.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jaxws-tools.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jaxws-tools.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jaxws-tools.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jaxws-tools.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jaxws-tools.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/jaxws-tools.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jaxws-tools.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/jaxws-tools.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jaxws-tools.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jaxws-tools.jar + + +echo "jdbc2_0-stdext.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jdbc2_0-stdext.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jdbc2_0-stdext.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jdbc2_0-stdext.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jdbc2_0-stdext.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jdbc2_0-stdext.jar + + +echo "jersey-bundle-1.9.1.jar" + rm -rf $OAT_SOURCE/HisAppraiser/lib/jersey-bundle-1.9.1.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jersey-bundle-1.9.1.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jersey-bundle-1.9.1.jar + + +echo "jersey-client-1.9.1.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jersey-client-1.9.1.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jersey-client-1.9.1.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jersey-client-1.9.1.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jersey-client-1.9.1.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jersey-client-1.9.1.jar + + +echo "jersey-core-1.9.1.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jersey-core-1.9.1.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jersey-core-1.9.1.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jersey-core-1.9.1.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jersey-core-1.9.1.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jersey-core-1.9.1.jar + + +echo "jersey-json-1.9.1.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jersey-json-1.9.1.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jersey-json-1.9.1.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jersey-json-1.9.1.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jersey-json-1.9.1.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jersey-json-1.9.1.jar + + +echo "jersey-server-1.9.1.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jersey-server-1.9.1.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jersey-server-1.9.1.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jersey-server-1.9.1.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jersey-server-1.9.1.jar + + +echo "jettison-1.1.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jettison-1.1.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jettison-1.1.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jettison-1.1.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jettison-1.1.jar + + +echo "jsr173_api.jar" + rm -rf $OAT_SOURCE/HisClient/lib/jsr173_api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jsr173_api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jsr173_api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jsr173_api.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jsr173_api.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jsr173_api.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/jsr173_api.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jsr173_api.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/jsr173_api.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jsr173_api.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jsr173_api.jar + + +echo "jsr181-api.jar" + rm -rf $OAT_SOURCE/HisClient/lib/jsr181-api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jsr181-api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jsr181-api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jsr181-api.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jsr181-api.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jsr181-api.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/jsr181-api.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jsr181-api.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/jsr181-api.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jsr181-api.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jsr181-api.jar + + +echo "jsr250-api.jar" + rm -rf $OAT_SOURCE/HisClient/lib/jsr250-api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/jsr250-api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jsr250-api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/jsr250-api.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jsr250-api.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jsr250-api.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/jsr250-api.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jsr250-api.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/jsr250-api.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jsr250-api.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jsr250-api.jar + + +echo "jsr311-api-1.1.1.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jsr311-api-1.1.1.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jsr311-api-1.1.1.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jsr311-api-1.1.1.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jsr311-api-1.1.1.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jsr311-api-1.1.1.jar + + +echo "jta.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jta.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jta.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jta.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jta.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jta.jar + + +echo "jtds-1.2.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/jtds-1.2.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/jtds-1.2.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jtds-1.2.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/jtds-1.2.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/jtds-1.2.jar + + +echo "log4j-1.2.8.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/log4j-1.2.8.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/log4j-1.2.8.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/log4j-1.2.8.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/log4j-1.2.8.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/log4j-1.2.8.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/log4j-1.2.8.jar + + +echo "mail.jar" + rm -rf $OAT_SOURCE/HisClient/lib/mail.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/mail.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/mail.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/mail.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/mail.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/mail.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/mail.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/mail.jar + rm -rf $OAT_SOURCE/TSSCoreService/lib/mail.jar + +echo "mimepull.jar" + rm -rf $OAT_SOURCE/HisClient/lib/mimepull.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/mimepull.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/mimepull.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/mimepull.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/mimepull.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/mimepull.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/mimepull.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/mimepull.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/mimepull.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/mimepull.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/mimepull.jar + + +echo "mysql-connector-java-5.0.7-bin.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/mysql-connector-java-5.0.7-bin.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/mysql-connector-java-5.0.7-bin.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/mysql-connector-java-5.0.7-bin.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/mysql-connector-java-5.0.7-bin.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/mysql-connector-java-5.0.7-bin.jar + + +echo "org.springframework.context.support-3.0.3.RELEASE.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/org.springframework.context.support-3.0.3.RELEASE.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/org.springframework.context.support-3.0.3.RELEASE.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/org.springframework.context.support-3.0.3.RELEASE.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/org.springframework.context.support-3.0.3.RELEASE.jar + + +echo "relaxngDatatype.jar" + rm -rf $OAT_SOURCE/HisClient/lib/relaxngDatatype.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/relaxngDatatype.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/relaxngDatatype.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/relaxngDatatype.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/relaxngDatatype.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/relaxngDatatype.jar + + +echo "resolver.jar" + rm -rf $OAT_SOURCE/HisClient/lib/resolver.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/resolver.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/resolver.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/resolver.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/resolver.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/resolver.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/resolver.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/resolver.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/resolver.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/resolver.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/resolver.jar + + +echo "saaj-api.jar" + rm -rf $OAT_SOURCE/HisClient/lib/saaj-api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/saaj-api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/saaj-api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/saaj-api.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/saaj-api.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/saaj-api.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/saaj-api.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/saaj-api.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/saaj-api.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/saaj-api.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/saaj-api.jar + + +echo "saaj-impl.jar" + rm -rf $OAT_SOURCE/HisClient/lib/saaj-impl.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/saaj-impl.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/saaj-impl.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/saaj-impl.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/saaj-impl.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/saaj-impl.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/saaj-impl.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/saaj-impl.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/saaj-impl.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/saaj-impl.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/saaj-impl.jar + + +echo "servlet.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/servlet.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/servlet.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/servlet.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/servlet.jar + + +echo "servlet-api.jar" + rm -rf $OAT_SOURCE/HisClient/lib/servlet-api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/servlet-api.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/jars-compile-only/servlet-api.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/servlet-api.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/servlet-api.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/servlet-api.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/servlet-api.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/jars-compile-only/servlet-api.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/servlet-api.jar + + +echo "stax-ex.jar" + rm -rf $OAT_SOURCE/HisClient/lib/stax-ex.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/stax-ex.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/stax-ex.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/stax-ex.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/stax-ex.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/stax-ex.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/stax-ex.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/stax-ex.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/stax-ex.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/stax-ex.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/stax-ex.jar + + +echo "streambuffer.jar" + rm -rf $OAT_SOURCE/HisClient/lib/streambuffer.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/streambuffer.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/streambuffer.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/streambuffer.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/streambuffer.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/streambuffer.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/streambuffer.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/streambuffer.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/streambuffer.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/streambuffer.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/streambuffer.jar + + +echo "woodstox.jar" + rm -rf $OAT_SOURCE/HisClient/lib/woodstox.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/clientlib/woodstox.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/woodstox.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/woodstox.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/woodstox.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/woodstox.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/woodstox.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/woodstox.jar + rm -rf $OAT_SOURCE/HisWebServices/clientlib/woodstox.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/woodstox.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/woodstox.jar + + +echo "xsdlib.jar" + rm -rf $OAT_SOURCE/HisClient/lib/xsdlib.jar + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/xsdlib.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/xsdlib.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/xsdlib.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/xsdlib.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/xsdlib.jar + + +echo "commons-cli-1.0.jar" + rm -rf $OAT_SOURCE/OpenAttestationAdminConsole/WebContent/WEB-INF/lib/commons-cli-1.0.jar + rm -rf $OAT_SOURCE/HisAppraiser/lib/commons-cli-1.0.jar + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/commons-cli-1.0.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/commons-cli-1.0.jar + rm -rf $OAT_SOURCE/OpenAttestationManifestWebServices/WebContent/WEB-INF/lib/commons-cli-1.0.jar + + +echo "jsp-api.jar" + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/jars-compile-only/jsp-api.jar + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/jars-compile-only/jsp-api.jar + + +echo "commons-discovery-0.2.jar" + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/commons-discovery-0.2.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/commons-discovery-0.2.jar + rm -rf $OAT_SOURCE/TSSCoreService/lib/commons-discovery-0.2.jar + +echo "wsdl4j-1.5.1.jar" + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/wsdl4j-1.5.1.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/wsdl4j-1.5.1.jar + rm -rf $OAT_SOURCE/TSSCoreService/lib/wsdl4j-1.5.1.jar + + +echo "axis.jar" + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/axis.jar + rm -rf $OAT_SOURCE/PrivacyCA/lib/axis.jar + rm -rf $OAT_SOURCE/TSSCoreService/lib/axis.jar + +echo "jaxb-libs.jar" + rm -rf $OAT_SOURCE/HisClient/lib/jaxb-libs.jar + + +echo "jta-spec1_0_1.jar" + rm -rf $OAT_SOURCE/HisClient/lib/jta-spec1_0_1.jar + + +echo "log4j-1.2.14.jar" + rm -rf $OAT_SOURCE/HisClient/lib/log4j-1.2.14.jar + + +echo "uuid-3.2.jar" + rm -rf $OAT_SOURCE/HisClient/lib/uuid-3.2.jar + + +echo "jaxb-impl-2.1.12.jar" + rm -rf $OAT_SOURCE/OpenAttestationWebServices/WebContent/WEB-INF/lib/jaxb-impl-2.1.12.jar + +echo "jaxrpc.jar" + rm -rf $OAT_SOURCE/PrivacyCA/lib/jaxrpc.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/jaxrpc.jar + rm -rf $OAT_SOURCE/TSSCoreService/lib/jaxrpc.jar + +echo "commons-logging-1.0.4.jar" + rm -rf $OAT_SOURCE/PrivacyCA/lib/commons-logging-1.0.4.jar + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/commons-logging-1.0.4.jar + +echo "SALlib_*" + rm -rf $OAT_SOURCE/PrivacyCA/lib/SALlib_* + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/ClientFiles/lib/SALlib_* + rm -rf $OAT_SOURCE/HisPrivacyCAWebServices2/WEB-INF/lib/SALlib_* + +echo "commons-collections.jar" + rm -rf $OAT_SOURCE/HisClient/lib/commons-collections.jar + +echo "bcprov-jdk15-129.jar" + rm -rf $OAT_SOURCE/HisWebServices/WEB-INF/lib/bcprov-jdk15-129.jar + +echo "ant-antlr-1.6.5.jar" + rm -rf $OAT_SOURCE/TSSCoreService/lib/ant-antlr-1.6.5.jar + +echo "saaj.jar" + rm -rf $OAT_SOURCE/TSSCoreService/lib/saaj.jar + +echo "jss4.jar" + rm -rf $OAT_SOURCE/TSSCoreService/lib/jss4.jar diff --git a/OpenAttestation/Source/xsd/Core_Integrity_Manifest_v1_0_1.xsd b/OpenAttestation/Source/xsd/Core_Integrity_Manifest_v1_0_1.xsd new file mode 100644 index 0000000..7edac47 --- /dev/null +++ b/OpenAttestation/Source/xsd/Core_Integrity_Manifest_v1_0_1.xsd @@ -0,0 +1,130 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/xsd/Integrity_Report_Manifest_v1_0.xsd b/OpenAttestation/Source/xsd/Integrity_Report_Manifest_v1_0.xsd new file mode 100644 index 0000000..8f5e742 --- /dev/null +++ b/OpenAttestation/Source/xsd/Integrity_Report_Manifest_v1_0.xsd @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/OpenAttestation/Source/xsd/Simple_Object_v1_0.xsd b/OpenAttestation/Source/xsd/Simple_Object_v1_0.xsd new file mode 100644 index 0000000..9c4c2bb --- /dev/null +++ b/OpenAttestation/Source/xsd/Simple_Object_v1_0.xsd @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Source/xsd/xmldsig-core-schema.xsd b/OpenAttestation/Source/xsd/xmldsig-core-schema.xsd new file mode 100644 index 0000000..8422fdf --- /dev/null +++ b/OpenAttestation/Source/xsd/xmldsig-core-schema.xsd @@ -0,0 +1,308 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/OpenAttestation/Test/README b/OpenAttestation/Test/README new file mode 100644 index 0000000..5ca878c --- /dev/null +++ b/OpenAttestation/Test/README @@ -0,0 +1,8 @@ +1. Run curl.sh or commandtool.sh to test basic functions +2. Enter "server name" and "port" +3. Type "quit" to create a new certificate file +4. See result at /tmp/Result +5. Add data into file 'forpoll.data' +6. Run pollhost.sh to populate Host specific data and test pollhosts interface +7. Enter "server name" and make sure 'certfile.cer' in the same folder + diff --git a/OpenAttestation/Test/commandtool.data b/OpenAttestation/Test/commandtool.data new file mode 100644 index 0000000..e6b7a5f --- /dev/null +++ b/OpenAttestation/Test/commandtool.data @@ -0,0 +1,12 @@ +Title : add : update : del : edge_length : over_length : RightSpecChar : WrongSpecChar +OEM_name OEMadd OEMup OEMdel OEM_edge_length_testdata_abcdefghijklmnopqrstuvwxy OEM_over_length_testdata_abcdefghijklmnopqrstuvwxyz OEMadd@ Oemadd# +OS_name OSadd OSup OSdel OS_edge_length_testdata_abcdefghijklmnopqrstuvwxyz OS_over_length_testdata_abcdefghijklmnopqrstuvwxyz0 OSadd@ OSadd# +OS_version osv1 osv2 osv3 osv_edge_length_testdata_abcdefghijklmnopqrstuvwxy osv_over_length_testdata_abcdefghijklmnopqrstuvwxyz osv1@ osv1# +MLE_Name_BIOS MLEBadd MLEBup MLEBdel MLEB_edge_length_testdata_abcdefghijklmnopqrstuvwx MLEB_over_length_testdata_abcdefghijklmnopqrstuvwxy MLEB@ MLEB# +MLE_Ver_BIOS mlebv1 mlebv2 mlebv3 mlebv_edge_length_testdata_abcdefghijklmnopqrstuvwmlebv_edge_length_testdata_abcdefghijklmnopqrstuvw mlebv_over_length_testdata_abcdefghijklmnopqrstuvwmlebv_over_length_testdata_abcdefghijklmnopqrstuvwx mlebv@ mlebv# +MLE_Name_VMM MLEVadd MLEVup MLEVdel MLEV_edge_length_testdata_abcdefghijklmnopqrstuvwx MLEV_over_length_testdata_abcdefghijklmnopqrstuvwxy MLEV@ MLEV# +MLE_Ver_VMM mlevv1 mlevv2 mlevv3 mlevv_edge_length_testdata_abcdefghijklmnopqrstuvwmlevv_edge_length_testdata_abcdefghijklmnopqrstuvw mlevv_over_length_testdata_abcdefghijklmnopqrstuvwmlevv_over_length_testdata_abcdefghijklmnopqrstuvwx mlevv@ mlevv# +PCR_Num 0 1 2 1000000000 20000000000 2@ 2# +PCR_Value 00000 99999 88888 FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 00000@ 00000# +HOST_Name HOSTadd HOSTup HOSTdel HOST_edge_length_testdata_abcdefghijklmnopqrstuvwx HOST_over_length_testdata_abcdefghijklmnopqrstuvwxy HOSTad@ HOSTad# +Description Descadd Descup Desdel Descr_edge_length_testdata_abcdefghijklmnopqrstuvwDescr_edge_length_testdata_abcdefghijklmnopqrstuvw Descr_over_length_testdata_abcdefghijklmnopqrstuvwDescr_over_length_testdata_abcdefghijklmnopqrstuvwx Descr@ Descr# diff --git a/OpenAttestation/Test/commandtool.sh b/OpenAttestation/Test/commandtool.sh new file mode 100644 index 0000000..7d11245 --- /dev/null +++ b/OpenAttestation/Test/commandtool.sh @@ -0,0 +1,1868 @@ +#!/bin/bash + +######################################################### +# The script for test MTW API # +######################################################### + +# Get OAT server name and create cert file +echo -n "Please enter the OAT server name[default:localhost]: " +read HOST_NAME +if [ "$HOST_NAME" = "" ];then + HOST_NAME=localhost +fi +./oat_cert -h $HOST_NAME > /tmp/cert.log +if [ -z "`cat /tmp/cert.log`" ];then + echo "The host $HOST_NAME can not connect, Exit..." + exit 1 +fi + +if [ -f /tmp/Result ];then + rm -f /tmp/Result +fi + +echo "Auto test script is running, please waitting..." + +echo "#The result about OEM" >> /tmp/Result +echo "******************Add OEM normal******************************************" >> /tmp/Result +# Add OEM successful (normal) +echo -n "Add OEM successful (normal) : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` # Get OEM Name +OEM_DESC=`awk 'NR==12 {print $2;}' commandtool.data` # Get Description +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +./oat_oem -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +# Add OEM fail (normal) +echo -n "Add OEM fail (normal) : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +OEM_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +./oat_oem -a -h $HOST_NAME $INFO > /tmp/res +grep "error_message" /tmp/res > /dev/null +EID=$? +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + ./oat_oem -a -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +elif [ $EID -eq 0 ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************Add OEM with checking boundary value********************" >> /tmp/Result +# Add OEM with null string +echo -n "Add OEM with null string : " >> /tmp/Result +OEM_TMP="" +OEM_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +./oat_oem -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add OEM with edge length string +echo -n "Add OEM with edge lenth string : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $5;}' commandtool.data` +OEM_DESC=`awk 'NR==12 {print $5;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +./oat_oem -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add OEM with over length string +echo -n "Add OEM with over length string : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $6;}' commandtool.data` +OEM_DESC=`awk 'NR==12 {print $6;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +./oat_oem -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************Add OEM with checking special character******************" >> /tmp/Result +# Add OEM success with special char +echo -n "Add OEM success with special char : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $7;}' commandtool.data` +OEM_DESC=`awk 'NR==12 {print $7;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +./oat_oem -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi +# Add OEM fail with special char +echo -n "Add OEM fail with special char : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $8;}' commandtool.data` +OEM_DESC=`awk 'NR==12 {print $8;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +./oat_oem -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************Edit OEM normal*****************************************" >> /tmp/Result +# Edit OEM successful (normal) +echo -n "Edit OEM successful (normal) : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $3;}' commandtool.data` +OEM_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +./oat_oem -a -h $HOST_NAME $INFO > /tmp/res +grep "error_message" /tmp/res > /dev/null +EID=$? +OEM_DESC=`awk 'NR==12 {print $3;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + ./oat_oem -e -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +elif [ $EID -eq 0 ];then + ./oat_oem -e -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +else + echo "Failed" >> /tmp/Result +fi + +# Edit OEM fail (normal) +echo -n "Edit OEM fail (normal) : " >> /tmp/Result +OEM_TMP=OEMnone +OEM_DESC=`awk 'NR==12 {print $6;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +./oat_oem -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************Edit OEM with checking boundary value******************" >> /tmp/Result +# Edit OEM with null string +echo -n "Edit OEM with null string : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $3;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"\"}"` +./oat_oem -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Edit OEM with edge length string +echo -n "Edit OEM with edge length string : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $3;}' commandtool.data` +OEM_DESC=`awk 'NR==12 {print $5;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +./oat_oem -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Edit OEM with over length string +echo -n "Edit OEM with over length string : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $3;}' commandtool.data` +OEM_DESC=`awk 'NR==12 {print $6;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +./oat_oem -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************Edit OEM with checking special character****************" >> /tmp/Result +# Edit OEM success with special char +echo -n "Edit OEM success with special char : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $3;}' commandtool.data` +OEM_DESC=`awk 'NR==12 {print $7;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +./oat_oem -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Edit OEM fail with special char +echo -n "Edit OEM fail with special char : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $3;}' commandtool.data` +OEM_DESC=`awk 'NR==12 {print $8;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +./oat_oem -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************Delete OEM normal**************************************" >> /tmp/Result +# Delete OEM successful (normal) +echo -n "Delete OEM successful (normal) : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $4;}' commandtool.data` +OEM_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +./oat_oem -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + INFO=`echo "{\"Name\":\"$OEM_TMP\"}"` + ./oat_oem -d -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +else + echo "Failed" >> /tmp/Result +fi + +# Delete OEM fail (normal) +echo -n "Delete non-existent OEM fail (normal) : " >> /tmp/Result +OEM_TMP=OEMnone +INFO=`echo "{\"Name\":\"$OEM_TMP\"}"` +./oat_oem -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************Delete OEM with checking boundary value*****************" >> /tmp/Result +# Delete OEM with null string +echo -n "Delete OEM with null string : " >> /tmp/Result +OEM_TMP="" +INFO=`echo "{\"Name\":\"$OEM_TMP\"}"` +./oat_oem -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Delete OEM with edge length string +echo -n "Delete OEM with edge length string : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $5;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\"}"` +./oat_oem -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************Delete OEM with checking special character**************" >> /tmp/Result +# Delete OEM with special char +echo -n "Delete OEM with special char : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $7;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\"}"` +./oat_oem -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************View OEM************************************************" >> /tmp/Result +# View OEM +echo -n "View OEM : " >> /tmp/Result +./oat_view_oem -h $HOST_NAME > /tmp/res +VIEW=`awk -F "\"" '{print $2;}' /tmp/res` +if [ "$VIEW" = "oem" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "#The result about OS" >> /tmp/Result +echo "******************Add OS normal*******************************************" >> /tmp/Result +# Add OS successful (normal) +echo -n "Add OS successful (normal) : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +OS_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +./oat_os -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +# Add OS fail (normal) +echo -n "Add OS fail (normal) : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +OS_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +./oat_os -a -h $HOST_NAME $INFO > /tmp/res +grep "error_message" /tmp/res > /dev/null +EID=$? +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + ./oat_os -a -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed " >> /tmp/Result + else + echo "Failed " >> /tmp/Result + fi +elif [ $EID -eq 0 ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +echo "******************Add OS with checking boundary value*********************" >> /tmp/Result +# Add OS with null string +echo -n "Add OS with null string : " >> /tmp/Result +OS_TMP="" +OS_VER="" +OS_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +./oat_os -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add OS with edge length string +echo -n "Add OS with edge length string : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $5;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $5;}' commandtool.data` +OS_DESC=`awk 'NR==12 {print $5;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +./oat_os -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add OS with over length string +echo -n "Add OS with over length string : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $6;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $6;}' commandtool.data` +OS_DESC=`awk 'NR==12 {print $6;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +./oat_os -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************Add OS with checking special character******************" >> /tmp/Result +# Add OS success with special char +echo -n "Add OS success with special char : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $7;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $7;}' commandtool.data` +OS_DESC=`awk 'NR==12 {print $7;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +./oat_os -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi +# Add OS fail with special char +echo -n "Add OS fail with special char : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $8;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $8;}' commandtool.data` +OS_DESC=`awk 'NR==12 {print $8;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +./oat_os -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************Edit OS normal*****************************************" >> /tmp/Result +# Edit OS successful (normal) +echo -n "Edit OS successful (normal) : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $3;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $3;}' commandtool.data` +OS_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +./oat_os -a -h $HOST_NAME $INFO > /tmp/res +grep "error_message" /tmp/res > /dev/null +EID=$? +OS_DESC=`awk 'NR==12 {print $3;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + ./oat_os -e -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +elif [ $EID -eq 0 ];then + ./oat_os -e -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +else + echo "Failed" >> /tmp/Result +fi + +# Edit OS fail (normal) +echo -n "Edit OS fail (normal) : " >> /tmp/Result +OS_TMP=OSnone +OS_VER=osv0 +OS_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +./oat_os -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************Edit OS with checking boundary value******************" >> /tmp/Result +# Edit OS with null string +echo -n "Edit OEM with null string : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $3;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $3;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"\"}"` +./oat_os -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Edit OS with edge length string +echo -n "Edit OEM with edge length string : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $3;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $3;}' commandtool.data` +OS_DESC=`awk 'NR==12 {print $5;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +./oat_os -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Edit OS with over length string +echo -n "Edit OS with over length string : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $3;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $3;}' commandtool.data` +OS_DESC=`awk 'NR==12 {print $6;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +./oat_os -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************Edit OS with checking special character****************" >> /tmp/Result +# Edit OS success with special char +echo -n "Edit OS success with special char : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $3;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $3;}' commandtool.data` +OS_DESC=`awk 'NR==12 {print $7;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +./oat_os -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Edit OS fail with special char +echo -n "Edit OS fail with special char : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $3;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $3;}' commandtool.data` +OS_DESC=`awk 'NR==12 {print $8;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +./oat_os -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************Delete OS normal**************************************" >> /tmp/Result +# Delete OS successful (normal) +echo -n "Delete OS successful (normal) : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $4;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $4;}' commandtool.data` +OS_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +./oat_os -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\"}"` + ./oat_os -d -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +else + echo "Failed" >> /tmp/Result +fi + +# Delete OS fail (normal) +echo -n "Delete non-existent OS fail (normal) : " >> /tmp/Result +OS_TMP=OEMnone +OS_VER=osv0 +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\"}"` +./oat_os -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************Delete OS with checking boundary value*****************" >> /tmp/Result +# Delete OS with null string +echo -n "Delete OS with null string : " >> /tmp/Result +OS_TMP="" +OS_VER="" +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\"}"` +./oat_os -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Delete OS with edge length string +echo -n "Delete OS with edge length string : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $5;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $5;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\"}"` +./oat_os -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************Delete OS with checking special character**************" >> /tmp/Result +# Delete OS with special char +echo -n "Delete OS with special char : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $7;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $7;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\"}"` +./oat_os -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************View OS************************************************" >> /tmp/Result +# View OS +echo -n "View OS : " >> /tmp/Result +./oat_view_os -h $HOST_NAME > /tmp/res +VIEW=`awk -F "\"" '{print $2;}' /tmp/res` +if [ "$VIEW" = "os" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + + +echo "#The result about MLE" >> /tmp/Result +echo "******************Add MLE normal******************************************" >> /tmp/Result +# Add MLE successful (VMM) +echo -n "Add MLE successful (VMM) : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +MLE_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==8 {print $2;}' commandtool.data` +MLE_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OsName\":\"$OS_TMP\",\"OsVersion\":\"$OS_VER\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"VMM\",\"Description\":\"$MLE_DESC\"}"` +./oat_mle -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add MLE fail (VMM) +echo -n "Add existed MLE fail (VMM) : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +MLE_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==8 {print $2;}' commandtool.data` +MLE_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OsName\":\"$OS_TMP\",\"OsVersion\":\"$OS_VER\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"VMM\",\"Description\":\"$MLE_DESC\"}"` +./oat_mle -a -h $HOST_NAME $INFO > /tmp/res +grep "error_message" /tmp/res > /dev/null +EID=$? +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + ./oat_mle -a -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +elif [ $EID -eq 0 ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add MLE successful (BIOS) +echo -n "Add MLE successful (BIOS) : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +MLE_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +./oat_mle -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add MLE fail (BIOS) +echo -n "Add existed MLE fail (BIOS) : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +MLE_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +./oat_mle -a -h $HOST_NAME $INFO > /tmp/res +grep "error_message" /tmp/res > /dev/null +EID=$? +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + ./oat_mle -a -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +elif [ $EID -eq 0 ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add MLE fail with wrong mle type +OS_TMP=`awk 'NR==3 {print $3;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $3;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $3;}' commandtool.data` +MLE1_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE2_TMP=`awk 'NR==6 {print $2;}' commandtool.data` +MLE1_VER=`awk 'NR==7 {print $2;}' commandtool.data` +MLE2_VER=`awk 'NR==8 {print $2;}' commandtool.data` +MLE_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO1=`echo "{\"Name\":\"$MLE2_TMP\",\"Version\":\"$MLE2_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"ODA\",\"Description\":\"$MLE_DESC\"}"` +INFO2=`echo "{\"Name\":\"$MLE1_TMP\",\"Version\":\"$MLE1_VER\",\"OsName\":\"$OS_TMP\",\"OsVersion\":\"$OS_VER\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"ODA\",\"Description\":\"Test\"}"` +echo -n "Add MLE fail (type is not BIOS) : " >> /tmp/Result +./oat_mle -a -h $HOST_NAME $INFO1 > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi +echo -n "Add MLE fail (type is not VMM) : " >> /tmp/Result +./oat_mle -a -h $HOST_NAME $INFO2 > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add MLE fail with non-existed OEM/OS +INFO1=`echo "{\"Name\":\"$MLE2_TMP\",\"Version\":\"$MLE2_VER\",\"OemName\":\"nexted1\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"ODA\",\"Description\":\"Test\"}"` +INFO2=`echo "{\"Name\":\"$MLE1_TMP\",\"Version\":\"$MLE1_VER\",\"OsName\":\"nexted2\",\"OsVersion\":\"$OS_VER\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"ODA\",\"Description\":\"Test\"}"` +echo -n "Add MLE fail with non-existed OEM : " >> /tmp/Result +./oat_mle -a -h $HOST_NAME $INFO1 > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi +echo -n "Add MLE fail with non-existed OS : " >> /tmp/Result +./oat_mle -a -h $HOST_NAME $INFO2 > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "*******************Add MLE with checking boundary value*************************" >> /tmp/Result +# Add MLE with checking boundary value +echo -n "Add MLE with null string : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +MLE_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"\",\"Version\":\"\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +./oat_mle -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo -n "Add MLE with edge length string : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $5;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $5;}' commandtool.data` +MLE_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +./oat_mle -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo -n "Add MLE with over length string : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $6;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $6;}' commandtool.data` +MLE_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +./oat_mle -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo "*******************Add MLE with checking special character*************************" >> /tmp/Result +# Add MLE with checking special character +echo -n "Add MLE successful with special char : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $7;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $7;}' commandtool.data` +MLE_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +./oat_mle -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo -n "Add MLE fail with special char : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $8;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $8;}' commandtool.data` +MLE_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +./oat_mle -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + + +echo "*******************Edit MLE (Normal)********************************************" >> /tmp/Result +# Edit MLE successful (Normal) +echo -n "Edit MLE successful (normal) : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $3;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $3;}' commandtool.data` +MLE_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +./oat_mle -a -h $HOST_NAME $INFO > /tmp/res +grep "error_message" /tmp/res > /dev/null +EID=$? +MLE_DESC=`awk 'NR==12 {print $3;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + ./oat_mle -e -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +elif [ $EID -eq 0 ];then + ./oat_mle -e -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +else + echo echo "Failed" >> /tmp/Result +fi + +echo -n "Edit MLE fail (normal) : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $4;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $4;}' commandtool.data` +MLE_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +./oat_mle -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "*******************Edit MLE with checking boundary value***********************" >> /tmp/Result +# Edit existed MLE with null string +echo -n "Edit MLE with null string : " >> /tmp/Result +MLE_TMP=`awk 'NR==5 {print $3;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $3;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"\"}"` +./oat_mle -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Edit existed MLE with edge string +echo -n "Edit MLE with edge length string : " >> /tmp/Result +MLE_TMP=`awk 'NR==5 {print $3;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $3;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +MLE_DESC=`awk 'NR==12 {print $5;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +./oat_mle -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Edit existed MLE with over string +echo -n "Edit MLE with over length string : " >> /tmp/Result +MLE_TMP=`awk 'NR==5 {print $3;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $3;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +MLE_DESC=`awk 'NR==12 {print $6;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +./oat_mle -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "*******************Edit MLE with checking special character***********************" >> /tmp/Result +# Edit MLE successful with special character +echo "Edit MLE successful with special char : " >> /tmp/Result +MLE_TMP=`awk 'NR==5 {print $3;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $3;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +MLE_DESC=`awk 'NR==12 {print $7;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +./oat_mle -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Edit MLE fail with special character +echo "Edit MLE fail with special char : " >> /tmp/Result +MLE_TMP=`awk 'NR==5 {print $3;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $3;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +MLE_DESC=`awk 'NR==12 {print $8;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +./oat_mle -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************Delete MLE Normal**********************************************" >> /tmp/Result +# Delete existent MLE successful +echo -n "Delete existent MLE successful : " >> /tmp/Result +MLE_TMP=`awk 'NR==5 {print $4;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $4;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +MLE_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +./oat_mle -a -h $HOST_NAME $INFO > /tmp/res +grep "error_message" /tmp/res > /dev/null +EID=$? +INFO=`echo "{\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + ./oat_mle -d -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +elif [ $EID -eq 0 ];then + ./oat_mle -d -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +else + echo "Failed" >> /tmp/Result +fi + +# Delete non-existent MLE fail +echo -n "Delete non-existent MLE fail : " >> /tmp/Result +MLE_TMP="MLEnone" +MLE_VER="mlev0" +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_mle -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "*****************Delete MLE with checking boundary value********************" >> /tmp/Result +# Delete existed MLE with null string +echo -n "Delete existed MLE with null string : " >> /tmp/Result +MLE_TMP="" +MLE_VER="" +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_mle -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Delete existed MLE with edge length string +echo -n "Delete MLE with edge length string : " >> /tmp/Result +MLE_TMP=`awk 'NR==5 {print $5;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $5;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_mle -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "*****************Delete MLE with checking special character*****************" >> /tmp/Result +# Delete existed MLE with special char +echo -n "Delete existed MLE with special char : " >> /tmp/Result +MLE_TMP=`awk 'NR==5 {print $7;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $7;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_mle -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************View/Search MLE********************************************" >> /tmp/Result +# View MLE (BIOS) +echo -n "View MLE (BIOS) : " >> /tmp/Result +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_view_mle -h $HOST_NAME $INFO > /tmp/res +grep "MLE_Type" /tmp/res > /dev/null +EID=$? +if [ $EID -eq 0 ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# View MLE (VMM) +echo -n "View MLE (VMM) : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +MLE_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==8 {print $2;}' commandtool.data` +INFO=`echo "{\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"osName\":\"$OS_TMP\",\"osVersion\":\"$OS_VER\"}"` +./oat_view_mle -h $HOST_NAME $INFO > /tmp/res +VIEW=`awk -F "\"" '{print $2;}' /tmp/res` +if [ "$VIEW" = "Attestation_Type" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Search MLE +echo -n "Search MLE (normal) : " >> /tmp/Result +./oat_mle_search -h $HOST_NAME '{MLE}' > /tmp/res +VIEW=`awk -F "\"" '{print $2;}' /tmp/res` +if [ "$VIEW" = "mleBean" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "#The result about PCR_WHITE_LIST" >> /tmp/Result +# Add a PCR successful +echo "******************Add PCR normal********************************************" >> /tmp/Result +echo -n "Add a PCR successful (normal) : " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $2;}' commandtool.data` +PCR_VALUE=`awk 'NR==10 {print $2;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +# Add a PCR fail which exists +echo -n "Add a PCR fail which exists : " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $2;}' commandtool.data` +PCR_VALUE=`awk 'NR==10 {print $2;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -a -h $HOST_NAME $INFO > /tmp/res +grep "error_message" /tmp/res > /dev/null +EID=$? +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + ./oat_pcrwhitelist -a -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed " >> /tmp/Result + else + echo "Failed " >> /tmp/Result + fi +elif [ $EID -eq 0 ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +# Add a PCR fail with non-exist MLE +echo -n "Add a PCR fail with non-exist MLE : " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $2;}' commandtool.data` +PCR_VALUE=`awk 'NR==10 {print $2;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $4;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $4;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $4;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +# Add MLE with PCR +echo -n "Add MLE with PCR : " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $2;}' commandtool.data` +PCR_VALUE=`awk 'NR==10 {print $2;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $4;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $4;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"Test\",\"MLE_Manifests\":[{\"Name\":\"$PCR_NUM\",\"Value\":\"$PCR_VALUE\"}]}"` +./oat_mle -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +echo "*******************Add PCR with checking boundary value**********************" >> /tmp/Result +# Add PCR with null string +echo -n "Add PCR with null string : " >> /tmp/Result +PCR_NUM="" +PCR_VALUE=`awk 'NR==10 {print $2;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +# Add PCR with edge length string +echo -n "Add PCR with edge length string : " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $5;}' commandtool.data` +PCR_VALUE=`awk 'NR==10 {print $5;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +# Add PCR with over length string +echo -n "Add PCR with over length string : " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $6;}' commandtool.data` +PCR_VALUE=`awk 'NR==10 {print $6;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +echo "*******************Add PCR with checking special character*******************" >> /tmp/Result +# Add PCR successful with special character +echo -n "Add PCR successful with special char : " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $7;}' commandtool.data` +PCR_VALUE=`awk 'NR==10 {print $7;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +# Add PCR fail with special character +echo -n "Add PCR fail with special char : " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $8;}' commandtool.data` +PCR_VALUE=`awk 'NR==10 {print $8;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi +echo "******************Update PCR Normal****************************************" >> /tmp/Result +# Update existent PCR successful +echo -n "Update existent PCR successful : " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $3;}' commandtool.data` +PCR_VALUE=`awk 'NR==10 {print $3;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -a -h $HOST_NAME $INFO > /tmp/res +grep "error_message" /tmp/res +EID=$? +PCR_VALUE=`awk 'NR==10 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + ./oat_pcrwhitelist -e -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result + else + echo "Failed " >> /tmp/Result + fi +elif [ $EID -eq 0 ];then + ./oat_pcrwhitelist -e -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result + else + echo "Failed " >> /tmp/Result + fi +else + echo "Failed " >> /tmp/Result +fi + +# Update nonexistent PCR fail +echo -n "Update nonexistent PCR fail : " >> /tmp/Result +PCR_NUM=12 +PCR_VALUE=`awk 'NR==10 {print $3;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +# Update all PCR which connect to one MLE record +echo -n "Update all PCR : " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $3;}' commandtool.data` +PCR_VALUE=`awk 'NR==10 {print $3;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +PCR2_NUM=`awk 'NR==9 {print $4;}' commandtool.data` +PCR2_VALUE=`awk 'NR==10 {print $4;}' commandtool.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"Test\",\"MLE_Manifests\":[{\"Name\":\"$PCR_NUM\",\"Value\":\"$PCR_VALUE\"},{\"Name\":\"$PCR2_NUM\",\"Value\":\"$PCR2_VALUE\"}]}"` +./oat_mle -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "********************Update PCR with checking boundary value******************************" >> /tmp/Result +# Update PCR with null string +echo -n "Update PCR with null string : " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $3;}' commandtool.data` +PCR_VALUE="" +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Update PCR with edge length string +echo -n "Update PCR with edge length string : " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $3;}' commandtool.data` +PCR_VALUE=`awk 'NR==10 {print $5;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Update PCR with over length string +echo -n "Update PCR with over length string : " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $3;}' commandtool.data` +PCR_VALUE=`awk 'NR==10 {print $6;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "********************Update PCR with checking special character*********************" >> /tmp/Result +# Update PCR successful with special char +echo -n "Update PCR successful with special char: " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $3;}' commandtool.data` +PCR_VALUE=`awk 'NR==10 {print $7;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Update PCR fail with special char +echo -n "Update PCR fail with special char : " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $3;}' commandtool.data` +PCR_VALUE=`awk 'NR==10 {print $8;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "**********************Delete PCR Normal************************************************" >> /tmp/Result +# Delete PCR successful +echo -n "Delete PCR successful : " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $4;}' commandtool.data` +PCR_VALUE=`awk 'NR==10 {print $4;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -a -h $HOST_NAME $INFO > /tmp/res +grep "error_message" /tmp/res > /dev/null +EID=$? +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + ./oat_pcrwhitelist -d -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +elif [ $EID -eq 0 ];then + ./oat_pcrwhitelist -d -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +else + echo "Failed" >> /tmp/Result +fi + +# Delete PCR fail +echo -n "Delete PCR fail : " >> /tmp/Result +PCR_NUM=12222 +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Delete PCR with MLE +echo -n "Delete PCR fail : " >> /tmp/Result +MLE_TMP=`awk 'NR==5 {print $3;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $3;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_mle -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + + +echo "**********************Delete PCR with checking boundary value***************************" >> /tmp/Result +# Delete PCR with null string +echo -n "Delete PCR with null string : " >> /tmp/Result +PCR_NUM="" +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Delete existed PCR with edge length string +echo -n "Delete PCR with edge length string : " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $5;}' commandtool.data` +PCR_VALUE=`awk 'NR==10 {print $5;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -a -h $HOST_NAME $INFO +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +echo "**********************Delete PCR with checking special character**********************" >> /tmp/Result +# Delete PCR successful with special char +echo -n "Delete PCR successful with special char: " >> /tmp/Result +PCR_NUM=`awk 'NR==9 {print $7;}' commandtool.data` +PCR_VALUE=`awk 'NR==10 {print $7;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -a -h $HOST_NAME $INFO +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_pcrwhitelist -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + + +echo "#The result about HOST" >> /tmp/Result +echo "***********************Add Host Normal***************************************************" >> /tmp/Result +# Add Host successful +echo -n "Add Host successful : " >> /tmp/Result +HOST_TMP=`awk 'NR==11 {print $2;}' commandtool.data` +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +VMM_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +VMM_VER=`awk 'NR==8 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +BIOS_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +BIOS_VER=`awk 'NR==6 {print $2;}' commandtool.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.1\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +./oat_host -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add Host fail (noraml) +echo -n "Add Host fail (normal) : " >> /tmp/Result +HOST_TMP=`awk 'NR==11 {print $2;}' commandtool.data` +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +VMM_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +VMM_VER=`awk 'NR==8 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +BIOS_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +BIOS_VER=`awk 'NR==6 {print $2;}' commandtool.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.1\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +./oat_host -a -h $HOST_NAME $INFO > /tmp/res +grep "error_message" /tmp/res > /dev/null +EID=$? +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + ./oat_host -a -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +elif [ $EID -eq 0 ];then + ./oat_host -a -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +else + echo "Failed" >> /tmp/Result +fi + +# Add Host with nonexistent MLE +echo -n "Add Host with nonexistent MLE : " >> /tmp/Result +HOST_TMP=`awk 'NR==11 {print $2;}' commandtool.data` +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +VMM_TMP=`awk 'NR==7 {print $4;}' commandtool.data` +VMM_VER=`awk 'NR==8 {print $4;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +BIOS_TMP=`awk 'NR==5 {print $4;}' commandtool.data` +BIOS_VER=`awk 'NR==6 {print $4;}' commandtool.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.1\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +./oat_host -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "*********************Add Host with checking boundary value*****************************" >> /tmp/Result +# Add Host with null string +echo -n "Add Host with null string : " >> /tmp/Result +HOST_TMP="" +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +VMM_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +VMM_VER=`awk 'NR==8 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +BIOS_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +BIOS_VER=`awk 'NR==6 {print $2;}' commandtool.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.1\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +./oat_host -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add Host with edgelength string +echo -n "Add Host with edgelength string : " >> /tmp/Result +HOST_TMP=`awk 'NR==11 {print $5;}' commandtool.data` +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +VMM_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +VMM_VER=`awk 'NR==8 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +BIOS_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +BIOS_VER=`awk 'NR==6 {print $2;}' commandtool.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.1\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +./oat_host -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add Host with over length string +echo -n "Add Host with over length string : " >> /tmp/Result +HOST_TMP=`awk 'NR==11 {print $6;}' commandtool.data` +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +VMM_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +VMM_VER=`awk 'NR==8 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +BIOS_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +BIOS_VER=`awk 'NR==6 {print $2;}' commandtool.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.1\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +./oat_host -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "*********************Add Host with checking special character*****************************" >> /tmp/Result +# Add Host successful with special char +echo -n "Add Host successful with special char : " >> /tmp/Result +HOST_TMP=`awk 'NR==11 {print $7;}' commandtool.data` +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +VMM_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +VMM_VER=`awk 'NR==8 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +BIOS_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +BIOS_VER=`awk 'NR==6 {print $2;}' commandtool.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.1\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +./oat_host -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add Host fail with special char +echo -n "Add Host fail with special char : " >> /tmp/Result +HOST_TMP=`awk 'NR==11 {print $8;}' commandtool.data` +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +VMM_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +VMM_VER=`awk 'NR==8 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +BIOS_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +BIOS_VER=`awk 'NR==6 {print $2;}' commandtool.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.1\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +./oat_host -a -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "********************Edit Host Normal*************************************************" >> /tmp/Result +# Edit Host successful +echo -n "Edit Host successful : " >> /tmp/Result +HOST_TMP=`awk 'NR==11 {print $3;}' commandtool.data` +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +VMM_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +VMM_VER=`awk 'NR==8 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +BIOS_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +BIOS_VER=`awk 'NR==6 {print $2;}' commandtool.data` +HOST_DESC=`awk 'NR==12 {print $3;}' commandtool.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.1\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +./oat_host -a -h $HOST_NAME $INFO > /tmp/res +grep "error_message" /tmp/res > /dev/null +EID=$? +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.1\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"$HOST_DESC\"}"` +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + ./oat_host -e -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +elif [ $EID -eq 0 ];then + ./oat_host -e -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +else + echo "Failed" >> /tmp/Result +fi + +# Edit Host fail +echo -n "Edit Host fail : " >> /tmp/Result +HOST_TMP=`awk 'NR==11 {print $4;}' commandtool.data` +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +VMM_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +VMM_VER=`awk 'NR==8 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +BIOS_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +BIOS_VER=`awk 'NR==6 {print $2;}' commandtool.data` +HOST_DESC=`awk 'NR==12 {print $3;}' commandtool.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.1\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +./oat_host -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +echo "*********************Edit Host with checking boundary value******************************" >> /tmp/Result +# Edit HOST with null string +echo -n "Edit HOST with null string : " >> /tmp/Result +HOST_TMP=`awk 'NR==11 {print $2;}' commandtool.data` +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +VMM_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +VMM_VER=`awk 'NR==8 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +BIOS_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +BIOS_VER=`awk 'NR==6 {print $2;}' commandtool.data` +HOST_DESC=`awk 'NR==12 {print $3;}' commandtool.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.2\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +./oat_host -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +#Edit existed HOST with edge string +echo -n "Edit existed HOST with edge string : " >> /tmp/Result +HOST_TMP=`awk 'NR==11 {print $2;}' commandtool.data` +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +VMM_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +VMM_VER=`awk 'NR==8 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +BIOS_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +BIOS_VER=`awk 'NR==6 {print $2;}' commandtool.data` +HOST_DESC=`awk 'NR==12 {print $5;}' commandtool.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.2\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"$HOST_DESC\"}"` +./oat_host -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +# Edit HOST with overlength string +echo -n "Edit HOST with overlength string : " >> /tmp/Result +HOST_TMP=`awk 'NR==11 {print $2;}' commandtool.data` +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +VMM_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +VMM_VER=`awk 'NR==8 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +BIOS_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +BIOS_VER=`awk 'NR==6 {print $2;}' commandtool.data` +HOST_DESC=`awk 'NR==12 {print $6;}' commandtool.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.2\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"$HOST_DESC\"}"` +./oat_host -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +echo "*********************Edit Host with checking special character*********************" >> /tmp/Result +# Edit HOST successful with special char +echo -n "Edit HOST successful with special char : " >> /tmp/Result +HOST_TMP=`awk 'NR==11 {print $2;}' commandtool.data` +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +VMM_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +VMM_VER=`awk 'NR==8 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +BIOS_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +BIOS_VER=`awk 'NR==6 {print $2;}' commandtool.data` +HOST_DESC=`awk 'NR==12 {print $7;}' commandtool.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.2\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"$HOST_DESC\"}"` +./oat_host -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +# Edit HOST fail with special char +echo -n "Edit HOST fail with special char : " >> /tmp/Result +HOST_TMP=`awk 'NR==11 {print $2;}' commandtool.data` +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +VMM_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +VMM_VER=`awk 'NR==8 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +BIOS_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +BIOS_VER=`awk 'NR==6 {print $2;}' commandtool.data` +HOST_DESC=`awk 'NR==12 {print $8;}' commandtool.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.2\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"$HOST_DESC\"}"` +./oat_host -e -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +echo "********************Delete Host Normal*****************************************" >> /tmp/Result +# Delete Host successful +echo -n "Delete Host successful : " >> /tmp/Result +HOST_TMP=`awk 'NR==11 {print $4;}' commandtool.data` +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +VMM_TMP=`awk 'NR==7 {print $2;}' commandtool.data` +VMM_VER=`awk 'NR==8 {print $2;}' commandtool.data` +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +BIOS_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +BIOS_VER=`awk 'NR==6 {print $2;}' commandtool.data` +HOST_DESC=`awk 'NR==12 {print $2;}' commandtool.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.2\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"$HOST_DESC\"}"` +./oat_host -a -h $HOST_NAME $INFO > /tmp/res +grep "error_message" /tmp/res > /dev/null +EID=$? +INFO=`echo "{\"hostName\":\"$HOST_TMP\"}"` +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + ./oat_host -d -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result + else + echo "Failed " >> /tmp/Result + fi +elif [ $EID -eq 0 ];then + ./oat_host -d -h $HOST_NAME $INFO > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result + else + echo "Failed " >> /tmp/Result + fi +else + echo "Failed " >> /tmp/Result +fi + +# Delete Host fail +echo -n "Delete Host fail : " >> /tmp/Result +HOST_TMP=HOSTnone +INFO=`echo "{\"hostName\":\"$HOST_TMP\"}"` +./oat_host -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +echo "********************Delete HOST with checking boundary value********************" >> /tmp/Result +# Delete HOST with null string +echo -n "Delete HOST with null string : " >> /tmp/Result +INFO=`echo "{\"hostName\":\"\"}"` +./oat_host -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +# Delete HOST with edge length string +echo -n "Delete HOST with edge length string : " >> /tmp/Result +HOST_TMP=`awk 'NR==11 {print $5;}' commandtool.data` +INFO=`echo "{\"hostName\":\"$HOST_TMP\"}"` +./oat_host -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +echo "********************Delete HOST with checking special character*****************" >> /tmp/Result +# Delete HOST with special char +echo -n "Delete HOST with special char : " >> /tmp/Result +HOST_TMP=`awk 'NR==11 {print $7;}' commandtool.data` +INFO=`echo "{\"hostName\":\"$HOST_TMP\"}"` +./oat_host -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + +echo "********************Search HOST*************************************************" >> /tmp/Result +# Search HOST +echo -n "Search HOST : " >> /tmp/Result +./oat_host -s -h $HOST_NAME '{HOST}' > /tmp/res +grep "hostBean" /tmp/res > /dev/null +EID=$? +#VIEW=`awk -F "\"" '{print $2;}' /tmp/res` +if [ $EID -eq 0 ];then + echo "Passed " >> /tmp/Result +else + echo "Failed " >> /tmp/Result +fi + + +echo "********************Delete Data which is connected to other data****************" >> /tmp/Result + +#Delete OS with connected MLE +echo -n "Delete OS with connected MLE : " >> /tmp/Result +OS_TMP=`awk 'NR==3 {print $2;}' commandtool.data` +OS_VER=`awk 'NR==4 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\"}"` +./oat_os -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +#Delete OEM with connected MLE +echo -n "Delete OEM with connected MLE : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\"}"` +./oat_oem -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Delete MLE with connected HOST +echo -n "Delete MLE with connected HOST : " >> /tmp/Result +OEM_TMP=`awk 'NR==2 {print $2;}' commandtool.data` +MLE_TMP=`awk 'NR==5 {print $2;}' commandtool.data` +MLE_VER=`awk 'NR==6 {print $2;}' commandtool.data` +INFO=`echo "{\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +./oat_mle -d -h $HOST_NAME $INFO > /tmp/res +if [ "`awk 'NR==3 $1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +#run over +echo "Run over, please check the result in file \"/tmp/Result\"" diff --git a/OpenAttestation/Test/curl.sh b/OpenAttestation/Test/curl.sh new file mode 100644 index 0000000..18994da --- /dev/null +++ b/OpenAttestation/Test/curl.sh @@ -0,0 +1,1450 @@ +#!/bin/bash + +######################################################### +# The script for test MTW API # +######################################################### + +# Get OAT server name and create cert file + +echo -ne "Please enter the OAT server name[default:localhost]: " +read HOST_NAME +if [ "$HOST_NAME" = "" ];then + HOST_NAME=localhost +fi +echo -ne "Please enter the OAT server port[default:8443]: " +read PORT +if [ "$PORT" = "" ];then + PORT=8443 +fi +echo "$HOST_NAME $PORT" +echo "Now creating cert file for $HOST_NAME" +openssl s_client -connect $HOST_NAME:$PORT -cipher DHE-RSA-AES256-SHA|tee certfile.cer + +#Check the Host and Service status +wget --ca-certificate=certfile.cer https://$HOST_NAME:$PORT/HisPrivacyCAWebServices2/hisPrivacyCAWebService2?wsdl >> /dev/null +if [ $? -ne 0 ];then + echo "The host $HOST_NAME can not accessed" + echo "Exit..." + exit 1 +fi +rm -f hisPrivacyCAWebService2?wsdl + +if [ -f /tmp/Result ];then + rm -f /tmp/Result +fi + +echo "#The result about OEM" >> /tmp/Result +echo +echo "******************Add OEM normal******************************************" >> /tmp/Result +# Add OEM successful (normal) +echo -ne "Add OEM successful (normal) : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +OEM_DESC=`awk -F ":" 'NR==12 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/oem" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Add OEM fail (normal) +echo -ne "Add OEM fail (normal) : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $2;}' test.data` +OEM_DESC=`awk -F ":" 'NR==12 {print $2;}' test.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/oem" -3 > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/oem" -3 > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +else + echo "Passed" >> /tmp/Result +fi + +echo +echo "******************Add OEM with checking boundary value********************" >> /tmp/Result +# Add OEM with null string +echo -ne "Add OEM with null string : " >> /tmp/Result +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d '{"Name":"","Description":"DESCRIPTION"}' "https://$HOST_NAME:$PORT/WLMService/resources/oem" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add OEM with edge lenth string +echo -ne "Add OEM with edge lenth string : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $3;}' test.data` +OEM_DESC=`awk -F ":" 'NR==12 {print $3;}' test.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/oem" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add OEM with over lenth string +echo -ne "Add OEM with over lenth string : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $4;}' test.data` +OEM_DESC=`awk -F ":" 'NR==12 {print $4;}' test.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/oem" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo "******************Edit OEM normal*****************************************" >> /tmp/Result +# Edit OEM successful (normal) +echo -ne "Edit OEM successful (normal) : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $5;}' test.data` +OEM_DESC=`awk -F ":" 'NR==12 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/oem" -3 > /dev/null +OEM_DESC=`awk -F ":" 'NR==12 {print $5;}' test.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/oem" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo -ne "Edit OEM fail (normal) : " >> /tmp/Result +# Edit OEM fail (normal) +OEM_TMP=`awk -F ":" 'NR==2 {print $6;}' test.data` +OEM_DESC=`awk -F ":" 'NR==12 {print $6;}' test.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/oem" -3 > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo "******************Edit OEM with checking boundary value******************" >> /tmp/Result +# Edit OEM with null string +echo -ne "Edit OEM with null string : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $5;}' test.data` +OEM_DESC=`awk -F ":" 'NR==12 {print $12;}' test.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/oem" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Edit OEM with edge lenth string +echo -ne "Edit OEM with edge lenth string : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $7;}' test.data` +OEM_DESC=`awk -F ":" 'NR==12 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/oem" -3 > /dev/null +OEM_DESC=`awk -F ":" 'NR==12 {print $7;}' test.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/oem" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Edit OEM with over lenth string +echo -ne "Edit OEM with over lenth string : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $7;}' test.data` +OEM_DESC=`awk -F ":" 'NR==12 {print $8;}' test.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/oem" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo "******************Delete OEM normal**************************************" >> /tmp/Result +# Delete OEM successful (normal) +echo -ne "Delete OEM successful (normal) : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $9;}' test.data` +OEM_DESC=`awk -F ":" 'NR==12 {print $9;}' test.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/oem" -3 > /dev/null +curl --cacert certfile.cer -H "Content-Type: application/json" -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/oem?Name=$OEM_TMP" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Delete OEM fail (normal) +echo -ne "Delete non-existent OEM fail (normal) : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $10;}' test.data` +curl --cacert certfile.cer -H "Content-Type: application/json" -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/oem?Name=$OEM_TMP" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo -ne "Delete connected OEM fail (normal) : " >> /tmp/Result +MLE_TMP=mle1test +MLE_VER=v1test +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"Test\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + curl --cacert certfile.cer -H "Content-Type: application/json" -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/oem?Name=$OEM_TMP" -3 > /tmp/res + + if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +else + echo "Add MLE fail" >> /tmp/Result +fi + +echo +echo "******************Delete OEM with checking boundary value*****************" >> /tmp/Result +# Delete OEM with null string +echo -ne "Delete OEM with null string : " >> /tmp/Result +curl --cacert certfile.cer -H "Content-Type: application/json" -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/oem?Name=" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Delete OEM with edge lenth string +echo -ne "Delete OEM with edge lenth string : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $11;}' test.data` +OEM_DESC=`awk -F ":" 'NR==2 {print $12;}' test.data` +INFO=`echo "{\"Name\":\"$OEM_TMP\",\"Description\":\"$OEM_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/oem" -3 > /dev/null +curl --cacert certfile.cer -H "Content-Type: application/json" -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/oem?Name=$OEM_TMP" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo "******************View OEM************************************************" >> /tmp/Result +# View OEM +echo -ne "View OEM : " >> /tmp/Result +curl --cacert certfile.cer -H "Content-Type: application/json" -X GET https://$HOST_NAME:$PORT/WLMService/resources/oem -3 > /tmp/res +VIEW=`awk -F "\"" '{print $2;}' /tmp/res` + +if [ "$VIEW" = "oem" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo +echo "#The result about OS" >> /tmp/Result +echo +echo "******************Add OS normal*******************************************" >> /tmp/Result +# Add OS successful (normal) +echo -ne "Add OS successful (normal) : " >> /tmp/Result +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +OS_DESC=`awk -F ":" 'NR==12 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/os" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Add OS fail (normal) +echo -ne "Add OS fail (normal) : " >> /tmp/Result +OS_TMP=`awk -F ":" 'NR==3 {print $2;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $2;}' test.data` +OS_DESC=`awk -F ":" 'NR==12 {print $2;}' test.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/os" -3 > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/os" -3 > /tmp/res + + if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +else + echo "Passed" >> /tmp/Result +fi + +echo +echo "******************Add OS with checking boundary value*********************" >> /tmp/Result +# Add OS with null string +echo -ne "Add OS with null string : " >> /tmp/Result +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d '{"Name":"","Version":"","Description":"DESCRIPTION"}' "https://$HOST_NAME:$PORT/WLMService/resources/os" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add OS with edge lenth string +echo -ne "Add OS with edge lenth string : " >> /tmp/Result +OS_TMP=`awk -F ":" 'NR==3 {print $3;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $3;}' test.data` +OS_DESC=`awk -F ":" 'NR==12 {print $3;}' test.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/os" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add OS with over lenth string +echo -ne "Add OS with over lenth string : " >> /tmp/Result +OS_TMP=`awk -F ":" 'NR==3 {print $4;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $4;}' test.data` +OS_DESC=`awk -F ":" 'NR==12 {print $4;}' test.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/os" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo "******************Edit OS normal******************************************" >> /tmp/Result +# Edit OS successful (normal) +echo -ne "Edit OS successful (normal) : " >> /tmp/Result +OS_TMP=`awk -F ":" 'NR==3 {print $5;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $5;}' test.data` +OS_DESC=`awk -F ":" 'NR==12 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/os" -3 > /dev/null +OS_DESC=`awk -F ":" 'NR==12 {print $5;}' test.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/os" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo -ne "Edit OS fail (normal) : " >> /tmp/Result +# Edit OS fail (normal) +OS_TMP=`awk -F ":" 'NR==3 {print $6;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $6;}' test.data` +OS_DESC=`awk -F ":" 'NR==12 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/os" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo "******************Edit OS with checking boundary value******************" >> /tmp/Result +# Edit OS with null string +echo -ne "Edit OS with null string : " >> /tmp/Result +OS_TMP=`awk -F ":" 'NR==3 {print $5;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $5;}' test.data` +OS_DESC=`awk -F ":" 'NR==12 {print $12;}' test.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/os" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Edit OS with edge lenth string +echo -ne "Edit OS with edge lenth string : " >> /tmp/Result +OS_TMP=`awk -F ":" 'NR==3 {print $5;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $5;}' test.data` +OS_DESC=`awk -F ":" 'NR==12 {print $7;}' test.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/os" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Edit OS with over lenth string +echo -ne "Edit OS with over lenth string : " >> /tmp/Result +OS_TMP=`awk -F ":" 'NR==3 {print $5;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $5;}' test.data` +OS_DESC=`awk -F ":" 'NR==12 {print $8;}' test.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/os" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo "******************Delete OS normal**************************************" >> /tmp/Result +# Delete OS successful (normal) +echo -ne "Delete OS successful (normal) : " >> /tmp/Result +OS_TMP=`awk -F ":" 'NR==3 {print $9;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $9;}' test.data` +OS_DESC=`awk -F ":" 'NR==12 {print $9;}' test.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/os" -3 > /dev/null +curl --cacert certfile.cer -H "Content-Type: application/json" -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/os?Name=$OS_TMP&Version=$OS_VER" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Delete OS fail (normal) +echo -ne "Delete non-existent OS fail (normal) : " >> /tmp/Result +OS_TMP=`awk -F ":" 'NR==3 {print $10;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $10;}' test.data` +curl --cacert certfile.cer -H "Content-Type: application/json" -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/os?Name=$OS_TMP&Version=$OS_VER" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi +echo -ne "Delete connected OS fail (normal) : " >> /tmp/Result +MLE_TMP=mle2test +MLE_VER=v2test +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OsName\":\"$OS_TMP\",\"OsVersion\":\"$OS_VER\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"VMM\",\"Description\":\"Test\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + curl --cacert certfile.cer -H "Content-Type: application/json" -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/os?Name=$OS_TMP&Version=$OS_VER" -3 > /tmp/res + if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +else + echo "Add MLE fail" >> /tmp/Result +fi +echo +echo "******************Delete OS with checking boundary value*****************" >> /tmp/Result +# Delete OS with null string +echo -ne "Delete OS with null string : " >> /tmp/Result +curl --cacert certfile.cer -H "Content-Type: application/json" -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/os?Name=&Version=" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Delete OS with edge lenth string +echo -ne "Delete OS with edge lenth string : " >> /tmp/Result +OS_TMP=`awk -F ":" 'NR==3 {print $11;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $11;}' test.data` +OS_DESC=`awk -F ":" 'NR==12 {print $11;}' test.data` +INFO=`echo "{\"Name\":\"$OS_TMP\",\"Version\":\"$OS_VER\",\"Description\":\"$OS_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/os" -3 > /dev/null +curl --cacert certfile.cer -H "Content-Type: application/json" -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/os?Name=$OS_TMP&Version=$OS_VER" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo "******************View OS************************************************" >> /tmp/Result +# View OS +echo -ne "View OS : " >> /tmp/Result +curl --cacert certfile.cer -H "Content-Type: application/json" -X GET https://$HOST_NAME:$PORT/WLMService/resources/os -3 > /tmp/res +VIEW=`awk -F "\"" '{print $2;}' /tmp/res` + +if [ "$VIEW" = "os" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo +echo "#The result about MLE" >> /tmp/Result +echo +echo "******************Add MLE normal******************************************" >> /tmp/Result +# Add MLE successful (VMM) +echo -ne "Add MLE successful (VMM) : " >> /tmp/Result +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +MLE_TMP=`awk -F ":" 'NR==7 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==8 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OsName\":\"$OS_TMP\",\"OsVersion\":\"$OS_VER\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"VMM\",\"Description\":\"Test\"}"` +echo $INFO +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add MLE fail (VMM) +echo -ne "Add existed MLE fail (VMM) : " >> /tmp/Result +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +MLE_TMP=`awk -F ":" 'NR==7 {print $2;}' test.data` +MLE_VER=`awk -F ":" 'NR==8 {print $2;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OsName\":\"$OS_TMP\",\"OsVersion\":\"$OS_VER\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"VMM\",\"Description\":\"Test\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res + + if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +else + echo "Passed" >> /tmp/Result +fi +# Add MLE successful (BIOS) +echo -ne "Add MLE successful (BIOS) : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"Test\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add MLE fail (BIOS) +echo -ne "Add existed MLE fail (BIOS) : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $2;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $2;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"Test\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res + + if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result + else + echo "Failed" >> /tmp/Result + fi +else + echo "Passed" >> /tmp/Result +fi + +# Add MLE fail when wrong mle +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +MLE1_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE2_TMP=`awk -F ":" 'NR==6 {print $1;}' test.data` +MLE1_VER=`awk -F ":" 'NR==7 {print $2;}' test.data` +MLE2_VER=`awk -F ":" 'NR==8 {print $2;}' test.data` +INFO1=`echo "{\"Name\":\"$MLE2_TMP\",\"Version\":\"$MLE2_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"ODA\",\"Description\":\"Test\"}"` +INFO2=`echo "{\"Name\":\"$MLE1_TMP\",\"Version\":\"$MLE1_VER\",\"OsName\":\"$OS_TMP\",\"OsVersion\":\"$OS_VER\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"ODA\",\"Description\":\"Test\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO1 "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO2 "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/rest +echo -ne "Add MLE fail (type is not BIOS) : " >> /tmp/Result + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo -ne "Add MLE fail (type is not VMM) : " >> /tmp/Result + +if [ "`awk '$1 ~/True/' /tmp/rest`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add MLE fail with non-existed OEM/OS +INFO1=`echo "{\"Name\":\"$MLE2_TMP\",\"Version\":\"$MLE2_VER\",\"OemName\":\"nexted1\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"ODA\",\"Description\":\"Test\"}"` +INFO2=`echo "{\"Name\":\"$MLE1_TMP\",\"Version\":\"$MLE1_VER\",\"OsName\":\"nexted2\",\"OsVersion\":\"$OS_VER\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"ODA\",\"Description\":\"Test\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO1 "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO2 "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/rest +echo -ne "Add MLE fail with non-existed OEM : " >> tmp/Result + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo -ne "Add MLE fail with non-existed OS : " >> /tmp/Result + +if [ "`awk '$1 ~/True/' /tmp/rest`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Add MLE with PCR +echo -ne "Add MLE with PCR : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $5;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $5;}' test.data` +PCR_N=`awk -F ":" 'NR==9 {print $1;}' test.data` +PCR_D=`awk -F ":" 'NR==10 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"Test\",\"MLE_Manifests\":[{\"Name\":\"$PCR_N\",\"Value\":\"$PCR_D\"}]}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo "*******************Add MLE with checking boundary value*************************" >> /tmp/Result +# Add MLE with checking boundary value +echo -ne "Add MLE with null string : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"\",\"Version\":\"\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"Test\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo -ne "Add MLE with edge lenth string : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $3;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $3;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"Test\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo -ne "Add MLE with over lenth string : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $4;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $4;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"Test\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo "*******************Edit MLE (Normal)********************************************" >> /tmp/Result +# Edit MLE successful (Normal) +echo -ne "Edit MLE successful (normal) : " >> /tmp/Result +MLE_TMP=`awk -F ":" 'NR==5 {print $5;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $5;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"Test\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /dev/null +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"Update\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/resx + +if [ "`awk '$1 ~/True/' /tmp/resx`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo -ne "Edit MLE fail (normal) : " >> /tmp/Result +MLE_TMP=`awk -F ":" 'NR==5 {print $6;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $6;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"Test\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo "*******************Edit MLE with checking boundary value***********************" >> /tmp/Result +# Edit existed MLE with null string +echo -ne "Edit MLE with null string : " >> /tmp/Result +MLE_TMP=`awk -F ":" 'NR==5 {print $5;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $5;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Edit existed MLE with edge string +echo -ne "Edit MLE with edge lenth string : " >> /tmp/Result +MLE_TMP=`awk -F ":" 'NR==5 {print $5;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $5;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +MLE_DESC=`awk -F ":" 'NR==12 {print $7;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Edit existed MLE with over string +echo -ne "Edit MLE with over lenth string : " >> /tmp/Result +MLE_TMP=`awk -F ":" 'NR==5 {print $5;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $5;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +MLE_DESC=`awk -F ":" 'NR==12 {print $8;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo "******************Delete MLE Normal**********************************************" >> /tmp/Result +# Delete existent MLE successful +echo -ne "Delete existent MLE successful : " >> /tmp/Result +MLE_TMP=`awk -F ":" 'NR==5 {print $9;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $9;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +MLE_DESC=`awk -F ":" 'NR==12 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res +curl --cacert certfile.cer -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/mles?mleName=$MLE_TMP&mleVersion=$MLE_VER&oemName=$OEM_TMP" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Delete non-existent MLE fail +echo -ne "Delete non-existent MLE fail : " >> /tmp/Result +MLE_TMP=`awk -F ":" 'NR==5 {print $10;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $10;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +curl --cacert certfile.cer -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/mles?mleName=$MLE_TMP&mleVersion=$MLE_VER&oemName=$OEM_TMP" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Delete MLE with connected to PCR +echo -ne "Delete MLE with connected to PCR : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $5;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $5;}' test.data` +PCR_N=`awk -F ":" 'NR==9 {print $1;}' test.data` +PCR_D=`awk -F ":" 'NR==10 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"Test\",\"MLE_Manifests\":[{\"Name\":\"$PCR_N\",\"Value\":\"$PCR_D\"}]}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res +curl --cacert certfile.cer -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/mles?mleName=$MLE_TMP&mleVersion=$MLE_VER&oemName=$OEM_TMP" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Delete MLE with connected to HOST +echo -ne "Delete MLE with connected to HOST : " >> /tmp/Result +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +VMM_TMP=`awk -F ":" 'NR==7 {print $2;}' test.data` +VMM_VER=`awk -F ":" 'NR==8 {print $2;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +BIOS_TMP=`awk -F ":" 'NR==5 {print $2;}' test.data` +BIOS_VER=`awk -F ":" 'NR==6 {print $2;}' test.data` +INFO=`echo "{\"HostName\":\"histest\",\"IPAddress\":\"192.168.0.1\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" -3 > /dev/null +curl --cacert certfile.cer -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/mles?mleName=$BIOS_TMP&mleVersion=$BIOS_VER&oemName=$OEM_TMP" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo "*****************Delete MLE with checking boundary value********************" >> /tmp/Result +# Delete existed MLE with null string +echo -ne "Delete existed MLE with null string : " >> /tmp/Result +curl --cacert certfile.cer -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/mles?mleName=&mleVersion=&oemName=$OEM_TMP" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Delete existed MLE with edge lenth string +echo -ne "Delete MLE with edge lenth string : " >> /tmp/Result +MLE_TMP=`awk -F ":" 'NR==5 {print $11;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $11;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +MLE_DESC=`awk -F ":" 'NR==12 {print $1;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"$MLE_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /dev/null +curl --cacert certfile.cer -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/mles?mleName=$MLE_TMP&mleVersion=$MLE_VER&oemName=$OEM_TMP" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo "******************View/Search MLE********************************************" >> /tmp/Result +# View MLE (BIOS) +echo -ne "View MLE (BIOS) : " >> /tmp/Result +MLE_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +curl --cacert ./certfile.cer -H "Content-Type: application/json" -X GET "https://$HOST_NAME:$PORT/WLMService/resources/mles/manifest?mleName=$MLE_TMP&mleVersion=$MLE_VER&oemName=$OEM_TMP" -3 > /tmp/res +VIEW=`awk -F "\"" '{print $2;}' /tmp/res` + +if [ "$VIEW" = "Attestation_Type" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# View MLE (VMM) +echo -ne "View MLE (VMM) : " >> /tmp/Result +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +MLE_TMP=`awk -F ":" 'NR==7 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==8 {print $1;}' test.data` +curl --cacert ./certfile.cer -H "Content-Type: application/json" -X GET "https://$HOST_NAME:$PORT/WLMService/resources/mles/manifest?mleName=$MLE_TMP&mleVersion=$MLE_VER&osName=$OS_TMP&osVersion=$OS_VER" -3 > /tmp/res +VIEW=`awk -F "\"" '{print $2;}' /tmp/res` + +if [ "$VIEW" = "Attestation_Type" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +# Search MLE +echo -ne "Search MLE (normal) : " >> /tmp/Result +curl --cacert ./certfile.cer -H "Content-Type: application/json"-X GET "https://$HOST_NAME:$PORT/WLMService/resources/mles?searchCriteria=mle" -3 > /tmp/res +VIEW=`awk -F "\"" '{print $2;}' /tmp/res` + +if [ "$VIEW" = "mleBean" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo +echo "#The result about PCR_WHITE_LIST" >> /tmp/Result +# Add a PCR successful +echo +echo "******************Add PCR normal********************************************" >> /tmp/Result +echo -ne "Add a PCR successful (normal) : " >> /tmp/Result +PCR_NUM=`awk -F ":" 'NR==9 {print $1;}' test.data` +PCR_VALUE=`awk -F ":" 'NR==10 {print $1;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Add a PCR fail which exists +echo -ne "Add a PCR fail which exists : " >> /tmp/Result +PCR_NUM=`awk -F ":" 'NR==9 {print $2;}' test.data` +PCR_VALUE=`awk -F ":" 'NR==10 {print $1;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr" -3 > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr" -3 > /tmp/res + + if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo -e "Passed " >> /tmp/Result + else + echo -e "Failed " >> /tmp/Result + fi +else + echo "Passed" >> /tmp/Result +fi +# Add a PCR fail with non-exist MLE +echo -ne "Add a PCR fail with non-exist MLE : " >> /tmp/Result +MLE_TMP=`awk -F ":" 'NR==5 {print $9;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $9;}' test.data` +PCR_NUM=`awk -F ":" 'NR==9 {print $1;}' test.data` +PCR_VALUE=`awk -F ":" 'NR==10 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $9;}' test.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +echo +echo "*******************Add PCR with checking boundary value**********************" >> /tmp/Result +# Add PCR with null string +echo -ne "Add PCR with null string : " >> /tmp/Result +PCR_VALUE=`awk -F ":" 'NR==10 {print $1;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +INFO=`echo "{\"pcrName\":\"\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Add PCR with edge lenth string +echo -ne "Add PCR with edge lenth string : " >> /tmp/Result +PCR_NUM=`awk -F ":" 'NR==9 {print $3;}' test.data` +PCR_VALUE=`awk -F ":" 'NR==10 {print $3;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr -3 > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Add PCR with over lenth string +echo -ne "Add PCR with over lenth string : " >> /tmp/Result +PCR_NUM=`awk -F ":" 'NR==9 {print $4;}' test.data` +PCR_VALUE=`awk -F ":" 'NR==10 {print $4;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +echo +echo "******************Update PCR Normal****************************************" >> /tmp/Result +# Update existent PCR successful +echo -ne "Update existent PCR successful : " >> /tmp/Result +PCR_NUM=`awk -F ":" 'NR==9 {print $5;}' test.data` +PCR_VALUE=`awk -F ":" 'NR==10 {print $1;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr" -3 > /dev/null +PCR_VALUE=`awk -F ":" 'NR==10 {print $5;}' test.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Update nonexistent PCR fail +echo -ne "Update nonexistent PCR fail : " >> /tmp/Result +PCR_NUM=`awk -F ":" 'NR==9 {print $6;}' test.data` +PCR_VALUE=`awk -F ":" 'NR==10 {print $1;}' test.data` +MLE_TMP=`awk -F ":" 'NR==7 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==8 {print $1;}' test.data` +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"osName\":\"$OS_TMP\",\"osVersion\":\"$OS_VER\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Update all PCR which connect to one MLE record +echo -ne "Update all PCR : " >> /tmp/Result +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +PCR_N1=`awk -F ":" 'NR==9 {print $1;}' test.data` +PCR_D1=`awk -F ":" 'NR==10 {print $1;}' test.data` +PCR_N2=`awk -F ":" 'NR==9 {print $2;}' test.data` +PCR_D2=`awk -F ":" 'NR==10 {print $2;}' test.data` +INFO=`echo "{\"Name\":\"$MLE_TMP\",\"Version\":\"$MLE_VER\",\"OemName\":\"$OEM_TMP\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"Test\",\"MLE_Manifests\":[{\"Name\":\"$PCR_N1\",\"Value\":\"$PCR_D1\"},{\"Name\":\"$PCR_N2\",\"Value\":\"$PCR_D2\"}]}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo "Passed" >> /tmp/Result +else + echo "Failed" >> /tmp/Result +fi + +echo +echo "********************Update PCR with checking boundary value******************************" >> /tmp/Result +# Update PCR with null string +echo -ne "Update PCR with null string : " >> /tmp/Result +PCR_NUM=`awk -F ":" 'NR==9 {print $5;}' test.data` +PCR_VALUE=`awk -F ":" 'NR==10 {print $12;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Update PCR with edge lenth string +echo -ne "Update PCR with edge lenth string : " >> /tmp/Result +PCR_NUM=`awk -F ":" 'NR==9 {print $5;}' test.data` +PCR_VALUE=`awk -F ":" 'NR==10 {print $7;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Update PCR with over lenth string +echo -ne "Update PCR with over lenth string : " >> /tmp/Result +PCR_NUM=`awk -F ":" 'NR==9 {print $5;}' test.data` +PCR_VALUE=`awk -F ":" 'NR==10 {print $8;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +echo +echo "**********************Delete PCR Normal************************************************" >> /tmp/Result +# Delete PCR successful +echo -ne "Delete PCR successful : " >> /tmp/Result +PCR_NUM=`awk -F ":" 'NR==9 {print $9;}' test.data` +PCR_VALUE=`awk -F ":" 'NR==10 {print $9;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +INFO=`echo "{\"pcrName\":\"$PCR_NUM\",\"pcrDigest\":\"$PCR_VALUE\",\"mleName\":\"$MLE_TMP\",\"mleVersion\":\"$MLE_VER\",\"oemName\":\"$OEM_TMP\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr" -3 > /tmp/res +curl --cacert certfile.cer -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr?pcrName=$PCR_NUM&mleName=$MLE_TMP&mleVersion=$MLE_VER&oemName=$OEM_TMP" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Delete PCR fail +echo -ne "Delete PCR fail : " >> /tmp/Result +curl --cacert certfile.cer -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr?pcrName=$PCR_NUM&mleName=$MLE_TMP&mleVersion=$MLE_VER&oemName=$OEM_TMP" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +echo +echo "**********************Delete PCR with checking boundary value***************************" >> /tmp/Result +# Delete PCR with null string +echo -ne "Delete PCR with null string : " >> /tmp/Result +MLE_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +curl --cacert certfile.cer -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr?pcrName=&mleName=$MLE_TMP&mleVersion=$MLE_VER&oemName=$OEM_TMP" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Delete existed PCR with edge lenth string +echo -ne "Delete PCR with edge lenth string : " >> /tmp/Result +PCR_NUM=`awk -F ":" 'NR==9 {print $3;}' test.data` +MLE_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +MLE_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +curl --cacert certfile.cer -X DELETE "https://$HOST_NAME:$PORT/WLMService/resources/mles/whitelist/pcr?pcrName=$PCR_NUM&mleName=$MLE_TMP&mleVersion=$MLE_VER&oemName=$OEM_TMP" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +echo +echo +echo "#The result about HOST" >> /tmp/Result +echo +echo "***********************Add Host Normal***************************************************" >> /tmp/Result +# Add Host successful +echo -ne "Add Host successful : " >> /tmp/Result +HOST_TMP=`awk -F ":" 'NR==11 {print $1;}' test.data` +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +VMM_TMP=`awk -F ":" 'NR==7 {print $1;}' test.data` +VMM_VER=`awk -F ":" 'NR==8 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +BIOS_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +BIOS_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.1\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Add Host fail (noraml) +echo -ne "Add Host fail (normal) : " >> /tmp/Result +HOST_TMP=`awk -F ":" 'NR==11 {print $2;}' test.data` +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +VMM_TMP=`awk -F ":" 'NR==7 {print $1;}' test.data` +VMM_VER=`awk -F ":" 'NR==8 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +BIOS_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +BIOS_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.1\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" -3 > /tmp/res +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" -3 > /tmp/res + + if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo -e "Passed " >> /tmp/Result + else + echo -e "Failed " >> /tmp/Result + fi +else + echo "Passed" >> /tmp/Result +fi + +# Add Host with nonexistent MLE +echo -ne "Add Host with nonexistent MLE : " >> /tmp/Result +BIOS_TMP=`awk -F ":" 'NR==5 {print $9;}' test.data` +BIOS_VER=`awk -F ":" 'NR==6 {print $9;}' test.data` +VMM_TMP=`awk -F ":" 'NR==7 {print $9;}' test.data` +VMM_VER=`awk -F ":" 'NR==8 {print $9;}' test.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.1\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +echo +echo "*********************Add Host with checking boundary value*****************************" >> /tmp/Result +# Add Host with null string +echo -ne "Add Host with null string : " >> /tmp/Result +INFO=`echo "{\"HostName\":\"\",\"IPAddress\":\"192.168.0.2\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Add Host with edgelenth string +echo -ne "Add Host with edgelenth string : " >> /tmp/Result +HOST_TMP=`awk -F ":" 'NR==11 {print $3;}' test.data` +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +VMM_TMP=`awk -F ":" 'NR==7 {print $1;}' test.data` +VMM_VER=`awk -F ":" 'NR==8 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +BIOS_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +BIOS_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.2\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Add Host with over lenth string +echo -ne "Add Host with over lenth string : " >> /tmp/Result +HOST_TMP=`awk -F ":" 'NR==11 {print $4;}' test.data` +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +VMM_TMP=`awk -F ":" 'NR==7 {print $1;}' test.data` +VMM_VER=`awk -F ":" 'NR==8 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +BIOS_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +BIOS_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.2\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +echo +echo "********************Edit Host Normal*************************************************" >> /tmp/Result +# Edit Host successful +echo -ne "Edit Host successful : " >> /tmp/Result +HOST_TMP=`awk -F ":" 'NR==11 {print $5;}' test.data` +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +VMM_TMP=`awk -F ":" 'NR==7 {print $1;}' test.data` +VMM_VER=`awk -F ":" 'NR==8 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +BIOS_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +BIOS_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +HOST_DESC=`awk -F ":" 'NR==12 {print $1;}' test.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.2\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"$HOST_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" -3 > /tmp/res +HOST_DESC=`awk -F ":" 'NR==12 {print $5;}' test.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.2\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"$HOST_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Edit Host fail +echo -ne "Edit Host fail : " >> /tmp/Result +HOST_TMP=`awk -F ":" 'NR==11 {print $6;}' test.data` +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +VMM_TMP=`awk -F ":" 'NR==7 {print $1;}' test.data` +VMM_VER=`awk -F ":" 'NR==8 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +BIOS_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +BIOS_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +HOST_DESC=`awk -F ":" 'NR==12 {print $1;}' test.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.2\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"$HOST_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +echo +echo "*********************Edit Host with checking boundary value******************************" >> /tmp/Result +# Edit HOST with null string +echo -ne "Edit HOST with null string : " >> /tmp/Result +HOST_TMP=`awk -F ":" 'NR==11 {print $5;}' test.data` +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +VMM_TMP=`awk -F ":" 'NR==7 {print $1;}' test.data` +VMM_VER=`awk -F ":" 'NR==8 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +BIOS_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +BIOS_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.2\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +curl --cacert certfile.cer -H "Content-type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +#Edit existed HOST with edge string +echo -ne "Edit existed HOST with edge string : " >> /tmp/Result +HOST_TMP=`awk -F ":" 'NR==11 {print $5;}' test.data` +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +VMM_TMP=`awk -F ":" 'NR==7 {print $1;}' test.data` +VMM_VER=`awk -F ":" 'NR==8 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +BIOS_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +BIOS_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +HOST_DESC=`awk -F ":" 'NR==12 {print $7;}' test.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.2\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"$HOST_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Edit HOST with overlenth string +echo -ne "Edit HOST with overlenth string : " >> /tmp/Result +HOST_TMP=`awk -F ":" 'NR==11 {print $5;}' test.data` +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +VMM_TMP=`awk -F ":" 'NR==7 {print $1;}' test.data` +VMM_VER=`awk -F ":" 'NR==8 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +BIOS_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +BIOS_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +HOST_DESC=`awk -F ":" 'NR==12 {print $8;}' test.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.2\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"$HOST_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +echo +echo "********************Delete Host Normal*****************************************" >> /tmp/Result +# Delete Host successful +echo -ne "Delete Host successful : " >> /tmp/Result +HOST_TMP=`awk -F ":" 'NR==11 {print $9;}' test.data` +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +VMM_TMP=`awk -F ":" 'NR==7 {print $1;}' test.data` +VMM_VER=`awk -F ":" 'NR==8 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +BIOS_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +BIOS_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +HOST_DESC=`awk -F ":" 'NR==12 {print $7;}' test.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.2\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"$HOST_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" -3 > /dev/null +curl --cacert certfile.cer -X DELETE "https://$HOST_NAME:$PORT/AttestationService/resources/hosts?hostName=$HOST_TMP" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Delete Host fail +echo -ne "Delete Host fail : " >> /tmp/Result +HOST_TMP=`awk -F ":" 'NR==11 {print $10;}' test.data` +curl --cacert certfile.cer -X DELETE "https://$HOST_NAME:$PORT/AttestationService/resources/hosts?hostName=$HOST_TMP" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +echo +echo "********************Delete HOST with checking boundary value********************" >> /tmp/Result +# Delete HOST with null string +echo -ne "Delete HOST with null string : " >> /tmp/Result +curl --cacert certfile.cer -X DELETE "https://$HOST_NAME:$PORT/AttestationService/resources/hosts?hostName=" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" != "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + +# Delete HOST with edge lenth string +echo -ne "Delete HOST with edge lenth string : " >> /tmp/Result +HOST_TMP=`awk -F ":" 'NR==11 {print $11;}' test.data` +OS_TMP=`awk -F ":" 'NR==3 {print $1;}' test.data` +OS_VER=`awk -F ":" 'NR==4 {print $1;}' test.data` +VMM_TMP=`awk -F ":" 'NR==7 {print $1;}' test.data` +VMM_VER=`awk -F ":" 'NR==8 {print $1;}' test.data` +OEM_TMP=`awk -F ":" 'NR==2 {print $1;}' test.data` +BIOS_TMP=`awk -F ":" 'NR==5 {print $1;}' test.data` +BIOS_VER=`awk -F ":" 'NR==6 {print $1;}' test.data` +HOST_DESC=`awk -F ":" 'NR==12 {print $7;}' test.data` +INFO=`echo "{\"HostName\":\"$HOST_TMP\",\"IPAddress\":\"192.168.0.2\",\"Port\":\"8080\",\"BIOS_Name\":\"$BIOS_TMP\",\"BIOS_Version\":\"$BIOS_VER\",\"BIOS_Oem\":\"$OEM_TMP\",\"VMM_Name\":\"$VMM_TMP\",\"VMM_Version\":\"$VMM_VER\",\"VMM_OSName\":\"$OS_TMP\",\"VMM_OSVersion\":\"$OS_VER\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"$HOST_DESC\"}"` +curl --cacert certfile.cer -H "Content-Type: application/json" -X POST -d $INFO "https://$HOST_NAME:$PORT/AttestationService/resources/hosts" -3 > /dev/null +curl --cacert certfile.cer -X DELETE "https://$HOST_NAME:$PORT/AttestationService/resources/hosts?hostName=$HOST_TMP" -3 > /tmp/res + +if [ "`awk '$1 ~/True/' /tmp/res`" = "True" ];then + echo -e "Passed " >> /tmp/Result +else + echo -e "Failed " >> /tmp/Result +fi + diff --git a/OpenAttestation/Test/forpoll.data b/OpenAttestation/Test/forpoll.data new file mode 100644 index 0000000..ac9e988 --- /dev/null +++ b/OpenAttestation/Test/forpoll.data @@ -0,0 +1,6 @@ +###### Add machine and pcrs info as below +Machine_Name= +PCR_Num_for_BIOS= +PCR_Value_for_BIOS= +PCR_Num_for_VMM= +PCR_Value_for_VMM= diff --git a/OpenAttestation/Test/pollhost.sh b/OpenAttestation/Test/pollhost.sh new file mode 100644 index 0000000..c9472d9 --- /dev/null +++ b/OpenAttestation/Test/pollhost.sh @@ -0,0 +1,39 @@ +#!/bin/bash + +echo -n "Please enter the OAT server name[default:localhost]: " +read HOST_NAME +if [ "$HOST_NAME" = "" ];then + HOST_NAME=localhost +fi + +if [ -f ./certfile.cer ];then + sleep 1 +else + echo "Please make sure there is "certfile.cer" in current folder" + exit 1 +fi + +MACHINE=`awk -F "=" 'NR==2 {print $2;}' forpoll.data` +NUMB=`awk -F "=" 'NR==3 -F {print $2;}' forpoll.data` +PCRB=`awk -F "=" 'NR==4 -F {print $2;}' forpoll.data` +NUMA=`awk -F "=" 'NR==5 -F {print $2;}' forpoll.data` +PCRA=`awk -F "=" 'NR==6 -F {print $2;}' forpoll.data` +PORT=8443 + +curl --cacert ./certfile.cer -H "Content-Type: application/json" -X POST -d '{"Name":"OS1","Version":"v1234","Description":"Test1"}' https://$HOST_NAME:$PORT/WLMService/resources/os -ssl3 +curl --cacert ./certfile.cer -H "Content-Type: application/json" -X POST -d '{"Name":"OEM1","Description":"Newdescription"}' https://$HOST_NAME:$PORT/WLMService/resources/oem -ssl3 +INFO=`echo "{\"Name\":\"NewRHELMLE\",\"Version\":\"123\",\"OsName\":\"OS1\",\"OsVersion\":\"v1234\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"VMM\",\"Description\":\"Test\",\"MLE_Manifests\":[{\"Name\":\"$NUMA\",\"Value\":\"$PCRA\"}]}"` +curl --cacert ./certfile.cer -H "Content-Type: application/json" -X POST -d $INFO https://$HOST_NAME:$PORT/WLMService/resources/mles -ssl3 > /tmp/mle +if [ "`awk '$1 ~/True/' /tmp/mle`" != "True" ];then + curl --cacert ./certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO https://$HOST_NAME:$PORT/WLMService/resources/mles -ssl3 +fi +INFO=`echo "{\"Name\":\"New2\",\"Version\":\"123\",\"OemName\":\"OEM1\",\"Attestation_Type\":\"PCR\",\"MLE_Type\":\"BIOS\",\"Description\":\"Test1111\",\"MLE_Manifests\":[{\"Name\":\"$NUMB\",\"Value\":\"$PCRB\"}]}"` +curl --cacert ./certfile.cer -H "Content-Type: application/json" -X POST -d $INFO https://$HOST_NAME:$PORT/WLMService/resources/mles -ssl3 > /tmp/mle +if [ "`awk '$1 ~/True/' /tmp/mle`" != "True" ];then + curl --cacert ./certfile.cer -H "Content-Type: application/json" -X PUT -d $INFO https://$HOST_NAME:$PORT/WLMService/resources/mles -ssl3 +fi +INFO=`echo "{\"HostName\":\"$MACHINE\",\"IPAddress\":\"192.168.0.1\",\"Port\":\"8080\",\"BIOS_Name\":\"New2\",\"BIOS_Version\":\"123\",\"BIOS_Oem\":\"OEM1\",\"VMM_Name\":\"NewRHELMLE\",\"VMM_Version\":\"123\",\"VMM_OSName\":\"OS1\",\"VMM_OSVersion\":\"v1234\",\"Email\":\"\",\"AddOn_Connection_String\":\"\",\"Description\":\"\"}"` +curl --cacert ./certfile.cer -H "Content-Type: application/json" -X POST -d $INFO https://$HOST_NAME:$PORT/AttestationService/resources/hosts -ssl3 +INFO=`echo "{\"hosts\":[\"$MACHINE\"]}"` +echo +curl --cacert ./certfile.cer -H "Content-Type: application/json" -X POST -d $INFO https://$HOST_NAME:$PORT/AttestationService/resources/PollHosts -ssl3 >> /tmp/Result diff --git a/OpenAttestation/Test/test.data b/OpenAttestation/Test/test.data new file mode 100644 index 0000000..d9ef9d3 --- /dev/null +++ b/OpenAttestation/Test/test.data @@ -0,0 +1,12 @@ +Normal_s:Normal_f:EdgeLenth_a:OverLenth_a:Edit_s:Edit_f:EdgeLenth_e:OverLenth_e:Delete_s:Delete_f:EdgeLenth_d:NULL +oemas:oemaf:oemedgelenthoemedgelenthoemedgelenthoemedgelenthas:oemoverlenthoemoverlenthoemoverlenthoemoverlenthoemoverlenthaff:oemes:oemef:oemedgelenthoemedgelenthoemedgelenthoemedgelenthes:oemoverlenthoemoverlenthoemoverlenthoemoverlenthoemoverlentheff:oemds:oemdf:oemedgelenthoemedgelenthoemedgelenthoemedgelenthds: +osas:osaf:osedgelenthosedgelenthosedgelenthosedgelenthosedas:osoverlenthosoverlenthosoverlenthosoverlenthosoverlenthosedgeaf:oses:osef:osedgelenthosedgelenthosedgelenthosedgelenthosedes:osoverlenthosoverlenthosoverlenthosoverlenthosoverlenthosedgeff:osds:osdf:osedgelenthosedgelenthosedgelenthosedgelenthosedds: +v1as:v1af:v1edgelenthv1edgelenthv1edgelenthv1edgelenthv1asas:v1overlenthv1overlenthv1overlenthv1overlenthv1afaf:v1es:v1ef:v1edgelenthv1edgelenthv1edgelenthv1edgelenthv1eses:v1overlenthv1overlenthv1overlenthv1overlenthv1efef:v1ds:v1df:v1edgelenthv1edgelenthv1edgelenthv1edgelenthv1dsds: +mlebas:mlebaf:mlebedgelenthmlebedgelenthmlebedgelenthmlebedgelas:mleboverlenthmleboverlenthmleboverlenthmleboverleaf:mlebes:mlebef:mlebedgelenthmlebedgelenthmlebedgelenthmlebedgeles:mleboverlenthmleboverlenthmleboverlenthmleboverlef:mlebds:mlebdf:mlebedgelenthmlebedgelenthmlebedgelenthmlebedgelds: +v2as:v2af:v2edgelenthv2edgelenthv2edgelenthv2edgelenthv2edgelenthv2edgelenthv2edgelenthv2edgelenthv2edgelenths:v2overlenthv2overlenthv2overlenthv2overlenthv2overlenthv2overlenthv2overlenthv2overlenthv2overlenthaf:v2es:v2ef:v2edgelenthv2edgelenthv2edgelenthv2edgelenthv2edgelenthv2edgelenthv2edgelenthv2edgelenthv2edgelenths:v2overlenthv2overlenthv2overlenthv2overlenthv2overlenthv2overlenthv2overlenthv2overlenthv2overlenthef:v2ds:v2df:v2edgelenthv2edgelenthv2edgelenthv2edgelenthv2edgelenthv2edgelenthv2edgelenthv2edgelenthv2edgelenths: +mlevas:mlevaf:mlevedgelenthmlevedgelenthmlevedgelenthmlevedgelas:mlevoverlenthmlevoverlenthmlevoverlenthmlevoverlaf:mleves:mlevef:mlevedgelenthmlevedgelenthmlevedgelenthmlevedgeles:mlevoverlenthmlevoverlenthmlevoverlenthmlevoverlef:mlevds:mlevdf:mlevedgelenthmlevedgelenthmlevedgelenthmlevedgelds: +v3as:v3af:v3edgelenthv3edgelenthv3edgelenthv3edgelenthv3edgelenthv3edgelenthv3edgelenthv3edgelenthv3edgelenths:v3overlenthv3overlenthv3overlenthv3overlenthv3overlenthv3overlenthv3overlenthv3overlenthv3overlenthaf:v3es:v3ef:v3edgelenthv3edgelenthv3edgelenthv3edgelenthv3edgelenthv3edgelenthv3edgelenthv3edgelenthv3edgelenths:v3overlenthv3overlenthv3overlenthv3overlenthv3overlenthv3overlenthv3overlenthv3overlenthv3overlenthef:v3ds:v3df:v3edgelenthv3edgelenthv3edgelenthv3edgelenthv3edgelenthv3edgelenthv3edgelenthv3edgelenthv3edgelenths: +0:10:111:10000000000:1:11:1111111111:11111111111:2:21:2222222222: +0000000000:00000000001:0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000:00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000:1111111111:11111111112:1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111:11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111:2222222222:22222222223:2222222222: +host1as:host1af:hostedgelenthhostedgelenthhostedgelenthhostedgeass:hostoverlenthhostoverlenthhostoverlenthhostoveraff1:host1es:host1ef:hostedgelenthhostedgelenthhostedgelenthhostedgeess:hostoverlenthhostoverlenthhostoverlenthhostovereff1:host1ds:host1ds:hostedgelenthhostedgelenthhostedgelenthhostedgedss: +descriptionas:descriptionaf:descriptionedgelenthdescriptionedgelenthdescriptionedgelenthdescriptionedgelenthdescriptionedgelenas:descriptionoverlenthdescriptionoverlenthdescriptionoverlenthdescriptionoverlenthdescriptionoverlenaf:descriptiones:descriptionef:descriptionedgelenthdescriptionedgelenthdescriptionedgelenthdescriptionedgelenthdescriptionedgelenes:descriptionoverlenthdescriptionoverlenthdescriptionoverlenthdescriptionoverlenthefdescriptionoverlenef:fordel:fordel:fordel: diff --git a/OpenAttestation/docs/BSD_LICENSE b/OpenAttestation/docs/BSD_LICENSE new file mode 100644 index 0000000..2c17a57 --- /dev/null +++ b/OpenAttestation/docs/BSD_LICENSE @@ -0,0 +1,27 @@ +OpenAttestation is released under the BSD license - + +==== + Copyright (C) 2011, U.S. Government, National Security Agency, National Information Assurance Research Laboratory + This is a work of the UNITED STATES GOVERNMENT and is not subject to copyright protection in the United States. Foreign copyrights may apply. + 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) Neither the name of the NATIONAL SECURITY AGENCY/NATIONAL INFORMATION ASSURANCE RESEARCH LABORATORY nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT HOLDER OR 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. + + + +==== +Copyright (c) 2012, Intel Corporation +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * 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. + * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 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 THE COPYRIGHT OWNER OR 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. + diff --git a/OpenAttestation/docs/Build.pdf b/OpenAttestation/docs/Build.pdf new file mode 100644 index 0000000..1107cc4 Binary files /dev/null and b/OpenAttestation/docs/Build.pdf differ diff --git a/OpenAttestation/docs/IR_new_storage.pdf b/OpenAttestation/docs/IR_new_storage.pdf new file mode 100644 index 0000000..0a1617f Binary files /dev/null and b/OpenAttestation/docs/IR_new_storage.pdf differ diff --git a/OpenAttestation/docs/Installation.pdf b/OpenAttestation/docs/Installation.pdf new file mode 100644 index 0000000..922d314 Binary files /dev/null and b/OpenAttestation/docs/Installation.pdf differ diff --git a/OpenAttestation/docs/MUST_READ_1st.pdf b/OpenAttestation/docs/MUST_READ_1st.pdf new file mode 100644 index 0000000..2b97afd Binary files /dev/null and b/OpenAttestation/docs/MUST_READ_1st.pdf differ diff --git a/OpenAttestation/docs/Overview.pdf b/OpenAttestation/docs/Overview.pdf new file mode 100644 index 0000000..dcebffa Binary files /dev/null and b/OpenAttestation/docs/Overview.pdf differ diff --git a/OpenAttestation/docs/Trouble_Shooting.pdf b/OpenAttestation/docs/Trouble_Shooting.pdf new file mode 100644 index 0000000..7c22b9f Binary files /dev/null and b/OpenAttestation/docs/Trouble_Shooting.pdf differ diff --git a/README.md b/README.md new file mode 100644 index 0000000..23e0170 --- /dev/null +++ b/README.md @@ -0,0 +1,309 @@ +# Introduction + +The code in this repository is used to create a Third-Party Verifier, which is able to perform TCG compliant remote attestation operation on the NED(s) pre-registered to it. + +The verifier hosts four services, remote attestation server, IMA reference database, periodic attestation tasks, web service publishes the attestation result. + +The remote attestation server is using [OpenAttestation v1.7](https://github.com/OpenAttestation/OpenAttestation/tree/v1.7) with additional tools to find the IMA measurements in the integrity report sent from the NED to the verifier in the reference database. + +The reference database is hosted using [apache-cassandra-1.2.19](http://cassandra.apache.org/), with customised modules to compare the package's versions, and store them in order in the reference database. + +The periodic attestation is created using [Celery](http://www.celeryproject.org/), and the message broker is [rabbitmq](https://www.rabbitmq.com/). + +The verifier is a computing intensive entity, the minimum spec is 2 CPU cores @ 2.66Ghz + 4GB memory + 4GB swap, the recommended spec is 4 cores @ 3392.142MHz + 4GB memory + 4GB swap. + + +# Dependencies for CentOS7 mininal installation: + +~~~bash +root@verifier# yum install epel-release +root@verifier# yum install ant trousers trousers-devel php-soap mariadb mariadb-server python-networkx python-suds python-matplotlib graphviz-devel patch java-1.7.0-openjdk java-1.7.0-openjdk-devel zip unzip gcc gcc-c++ rpm-build python-pip git httpd php php-mysql rpm-devel rabbitmq-server mod_ssl mysql-connector-python firewalld +root@verifier# pip install pycassa pygraphviz Celery urllib3 requests tornado +~~~ + +# Installation steps: +0. it is assumed that the initial directory is `BASEDIR/verifier` and all files are cloned to this directory; + +1. map the verifier's ip address into `/etc/hosts` and change the local host name + to 'verifier', to simplify the future setup; + + ```bash + root@verifier# echo -e 'xxx.xxx.xxx.xxx \t verifier' >> /etc/hosts + root@verifier# echo 'verifier' > /etc/hostname + ``` + + attestation requests are sent to the host named verifier. + +2. go to `BASEDIR/verifier/OpenAttestation/Source` directory, run + `distribute_jar_packages.sh`; + + ```bash + root@verifier# cd BASEDIR/verifier/OpenAttestation/Source + root@verifier# bash distribute_jar_packages.sh + ``` + +3. go to `BASEDIR/verifier/OpenAttestation/Installer` directory, run `rpm.sh` to + compile the OAT-appraiser package; + + ```bash + root@verifier# cd BASEDIR/verifier/OpenAttestation/Installer + root@verifier# sh rpm.sh -s BASEDIR/verifier/OpenAttestation/Source + ``` + exactly from this directory, otherwise it does not work. + +4. install the package of `/root/rpmbuild/RPMS/x86_64/OAT-Appraiser-Base-OATapp-1.0.0-2.el7.centos.x86_64.rpm`; + + ``` bash + root@verifier# systemctl start mariadb + root@verifier# systemctl enable mariadb + root@verifier# cd /root/rpmbuild/RPMS/x86_64/ + root@verifier# yum localinstall OAT-Appraiser-Base-OATapp-1.0.0-2.el7.centos.x86_64.rpm + root@verifier# systemctl daemon-reload + ``` + run this step only when mariadb service is running, because during installation phase, OAT will create database `oat_db` in mariadb. + +5. go to `BASEDIR/verifier/OpenAttestation/CommandTool` directory, and generate the CA certificate which will be used to access the OpenAttestation's services; + + ```bash + user@verifier$ cd BASEDIR/verifier/OpenAttestation/CommandTool + user@verifier$ bash oat_cert -h verifier + ``` + +6. and configure OpenAttestation with the `configure_oat.sh` following this format; + + ``` bash + user@verifier$ bash configure_oat.sh $selfname $attestorname $attestorIP $PCR0value $OSdistname $RApath $DBIP $CERTDGST + ``` + + example: + + ```bash + bash configure_oat.sh verifier ned xxx.xxx.xxx.xxx 7D94A15BE0295A3743FC259B07202FF42550B369 CentOS7 /root/ratools-tclouds/verifier/v2/ra_verifier.py xxx.xxx.xxx.xxx 8b71648e9c52a24cfe259305c611483ea56ca4dc + ``` + + $selfname is 'verifier' by default, it is the host accepting the attestation requests + + $attestorname is the attestor's hostname, which will be used in the attestation requests + + $attestorIP is the IP address of the attestor, which will be linked the $attestorname + + $PCR0value is the value in the PCR0 slot in the TPM, which is used as a golden value with VALIDATE_PCR command + + $OSdistname is the distribution of the OS running in the attestor, which will be used in the attestation analysis + + $RApath is the path to the ra_verifier.py script, which is used to analyse the IMA measurements + + $DBIP is the ip of the reference database, if the database is running inside the same machine, please just put `localhost` + + $CERTDGST is the SHA1 digest of the file containing the strongSwan certificate used for NED to authenticate itself (i.e. peerCert.der) + +7. open ports for receiving/sending integrity reports, default ports are 80 and 8443 + + ``` bash + root@verifier# firewall-cmd --permanent --add-port=80/tcp + root@verifier# firewall-cmd --add-port=80/tcp + root@verifier# firewall-cmd --permanent --add-port=8443/tcp + root@verifier# firewall-cmd --add-port=8443/tcp + ``` + +8. change `/etc/oat-appraiser/OAT.properties` to store integrity reports in files, receive delta reports and discard identical integrity reports; + + uncomment IR_DIR, IR_DIGEST_METHOD, SCALABILITY, DISCARD_IDENTICAL_IR + +9. to check if the verifier is working, use a browser to access the verifier's reference portal in the following link address: + + `http://verifier/OAT/alerts.php` + + In case of 403 Forbidden error, needs to change the permission of `/var/www/html/OAT`. + +10. in this step, ned need to be configured; + + read guidelines in ned repo. + +11. install cassandra reference database; + + ```bash + root@verifier# cd BASEDIR/verifier/db/install + root@verifier# tar -xvzf apache-cassandra-1.2.19-bin.tar.gz + root@verifier# ./install_cassandra_libs.sh BASEDIR/verifier/db/install/apache-cassandra-1.2.19 + ``` + +12. initialise the reference database with the schema used to store the information; + + ```bash + root@verifier# cd BASEDIR/verifier/db/install/apache-cassandra-1.2.19/bin + root@verifier# ./cassandra > /dev/null + root@verifier# ./cassandra-cli -h localhost -f BASEDIR/verifier/db/install/cassandra/schema/cassandra-schema-common.txt + root@verifier# ./cassandra-cli -h localhost -f BASEDIR/verifier/db/install/cassandra/schema/cassandra-schema-rpm.txt + ``` + +13. copy configuration files into `/etc/ra`; + + ```bash + root@verifier# mkdir /etc/ra + root@verifier# cp BASEDIR/verifier/db/conf/pkgs_download_list.conf.sample /etc/ra/pkgs_download_list.conf + root@verifier# cp BASEDIR/verifier/db/conf/ra.conf.sample /etc/ra/ra.conf + ``` +RABASEDIR in ra.conf needs to be changed to `BASEDIR/verifier` + +14. create `Packages` directory, go to `scripts` directory and run `update_pkgs.sh`; + + ```bash + root@verifier# mkdir BASEDIR/verifier/Packages + root@verifier# cd BASEDIR/verifier/db/scripts + root@verifier# bash update_pkgs.sh + ``` +15. when the database is created, please use the `ra_verifier.py` script to test it; + + ```bash + root@verifier# cd BASEDIR/verifier/v2 + root@verifier# ./ra_verifier.py -i BASEDIR/verifier/db/measurements/ascii_runtime_measurements -q CentOS7 -a "load-time,l_req=l4|>=" -v -H localhost + ``` +Should see information like following: + ```bash + Info: 0 (0/0) + 0 (0/0) + 0 + 0 + + Info: 0.00266 + 0.24042 + 0.07041 + 0.11005 + 0 + 0.42355 + ``` + +16. start the command in CommandTool to poll the integrity reports and verify it as defined in the configure.sh script; + + ``` bash + root@verifier# bash oat_pollhosts -h verifier '{"hosts":["ned"],"analysisType":"load-time+check-cert,l_req=l4_ima_all_ok|==,cert_digest=095b7792c076d65a9c45f4f484d06cd1fa29a9ba"}' + ``` + +17. if returned result is 'untrusted', which means the attestation feature is actually working, but there are some unknown digests in the IMA measurement list. In order to see which are unknown digests, run the following command: + + ```python + URL=https://verifier:8443/HisWebServices/hisDownloadReportService?wsdl IR=177 OS=CentOS7 /BASEDIR/verifier/v2/ra_verifier.py -H localhost -a "load-time+check-cert,l_req=l4_ima_all_ok|==,cert_digest=095b7792c076d65a9c45f4f484d06cd1fa29a9ba" -v + ``` +You need to change the IR to the id received in the previous command (i.e. pollhosts) and also the cert_digest to the one measured in the NED. +For unknown digests, two possible solutions. First, insert unknown digests in the whilelist, which is stored in ``/BASEDIR/verifier/v2/structs.py`, called known_digests. If multiple unknown digests are from a same package, which is not installed from the official repository, then you can insert the package manually as a 'testing' package with following command: + ```bash + user@verifier$ bash /BASEDIR/verifier/db/scripts/update_pkgs.sh -d temp/ -t testing -n CentOS -q 7 -c x86_64 + ``` +Where `temp` directory is used for storing the testing packages. + +18. to update the certificate used by strongSwan in the NED, the information of this NED needs to be updated; + + ```bash + root@verifier:# bash update_cert.sh $selfname $attestorname $attestorIP $OSdistname $CERTDGST + ``` +example: + ```bash + user@verifier$ update_cert.sh verifier ned xxx.xxx.xxx.xxx CentOS7 8b71648e9c52a24cfe259305c611483ea56ca4dc + ``` + +19. to configure periodic attestation task; first need to configure `rabbitmq-server` + + ```bash + root@verifier:# rabbitmqctl add_user user secured + root@verifier:# rabbitmqctl add_vhost uservhost + root@verifier:# rabbitmqctl set_permissions -p uservhost user ".*" ".*" ".*" + root@verifier:# systemctl enable rabbitmq-server + root@verifier:# systemctl start rabbitmq-server + ``` +If you start the `rabbitmq-server`, your rabbit node should now be rabbit@myhost, as verified by _rabbitmqctl_: + ```bash + root@verifier:# rabbitmqctl status + ``` +If you need to stop the rabbitmq server, just run: + ```bash + root@verifier:# rabbitmqctl stop + ``` + +20. after `rabbitmq-server` is running, you can configure Celery in `/BASEDIR/verifier/ram/config.py` and `/BASEDIR/verifier/ram/celeryconfig.py`. +In `celeryconfig.py`, you can change the periodic attestation frequency. In `config.py`, you can change the OpenAttestation related parameters, especially `OAT_NODE`, `OAT_VERIFIER` and `OAT_LEVEL`. Also, the new certificate generated by OpenAttestation (i.e. certfile.cer) needs to be copied from the `BASEDIR/verifier/OpenAttestation/CommandTool` into `data` directory to replace the old one. +Then copy `/BASEDIR/verifier/ram` to `/home/user/ram` and start the periodic task with user account. + + ```bash + root@verifier:# cp /BASEDIR/verifier/OpenAttestation/CommandTool/certfile.cer /BASEDIR/verifier/ram/data/certfile.cer + root@verifier:# cp -r /BASEDIR/verifier/ram /home/user/ram + root@verifier:# su user + user@verifier:$ cd /home/user/ram + user@verifier:$ celery -A tasks worker --beat & + ``` +In order for OpenAttestation to know the certificate used by strongswan in the NED to authenticate itself, when the NED is registering to the verifier, it also needs to input the digest of the file containing his certificate (i.e. [`peerCert.der`](https://gitlab.secured-fp7.eu/secured/ned/tree/strongswan/strongswan) step 6 in NED repository) along with it, see [step 7](https://gitlab.secured-fp7.eu/secured/verifier/blob/devel/README.md) in verifier repository. +When NED revokes its certificate, it needs to be re-registered again, with the digest of the certificate, with the _update_cert.sh_ script in `/BASEDIR/verifier/OpenAttestation/CommandTool` directory. + +21. The web service created by OpenAttestation, running by _httpd_, the configuration files are in `/etc/httpd/conf.d`, need to change `ssl.conf` by adding new ServerName attribute `ServerName verifier:443`, and need to copy `tossl.conf` to the same `/etc/httpd/conf.d` directory. And the web page for user to read the attestation result changes to _https://verifier/OAT/result.php?CN=ned2&LEVEL=4&DGST=8b71648e9c52a24cfe259305c611483ea56ca4dc_, it will provide the same result as it was. +The REST API has also changed from `http` to `https`, the new URL to the REST API is `https://verifier/OAT/attest.php`. + +22. if OpenAttestation has been installed and running correctly, just need to copy the new php files in the `/BASEDIR/verifier/OpenAttestation/Source/Portal` directory into `/var/www/html/OAT` directory. + +23. in order to register multiple NEDs into this verifier, need to run the steps defined in `NED setup` in the NED README. Afterward, need to run `add_NED.sh` in the `/BASEDIR/verifier/OpenAttestation/CommandTool` directory as following. + + ``` bash + user@verifier$ bash add_NED.sh $selfname $attestorname $attestorIP $PCR0value $OSdistname $CERTDGST + ``` +example: + ```bash + add_NED.sh verifier ned2 xxx.xxx.xxx.xxx 7D94A15BE0295A3743FC259B07202FF42550B369 CentOS7 8b71648e9c52a24cfe259305c611483ea56ca4dc + ``` +Then the new NED's name needs to be inserted into the `OAT_NODE` variable in `BASEDIR/verifier/ram/config.py` file. + +## Example +You need to change the ned's cert_digest. + +Open _https://verifier/OAT/result.php?CN=ned2&LEVEL=4&DGST=8b71648e9c52a24cfe259305c611483ea56ca4dc_ with a browser to see the attestation result. + +* CN is the common name of the NED +* LEVEL is the trust level of the requirement +* DGST is the digest of the strongSwan certificate used by the NED + +Or send POST requests to `https://verifier/OAT/attest.php`: + + ```bash + user@verifier:$ PDATA='{"hosts":["ned"],"analysisType":"load-time+check-cert,l_req=l4_ima_all_ok|>=,cert_digest=efae492da504edea2c2358dea1fb1e6770780b6e"}' + user@verifier:$ curl -XPOST -H "Content-Type:application/json" -d "$PDATA" https://verifier/OAT/attest.php + ``` +You need to change the ned's cert_digest. +Response is a JSON message structed as following: +Responses will be a JSON message structured as follow: + +```json +{ + "status": "success", + "n_results": 1, + "results":[ + { + "trust_lvl": "trusted", + "host_name": "ned" + }, + ] +} +``` +## License + + The MIT License (MIT) + + Copyright (c) 2015 TORSEC Group (http://security.polito.it) + Politecnico di Torino + + author: Tao Su + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. diff --git a/db/README.md b/db/README.md new file mode 100644 index 0000000..468517a --- /dev/null +++ b/db/README.md @@ -0,0 +1,69 @@ +# Introduction + +The scripts in this directory is to create a external reference database used by the external analysis tool of OpenAttestion framework, they are developed by TorSec Group in Politecnico di Torino. The external analysis tool relies on this database to verify the digests of the executable running in the attested platform. The database chosen is Cassandra-1.2.19. These scripts are capable to download the update packages from pre-defined repositories, de-compile them, compute the SHA1 values of the binraies and meanwhile find its update type, and insert them into the reference database. Then when challenger is attesting the target, it can know what software is running in the attestor and whether it is up-to-date, and if it has security vulnerability. + +Only packages of CentOS7 is considered here. + +# Dependencies + +```bash +root@verifier# yum install rpm-devel java-1.7-0-openjdk.x86_64 java-1.7-0-openjdk-devel.x86_64 python-pip +root@verifier# pip install pycassa pygraphviz +``` + +# Installation steps +0. It is assumed all files are cloned as they are in the repository. The base directory is $BASEDIR/verifier; + +1. go to install directory, un-compress the cassandra database; +```bash +root@verifier# cd BASEDIR/verifier/db/install +root@verifier# tar -xvzf apache-cassandra-1.2.19-bin.tar.gz +``` + +2. install cassandra database; +```bash +root@verifier# ./install_cassandra_libs.sh BASEDIR/verifier/db/install/apache-cassandra-1.2.19 +``` + +3. initialise the database with the schema used to store the information; +```bash +root@verifier# cd BASEDIR/verifier/db/install/apache-cassandra-1.2.19/bin +root@verifier# ./cassandra > /dev/null +root@verifier# ./cassandra-cli -h localhost -f BASEDIR/verifier/db/install/cassandra/schema/cassandra-schema-common.txt +root@verifier# ./cassandra-cli -h localhost -f BASEDIR/verifier/db/install/cassandra/schema/cassandra-schema-rpm.txt +``` + +4. copy configuration files into `/etc/ra`; +```bash +root@verifier# mkdir /etc/ra +root@verifier# cp BASEDIR/verifier/db/conf/pkgs_download_list.conf.sample /etc/ra/pkgs_download_list.conf +root@verifier# cp BASEDIR/verifier/db/conf/ra.conf.sample /etc/ra/ra.conf +``` +RABASEDIR attribute in ra.conf needs to be changed to `BASEDIR/verifier` + +5. create Packages directory, go to `scripts` directory and run `update_pkgs.sh`; +```bash +root@verifier# mkdir BASEDIR/verifier/Packages +root@verifier# cd BASEDIR/verifier/db/scripts +root@verifier# bash update_pkgs.sh +``` +6. when the database is created, please use the `ra_verifier.py` script to test it; +```bash +root@verifier# cd BASEDIR/verifier/v2 +root@verifier# ./ra_verifier.py -i BASEDIR/verifier/db/measurements/ascii_runtime_measurements -q CentOS7 -a "load-time,l_req=l4|>=" -v -H localhost +``` + +Should see information: +```bash +Info: 0 (0/0) +0 (0/0) +0 +0 + +Info: 0.00266 +0.24042 +0.07041 +0.11005 +0 +0.42355 +``` diff --git a/db/conf/pkgs_download_list.conf.sample b/db/conf/pkgs_download_list.conf.sample new file mode 100644 index 0000000..7d58977 --- /dev/null +++ b/db/conf/pkgs_download_list.conf.sample @@ -0,0 +1,2 @@ +CentOS 7 7.1.1503/updates/x86_64/Packages x86_64 rsync anonymous mirror.de.leaseweb.net centos CentOS updates +CentOS 7 7.1.1503/os/x86_64/Packages x86_64 rsync anonymous mirror.de.leaseweb.net centos CentOS newpackage diff --git a/db/conf/ra.conf.sample b/db/conf/ra.conf.sample new file mode 100644 index 0000000..9731f25 --- /dev/null +++ b/db/conf/ra.conf.sample @@ -0,0 +1,8 @@ +# Set this variable to the directory path of the RA installation +RABASEDIR="/srv/ra" + +# Set this variable to the directory where packages are downloaded +TARGETBASEDIR="$RABASEDIR/Packages" + +# Set this variable to of the Apache Cassandra database +CASSANDRAURL="localhost:9160" diff --git a/db/install/apache-cassandra-1.2.19-bin.tar.gz b/db/install/apache-cassandra-1.2.19-bin.tar.gz new file mode 100644 index 0000000..9bf6ea5 Binary files /dev/null and b/db/install/apache-cassandra-1.2.19-bin.tar.gz differ diff --git a/db/install/cassandra/Makefile b/db/install/cassandra/Makefile new file mode 100644 index 0000000..92701ec --- /dev/null +++ b/db/install/cassandra/Makefile @@ -0,0 +1,27 @@ +CC := cc +CFLAGS := -fPIC -Werror +LDFLAGS := -s +OBJ := filevercmp.o filevercmp_deb.o filevercmp_java.o filevercmp_java_deb.o + +%.o : %.c + $(CC) $(CFLAGS) -c $< -I $(JAVAHEADERS) -I $(JAVAHEADERS)/linux + +libfilevercmp.so: $(OBJ) + $(CC) $(LDFLAGS) -shared -Wl,-soname,$@ -o $@ $(OBJ) -lrpm + +rassandra.jar: + javac -cp $(CASSANDRACLASSPATH) torsec/ra/cassandra/db/PackagesVersionType.java torsec/ra/cassandra/db/PackagesVersionTypeDEB.java + javah -jni -classpath $(CASSANDRACLASSPATH):. torsec.ra.cassandra.db.PackagesVersionType + javah -jni -classpath $(CASSANDRACLASSPATH):. torsec.ra.cassandra.db.PackagesVersionTypeDEB + jar cf rassandra.jar torsec + +clean: + rm -Rf *.o libfilevercmp.so rassandra.jar + rm -Rf torsec/ra/cassandra/db/*.class + rm -Rf torsec_ra_cassandra_db_PackagesVersionType*.h + +all: rassandra.jar libfilevercmp.so + +install: + install -m 744 libfilevercmp.so $(DESTDIR)$(LIBDIR) + install -m 644 rassandra.jar ${DESTDIR}$(CASSANDRADIR)/lib diff --git a/db/install/cassandra/filevercmp.c b/db/install/cassandra/filevercmp.c new file mode 100644 index 0000000..fde0152 --- /dev/null +++ b/db/install/cassandra/filevercmp.c @@ -0,0 +1,99 @@ +/* + * filevercmp.c: compare RPM versions + * + * Copyright (C) 2014 Politecnico di Torino, Italy + * TORSEC group -- http://security.polito.it + * + * Author: Roberto Sassu + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see + * . + * + */ + +#include +#include +#include + + +static int compare_values(const char *str1, const char *str2) +{ + if (!str1 && !str2) + return 0; + else if (str1 && !str2) + return 1; + else if (!str1 && str2) + return -1; + return rpmvercmp(str1, str2); +} + +int filevercmp(const char *a, const char *b) +{ + const char *v1, *r1, *v2, *r2; + const char *e1 = "0", *e2 = "0"; + char *a_copy, *b_copy, *ptr; + int rc; + + if (strcmp(a, b) == 0) + return 0; + + a_copy = strdup(a); + if (a_copy == NULL) { + printf("allocation error\n"); + return 0; + } + + b_copy = strdup(b); + if (b_copy == NULL) { + printf("allocation error\n"); + free(a_copy); + return 0; + } + + v1 = a_copy; + v2 = b_copy; + + ptr = strchr(a_copy, ':'); + if (ptr != NULL) { + *ptr = '\0'; + e1 = a_copy; + v1 = ptr + 1; + } + + ptr = strchr(b_copy, ':'); + if (ptr != NULL) { + *ptr = '\0'; + e2 = b_copy; + v2 = ptr + 1; + } + + ptr = strchr(v1, '-'); + *ptr = '\0'; + r1 = ptr + 1; + + ptr = strchr(v2, '-'); + *ptr = '\0'; + r2 = ptr + 1; + + rc = compare_values(e1, e2); + if (!rc) { + rc = compare_values(v1, v2); + if (!rc) + rc = compare_values(r1, r2); + } + + free(a_copy); + free(b_copy); + return rc; +} diff --git a/db/install/cassandra/filevercmp_deb.c b/db/install/cassandra/filevercmp_deb.c new file mode 100644 index 0000000..7fbc81d --- /dev/null +++ b/db/install/cassandra/filevercmp_deb.c @@ -0,0 +1,256 @@ +/* + * filevercmp_deb.c: compare DEB versions + * + * Copyright © 1994,1995 Ian Jackson + * Copyright © 2000,2001 Wichert Akkerman + * Copyright © 2006-2014 Guillem Jover + * Copyright (C) 2013 Politecnico di Torino, Italy + * TORSEC group -- http://security.polito.it + * + * Author: Roberto Sassu + * + * This is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +#include +#include +#include +#include +#include + + +struct versionrevision { + /* + * taken from file "dpkg-db.h" + */ + unsigned long epoch; + char *version; + char *revision; +}; + +/* + * My functions + */ +int filevercmp_deb(char* version, char* refversion); +struct versionrevision* create_struct_versionrevision(char* str); + +/* + * Implementations + */ + +int cisdigit(int c) { + /* + * Taken from file "utils.c" + */ + return (c >= '0') && (c <= '9'); +} + +int cisalpha(int c) { + return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')); +} + +/** + * Give a weight to the character to order in the version comparison. + * + * @param c An ASCII character. + */ +static int order(int c) { + if (cisdigit(c)) + return 0; + else if (cisalpha(c)) + return c; + else if (c == '~') + return -1; + else if (c) + return c + 256; + else + return 0; +} + +static int verrevcmp(const char *val, const char *ref) { + if (!val) + val = ""; + if (!ref) + ref = ""; + + while (*val || *ref) { + int first_diff = 0; + + while ((*val && !cisdigit(*val)) || (*ref && !cisdigit(*ref))) { + int vc = order(*val), rc = order(*ref); + if (vc != rc) + return vc - rc; + val++; + ref++; + } + + while (*val == '0') + val++; + while (*ref == '0') + ref++; + while (cisdigit(*val) && cisdigit(*ref)) { + if (!first_diff) + first_diff = *val - *ref; + val++; + ref++; + } + if (cisdigit(*val)) + return 1; + if (cisdigit(*ref)) + return -1; + if (first_diff) + return first_diff; + } + return 0; +} + + +/** + * Parse a version string and check for invalid syntax. + * + * Distinguish between lax (warnings) and strict (error) parsing. + * + * @param rversion The parsed version. + * @param string The version string to parse. + * + * @retval 0 On success. + * @retval -1 On failure + */ +int +parseversion(struct versionrevision *rversion, const char *string) +{ + char *hyphen, *colon, *eepochcolon; + const char *end, *ptr; + unsigned long epoch; + + if (!*string) { + printf("version string is empty\n"); + return -1; + } + + /* Trim leading and trailing space. */ + while (*string && isblank(*string)) + string++; + /* String now points to the first non-whitespace char. */ + end = string; + /* Find either the end of the string, or a whitespace char. */ + while (*end && !isblank(*end)) + end++; + /* Check for extra chars after trailing space. */ + ptr = end; + while (*ptr && isblank(*ptr)) + ptr++; + if (*ptr) { + printf("version string has embedded spaces\n"); + return -1; + } + + colon= strchr(string,':'); + if (colon) { + epoch= strtoul(string,&eepochcolon,10); + if (colon != eepochcolon) { + printf("epoch in version is not number\n"); + return -1; + } + if (!*++colon) { + printf("nothing after colon in version number\n"); + return -1; + } + string= colon; + rversion->epoch= epoch; + } else { + rversion->epoch= 0; + } +// rversion->version= nfstrnsave(string,end-string); +// Replaced by POL + rversion->version= calloc(end-string+1, sizeof(char)); + if (rversion->version == NULL) { + printf("out of memory\n"); + return -1; + } + strncpy(rversion->version, string, end-string); + hyphen= strrchr(rversion->version,'-'); + if (hyphen) + *hyphen++ = '\0'; + rversion->revision= hyphen ? hyphen : ""; + + /* XXX: Would be faster to use something like cisversion and cisrevision. */ + ptr = rversion->version; + if (*ptr && !cisdigit(*ptr++)) { + printf("version number does not start with digit\n"); + return -1; + } + for (; *ptr; ptr++) { + if (!cisdigit(*ptr) && !cisalpha(*ptr) && strchr(".-+~:", *ptr) == NULL) { + printf("invalid character in version number\n"); + return -1; + } + } + for (ptr = rversion->revision; *ptr; ptr++) { + if (!cisdigit(*ptr) && !cisalpha(*ptr) && strchr(".+~", *ptr) == NULL) { + printf("invalid character in revision number\n"); + return -1; + } + } + + return 0; +} + +struct versionrevision* create_struct_versionrevision(char* str) { + struct versionrevision* vr = calloc(1, sizeof(struct versionrevision)); + if (vr == NULL) { + printf("versionrevision: out of memory\n"); + return vr; + } + parseversion(vr, str); + return vr; +} + +void free_struct_versionrevision(struct versionrevision *vr) { + if (vr == NULL) + return; + if (vr->version != NULL) + free(vr->version); + free(vr); +} + +int versioncompare(const struct versionrevision *version, + const struct versionrevision *refversion) { + int r; + + if (version->epoch > refversion->epoch) return 1; + if (version->epoch < refversion->epoch) return -1; + r= verrevcmp(version->version,refversion->version); if (r) return r; + return verrevcmp(version->revision,refversion->revision); +} + +int filevercmp_deb(char* version, char* refversion) { + /* + * This function it's a wrapper to use the ubuntu implementation of the version comparison + */ + int result; + struct versionrevision *vr1 = create_struct_versionrevision(version); + struct versionrevision *vr2 = create_struct_versionrevision(refversion); + if (vr1 == NULL || vr2 == NULL) { + result = -2; + goto out; + } + + result = versioncompare(vr1, vr2); +out: + free_struct_versionrevision(vr1); + free_struct_versionrevision(vr2); + return result; +} diff --git a/db/install/cassandra/filevercmp_java.c b/db/install/cassandra/filevercmp_java.c new file mode 100644 index 0000000..b48ce81 --- /dev/null +++ b/db/install/cassandra/filevercmp_java.c @@ -0,0 +1,48 @@ +/* + * filevercmp_java.c + * + * Copyright (C) 2013 Politecnico di Torino, Italy + * TORSEC group -- http://security.polito.it + * + * Author: Roberto Sassu + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see + * . + * + */ + +#include +#include "torsec_ra_cassandra_db_PackagesVersionType.h" + +extern int filevercmp (const char *a, const char *b); + +JNIEXPORT jint JNICALL Java_torsec_ra_cassandra_db_PackagesVersionType_filevercmp (JNIEnv *env, jobject obj, jstring o1, jstring o2) +{ + const char *a, *b; + jint res = 0; + + a = (*env)->GetStringUTFChars(env, o1, 0); + b = (*env)->GetStringUTFChars(env, o2, 0); + res = filevercmp(a, b); + + (*env)->ReleaseStringUTFChars(env, o1, a); + (*env)->ReleaseStringUTFChars(env, o2, b); + if(res == 0) + return 0; + else if(res < 0) + return -1; + else + return 1; +// return res; +} diff --git a/db/install/cassandra/filevercmp_java_deb.c b/db/install/cassandra/filevercmp_java_deb.c new file mode 100644 index 0000000..564d3e7 --- /dev/null +++ b/db/install/cassandra/filevercmp_java_deb.c @@ -0,0 +1,47 @@ +/* + * filevercmp_java_deb.c + * + * Copyright (C) 2013 Politecnico di Torino, Italy + * TORSEC group -- http://security.polito.it + * + * Author: Roberto Sassu + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library. If not, see + * . + * + */ + +#include +#include "torsec_ra_cassandra_db_PackagesVersionTypeDEB.h" + +extern int filevercmp_deb (const char *a, const char *b); + +JNIEXPORT jint JNICALL Java_torsec_ra_cassandra_db_PackagesVersionTypeDEB_filevercmp_1deb (JNIEnv *env, jobject obj, jstring o1, jstring o2) +{ + const char *a, *b; + jint res = 0; + + a = (*env)->GetStringUTFChars(env, o1, 0); + b = (*env)->GetStringUTFChars(env, o2, 0); + res = filevercmp_deb(a, b); + + (*env)->ReleaseStringUTFChars(env, o1, a); + (*env)->ReleaseStringUTFChars(env, o2, b); + if(res == 0) + return 0; + else if(res < 0) + return -1; + else + return 1; +} diff --git a/db/install/cassandra/init.d/cassandra b/db/install/cassandra/init.d/cassandra new file mode 100644 index 0000000..d8b29d9 --- /dev/null +++ b/db/install/cassandra/init.d/cassandra @@ -0,0 +1,115 @@ +#!/bin/bash +# +# cassandra Start up the cassandra server daemon +# +# chkconfig: 2345 55 25 +# description: SSH is a protocol for secure remote shell access. \ +# This service starts up the OpenSSH server daemon. +# +# processname: cassandra +# pidfile: /var/run/cassandra.pid + +### BEGIN INIT INFO +# Provides: cassandra +# Required-Start: $local_fs $network $syslog +# Required-Stop: $local_fs $syslog +# Should-Start: $syslog +# Should-Stop: $network $syslog +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: Start up the cassandra server daemon +# Description: SSH is a protocol for secure remote shell access. +# This service starts up the OpenSSH server daemon. +### END INIT INFO + +# source function library +. /etc/rc.d/init.d/functions + +RETVAL=0 +PROGDIR="/srv/cassandra/apache-cassandra-0.7.2" +PROG="cassandra" +CASSANDRA="cassandra" + +runlevel=$(set -- $(runlevel); eval "echo \$$#" ) + + +do_restart_sanity_check() +{ + $SSHD -t + RETVAL=$? + if [ $RETVAL -ne 0 ]; then + failure $"Configuration file or keys are invalid" + echo + fi +} + +start() +{ + echo -n $"Starting $PROG: " + $PROGDIR/bin/$PROG -p /var/run/cassandra.pid &>/dev/null && success || failure + RETVAL=$? + echo + return $RETVAL +} + +stop() +{ + echo -n $"Stopping $prog: " + if [ -n "`pidfileofproc $CASSANDRA`" ] ; then + killproc $CASSANDRA + else + failure $"Stopping $prog" + fi + RETVAL=$? + + echo +} + +restart() { + stop + start +} + +force_reload() { + restart +} + +rh_status() { + PIDPATH=`ps -e |grep java |awk '{print $1}'` + for i in $PIDPATH; do + CWDPATH=`cat /proc/$i/cmdline` + if echo $CWDPATH | grep "cassandra" &>/dev/null; then + echo "cassandra (pid $i) is running..." + return 1 + fi + done + echo "cassandra is stopped" + return 0 +} + +rh_status_q() { + rh_status >/dev/null 2>&1 +} + +case "$1" in + start) + start + ;; + stop) + stop + ;; + restart) + restart + ;; + status) + rh_status + RETVAL=$? + if [ $RETVAL -eq 3 ] ; then + RETVAL=2 + fi + ;; + *) + echo $"Usage: $0 {start|stop|restart|status}" + RETVAL=2 +esac +exit $RETVAL diff --git a/db/install/cassandra/rpm_vercmp.c b/db/install/cassandra/rpm_vercmp.c new file mode 100644 index 0000000..f9b905b --- /dev/null +++ b/db/install/cassandra/rpm_vercmp.c @@ -0,0 +1,81 @@ +#include +#include +#include + + +static int compare_values(const char *str1, const char *str2) +{ + if (!str1 && !str2) + return 0; + else if (str1 && !str2) + return 1; + else if (!str1 && str2) + return -1; + return rpmvercmp(str1, str2); +} + +int filevercmp(const char *a, const char *b) +{ + const char *v1, *r1, *v2, *r2; + const char *e1 = "0", *e2 = "0"; + char *a_copy, *b_copy, *ptr; + int rc; + + if (strcmp(a, b) == 0) + return 0; + + a_copy = strdup(a); + if (a_copy == NULL) { + printf("allocation error\n"); + return 0; + } + + b_copy = strdup(b); + if (b_copy == NULL) { + printf("allocation error\n"); + free(a_copy); + return 0; + } + + v1 = a_copy; + v2 = b_copy; + + ptr = strchr(a_copy, ':'); + if (ptr != NULL) { + *ptr = '\0'; + e1 = a_copy; + v1 = ptr + 1; + } + + ptr = strchr(b_copy, ':'); + if (ptr != NULL) { + *ptr = '\0'; + e2 = b_copy; + v2 = ptr + 1; + } + + ptr = strchr(v1, '-'); + *ptr = '\0'; + r1 = ptr + 1; + + ptr = strchr(v2, '-'); + *ptr = '\0'; + r2 = ptr + 1; + + rc = compare_values(e1, e2); + if (!rc) { + rc = compare_values(v1, v2); + if (!rc) + rc = compare_values(r1, r2); + } + + free(a_copy); + free(b_copy); + return rc; +} + +int main(int argc, char *argv[]) +{ + printf("%d\n", filevercmp(argv[1], argv[2])); + return 0; +} diff --git a/db/install/cassandra/schema/cassandra-schema-common.txt b/db/install/cassandra/schema/cassandra-schema-common.txt new file mode 100644 index 0000000..2711742 --- /dev/null +++ b/db/install/cassandra/schema/cassandra-schema-common.txt @@ -0,0 +1,19 @@ +create keyspace PackagesDB + with strategy_options=[{replication_factor:1}] + and placement_strategy = 'org.apache.cassandra.locator.SimpleStrategy'; +use PackagesDB; +create column family FilesToPackages + with column_type = Super + and comparator = 'BytesType' + and subcomparator = 'BytesType'; + +create column family FilesToPackages_test + with column_type = Super + and comparator = 'BytesType' + and subcomparator = 'BytesType'; + +create column family FilesToPackages_pyunit + with column_type = Super + and comparator = 'BytesType' + and subcomparator = 'BytesType'; + diff --git a/db/install/cassandra/schema/cassandra-schema-deb.txt b/db/install/cassandra/schema/cassandra-schema-deb.txt new file mode 100644 index 0000000..b38de6d --- /dev/null +++ b/db/install/cassandra/schema/cassandra-schema-deb.txt @@ -0,0 +1,15 @@ +use PackagesDB; +create column family PackagesHistoryDEB + with column_type = Super + and comparator = 'torsec.ra.cassandra.db.PackagesVersionTypeDEB' + and subcomparator = 'BytesType'; + +create column family PackagesHistoryDEB_test + with column_type = Super + and comparator = 'torsec.ra.cassandra.db.PackagesVersionTypeDEB' + and subcomparator = 'BytesType'; + +create column family PackagesHistoryDEB_pyunit + with column_type = Super + and comparator = 'torsec.ra.cassandra.db.PackagesVersionTypeDEB' + and subcomparator = 'BytesType'; diff --git a/db/install/cassandra/schema/cassandra-schema-rpm.txt b/db/install/cassandra/schema/cassandra-schema-rpm.txt new file mode 100644 index 0000000..8f3b76d --- /dev/null +++ b/db/install/cassandra/schema/cassandra-schema-rpm.txt @@ -0,0 +1,29 @@ +use PackagesDB; +create column family PackagesHistory + with column_type = Super + and comparator = 'torsec.ra.cassandra.db.PackagesVersionType' + and subcomparator = 'BytesType'; + +create column family PackagesHistory_test + with column_type = Super + and comparator = 'torsec.ra.cassandra.db.PackagesVersionType' + and subcomparator = 'BytesType'; + +create column family PackagesHistory_pyunit + with column_type = Super + and comparator = 'torsec.ra.cassandra.db.PackagesVersionType' + and subcomparator = 'BytesType'; + +create keyspace BodhiDB + with strategy_options=[{replication_factor:1}] + and placement_strategy = 'org.apache.cassandra.locator.SimpleStrategy'; +use BodhiDB; + +create column family Bodhi + with column_type = Super + and comparator = 'BytesType' + and subcomparator = 'BytesType'; +create column family Bodhi2 + with column_type = Super + and comparator = 'BytesType' + and subcomparator = 'BytesType'; diff --git a/db/install/cassandra/torsec/ra/cassandra/db/PackagesVersionType.java b/db/install/cassandra/torsec/ra/cassandra/db/PackagesVersionType.java new file mode 100644 index 0000000..0b8ad29 --- /dev/null +++ b/db/install/cassandra/torsec/ra/cassandra/db/PackagesVersionType.java @@ -0,0 +1,138 @@ +/* + * PackagesVersionType.java + * + * Copyright (C) 2013 Politecnico di Torino, Italy + * TORSEC group -- http://security.polito.it + * + * Author: Roberto Sassu + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package torsec.ra.cassandra.db; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.Arrays; +import java.nio.ByteBuffer; +import java.sql.Types; +import org.apache.cassandra.utils.ByteBufferUtil; +import org.apache.cassandra.db.marshal.AbstractType; +import org.apache.cassandra.db.marshal.MarshalException; +import java.nio.charset.CharacterCodingException; + +import org.apache.cassandra.utils.Hex; + +public class PackagesVersionType extends AbstractType { + private native int filevercmp(String o1, String o2); + public static final PackagesVersionType instance = new PackagesVersionType(); + + PackagesVersionType() {} + + public ByteBuffer compose(ByteBuffer bytes) + { + return bytes.duplicate(); + } + + public ByteBuffer decompose(ByteBuffer value) + { + return value; + } + + public int compare(ByteBuffer o1, ByteBuffer o2) { + try { + return filevercmp(ByteBufferUtil.string(o1), ByteBufferUtil.string(o2)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public String getString(ByteBuffer bytes) { + try { + return ByteBufferUtil.string(bytes); + } catch (CharacterCodingException e) { + throw new MarshalException("invalid UTF8 bytes " + ByteBufferUtil.bytesToHex(bytes)); + } + } + + public String toString(ByteBuffer byteBuffer) + { + return getString(byteBuffer); + } + + public void validate(ByteBuffer bytes) { + // all bytes are legal. + } + + public Class getType() + { + return ByteBuffer.class; + } + + public boolean isSigned() + { + return false; + } + + public boolean isCaseSensitive() + { + return false; + } + + public boolean isCurrency() + { + return false; + } + + public int getPrecision(ByteBuffer obj) + { + return -1; + } + + public int getScale(ByteBuffer obj) + { + return -1; + } + + public int getJdbcType() + { + return Types.BINARY; + } + + public boolean needsQuotes() + { + return true; + } + + public ByteBuffer fromString(String source) + { + try + { + return ByteBuffer.wrap(Hex.hexToBytes(source)); + } + catch (NumberFormatException e) + { + throw new MarshalException(String.format("cannot parse '%s' as hex bytes", source), e); + } + } + + static { + System.loadLibrary("filevercmp"); + } + +} diff --git a/db/install/cassandra/torsec/ra/cassandra/db/PackagesVersionTypeDEB.java b/db/install/cassandra/torsec/ra/cassandra/db/PackagesVersionTypeDEB.java new file mode 100644 index 0000000..9b7b82f --- /dev/null +++ b/db/install/cassandra/torsec/ra/cassandra/db/PackagesVersionTypeDEB.java @@ -0,0 +1,177 @@ +/* + * PackagesVersionTypeDEB.java + * + * Copyright (C) 2013 Politecnico di Torino, Italy + * TORSEC group -- http://security.polito.it + * + * Author: Giuseppe Baglio + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package torsec.ra.cassandra.db; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.Arrays; +import java.nio.ByteBuffer; +import java.sql.Types; +import java.io.BufferedWriter; +import java.io.FileWriter; + +import org.apache.cassandra.utils.ByteBufferUtil; +import org.apache.cassandra.db.marshal.AbstractType; +import org.apache.cassandra.db.marshal.MarshalException; +import java.nio.charset.CharacterCodingException; +import org.apache.cassandra.utils.Hex; + +public class PackagesVersionTypeDEB extends AbstractType { + private native int filevercmp_deb(String o1, String o2); + public static final PackagesVersionTypeDEB instance = new PackagesVersionTypeDEB(); + + PackagesVersionTypeDEB() {} + + public ByteBuffer compose(ByteBuffer bytes) + { + return bytes.duplicate(); + } + + public ByteBuffer decompose(ByteBuffer value) + { + return value; + } + + public int compare(ByteBuffer o1, ByteBuffer o2) { + String val1, val2; + try { + val1 = ByteBufferUtil.string(o1); + } catch ( CharacterCodingException cce){ + writeToFile("CharacterCodingException per valore 1"); + System.err.println("Error: " + cce.getMessage()); + throw new RuntimeException(cce); + } + try { + val2 = ByteBufferUtil.string(o2); + } catch ( CharacterCodingException cce){ + writeToFile("CharacterCodingException per valore 2"); + System.err.println("Error: " + cce.getMessage()); + throw new RuntimeException(cce); + } + + try { + int retval; + if ( val1.compareTo(val2) == 0 ) + retval = 0; + else + retval = filevercmp_deb( val1, val2 ); + String logStr = val1 + " " + val2 + " " + String.valueOf(retval); + writeToFile(logStr); + return retval; + } catch (Exception e) { + writeToFile("Error: " + e.getMessage()); + System.err.println("Error: " + e.getMessage()); + throw new RuntimeException(e); + } + } + + public String getString(ByteBuffer bytes) { + try { + return ByteBufferUtil.string(bytes); + } catch (CharacterCodingException e) { + writeToFile("invalid UTF8 bytes " + ByteBufferUtil.bytesToHex(bytes)); + throw new MarshalException("invalid UTF8 bytes " + ByteBufferUtil.bytesToHex(bytes)); + } + } + + public String toString(ByteBuffer byteBuffer) + { + return getString(byteBuffer); + } + + public void validate(ByteBuffer bytes) { + // all bytes are legal. + } + + public Class getType() + { + return ByteBuffer.class; + } + + public boolean isSigned() + { + return false; + } + + public boolean isCaseSensitive() + { + return false; + } + + public boolean isCurrency() + { + return false; + } + + public int getPrecision(ByteBuffer obj) + { + return -1; + } + + public int getScale(ByteBuffer obj) + { + return -1; + } + + public int getJdbcType() + { + return Types.BINARY; + } + + public boolean needsQuotes() + { + return true; + } + + static { + System.loadLibrary("filevercmp"); + } + +public ByteBuffer fromString(String source) + { + try + { + return ByteBuffer.wrap(Hex.hexToBytes(source)); + } + catch (NumberFormatException e) + { + throw new MarshalException(String.format("cannot parse '%s' as hex bytes", source), e); + } + } + + void writeToFile(String str){ + try{ + FileWriter fstream = new FileWriter("/var/log/cassandra/comparisons.log"); + BufferedWriter out = new BufferedWriter(fstream); + out.write(str); + out.close(); + fstream.close(); + }catch (Exception e){ + System.err.println("Error: " + e.getMessage()); + } + } +} diff --git a/db/install/cassandra/torsec_ra_cassandra_db_PackagesVersionType.h b/db/install/cassandra/torsec_ra_cassandra_db_PackagesVersionType.h new file mode 100644 index 0000000..1855baf --- /dev/null +++ b/db/install/cassandra/torsec_ra_cassandra_db_PackagesVersionType.h @@ -0,0 +1,21 @@ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class torsec_ra_cassandra_db_PackagesVersionType */ + +#ifndef _Included_torsec_ra_cassandra_db_PackagesVersionType +#define _Included_torsec_ra_cassandra_db_PackagesVersionType +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: torsec_ra_cassandra_db_PackagesVersionType + * Method: filevercmp + * Signature: (Ljava/lang/String;Ljava/lang/String;)I + */ +JNIEXPORT jint JNICALL Java_torsec_ra_cassandra_db_PackagesVersionType_filevercmp + (JNIEnv *, jobject, jstring, jstring); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/db/install/cassandra/torsec_ra_cassandra_db_PackagesVersionTypeDEB.h b/db/install/cassandra/torsec_ra_cassandra_db_PackagesVersionTypeDEB.h new file mode 100644 index 0000000..c5edd5f --- /dev/null +++ b/db/install/cassandra/torsec_ra_cassandra_db_PackagesVersionTypeDEB.h @@ -0,0 +1,21 @@ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class torsec_ra_cassandra_db_PackagesVersionTypeDEB */ + +#ifndef _Included_torsec_ra_cassandra_db_PackagesVersionTypeDEB +#define _Included_torsec_ra_cassandra_db_PackagesVersionTypeDEB +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: torsec_ra_cassandra_db_PackagesVersionTypeDEB + * Method: filevercmp_deb + * Signature: (Ljava/lang/String;Ljava/lang/String;)I + */ +JNIEXPORT jint JNICALL Java_torsec_ra_cassandra_db_PackagesVersionTypeDEB_filevercmp_1deb + (JNIEnv *, jobject, jstring, jstring); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/db/install/cleanup_cassandra_libs.sh b/db/install/cleanup_cassandra_libs.sh new file mode 100644 index 0000000..02ba9a8 --- /dev/null +++ b/db/install/cleanup_cassandra_libs.sh @@ -0,0 +1,7 @@ +#! /bin/bash + +pushd cassandra + +make clean + +popd diff --git a/db/install/install_cassandra_libs.sh b/db/install/install_cassandra_libs.sh new file mode 100644 index 0000000..50fb80b --- /dev/null +++ b/db/install/install_cassandra_libs.sh @@ -0,0 +1,36 @@ +#! /bin/bash + +if [ -z $1 ]; then + echo "Usage: $0 " + exit 1 +fi + +CASSANDRADIR=$1; +echo $CASSANDRADIR | grep '/$' > /dev/null +if [ $? -eq 0 ]; then + CASSANDRADIR=$(echo "${CASSANDRADIR%?}") +fi +export CASSANDRADIR + +JNI_H=$(find /usr/lib/jvm -name "jni.h") +if [ -z $JNI_H ]; then + echo "Java headers not found. Please install the java-1.6.0-openjdk-devel package" + exit 1 +fi + +JAVAHEADERS=$(dirname $JNI_H); export JAVAHEADERS +CASSANDRACLASSPATH=$(find $CASSANDRADIR -type f -name "apache-cassandra-[0-9]*"); export CASSANDRACLASSPATH + +LIBDIR="/usr/lib64" +if [ ! -d $LIBDIR ]; then + LIBDIR="/usr/lib" +fi + +export LIBDIR +pushd cassandra + +make clean +make all +make install + +popd diff --git a/db/measurements/ascii_runtime_measurements b/db/measurements/ascii_runtime_measurements new file mode 100644 index 0000000..62f8c25 --- /dev/null +++ b/db/measurements/ascii_runtime_measurements @@ -0,0 +1,434 @@ +10 e62454770f7d07bcbb340edffee94117a9bdc1c8 ima 17803ce42ab2ef93ffd92db6e0e44b56d47bae68 boot_aggregate +10 eea51a4c318f6a580f4c5c38f2227442673eaf54 ima 9bda9f15007dad1f77c33e57fc853693ec94a7d2 /usr/lib/systemd/system-generators/systemd-cryptsetup-generator +10 e5768913ea4b4fa91131c427938921073f7397c9 ima 275efe695f22265d255e1bc40e86b9bdc899f5a8 /usr/lib/systemd/system-generators/systemd-efi-boot-generator +10 6eee93300fee4872a4c8c0e47ca2e35d4d2dd2d4 ima 31814476fc16169c8d9b02fbe60ca5d9c9710989 /usr/lib/systemd/system-generators/systemd-getty-generator +10 4bdb8679cf30d45a873ce137eea7dcfebc00c6fb ima 58107b924499022c36367e48362486ba526f0314 /usr/lib/systemd/system-generators/systemd-system-update-generator +10 db2fc7981e425bd1f815de2fd2b9447429a33256 ima 5867a2edda37658f4c94ded88d37d26d36c35046 /usr/lib/systemd/system-generators/systemd-fstab-generator +10 95c6f08901495124151e704786712e26e5bfdbc5 ima fb73c1553c7a3f120914554be03ec379002bc1c6 /usr/lib/systemd/system-generators/systemd-rc-local-generator +10 bc806d958bd6cb15ac4fd64f609ecdb4e3158926 ima 08a0c10b56b5abe75c70bd65ccec09e5d4145ab4 /usr/lib64/ld-2.17.so +10 ba452a04d199d98f0ac82d79e270012fcfbe9b8f ima 605626cb8acc5e7f601da05fcc22ec4b84a41e0e /usr/lib64/libgcc_s-4.8.3-20140911.so.1 +10 09b09509a2b412e53754c04d2572a43ae8b46d6c ima 14c54fb250e202cdeb4a0cbd9f16446432fd0c79 /usr/lib/systemd/system-generators/kdump-dep-generator.sh +10 3edba53ed2235777217b7dbfd2d40a6e434fb827 ima 53b8545b9c0e9c2641a0dae4b60b8578119dd8c9 /usr/lib64/libselinux.so.1 +10 386fb2d3db9652a77171780c7eb7dba67b72b6b9 ima 577db58ba198bf423c8c092cbdb40dff7e8714da /usr/lib64/libc-2.17.so +10 83ac4ef1b67fb28fe732171e63f8ee55208ad7eb ima 5b41657846db7ce93cc7c18d7fdd5be35e7e261a /bin/sh +10 f4b6e246fb00c970da0fa414401d3be0716fcbdb ima 61a83fb36f80242a5b4654f9c0b6e364c35414db /usr/lib64/libpcre.so.1.2.0 +10 e9403b1e75a4e3e790e4033c401f64640606880f ima b964d65c02d1c4aa8cf2b59e1f9744496b3437aa /usr/lib64/liblzma.so.5.0.99 +10 a7f45041a9e478ddc1802046035d372dd9e0a81f ima 6f929bb3ed8041afe99905d0a5b4acac362c4979 /usr/lib64/libdl-2.17.so +10 964a0243407ef4cc218c63b172985775298492d3 ima f4c8c9dbd387244a2eb0245cd5c858b1d7d8508c /usr/lib64/libpthread-2.17.so +10 daaf197f61d1787e571aff694cdebe0477c4998a ima 29d2074abc75c8a5e1cf1361c4a6c9c583a99b88 /usr/lib64/libtinfo.so.5.9 +10 ef68b8ba661e42b14e5142fc6b9520f7516b7bca ima 187a650226f09d9be72ab55f01745130cb117366 /usr/lib64/libnss_files-2.17.so +10 26bd412aac82ed488c87c18f823b95719d0c1407 ima bf3303d34a432bf99f8417b4be7d1de0bad14ecd /usr/bin/grep +10 1b4aedc9c16c24da6f0639f00945b2e692cc9a8e ima 8d8f3a043b794c8f2e8a814108c7d87023a05052 /usr/lib64/plymouth/text.so +10 d27c11a3e9991f11a92bbea2dbd8281fffb9959a ima 02c2af2e31ce6ca10b7e0eb56fdd46e514ec2cd7 /usr/lib/systemd/systemd-readahead +10 e615e945b814c03c8c63318648e5247b90e1c4da ima f996bcc51270e289c184604e4f6a61162620e3c4 /usr/lib64/libsystemd-daemon.so.0.0.10 +10 cf098d1a6a43e1c91d140c2ddaa1532f50d6a654 ima c73bc58def00781ac5418290b7d4d89387a4f124 /usr/bin/udevadm +10 28314d1ac1be95a0f94810a1563586f9aab77da1 ima 8c692d97f0ac9e9720ef4be30619b1d178e7aa7e /usr/lib64/libudev.so.1.4.0 +10 7f1ae68f7b8cbe6c85625e0d73c873b160be13cb ima abfb0cb8f97c4fc6f277a7b0b502bba721a76539 /bin/mount +10 c226807271ace0ad4301836fbce0b6d16ee89083 ima b38bcc602dfb51b351d343c9a441b849791c2e5b /usr/lib64/librt-2.17.so +10 cddcf616e4f695a6161749fcb1ae50190c30f605 ima 67172f753d97b542718ab2c7ee1e6407720de4cb /usr/bin/mkdir +10 51959db55d3d8932869f572ef55982f27e0d2929 ima 1e7e5dd27737060c8e79934e0e22813b135afdd2 /usr/lib/systemd/systemd-journald +10 e78ca532f40d5169c5463fc4f4ef34d2dc327e85 ima b32ab6ea6243a2f12e7852d7ab08160c24fe0b58 /usr/lib64/libmount.so.1.1.0 +10 3cea5c33c4fab35c5b053664d17abcceac9c4862 ima fed9b295efd79fd761402fbc28052cbb63888553 /usr/lib64/libblkid.so.1.1.0 +10 4472115c2d91f33220368a849f5f4acd29de38b1 ima 02181d983ea077d6e26f0c050a8cd90f16f01a3f /usr/lib64/libuuid.so.1.3.0 +10 0140f50d58c6be08e142820b8a0cdc2a1fa31991 ima 4f4228771ef954ec28b4bc9f91a0087b37c2ac4b /usr/lib64/libcap.so.2.22 +10 c421298d75efbf51e1ace11b5b86deefaabf0e24 ima a272679340f07ad2cf21a4e033fcb8a84dc9f9d0 /usr/lib64/libkmod.so.2.2.4 +10 1e47204b88cf24708f8d6bf18ec241d7ea5d4a57 ima 2824d4ad0859171e612a9c8c3d2d493279661fa7 /usr/lib/systemd/systemd-cgroups-agent +10 6391e32ad877f31c0e6d61fdc83fb6e456ecafe9 ima fd06972c4aeafafeabb040f7bf6f0002be6d9235 /usr/bin/kmod +10 e78e3afc0c773d491af988ab3ceecc9c9b1e3c95 ima bc5a3f54716c38af38538faf40f0c779c6c59d19 /usr/lib64/libacl.so.1.1.0 +10 ed70009a4d136b88f005edba06fb445a4cdba4f9 ima 6a4a45fae15fd17f0271a835b51043fad2c96175 /usr/lib64/libdbus-1.so.3.7.4 +10 f9d88c9981096c74794b798788f27869c7ba412c ima 300cf0f2bd418bfdf3da1b2b7048cab1b0db2238 /usr/lib64/libz.so.1.2.7 +10 d1df0f2a62ea94ce8ef6632e2e6f70732e95d127 ima 7c93acbdea5e704954d9c1e723c2aa6b3073810a /usr/lib64/libattr.so.1.1.0 +10 25842ed077683fc4a114754c62654abdfcdeea2a ima 2c8b463ccd59592e2a5b4931ea780e4ecc100075 /usr/lib/systemd/systemd-sysctl +10 c7fb67603894093676ea136a2bf50125d1ac5f1d ima 2033530f7697ea96b16cbe2d87259d360035aeba /usr/lib/systemd/systemd-remount-fs +10 535e575bf6504c52c27bfa219e096cbe2617d666 ima 49b1d09963fae4940fd392f226e5b121aef4e04d /usr/lib64/libgcrypt.so.11.8.2 +10 2bcb287239b074351c0d04d67c2383b21c178caf ima c116da44a183d735e96e27acb66a3341859314d3 /usr/lib64/libgpg-error.so.0.10.0 +10 9a21dc4bc0fbede8aa554ce4283120d7ae9b4b48 ima 67a887b9c17e9c33935a8fd26704be933375a2ca /usr/lib/systemd/systemd-random-seed +10 2347805a73cde731bd01548b92bddedc950fa99f ima 8de5dc7a24efeaff57a7eb22e6914ca14a9b7d1e /lib/systemd/rhel-readonly +10 5c04724b5ddf222b1aa3a4fcf6a7fd0592e57c51 ima 535951f6d169a2a0c2903c48ac0b3cd0dd528061 /usr/bin/systemd-tmpfiles +10 c30ce0901de04284deb5d61893fc3e5a66cb89e1 ima a489650b0af15cc01badaa8bfc38a6c1ade86383 /bin/cat +10 4066ed7523d8ca409eccb6e3f7b5037e76d25afc ima bd75a096d7118169cf24708f92e3967cd0d61eb5 /usr/lib/systemd/systemd-udevd +10 c9bfafc9a52deeb9e9c2e6640e74f267cad84d69 ima 55988a3d90fefccaa5cad29d040aa4fd562cff0d /lib/udev/rename_device +10 a25267d681b6c7b538dc04045647ad009d4a89e8 ima 458fc98c0a9e2899ba343299d8695fd5fcbadd56 /usr/lib/udev/ata_id +10 907c3e2968d44b90bda44e8481b69ca58d563a10 ima a6afe70d9e5c972e07df8559fab84759d7470386 /usr/lib64/libglib-2.0.so.0.4000.0 +10 5a9cb7de1404a1f17ca20151852e5800fe5dac9f ima e9d47c06bd4e265bdffab3f189fc7fad1955d1f6 /bin/systemctl +10 23567815f7b549f55f80e8d66e4e09e2e2b2f7f3 ima f44420424ed87378eb7e123893733bd942ad206d /usr/lib/systemd/systemd-vconsole-setup +10 6274ac35b70c136511409c83b7175feb30ed23cf ima fb857dc1d3876529f33d26b87e011f1f01327681 /usr/bin/setfont +10 cdfbad45aa3fdd1a297083c3efcb108030cdd067 ima 2c58a8864feac3cef9a1891aa9b1758be8f61d16 /usr/bin/gzip +10 134b4a374dab450e3ec7782abdea35ca19ab5047 ima 46c5d35269e4e2b7de0f49ed516866d6a85944e5 /usr/bin/loadkeys +10 61c9e4325bb41eba036866620b41009562cacb0b ima 16816ab7bbc7c5fbe2d7704ef866c7350dc47e37 /sbin/swapon +10 2c62e690ad95f50494d14fc1602b51e10b75594e ima 01ac7397387d337d1b6258fa9f6c6f4289d8988e /lib/systemd/rhel-import-state +10 2cf40df8efb2ac5107fe07dcf3954d767d3359a7 ima 7fc37a6672c4d98ef236b23ac998123ce4af4176 /usr/bin/plymouth +10 079695bd8bcf98a3d1a2b5160d65a0bd23d97d60 ima 933fdf9df633e095e46075e0c2ac02f665b19e9f /usr/bin/find +10 aac06260c62888c19ce9312458ab3c26a2eabeb2 ima f85d5d5902e942e7e1b32dade6cfeb17f24252bc /usr/lib64/libply.so.2.1.0 +10 1152519ac3435916f2ebeca13a6f82e2e231297b ima 88380e21d2ee3d3d82b61867730ba5b9f8c5d077 /usr/lib64/libm-2.17.so +10 e6109dabd0b8ac292000a43efb513d15ff1ca47f ima 86facb338f238ae5a52874b5cd2d0847ecb582e2 /usr/bin/cp +10 7d94b0867f9e8468fae915aab5a3d2121ec8d4e2 ima 713743dc834f29cedbd4e00933f1f7bfff1a7eb2 /usr/bin/xargs +10 d0104d2bf1883238e3e0b02cfcf89d316487ad3f ima cdb42be54566ba75c1b471d5f5736f5d1e2babb3 /usr/sbin/restorecon +10 62678fec610313f79ffba33866b39dd8b8014fe1 ima 7f4411d0b298398166b7aa6f81e17b60797e7810 /usr/lib64/libsepol.so.1 +10 b5041e35fad599f7a70309b5a135def9492ef3ef ima e0f4e650689524a02c3c38a3d8cb4bd85e760bbe /usr/lib64/libaudit.so.1.0.0 +10 9c35477fc708bcae92a69e41b79d4e7aac3bedc4 ima 7bef2aa758520c2b0c9093e009645cb7f4c8067b /sbin/augenrules +10 148abcc40aa7fd513486188a05ea0fa793109718 ima e2e506d318612f8e53ad1d7b26b61a6590b76f25 /sbin/auditd +10 55c40b41ac7eb10833474a37a2fd3c8e5ed25fa3 ima 8bb72296811d36a089788f4c6cc1f1edd04347b4 /usr/bin/mktemp +10 5e090c0d559f6e0d72f36ff922a3f3895f3199b6 ima f3a5809e14effe54f77ef8a8c6514e5e602725fe /usr/lib64/libwrap.so.0.7.6 +10 e8408cf66ebc2b20b8e2907897f9a3c90fc3ca92 ima d2bdfd31475b7bd0087cb45260843ecd0225ba47 /usr/lib64/libnsl-2.17.so +10 5e6fc49fb293b1734e286ba208f866bfbf91c0fb ima 3389e29a24705351125e8bb8c82cf0a95cb62934 /bin/ls +10 9b9abc2e5cb99b44b0805f9de4d5a3d750b3947e ima 863d89e1c0176e0e2e47fd5e62ad7548e237fb27 /usr/bin/awk +10 bb2c14fc6301588a6de8446bd52659ea71ee742a ima 2b4623fd436fd86de5c37302a8930bf497288882 /usr/lib64/libgssapi_krb5.so.2.2 +10 404dc7e11887ab70fdeb7c6e1e9339c7f400bead ima 314c999887502fb0c7e1fa791a5e86eb3459a3e0 /usr/bin/cmp +10 fa68681cdd751e0a0810814604ad423513ea71c3 ima 3e3d3fa142f15e8d90e010779a1342506c73e502 /usr/lib64/libkrb5.so.3.3 +10 90560831fda66ee0663499c23ad96a59922db5a7 ima 3e1a999f0690c233d701375d3c5e6dcb41b2b5c1 /usr/bin/rm +10 b08baf7832e7773df152a51d22d5f7950b562f58 ima d1077dc55c8177c88f5d07644905db662c3daf17 /usr/lib64/libk5crypto.so.3.1 +10 f7a6375ec1bd6e3f5e6c8d3dc15b5bc0eb12f347 ima 928089f824381f2f1dc61f469f69c43499a893ab /usr/sbin/auditctl +10 344ce7b533cf89c3327a96b6f54617816b79325a ima fb355ca32642f61abbeaaa0f0daf7c0961329405 /usr/lib64/libcom_err.so.2.1 +10 19d5b69c0e724fdc5bcd77642ef221c787385236 ima d703af6e043e90c44a4509f44af7237616c2e90c /usr/lib64/libauparse.so.0.0.0 +10 27b49c45768c67afff0e1a9a41c242352c5087f7 ima bc48acdfec7d1acef997ed45e7755de1aac3e1f0 /usr/lib64/libkrb5support.so.0.1 +10 d5c2d1ac8f738228b05d9d11f7e1306b93c7b74e ima 914bbc1184c9efaa4447d02d69c945e81788dbc6 /usr/lib64/libkeyutils.so.1.5 +10 071ed56559fc9f4ba73992cf60c4cf0ecaca0051 ima 18e5c78c336f02f5a7874551ba866547614b8e0a /usr/lib/systemd/systemd-update-utmp +10 b065a0afb0ddedd0321753baae4ee079141a3e1b ima b03f19edad09c3ecf06111d033e3b3c66a65a14f /usr/lib64/libresolv-2.17.so +10 b585749b8e1f06fd800b253ad9db1ea85bfb9120 ima 6f7f1852ac3e3bba6e7b639c8fd0f9f12968ed9f /usr/sbin/firewalld +10 eb1e04a5d8c76d43e3b9e663d3b2f9368fca23ad ima 0e3523fd328ed256bb7a9506533f1038081ea688 /usr/lib/systemd/rhel-dmesg +10 48427685915818e02682faaadbf28ad8c70b4334 ima 5542c96d57cec1b0d20924c9a164ff83397c9002 /etc/rc.d/init.d/openvswitch +10 837636fe5a031197e4fe9aaa4602e877b6534e3b ima 8cc17bc0b86c99d80a82d193efa189c36340ca58 /usr/lib/systemd/systemd-user-sessions +10 5b2f360407c330decea625ab3cd81ed20f742b54 ima f90d90778263cd394831af20f562a840a109fa66 /usr/sbin/rsyslogd +10 6cb4cdb65732f5b2a1f158a1e16f34e298ff8e9b ima 250818f9c21f6a3c64a095d473408455897782ad /usr/libexec/ksmctl +10 0c794685da8aca2caa2bbf2b52a4ba452009570f ima dc992be677469b55d8c1289c5e2fc047bfe6c0a4 /sbin/tcsd +10 443826ddb5bcac60b1edc26b246b55352bcac5ea ima b66eb55d0ebf2ea338f034d7c6d872e7f244733d /usr/sbin/irqbalance +10 4aee515bffd673ec468acdb45165f6a1e8f809da ima d7ac77191cb53dcef4448852a64941d528164218 /bin/dbus-daemon +10 58dd899b49bd3732c744ec0ac75d1c03555f29c7 ima bc9fb9269ea1f5c5ad06ff1d224f10e81327c5d5 /usr/sbin/tuned +10 465f70342483344654b4380420d0533825bb3144 ima d7646f62a87a53f432309e953021ba792a8cb466 /usr/lib/systemd/systemd-logind +10 efa4b6176638913e6d74eea4b4a1bc03ce885576 ima ddf237d41c2e1f980b1e154cd469259ae23fea3a /sbin/audispd +10 74865bada8e7fa9a789f10bf9a89560e88d4e73d ima 958b7d0f7d8a891e16bf310700ea64c783efb8c2 /usr/bin/python +10 4c11405bef1e19522cd9a6d840b46cbc1cab7080 ima da34d3c7702c26f0398cab19a2d9684006d66f20 /usr/bin/mv +10 3c95d2f081b8afe41bbfbd93f09aefeb8adc82ce ima afdd5d05936c8e5d0e74a326cd1ecf56d2ecad8a /bin/date +10 5f476c10562d21d4830f7bfa60acce5340421e4d ima 7e2669372a5a5bb1a280cbc7a5e3824caffcd562 /usr/sbin/crond +10 f005e8a07a0ec1d3be28d6f0a4b92f1cbf151184 ima eb7df5d606d245e48468b660708b50fd73cca690 /usr/lib64/libestr.so.0.0.0 +10 55c3319824a534f3cc1b7c373bc2fc752fba3f10 ima fde34f16327b87c7c027e415fcfb3b418d722035 /usr/sbin/ksmtuned +10 ffb12c498484f3910ea02279b7927b5e6239bf3a ima 10cf25bbc8f475f0a0d8363d90b24cdde6600acc /usr/lib64/libcrypto.so.1.0.1e +10 30d495091e6ed5aebca5f44bb556420668a66394 ima beef663a67d30c9cd91d172eeb5f7c67b8e00866 /usr/lib64/libcap-ng.so.0.0.0 +10 a06c4b23c50c4231a91fff3af1c223dfe9cec5fb ima e05199b70ed00f76b3394056b842318bfcf81185 /usr/lib64/libexpat.so.1.6.0 +10 bd9019e5033236f134a9afb76641e95e4032fd6a ima 7c30b333e54ea1a640582760a872146b6b96ceda /usr/lib64/libpython2.7.so.1.0 +10 c42d0db98a0078954995d4cbebae0fee37ed815c ima 32dc5ffc34d210594a4d090c7510c87d84ed77bf /usr/bin/dmesg +10 eb95034b09170ce0fde29a0575869a3f17274fb2 ima 37a2340d0dbc2734e517f78151947d63559cdd51 /usr/share/openvswitch/scripts/ovs-ctl +10 a2ba88c2a87dc33e9170d99b81d2cfe2ad93e40f ima 7f0ad68759d0fdb80725bfef7dffe2aef3b8b046 /bin/tee +10 beb6f238b81864f46c329774c325c1d7ee9d6373 ima e864f58a87f86dbd2423cb550d3823952e28aa0d /usr/lib64/libpam.so.0.83.1 +10 809e671997aac84a35262044ef1d3ae70e85d45b ima 1a58bc000aa9d0e401bcb3c5b55d819aa7b905d0 /usr/lib64/libjson-c.so.2.0.1 +10 af40a39b5223e9899cb35d4dbb61a6f297c26652 ima 2f0489b906af356b98d1fc35010b3697a9edcb61 /usr/lib64/rsyslog/lmnet.so +10 0c50e085756178dd31cebcf4c94b5868e019e341 ima a50af7c10eb236df2cb721fc41eee00f003b05c3 /usr/bin/touch +10 b42ca930bba290c5a1f5a97d853b2c5cc5cb0079 ima 0f976ee6076b7830e7237c4a44cae430ee61c432 /usr/lib64/libnuma.so.1 +10 cb3e95db4d143efc2c5dfb527adc575e6c26954a ima a652e988d1f9be7b4dcb9ce86042a69fda127bf9 /usr/lib64/libutil-2.17.so +10 9ebdf0deeeb6c749e6ff7876be926488c66f29f2 ima 6ecf9700205a1fde9b7605f2749c5001419c3d3f /bin/sed +10 03b0de694a9b80bb52fe787cded6092df9a6b789 ima 4a0bcb6b97bb319933db922e276ee0e4717b97e1 /usr/lib64/rsyslog/imuxsock.so +10 16eb20079c27a4d568ddd54c254be1e19d93f11e ima 5dd3e6ee56cff73b0a31fa0a389ca93ca9b59a1c /usr/bin/sleep +10 0891c68277e7f1d6b36cf9a3b383dcff7ecad83f ima 3f537d1bfd0832c3ccaba02412e9132f166aa154 /usr/lib64/python2.7/lib-dynload/_collectionsmodule.so +10 2ccd947c4dad4bf8173ede9fe5673a2a643a9a55 ima 1cadd87d8a19204e82e03288699f0d77b8ea1298 /bin/mountpoint +10 f312973283df58b67eaf3b3312c4cde31c44e8bc ima 1f0854cea2879d26e4b2354e67abe641b7471845 /usr/lib64/python2.7/site-packages/_dbus_bindings.so +10 8b5b66a2c015b773b3381b4a9c8c4a2e0408d226 ima 59f4d6e77d363ff80ef0905d1d90bc146b99c12f /usr/lib64/rsyslog/imjournal.so +10 deb9a3a42cc600c33d4ea0ef431fcb7d39a073b4 ima 6cf67aae6b08f98cf6f97a83fb115b11af2d0da8 /usr/lib64/python2.7/lib-dynload/operator.so +10 c5ca7392a694923947e34d1af93b019821e76c5b ima 6ea44a7315e17566fe6a1942de56f0d0ad2e53a0 /bin/expr +10 dfe4429796f3a31b793e721e56f18cc47022cfc2 ima 3fc412866e89025e36cb0a260009641b149444d3 /usr/lib64/python2.7/lib-dynload/timemodule.so +10 6b86f56d864e80ef09f78325155802d4ccb7313e ima 05842182e5ceb603cde03a0fcdb52f9108aa1b77 /usr/lib64/libsystemd-journal.so.0.11.3 +10 06954d46138b05d09f70d08ea5386cfa271c9cda ima 86c4787314ec3275916266b90fc689827e7a31ee /usr/lib64/python2.7/lib-dynload/itertoolsmodule.so +10 f7465292ae8632b6604e6c22565c344478a55523 ima 86c9b15407dd44ba3b09b7e24615c690077bb081 /usr/lib64/libgmp.so.10.2.0 +10 eec72deced6060a92684a00d26152cafdf5a3436 ima 8bb0706320ab12126411ca6c095d1f5eb6a67bd0 /usr/lib64/python2.7/lib-dynload/cStringIO.so +10 ceedf7d687ca1a5ed82e21af35bc8fa3f7133eaf ima 7cb3be3b5f370b361f9976f9726f6e3d5a0bccbb /usr/lib64/libsystemd-id128.so.0.0.26 +10 1f027e8d9b1d1e8a57b0355d541d3894e693e58e ima 343f138469c1903c20f9c6d06c5a72fa9fd1847d /usr/lib64/python2.7/lib-dynload/_heapq.so +10 9c854de8040e6c917e41f6fabe73ba279d711e18 ima 2177b6b494d645e2fd10818773ae9d8a13eefb27 /bin/tr +10 55e50e3aa4d7a9cc5d05b4cbba58b3a620efe512 ima 07c58b0e7ad594fa73463571ebcd85bf1d76fda0 /usr/lib64/python2.7/lib-dynload/stropmodule.so +10 1f66afc93c55bb175eaad9491d87541d0cc44d99 ima 145dc0d9b71f7b71f9bef806a18bf01af276327f /usr/lib64/python2.7/lib-dynload/pyexpat.so +10 2519828794b5af0f329e7bcf9349c94f9b96b94a ima 144da12930b543a9715895efcba827259e7be85a /bin/ovsdb-tool +10 f71ffd37ad33de85c5ef659c1f3984210727b1fb ima 01ddbe4592f8673b5d4508da83c00898442e10c1 /usr/lib64/python2.7/lib-dynload/_functoolsmodule.so +10 6575db20e3132bb56eb50f6f4afae0321fc5309f ima 391d2b46919a2827f3af005837d3176d4727ab2a /usr/lib64/python2.7/lib-dynload/syslog.so +10 f0a41daceb5e0faffe90a0a8419551a0b5cf0e10 ima 2c31c888a5e3de54517bc2d3cdd034cd4b3a2714 /usr/lib64/libssl.so.1.0.1e +10 ed0869b237b202a2aee63ca0ddb0c490eb1d4108 ima 01df0bc543f8d528fe761f7ff401a7cad8d86ea4 /usr/lib64/python2.7/lib-dynload/_localemodule.so +10 b61d0c0f3bcb4e636e938afe73ced27e6871e920 ima 1360e3d5d3acfff994ac98a3606a1ee28c05975b /usr/lib64/python2.7/lib-dynload/_struct.so +10 fb9099243e9d3f208781796895c57ad8b2adcd29 ima ea34a621b4153bad0c7c682b8af01bf7403a342c /bin/install +10 12cb3e57c7f29273eac3e64beaa466ed6d5ec53a ima 764e04cfdf89be3ab219153771e764295c505b33 /usr/lib64/python2.7/lib-dynload/_socketmodule.so +10 856e605eaf2611d5607d9e7ea770a43a103a51ec ima 61a9acf53e5438a1416b4235b99ed161f1ebf54e /bin/nice +10 cc9b6a03b3c403828f5041136d92b4c8cd01c028 ima 6923863a862543d8f1e27c8daaf702152b8aaff7 /usr/lib64/python2.7/lib-dynload/_ssl.so +10 920b5698174a08794d1ddd28aef07edbc515b0d0 ima df4fb44dfc069120f6961e5cc7c6fe6ccee01375 /sbin/ovsdb-server +10 17c3f04511275edebf33d0026f6be984f764aca8 ima 99a6842287c28b55e6ba24dd026af68998c1b39e /usr/lib64/python2.7/lib-dynload/cPickle.so +10 708555c0b5f31c392ddbbebafe35305b60451a2d ima a32eac9818b25d733edcb5da453e61707c9d2702 /usr/lib64/python2.7/lib-dynload/_io.so +10 771da22e9a0ae0ad74ab99b3c2573cc264a4f633 ima a3caa531c6944d88492f7a15c7601aafafc8c56f /bin/ovs-vsctl +10 9c5dd2f578eb24a66a8162616c85b67cb1813784 ima 87cba0eb25f912f8ac2d3ba93233915d797ae10e /usr/lib64/python2.7/lib-dynload/binascii.so +10 ec11cdfbdb7cc1cd920aed3d2f75b9c5864b52d4 ima 7c23c61a5cdfe7d9e60fd2a49a8ed79ebd5fc095 /usr/lib64/python2.7/lib-dynload/math.so +10 c9d74e58b7e9745dc617425c59538dbb7182ff19 ima b63263b6e32d3849f0bfd6596e7d1b0dd4f8c383 /sbin/ovs-vswitchd +10 8988d56a9d18cbfac6ef675ada0d156422b0e75a ima 7761cada80b4b41334cf1a115519cc212d946c26 /usr/lib64/python2.7/site-packages/_dbus_glib_bindings.so +10 3824c295c1cff5ad868c5d22b8a1aa7707991383 ima 334efa2fd1ca614b695db100f67d55a045b3498c /usr/lib64/python2.7/lib-dynload/_hashlib.so +10 cb82f64b207e1fddc61ba97233032c1cc3f9a0d0 ima f87f9cf69d7874d7516119f343f1771141ace901 /usr/lib64/libdbus-glib-1.so.2.2.2 +10 4a168048d62efa0a0c2329cead13d00f06f4ed52 ima 98fedd1d6c57d6c06600fc2ab226487ef080bc84 /usr/lib64/libgobject-2.0.so.0.4000.0 +10 6f9c023f76746ed381fa33f64fb6ef1d2b3533ca ima a5f60db3630ae9ad26e2d0bdc780bffe62ecabfb /usr/lib64/python2.7/lib-dynload/_randommodule.so +10 b0c2814d22f9b50ab7ed55bc3ec9fe7fafbb5855 ima 483150b84ad4b6f46e4dc8cf486381a21b2f0468 /usr/lib64/libgio-2.0.so.0.4000.0 +10 c95fdffa50f7d7c82aa41ab87fecda859889b550 ima 484054764e0506e0178a05effe57d98bd6efa342 /usr/lib64/libffi.so.6.0.1 +10 305286681fe8d418c34efb4b08d1503573d7439d ima 027617531f639b74a011152096feb2db6315bc79 /usr/lib64/python2.7/lib-dynload/fcntlmodule.so +10 fc33c4cbd3b03742c345043300a3d7309f6f6aa9 ima 86d6971feeffb868a959d8111fa69da8e7212026 /bin/ovs-appctl +10 3460d6897291bfce086e2f2e3bd26d069857f0c1 ima b7077dc6d5dd93783a0ef9723d48c9876314891a /usr/lib64/libgmodule-2.0.so.0.4000.0 +10 6a5580073b806da033ad5f031ccd0b356a28c90d ima 1436290c31b99f6d9e2920ff03755e426f783207 /usr/lib64/python2.7/site-packages/gi/_gi.so +10 88ece778b4f9c8f9a7f0d902da9a231d76e45530 ima 8605151addcf981bbd6eee235f7b21e83d8171ff /usr/lib64/libgirepository-1.0.so.1.0.0 +10 6854288ffdba4ee10a5339983c148b093b3911b2 ima 7728ea9588ae4b46b7d5e8180ce17c5baf1589cc /usr/lib64/libpyglib-gi-2.0-python.so.0.0.0 +10 3c39face6da3bcde184904be7f322185faa06e10 ima dee40ab4ba0655956e91fe3ead6769a89aebb763 /usr/lib64/libgthread-2.0.so.0.4000.0 +10 875f0bea3cb30c6ed47e6a044c6dbcf650c9f91c ima 35c102d4feab1f37bcae4fa68d04f890e814bd26 /usr/lib64/python2.7/site-packages/gi/_gobject/_gobject.so +10 e5c0712e3b882a7524d01c8669c7bd42aacc109a ima 5955bcf54cfaea8a65e0527c547faeb80afaa316 /usr/lib64/python2.7/site-packages/gi/_glib/_glib.so +10 8bb3a2c8001c198c8ed1e07a8f0a7baaf118edea ima aaa10bac391359d4294f8b9523c5bb28e40ea244 /usr/lib64/python2.7/lib-dynload/datetime.so +10 baf8a68a4e8f19a25d5d706bfe2ecccb88b013ed ima 2b7f5362434b9605887c1fecd6bd43e881ad8c02 /usr/lib64/python2.7/lib-dynload/_ctypes.so +10 0e337ab1091f1bc3fbc2615091b62f8bdbf83f01 ima 6da7782a8b8582afeef9e07c4f8af6966ff43618 /sbin/iptables +10 7fa6b39fb3e1ed000ad61df0ec4775b61edc8e5d ima 6d341e56447546e70a32662a2065b98b82d87982 /sbin/ldconfig +10 398625a33671cc5261d4ecd50ca9de49f908bc85 ima 505e54be1bd35a3528f41b5ce277c35408c25460 /usr/lib64/libip4tc.so.0.1.0 +10 4e9cc4a73b95f7fde057d40744997d8fce6a0306 ima 0817fc703b16b1b3a55738df5af59f9f927d2922 /usr/lib64/python2.7/lib-dynload/selectmodule.so +10 d6459abb8e537e89b2ae0c2b20ca98bf28e47ef1 ima 65ec4622f3be3a84b17b0673fd642fb85d98091b /usr/lib64/libip6tc.so.0.1.0 +10 e7834639857c5b6906a9196d5289968d1bc7cf6b ima 1ceaf73df40e531df3bfb26b4fb7cd95fb7bff1d /tmp/ffiR3WC1H (deleted) +10 2ff1b40f65b35a7174a78372b7852fa464f9b842 ima 30216be7c708f073f354f653367854ea86bf6c0c /usr/lib64/libxtables.so.10.0.0 +10 042248a33c31a2bee8f61670702f4bc6b7c987b5 ima e9f9e3f3429783991a2e22250ffed8a90896c136 /usr/bin/cpupower +10 cd30962cdc477301b61fd7712ff18c8b1d5eaaa7 ima ba94b7b3533f4d7afd475c3d53398b391b890b8d /usr/lib64/libcpupower.so.0.0.0 +10 80e312c74a22c497ad863b82aefdacab0f6cd76a ima a1cc5c9f889acf152e284a00120109215aa0e351 /usr/lib64/libpci.so.3.2.1 +10 deef2ab4b5f2be4d3c6a151ca405051c39e5747a ima 609c61b73c848ec6d9feaa8df8413f82ba34a28d /sbin/ebtables +10 7171be9a790be1bdcc9327ecf4260e7a7a381fe5 ima 1ae46e46d9a13ec757da14794994bebf86fdf6c1 /usr/bin/x86_energy_perf_policy +10 440e451fab4607438115e99b4ff4963c2085dbb8 ima 51252831432a2abbc649ceeb48e2289607258046 /usr/lib64/libebtc.so +10 ff4dcd4a40a18fecd61e9c84f07a6b8e837243c1 ima 7b987b7bab205c84d1b91ed7829068715c396c56 /usr/lib64/ebtables/libebt_802_3.so +10 19a88b57a51e132f3fff5823ffc948e420ec60ba ima 72a88229ac56504ab6b871c0b2875efc2a37888a /usr/lib64/ebtables/libebt_nat.so +10 059b9b8e4cad8b57da709aa9068be4ee3941be31 ima a18d7cbcffa0afb2523a2d314c92bd837577aace /usr/lib64/ebtables/libebt_arp.so +10 cbb52d394e99b92234bb5335c81bd423f54360ac ima 53dc93eef99cf60022606b5deb4eb09e90997d28 /usr/lib64/ebtables/libebt_arpreply.so +10 454339e9c947ad6654c1926467e227b56ed4b08b ima af522a584c773a8e0f4dba8c650831fb25a58c8b /usr/lib64/ebtables/libebt_ip.so +10 c50f7ba49d10cd0deb6b64953865ca9f9f988755 ima 7532476b1bc7da2906474a20364a5fbf8c07959a /usr/lib64/ebtables/libebt_ip6.so +10 6815ac935e7647738e6023f546f650cf7dee5087 ima 724fb5295b6a3d29b9d8e33848c9d3cd9243180e /usr/lib64/ebtables/libebt_standard.so +10 026b33c9e12da3c960e784a3fdfc7c0533341f2a ima 61dfdda8dde36a751fdf9e04dcbb63306e35e9c3 /usr/lib64/ebtables/libebt_log.so +10 f1a9eb50d992793f63f6401d0a2b61be81b6fc73 ima 7a31df8c949b155ab398998b6371176cf5937293 /usr/lib64/ebtables/libebt_redirect.so +10 e0247372f63863f3dc89db8dfdf2938f5efd5375 ima 920df97f45323187693afb556871a5957cd2f298 /usr/lib64/ebtables/libebt_vlan.so +10 50aa9f2a2938c06522c88a58c1d0bdca145a5dd2 ima 1329d3b1fde0e4c6e618faac1c597396dd40526f /usr/lib64/ebtables/libebt_mark_m.so +10 56147c25e2ea56be3828e592be627dcbfc753f81 ima d0bdc8759de7a60d5052c0dea5256cbc3110a23a /usr/lib64/ebtables/libebt_mark.so +10 1ad0b990a1e0738be85da867d5af78df895dab4d ima 7f660daf5ccd87e2620fb7231b0cddae9038d6ff /usr/lib64/ebtables/libebt_pkttype.so +10 ce8efc32c9399c7c092ad98e13417ed64f9df86d ima 8f592a2a6d10431a367eb77238fffb9f892d71b4 /usr/lib64/ebtables/libebt_stp.so +10 14fe620c814703b0610bc1c3d5384ac35e1fda75 ima 91cf8447d36b74054c04fe2c05737dadabbf9b62 /usr/lib64/ebtables/libebt_among.so +10 28c5dac5fc19301b62dd3c8a3693a1dcb0a40e56 ima 3fbe876eb357d4bbdb2783a386852034dc4f7745 /usr/lib64/ebtables/libebt_limit.so +10 3fb1c515dedefba140314c314a41d9ab2aa5c68f ima 1c1acaf1f7afdaeb3d573a52f2539a75ce1e96ed /usr/lib64/ebtables/libebt_ulog.so +10 cf80b6a40b8469efebc3828ef9fae8c593a1f800 ima befb5a6706d2ccbfc33009ec35a60325ab9d84ac /usr/lib64/ebtables/libebt_nflog.so +10 4cd0c2c0a0352991039ed485971521f31c792f62 ima 9fe4cede96869ad7dcda7e5f88c95816cb01fc1f /usr/lib64/ebtables/libebt_AUDIT.so +10 dbf45645b3cca0318d8989e0ac9651eef709f187 ima 2a160e8fabe8377c92fd7bebce88cb59785f314b /sbin/agetty +10 ea3175431f41f983266b732a34c5dcdf40cf8f79 ima 80ef22cb8e986d0b25cc119507bf6ef2012bedc1 /usr/lib64/ebtables/libebtable_filter.so +10 0c4b3462a6088db72c8cb47a37599ea434c8c28a ima a2e2a5fc79e48c472975d96846212d785d74a5f7 /usr/lib64/ebtables/libebtable_nat.so +10 1fc812bcb6426ff98c022d4c38ada233a232cc19 ima 3014d522230bfaada8d1462ef7860aeb30b09e7a /usr/lib64/ebtables/libebtable_broute.so +10 bfd47e4b886b6a2ee3bef885ff071b68d9ead720 ima d58854cddd040fce46cb21fb00d12781b5199fb4 /usr/lib64/python2.7/lib-dynload/grpmodule.so +10 21dd4a8b862ff82b0890fb2abf5a7cbf798603bb ima 32664b3b4fdb64ee8bf1ba30edf854cab23aabca /usr/sbin/NetworkManager +10 858bbddc3aea700b2c075af0d7449b13181c28c0 ima 7c4bf94681f3de7fb49b9e5a7efc25c1b282bf67 /usr/lib64/libssl3.so +10 29ffb2de0ceee1629bd03376d90a56820e89b3db ima 681a4fda0c3712f32f1a6bd09b65d763e7c86fad /usr/lib64/libsmime3.so +10 b00a0bde587e595ce3691b62f53c1e861ec96097 ima 6b1c5c857f05b710727e71e286964ef1f66e034f /usr/lib64/libnss3.so +10 dca87cf061af90b2d22bba0c0b857b20922f0306 ima be12e56161f741439533eaf5f22ad0e4d46ff295 /usr/lib64/libnssutil3.so +10 d6db25db57ab80115785de184e03343d2c28abc4 ima e699b823266e138eca6e5f22d1cb1eb380f66e82 /usr/lib64/xtables/libxt_conntrack.so +10 ccf015bcdf67097afcd498553d038b09b1dd6cfd ima 4aa33b532c73e9fc8324ffec8dee2c42c85ce599 /usr/lib64/libplds4.so +10 0636e08525a1c5306414d5a410607e4f7ae9c888 ima 14d18e96e28cb5bdba8644ebf878828731881ce3 /usr/lib64/xtables/libxt_standard.so +10 ae66687954c339bad57270736a6bf91e38a989a2 ima 95fe9fdc39f972706b4b8324d62b5cdac0f6bfe5 /usr/lib64/libplc4.so +10 e81791117f07f1885396c507ae6024122e570d84 ima 4c1b45be1d52f804c8ec6ada36e4658726b3fd84 /usr/lib64/xtables/libipt_REJECT.so +10 5d037f09fd4e8645e46675db37886032eb49fdfd ima bb14c40e72fc857c1639645271f8746a9fa457e0 /usr/lib64/libnspr4.so +10 d196d487a2911e5e5723a0ab8286378b1f664ad2 ima 999979006993dcda62060653c4fe91694494b052 /usr/lib64/libgudev-1.0.so.0.1.3 +10 a060bbe8e4464dade5fd97f2c137e1e7b9ef7a9b ima b27cfe14ea97711116277f82404619ad3b0cc44c /usr/lib64/libnl-route-3.so.200.16.1 +10 0ec1556483d6ab26864e950f78b10814ede8aa44 ima ccdb37afaf3264cf92f382e561514c43b53f53ed /usr/lib64/libnl-genl-3.so.200.16.1 +10 46344a3c99bef38a55ed36c825655340f7eb1152 ima b3f4f7470f8caf0422b0fa90c31cd8d0dab53b00 /usr/lib64/libnl-3.so.200.16.1 +10 307dd6b61f97a0b68495c6091be383b51641d756 ima c8a13ae67661ca871460180684d38db2d31f6703 /usr/lib64/libsystemd-login.so.0.9.1 +10 17a78e05a978cc6e31f0301cfccc0f64d11414bc ima 8b2ffdb24d649d0e0d00cc67ab61655599a0ca85 /usr/lib64/libndp.so.0.0.0 +10 75e9c87f91d25a762724bf3261b95efd0522337e ima 2cf188d5bdb303942c9014bf4fd06157f59db433 /usr/lib64/xtables/libip6t_REJECT.so +10 05f83b92a3e1bbeefc6bc520cfe84c2c96fd9bc3 ima d356050f350768d4de53cb34b511091d6e1d4e0c /usr/lib64/libsoup-2.4.so.1.7.0 +10 8967d4b697fd938f6f20e3f23e938c32bfb6c36b ima 02241081952cd8bac3d54807f76f4089776ef3d2 /usr/lib64/libxml2.so.2.9.1 +10 f41c80f02a23ee4fda236020df9351a8606406b2 ima 30b900203df31e993e5af7a7009efbf3ee50df4f /usr/lib64/libsqlite3.so.0.8.6 +10 03a3f602fef8864b521e735e4ef7d85a6bd8bc39 ima e99d53ef49341f9d8db2b3ee070aeccd92033d2b /usr/lib64/xtables/libip6t_icmp6.so +10 d8276c8ffd70aa0f6411fa96d5413dcc724f073b ima 3c46e7ebb7d519ce58f2f4a55a43f6a34c2f24d9 /usr/lib64/gio/modules/libgsettingsgconfbackend.so +10 822bff1939bb624ae21c1402e92c4fb1f6d8577b ima a97d873a4f3be1af08274aa40d6b9812ac55b500 /usr/lib64/xtables/libxt_rpfilter.so +10 8916a0beefc5644481c70a50bc4f5c186154fb45 ima be1ae3fa6d09eff8c95dc5370387fe824cc0b8e6 /usr/lib64/libgconf-2.so.4.1.5 +10 95d8783e7f21134777cd48d55f2c68783ad3e836 ima 2fee1f1b5b8d22d66e0da8545b9de7525c01a253 /usr/lib64/NetworkManager/libnm-settings-plugin-ifcfg-rh.so +10 8457aa16cda7c91264dc608edd1c5480be78d180 ima 5861006481311613522930bead631289cd59faeb /usr/lib64/NetworkManager/libnm-settings-plugin-ibft.so +10 f2f1cf2f351cb45cb1ef9c104ae5a8646c2a7fd2 ima 3e86468a681dcde79cfc4af06ee3c12fec6736d0 /usr/lib64/xtables/libxt_tcp.so +10 2e2d3793cccc9ede1f7e654fa0f9164812034c8b ima ba99969f8aab9a86c5ee65b845e11b72d5ccb59f /etc/rc.d/init.d/network +10 2bc4ea98af725e4af683531c35a3246b11bae58e ima e8ca450d099b48e6ed0102f09d7c97f01f0890b6 /bin/sort +10 2ee6319eb925e07af19b941ee3566cce5668e6a1 ima 059d4f3205f3326e457989066c8acf31f05c81b1 /etc/sysconfig/network-scripts/init.ipv6-global +10 224cd4022710da1f36951e00b3dcd7e8548b03cd ima 5b517cb711e2d90378ab0e32dd860be4940c0bee /sbin/sysctl +10 c06a2511694dfd5527df901ab21daa02f2adbe2b ima 9319a207131c4edf823f2f1790266a6e446a6ecf /usr/lib64/libprocps.so.4.0.0 +10 8cfd62f93d79571f2f13c9249f811c4b5c04a78f ima 455c92d53ec08f931993bb0bdb85219f6c006f05 /usr/lib/polkit-1/polkitd +10 e85f95883be93fcf172647e9ecb6b35245285d87 ima 3e606c09d6943871679cbafeb5057c310ac8b25a /usr/lib64/libpolkit-gobject-1.so.0.0.0 +10 4b0861ff663834ad37f402b2d90bf00f7b7154ab ima 5633bbf7e0554cdc0722700ef15f959918a66b3f ./ifup +10 64af0ef6d44e7fc9d31f7be3787ce7dd6904d2ac ima 653266233e5e270c4acbaba773f9703407e82a37 /usr/lib64/libmozjs-17.0.so +10 e10276d1e0573b3b12fc83f7e099915ad47d358b ima 57465cd7c8fd1ea6e8cb92d5413b6bb3f30ca478 /bin/nmcli +10 52f3899efcb7a35244dd58f83df94aa1c18182c4 ima 58a3ac9b3246e60dffb298a0e192f15aa6cb0c7f /usr/lib64/libreadline.so.6.2 +10 dca9e80afcdcc1265b628369d4164a1ea6087f2d ima 34df64704c152ce1a6ce46ad46eca442e3fc6b8f /usr/lib64/libstdc++.so.6.0.19 +10 09bff45640351151c0a706e447a55d4457d0256a ima 3e41374dc63a3b00012e0cbad0e22b01ca3a48de /usr/lib64/libnm.so.0.0.0 +10 b06614653ffe75033a46267eb5164d5592b28049 ima 7e36d730030c298f029bbee39416f8d15c964f90 /usr/lib64/libpolkit-agent-1.so.0.0.0 +10 8a2af442570d2d9f8255581b5e5d9225d8064739 ima 1ceaf73df40e531df3bfb26b4fb7cd95fb7bff1d /tmp/ffiOJ83IM (deleted) +10 f70f358489811a96bcfb2243c4e56e8fe278e735 ima 871220d3471e3495e0e7295729470fd546ccf466 /bin/dbus-send +10 eabc1f1d3ff3d5e48384c4c9d7ff7d9809b2c1a7 ima 7ca53864282da78c0d894c3e7ea1cce62fd3b22e /etc/sysconfig/network-scripts/ifup-eth +10 90c70d0b7aaa713a9085ddac905285e9ec4502bf ima 7f01861d3b0cdfcb4268366b7470787cd0f629e9 /bin/ipcalc +10 5dd0be460660e306324993a052cef67e2d08249d ima a2b93afd6e3160d508eb690b937181121498c9b8 /usr/lib64/libpopt.so.0.0.0 +10 a0bba83e3a34b072db7ab510ebf986eecd1a6788 ima b5923c00d9c7f8ecc8483051594a85073460ec9b /sbin/ip +10 7c208f1909e5934465431157d7aa2d3ce5ca14e6 ima 410b29ef8195b2177e1c3eb1a5b5074c5176d185 /etc/sysconfig/network-scripts/ifup-ipv6 +10 25362852a6478bab3bae0d63bec75c771caf028e ima 4d9c17edf8dd1f02708c108a74e1ef12056810b7 /etc/sysconfig/network-scripts/ifup-post +10 9f56b26310031479bebe26200b2fd65b3b9bd3b9 ima 89a4bdcac6022ba6a18b00749765c52ae17230ba /etc/sysconfig/network-scripts/ifup-aliases +10 bf519f72816a7a5d7ed66e8f4ef7468033f4e683 ima b600eb9d1015b8bc90a9c3aa82ef03773ff5271f /etc/sysconfig/network-scripts/ifup-routes +10 580edd2963ee6c70d84bea7330f3d246b076e804 ima c7c6cccda66b6d6637e3d7e0e98f3de9c9be3bd8 /usr/sbin/arping +10 546bd9bc0133af6d9942c4c75f544c67236c1ee7 ima c526de9c216735188b929ffb45f75203a7a357cd /usr/lib64/libidn.so.11.6.11 +10 a0742ac338e953a15a995d4207d9c04321088c7e ima 5ab054e52be291bd74f56ec2d2126ca360d99aa2 /usr/libexec/nm-dispatcher +10 e353bb3487ba7267f6071f2572e72101388db17c ima cb3fd4528cd2e135fd8048ab79754257952a376d /etc/NetworkManager/dispatcher.d/00-netreport +10 2f2e0ca6282bb7380d8b93638777b3903c81b05e ima 1fde00e484e0e678257d290740cf92069ee948c2 /etc/NetworkManager/dispatcher.d/11-dhclient +10 19a36dc8614f21462c67931efba8519b45512380 ima 3c6323d16ef437a041280d8fd656ceeb67a5fe7b /usr/libexec/postfix/aliasesdb +10 63710d4d454b9b3c2e8b2250562844133f888afa ima dec6c3db42304e3f2713abe94e127f6a21585035 /usr/bin/kdumpctl +10 ac383755d856c5fd05bd2fa7e3fe4413a10e0268 ima 79c17ccab4f6f65c9f2fe54a2f2da19a649941be /etc/rc.d/init.d/OATClient +10 cae56be8718048cfcd65e72d22eb43fddeab881e ima 8c8849367664badb914b6d6452ba806695d8056a /usr/sbin/sshd +10 11a78b3dcbe4569aac10e0a536ff077824366068 ima 12fa5bf15a081c09027c9e26630d613d2f83ed26 /usr/sbin/postconf +10 e6c0e7632a627d740d46808f9e72a681f805735e ima 332b4f34204fc32c5ec6a804ceca606f43a3d12b /usr/sbin/httpd +10 482e92d0877222c0b177dfed737ae0e129da9ca9 ima f9a7a23405a06d0969a4aa2864e3ffc58265711d /usr/bin/flock +10 eff1f91d6acb64e2521c0352e4051ec725825b55 ima 4b020677021ee81add38adcc3ce5007c45c733c9 /sbin/service +10 7f6fb95b05b398685570032cad4d01442276f418 ima f739ad1acb4f822bbad1f10fbe2bfcea64d75661 /usr/lib64/libfipscheck.so.1.2.1 +10 b315045e797e9cde393efe55ccac2977d26835c8 ima f5a9e2c7f8af38683bde581087420bcbcc23f1c6 /usr/lib64/libldap-2.4.so.2.10.2 +10 1edf26b7f028c5dfa1e1d6be6d35c4350b0e6ce6 ima 23dacc05ae2c676298555fca8330bea2c2ddcd44 /usr/lib64/liblber-2.4.so.2.10.2 +10 912374ae5393086de6dc9dcd81a65c399c887164 ima 16e4ac447a8b3d4aede788cf62ee725d2711fb55 /usr/lib64/libaprutil-1.so.0.5.2 +10 0fc86e1d64b03105b529e2265f76df01c15121b4 ima 11d27dc2b75306e171ba78f6e32b0da47e68f768 /bin/basename +10 45ec95c5863a25aa4b953ab04808770ef7405e36 ima 1769eeb3cb02a387c4fca16da12228afe8e670e4 /usr/lib64/libcrypt-2.17.so +10 4c7472e3c2ad26dd59c8d81ef9d25a526af5c226 ima c9399affcff0875d1ef1f746f406365839e4d7e2 /usr/lib64/mysql/libmysqlclient.so.18.0.0 +10 319adfbb09dc789bb1d5f1a27eb002d033297fbe ima 7fcaa88d76d432472583844a1c0e8f6e07715461 /bin/egrep +10 af444271bcdd2ab2ee8212fc55be316ab227fdf4 ima b66befdfa514246d63fb8783ac9a5ffa8f29e941 /usr/lib64/libsasl2.so.3.0.0 +10 330a21733d63d45149072dcbde59fd4a4f79d3f3 ima 4f86f341750987b6fcc0fff497aa72f2e120c37a /usr/lib64/libfreebl3.so +10 d127e704f1bd6d88ea7c25c6ae5335591ee1347d ima 129fd572bbc160bbaa27ddf041e5bccd29789906 /usr/lib64/libdb-5.3.so +10 2eb76093a250aa9f6b35ea74969366e5cb9ea1a5 ima 324a580cd00c4fe8a1545287ca1734f3b2a799f8 /usr/bin/java +10 f80b4b5776caec4c7108f037f3af7f50ccc0efb2 ima f1c380cea834f33a4ea8c4ee473dd9417dbd4adb /usr/lib64/libapr-1.so.0.4.8 +10 b8c55465faf1f753975e6d147f41062c8a5173c4 ima 2a7db5fd791841f4beba345bd62a8a56fe0beda0 /usr/libexec/postfix/chroot-update +10 d4294da8d99b16bbad762ee69135aa7f54a78a36 ima 4ba0440c66c2951fa63e6ef0133552a48d2221f8 /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.85-2.6.1.2.el7_1.x86_64/jre-abrt/bin/java +10 ccbde2e002688deebad300a428b75f6cbf900fa7 ima 5b2cb2adea6d8448e58a4c1393c421796dbe9038 /usr/bin/hostname +10 54d1cd6ca69b85526b441b9a5d7edf129c92c10c ima ea94150f89440a5f1b3405de0104b275dbc1dbb8 /usr/sbin/postfix +10 b51aeb8a3c71b1a29e97750d5dc3afc5df04cd4d ima 1e48742f3169381e7dc7dc1b1eca78c9f134da7c /usr/lib64/httpd/modules/mod_access_compat.so +10 7ee7d0ca6be9ba61bb3d0e2538404809b78cbc1d ima b0cb8afbe037620584c2b274c028fbe34d8c1925 /usr/bin/cut +10 a6aa2ffe8bbb70687c694896aad162263546a29a ima 8b045ec776311b85a507ffa77f51670c0aa330d1 /usr/bin/tail +10 4f1a494c5ab474a5f7708deb3537961f041bc5bc ima b5827cbd6eb075854dc2e4fbf5d82370a1eeae2f /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.85-2.6.1.2.el7_1.x86_64/jre/lib/amd64/jli/libjli.so +10 bc71b4aa1566d2eeeb86dff28c39bd87f025bb0d ima d1b0ecc427d317d4d98f57217f4f0eac986f3446 /usr/libexec/postfix/postfix-script +10 e96d669e5179860de1c100e7f1879abe37622e60 ima 85fb21c8e81f8ff507e958f1ece038f8ee7960cb /usr/lib64/httpd/modules/mod_actions.so +10 9c412e24d09c6dfea0f5ab110020ad61929f6ef7 ima f3a98e753bbfec04510e302a0758ac8ac1e404ee /usr/sbin/sestatus +10 f00ff2595ae49723db7ac08413b9831927fe6342 ima b2326bb10104ef5ab2829eebea572d5286072a4f /usr/libexec/postfix/master +10 ed76650990caaee4c6ecd19407a4c5fd2c317b9c ima d69a34c8ada800e5a795cd2092161902c9ea3393 /usr/lib64/httpd/modules/mod_alias.so +10 1c1c5e47050c6bed72e1178a006774637956d768 ima 9c3c2662a13994aee3d6107ff630ea383f752c62 /usr/bin/df +10 69d52f423e6b3de9c70183989fa87eca204194ce ima e4cfd3a47674dca8a4884aa2c77d7de5610dcad3 /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.85-2.6.1.2.el7_1.x86_64/jre/lib/amd64/server/libjvm.so +10 7eeed825b36246d93cd198aecd021bfc2763caeb ima 326bca7f6c9d2ab2d5e542fff337b9e3f2441180 /bin/uname +10 2e4e3dfaaeb2cf364fd7db931f774b352f8d7a35 ima b5aea53cf1b9b1dabd8c63d2e5ef8ac0e7873795 /usr/lib64/httpd/modules/mod_allowmethods.so +10 62c80701ae40cb7da5f6c3471aa439fc55c6679f ima 78c8470662b2a2b84e438fe3d5ff824a19e0ac11 /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.85-2.6.1.2.el7_1.x86_64/jre/lib/amd64/libverify.so +10 3875dca084451e904c18d946386d757c907537c2 ima 872978a722fea3c3f6ebb250a93c6bb14e8b1127 /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.85-2.6.1.2.el7_1.x86_64/jre/lib/amd64/libjava.so +10 247c7d3d9a46cacde0dd73e6fc2f5acacffc476f ima 1e2424f2772d35a684aa9edf63807d96c3a3f35d /usr/lib64/httpd/modules/mod_auth_basic.so +10 f9566dda1eba6d94e36291e4191995a8e529582e ima b1944e7c238470b6c8e10ed1e111e0cc6721bfa5 /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.85-2.6.1.2.el7_1.x86_64/jre/lib/amd64/libzip.so +10 d62ddf10d7a47d546d4dc54886408aab7fbf2da1 ima f3cc863f612a9daf9f740079f40b84237239b3cc /usr/lib64/httpd/modules/mod_auth_digest.so +10 d6ad4a121138eb3e9c6da1ccd3e8b7b84e7cb0ef ima 1d5d62f8e07ce73d44867d7bbee5b61d5bf2440d /usr/lib64/httpd/modules/mod_authn_anon.so +10 2987bd37fd8540c1286c73995946925f53b84d8b ima c6e975273cb038c4d1a3c0cb722a243990b607b6 /usr/lib64/httpd/modules/mod_authn_core.so +10 0313e9a9b574993309dc8707e73b85eb6b780adf ima 87c7277e6f8933d13b969f15d687d60f19843006 /usr/lib64/httpd/modules/mod_authn_dbd.so +10 30808d640392b1e96ef8bd289e75f682a4171d0d ima 598762e0ec26e4fb7aa6b01c8547dbcdbc460947 /usr/bin/stat +10 127327c222d210c342bda313a390a1078192b4e5 ima a348b14f8c46dda9412bacfe5b8e17514090d512 /usr/sbin/postsuper +10 4cd1465d45680e35774655245469395387902c5c ima f20af4bdfda0419c27d2e74afda758ef4a3c714c /usr/lib64/httpd/modules/mod_authn_dbm.so +10 fc465394bcf5d6a272791912c545c6626dcfbee1 ima 9d8190130970993cf920d21e6803c25b162a4aa4 /sbin/kexec +10 ede654e08bec915910d433f96bd0ebd56aebc142 ima 1b53053cf02987a06c198992f9caa7b23926d714 /usr/lib64/httpd/modules/mod_authn_file.so +10 6e2df9156971905184734c3106f0b10e2c43a0af ima 2a0a88b9bc2b6e588fdfc8489ec3a747232efcfe /usr/sbin/postlog +10 4da532c2c33f9012ea8855bfd3bad650a2dc1dd3 ima 47ab3da9a56650a8d6dcdf73554ba540568f7c32 /usr/libexec/postfix/pickup +10 9933fcbcf1b19d5186988ec631467570336e1337 ima c28dd47bd3475a0df7968e8631f92d9c7bfdb67e /usr/libexec/postfix/qmgr +10 b76f45b7e2ae550cc8a2a1d070027390170db2ff ima cc876ff2fcce3df5d98cfd323daf8598c1a2027c /usr/lib64/httpd/modules/mod_authn_socache.so +10 2cd54e8892f4b19328db9a5385dc38105a0a15e7 ima 3a00bab661232eff293a86185a4f0728cf2aee8a /usr/lib64/httpd/modules/mod_authz_core.so +10 37e2f4322b5725fdb2fd4c2fb7f541851f16a50c ima 02e2734d91d1287c8f8585f153c3c65d7ead4aaf /usr/lib64/httpd/modules/mod_authz_dbd.so +10 1fe8035ace1fe671b2df22019eb9df639d6e47fe ima 464e14a105d47244daed9c90997e3ad67546982d /usr/lib64/httpd/modules/mod_authz_dbm.so +10 843873f0137f17e9725f864cee9685a426ad83f3 ima 582e73668a7d5e3caa1f3eb7fc853e2b1a617a6b /usr/lib64/httpd/modules/mod_authz_groupfile.so +10 3f183223c6f86ace1aa2acd8ffb1b532ae2a7e84 ima 38f3f1f3b6c53bf445bcfab31f9dc87a7809c1f4 /usr/lib64/httpd/modules/mod_authz_host.so +10 68ae8a03e92588da664cb5bc6dd9429565c38187 ima d903aaeae4dc2a543f36a23319267ead6f7fd31c /usr/lib64/httpd/modules/mod_authz_owner.so +10 a8849682d8946d35c89ba63071d1d2441d81c787 ima f487841ce4ab0cb7ce22d5de74ac5302803e9020 /usr/lib64/httpd/modules/mod_authz_user.so +10 8e8ea1cf6888ee00960825741ae45862a6b7d809 ima cbb08606860347258782fc7f6a57bad11cd7713d /usr/lib64/httpd/modules/mod_autoindex.so +10 106cb907690c06f7a93ade9e795a44af5c7c322d ima f7c6787be9f538ebe3f7deace309856a28cf672b /usr/lib64/httpd/modules/mod_cache.so +10 9d99f69aba2d2f960bac06c35e317e2c9702d3f8 ima 098e89de3fb4e1f6ae5c528ea6c482e67a30e56e /usr/lib64/httpd/modules/mod_cache_disk.so +10 84d1df9430a77a46a19214a90a9a045bb6a25ce0 ima 67d2d22c9c54d21bb14579e778e5381fba1cc7f7 /usr/lib64/httpd/modules/mod_data.so +10 00827bf2696cadae605095b3a83d80b76481ebc6 ima 754a1036091dd046a7e99c2b8ee680cb58565e81 /usr/lib64/httpd/modules/mod_dbd.so +10 9f86198dabcfc7201642be32f8aa3cd88044454d ima 8e162aacd5fc7ef12c87ce01cd6666efec75714c /usr/lib64/httpd/modules/mod_deflate.so +10 dd32b65addfdcf16cf79151f38069c827f33e0b8 ima 2d93b38d51ebe487d06a41f540b59fb7c82ba529 /usr/lib64/httpd/modules/mod_dir.so +10 1793e370d9880b22d3db3dbeaaf55a49b47b6ab5 ima a9406a69a2cd2ddbaf33b6c119c7153f595a006f /usr/lib64/httpd/modules/mod_dumpio.so +10 b261422e0155496516ad0919bbc422903fc82eea ima fea23976e9d6e96a1e5545568e3e06f9fcaf09b6 /usr/lib64/httpd/modules/mod_echo.so +10 41151a07afe76a45ff712d29d03916ede1ae4019 ima 0d46f2404cec0019be4e125f6dc87c4fbb59799e /usr/lib64/httpd/modules/mod_env.so +10 b545c1c8f359c480031db476ded56ff183ae4dee ima 25eaaba3bd14015c292807a814a450ee7d37af66 /usr/lib64/httpd/modules/mod_expires.so +10 a9f9f1f5b091dca811a11d20bbdfc65b353c1866 ima e35d08f44977fbed59082136b647dd66a8380012 /usr/lib64/httpd/modules/mod_ext_filter.so +10 b341a0db47627db3f9119ab14cafe5e446e514f6 ima 7deac13b7394cac1a9046141159fc3bc1d456fa0 /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.85-2.6.1.2.el7_1.x86_64/jre/lib/amd64/libnet.so +10 43ebf2f295ce1606ba6ab4de9808ced37342e8d5 ima b4217eb9ad9136d7618540a50c03c0adef8763e0 /usr/lib64/httpd/modules/mod_filter.so +10 11e00e7dcecb4cd481de55141727981debce7bce ima a2d6e1acabc2b201dfc16eb3d8e7510924d04794 /usr/lib64/httpd/modules/mod_headers.so +10 11f9db7125f6f00c6f237b21e6010b3ade21d739 ima 71645c06e6ec4b97fab4057ddd8eac8c1dcb87e3 /usr/lib64/httpd/modules/mod_include.so +10 5cb1f50c2d8a69862ed8b0273ee063afb71c7849 ima cf4f912adad9d5d2680b940d90adeb72fd8438f6 /usr/lib64/httpd/modules/mod_info.so +10 346b43685d4570e81d5d0d88978dc14f6a0738fc ima 42f3d6a945fad0c57adb3b55bdf193d421c1d7f8 /usr/lib64/httpd/modules/mod_log_config.so +10 7c6546e3b48af92539e6de0a71f14eec7ef6bf45 ima fecd1a3abac647c4a9660b51422fff672dc8af17 /usr/lib64/httpd/modules/mod_logio.so +10 50dfd1f449db502803d8badb84f2c3395fc0def7 ima e8902e8a38fe5104c408a3372781f01a00f1f322 /usr/lib64/httpd/modules/mod_mime_magic.so +10 ed7a72dd5ae48475e5f9365920accedcb668ffcf ima 2655429119797fd7f9e87c6a032d862ba9a28bc4 /usr/lib64/httpd/modules/mod_mime.so +10 8a0b41bbdbee8ac1c04a462fdde85770bf9bd9cf ima 9d733d1fa3fb153460e9e93940b64062748606ff /usr/lib64/httpd/modules/mod_negotiation.so +10 21ebd34e08d415677619a0df2e991d0002c595f5 ima 724f0e2abc7a4fd5286d093a74c935c3d7eb5c95 /usr/lib64/httpd/modules/mod_remoteip.so +10 27ae7f0b0b010cc0766f6bd454be866fba715705 ima 321ff0a35ec298c691e8348cd8ab6831ed98c16a /usr/lib64/httpd/modules/mod_reqtimeout.so +10 5ecb89ca0ea54e5e299c5b753ad3164e5d5ba4c6 ima 0dc72d1dd16209376cef95e0c6234f9a878debfb /usr/lib64/httpd/modules/mod_rewrite.so +10 bcc641a49b28d11c387e1bbe2e5e58cabad4b43a ima ec10354162f3ecc7fc9599a3526e83f36043679b /usr/lib64/httpd/modules/mod_setenvif.so +10 49df5a6a44f459f934d308b1561bd4f53a839022 ima 47287459245127da70d36dd79f571c5662edb83b /usr/lib64/httpd/modules/mod_slotmem_plain.so +10 616992655d2010111f318e9561fdafd962d5ac7f ima e9a23915a1896003b4ef8bc9c69b7ea5301ba365 /usr/lib64/httpd/modules/mod_slotmem_shm.so +10 bf1312eab7ab7ec507ba7c92ef984c2578095e1a ima e679cc0de32520d393d8fed85a5f001603379b70 /usr/lib64/httpd/modules/mod_socache_dbm.so +10 afedb1e3cd508658f2b9ba8ab577861b3b132c9c ima c7c2f80e4c1c73f19c092546a550f97b14e248ff /usr/lib64/httpd/modules/mod_socache_memcache.so +10 4a22600770ee54927c32845d68d0d30bbe89f35e ima f234aff069735ad5b4bda691c676cbe931bb86ad /usr/lib64/httpd/modules/mod_socache_shmcb.so +10 22d7d14818412e9e9bbbe529dae3575cdb120301 ima 01e3a79e306578215c3d078b01b43a9ca619f0ca /usr/lib64/httpd/modules/mod_status.so +10 e6932c38134bc806a440067cc3fb1a2dca7015f1 ima 77060eb0c4729aa440ffdaa5a86e2fa058d2d574 /usr/lib64/httpd/modules/mod_substitute.so +10 b3fc87107b10838c6edba6d501c9e2a1b8753cb7 ima 64d0df589eccae55a75b0239f8397fad539e2bff /usr/lib64/httpd/modules/mod_suexec.so +10 dca7126ef42f899e91f249703b78461b8208b818 ima 11539e8aa59cb97e24e365ed1c37e6578bc15e60 /usr/lib64/httpd/modules/mod_unique_id.so +10 7645faaae7c1e6eeae2eaae6fb8e90fa594468cd ima 733ddbc381e69c7d626ddadc73c2f5b100cb1cd6 /usr/lib64/httpd/modules/mod_unixd.so +10 4296436f8defd55169afa388b14956f303b48bfd ima 5cab432a3a85ca267406f4ea1a293e327a060bad /usr/lib64/httpd/modules/mod_userdir.so +10 1bdbb5b1ad44dcc3e7793ae36e522dbb26d2ca65 ima 3a0e134e1e247e29a2fe4651aec7a82c27c120c0 /usr/lib64/httpd/modules/mod_version.so +10 b32a1a7df74c1bdcb78313207bbecece658536ab ima 490fa5307d5a9841fb0879fe1ca61230ca2f28a8 /usr/lib64/httpd/modules/mod_vhost_alias.so +10 1980b8f55ae2111456dd46fc00b3c9b92e2bb8ea ima 3742ba32ae5b242ced6518471c4d648636573739 /usr/lib64/httpd/modules/mod_dav.so +10 99ff862857545f807d6fd732190d42d824e10616 ima 9f6948f87356ed2219801f2aac7411ebae923f68 /usr/lib64/httpd/modules/mod_dav_fs.so +10 1777a410f2b338827db1b2db62300d56fb8b496c ima e46ef75ff6e746bd6cafa024ee4ddf4d6c1fb8ba /usr/lib64/httpd/modules/mod_dav_lock.so +10 8f21bef19424be550cb4b78ef5e45cec2d0db0a4 ima d6fc467770568e4f47a052554855f141c25e6ca3 /usr/lib64/httpd/modules/mod_lua.so +10 fb5fb3dabe4a69be01a3d641b87ec2c5ac7819d4 ima 04f2ddfca12f11031cac047440941d5409cdd98e /usr/lib64/liblua-5.1.so +10 4a91c4fc31ba4982e4bb5914645dc5763484676c ima 43b0c0fd9010d6e0eb8619e4a233ed427fc7eaf1 /usr/lib64/httpd/modules/mod_mpm_prefork.so +10 f296b10c31cf21f3fcf0c8171cd9b6c7ea0a1bf3 ima f49fe9e3301a6bc9b7d1fda10c76fb17346d8434 /usr/lib64/httpd/modules/mod_proxy.so +10 ac38b5f787666aa7af0425d885907379380e88f6 ima 5b219f79e4ce6d6b1097bae3006a3416228e7606 /usr/lib64/httpd/modules/mod_lbmethod_bybusyness.so +10 1db5bea132c4450e9fbd2766b92876ca7891cd99 ima 7174fdcc1c24d17fd30cd345d115beb87865aee0 /usr/lib64/httpd/modules/mod_lbmethod_byrequests.so +10 2bcb1e78355780eb28035a62c737e8d398370a37 ima be924a27c7f171b5e482549d5b4da069b4d5bd50 /usr/lib64/httpd/modules/mod_lbmethod_bytraffic.so +10 90db344dba315e727a0c05960740541281583030 ima 0380be00aee815437fb43ae769c74d7b04d4cd14 /usr/lib64/httpd/modules/mod_lbmethod_heartbeat.so +10 2b5d974149aea3868524bc7b3ea93b13a774fb9a ima 35c8b8a5e28e2299890491be682d3314ee9c1698 /usr/lib64/httpd/modules/mod_proxy_ajp.so +10 580a85ee5a9d5b7df4809ab15f36fffa19d72ad0 ima fbb8d1a3c083402afb866b69d9b9763e90eee368 /usr/lib64/httpd/modules/mod_proxy_balancer.so +10 448c82515abeaeea0c0ccf1a4824fd6a44aaa836 ima 90642968cb8f2740bae7d7a82a57cca9e8e3651c /usr/lib64/httpd/modules/mod_proxy_connect.so +10 811a99b93f6a5ebdd10c3e4ebbc43eac19c3de20 ima 2412b234037bcb6d5a7cb0d89e976373b859eb1c /usr/lib64/httpd/modules/mod_proxy_express.so +10 231a91ee9e7a0d20a0d268fb0d738a15b1d92c47 ima d8327a77b259e2f86fa1a610a587cc740edf928f /usr/lib64/httpd/modules/mod_proxy_fcgi.so +10 a0a183330741b5a6f951eb6acdeb0d3307e3546c ima e9cbabccd732da44b19da0f262d38cea5f1ea432 /usr/lib64/httpd/modules/mod_proxy_fdpass.so +10 05ae4c2ea859e5c78438363cb2a312aaed47211b ima 31ae79bedb9b97365ea6c6c20785c0dac5a07742 /usr/lib64/httpd/modules/mod_proxy_ftp.so +10 5987d122f91b538bf1113af1c221d8c49a81e57e ima 9e6343a6ebd7f86641f9222830c4f88dff235def /usr/lib64/httpd/modules/mod_proxy_http.so +10 ef8772d7290441df692dd6375116353ca85adade ima fd6044ad3231e68e0560e27f446aa499619fb1c9 /OAT/NIARL_TPM_Module +10 003f841f020631f849d5946e0fc9eb9e907570e4 ima 911bd5185ffb83fc9e897f81eff515349cd42dfa /usr/lib64/httpd/modules/mod_proxy_scgi.so +10 679579396618d1433e01adf4e46a0992c4c83010 ima f3e51bbef403f6d3b28b76e99300539322e9d25d /usr/lib64/libtspi.so.1.2.0 +10 b00243839489ed8f25a200f63897a774791d92cc ima c1e439f233b3cba07af48ff38189bd6006b76bfd /usr/lib64/httpd/modules/mod_systemd.so +10 f52b1eded8aa33b861f79518854fd4b0b1de4f86 ima 474d5551c29e8bcd311223bafb06ce1f1ce06724 /usr/lib64/httpd/modules/mod_cgi.so +10 46c80931bfba3bbe6d16de34c4fed42654aa89d6 ima ce103a1b5fc83993bab3bd661a987ae88a82d232 /usr/lib64/httpd/modules/libphp5.so +10 29e43cf4e9f053cb63af1f2990963a181976eef5 ima 8517e4030281ea11c0aee6a97eda8a601ba6261a /usr/lib64/libbz2.so.1.0.6 +10 368c8ba5e5696c794465f62ddf64b183c38c9977 ima a4bf0432fa2226492f4f70604e7e271e33314d0d /usr/lib64/php/modules/curl.so +10 a750a35d5aa3201e67f1f6c373649770f8772f29 ima d014316546a5bb8cc50558b84369ae3eb349da55 /usr/lib64/libcurl.so.4.3.0 +10 b1376581eb0e7bcf2f941d22b756a1322dfc991f ima db241293d5bf2185388f8d52cabdcced3e199b14 /usr/lib64/libssh2.so.1.0.1 +10 d3aceab9723ef4b0367a9cd7a18e40a274551509 ima 4bf36699e07285e2e1e7f40ce61bfeadcc0a2979 /usr/lib64/php/modules/fileinfo.so +10 353d8ae0d1d21c27914efa829c8012d9cbc2ec7b ima 0b83d8e3da313082ddcb7684a0b336706069e888 /usr/lib64/php/modules/json.so +10 0db97bf7a65cf8e779473b0b16b6831704a05737 ima 986d5bba9d9ceb6d9b88882d7ade6dfedaa533c0 /usr/lib64/php/modules/mysql.so +10 7ba71be0b07fa899080dfbec654791f6b6476196 ima 2a063ef8e17b7984bcdd40f3b195e9177a1d8e83 /usr/lib64/php/modules/mysqli.so +10 e80d7534837ca5aeb78b0340dc5ca78b3e2f32b3 ima 78c74fa47a7e9596c2639099de6ad472a3d2c18a /usr/lib64/php/modules/pdo.so +10 094103e315f1d3171dd7b83365dfa4f206edb406 ima cdf6e4499ec475865b2dd945b1ac95e5ec8e7e2a /usr/lib64/php/modules/pdo_mysql.so +10 8337f1c7abcdaa6e10d5d92e0b0d80d319594c5c ima cedc21df47b28bbc4f5ade6e5d4008455f5f24ce /usr/lib64/php/modules/pdo_sqlite.so +10 af90f0b6b16b9ff1115ee5963ac76da1f0e9c79f ima 1896412881c22741697c57ce66189df9b09ba612 /usr/lib64/php/modules/phar.so +10 669e2b82bda02263e1cfdb72815b7d1fc150aa4b ima c6e17103d0c5e9bf71b518f9c879290c72455e73 /usr/lib64/php/modules/soap.so +10 89513d2821ef283d7d0f30e785ee38659af467fd ima 80c4901fee5d0fbc6ce3952bd04e8ba074433dc3 /usr/lib64/php/modules/sqlite3.so +10 460495d6b0d49eb036d2794fb78c577c0c7b2b45 ima cd1e4c880aeaf3a4eb2880d9a70f13bdb5291e67 /usr/lib64/php/modules/zip.so +10 9100054d465ff008ba1ce8803c5801d69bbf0c3c ima 56cbbf8199ac1c97c1a3a47c96a3bf31adc1eb6c /usr/lib64/libzip.so.2.1.0 +10 c64672945a8f378e280eb88dacefb24853e7043b ima 8dcb5bc30bda84359f077ad465ca2b193863f732 /usr/lib64/libnss_dns-2.17.so +10 0a93e81cb2b1c75a28446c84cfe276ae485f795a ima 19c5881591e9560616395d7e4548b9c2b2ec8d54 /usr/lib64/libnss_myhostname.so.2 +10 22884cf3724361fa37b76e03011bd507c25a9798 ima d30da11de2e446994678a2624348829ccc7be5de /usr/lib64/security/pam_sepermit.so +10 9cdaf283e71ed3276aedb1e0a4c721b7004b8947 ima 2755b887464c5b9acf693bfc5cb2bf94ca30b0a2 /usr/lib64/security/pam_env.so +10 8497fa5b29e0e53d366fdf9db039d4dac3ee2a3b ima 2036e5ee60169fd2a07636121b5961b1c65659d2 /usr/lib64/security/pam_unix.so +10 19a64abfbb0263cdf4b9c07d109996d3fc5c44bc ima 904454e975f99625385fedb29db10bb2cc5c64be /usr/lib64/security/pam_succeed_if.so +10 1bc75145f02263a4c3fc5aef3026dfe8269eb716 ima 9cedbcc612684c8a470a303bc29161c9e8dc7739 /usr/lib64/security/pam_deny.so +10 8db02c2261868353407e9b1c5af2676f7a516b10 ima c89a92aa93df449f0183165f43f918412c1247d7 /usr/lib64/security/pam_nologin.so +10 3f3e35ef287efa2a11b96b54848459727d8bbf39 ima 106036ed7a161cde3edb91c77abd09b63183681a /usr/lib64/security/pam_localuser.so +10 ca9e00fed56775802d54163ac30f81af8dac8b63 ima 4426f4ed570d196c20070ff4dafe017043d5dda7 /usr/lib64/security/pam_permit.so +10 06211cec194368abb949d95ebc6455d6687a303d ima cc33230fea497542e49a990a0b073994bde4b30d /usr/lib64/security/pam_pwquality.so +10 4ea7cbdc794fb7ae3e61c7da437849e98e785778 ima 9e72beeef8b2a9dcadbd4850c7ab7c27c0748414 /usr/lib64/libpwquality.so.1.0.2 +10 996b40465a50acbff02e53858384673940d49f1b ima 4c882f3b69a5017cfd809c0c6ffd3f84fe47bac8 /usr/lib64/libcrack.so.2.9.0 +10 33ff7de7a4920160c82f23598894af93a42148ed ima 765f497d990d39afef494c7eaaa2ffbd4c7c2240 /usr/lib64/security/pam_selinux.so +10 2d1d27552a2085c9749086e950c7d2e47de48117 ima 31897695ff182eb12e61ee48d699acc9365dafa1 /usr/lib64/security/pam_loginuid.so +10 6d7cf57d2d37d6485c7a7cb1cb09c9d7d06c1927 ima 2d054b560178cac86c6db5ddb52e9b2872c94132 /usr/lib64/security/pam_keyinit.so +10 f2500e8f9a0485fb5bc556140a357eb4b5fbb507 ima 375f5ba17b61acd9656d74c3c203532d4b618d3e /usr/lib64/security/pam_limits.so +10 4202530e695687fb522b83fdcf9edc44f76ea0d5 ima 0f408c4244f0c903ac46ae97f6edccc0ea2e1041 /usr/lib64/security/pam_systemd.so +10 9c724e6860464bece572437b7f0bc404df3b19d5 ima 3e5e69733ddc94d7a541dd91e59e0fb1b85b9d61 /usr/lib64/libpam_misc.so.0.82.0 +10 fb9022c85a1fe69d3a76caab72047a49cca100df ima 198ffc04e4feccb4b4e4ccfe14aa0bcd1eee2043 /usr/lib64/security/pam_lastlog.so +10 65f7e2bd5c2d67ca1aa5d2957cbd9a35e9bbbc42 ima c7b8ada78a4d438c5c0e18f0fb77c9d2dce9f4ec /usr/sbin/unix_chkpwd +10 a3c0aad8cb740e982654038b573c668912546a83 ima 253d086e3acec4755f4455df2aedb542c91cc064 /usr/bin/id +10 c2051e045e9bac4906d82f1cd05ab71200846789 ima 3eb29305293b830d4545975f2f368b90ef934670 /usr/libexec/grepconf.sh +10 82d935da31e8593eb1d07578181ee6ce4837a837 ima f2f05207552023af966ddab516ccb5e77ee2633c /usr/bin/tty +10 d4c8057e38c52b4715f3a7e8a34cf13a8d4b88f0 ima c5209b6992b5ca6a8b152dddd739b2fcf5e0dcdd /usr/bin/tput +10 7fe0a777850e32f8aa6aa83bbc6686130f403d39 ima 06c750799eec68122f0ef64e1a28f94e341098fb /usr/bin/dircolors diff --git a/db/measurements/ir.xml b/db/measurements/ir.xml new file mode 100644 index 0000000..1ad37b0 --- /dev/null +++ b/db/measurements/ir.xml @@ -0,0 +1 @@ +480YmHju1ObfHB44w3u2dNN27gC4BM=OAove/9seVUX99Rg+NrlX3/ynP8=1qFkbkbjN3IyE7GyixaSsnadPGs=7P2Qqh5D6EJa1l3ccV8uQSrKFTk=6Rx2itYyH6oTL6SScBNVGoiCKUE=LSzazzhN6IAJEF/k6zbdjICQ294=7P2Qqh5D6EJa1l3ccV8uQSrKFTk=7P2Qqh5D6EJa1l3ccV8uQSrKFTk=AAAAAAAAAAAAAAAAAAAAAAAAAAA=AAAAAAAAAAAAAAAAAAAAAAAAAAA=whZzLZdEhgdXCPchPnHZ/9lcXXc=AAAAAAAAAAAAAAAAAAAAAAAAAAA=AAAAAAAAAAAAAAAAAAAAAAAAAAA=AAAAAAAAAAAAAAAAAAAAAAAAAAA=AAAAAAAAAAAAAAAAAAAAAAAAAAA=AAAAAAAAAAAAAAAAAAAAAAAAAAA=AAAAAAAAAAAAAAAAAAAAAAAAAAA=//////////////////////////8=//////////////////////////8=//////////////////////////8=//////////////////////////8=//////////////////////////8=//////////////////////////8=AAAAAAAAAAAAAAAAAAAAAAAAAAA=HI+duLo0OtZnv6QUmyGhqSx7TUOkihDx1eM0Ky2wIAgXAYHxnarnWjYOW8KvXol8DbNo6N85r/5rVamGMRAvaD4xefGZ7rn8rlQR6Cx/oesIDXr8PtMJKUTcT3teQw6lsyCFCmqFmRf9zBxH8PMWPaFk4a/+UCelLKV90ZFDeMvTDbV9uQkNDGdsHA2norwbT5SO/czLba6Oni8S/ho22CDZfUSF7hdOIDm95HVm43kx96BFzv77AbPcDHB34PC7qeNyyAodk/N7+G/WB0fUykWSzbe6+uoX8KVFzMNcOvrk+0vrVc8dNNPAmx4BXhcH+7t0ngT0WyMb00mGfuCCHw==ned-torsec0DEMOjFQZiequvKruBU1WqL4z/bq4Lnw=cdDHb5aO1hljNyBI6c7LHpUeIyY=kGnKeOdFCihRc0MbPlLFwlKZ5HM=2b5lJKX1BH21hmgTrPMneJKnowo=YmHju1ObfHB44w3u2dNN27gC4BM=0DEMOmY2P2qzdlxDfq4r1zsCTBz1XgU0=jdDyqNXZhLqNEGDYcS+kxeJ79O8=kGnKeOdFCihRc0MbPlLFwlKZ5HM=2b5lJKX1BH21hmgTrPMneJKnowo=1qFkbkbjN3IyE7GyixaSsnadPGs=0DEMOjvumiZMxxLE+fok93CmUONlGyj0=kGnKeOdFCihRc0MbPlLFwlKZ5HM=2b5lJKX1BH21hmgTrPMneJKnowo=OAove/9seVUX99Rg+NrlX3/ynP8=0DEMOGyT39LuEAAMCIJ0SmNYvV3mpT0U=9WKDS5hqVZBKYcZOnOucZ5QGtUA=ILxPyNIkt3s4Rjb6Jv/bgiVGNlc=GIRmZJkEKITAQ5dR1WoOM6Ayr08=zQ/bRTGm7EG+J1O6BCY31uX38lY=kGnKeOdFCihRc0MbPlLFwlKZ5HM=2b5lJKX1BH21hmgTrPMneJKnowo=IRre+h09m4qimiw+9tpjWGRopj8=LSzazzhN6IAJEF/k6zbdjICQ294=0DEMOkGnKeOdFCihRc0MbPlLFwlKZ5HM=2b5lJKX1BH21hmgTrPMneJKnowo=7P2Qqh5D6EJa1l3ccV8uQSrKFTk=0DEMOkGnKeOdFCihRc0MbPlLFwlKZ5HM=lav61mRlAhtYJYxhceTA4XT6pks=2b5lJKX1BH21hmgTrPMneJKnowo=OPMKCpZ/zyv+4eOylx3lQBFQSMg=FJgiIW8q13a/PhYVjqx0ZkmkxAQ=6Rx2itYyH6oTL6SScBNVGoiCKUE=0DEMOkGnKeOdFCihRc0MbPlLFwlKZ5HM=2b5lJKX1BH21hmgTrPMneJKnowo=7P2Qqh5D6EJa1l3ccV8uQSrKFTk=0DEMOkGnKeOdFCihRc0MbPlLFwlKZ5HM=2b5lJKX1BH21hmgTrPMneJKnowo=7P2Qqh5D6EJa1l3ccV8uQSrKFTk=0DEMOGT1MtLZ5ZXb2u+5AGx81DTUAPW8=CbCVCaK0EuU3VMBNJXKkOui0bWw=lcbwiQFJUSQVHnBHhnEuJuW/28U=2y/HmB5CW9H4Fd4v0rlEdCmjMlY=bu6TMA/uSHKkyMDkfKLjXU0t0tQ=S9uGec8w1FqHPOE37qfc/rwAxvs=7qUaTDGPalgPTFw48iJ0Qmc+r1Q=5XaJE+pLT6kRMcQnk4khBz9zl8k=KAgSrXNmZDsjtGetRx2p/S9gHRg=g6xO8bZ/so/nMhceY/juVSCK1+s=vIBtlYvWyxWsT9ZPYJ7NtOMViSY=PtulPtIjV3che32/0tQKbkNPuCc=ukUqBNGZ2Y8KyC154nABL8++m48=2q8Zf2HReH5XGv9pTN6+BHfEmYo=FVAyRiFV1ON8NrGX+bzqZmMo6no=OG+y09uWUqdxcXgMfrfbpntytrk=p/RQQankeN3BgCBGA103LdngqB8=J+vb+Xe6MOcivfvK+zscsl9YVHw=9LbiRvsAyXDaD6QUQB074HFvy9s=72i4umYeQrFOUUL8a5Ug91Fre8o=c3HMAmxfIIKlItHIl9YzdA2Q6WM=6UA7HnWk4+eQ5AM8QB9kZAYGiA8=KDFNGsG+laD5SBChVjWG+aq3faE=Jr1BKqyC7UiMh8GPgjuVcZ0MFAc=lkoCQ0B+9MwhjGOxcphXdSmEktM=POpcM8T6s1xbBTZk0Xq8zqycSGI=G0rtycFsJNpvBjnwCUWy5pLMmo4=YmeP7GEDE/ef+6M4ZrOd2LgBT+E=wiaAcnGs4K1DAYNvvOC20W7okIM=RHIRXC2R8zIgNoqEn19KzSneOLE=0nwRo+mZHxGpK76i29goH/+5lZo=zwmNGmpD4ckdFAwt2qFTL1DWplQ=5hXpRbgUwDyMYzGGSOUke5DhxNo=fxrmj3uMvmyFYl4Nc8hzsWC+E8s=xCEpjXXvv1HhrOEbW4be76q/DiQ=zdz2FuT2laYWF0n8sa5QGQww9gU=Xqkp0Jbhfc7mVGEtxHSo+JQ0B0g=54ylMvQNUWnFRj/E9O800twyfoU=UZWdtV09iTKGn1cu9VmC8n4NKSk=5446/Ax3PUka+YirPO7MnJsePJU=AUD1DVjGvgjhQoILigzcKh+jGZE=+diMmYEJbHR5S3mHiPJ4ace6QSw=UvOJnvy3o1JE3Vj4PflKocGBgsQ=HkcgS4jPJHCPjWvxjsJB1+pdSlc=U15XW/ZQTFLCe/ohnglsviYX1mY=0d8PKmLqlM6O9mMuLm9wcy6V0Sc=JYQu0HdoP8ShFHVMYmVKvfze6io=7XAAmk0Ta4jwBe26BvtEWkzbpPk=K8socjmwdDUcDQTWfCODshwXjK8=x/tnYDiUCTZ26hNqK/UBJdGsXx0=Y5HjKth38xwObWH9yD+25Fbsr+k=I0eAWnPN5zG9AVSLkr3e3JUPqZ8=miHcS8D77eiqVUzkKDEg166bS0g=sNlNmm6Nu/oSiZQwigDA9QdWPzA=XARyS13fIisao6T89qf9BZLlfFE=wwzgkB3gQoTetdYYk/w+WmbLieE=QGbtdSPYykCezLbj97UDfnbSWvw=yb+vyaUt7rnpwuZkDnTyZ8rYTWk=Ky11fZ+dsOCMyPHiTiaZnOBfsGY=olJn1oG2x7U43AQEVketAJ1Kieg=Wpy33hQEofF8ogFRhS5YAP5drJ8=I1Z4Ffe1SfVfgOjWbk4J4uKy9/M=kHw+KWjUS5C9pE6EgbacpY1WOhA=mnNgtND/TkcwrIg5ccwcKFMRD2U=QMiAE6BE17FvBzg1o4G9R2Djn7w=ZULBVpVnP4IwnSIa63pvno4LJr4=YnSsNbcME2URQJyDtxdf6zDtI88=EVJRmsNDWRby6+yhOm+C4uIxKXs=zfutRao/3RopcIPD78sQgDDN0Gc=E0tKN02rRQ4+x3gqveo1yhmrUEc=YcnkMlu0HroDaGZiC0EAlWLKyws=LGLmkK2V9QSU0U/BYCtR4Qt1WU4=LPQN+O+yrFEH/gfc85VNdn0zWac=B5aVvYvPmKPRorUWDWWgvSPZfWA=qsBiYMYoiMGc6TEkWKs8JqLqvrI=5hCdq9C4rCkgAKQ++1E9Ff8cpH8=fZSwhn+ehGj66RWqtaPSEh7I1OI=0BBNK/GIMjjj4LAs/PidMWSHrT8=tQQeNfrVmfenAwm1oTXe+Uku8+8=nDVHf8cIvK6Spp5Bt51Oeqw77cQ=FIq8xAqn/VE0hhiKBeoPp5MQlxg=VcQLQax+sQgzR0o3ov08jl7SX6M=XgkMDVWfbg1y82/5IqPziV8xmbY=6ECM9m68KyC44pB4l/mjyQ/DypI=Xm/En7KTsXNOKGuiCPhmv7+RwPs=m5q8Lly5m0SwgF+d5NWj11CzlH4=uywU/GMBWIpt6ERr1SZZ6nHudCo=QE3H4RiHq3D963xuHpM5x/QAvq0=+mhoHN11HgoIEIFGBK1CNRPqccM=sIuveDLndz3xUqUdItX3lQtWL1g=kFYIMf2mbuBmNJnCOtlqWZIttac=NEzntTPPicMyepa29UYXgWt5Mlo=96Y3XsG9bj9ebI09wVtbwOsS80c=M9lUUuN/ipZLoygDuqDYoZIRk6I=J7ScRXaMZ6//DhqaQcJCNSxQh/c=GdW2nA5yT9xbzXdkLvIhx4c4UjY=1cLRrI9zgiiwXZ0R9+Ewa5PHt04=Bx7VZVn8n0unOZLPYMTPDsrKAFE=sGWgr7Dd7dAyF1O6rk7geRQaPhs=tYV0m44fBv2ACyU62dseqFv7kSA=6x4EpdjHbUPjueZj07L5No/KI60=RDgm3bW8rGCx7cJrJGtVNSvKxeo=WN2Jm0m9NzLHROwKx10cA1VfKcc=lRZBbyiknWN7HKVdoZVNIGzOaog=rfRpF7bMt/g3zX66Wh/0qHqpcOU=u4Em9oT/40Ej3sv72t8ZGZoQWz4=A1PF/JzAMRTRaQ+aWqxnDqXFi9c=Rl9wNCSDNEZUtDgEINBTOCW7MUQ=DHlGhdqKyiyqK78rUqS6RSAJVw8=Su5RW//Wc+xGis20UWX2oej4Cdo=76S2F2Y4kT5tdO6ktKG8A86IVXY=dIZbrajn+pp4nxC/molWDojU5z0=SEJ2hZFYGOAmgvqq2/KK2McLQzQ=TBFAW+8eGVIs2abYQLRsvByrcIA=MNSVCR5u1a68pfRLtVZCBmimY5Q=8AXooHoOwdO+KNbwpLkvHL8VEYQ=VcMxmCSlNPPMG3w3O8L8dS+6PxA=6BBn81eFhN6rZtba4dWL2jXeGl0=/7EsSYSE85EOoCJ5t5J7XmI5vzo=oGxLI8UMQjGpH/868cIj3+nOxfs=vZAZ5QMyNvE0qa+3ZkHpXkAy/Wo=PJXS8IG4r+Qbv72T8Jrv64rcgs4=xC0NuYoAeJVJldTL664P7jftgVw=tCypMLuikMWh9al9hTssXMXLAHk=gJ5nGZeqyEo1JiBE7x065w6F1Fs=DFDghXVheN0xzrz0yUtYaOAZ40E=yz6V200UPvwsXftSetxXXmwmlUo=65UDSwkXDOD94poFdYaaPxcnT7I=orqIwqh9wz6RcNmbgdLP4q2T5A8=4UF3wQ08RIujNAP3+nUdaNITUAs=slV04kSkGF5hzuX1WwCNFttaO9g=FusgB5wnpNVo3dVMJUvh4Z2T8R4=nr3w3u62x0nm/3h2vpJkiMZvKfI=EdC3jYsCHcauDJrvgr6xjPMOX9g=8xKXMoPfWLZ+rzszEsTN4xxE6Lw=OlNHzlXwTdInTus+P5+jdF3nYkY=qnJq6c+PvOfQVTDjLzO1tCcrKZc=LM2UfE2tS/gXPt6f5Wc6KmQ6mlU=VeUOOqTXqcxdBbTLulizpiDv5RI=3+RCl5bzoxt5PnIeVvGMxHAiz8I=9z4i+CCVGljsezpmNhS1VoksHgw=J6b6MNZVPusELqM5a01uzoztEIE=xcpzkqaUkjlH400a+TsBmCHnbFs=3rmjpCzGAMM9TqDvQx/LfTmgc7Q=7sct7O1gYKkmhKANJhUsr99aNDY=a4b1bYZOgO8J94MlFVgC1My3MT4=tc1pgWrE/wsLBcBGhDageOU+hFA=QF4OqIxbjzMeGyUBEZ1SOU9TSVg=9x/9N60z3oXF72WcHzmEIQcnsfs=CJHGgnfn8dazbPmjs4Pc/37K2D8=zu331ofKGl7YLiGvNbyPo/cTPq8=GBGwWN4WkcOeIGUtWQ5Qa5MWVko=nIVN6AQObJF+Qfb6vnO6J51xHhg=7QhpsjeyAqKu5jyg3bDEkOsdQQg=BpVNRhOLBdCfcNCOpThs+iccnNo=HufXc5RUB8YU+AQGZxhmBIy13T4=JRmCh5S1rw8ynnvPk0nJT5uWuUo=th0MDzvLTmNuk4r+c87Sfmhx6SA=HwJ+jZsdHopXsDVdVB04lOaT5Y4=Kd6RaGBAQqrbGEbkmq1ROxNpm88=8KQdrOteD6/+kKCoQZVRoLXPDhA=Ess+V8fyknPqw+ZL6qRm7W1exTo=H2avyTxVuxdeqtlJHYdUHQzETZk=P2ce7jL3S9pCIbKVJ8cIs291mcY=+5CZJD6dPyCHgXlolcV62LKtzSk=zJtqA7PEA4KPUEETbZK0yM0BwCg=ZXXbIOMTK7VutQ9vSvrgMh/FMJ8=ubH1jJL6bDLZTqLoa08ypbl41HY=hW5gXq8mEdVgfZ5+p3CkOhA6Uew=F8PwRREnXt6/M9ACb2vphPdkrKg=cIVVwLXzHDkt2766/jUwW2BFGi0=n3Is7+tWOQmVIXu+KzJzbMgdB/w=kgtWmBdKCHlNHd0orvB+28UVsNA=nF3S9XjrJKZqgWJhbIW2fLGBN4Q=7BHN+9t8wc2SCu09L3W5xYZLUtQ=A0acbWM5B0Pr5PeXaK4FyhaC9Lk=dx2iLpoK4K10q5mzwlc8wmSk9jM=iYjVap0Yy/rG72da2g0VZCKw51o=OCTClcHP9a2GjF0iuKGqdweZE4M=BPut9P+b6g5DKxlYb6NrM1NBu4I=yddOWLfpdF3GF0JcWVONu3GC/xk=y4L2SyB+H93GG6lyMwMsHMP5oNA=b5wCP3Z0btOB+jP2T7bvHSs1M8o=mIvVlQcD2jm39eli1XP8MmgryBM=ShaASNYu+goMIynOrRPQDwb07VI=MFKGaB/o1BjDTvtLCNFQNXPXQ50=3j0hc91vXF0N40tJz68Vim6NYNk=sMKBTSL5tQq37VW8Psn+f6+7WFU=alWABzuAbaAzrV8DHM0LNWooyQ0=QK1zh6yu5/+xbRBniMvIJpj0T3U=yV/f+lD318gqpBq4f+zahZiJtVA=iOzneLT5yPmn8NkC2pojHXbkVTA=vWMmCMXNKH0K38qDintfYQQ+irc=NGDWiXKRv84Ibi8uO9JtBphX8ME=aFQoj/26TuEKUzmYPBSLCTs5EbI=cNmfWKqmFr5tdL9tIyEhSomx5xQ=PDn6zm2jvN4YSQS+fzIhhfqgbhA=0YvlzmQV/72CLOlVByUZPpEWEw8=h18L6jyzDG7UfmoETG289lDJ+Rw=HVJjF+IsY0m/rrAJ7re+IUqz/T0=5cBxLjuIKnUk0ByGace9QqrMEJo=VvDT7CYNYssdzJ/9QEYs6u1Nwoc=i7OiyAAcGYyO0eB6jwp7qvEY7eo=QabYwhiHCAIv0S0czBG2PGdT6ks=uvimik6PGaJdXXBr/i7My4iwE+0=DjN6sQkfG8P7wmFQkbYvi9v4PwE=juESFJOFqOzVOkf0zGtMzKjLd04=f6azn7Ph7QAK1h3w7Ed1th7cjl0=OYYlozZxzFJh1OzVDKneSfkIvIU=ncI69qRj8pcYwQUsyZ8p7dYF84k=TpzEpzuV9/3gV9QHRJl9j85qAwY=1kWau45TfomyrgwrIMqYvyjkfvE=elcBUHdqlk0uvM2b1oKykmZgxCM=W/YUW8gSb3mqh9UuVdQZUf8Ja1U=L/G0D2WzWnF0p4Nyt4UvpGT5uEI=1dTvFJiE+ceIHbgEWELlYmzkkEw=U/oY5FD9NLtq5Qorjg5DMcG3QZI=B7aBndRMK941lsCtqvv+auAIRA4=3u8qtLXyvk08ahUcpAUFHDnldHo=8okijOLZV7hBxfHnUrJV8un6ibk=yuBQg11HuTym42khBxtMKZaUCSE=RA5FH6tGB0OBFembT/SWPCCF27g=gOMSx0oixJethjuCrv2sqw9s12o=/03NSkChj+zWHpyE8HprjoNyQ8E=53/PbVRuSP+X39Gmv5t33VwIdjU=cXG+mnkL4b3Mkyfs9CYOeno4H+U=GaiLV6UeEy8//1gj/8lI5CDsYLo=SLmUS/rp9CwPj6/6zUoq196R6KI=BZubjkyti1facJqpBovk7jlBvjE=gOAQR3dg2Ml/Nr44a1QOA8jarNM=y7UtOU6ZuSI0u1M1yBvUI/VDYKw=UafD4tPO7H+MRsdUqNaGCw9FTDc=RUM56clHrWZUwZJkZ+IntW7UsIs=NhBFRRiRppUNutCWy7+lF9Ph+eg=xQ97pJ0QzQ3ra2SVOGXKn5+Yh1U=5HksZylWbPNzEZLw+4laMWYw/+s=aBWsk152R3OOYCP1RvZQz33uUIc=fsv0n19xeaaDuFG78ZFu9+s0/Oc=AmszyeEto8lg54Sj/fx8BTM0Hyo=wMal6kF6JPu1to0hC11rYD8FqtY=8anrUNmSeT9j9kAdCithvoG2/HM=p1CjXVqjIB5n8fbDc2SXcPh3Lyk=4CRzcvY4Y/PciduN/fKTj179U3U=VGvZvAEzr22ZQsTHX1RMZyNsHuc=UKqfKik4wGUiyIpYwdC9yhRaXdI=sTdlgesOe88vlB0it1ahMi38mR8=VhR8JeLqVr44KOWSvmJ9y/x1P4E=mJA1ld+iaAU3HSgnwBgplQt5kj4=GtC5kKHgc4voXahn1a9434ldq00=6kVOHzSCVm2eYbPVwubquYwJRt0=zo78Msk5nHwJKtmOE0F+1k+d+G0=RV0guPGFRwsMloqJH/EeJrZ15wk=FP5iDIFHA7BhC8HD1ThKw14f2nU=sdObUp2FcdmaRjh+SuH2EL8qa6w=KMXaxfwZMBti3TyKNpOh3LCkDlY=QqmbhE3Z0RROKZan8zT6B0TEuMA=P7HFFd7e+6FAMUwxSkHZqyqlxo8=WmBJvRCfos6Fo9npooeq/ueo7sA=z4C2pAuEae/rw4KO+froxZOh+AA=/L4OpX/gkhMfORMxdaEaWMfqnq4=TNDCwKA1KZEDntSFlxUh8xx5L2I=lnFPLngFGn2fma6VuVX51XKhzTQ=6jF1Qx9B+YMma3MqNMXc30DPj3k=XS+oW9ktF/ibVEUvnODTzk93P1E=DEs0YqYIjbcsjLR6N1mepDTIwoo=r0RCcbzdKrLughL8Vb4xarIn/fQ=H8gSvLZCb/mMAi1MOK2iM6IyzBk=ReyVxYY6JapLlTqwSAh3DvdAXjY=v9R+S4hrai7jvviF/wcbaNnq1yA=Mwohcz1j1FFJBy3L3ln9Sk950/M=vcE2KMFLZB7nQwqXaJyIQKspVXU=lONyzAgy8n/C4pUTqaLGFmnG8nQ=UPy8HCwaGv9ToqQV4MwEqJ4PnUc=GnCq28m2QFQSp/VxbuVYXPXW6kk=1tsl21ergBFXhd4YTgM0PSwoq8Q=0pNfmBgukwVLXXzFVR8Xmh84tJc=BjbghSWhxTBkFNWkEGB+T3rpyIg=2PjGKbytr3zBFoFePR6KbMr8L9Q=0ZbUh6KRHl5XI6CrgoY3ix9mStI=6BeREX8H8YhTlsUHrmAkEi5XDYQ=xvxYZVrFDeVwCIGnIepGaV0GOd4=DhgjpnSpcjCUsDz1erfz18/hrOM=O3J/d3fTlVcViUMOLCB7JrSf5R0=denIf5HSWnYnJL8yYble/QUiM34=V4Aaf0xCvmjPFhpnegA1kSSRrwo=28dPip3PkX2lNJMvSeGEe0BvDJI=0jPM8wF5pBP2SunDFvqr1gr/GlY=A6P2Av74hktSHnNeTvfYWmvYvDk=MH3Wth+XoLaElcYJG+ODtRZB11Y=e8SaHwB6I/GGqC2uo2mb/B5vljw=giv/GTm7YkriHBQC6SxPsfbYV3s=F6eOBal4zG4x8DAc/MwPZNEUFLw=3DHXtRw38DatOuhZXPSG3laAjnQ=Bfg7kqPhu+78a8Ugz+hMLJb9m8M=LHnZ2jrdPPgPjBnQ7ZlxZcDc9do=B28O4hu/fgDflmCDgQz8nZJPoNw=iWfUtpf9k49vIOPyPpOMMr+2w2s=8vHPLzUctFyx75wQSuWoZGwqf9I=IXgxtC43p6U8sdUjhZiM42SUcBc=9ByA8Coj7k/aI2Ag35NRqGBkBrI=9MQ13fmuip8FPJFVxPOlWtaAdXM=2Cdsj/1wqg9kEfqW1UE9zHJPBzs=WGKZKlF4LibUzjC27zBdlr018Js=iRagvu/FZESBxwpQvE9cGGFU+0U=z+fwa50k0YSKd1NAyoX2PDaUYiU=UrRjUAFmjsMTU8Ysz/eTl2srZqM=6gibYSvfBrKPvmBN0xzV9hmPpi8=tnSM0ESJ4+p16Q5ENNI1N5oxnHg=oUzmpU7jfCSohutUyhieKvNkCuw=pG57iB66WiI5Q6ovgv6trvTHRy0=0haK5Xq4wm94dOeXlLOqDv6QKaI=/LYv2/vvM4gNEA8ANB8h3hIQSdM=SFAF+fyikHrwrdw54qyH7boDvbw=fN3B6cSfUl1scZjbJEUBXKMn+Aw=vrbyOLgYZPRsMpd0wyXB1+6dY3M=AVsbC9u6VFg9poK/TxmRyghtp9w=PfkDGrQDJ5CSmOGU3gRKR+3RF+c=Li03k8zMnt4ffmVPoPkWSBIDTIs=3A3/zU/2b4lElF/Qc5WH/C+C8DU=K8TqmK9yXkr2g1McNaMkaxG65Y4=LuYxnrkl4Hrxm5Qe41ZszlZo5qE=jP1i+T15Vx8vE8kkn4EcS1wEp48=IkzUAicQ2h82lR4As9zX6FSLA80=6F+ViDvpP88XJkfp7LazUkUoXYc=wGolEWlN/VUn35Aash2qAvKtvis=ZK8O9tROf8nTH3vjeHzn3WkE0qw=Swhh/2Y4NK039AKy2QvwD3txVKs=3KnoCvzcwSZbYoNp1BZKHqYIfy0=855SneEUOCsijjPpHUQTz3OqDYw=lKeOVDvkdqX+PWb45Rcb7oBMP/s=sGYUZT/+dQM6RiZ+tRZNVZKygEk=9w81hImBGpa8+yJDxOVuj+J45zU=6rwfHT/z1eSDhMTJ1/99mAmywac=kMcNC3qqcTqQhd2skFKF6exFAr8=XdC+RgZg4wYySZOgUs72fi0IJJ0=oLuoPjo0sHLberUQ6/mG7s0aZ4g=fCCPGQnlk0RlQxFX16otPOXKFOY=JTYoUqZHi6s7rg1jvsdcdxyvAo4=n1ayYxADFHm+viYgCy/WWzub07k=v1GfcoFqel1+1m6PTvdGgDP05oM=4epxdCvHCVaesIZftBsa9XIoXcc=GaNtyGFPIUYsZ5Me+6hRm0VRI4A=6QjgKrKxX/cAWgCXHNnIZO5WnG4=yuVr6HGASM/NZectIutD/d6riB4=Y3ENTUVLmzwuiyJQVihEEz+Iivo=g3Y2/loDEZfk/pqqRgLod7ZTTjs=EaeLPcvkVpqsEOClNv8HeCQ2YGg=WA7dKWPubHDYS+pzMPPSRrB26AQ=auo/rOMAOX0eE6dSjhw3nolunGQ=f2+5WwWzmGhVcAMsrU0BRCJ29Bg=SC6S0IdyIsCxd9/tc3rg4SnanKk=X0dsEFYtIdSDD3v6YKzOU0BCHk0=THRy48KtJt1ZyNge+dJaUmr1wiY=k5u1pEnnZVZUvKmEQFvdxw6Dz3o=I+MKz2FuLJeYAe3DNk3RleIi3v0=0SfnBPG9bYjqfCXGrlM1WR7hNH0=41O7NIe6cmf2Bx8lcuchATiNsXw=4E0qIWs8F+fMNzs2Vkg4yUKCNbg=zL3i4AJoje660wCkKLdfbL+QD6c=uMVUZfrx91OXXm0Uf0EGLIpRc8Q=CfLVIo0sxG6ZBQv+HnSRe297vIw=4Z/7B3DYWRVLX2XaPkOjJZfihxw=pqov/ou7cGh8aUiWqtFiJjVGopo=fufQymvpumG7PQ4lOEBICbeMvB0=VNHNbKabhVJrRBuaXX7fEpySwQw=Ly4MpigrtzgNi5Njh3ezkDyBsF4=Sq64tpFWJ2z3mLOMHIYx5UgTfYU=nEEuJNCcbf6g9asRACCtYZKfbvc=vHG0qhVm0u7rht/yjDm9h/Aluw0=5FGCvXkz68+5hMeFA5ZCpiX3jf8=6qZQi+dLsqcRUwIO0Uvnnv8pEZw=xfoakVB7Z9QLE14O7zS+ja8vTXo=8A/yWVrklyPbesCEE7mDGSf+Y0I=Rt2wbuOWzTDlT6RXl7+Xzi80YpA=ZlbyEw6Jn/FbqpPLgW7U1W3/oiE=HBxeRwUMa+1y4ReKAGd0Y3lW12g=tfz28mo1gZJuY3Tz0dKZE+1N4mc=lVVxy9ib2ci/Tt46QgTIGjThD/E=xkZylFqPN44oDriNrO+ySFPnBDs=Z5V5OWYY0UM+Aa305GoJksTIMBA=5EBGsNujojpDMQbzQLl0Ura4lYY=CpPoHLKxx1ooRGyEz+J2rkhfeVo=EnMnwiLSEMNCvaMTo5ChB4GStOU=G3JDwXOiD7DbaoS47e7S6HsV+9U=IohM83JDYfo3t24DARvVB8Jal5g=MICNZAOSselu+L0onnX2gqQXHQ0=8VWjN1ECjpEPohCIWmC4cqNeTSQ=bi35FWlxkFGEc0wxBvCxDixDoK8=nNryg+ce0ydq7bHgpMchtwBLiUc=/EZTlLz11qJyeRkSxUXGYm3PvuE=qGURueuwF+Oo2hEOYBn4JGNwIic=TaUywsM/kBLqiFW/07rWUKLcHdM=mTP8vPGxnVGGmI7GMUZ1cDNuEzc=hJf6Wyng5T02b9+dsDnU2sPuKjs=N2GSuVQViqxt4aZeUkduIZT9a4A=GaZKv7sCY830ucB9EJmW0/xcRLw=Ua5r4/wVvdn5oyilF9HMWvODW7c=G8dRRfAiY6TD/FrvMCbf6CaetxY=aMlvGAq8b2N3Q6I7sZKYB513Yb4=jbAsImGGg1NAfpscWvJnb3pRaxA=ImnDNjkEI34Vi98rReQuj4TKCGI=Pz417yh++ioRuWtUhIRZcn2Lvzk=Ss4LpRh427u/+rcdxosXUra0zHQ=yp4A/tVndYAtVBY6ww+Br42si2M=l1dJAirHC0gcJUe713p32Hrr9io=BiEc7BlDaKu5SdlevGRV1mh6MD0=mnhFdGbkOoJNSuxC8EqjUYt9chU=TqfL3HlPt64+YcfaQ3hJ6Y54V3g=icJCjmWLqVqjb0NOs9t4pbl/Et0=mWtARlpQrL/wLlOFg4RnOUDUnxs=6rneTzvu8uyEhXWlcJyzy95SZ7I=M/9956SSAWDILyNZiJSvk6QhSO0=ZbtMdBV/MHw7d7a7ztrJqvGUUcE=LR0nVSoghcl0kIbpUMfS5H3kgRc=R0Kya5YktIeTbfqjaiYoOJ7hfW0=bXz1fS031khcenyxywnJ19BsGSc=55kju8JVJCCBxS2TgfzigA+dS3w=8lAOj5oEhftbxVYUCjV+tLX7tQc=VgxTri6zatOGbWLeFvU3cgMPSkU=QgJTDmlWh/tSK4P9z57cRPduoNU=/wzRmoDZyKXaZeOmEzlDojxBeUw=nHJOaGBGS+zlckN7fwvEBN87GdU=ySze0wS72wqOCZRVq04GltL4eZQ=+5AiyFof5p06dsqrcgR6ScyhAN8=ZjiDWYGthFWm8pWsqlvb7DMW8qI=kaIf4eNFAaE6/OKW7nPPaUIN4nA=Hf0X0rB3N7G0tjRdyOPLOxe5lPs=ZffivVwtZ8oapdKVfL2aNem7vEI=EBQl1NBqxRAHlzvMfXCi/suDLOg=uKDub+LsWq/m7hZkLv/RIoi8dKY=4p8Aa01adhT+mwnqt93I0EzKe9c=u8fijU9IylhVPKXGDaf4pZSqpm8=PO2i8aF0FyAykcG72PSThAHyX3Y=o8Cq2Mt0DpgmVAOLVzxmiRJUaoM=W3Sj9XuS1wk+pcUWteJnaJJ7lDk=wgUeBF6brEkG2C8c0Fq3EgCEZ4k=gtk12jHoWT6x0HV4GB7mzkg3qDc=ZFS/9uno/MVIbXE107MyvVDK3VU=1MgFfjjFK0cV86foo0zxOo1LiPA=f+Cnd4UOMviqaqg7vGaGEw9APTk=pJ1CN+V53ZKyaeMTxTUZgJcW48A=2/RWRbPMoDGNiYngrJZR7vcJ8Yc=6kUSXfwyrJGLGGfB34YyDT6PF38=VYTfakkwjTFumpXt6kWeDlacJY4=WMGidjrD+fcbKTEnCdCBeJeb0n4=nP8nvXmAWnpK13HJxObY8CWMNGY=fc/OKzMVwdkDFqSnwr9vjzPI0/Q=7/H5HWrLZOJSHANS5AUexyWCW1U=D8huHWSwMQW1KeImX3bfAcFRIbQ=5gqSAE8HK1xjWqW5FQoDMGgW9So=dNGSJcJ3dXbA1rme+u8+oymeAp4=nlTM/1RECUo81ZcX7GvD5uWbQ8s=dLQxNvYgD4BGPwfHGEc8O0ShCyk=kQnknk5xxaDLKHGTryz3PHoOeHk=2HhB96BgYSlCO6McreYdC9Q2qEA=E/5EOc8Wzv6Yr9/ZA80u9A2kmYw=7siI9yFVjixk6LQZ0/hxph29fYk=9QHxVwAM8fGPBA2FAL6DlB7mmSU=Fit1E/EMPiAcAmBs+C2b5ABco80=ybVmSBbw0jxPGmAM9UkathsfJek=pa3PyjznymUTHijUJOkSaiyWLNI=qHZrSyo2p4+RNjEFArnA6x00mh4=r12/ku1vHLUE5uZjY3KWQJp2tow=MH8n+1zkcusaVIjrY5487wFe7Ro=whZzLZdEhgdXCPchPnHZ/9lcXXc= \ No newline at end of file diff --git a/db/scripts/client_insert_pkg_bodhi.py b/db/scripts/client_insert_pkg_bodhi.py new file mode 100644 index 0000000..875c510 --- /dev/null +++ b/db/scripts/client_insert_pkg_bodhi.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# client_insert_pkg_bodhi.py: obtain and insert Fedora packages update type +# +# Copyright (C) 2014 Politecnico di Torino, Italy +# TORSEC group -- http://security.polito.it +# +# Author: Roberto Sassu +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# . + +import pycassa + +import time +import pprint +import sys +import os +import getopt +import string +from datetime import datetime, timedelta +from subprocess import * +from fedora.client import AuthError, ServerError +from fedora.client.bodhi import BodhiClient +from utils import * + +MAX_QUERY_LIMIT = 200 + +def main(argv): + keyspace = "BodhiDB" + logfile = "/srv/ra/db/logs/bodhi_err.log" + BODHI_URL = 'https://admin.fedoraproject.org/updates/' + CASSANDRA_URL = 'localhost:9160' + saved_end_date='' + saved_start_date='' + release_packages = False + total_records = 0; + distribution = 'F14' + packages_dir = None + packages_list = None + + try: + opts, args = getopt.getopt(argv, "hK:l:b:c:rd:p:q:", ["help", "keyspace=", "log-file=", "bodhi-url=", + "cassandra-url=", "release-packages=", "distribution=", "packages-dir=", "packages-list="]) + except getopt.GetoptError: + usage() + sys.exit(2) + + for opt, arg in opts: + if opt in ("-h", "--help"): + usage() + sys.exit() + elif opt in ("-K", "--keyspace"): + keyspace = arg + elif opt in ("-l", "--log-file"): + logfile = arg + elif opt in ("-b", "--bodhi-url"): + BODHI_URL = arg + elif opt in ("-c", "--cassandra-url"): + CASSANDRA_URL = arg + elif opt in ("-r", "--release-packages"): + release_packages = True + elif opt in ("-d", "--distribution"): + distribution = arg + elif opt in ("-p", "--packages-dir"): + packages_dir = arg + elif opt in ("-q", "--packages-list"): + packages_list = arg + + distroupdate = 'update-' + distribution + + try: + flog = open(logfile, 'ac'); + except: + print "Error opening %s for writing" %(logfile) + sys.exit(2) + + try: + client = pycassa.ConnectionPool(keyspace, [CASSANDRA_URL], pool_timeout = -1, max_retries = -1) + clientb = pycassa.ConnectionPool("PackagesDB", [CASSANDRA_URL], pool_timeout = -1, max_retries = -1) + except pycassa.TException, tx: + message = "[%s]: error -dbserverconnfailed- %s\n" %(datetime.datetime.now(), CASSANDRA_URL) + flog.write(message) + flog.close() + sys.exit(2) + + try: + bodhi = BodhiClient(BODHI_URL, username='', debug='') + bodhi.timeout = 500 + except ServerError, e: + message = "[%s]: error -bodhiserverconnfailed- %s\n" %(datetime.datetime.now(), BODHI_URL) + flog.write(message) + flog.close() + sys.exit(2) + + column_path_packagesh = pycassa.ColumnFamily(clientb, 'PackagesHistory'); + epoch_dict = get_epoch_dict(packages_dir, packages_list) + date_pushed_interval = get_date_pushed_interval(packages_dir, packages_list) + saved_end_date = date_pushed_interval[0] + count = len(epoch_dict.keys()) + + while count > 0: + print "Querying bodhi - distribution: %s, end_date: %s, remaining pkgs: %d" %(distribution, saved_end_date, count) + + data = bodhi.query(release=distribution, + status='stable', type_='', bugs='', + request='', mine='', limit=MAX_QUERY_LIMIT, end_date=str(saved_end_date)) + + if data['num_items'] == 0: + break + + for update in data['updates']: + for build in update['builds']: + if build['nvr'] not in epoch_dict: + continue + + count -= 1 + epoch_prefix = '' + if len(epoch_dict[build['nvr']]) > 0: + epoch_prefix = epoch_dict[build['nvr']] + ':' + epoch_dict[build['nvr']] = None + + pkg_name = '-'.join(build['nvr'].split('-')[:-2]) + pkg_version = epoch_prefix + '-'.join(build['nvr'].split('-')[-2:]) + + try: + column_path_packagesh.insert(pkg_name + '-' + distribution.replace('F', 'Fedora'), + {pkg_version: {'name': pkg_name + '-' + pkg_version}}) + column_path_packagesh.insert(pkg_name + '-' + distribution.replace('F', 'Fedora'), + {pkg_version: {'updatetype': update['type']}}) + except pycassa.NotFoundException, TException: + message = "[%s]: error -dbinserterror- %s\n" %(datetime.now(), build['nvr']) + flog.write(message) + flog.close() + sys.exit(2) + + saved_end_date = data['updates'][-1]['date_pushed'] + if date_is_older(saved_end_date, date_pushed_interval[1]): + break + + if count > 0: + for pkg in epoch_dict: + if epoch_dict[pkg] is not None: + message = "[%s]: error -pkghistorynotfound- %s\n" %(datetime.now(), pkg) + flog.write(message) + flog.close() + + sys.exit(2) + + flog.close() + +if __name__ == '__main__': + main(sys.argv[1:]) diff --git a/db/scripts/client_insert_pkg_bodhi_DEB.py b/db/scripts/client_insert_pkg_bodhi_DEB.py new file mode 100644 index 0000000..765fd7f --- /dev/null +++ b/db/scripts/client_insert_pkg_bodhi_DEB.py @@ -0,0 +1,322 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# client_insert_pkg_bodhi_DEB.py: obtain and insert Ubuntu packages update type +# +# Copyright (C) 2013 Politecnico di Torino, Italy +# TORSEC group -- http://security.polito.it +# +# Author: Giuseppe Baglio +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# . + +import getopt +import pycassa +import datetime +import sys +import os +from subprocess import * +import tempfile +import shutil +from shutil import copyfile +from collections import defaultdict +from time import sleep +import time +import itertools +import math +from time import gmtime, strftime +import pdb + +dist_filter = ['empty'] +tmpdirstr = 'dist_extr_' +row_priority = 'Priority' +#row_arch = 'Architecture' +row_source = 'Source' +row_version = 'Version' +row_filename = 'Filename' + +def get_all_files(folder): + p = Popen(['find ' + folder + ' -type f -name "*.bz2"'], shell = True, stdout = PIPE, stderr = PIPE) +# p2 = Popen(['grep -v temp'],shell=True,stdin=p.stdout,stdout=PIPE,stderr=PIPE) +# stdout,stderr = p2.communicate() + stdout, stderr = p.communicate() + + if len(stderr) > 0: + return stderr + + if 'empty' in dist_filter: + return stdout.split('\n') + + result = [] + for filepath in stdout.split('\n'): + add2result = False + for uptype in dist_filter: + key = uptype + "/" + if filepath.find(key) != -1: + add2result = True + break + if add2result == True: + result.append(filepath) + + return result + +def extractDistFile(fpath): + p = Popen(['bunzip2 ' + fpath], shell = True, stdout = PIPE, stderr = PIPE) + stdout, stderr = p.communicate() + + if len(stderr) > 0: + return [stderr] + return + +def get_elements(fd, package): + dict_rows = {} + line = '' + + # priority line + while not line.startswith(row_priority): + line = fd.readline() + dict_rows[row_priority] = line.replace('\n', '').split(':')[-1].strip() + + # source name or version + keep_reading = True + while keep_reading == True: + line = fd.readline() + if line.startswith(row_source): + keep_reading = False + + if line.startswith(row_version): + keep_reading = False + + # it means the package have a source + if line.startswith(row_source): + #workaround for packages which have a different version compared to their source package + if line.find('(') != -1: + line = line.replace('\n', '').split(':', 1)[-1].split('(') + source_version = line[-1].replace(')', '').strip() + dict_rows[row_version] = source_version + line = line[-2] + dict_rows[row_source] = line.replace('\n', '').split(':')[-1].strip() + + # the row_version is already inserted when package and source have different version + if not row_version in dict_rows: + while not line.startswith(row_version): + line = fd.readline() + dict_rows[row_version] = line.replace('\n', '').split(':', 1)[-1].strip() + + # it happens when a package has no source + if not row_source in dict_rows: + dict_rows[row_source] = package + + while not line.startswith(row_filename): + line = fd.readline() + dict_rows[row_filename] = line.replace('\n', '').split(':')[-1].strip() + + # set line to the last row + while not line == '\n': + line = fd.readline() + + return dict_rows + +def log(flog, message, mustExit): + flog.write(message) + flog.close() + if mustExit == True: + sys.exit(2) + +def usage(): + print "usage():" + print "\t-d, --directory : directory containing the Packages.bz2 files" + print "\t-l, --log-file" + print "\t-K, --keyspace" + print "\t-H, --host" + print "\t-f, --filter filter1|filter2|..." + print "\t-b, --backupdir" + +def main(argv): + backup_folder = '/srv/ra/dist/backup' + folder_dist = '' + logfile = '/srv/ra/db/logs/distinsert_err.log' + keyspace = "PackagesDB" + cassandra_url = 'localhost:9160' + verbose = True + checkDB = False + + # parse command line + try: + opts, args = getopt.getopt(argv, "d:l:H:k:f:b:", ["directory=", "log-file=", "host=", "keyspace=", "filter=", "backupdir="]) + except getopt.GetoptError, ex: + print ex + usage() + sys.exit(2) + + for opt, arg in opts: + if opt in ("-h", "--help"): + usage() + sys.exit() + elif opt in ("-d", "--directory"): + folder_dist = arg + elif opt in ("-l", "--log-file"): + logfile = arg + elif opt in ("-H", "--host"): + cassandra_url = arg + elif opt in ("-K", "--keyspace"): + keyspace = arg + elif opt in ("-f", "--filter"): + filter_args = arg.split('|') + global dist_filter + dist_filter = [] + for el in filter_args: + dist_filter.append(el) + elif opt in ("-b", "--backupdir"): + backup_folder = arg + if backup_folder.endswith('/'): + backup_folder = backup_folder[:-1] + + try: + flog = open(logfile, 'ac'); + except: + print "Error opening %s for writing" % (logfile) + sys.exit(2) + + all_files = get_all_files(folder_dist) + if not isinstance(all_files, list): + print all_files + return + n_tot = len (all_files) + n_current = 1 + n_count = 0 + pkgstat = {'newpackage':0, 'updates':0, 'security':0} + for distfile_path in all_files: + if n_current == n_tot: + pass + +# n_missing_pkg = 0 + print '\nAnalyzing %d of %d files: "%s"' % (n_current, n_tot, distfile_path) + if distfile_path == '': + continue + if distfile_path.find('.temp') != -1: + print "Temporary file: skipping..." + continue + + tmpdir = tempfile.mkdtemp(prefix = tmpdirstr) + mydir = os.getcwd() + os.chdir(tmpdir) + + # copy file and extract + copy_filename = 'Packages.bz2' + try: + copyfile(distfile_path, copy_filename) + except Exception, ex: + message = "[%s]: error -filecopyerror- %s\n" % (datetime.datetime.now(), ex) + flog.write(message) + continue + + extr_out = extractDistFile(copy_filename) + if isinstance(extr_out, list): + message = "[%s]: error -packagesfilextraction- %s\n" % (datetime.datetime.now(), extr_out) + flog.write(message) + continue + + filelist = os.listdir(".") + if not 'Packages' in filelist: + message = "[%s]: error -packagesfilextraction- content%s\n" % (datetime.datetime.now(),) + flog.write(message) + flog.close() + sys.exit(2) + + try: + fd = open('Packages', 'r') + except: + message = "[%s]: error -openpkgfilerror- %s\n" % (datetime.datetime.now(), tmpdir) + flog.write(message) + flog.close() + sys.exit(2) + + try: + client = pycassa.ConnectionPool(keyspace, [cassandra_url], pool_timeout = -1, max_retries = -1) + except: + message = "[%s]: error -dbserverconnfailed- %s\n" % (datetime.datetime.now(), cassandra_url) + flog.write(message) + fd.close() + flog.close() + sys.exit(2) + + column_path_packagesh = pycassa.ColumnFamily(client, 'PackagesHistoryDEB') + # for update_type it's not possible to do: + # distfile_path.split('/')[-2].split('-')[-4] + index = distfile_path.find('dist') + len('dist') + 2 + distro = distfile_path[index:].split('/')[0] + if distro.find('-') != -1: + update_type = distro.split('-')[-1] + distro = distro.split('-')[-2] + else: + update_type = 'newpackage' + + #backup file + if os.path.exists(backup_folder): + try: + backupfile = backup_folder + '/Packages-' + strftime("%Y%m%d_%H%M", gmtime()) + '.bz2' + copyfile(distfile_path, backupfile) + except Exception, ex: + message = "[%s]: error -savebackupcopyerror- %s\n" % (datetime.datetime.now(), ex) + flog.write(message) + else: + message = "[%s]: error -backupdirnotexist- %s\n" % (datetime.datetime.now(), backup_folder) + flog.write(message) + + while True: + line = fd.readline() + if line == '':#end of file + break + if not line.startswith('Package'): + continue + + dicitonary = get_elements(fd, line.split(':')[-1].strip()) + if not row_source in dicitonary: + message = "[%s]: error -missingkeyerror- %s in %s\n" % (datetime.datetime.now(), row_source , dicitonary) + flog.write(message) + continue + + n_count = n_count + 1 + pkgstat[update_type] += 1 + key = dicitonary[row_source] + '-' + distro +# # check DB +# try: +# db_dict = column_path_packagesh.get(key) +# if not dicitonary[row_version] in db_dict and checkDB == True: +# n_missing_pkg = n_missing_pkg + 1 +# message = "[%s]: error -missingDBversionerror- key = %s, distro = %s, update_type = %s, filename = %s\n" % (datetime.datetime.now(), key, distro, update_type, dicitonary[row_filename]) +# flog.write(message) +# except: +# n_missing_pkg = n_missing_pkg + 1 +# if checkDB: +# message = "[%s]: error -missingDBkeyerror- key = %s, distro = %s, update_type = %s, filename = %s\n" % (datetime.datetime.now(), key, distro, update_type, dicitonary[row_filename]) +# flog.write(message) + column_path_packagesh.insert(key, { dicitonary[row_version] : { 'updatetype' : update_type } }) + column_path_packagesh.insert(key, { dicitonary[row_version] : { 'priority' : dicitonary[row_priority] } }) + + fd.close() + os.chdir(mydir) + shutil.rmtree(tmpdir) + n_current = n_current + 1 + + if verbose: + print '\n\tTotal num of packages processed: %d' % (n_count) + print '\t\tnewpackage: %d\n\t\tupdates: %d\n\t\tsecurity: %d' % (pkgstat['newpackage'], pkgstat['updates'], pkgstat['security']) + return + +if __name__ == '__main__': + print os.path.basename(__file__) + ': execution started.' + main(sys.argv[1:]) diff --git a/db/scripts/client_insert_pkg_centos.py b/db/scripts/client_insert_pkg_centos.py new file mode 100644 index 0000000..04a32df --- /dev/null +++ b/db/scripts/client_insert_pkg_centos.py @@ -0,0 +1,279 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# client_insert_pkg_centos.py: obtain and insert CentOS packages update type +# +# Copyright (C) 2014 Politecnico di Torino, Italy +# TORSEC group -- http://security.polito.it +# +# Author: Tao Su +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# . + +import time +import sys +import os +import getopt +import string +import datetime +from dateutil.relativedelta import relativedelta + +from lxml.html import * +import urllib +import pycassa +import insert_rpm_library + +import utils + +CENTOSANNOUNCE = "http://lists.centos.org/pipermail/centos-announce/" +CENTOSCRANNOUNCE = "http://lists.centos.org/pipermail/centos-cr-announce/" + +def usage(): + print "python client_insert_pkg_centos.py {-h help | -K keyspace | -l log-file | -c cassandra-url | -d distribution | -b base-directory | -p package-list-file}" + +def getZeroDayUpdates(url_level3): + global packageUpdateType + emailContent = fromstring(urllib.urlopen(url_level3).read()) + content = emailContent.xpath("//html/body/pre") + links = emailContent.xpath("//html/body/pre/a/@href") + length_links=len(links) + + for i in content: + packages = i.xpath("./text()") + counter = 0 + for j in packages: + list_level2 = j.split() + upstream = links[counter] + if 'RHEA' in upstream : + updateType = 'enhancement' + elif 'RHBA' in upstream : + updateType = 'bugfix' + elif 'RHSA' in upstream : + updateType = 'security' + + for m in list_level2: + if '.src.rpm' in m: + packageUpdateType[m] = updateType + if counter >= length_links-1: + break + else: + counter+=1 + +def getSourcePackages(url_level3): + global packageUpdateType + emailContent = fromstring(urllib.urlopen(url_level3).read()) + content = emailContent.xpath("//html/body/pre/text()") + if "security advisory" in content[0].lower(): + updateType = 'security' + elif "bugfix advisory" in content[0].lower(): + updateType = 'bugfix' + elif "enhancement advisory" in content[0].lower(): + updateType = 'enhancement' + + for i in content: + list_level1 = i.split('\n') + for j in list_level1: + list_level2 = j.split() + for m in list_level2: + if '.src.rpm' in m: + packageUpdateType[m] = updateType + else: + continue + +def getEmails(url_level2, keyword): + print "Searching update type in " + url_level2 + keyword = keyword.lower() + tree_threads = fromstring(urllib.urlopen(url_level2).read()) + thread = tree_threads.xpath("//html/body/ul/li") + tempurl = url_level2.replace('thread.html', '') + for i in thread: + emails = i.xpath("./a/text()") + for j in emails: + j = j.lower() + if 'update' in j and keyword in j and not 'zero day' in j : + emailAddress = i.xpath("./a/@href")[0] + getSourcePackages(tempurl+emailAddress) + elif 'update' in j and keyword in j and 'zero day' in j: + emailAddress = i.xpath("./a/@href")[0] + getZeroDayUpdates(tempurl+emailAddress) + +def getThreads(url_level1, keyword_list): + tree = fromstring(urllib.urlopen(url_level1).read()) + threads = tree.xpath("//html/body/table/tr") + for i in threads: + thread = i.xpath("./td[2]/a[1]/@href") + for j in thread: + for keyword in keyword_list: + getEmails(url_level1+j, keyword) + +def insertCentosDB(DBlink, pkg_name, pkg_version, distname, updateType): + global counterNumber + DBlink.insert(pkg_name + '-' + distname, { pkg_version : { 'name' : pkg_name + '-' + pkg_version } } ); + DBlink.insert(pkg_name + '-' + distname, { pkg_version : { 'updatetype': updateType } } ); + print "[%s/%s] %s is inserted into PackagesHistory" %(counterNumber,totNumber,pkg_name) + counterNumber = counterNumber+1 + + +def main(argv): + global flog + global packageUpdateType + global counterNumber,totNumber + + counterNumber = 1 + packageUpdateType = {} + cassandra_url='localhost:9160' + packages_dir = "" + packages_list = "" + keyspace = "PackagesDB" + distribution = "CentOS7" + logfile = "/srv/ra/db/logs/cassandra_err.log" + base_directory = '/srv/ra/' + counterNumber = 1 + packagesdb = {} + + try: + opts, args = getopt.getopt(argv, "hK:l:c:d:b:p:f:", ["help", "keyspace=", "log-file=", "cassandra-url=", "distribution=", "base-directory=","package-dir=","package-list="]) + except getopt.GetoptError: + usage() + sys.exit(2) + + for opt, arg in opts: + if opt in ("-h", "--help"): + usage() + sys.exit() + elif opt in ("-K", "--keyspace"): + keyspace = arg + elif opt in ("-l", "--log-file"): + logfile = arg + elif opt in ("-c", "--cassandra-url"): + CASSANDRA_URL = arg + elif opt in ("-d", "--distribution"): + distribution = arg.replace('-', ' ') + elif opt in ("-b", "--base-directory"): + RABASEDIR = arg + elif opt in ("-p", "--package-dir"): + packages_dir = arg + if packages_dir.endswith('/'): + packages_dir=packages_dir[:-1] + elif opt in ("-f", "package-list"): + package_list = arg + + epoch_dict = utils.get_epoch_dict(packages_dir,package_list) + DBdistribution = distribution.replace(' ', '') + emailDistribution = distribution.split('.')[0] + distributionVersion = emailDistribution.split(' ')[1] + + log_missing_package = [] + with open(logfile,'a+') as f: + f.seek(0) + while True: + message = f.readline() + if len(message) == 0: + break + if '-pkghistorynotfound-' in message and 'solved' not in message: + pkg_name = message.split(' ')[4].strip() + if 'el'+distributionVersion in pkg_name and pkg_name not in log_missing_package: + log_missing_package.append(pkg_name) + elif '-pkghistorynotfound-' in message and 'solved' in message: + pkg_name = message.split(' ')[4].strip() + if pkg_name in log_missing_package: + log_missing_package.remove(pkg_name) + + try: + flog = open(logfile, 'ac'); + except: + print "Error opening %s for writing " %(logfile) + sys.exit(2) + + for pkg in log_missing_package: + current = datetime.datetime.now().date()-relativedelta(months=1) + pkg_key = pkg.split(':')[0] + '.src.rpm' + print '\nsearching previous unknown pkgs: ', pkg_key + pkg_name = '-'.join(pkg.split('-')[:-2]) + while current < datetime.datetime.now().date()+relativedelta(days=1): + getEmails(CENTOSANNOUNCE+current.strftime('%Y-%B')+'/thread.html', pkg_name) + getEmails(CENTOSCRANNOUNCE+current.strftime('%Y-%B')+'/thread.html', pkg_name) + current = current+relativedelta(months=1) + if pkg_key in packageUpdateType: + print "pkg found " + pkg_key + message = "[%s]: solved -pkghistorynotfound- %s\n" %(datetime.datetime.now(), pkg) + flog.write(message) + epoch_dict[pkg.split(':')[0]] = pkg.split(':')[1] + + try : + (latest, oldest) = utils.get_date_pushed_interval(packages_dir,package_list) + latest = datetime.datetime.strptime(latest,'%Y-%m-%d %H:%M:%S') + oldest = datetime.datetime.strptime(oldest,'%Y-%m-%d %H:%M:%S') + current = oldest-relativedelta(months=1) + print "\nRetrieving update types in CentOS mailing list..." + while True: + if current > latest : + break + else: + getEmails(CENTOSANNOUNCE+current.strftime('%Y-%B')+'/thread.html', emailDistribution) + getEmails(CENTOSCRANNOUNCE+current.strftime('%Y-%B')+'/thread.html',emailDistribution) + current = current+relativedelta(months=1) + except Exception as e: + message = "[%s]: error -readingmailinglist- %s\n" %(datetime.datetime.now(), e) + print message + flog.write(message) + pass + + try: + client = pycassa.ConnectionPool(keyspace, [CASSANDRA_URL], pool_timeout = -1, max_retries = -1) + except pycassa.TException, tx: + message = "[%s]: error -dbserverconnfailed- %s\n" %(datetime.datetime.now(), CASSANDRA_URL) + flog.write(message) + flog.close() + sys.exit(2) + + column_path_packagesh = pycassa.ColumnFamily(client,'PackagesHistory') + + totNumber=len(epoch_dict) + + for pkg in epoch_dict: + pkg_key = pkg + '.src.rpm' + if pkg_key not in packageUpdateType: + print 'searching missing pkg: ', pkg_key + packageUpdateType[pkg + '.src.rpm'] = 'unknown' + current = utils.get_pkg_datetime(packages_dir, package_list, pkg_key) + pkg_name = '-'.join(pkg.split('-')[:-2]) + getEmails(CENTOSANNOUNCE+current.strftime('%Y-%B')+'/thread.html', pkg_name) + getEmails(CENTOSCRANNOUNCE+current.strftime('%Y-%B')+'/thread.html', pkg_name) + + for pkg in epoch_dict: + epoch_prefix = '' + if len(epoch_dict[pkg]) > 0: + epoch_prefix = epoch_dict[pkg] + ':' + + pkg_name = '-'.join(pkg.split('-')[:-2]) + pkg_version = epoch_prefix + '-'.join(pkg.split('-')[-2:]) + update_type = packageUpdateType[pkg + '.src.rpm'] + if update_type == 'unknown': + message = "[%s]: error -pkghistorynotfound- %s:%s\n" %(datetime.datetime.now(), pkg,epoch_dict[pkg]) + flog.write(message) + + try: + insertCentosDB(column_path_packagesh, pkg_name, pkg_version, DBdistribution, update_type) + except pycassa.NotFoundException, TException: + message = "[%s]: error -dbinserterror- %s\n" %(datetime.datetime.now(), pkg) + flog.write(message) + flog.close() + sys.exit(2) + + flog.close() + +if __name__ == '__main__': + main(sys.argv[1:]) diff --git a/db/scripts/client_insert_pkg_hash.py b/db/scripts/client_insert_pkg_hash.py new file mode 100644 index 0000000..6ff4f41 --- /dev/null +++ b/db/scripts/client_insert_pkg_hash.py @@ -0,0 +1,491 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# client_insert_pkg_hash.py: insert digest information to the DB +# +# Copyright (C) 2014 Politecnico di Torino, Italy +# TORSEC group -- http://security.polito.it +# +# Author: Roberto Sassu +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# . + +import pycassa + +import time +import pprint +import sys +import os +import getopt +import rpm +import string +from subprocess import * +import re +import tempfile +import hashlib +import shutil +import datetime +import time +from collections import defaultdict +import insert_deb_library,insert_rpm_library + +insert_modes = [ 'newpackage', 'updates', 'testing' , 'security', 'pyunit' ] + +handlers = {'rpm': {'module': insert_rpm_library, + 'packagesh_cf_name': 'PackagesHistory', 'separator': '-'}, + 'deb': {'module': insert_deb_library, + 'packagesh_cf_name': 'PackagesHistoryDEB', + 'separator': '_'} +} + +MAX_NUM_RETRIES = 10 + +#def get_db_pkg(db): +# sources_key = db.keys() +# if len(sources_key) == 0: +# return None +# arch_keys = db[sources_key[0]].keys() +# if len(arch_keys) == 0: +# return None +# return db[sources_key[0]][arch_keys[0]][0] + + +def main(argv): + cassandra_url='localhost:9160' + packages_dir = "" + packages_list = "" + keyspace = "PackagesDB" + cfsuffix = "" + distname = "Fedora14" + distarch = "x86_64" + logfile = "/srv/ra/db/logs/cassandra_err.log" + only_package_info = False + insert_mode = None + resumepkgnum = '0' + + try: + opts, args = getopt.getopt(argv, "hK:p:d:l:iI:c:m:z:", ["help", "keyspace=", "package-list=", "package-dir=", + "log-file=", "only-package-info", "insert-mode=", "cassandra-url=", "resumepkgnum=" + "dist-name="]) + + except getopt.GetoptError: + usage() + sys.exit(2) + + for opt, arg in opts: + if opt in ("-h", "--help"): + usage() + sys.exit() + elif opt in ("-K", "--keyspace"): + keyspace = arg + elif opt in ("-p", "--package-list"): + packages_list = arg + elif opt in ("-d", "--package-dir"): + packages_dir = arg + if packages_dir.endswith('/'): + packages_dir=packages_dir[:-1] + elif opt in ("-l", "--log-file"): + logfile = arg + elif opt in ("-i", "--only-package-info"): + only_package_info = True + elif opt in ("-I", "--insert-mode"): + insert_mode = arg + elif opt in ("-c", "--cassandra-url"): + cassandra_url = arg + elif opt in ("-m", "--resume"): + resumepkgnum = arg + elif opt in ("-z", "--dist-name"): + distname = arg + + resumepkgnum = string.atoi(resumepkgnum) + + try: + flog = open(logfile, 'ac'); + except: + print "Error opening %s for writing" %(logfile) + sys.exit(2) + + if insert_mode not in insert_modes: + message = "[%s]: error -insertmodeunknown-\n" %(datetime.datetime.now()) + flog.write(message) + flog.close() + sys.exit(2) + + if insert_mode == 'testing': + cfsuffix = '_test' + elif insert_mode == 'pyunit': + cfsuffix = '_pyunit' + + try: + fd = open(packages_list, 'r') + except: + message = "[%s]: error -packagelistnotfound- %s\n" %(datetime.datetime.now(), packages_list) + flog.write(message) + flog.close() + sys.exit(2) + + try: + client = pycassa.ConnectionPool(keyspace, [cassandra_url], pool_timeout = -1, max_retries = -1) +# clientB = pycassa.ConnectionPool('BodhiDB', [cassandra_url], pool_timeout = -1, max_retries = -1) + except: + message = "[%s]: error -dbserverconnfailed- %s\n" %(datetime.datetime.now(), cassandra_url) + flog.write(message) + fd.close() + flog.close() + sys.exit(2) + +# column_path_files = pycassa.ColumnFamily(client, 'Files'); + column_path_filestop = pycassa.ColumnFamily(client, 'FilesToPackages' + cfsuffix) +# column_path_packagesh = pycassa.ColumnFamily(client, 'PackagesHistory' + cfsuffix) +# column_path_bodhidb = pycassa.ColumnFamily(clientB, 'Bodhi'); + + packagedb = {} + epoch_dict = {} + + for package in fd.readlines(): + if len(package) == 0: + continue + + package = package.strip() + package_type = package.split('.')[-1] + if package_type not in handlers: + continue + + # FIXME: check if this is needed +# if package.endswith('deb'): +# package = package.split(' ')[-1] + + if len(packages_dir) != 0: + package_path = "%s/%s" %(packages_dir, package) + else: + package_path = package + + try: + # Get: source package name, source package version and release, package arch, errors + result = handlers[package_type]['module'].getSrcAndArch(package_path) + if result[3] is not None: + message = "[%s]: error -accesserror- %s %s\n" %(datetime.datetime.now(), package, result[3]) + flog.write(message) + continue + except Exception, ex: + message = "[%s]: error -accesserror- %s %s\n" %(datetime.datetime.now(), package, ex) + flog.write(message) + continue + + # remove the epoch from RPM packages to correctly group them + pkg_version_release = result[1] + if package_type == 'rpm': + epoch = '' + if ':' in result[1]: + epoch = result[1].split(':')[0] + pkg_version_release = result[1].split(':', 1)[1] + + epoch_key = result[0] + '-' + pkg_version_release + pkg_key = '.'.join(os.path.basename(package).split('.')[:-2]) + if epoch_key not in epoch_dict or pkg_key == epoch_key: + epoch_dict[epoch_key] = epoch + + # Create the packagedb key in a way that it is easy to split + packagedb_key = (result[0], pkg_version_release, package_type) + if packagedb_key not in packagedb: + packagedb[packagedb_key] = {} + if result[2] not in packagedb[packagedb_key]: + packagedb[packagedb_key][result[2]] = set() + + # FIXME: check if ordering packages is needed + packagedb[packagedb_key][result[2]].add(package) + + totcount = len(packagedb) + print "\nStarting insert of package's data [%d]...\n" % (totcount) + + pcount = 1 + num_retries = 0 + do_restart = False + packagedb_iterator = packagedb.iterkeys() + current_package = None + + while True: + if not do_restart: + try: + package_source_rpm = packagedb_iterator.next() + num_retries = 0 + except StopIteration: + break + else: + do_restart = False + num_retries = num_retries + 1 + if num_retries > MAX_NUM_RETRIES: + message = "[%s]: error -maxnumretriesreached- %s\n" %(datetime.datetime.now(), package_source_rpm) + flog.write(message) + break + + message = "[%s]: error -retrysourcepackage- %s\n" %(datetime.datetime.now(), package_source_rpm) + flog.write(message) + time.sleep(5) + + if pcount < resumepkgnum: + pcount = pcount + 1 + continue + + message = "[%d of %d] %s:\n" % (pcount, totcount, package_source_rpm) + sys.stdout.write(message) + + source_package_type = package_source_rpm[2] + package_handler = handlers[source_package_type]['module'] + packagesh_cf_name = handlers[source_package_type]['packagesh_cf_name'] + cfsuffix + column_path_packagesh = pycassa.ColumnFamily(client, packagesh_cf_name) + packagesh_row = '-'.join([package_source_rpm[0], distname]) + packagesh_super_column = package_source_rpm[1] + epoch_dict_key = '-'.join(package_source_rpm[0:2]) + if source_package_type == 'rpm' and epoch_dict_key in epoch_dict and len(epoch_dict[epoch_dict_key]) > 0: + packagesh_super_column = '%s:%s' % (epoch_dict[epoch_dict_key], packagesh_super_column) + source_package_name = handlers[source_package_type]['separator'].join([package_source_rpm[0], packagesh_super_column]) + + if source_package_type != 'rpm' or insert_mode != 'updates': + try: + column_path_packagesh.insert(packagesh_row, {packagesh_super_column: {'name' : source_package_name}}) + column_path_packagesh.insert(packagesh_row, {packagesh_super_column: {'updatetype' : insert_mode}}) + except Exception as e: + message = "[%s]: error -dberror- %s %s\n" %(datetime.datetime.now(), package_source_rpm, e) + flog.write(message) + do_restart = True + continue + + try: + pkg_history = column_path_packagesh.get(packagesh_row, column_reversed=True) + pkg_history_versions = pkg_history.keys() + index_new_pkg_version = pkg_history_versions.index(packagesh_super_column) + except: + column_path_packagesh.insert(packagesh_row, {packagesh_super_column: {'name' : source_package_name}}) + column_path_packagesh.insert(packagesh_row, {packagesh_super_column: {'updatetype' : 'unknown'}}) + message = "[%s]: error -pkghistorynotfound- %s\n" %(datetime.datetime.now(), package_source_rpm[0]) + flog.write(message) + do_restart = True + continue + + if only_package_info == True: + pcount = pcount + 1 + sys.stdout.write('.\n') + continue + + # NOTE: to avoid error messages about existing files, extract in the tmp dir + # only packages of one architecture. + # TODO: check if it is possible to have a library link in the 'all' architecture + # that points to a library in a different architecture ('i386' or 'amd64'). + for distarch in packagedb[package_source_rpm]: + sys.stdout.write(distarch) + + files = [] + links = [] + tmpdir = tempfile.mkdtemp(prefix="rpm_extract.") + mydir = os.getcwd() + os.chdir(tmpdir) + + for package in packagedb[package_source_rpm][distarch]: + if len(packages_dir) != 0: + package_path = "%s/%s" %(packages_dir, package) + else: + package_path = package + + # Extract in tmpdir/package_filename + destdir = os.path.join(tmpdir, os.path.basename(package)) + # Workaround: cpio does not support destination directory parameter + os.mkdir(destdir) + os.chdir(destdir) + package_files, errors = package_handler.extract_package_files(package_path) + os.chdir(tmpdir) + if errors is not None: + message = "[%s]: error -listpackagefileserror- %s: %s\n" %(datetime.datetime.now(), package, errors) + flog.write(message) + continue + + for f in package_files: + fpathname = os.path.join(os.path.basename(package), os.path.normpath(f)) + if os.path.islink(fpathname): + links.append(fpathname) + files.append((os.path.basename(package), fpathname)) + + for l in links: + linkvalue = os.readlink(l) + for package in packagedb[package_source_rpm][distarch]: + if linkvalue.startswith('/'): + resolvedlink = os.path.join(tmpdir, os.path.basename(package), linkvalue[1:]) + else: + resolvedlink = os.path.join(tmpdir, os.path.basename(package), '/'.join(os.path.dirname(l).split('/')[1:]), linkvalue) + + if os.path.lexists(resolvedlink): + found_link_dest = True + os.unlink(l) + os.symlink(resolvedlink, l) + break + + + do_restart_package_files = False + num_retries_package_files = 0 + files_iterator = files.__iter__() + + while True: + if not do_restart_package_files: + try: + files_entry = files_iterator.next() + num_retries_package_files = 0 + except StopIteration: + break + else: + do_restart_package_files = False + num_retries_package_files = num_retries_package_files + 1 + if num_retries_package_files > MAX_NUM_RETRIES: + message = "[%s]: error -maxnumretriesreachedpackagefiles- %s\n" %(datetime.datetime.now(), package_source_rpm) + flog.write(message) + break + + message = "[%s]: error -retrypackagefiles- %s %s\n" %(datetime.datetime.now(), package_source_rpm, distarch) + flog.write(message) + time.sleep(5) + + curpackage, fpathname = files_entry + fname = os.path.basename(fpathname) + + if not os.path.exists(fpathname): + if '.so' in fpathname: + message = "[%s]: error -extractedfilenotfound- %s %s\n" %(datetime.datetime.now(), package_source_rpm, fpathname) + flog.write(message) + continue + + if not os.path.isfile(fpathname): + continue + + extra = [] + + is_link = os.path.islink(fpathname) + is_elf = False + + sys.stdout.write('.') + + elf_type = 'undefined' + shared_libraries = [] + + fd = open(fpathname, 'rb') + header = fd.read(4) + fd.close() + if header == b'\x7fELF': + is_elf = True + p1 = Popen(['readelf', '-h', '-s', '-d', fpathname],stdout=PIPE, stderr=PIPE).communicate()[0] + for line in p1.split('\n'): + if len(line) == 0: + continue + line_split = line.split() + if len(line_split) > 1 and line_split[0] == 'Type:': + elf_type = line_split[1] + # override elf_type if there is the symbol __libc_start_main (some executables have type DYN, like /sbin/pam_timestamp_check) + if len(line_split) > 7 and line_split[6] == 'UND' and line_split[7].startswith('__libc_start_main'): + elf_type = 'EXEC' + if len(line_split) > 2 and line_split[1] == '(NEEDED)': + shared_libraries.append(line_split[4][1:-1]) + + filetype = 'other' + if is_link: + if is_elf and elf_type == 'DYN': + filetype = 'linklib' + extra.append(os.path.relpath(os.path.realpath(fpathname), tmpdir)) + else: + filetype = 'link' + elif not is_link and is_elf and elf_type in ['EXEC', 'DYN']: + extra.extend(shared_libraries) + if elf_type == 'EXEC': + filetype = 'exe' + elif elf_type == 'DYN': + filetype = 'lib' + + if filetype is 'link': + continue + + try: + f = open(fpathname) + h = hashlib.sha1() + h.update(f.read()) + fdigest = h.hexdigest() + f.close() + except IOError, reason: + message = "[%s]: error -fileioerror- %s %s\n" %(datetime.datetime.now(), package_source_rpm, fpathname) + flog.write(message) + do_restart_package_files = True + continue + try: + # Temporaney cleanup +# column_path_filestop.remove( fdigest , super_column=distname + '-' + distarch, columns = [files[fpathname]] ) +# column_path_filestop.remove( fdigest , super_column='-w-' + distarch) + + if filetype is not "linklib": +# column_path_files.insert( fdigest , { 'name' : fname } ) + fullpath = '/' + '/'.join(fpathname.split('/')[1:]) + column_path_filestop.insert( fdigest , { distname + '-' + distarch : { 'fullpath' : fullpath } } ) + + filestop_pkg_super_column = 'pkg-' + package_source_rpm[0] + insert_current_pkg_version = False + current_pkg_version = None + + try: + current_pkg_version = column_path_filestop.get(fdigest, super_column=distname + '-' + distarch)[filestop_pkg_super_column] + except: + insert_current_pkg_version = True + + if current_pkg_version is not None: + index_current_pkg_version = pkg_history_versions.index(current_pkg_version) + if index_new_pkg_version < index_current_pkg_version: + insert_current_pkg_version = True + + if insert_current_pkg_version: + column_path_filestop.insert(fdigest, {distname + '-' + distarch: {filestop_pkg_super_column: packagesh_super_column}}) + + if filetype in ["lib", "exe"]: + column_path_filestop.insert(fdigest, {distname + '-' + distarch: {'libraries': ','.join(extra)}}) + if filetype is "exe": + column_path_filestop.insert(fdigest, {distname + '-' + distarch: {'is_executable': 'yes'}}) + + if filetype in ["lib", "linklib"]: + insert_library_list = True + + try: + item = column_path_filestop.get( fdigest , super_column = distname + "-" + distarch) + library_list = item['lib_aliases'].split(',') + if fname not in library_list: + library_list.append(fname) + else: + insert_library_list = False + except (pycassa.NotFoundException, KeyError): + library_list = [fname] + + if insert_library_list: + column_path_filestop.insert( fdigest , { distname + '-' + distarch : { 'lib_aliases' : ','.join(library_list) } } ) + except Exception, ex: + message = "[%s]: error -dbinserterror- %s %s: %s\n" %(datetime.datetime.now(), package_source_rpm, fpathname, ex) + flog.write(message) + do_restart_package_files = True + continue + + sys.stdout.write('\n') + os.chdir(mydir) + try: + shutil.rmtree(tmpdir) + except OSError, reason: + message = "[%s]: error -tmpdirnotremoved- %s %s\n" %(datetime.datetime.now(), package_source_rpm, tmpdir) + flog.write(message) + pcount = pcount + 1 + + flog.close() + fd.close() +if __name__ == '__main__': + main(sys.argv[1:]) diff --git a/db/scripts/client_insert_pkg_http.py b/db/scripts/client_insert_pkg_http.py new file mode 100644 index 0000000..f6d8dcb --- /dev/null +++ b/db/scripts/client_insert_pkg_http.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# client_insert_pkg_http.py: obtain and insert Fedora/EPEL packages update type +# +# Copyright (C) 2014 Politecnico di Torino, Italy +# TORSEC group -- http://security.polito.it +# +# Author: Roberto Sassu +# Tao Su +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# . + +import datetime +import getopt +import lxml.html +import os +import pycassa +import sys +import urllib +import utils + + +def main(argv): + keyspace = "PackagesDB" + logfile = "/srv/ra/db/logs/http_err.log" + CASSANDRA_URL = 'localhost:9160' + release_packages = False + distribution = 'Fedora19' + packages_dir = None + packages_list = None + + try: + opts, args = getopt.getopt(argv, "hK:l:b:c:rd:p:q:", ["help", "keyspace=", "log-file=", "cassandra-url=", + "distribution=", "packages-dir=", "packages-list="]) + except getopt.GetoptError: + usage() + sys.exit(2) + + for opt, arg in opts: + if opt in ("-h", "--help"): + usage() + sys.exit() + elif opt in ("-K", "--keyspace"): + keyspace = arg + elif opt in ("-l", "--log-file"): + logfile = arg + elif opt in ("-c", "--cassandra-url"): + CASSANDRA_URL = arg + elif opt in ("-d", "--distribution"): + distribution = arg.replace('-', '') + elif opt in ("-p", "--packages-dir"): + packages_dir = arg + elif opt in ("-q", "--packages-list"): + packages_list = arg + + try: + flog = open(logfile, 'ac'); + except: + print "Error opening %s for writing" %(logfile) + sys.exit(2) + + try: + client = pycassa.ConnectionPool(keyspace, [CASSANDRA_URL], pool_timeout = -1, max_retries = -1) + except pycassa.TException, tx: + message = "[%s]: error -dbserverconnfailed- %s\n" %(datetime.datetime.now(), CASSANDRA_URL) + flog.write(message) + flog.close() + sys.exit(2) + + column_path_packagesh = pycassa.ColumnFamily(client, 'PackagesHistory'); + epoch_dict = utils.get_epoch_dict(packages_dir, packages_list) + date_pushed_interval = utils.get_date_pushed_interval(packages_dir, packages_list) + saved_end_date = date_pushed_interval[0] + count = len(epoch_dict.keys()) + current_page = 1 + updatetype_db = {} + + distribution_id = distribution + if distribution.startswith('Fedora'): + distribution_id = distribution.replace('edora', '') + elif distribution.startswith('EPEL'): + if distribution in ['EPEL5', 'EPEL6']: + distribution_id = distribution.replace('EPEL', 'EL-') + else: + distribution_id = distribution.replace('EPEL', 'EPEL-') + + while count > 0: + fedora_url = 'https://bodhi.fedoraproject.org/updates/?status=stable&releases=%s&page=%s' % (distribution_id, current_page) + print "Querying Fedora Web site - distribution: %s, current page: %d, remaining pkgs: %d" %(distribution_id, current_page, count) + + response_str = urllib.urlopen(fedora_url).read(); + response_dict = yaml.load(response_str); + + accessed_page = response_dict['page']; + + if accessed_page != current_page: + break + + for item in response_dict['updates']: + + if ' ' in item['title']: + pkg_list = item['title'].split(' ') + elif "," in item['title']: + pkg_list = item['title'].split(',') + else : + pkg_list = item['title'].split('?') + + update = item['type'] + if item['date_pushed'] is None: + date_released = date_pushed_interval[1] + else: + date_released = item['date_pushed'].strip() + + for pkg in pkg_list: + if pkg not in epoch_dict: + continue + + count -= 1 + updatetype_db[pkg] = update + + if utils.date_is_older(date_released, date_pushed_interval[1]): + break + + current_page += 1 + + for pkg in epoch_dict: + try: + update_type = updatetype_db[pkg] + except: + update_type = 'unknown' + message = "[%s]: error -pkghistorynotfound- %s\n" %(datetime.datetime.now(), pkg) + flog.write(message) + + epoch_prefix = '' + if len(epoch_dict[pkg]) > 0: + epoch_prefix = epoch_dict[pkg] + ':' + + pkg_name = '-'.join(pkg.split('-')[:-2]) + pkg_version = epoch_prefix + '-'.join(pkg.split('-')[-2:]) + + try: + column_path_packagesh.insert(pkg_name + '-' + distribution, {pkg_version: {'name': pkg_name + '-' + pkg_version}}) + column_path_packagesh.insert(pkg_name + '-' + distribution, {pkg_version: {'updatetype': update_type}}) + except pycassa.NotFoundException, TException: + message = "[%s]: error -dbinserterror- %s\n" %(datetime.datetime.now(), pkg) + flog.write(message) + flog.close() + sys.exit(2) + + flog.close() + +if __name__ == '__main__': + main(sys.argv[1:]) diff --git a/db/scripts/createDb_with_rsync-files.sh b/db/scripts/createDb_with_rsync-files.sh new file mode 100644 index 0000000..cbf4d1f --- /dev/null +++ b/db/scripts/createDb_with_rsync-files.sh @@ -0,0 +1,85 @@ +#! /bin/bash + +# create_Db_with_rsync-files.sh +# +# Copyright (C) 2013 Politecnico di Torino, Italy +# TORSEC group -- http://security.polito.it +# +# Author: Giuseppe Baglio +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# . + +show_help(){ +echo "Usage: + h | ? ) show this help message + d ) DB packages directory + u ) input rsync file for 'updates' packages + s ) input rsync file for 'security' packages + n ) input rsync file for 'newpackage' packages + o ) standard output file for this script + e ) standard error file for inner command + i ) standard output file for inner command + f ) update script to insert packages in the DB +" +} + +PKGS_DIR='/srv/ra/Packages/precise' +SCRIPT_OUTPUT=$0"_execution.output" +SCRIPT_STDERR=$0"_inner.stderr" +SCRIPT_SDTOUT=$0"_inner.stdout" +SYNC_NEWPKGS='rsync-Ubuntu-precise-all,amd64-newpackage-10001010_0000.log' +RSYNC_UPDS='rsync-Ubuntu-precise-all,amd64-updates-10001010_0000.log' +RSYNC_SEC='rsync-Ubuntu-precise-all,amd64-security-10001010_0000.log' +UPDATE_SCRIPT='/srv/ra/update_pkgs.sh' + +while getopts "h?dnusoeif:" opt; do + case "$opt" in + h|\?) + show_help + exit 0 + ;; + d) PKGS_DIR=$OPTAR + ;; + n) RSYNC_NEWPKGS=$OPTARG + ;; + u) RSYNC_UPDS=$OPTARG + ;; + s) RSYNC_SEC=$OPTARG + ;; + o) SCRIPT_OUTPUT=$OPTARG + ;; + e) SCRIPT_STDERR=$OPTARG + ;; + i) SCRIPT_SDTOUT=$OPTARG + ;; + f) UPDATE_SCRIPT=$OPTARG + ;; + esac +done + +echo "Newpackage pkgs: " > $SCRIPT_OUTPUT +date >> $SCRIPT_OUTPUT +$UPDATE_SCRIPT -r $RSYNC_NEWPKGS -d $PKGS_DIR 1>$SCRIPT_SDTOUT 2>$SCRIPT_STDERR +date >> $SCRIPT_OUTPUT + +echo "Security pkgs: " >> $SCRIPT_OUTPUT +date >> $SCRIPT_OUTPUT +$UPDATE_SCRIPT -r $RSYNC_SEC -d $PKGS_DIR 1>$SCRIPT_SDTOUT 2>$SCRIPT_STDERR +date >> $SCRIPT_OUTPUT + +echo "Updates pkgs: " >> $SCRIPT_OUTPUT +date >> $SCRIPT_OUTPUT +$UPDATE_SCRIPT -r $RSYNC_UPDS -d $PKGS_DIR 1>$SCRIPT_SDTOUT 2>$SCRIPT_STDERR +date >> $SCRIPT_OUTPUT diff --git a/db/scripts/db_fix.py b/db/scripts/db_fix.py new file mode 100644 index 0000000..46e04ff --- /dev/null +++ b/db/scripts/db_fix.py @@ -0,0 +1,47 @@ +#! /usr/bin/python + +# db_fix.py: tool to fix the database +# +# Copyright (C) 2014 Politecnico di Torino, Italy +# TORSEC group -- http://security.polito.it +# +# Author: Roberto Sassu +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# . + +import pycassa +keyspace = "PackagesDB" +cassandra_url='130.192.1.104:9160' +client = pycassa.ConnectionPool("PackagesDB",[cassandra_url],) +clientb = pycassa.ConnectionPool('BodhiDB',[cassandra_url],) +cf = pycassa.ColumnFamily(client, 'PackagesHistory') +cf_bodhi = pycassa.ColumnFamily(clientb, 'Bodhi') + +for item in cf.get_range(): + if '-Fedora' in item[0]: + for version in item[1].keys(): + if item[1][version]['updatetype'] != 'updates': + continue + + try: + source_pkg = '-'.join(item[0].split('-')[:-1]) + if ':' in version: + version = version.split(':')[1] + updatetype = cf_bodhi.get('update', super_column = source_pkg + '-' + version)['updatetype'] + cf.insert(item[0], {version: {'updatetype' : updatetype}}) + except pycassa.NotFoundException as e: + cf.remove(item[0], None, version) + except Exception as e: + print e diff --git a/db/scripts/insert_deb_library.py b/db/scripts/insert_deb_library.py new file mode 100644 index 0000000..cb64459 --- /dev/null +++ b/db/scripts/insert_deb_library.py @@ -0,0 +1,75 @@ +# insert_deb_library.py: DEB library functions +# +# Copyright (C) 2013 Politecnico di Torino, Italy +# TORSEC group -- http://security.polito.it +# +# Author: Giuseppe Baglio +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# . + +from subprocess import PIPE,Popen +import pycassa,os,re +import datetime +import string + + +def _get_dpkg_output(file_name_deb): + # To extract the information about the package this function uses the "dpkg --info" shell command + # + # INPUT: pool/main/s/sudo/sudo_1.8.3p1-1ubuntu3.4_amd64.deb + # OUTPUT: returns a tuple (stdout, stderr) of dpkg command + p = Popen(['dpkg', '--info', file_name_deb], stdout=PIPE, stderr=PIPE) + return p.communicate() + +def getSrcAndArch(package_path): + # INPUT: "libdevmapper1.02.1_1.02.48-4ubuntu7.3_amd64.deb" + # OUTPUT: "lvm2_2.02.66-4ubuntu7.3", "amd64" + + output_dpkg, errors = _get_dpkg_output(package_path) + if len(errors) > 0: + return None, None, None, errors + + source_name = "" + source_ver_and_rev = None + if output_dpkg.find('Source: ') != -1: + out_split = output_dpkg.split('Source: ')[1].split('\n')[0] + # check if package and its source have different versions + if out_split.find("(") != -1: + source_ver_and_rev = out_split.split("(")[1].split(')')[0].strip() + out_split = out_split.split("(")[0].strip() + source_name = out_split + else: + out_split = output_dpkg.split('Package: ') + if (len (out_split) > 1): + source_name = out_split[1].split('\n')[0] + + # Epoch and version+revision (if not defined already) + if source_ver_and_rev == None: + source_ver_and_rev = output_dpkg.split('Version: ')[1].split('\n')[0] + + arch = output_dpkg.split('Architecture: ')[1].split('\n')[0].strip() + return source_name, source_ver_and_rev, arch, None + +def extract_package_files(package_path): + p = Popen (['dpkg', '-X', package_path, '.'], stdout=PIPE, stderr=PIPE) + + stdout, stderr = p.communicate() + if len(stderr) > 0: + return None, stderr + + stdout_split = stdout.split('\n') + if len(stdout_split[-1]) == 0: + stdout_split.pop(-1) + return stdout_split, None diff --git a/db/scripts/insert_rpm_library.py b/db/scripts/insert_rpm_library.py new file mode 100644 index 0000000..c0aab91 --- /dev/null +++ b/db/scripts/insert_rpm_library.py @@ -0,0 +1,55 @@ +# insert_rpm_library.py: RPM library functions +# +# Copyright (C) 2014 Politecnico di Torino, Italy +# TORSEC group -- http://security.polito.it +# +# Author: Roberto Sassu +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# . + +import os,rpm,string,pycassa +from subprocess import PIPE,Popen + + +def getSrcAndArch(package_path): + try: + fdno = os.open(package_path,os.O_RDONLY) + ts = rpm.TransactionSet() + ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES) + hdr = ts.hdrFromFdno(fdno) + os.close(fdno) + except Exception,ex: + return None, None, None, ex + + #NOTE: always take the version and release extracted from the source RPM +# source_ver_and_rev = '-'.join([hdr[rpm.RPMTAG_VERSION], hdr[rpm.RPMTAG_RELEASE]]) + source_ver_and_rev = '.'.join('-'.join(hdr[rpm.RPMTAG_SOURCERPM].split('-')[-2:]).split('.')[:-2]) + + #TODO: at the moment, we assume that the epoch of the source package and the binary package are always the same + # to remove this assumption it is needed to fetch the epoch directly from the source package since it is not + # contained in the source package file name. + if hdr[rpm.RPMTAG_EPOCH] is not None: + source_ver_and_rev = ':'.join([str(hdr[rpm.RPMTAG_EPOCH]), source_ver_and_rev]) + + return '-'.join(hdr[rpm.RPMTAG_SOURCERPM].split('-')[:-2]), source_ver_and_rev, hdr[rpm.RPMTAG_ARCH], None + +def extract_package_files(package_path): + p1 = Popen(['rpm2cpio',package_path],stdout=PIPE) + p2 = Popen(['cpio','--quiet','--no-absolute-filenames','-idmuv','--no-preserve-owner'], stdin=p1.stdout, stdout=PIPE, stderr=PIPE) + p1.stdout.close() + + # cpio sends the list of extracted files to stderr + p2_stderr_split = [f for f in p2.communicate()[1].split('\n') if not f.startswith('cpio:') and len(f) > 0] + return p2_stderr_split, None diff --git a/db/scripts/new-distro_rsync-files.sh b/db/scripts/new-distro_rsync-files.sh new file mode 100644 index 0000000..e20167e --- /dev/null +++ b/db/scripts/new-distro_rsync-files.sh @@ -0,0 +1,87 @@ +#!/bin/sh + +# new-distro_rsync-files.sh +# +# Copyright (C) 2013 Politecnico di Torino, Italy +# TORSEC group -- http://security.polito.it +# +# Author: Giuseppe Baglio +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# . + +show_help(){ +echo "Usage: + h | ? ) show this help message + u ) input rsync file for 'updates' packages + s ) input rsync file for 'security' packages + n ) input rsync file for 'newpackage' packages +" +} + +# +# Il file installed_pkg.txt contiene il nome di tutti i pacchetti installati della distribuzione che si vuole analizzare. +# Deve essere creato con il comando +# dpkg --get-selections | awk '{print $1}' +# +PKGS=$(cat installed_pkg.txt) + +# Il file seguente deve contenere tutte le "voci rsync" dei pacchetti di tipo "newpackage" presenti nel filesystem del server +# Può essere creato con il comando +# cat /srv/ra/db/logs/rsync*newpackage* | grep "deb$" | awk '{print $5}' | sort | uniq | awk '{print "1999/01/01 00:00:00 [1986] >f+++++++++ "$1}' > rsync-Ubuntu-release-arch-newpackage-20130000_0000.log +RSYNC_NEWPKGS='/srv/ra/db/logs/rebuildDB/uniqueRsyncFile/rsync-Ubuntu-precise-all,amd64-newpackage-20130000_0000.log' + +# E' il file rsync che contiene tutti pacchetti correttamente filtrati +OUTFILE_NEWPKGS='rsync-Ubuntu-precise-all,amd64-newpackage-10001010_0000.log' + +TMP_NEWPKGS='tmp_NEWPKGS.txt' + +RSYNC_UPDS='/srv/ra/db/logs/rebuildDB/uniqueRsyncFile/rsync-Ubuntu-precise-all,amd64-updates-20130000_0000.log' +OUTFILE_UPDS='rsync-Ubuntu-precise-all,amd64-updates-10001010_0000.log' +TMP_UPDS='tmp_UPDS.txt' + +RSYNC_SEC='/srv/ra/db/logs/rebuildDB/uniqueRsyncFile/rsync-Ubuntu-precise-all,amd64-security-20130000_0000.log' +OUTFILE_SEC='rsync-Ubuntu-precise-all,amd64-security-10001010_0000.log' +TMP_SEC='tmp_SEC.txt' + +while getopts "h?n:u:s:" opt; do + case "$opt" in + h|\?) + show_help + exit 0 + ;; + n) RSYNC_NEWPKGS=$OPTARG + ;; + u) RSYNC_UPDS=$OPTARG + ;; + s) RSYNC_SEC=$OPTARG + ;; + esac +done + +for pkg in $PKGS +do + cat $RSYNC_NEWPKGS | grep $pkg"_" | grep "deb$" >> $TMP_NEWPKGS + cat $RSYNC_UPDS | grep $pkg"_" | grep "deb$" >> $TMP_UPDS + cat $RSYNC_SEC | grep $pkg"_" | grep "deb$" >> $TMP_SEC +done + +cat $TMP_NEWPKGS | sort | uniq > $OUTFILE_NEWPKGS && rm $TMP_NEWPKGS +echo "Done:\n\t" $RSYNC_NEWPKGS"\n\t\t (n. line: "$(wc -l $OUTFILE_NEWPKGS | awk '{print $1}')")" + +cat $TMP_UPDS | sort | uniq > $OUTFILE_UPDS && rm $TMP_UPDS +echo "Done:\n\t" $RSYNC_UPDS"\n\t\t (n. line: "$(wc -l $OUTFILE_UPDS | awk '{print $1}')")" + +cat $TMP_SEC | sort | uniq > $OUTFILE_SEC && rm $TMP_SEC +echo "Done:\n\t" $RSYNC_SEC"\n\t\t (n. line: "$(wc -l $OUTFILE_SEC | awk '{print $1}')")" diff --git a/db/scripts/update_pkgs.sh b/db/scripts/update_pkgs.sh new file mode 100644 index 0000000..e9f2dd8 --- /dev/null +++ b/db/scripts/update_pkgs.sh @@ -0,0 +1,394 @@ +#! /bin/bash + +# update_pkgs.sh +# +# Copyright (C) 2014 Politecnico di Torino, Italy +# TORSEC group -- http://security.polito.it +# +# Author: Roberto Sassu +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# . + +RA_CONFIG_DIR="/etc/ra" +RA_CONFIG_FILE="$RA_CONFIG_DIR/ra.conf" + +if [ -f $RA_CONFIG_FILE ]; then +. $RA_CONFIG_FILE +fi + +if [ -z $RABASEDIR ]; then + echo "RABASEDIR variable is not defined. Please set it in /etc/ra/ra.conf" + exit 1 +fi + +if [ -z $TARGETBASEDIR ]; then + echo "TARGETBASEDIR variable is not defined. Please set it in /etc/ra/ra.conf" + exit 1 +fi + +if [ ! -d $TARGETBASEDIR ]; then + echo "The $TARGETBASEDIR directory is not existent" + exit 1 +fi + + +DATESUFFIX=`date +%Y%m%d_%H%M_%S` +INSERTSCRIPT="$RABASEDIR/db/scripts/client_insert_pkg_hash.py" +BODHISCRIPT="$RABASEDIR/db/scripts/client_insert_pkg_bodhi.py" +HTTPSCRIPT="$RABASEDIR/db/scripts/client_insert_pkg_http.py" +BODHISCRIPT_DEB="$RABASEDIR/db/scripts/client_insert_pkg_bodhi_DEB.py" +KEYSPACE="PackagesDB" +LOGDIR="$RABASEDIR/db/logs" +DBLOGFILE="$LOGDIR/cassandra_err.log" +BODHILOGFILE="$LOGDIR/bodhi_err.log" +BODHILOGFILE_DEB="$LOGDIR/bodhideb_err.log" +RHEL6LOGFILE="$LOGDIR/rhel_err.log" +HTTPLOGFILE="$LOGDIR/http_err.log" +TRANSACTIONLOGFILE="$LOGDIR/transactions.log" +CONFDIR="$RABASEDIR/db/conf" +FILELIST="$RA_CONFIG_DIR/pkgs_download_list.conf" +CENTOSSCRIPT="$RABASEDIR/db/scripts/client_insert_pkg_centos.py" +CENTOSLOGFILE="$LOGDIR/centos.log" + + +if [ ! -d "$TARGETBASEDIR" ]; then + mkdir -p $TARGETBASEDIR +fi + +function db_insert() +{ + # Workaround for distribution name +# curdist=$(echo $2 | sed 's/^F/Fedora/g') +# curdist=$(echo $curdist | awk -F"-" '{ if (length($2)==0) print $1; else print $2}') + + curdist=$(echo $2 | sed 's/-//g' | sed 's/Ubuntu//g') + +# if [ $(expr match $2 "Ubuntu") -eq 6 ]; then +# # Setup a GIT repository for each Packages.[bz2|gz] +# for pkgdbfile in $(cat $1 | awk '$4 ~ />f+++++++++/ && $5 ~ /^dists/ && $5 ~ /Packages.gz/ {print $5}'); do +# PACKAGESDBDIR=$6/$(dirname $pkgdbfile) +# PACKAGESDBGITDIR=$PACKAGESDBDIR/Packages_git +# SAVEDDIR=$PWD +# +# if [ ! -e "$PACKAGESDBGITDIR" ]; then +# mkdir $PACKAGESDBGITDIR +# git init $PACKAGESDBGITDIR +# git config -f $PACKAGESDBGITDIR/.git/config user.name "update_pkgs.sh" +# git config -f $PACKAGESDBGITDIR/.git/config user.email "user@localhost" +# touch $PACKAGESDBGITDIR/Packages +# fi +# +# cd $PACKAGESDBGITDIR +# zcat $6/$pkgdbfile > Packages +# git add Packages +# git commit -m"Automated save of Packages database" +# if [ $? -eq 0 ]; then +# git tag $DATESUFFIX +# fi +# +# cd $SAVEDDIR +# done +# if [ $4 != "testing" ] && [ $4 != "newpackage" ] && [ $4 != "pyunit" ]; then +# $BODHISCRIPT_DEB -b "$RABASEDIR/dist/backup/" -l $BODHILOGFILE_DEB -d $6 -H $CASSANDRAURL +# fi +# else + if [ ! -f $1 ]; then + return 1 + fi + + # Extracting package list from the log file and put it in + PACKAGELISTFILE=${1//rsync-/data-} + cat $1 | awk '$4 ~ />f+++++++++/ && $5 ~ /\.deb$/ {print $5}' &> $PACKAGELISTFILE | awk 'BEGIN{FS="/"} {print $NF}' +# cat $1 | awk '$4 ~ />f+++++++++/ && $5 ~ /\.udeb$/ {print $5}' &>> $PACKAGELISTFILE | awk 'BEGIN{FS="/"} {print $NF}' + cat $1 | awk '$4 ~ />f+++++++++/ && $5 ~ /\.rpm$/ {print $5}' &>> $PACKAGELISTFILE | awk 'BEGIN{FS="/"} {print $NF}' + + # Parsing the log file generated by rsync + if [ ! -f $PACKAGELISTFILE ]; then + echo "[`date`]: error -parsinglogerror-" >> $DBLOGFILE + return 1 + fi + + # Verifying if there are packages to process + total_lines=`wc -l $PACKAGELISTFILE | awk '{print $1}'` + if [ $total_lines -eq 0 ]; then + echo "No packages to insert in the DB" + rm $PACKAGELISTFILE + rm $1 + return 0 + fi + + if [ $4 = "updates" ] && [ $5 -eq 0 ]; then + if [ $(expr match $curdist "Fedora") -eq 6 ]; then + $HTTPSCRIPT -d $2 -l $HTTPLOGFILE -c $CASSANDRAURL -p $6 -q $PACKAGELISTFILE + elif [ $(expr match $curdist "EPEL") -eq 4 ]; then + $HTTPSCRIPT -d $2 -l $HTTPLOGFILE -c $CASSANDRAURL -p $6 -q $PACKAGELISTFILE + elif [ $(expr match $curdist "RHEL") -eq 4 ]; then + $RHELSCRIPT -d $6 -l $RHEL6LOGFILE -o $1 $IGNOREOPT $DOWNLOADALLOPT $ADVISORYOPT + elif [ $(expr match $curdist "CentOS") -eq 6 ]; then + $CENTOSSCRIPT -d $2 -l $CENTOSLOGFILE -c $CASSANDRAURL -K 'PackagesDB' -b $RABASEDIR -f $PACKAGELISTFILE -p $6 + fi + fi + + INSERTRESULT=$? + if [ $INSERTRESULT -ne 0 ]; then + rm $PACKAGELISTFILE + return $INSERTRESULT + fi + + # Executing package insert script + $INSERTSCRIPT -p $PACKAGELISTFILE -d $6 -l $DBLOGFILE -z $curdist -I $4 -c $CASSANDRAURL -m $5 + + # Adding the log file name to a list of successful transactions if the insert script has been executed correctly + INSERTRESULT=$? + if [ $INSERTRESULT -eq 0 ]; then + echo $RSYNCLOGFILE >> $TRANSACTIONLOGFILE + if [[ ! -z "$7" ]]; then + cat $PACKAGELISTFILE >> $7 + fi + fi + rm $PACKAGELISTFILE + + return $INSERTRESULT +} + + +IGNOREOPT="" +DOWNLOADALLOPT="" +TARGETDIROPT="" +RECURSIVEMODE="" +RESUMEITEM=0 +KEEPDOWNLOADEDFILES=0 + +while getopts "hifa:r:d:et:m:n:c:oq:s:kl:" opt; do + case $opt in + h) + echo -e "Usage: ./update_pkgs.sh [ options ] \ + \n\nOptions: \ + \n\t -i \t\t\t ignore existent pkgs [RHEL6] \ + \n\t -f \t\t\t fetch all pkgs from RedHat [RHEL6] \ + \n\t -a \t\t fetch all pkgs related to the specified advisory [RHEL6] \ + \n\t -r \t replay the transation detailed in rsynclogfile; \ + \n\t \t\t\t must be specified in conjunction with -d \ + \n \ + \n\t -d \t specify the directory containing the pkgs to be inserted in the DB \ + \n\t -e \t\t\t process pkgs contained in the current directory and all subdirectories \ + \n\t -t \t specify the type of pkgs to be inserted [releases, updates, testing]; \ + \n \t\t\t\t (mandatory with -d option alone) \ + \n \ + \n\t -m \t\t replay a transation from the src pkgs #number \ + \n\t -n \t\t specify the distribution name (mandatory with -d option alone) \ + \n\t -q \t\t specify the distribution version (mandatory with -d option alone) \ + \n\t -s \t specify the distribution section (for Ubuntu distrubutions only) \ + \n\t -c \t\t specify the distribution architecture (mandatory with -d option alone) \ + \n\t -o \t\t\t display log messages on stdout \ + \n\t -k \t\t\t keep downloaded files" + exit + ;; + i) + IGNOREOPT="-$opt" + ;; + f) + DOWNLOADALLOPT="-$opt" + ;; + a) + ADVISORYOPT="-$opt=$OPTARG" + ;; + r) + RSYNCLOGFILE="$OPTARG" + ;; + d) + TARGETDIROPT="$OPTARG" + if [ ${TARGETDIROPT:${#TARGETDIROPT}-1} != '/' ]; then + TARGETDIROPT="${TARGETDIROPT}/" + fi + ;; + e) + RECURSIVEMODE="ON" + ;; + t) + OPERATIONTYPE="$OPTARG" + ;; + m) + RESUMEITEM="$OPTARG" + ;; + n) + DISTNAME="$OPTARG" + ;; + q) + DISTVER="$OPTARG" + ;; + s) + DISTSECTION="$OPTARG" + ;; + c) + DISTARCH="$OPTARG" + ;; + o) + DBLOGFILE="/dev/stdout" + ;; + k) + KEEPDOWNLOADEDFILES=1 + ;; + l) + LINENUMBER="$OPTARG" + ;; + esac +done + + +if [ "$TARGETDIROPT" ]; then + if [ "$RSYNCLOGFILE" ]; then + if [ ! -f "$RSYNCLOGFILE" ]; then + echo "[`date`]: error -logfilenamemissing- $RSYNCLOGFILE" >> $DBLOGFILE + exit + fi + + filename=`basename $RSYNCLOGFILE` + FIELDS=$(echo $filename | awk 'BEGIN{FS="-"} {print NF}') + if [ "$FIELDS" -ne 7 ]; then + echo "[`date`]: error -logfilenameparseerror- $RSYNCLOGFILE" >> $DBLOGFILE + exit + fi + + # Parsing fields of filename to determine distribution name, arch and the type of the update + DISTNAME=`echo $filename | cut -d '-' -f 2` + DISTVER=`echo $filename | cut -d '-' -f 3` + DISTSECTION=`echo $filename | cut -d '-' -f 4 | sed 's/+/\//g'` + DISTARCH=`echo $filename | cut -d '-' -f 5` + OPERATIONTYPE=`echo $filename | cut -d '-' -f 6` + + if [ -z $DISTNAME ] || [ -z $DISTARCH ] || [ -z $OPERATIONTYPE ] || [ -z "$DISTVER" ] || [ -z "$DISTSECTION" ]; then + echo "[`date`]: error -logfilenameparseerror- $RSYNCLOGFILE" >> $DBLOGFILE + exit + fi + KEY=$(echo "$DISTNAME-$DISTVER-$DISTSECTION-$DISTARCH-$OPERATIONTYPE" | sed 's/\//+/g') + RSYNCURL=$(echo $RSYNCLOGFILE | awk 'BEGIN{FS="/"} {print $(NF-1)}') + RSYNCEXCLUDEFILE="$LOGDIR/$RSYNCURL/exclude-$KEY.list" + else + if [ -z "$DISTNAME" ] || [ -z "$DISTARCH" ] || [ -z "$OPERATIONTYPE" ] || [ -z "$DISTVER" ]; then + echo "[`date`]: error -missingvars- DISTNAME, DISTVER, DISTARCH, OPERATIONTYPE" >> $DBLOGFILE + exit + fi + + if [ "$DISTNAME" = "Ubuntu" ] && [ -z "$DISTSECTION" ]; then + echo "[`date`]: error -missingvars- DISTSECTION" >> $DBLOGFILE + exit + fi + + RSYNCLOGFILE="$LOGDIR/rsync-$DISTNAME-$DISTVER-$DISTSECTION-$DISTARCH-$OPERATIONTYPE-$DATESUFFIX.log" + if [ -f "$RSYNCLOGFILE" ]; then + echo "[`date`]: error -logfileexists- $RSYNCLOGFILE" >> $DBLOGFILE + exit + fi + + if [ -z "$RECURSIVEMODE" ]; then + FINDOPT="-maxdepth 1" + fi + + echo "# Packages in the directory: $TARGETDIROPT" >> $RSYNCLOGFILE + for pkg in $(find $TARGETDIROPT $FINDOPT -type f); do + TARGETDIRSED="$(echo $TARGETDIROPT | sed 's/\//\\\//g')" + PKGSED="$(echo $pkg | sed 's/'$TARGETDIRSED'//')" + echo "rsync rsync rsync >f+++++++++ $PKGSED" >> $RSYNCLOGFILE + done + fi + + DIST=$DISTNAME"-"$DISTVER + db_insert $RSYNCLOGFILE $DIST $DISTARCH $OPERATIONTYPE $RESUMEITEM $TARGETDIROPT $RSYNCEXCLUDEFILE +else + CURRENTLINE=0 + while read DISTNAME DISTVER DISTSECTION DISTARCH DOWNLOADMETHOD RSYNCUSER RSYNCURL RSYNCDIR TARGETDIR OPERATIONTYPE; do + (( CURRENTLINE++ )) + + if [[ $DISTNAME == \#* ]]; then + continue + fi + + if [ ! -z "$LINENUMBER" ] && [ "$CURRENTLINE" -ne "$LINENUMBER" ]; then + continue + fi + + KEY=$(echo "$DISTNAME-$DISTVER-$DISTSECTION-$DISTARCH-$OPERATIONTYPE" | sed 's/\//+/g') + RSYNCLOGFILE="$LOGDIR/$RSYNCURL/rsync-$KEY-$DATESUFFIX.log" + RSYNCEXCLUDEFILE="$LOGDIR/$RSYNCURL/exclude-$KEY.list" + + if [ ! -e "$LOGDIR/$RSYNCURL" ]; then + mkdir -p $LOGDIR/$RSYNCURL + fi + + if [ ! -f "$RSYNCLOGFILE" ]; then + touch $RSYNCLOGFILE + fi + INCLUDE_OPT="$(echo $DISTSECTION | awk 'BEGIN{FS="/"} {printf("--include ./ "); for (i=1; i<=NF;i++) {printf("--include "); for (j=1;j<=i;j++) {printf("%s/", $j)} printf(" ")}}')" + if [[ -f $RSYNCEXCLUDEFILE ]]; then + EXCLUDE_OPT="--exclude-from $RSYNCEXCLUDEFILE" + else + EXCLUDE_OPT="" + fi + + case "$DISTNAME" in + Fedora|CentOS|EPEL) + # Synchronizing the update directory + if [ "$RSYNCURL" != "NORSYNC" ]; then + rsync -vaHz --numeric-ids --delay-updates --no-motd --log-file=$RSYNCLOGFILE \ + $EXCLUDE_OPT $INCLUDE_OPT --include "$DISTSECTION/*.rpm" --include "$DISTSECTION/[0-9,a-z]/" --include "$DISTSECTION/[0-9,a-z]/*.rpm" \ + --exclude "*" $DOWNLOADMETHOD://$RSYNCURL/$RSYNCDIR $TARGETBASEDIR/$TARGETDIR + + # Testing the exit status of rsync + if [ $? -ne 0 ]; then + echo "[`date`]: error -rsyncerror- $RSYNCURL" >> $DBLOGFILE + exit + fi + fi + ;; + Ubuntu) + DISTEXTRAPATHINDEX=$(expr index $DISTVER "\+") + DISTEXTRAPATH="" + if [ "$DISTEXTRAPATHINDEX" -ne 0 ]; then + DISTEXTRAPATH=${DISTVER:$DISTEXTRAPATHINDEX} + DISTVER=${DISTVER:0:$[$DISTEXTRAPATHINDEX-1]} + fi + + if [ "$OPERATIONTYPE" != "newpackage" ] && [ "$OPERATIONTYPE" != "testing" ]; then + DISTPARAM=""$DISTVER"-"$OPERATIONTYPE + else + DISTPARAM=""$DISTVER + fi + + if [ ! -z "$DISTEXTRAPATH" ]; then + DISTPARAM=$DISTPARAM/$DISTEXTRAPATH + fi + + if [ "$DOWNLOADMETHOD" = "http" ]; then + debmirror --debug --rsync-extra=none --host=$RSYNCURL --root=$RSYNCDIR --method=$DOWNLOADMETHOD --dist=$DISTPARAM \ + --section=$DISTSECTION --arch=$DISTARCH --user=$RSYNCUSER --nosource --no-check-gpg $TARGETBASEDIR/$TARGETDIR | \ + awk '$1 ~ /^http/ {pos=match($1, /pool/); if (pos > 0) {pool_path=substr($1, pos); + printf("rsync rsync rsync >f+++++++++ %s\n", pool_path)}}' > $RSYNCLOGFILE + else + debmirror --section=$DISTSECTION --dist=$DISTPARAM --arch=$DISTARCH \ + --rsync-option="--log-file=$RSYNCLOGFILE --partial -aL -r -v $EXCLUDE_OPT" \ + --host=$RSYNCURL --root=$RSYNCDIR $RSYNCUSEROPT --user=$RSYNCUSER --nosource --nocleanup --progress \ + --ignore-small-errors --ignore-release-gpg --method=$DOWNLOADMETHOD $TARGETBASEDIR/$TARGETDIR + fi + ;; + esac + + DIST=$DISTNAME"-"$DISTVER + db_insert $RSYNCLOGFILE $DIST $DISTARCH $OPERATIONTYPE $RESUMEITEM $TARGETBASEDIR/$TARGETDIR $RSYNCEXCLUDEFILE + if [[ $? -eq 0 ]] && [[ $KEEPDOWNLOADEDFILES -eq 0 ]]; then + rm -Rf $TARGETBASEDIR/$TARGETDIR/$DISTSECTION + fi + done < $FILELIST +fi diff --git a/db/scripts/utils.py b/db/scripts/utils.py new file mode 100644 index 0000000..bdf1255 --- /dev/null +++ b/db/scripts/utils.py @@ -0,0 +1,110 @@ +# utils.py: some useful functions +# +# Copyright (C) 2014 Politecnico di Torino, Italy +# TORSEC group -- http://security.polito.it +# +# Author: Roberto Sassu +# Tao Su +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library. If not, see +# . + +import os +import rpm +from subprocess import Popen, PIPE +from datetime import datetime, timedelta, date + + +def get_rpm_header(rpm_file): + fdno = os.open(rpm_file, os.O_RDONLY) + ts = rpm.TransactionSet() + ts.setVSFlags(rpm._RPMVSF_NOSIGNATURES) + hdr = ts.hdrFromFdno(fdno) + os.close(fdno) + return hdr + + +def get_pkg_list(pkg_base_dir, pkgs_list): + result = [] + fd = open(pkgs_list, 'r') + for package in fd.readlines(): + if len(package) == 0: + continue + + package = package.strip() + if len(pkg_base_dir) != 0: + package_path = "%s/%s" %(pkg_base_dir, package) + else: + package_path = package + + result.append(package_path) + + return result + + +def get_epoch_dict(pkg_base_dir, pkgs_list): + epoch_dict = {} + for pkg in get_pkg_list(pkg_base_dir, pkgs_list): + rpm_hdr = get_rpm_header(pkg) + srpm = rpm_hdr[rpm.RPMTAG_SOURCERPM] + srpm_key = '.'.join(srpm.split('.')[:-2]) + pkg_key = '.'.join(os.path.basename(pkg).split('.')[:-2]) + + epoch_str = '' + if rpm_hdr[rpm.RPMTAG_EPOCH] is not None: + epoch_str = str(rpm_hdr[rpm.RPMTAG_EPOCH]) + + if srpm_key not in epoch_dict or srpm_key == pkg_key: + epoch_dict[srpm_key] = epoch_str + + return epoch_dict + + +def get_date_pushed_interval(pkg_base_dir, pkgs_list): + last_date_submitted = None + first_date_submitted = None + + for pkg in get_pkg_list(pkg_base_dir, pkgs_list): + timestamp = os.path.getmtime(pkg) + pkg_mtime = datetime.fromtimestamp(timestamp) + if last_date_submitted is None or pkg_mtime > last_date_submitted: + last_date_submitted = pkg_mtime + if first_date_submitted is None or pkg_mtime < first_date_submitted: + first_date_submitted = pkg_mtime + + # usually updates are announced 1 day after a pkg is uploaded + delta = timedelta(days=3) + last_date_submitted += delta + first_date_submitted -= delta + + return (datetime.strftime(last_date_submitted, '%Y-%m-%d %H:%M:%S'), + datetime.strftime(first_date_submitted, '%Y-%m-%d %H:%M:%S')) + + +def date_is_older(date_a, date_b): + a = datetime.strptime(date_a, '%Y-%m-%d %H:%M:%S') + b = datetime.strptime(date_b, '%Y-%m-%d %H:%M:%S') + return a <= b + + +def get_pkg_datetime(pkg_base_dir, pkgs_list, requested_pkg): + for pkg in get_pkg_list(pkg_base_dir, pkgs_list): + rpm_hdr = get_rpm_header(pkg) + srpm = rpm_hdr[rpm.RPMTAG_SOURCERPM] + if srpm != requested_pkg: + continue + + return datetime.fromtimestamp(os.path.getmtime(pkg)) + + return None diff --git a/ram/analysis.py b/ram/analysis.py new file mode 100644 index 0000000..a330efa --- /dev/null +++ b/ram/analysis.py @@ -0,0 +1,102 @@ +''' +The MIT License (MIT) + +Copyright (c) 2015 Tao Su + Paolo Smiraglia + TORSEC Group (http://security.polito.it) + Politecnico di Torino + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +''' + +import config as cfg +from logger import general_log as LOG +import db +import datetime +import json + +def _get_new_req_id(host): + r = oat.issuePostAttestation(cfg.OAT_VERIFIER, host, cfg.OAT_LEVEL) + LOG.debug('issuePostAttestation:' + json.dumps(r)) + new_id = r['requestId'] + if new_id is None: + LOG.warning("Something goes wrong id requesting " + "new requestId for host '%s'" % host) + else: + LOG.info("Saving new requestId (%s) for host '%s'" % (new_id, host)) + db.save_req_id(host, new_id) + + +def _get_attestation_result(host, req_id): + r = oat.issuePostAttestationResult(cfg.OAT_VERIFIER, req_id) + LOG.debug('issuePostAttestationResult:' + json.dumps(r)) + if 'hosts' in r: + LOG.info("Found valid attestation result for host '%s'" % host) + return r['hosts'] + else: + LOG.info(("Valid attestation result not available for host '%s'") % + (host)) + return None + +def _get_result_level(host): + unknown_log_dir = "/var/www/html/OAT/unknown_log"; + reportID = db.getReportID(host); + logName = "%s/unknown_log_%s" % (unknown_log_dir,reportID['id']); + logFile = open(logName, 'r'); + res_level = 4; + + for line in logFile: + if 'Info: load) level' in line: + image = line.split(' '); + res_level = image[3]; + break; + return res_level; + +def do_analysis(hosts=[], cert="", req_level=1): + results = [] + for host in hosts: + LOG.info("Trying to get valid attestation result for host '%s'" % host) + + result = db.getAttestationResult(host) + if not result : + LOG.info("No information of for host '%s'" %(host)) + _r = dict( + host_name=host, + trust_lvl='unknown' + ) + else: + LOG.info("Found result for '%s'" %(host)) + _r = dict( + host_name=result['host_name'], + ) + res_level = _get_result_level(host); + if cert != result['analysis_request'].split(",")[2].split("=")[1]: + _r['trust_lvl'] = "cert-err" + elif datetime.datetime.now() - result['validate_time'] > datetime.timedelta(seconds=30): + _r['trust_lvl'] = "vtime-err" + elif (result['analysis_results'] != None and '|true|' in result['analysis_results'] and "|ANALYSIS_COMPLETED|0|" in result['analysis_results']) or (req_level<=res_level) : + _r['trust_lvl'] = "trusted" + else: + _r['trust_lvl'] = 'untrusted' + _r['validate_time'] = str(result['validate_time']) + _r['analysis_request'] = result['analysis_request'] + + results.append(_r) + + return results diff --git a/ram/celeryconfig.py b/ram/celeryconfig.py new file mode 100644 index 0000000..7ebb054 --- /dev/null +++ b/ram/celeryconfig.py @@ -0,0 +1,10 @@ +from datetime import timedelta +import config as cfg + +CELERYBEAT_SCHEDULE = { + 'add-every-15-seconds': { + 'task': 'tasks.pollhostsCheckCert', + 'schedule': timedelta(seconds=15), + 'args': (cfg.OAT_VERIFIER, cfg.OAT_NODE, cfg.OAT_LEVEL), + }, +} diff --git a/ram/config.py b/ram/config.py new file mode 100644 index 0000000..cb32155 --- /dev/null +++ b/ram/config.py @@ -0,0 +1,52 @@ +''' +The MIT License (MIT) + +Copyright (c) 2015 Tao Su + TORSEC Group (http://security.polito.it) + Politecnico di Torino + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +''' + +BASE_DIR = '/home/tao/ram' + + +STATIC_PATH= '%s/html/' % BASE_DIR +DB_PATH = '%s/data/mw.db' % BASE_DIR + +DB_HOST = 'verifier' +DB_USER = 'secured' + + +WEBAPP_PORT = 8899 +WEBAPP_ADDRESS = 'verifier' +WEBAPP_AS_DAEMON = False + +OAT_CERT = '%s/data/certfile.cer' % BASE_DIR +OAT_PERIOD = 60000 +OAT_NODE = ['ned1','ned2'] +OAT_EXPIRATION = '1d' +OAT_VERIFIER = 'verifier' +OAT_LEVEL = 'l_req=l4_ima_all_ok|>=' +OAT_WAITTIME = 8 + + +# accepted values: debug, info, warn, err +LOG_LEVEL = 'debug' +LOG_DIR = '%s/logs' % BASE_DIR diff --git a/ram/data/certfile.cer b/ram/data/certfile.cer new file mode 100644 index 0000000..415d7df --- /dev/null +++ b/ram/data/certfile.cer @@ -0,0 +1,56 @@ +CONNECTED(00000003) +--- +Certificate chain + 0 s:/C=US/O=U.S. Government/OU=DoD/CN=verifier + i:/C=US/O=U.S. Government/OU=DoD/CN=verifier +--- +Server certificate +-----BEGIN CERTIFICATE----- +MIIDYzCCAkugAwIBAgIJAKE9rSaFjBBRMA0GCSqGSIb3DQEBCwUAMEgxCzAJBgNV +BAYTAlVTMRgwFgYDVQQKDA9VLlMuIEdvdmVybm1lbnQxDDAKBgNVBAsMA0RvRDER +MA8GA1UEAwwIdmVyaWZpZXIwHhcNMTQxMjE3MTU0OTQ5WhcNMTYxMjE2MTU0OTQ5 +WjBIMQswCQYDVQQGEwJVUzEYMBYGA1UECgwPVS5TLiBHb3Zlcm5tZW50MQwwCgYD +VQQLDANEb0QxETAPBgNVBAMMCHZlcmlmaWVyMIIBIjANBgkqhkiG9w0BAQEFAAOC +AQ8AMIIBCgKCAQEAoqTIktDRjDZhedtMhazpOADcoE8K7iheBDf2lbFqQBP8ZMxP +v/De0PoGqreuzl3zt1n0EEAfboklwQg8Dchk3HuWsTSYFPu0HXQb5dlGAcsxI1MK +raSH73O8HBGQkpbb5U8FlVBUKXknGo0ISfde+NeKJ85H7GF1aokGxtbESnffkAvW +C8UKMvwNZMB+j11ZR90P7maPIEbSKzSRnddUX85Gs5wAB1GhPoBRkIKUvLEGmIxZ +1hTBqEqwy2Epr+VkecOG41Lx4DNz3U5GRt6cSal3ZpG/5odS6EfJ+BciFeQm5386 +x4m+GtzvuiBK6g2OkHDDb+5LSLqQaxyCh5RD5QIDAQABo1AwTjAdBgNVHQ4EFgQU +m0ETQm5kXuJrS6VPgyWnqSieyJUwHwYDVR0jBBgwFoAUm0ETQm5kXuJrS6VPgyWn +qSieyJUwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAfJjVsyMIvhR3 +8hhb0Z8EE+AcKzsAQ148ZSbjJHdYKY1UAIkudH9JT50xA9+T7ul7Rq5hBaROZAPb +Bh27k7hJhe+Lr6jvg04fmvgbvTsIDjhxEUIR1axhtcvgXQHGF2hJf54aVZ8Cib82 +TSih6/4kisKeNnqDMncse0DgWue0aA0ar+LIElhzTkI5es+z75RGjQlge9wIbP+p +RR0chUiCojxjX1VPkwxxvEa2+YaBQTeDTcoBHBYB1eAOJ/4X/G8Y6SbCgdhXC5qu +ivrN+ylaWUlARAZfy8wmRXFWf93cHXyx94VWVbmy13I0gUy14im4SDZEmx10KMQm +dduO20ILdw== +-----END CERTIFICATE----- +subject=/C=US/O=U.S. Government/OU=DoD/CN=verifier +issuer=/C=US/O=U.S. Government/OU=DoD/CN=verifier +--- +Acceptable client certificate CA names +/C=US/O=U.S. Government/OU=DoD/CN=verifier +Server Temp Key: DH, 768 bits +--- +SSL handshake has read 1715 bytes and written 295 bytes +--- +New, TLSv1/SSLv3, Cipher is DHE-RSA-AES256-SHA +Server public key is 2048 bit +Secure Renegotiation IS supported +Compression: NONE +Expansion: NONE +SSL-Session: + Protocol : TLSv1.2 + Cipher : DHE-RSA-AES256-SHA + Session-ID: 55AD2609EE5399A8AB1C1CD6FF39A7879FA02103A338D8C4631979A03AD69DAC + Session-ID-ctx: + Master-Key: 64BC0A66AA798D321DDE1FE5DD362716BE1CD9B35EDD8100D0963F927030DB0FFEA32B7FD488B57D2601B99AB42C0933 + Key-Arg : None + Krb5 Principal: None + PSK identity: None + PSK identity hint: None + Start Time: 1437410825 + Timeout : 300 (sec) + Verify return code: 18 (self signed certificate) +--- diff --git a/ram/data/myserver.crt b/ram/data/myserver.crt new file mode 100644 index 0000000..01a7038 --- /dev/null +++ b/ram/data/myserver.crt @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE----- +MIICQTCCAaoCCQDhXXP4nJmM3TANBgkqhkiG9w0BAQUFADBlMQswCQYDVQQGEwJJ +VDERMA8GA1UECAwIUGllbW9udGUxDjAMBgNVBAcMBVR1cmluMQ8wDQYDVQQKDAZQ +T0xJVE8xDzANBgNVBAsMBlBPTElUTzERMA8GA1UEAwwIdmVyaWZpZXIwHhcNMTUx +MDI4MTUyMTQxWhcNMTYxMDI3MTUyMTQxWjBlMQswCQYDVQQGEwJJVDERMA8GA1UE +CAwIUGllbW9udGUxDjAMBgNVBAcMBVR1cmluMQ8wDQYDVQQKDAZQT0xJVE8xDzAN +BgNVBAsMBlBPTElUTzERMA8GA1UEAwwIdmVyaWZpZXIwgZ8wDQYJKoZIhvcNAQEB +BQADgY0AMIGJAoGBAJat0hcvlGtf3U3R3XWxn2qn/tW6ywOoV+6PtCRpWk4ZQNKj +QYIJFap6XM9otuKJKM3O20S0cnMN/LI/Yc4QNrlhZY9R0g2hepkZ9+jcsgfBWogU +YvwkJJ+L/6Ps+7jlBqXd8Un6OWXxoq26YKGaPEgOV7hzNhfG2n5vgvJfw8X5AgMB +AAEwDQYJKoZIhvcNAQEFBQADgYEARoWaRRXrVx0oEOkRKbonf5abnR5rwLNL4nj+ +y0OI1KdRQPEcMn6E08F1yp3A1FDYma1DR8563MekUaZyvtqUqONSh495JiF0+QAX +E2yrGPyGo6dggeyn8EKeqLZ5BEhjUfp6q6wIDd5hHz5dNHGwDLDNyrr8l6vvTkR+ +z8gXSmU= +-----END CERTIFICATE----- diff --git a/ram/data/myserver.csr b/ram/data/myserver.csr new file mode 100644 index 0000000..ccbc56e --- /dev/null +++ b/ram/data/myserver.csr @@ -0,0 +1,11 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIIBpTCCAQ4CAQAwZTELMAkGA1UEBhMCSVQxETAPBgNVBAgMCFBpZW1vbnRlMQ4w +DAYDVQQHDAVUdXJpbjEPMA0GA1UECgwGUE9MSVRPMQ8wDQYDVQQLDAZQT0xJVE8x +ETAPBgNVBAMMCHZlcmlmaWVyMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCW +rdIXL5RrX91N0d11sZ9qp/7VussDqFfuj7QkaVpOGUDSo0GCCRWqelzPaLbiiSjN +zttEtHJzDfyyP2HOEDa5YWWPUdINoXqZGffo3LIHwVqIFGL8JCSfi/+j7Pu45Qal +3fFJ+jll8aKtumChmjxIDle4czYXxtp+b4LyX8PF+QIDAQABoAAwDQYJKoZIhvcN +AQELBQADgYEASvSybo/etSaTqzuZa5lwKxYFAeuWHOogIEG6M1VZXHvBd0XrlYT2 +Nq6m9YSXAfEr7294StYfNDJf7qHZ953XOphIaYAGYKUaHfuu4TUmggQGpxiryZeR +QYsQrCsYW5R/jZw1SGa356Ow3fF3+W2/fEI+8DYOnVg7S02VIYhF2nE= +-----END CERTIFICATE REQUEST----- diff --git a/ram/data/myserver.key b/ram/data/myserver.key new file mode 100644 index 0000000..c577b8b --- /dev/null +++ b/ram/data/myserver.key @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXAIBAAKBgQCWrdIXL5RrX91N0d11sZ9qp/7VussDqFfuj7QkaVpOGUDSo0GC +CRWqelzPaLbiiSjNzttEtHJzDfyyP2HOEDa5YWWPUdINoXqZGffo3LIHwVqIFGL8 +JCSfi/+j7Pu45Qal3fFJ+jll8aKtumChmjxIDle4czYXxtp+b4LyX8PF+QIDAQAB +AoGAHqurBAUvVNvilCCPz5EkPfWMLb0j7c6qd2jQ5kh7lUIWq8mHYAyxWE4n7iAG +ef4pTBs7DrUcRscmFLJKGkO6n5l3x0pPQUCU01Lh8tTUGa4D8RzgPzMJybc7AKF5 +51dUdO+ShxLcB1S5NFfU5YAL2yvgRvsuM7Bq+d6oyShNMgECQQDH25KJzT37+fwb +UA6GbNKmSuUkuj4/hOzRINWXh9lkn87MOciFHKeI4uxA5Idg8rkG/4jveZmkl2Bw +CWVFEB2JAkEAwQGk7Qu6Yvypb4wvkNwmQAdwkJon1nsRgtIQ9CWjJKzrGnpaSEz8 +HHAOhfkfHlFnRXSIVpPoUlcvUI+V1ZI48QJAGXqZpO3AgDYveL/tCiAnfsG/kr4X +n3tvwX2BHW9ZPKXO9GRNdwLfLOlZGzDHPYnUIttC9ty2xK/zwHTCL1rNmQJAMRWU +9wADj8cH5Cl3s1R5mdEKjIvX09EKnAWGcEDeI6aiR+KT8U061JSe7O11P4WeSOig +/7uv2rj3fHp3tY/xUQJBAKutpME6+teZfyYeTMUsLDOXCjTReyRvURgIxS9hVfaN ++zEqsVJbSgJoTKn0KH0DbxnhshBweywBByeDvX6w13w= +-----END RSA PRIVATE KEY----- diff --git a/ram/data/myserver.key.org b/ram/data/myserver.key.org new file mode 100644 index 0000000..c577b8b --- /dev/null +++ b/ram/data/myserver.key.org @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXAIBAAKBgQCWrdIXL5RrX91N0d11sZ9qp/7VussDqFfuj7QkaVpOGUDSo0GC +CRWqelzPaLbiiSjNzttEtHJzDfyyP2HOEDa5YWWPUdINoXqZGffo3LIHwVqIFGL8 +JCSfi/+j7Pu45Qal3fFJ+jll8aKtumChmjxIDle4czYXxtp+b4LyX8PF+QIDAQAB +AoGAHqurBAUvVNvilCCPz5EkPfWMLb0j7c6qd2jQ5kh7lUIWq8mHYAyxWE4n7iAG +ef4pTBs7DrUcRscmFLJKGkO6n5l3x0pPQUCU01Lh8tTUGa4D8RzgPzMJybc7AKF5 +51dUdO+ShxLcB1S5NFfU5YAL2yvgRvsuM7Bq+d6oyShNMgECQQDH25KJzT37+fwb +UA6GbNKmSuUkuj4/hOzRINWXh9lkn87MOciFHKeI4uxA5Idg8rkG/4jveZmkl2Bw +CWVFEB2JAkEAwQGk7Qu6Yvypb4wvkNwmQAdwkJon1nsRgtIQ9CWjJKzrGnpaSEz8 +HHAOhfkfHlFnRXSIVpPoUlcvUI+V1ZI48QJAGXqZpO3AgDYveL/tCiAnfsG/kr4X +n3tvwX2BHW9ZPKXO9GRNdwLfLOlZGzDHPYnUIttC9ty2xK/zwHTCL1rNmQJAMRWU +9wADj8cH5Cl3s1R5mdEKjIvX09EKnAWGcEDeI6aiR+KT8U061JSe7O11P4WeSOig +/7uv2rj3fHp3tY/xUQJBAKutpME6+teZfyYeTMUsLDOXCjTReyRvURgIxS9hVfaN ++zEqsVJbSgJoTKn0KH0DbxnhshBweywBByeDvX6w13w= +-----END RSA PRIVATE KEY----- diff --git a/ram/db.py b/ram/db.py new file mode 100644 index 0000000..4db68c1 --- /dev/null +++ b/ram/db.py @@ -0,0 +1,178 @@ +''' +The MIT License (MIT) + +Copyright (c) 2015 Tao Su + Paolo Smiraglia + TORSEC Group (http://security.polito.it) + Politecnico di Torino + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +''' + +import config as cfg +import mysql.connector as mariadb + + +from logger import general_log as LOG + + +def __db_connect(): + try: + mariadb_connection = mariadb.connect(host=cfg.DB_HOST, user=cfg.DB_USER, password='secured', database= 'oat_db'); + except Exception, ex: + errMessage = 'error, connection to the database error - %s\n' % (ex); + LOG.info(errMessage) + return mariadb_connection + + +def _c_req_id(host, id): + conn = __db_connect() + c = conn.cursor() + q = "INSERT INTO req_id VALUES (?,?)" + c.execute(q, (host, id,)) + conn.commit() + conn.close() + + +def _r_req_id(host): + conn = __db_connect() + c = conn.cursor() + q = "SELECT * FROM req_id WHERE host==?" + c.execute(q, (host,)) + row = c.fetchone() + conn.close() + return row + + +def _u_req_id(host, id): + conn = __db_connect() + c = conn.cursor() + q = "UPDATE req_id SET req_id=? WHERE host=?" + c.execute(q, (id, host,)) + conn.commit() + conn.close() + + +def _d_req_id(host): + conn = __db_connect() + c = conn.cursor() + q = "DELETE FROM req_id WHERE host=?" + c.execute(q, (host,)) + conn.commit() + conn.close() + + +def init_db(): + conn = __db_connect() + c = conn.cursor() + # dropping existing table + q = 'DROP TABLE IF EXISTS req_id' + c.execute(q) + LOG.info("dropping table 'req_id'") + conn.commit() + # creating a new table + q = '''CREATE TABLE IF NOT EXISTS req_id + (host TEXT PRIMARY KEY, req_id TEXT)''' + c.execute(q) + LOG.info("creating table 'req_id'") + conn.commit() + conn.close() + + +def save_req_id(host, id): + r = _r_req_id(host) + if r is None: + _c_req_id(host, id) + else: + _u_req_id(host, id) + + +def load_req_id(host): + r = _r_req_id(host) + if r is None: + return None + else: + return r[1] + + +def getHostCertDGST(host): + conn = __db_connect() + cursor = conn.cursor() + + getCertDGSTCommand= "select HOST_NAME, DESCRIPTION from HOST where HOST_NAME='%s';" % (host); + + try : + cursor.execute(getCertDGSTCommand); + except Exception as e: + message = "error - noresultavailableinDB - %s \n" %(e); + print message; + LOG.info(message); + sys.exit(1) + + certDigest = {}; + for HOST_NAME, DESCRIPTION in cursor: + certDigest['host_name'] = HOST_NAME; + certDigest['cert_digest'] = DESCRIPTION; + return certDigest + +def getReportID(host): + # this is the right approach, need to check the ned's id before giving back the result + conn = __db_connect() + cursor = conn.cursor() + reportID = {}; + + getReportIDCommand= "select id, machine_name from audit_log where machine_name='%s' ORDER BY id DESC LIMIT 1;" % (host); + try : + cursor.execute(getReportIDCommand); + except Exception as e: + message = "error - noresultavailableinDB - %s \n" %(e); + print message; + LOG.info(message); + sys.exit(1) + + for id, machine_name in cursor: + reportID['id'] = id; + reportID['host_name'] = machine_name; + + return reportID + + +def getAttestationResult(host): + conn = __db_connect() + cursor = conn.cursor() + + getResultCommand= "select host_name, analysis_request, analysis_results, validate_time, expiration_time from attest_request where host_name='%s' ORDER BY validate_time DESC LIMIT 1;" % (host); + + try : + cursor.execute(getResultCommand); + except Exception as e: + message = "error - noresultavailableinDB - %s \n" %(e); + print message; + LOG.info(message); + sys.exit(1) + + attestResult = {} + for host_name, analysis_request, analysis_results, validate_time, expiration_time in cursor: + attestResult['host_name'] = host_name; + attestResult['analysis_request'] = analysis_request; + attestResult['analysis_results'] = analysis_results; + attestResult['validate_time'] = validate_time; + attestResult['expiration_time'] = expiration_time; + + return attestResult diff --git a/ram/html/static/css/img/secured_logo.png b/ram/html/static/css/img/secured_logo.png new file mode 100644 index 0000000..4511eaf Binary files /dev/null and b/ram/html/static/css/img/secured_logo.png differ diff --git a/ram/html/static/css/screen.css b/ram/html/static/css/screen.css new file mode 100644 index 0000000..c0af9ba --- /dev/null +++ b/ram/html/static/css/screen.css @@ -0,0 +1,62 @@ +/* GLOBAL STYLES */ +* { +margin:0; +padding:0; +font-family: Arial, Helvetica, sans-serif; +} + +html { +background-color: while; +} + +body { +/* background-image: url("img/secured_logo.png");*/ +background-repeat: no-repeat; +background-size: cover; +} + +div.error { + position: absolute; + top: 80px; + left: 200px; + width: 2000px; + height: 1000px; + color:red; + font-size: 160%; +} + + +div.general { + position: absolute; + top: 80px; + width: 1000px; + left: 200px; + height: 200px; + /*border-style: solid; + border-width: 5px;*/ +} + +div.trusted { + position: absolute; + left: 200px; + top: 350px; + color:green; + font-size: 300%; +} + +div.full { + position: absolute; + left: 200px; + top: 550px; + color:black; + font-size: 200%; +} + +img { + /*position: fixed;*/ + position: relative; + left: 1000px; + /*top: 80px;*/ + width: 400px; + height: 350px; +} diff --git a/ram/html/static/scripts/jquery.js b/ram/html/static/scripts/jquery.js new file mode 100644 index 0000000..d4b67f7 --- /dev/null +++ b/ram/html/static/scripts/jquery.js @@ -0,0 +1,10308 @@ +/*! + * jQuery JavaScript Library v1.11.1 + * http://jquery.com/ + * + * Includes Sizzle.js + * http://sizzlejs.com/ + * + * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-05-01T17:42Z + */ + +(function( global, factory ) { + + if ( typeof module === "object" && typeof module.exports === "object" ) { + // For CommonJS and CommonJS-like environments where a proper window is present, + // execute the factory and get jQuery + // For environments that do not inherently posses a window with a document + // (such as Node.js), expose a jQuery-making factory as module.exports + // This accentuates the need for the creation of a real window + // e.g. var jQuery = require("jquery")(window); + // See ticket #14549 for more info + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Can't do this because several apps including ASP.NET trace +// the stack via arguments.caller.callee and Firefox dies if +// you try to trace through "use strict" call chains. (#13335) +// Support: Firefox 18+ +// + +var deletedIds = []; + +var slice = deletedIds.slice; + +var concat = deletedIds.concat; + +var push = deletedIds.push; + +var indexOf = deletedIds.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var support = {}; + + + +var + version = "1.11.1", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }, + + // Support: Android<4.1, IE<9 + // Make sure we trim BOM and NBSP + rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, + + // Matches dashed string for camelizing + rmsPrefix = /^-ms-/, + rdashAlpha = /-([\da-z])/gi, + + // Used by jQuery.camelCase as callback to replace() + fcamelCase = function( all, letter ) { + return letter.toUpperCase(); + }; + +jQuery.fn = jQuery.prototype = { + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // Start with an empty selector + selector: "", + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + return num != null ? + + // Return just the one element from the set + ( num < 0 ? this[ num + this.length ] : this[ num ] ) : + + // Return all the elements in a clean array + slice.call( this ); + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + ret.context = this.context; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + // (You can seed the arguments with an array of args, but this is + // only used internally.) + each: function( callback, args ) { + return jQuery.each( this, callback, args ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map(this, function( elem, i ) { + return callback.call( elem, i, elem ); + })); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: deletedIds.sort, + splice: deletedIds.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var src, copyIsArray, copy, name, options, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + isWindow: function( obj ) { + /* jshint eqeqeq: false */ + return obj != null && obj == obj.window; + }, + + isNumeric: function( obj ) { + // parseFloat NaNs numeric-cast false positives (null|true|false|"") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0; + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + isPlainObject: function( obj ) { + var key; + + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call(obj, "constructor") && + !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Support: IE<9 + // Handle iteration over inherited properties before own properties. + if ( support.ownLast ) { + for ( key in obj ) { + return hasOwn.call( obj, key ); + } + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + for ( key in obj ) {} + + return key === undefined || hasOwn.call( obj, key ); + }, + + type: function( obj ) { + if ( obj == null ) { + return obj + ""; + } + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call(obj) ] || "object" : + typeof obj; + }, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && jQuery.trim( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + // args is for internal usage only + each: function( obj, callback, args ) { + var value, + i = 0, + length = obj.length, + isArray = isArraylike( obj ); + + if ( args ) { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } + } + + return obj; + }, + + // Support: Android<4.1, IE<9 + trim: function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArraylike( Object(arr) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + var len; + + if ( arr ) { + if ( indexOf ) { + return indexOf.call( arr, elem, i ); + } + + len = arr.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in arr && arr[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + while ( j < len ) { + first[ i++ ] = second[ j++ ]; + } + + // Support: IE<9 + // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) + if ( len !== len ) { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, + i = 0, + length = elems.length, + isArray = isArraylike( elems ), + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var args, proxy, tmp; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + now: function() { + return +( new Date() ); + }, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +}); + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +function isArraylike( obj ) { + var length = obj.length, + type = jQuery.type( obj ); + + if ( type === "function" || jQuery.isWindow( obj ) ) { + return false; + } + + if ( obj.nodeType === 1 && length ) { + return true; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v1.10.19 + * http://sizzlejs.com/ + * + * Copyright 2013 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-04-18 + */ +(function( window ) { + +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + -(new Date()), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // General-purpose constants + strundefined = typeof undefined, + MAX_NEGATIVE = 1 << 31, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf if we can't use a native one + indexOf = arr.indexOf || function( elem ) { + var i = 0, + len = this.length; + for ( ; i < len; i++ ) { + if ( this[i] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + // http://www.w3.org/TR/css3-syntax/#characters + characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + + // Loosely modeled on CSS identifier characters + // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors + // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = characterEncoding.replace( "w", "w#" ), + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + + "*\\]", + + pseudos = ":(" + characterEncoding + ")(?:\\((" + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + characterEncoding + ")" ), + "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + rescape = /'|\\/g, + + // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox<24 + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + high < 0 ? + // BMP codepoint + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }; + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var match, elem, m, nodeType, + // QSA vars + i, groups, old, nid, newContext, newSelector; + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + + context = context || document; + results = results || []; + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { + return []; + } + + if ( documentIsHTML && !seed ) { + + // Shortcuts + if ( (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document (jQuery #6963) + if ( elem && elem.parentNode ) { + // Handle the case where IE, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; + } + } + + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // QSA path + if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + nid = old = expando; + newContext = context; + newSelector = nodeType === 9 && selector; + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + groups = tokenize( selector ); + + if ( (old = context.getAttribute("id")) ) { + nid = old.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", nid ); + } + nid = "[id='" + nid + "'] "; + + i = groups.length; + while ( i-- ) { + groups[i] = nid + toSelector( groups[i] ); + } + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; + newSelector = groups.join(","); + } + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch(qsaError) { + } finally { + if ( !old ) { + context.removeAttribute("id"); + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {Function(string, Object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key + " " ] = value); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ +function assert( fn ) { + var div = document.createElement("div"); + + try { + return !!fn( div ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( div.parentNode ) { + div.parentNode.removeChild( div ); + } + // release memory in IE + div = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = attrs.length; + + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + ( ~b.sourceIndex || MAX_NEGATIVE ) - + ( ~a.sourceIndex || MAX_NEGATIVE ); + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Checks a node for validity as a Sizzle context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== strundefined && context; +} + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Detects XML nodes + * @param {Element|Object} elem An element or a document + * @returns {Boolean} True iff elem is a non-HTML XML node + */ +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var hasCompare, + doc = node ? node.ownerDocument || node : preferredDoc, + parent = doc.defaultView; + + // If no document and documentElement is available, return + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Set our document + document = doc; + docElem = doc.documentElement; + + // Support tests + documentIsHTML = !isXML( doc ); + + // Support: IE>8 + // If iframe document is assigned to "document" variable and if iframe has been reloaded, + // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 + // IE6-8 do not support the defaultView property so parent will be undefined + if ( parent && parent !== parent.top ) { + // IE11 does not have attachEvent, so all must suffer + if ( parent.addEventListener ) { + parent.addEventListener( "unload", function() { + setDocument(); + }, false ); + } else if ( parent.attachEvent ) { + parent.attachEvent( "onunload", function() { + setDocument(); + }); + } + } + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) + support.attributes = assert(function( div ) { + div.className = "i"; + return !div.getAttribute("className"); + }); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert(function( div ) { + div.appendChild( doc.createComment("") ); + return !div.getElementsByTagName("*").length; + }); + + // Check if getElementsByClassName can be trusted + support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) { + div.innerHTML = "

    "; + + // Support: Safari<4 + // Catch class over-caching + div.firstChild.className = "i"; + // Support: Opera<10 + // Catch gEBCN failure to find non-leading classes + return div.getElementsByClassName("i").length === 2; + }); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert(function( div ) { + docElem.appendChild( div ).id = expando; + return !doc.getElementsByName || !doc.getElementsByName( expando ).length; + }); + + // ID find and filter + if ( support.getById ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== strundefined && documentIsHTML ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [ m ] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + // Support: IE6/7 + // getElementById is not reliable as a find shortcut + delete Expr.find["ID"]; + + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; + } + + // Tag + Expr.find["TAG"] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== strundefined ) { + return context.getElementsByTagName( tag ); + } + } : + function( tag, context ) { + var elem, + tmp = [], + i = 0, + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See http://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + div.innerHTML = ""; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( div.querySelectorAll("[msallowclip^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + }); + + assert(function( div ) { + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = doc.createElement("input"); + input.setAttribute( "type", "hidden" ); + div.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( div.querySelectorAll("[name=d]").length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Opera 10-11 does not throw on post-comma invalid pseudos + div.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } + + if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { + + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( div, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); + + /* Contains + ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); + + // Element contains another + // Purposefully does not implement inclusive descendent + // As in, an element does not contain itself + contains = hasCompare || rnative.test( docElem.contains ) ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = hasCompare ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { + return -1; + } + if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } : + function( a, b ) { + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Parentless nodes are either documents or disconnected + if ( !aup || !bup ) { + return a === doc ? -1 : + b === doc ? 1 : + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return doc; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + if ( support.matchesSelector && documentIsHTML && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch(e) {} + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + (val = elem.getAttributeNode(name)) && val.specified ? + val.value : + null; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + while ( (node = elem[i++]) ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (jQuery #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[6] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[3] ) { + match[2] = match[4] || match[5] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { return true; } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, outerCache, node, diff, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + // Seek `elem` from a previously-cached index + outerCache = parent[ expando ] || (parent[ expando ] = {}); + cache = outerCache[ type ] || []; + nodeIndex = cache[0] === dirruns && cache[1]; + diff = cache[0] === dirruns && cache[2]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + // Use previously-cached element index if available + } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { + diff = cache[1]; + + // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) + } else { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { + // Cache the index of each encountered element + if ( useCache ) { + (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf.call( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( (tokens = []) ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push({ + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + }); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push({ + value: matched, + type: type, + matches: match + }); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + if ( (oldCache = outerCache[ dir ]) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return (newCache[ 2 ] = oldCache[ 2 ]); + } else { + // Reuse newcache so results back-propagate to previous elements + outerCache[ dir ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { + return true; + } + } + } + } + } + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf.call( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), + len = elems.length; + + if ( outermost ) { + outermostContext = context !== document && context; + } + + // Add elements passing elementMatchers directly to results + // Keep `i` a string if there are no elements so `matchedCount` will be "00" below + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + for ( ; i !== len && (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +}; + +/** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +select = Sizzle.select = function( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( (selector = compiled.selector || selector) ); + + results = results || []; + + // Try to minimize operations if there is no seed and only one group + if ( match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + support.getById && context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +}; + +// One-time assignments + +// Sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + +// Support: Chrome<14 +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = !!hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert(function( div1 ) { + // Should return 1, but returns 4 (following) + return div1.compareDocumentPosition( document.createElement("div") ) & 1; +}); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert(function( div ) { + div.innerHTML = ""; + return div.firstChild.getAttribute("href") === "#" ; +}) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + }); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert(function( div ) { + div.innerHTML = ""; + div.firstChild.setAttribute( "value", "" ); + return div.firstChild.getAttribute( "value" ) === ""; +}) ) { + addHandle( "value", function( elem, name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + }); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert(function( div ) { + return div.getAttribute("disabled") == null; +}) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return elem[ name ] === true ? name.toLowerCase() : + (val = elem.getAttributeNode( name )) && val.specified ? + val.value : + null; + } + }); +} + +return Sizzle; + +})( window ); + + + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.pseudos; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + + +var rneedsContext = jQuery.expr.match.needsContext; + +var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); + + + +var risSimple = /^.[^:#\[\.,]*$/; + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + /* jshint -W018 */ + return !!qualifier.call( elem, i, elem ) !== not; + }); + + } + + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + }); + + } + + if ( typeof qualifier === "string" ) { + if ( risSimple.test( qualifier ) ) { + return jQuery.filter( qualifier, elements, not ); + } + + qualifier = jQuery.filter( qualifier, elements ); + } + + return jQuery.grep( elements, function( elem ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; + }); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 && elem.nodeType === 1 ? + jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : + jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + })); +}; + +jQuery.fn.extend({ + find: function( selector ) { + var i, + ret = [], + self = this, + len = self.length; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }) ); + } + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + // Needed because $( selector, context ) becomes $( context ).find( selector ) + ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); + ret.selector = this.selector ? this.selector + " " + selector : selector; + return ret; + }, + filter: function( selector ) { + return this.pushStack( winnow(this, selector || [], false) ); + }, + not: function( selector ) { + return this.pushStack( winnow(this, selector || [], true) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +}); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // Use the correct document accordingly with window argument (sandbox) + document = window.document, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, + + init = jQuery.fn.init = function( selector, context ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + + // scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[1], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return typeof rootjQuery.ready !== "undefined" ? + rootjQuery.ready( selector ) : + // Execute immediately if ready is not present + selector( jQuery ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document ); + + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.extend({ + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +jQuery.fn.extend({ + has: function( target ) { + var i, + targets = jQuery( target, this ), + len = targets.length; + + return this.filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { + // Always skip document fragments + if ( cur.nodeType < 11 && (pos ? + pos.index(cur) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector(cur, selectors)) ) { + + matched.push( cur ); + break; + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.unique( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter(selector) + ); + } +}); + +function sibling( cur, dir ) { + do { + cur = cur[ dir ]; + } while ( cur && cur.nodeType !== 1 ); + + return cur; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + if ( this.length > 1 ) { + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + ret = jQuery.unique( ret ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + } + + return this.pushStack( ret ); + }; +}); +var rnotwhite = (/\S+/g); + + + +// String to Object options format cache +var optionsCache = {}; + +// Convert String-formatted options into Object-formatted ones and store in cache +function createOptions( options ) { + var object = optionsCache[ options ] = {}; + jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + }); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + ( optionsCache[ options ] || createOptions( options ) ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list was already fired + fired, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // First callback to fire (used internally by add and fireWith) + firingStart, + // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = !options.once && [], + // Fire callbacks + fire = function( data ) { + memory = options.memory && data; + fired = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + firing = true; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { + memory = false; // To prevent further calls using add + break; + } + } + firing = false; + if ( list ) { + if ( stack ) { + if ( stack.length ) { + fire( stack.shift() ); + } + } else if ( memory ) { + list = []; + } else { + self.disable(); + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + // First, we save the current length + var start = list.length; + (function add( args ) { + jQuery.each( args, function( _, arg ) { + var type = jQuery.type( arg ); + if ( type === "function" ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && type !== "string" ) { + // Inspect recursively + add( arg ); + } + }); + })( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away + } else if ( memory ) { + firingStart = start; + fire( memory ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + // Handle firing indexes + if ( firing ) { + if ( index <= firingLength ) { + firingLength--; + } + if ( index <= firingIndex ) { + firingIndex--; + } + } + } + }); + } + return this; + }, + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); + }, + // Remove all callbacks from the list + empty: function() { + list = []; + firingLength = 0; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( list && ( !fired || stack ) ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + if ( firing ) { + stack.push( args ); + } else { + fire( args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + + +jQuery.extend({ + + Deferred: function( func ) { + var tuples = [ + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], + [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], + [ "notify", "progress", jQuery.Callbacks("memory") ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred(function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[1] ](function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .done( newDefer.resolve ) + .fail( newDefer.reject ) + .progress( newDefer.notify ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); + } + }); + }); + fns = null; + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Keep pipe for back-compat + promise.pipe = promise.then; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; + + // promise[ done | fail | progress ] = list.add + promise[ tuple[1] ] = list.add; + + // Handle state + if ( stateString ) { + list.add(function() { + // state = [ resolved | rejected ] + state = stateString; + + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + } + + // deferred[ resolve | reject | notify ] + deferred[ tuple[0] ] = function() { + deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); + return this; + }; + deferred[ tuple[0] + "With" ] = list.fireWith; + }); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( values === progressValues ) { + deferred.notifyWith( contexts, values ); + + } else if ( !(--remaining) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ) + .progress( updateFunc( i, progressContexts, progressValues ) ); + } else { + --remaining; + } + } + } + + // if we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); + } + + return deferred.promise(); + } +}); + + +// The deferred used on DOM ready +var readyList; + +jQuery.fn.ready = function( fn ) { + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; +}; + +jQuery.extend({ + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.triggerHandler ) { + jQuery( document ).triggerHandler( "ready" ); + jQuery( document ).off( "ready" ); + } + } +}); + +/** + * Clean-up method for dom ready events + */ +function detach() { + if ( document.addEventListener ) { + document.removeEventListener( "DOMContentLoaded", completed, false ); + window.removeEventListener( "load", completed, false ); + + } else { + document.detachEvent( "onreadystatechange", completed ); + window.detachEvent( "onload", completed ); + } +} + +/** + * The ready event handler and self cleanup method + */ +function completed() { + // readyState === "complete" is good enough for us to call the dom ready in oldIE + if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { + detach(); + jQuery.ready(); + } +} + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called after the browser event has already occurred. + // we once tried to use readyState "interactive" here, but it caused issues like the one + // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + setTimeout( jQuery.ready ); + + // Standards-based browsers support DOMContentLoaded + } else if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed, false ); + + // If IE event model is used + } else { + // Ensure firing before onload, maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", completed ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", completed ); + + // If IE and not a frame + // continually check to see if the document is ready + var top = false; + + try { + top = window.frameElement == null && document.documentElement; + } catch(e) {} + + if ( top && top.doScroll ) { + (function doScrollCheck() { + if ( !jQuery.isReady ) { + + try { + // Use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + top.doScroll("left"); + } catch(e) { + return setTimeout( doScrollCheck, 50 ); + } + + // detach all dom ready events + detach(); + + // and execute any waiting functions + jQuery.ready(); + } + })(); + } + } + } + return readyList.promise( obj ); +}; + + +var strundefined = typeof undefined; + + + +// Support: IE<9 +// Iteration over object's inherited properties before its own +var i; +for ( i in jQuery( support ) ) { + break; +} +support.ownLast = i !== "0"; + +// Note: most support tests are defined in their respective modules. +// false until the test is run +support.inlineBlockNeedsLayout = false; + +// Execute ASAP in case we need to set body.style.zoom +jQuery(function() { + // Minified: var a,b,c,d + var val, div, body, container; + + body = document.getElementsByTagName( "body" )[ 0 ]; + if ( !body || !body.style ) { + // Return for frameset docs that don't have a body + return; + } + + // Setup + div = document.createElement( "div" ); + container = document.createElement( "div" ); + container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; + body.appendChild( container ).appendChild( div ); + + if ( typeof div.style.zoom !== strundefined ) { + // Support: IE<8 + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1"; + + support.inlineBlockNeedsLayout = val = div.offsetWidth === 3; + if ( val ) { + // Prevent IE 6 from affecting layout for positioned elements #11048 + // Prevent IE from shrinking the body in IE 7 mode #12869 + // Support: IE<8 + body.style.zoom = 1; + } + } + + body.removeChild( container ); +}); + + + + +(function() { + var div = document.createElement( "div" ); + + // Execute the test only if not already executed in another module. + if (support.deleteExpando == null) { + // Support: IE<9 + support.deleteExpando = true; + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + } + + // Null elements to avoid leaks in IE. + div = null; +})(); + + +/** + * Determines whether an object can have data + */ +jQuery.acceptData = function( elem ) { + var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ], + nodeType = +elem.nodeType || 1; + + // Do not set data on non-element DOM nodes because it will not be cleared (#8335). + return nodeType !== 1 && nodeType !== 9 ? + false : + + // Nodes accept data unless otherwise specified; rejection can be conditional + !noData || noData !== true && elem.getAttribute("classid") === noData; +}; + + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /([A-Z])/g; + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + var name; + for ( name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} + +function internalData( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var ret, thisCache, + internalKey = jQuery.expando, + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + // Avoid exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( typeof name === "string" ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; +} + +function internalRemoveData( elem, name, pvt ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split(" "); + } + } + } else { + // If "name" is an array of keys... + // When data is initially created, via ("key", "val") signature, + // keys will be converted to camelCase. + // Since there is no way to tell _how_ a key was added, remove + // both plain key and camelCase key. #12786 + // This will only penalize the array argument path. + name = name.concat( jQuery.map( name, jQuery.camelCase ) ); + } + + i = name.length; + while ( i-- ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject( cache[ id ] ) ) { + return; + } + } + + // Destroy the cache + if ( isNode ) { + jQuery.cleanData( [ elem ], true ); + + // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) + /* jshint eqeqeq: false */ + } else if ( support.deleteExpando || cache != cache.window ) { + /* jshint eqeqeq: true */ + delete cache[ id ]; + + // When all else fails, null + } else { + cache[ id ] = null; + } +} + +jQuery.extend({ + cache: {}, + + // The following elements (space-suffixed to avoid Object.prototype collisions) + // throw uncatchable exceptions if you attempt to set expando properties + noData: { + "applet ": true, + "embed ": true, + // ...but Flash objects (which have this classid) *can* handle expandos + "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data ) { + return internalData( elem, name, data ); + }, + + removeData: function( elem, name ) { + return internalRemoveData( elem, name ); + }, + + // For internal use only. + _data: function( elem, name, data ) { + return internalData( elem, name, data, true ); + }, + + _removeData: function( elem, name ) { + return internalRemoveData( elem, name, true ); + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var i, name, data, + elem = this[0], + attrs = elem && elem.attributes; + + // Special expections of .data basically thwart jQuery.access, + // so implement the relevant behavior ourselves + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = jQuery.data( elem ); + + if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE11+ + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.slice(5) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + jQuery._data( elem, "parsedAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + return arguments.length > 1 ? + + // Sets one value + this.each(function() { + jQuery.data( this, key, value ); + }) : + + // Gets one value + // Try to fetch any internally stored data first + elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined; + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + + +jQuery.extend({ + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray(data) ) { + queue = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // not intended for public consumption - generates a queueHooks object, or returns the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return jQuery._data( elem, key ) || jQuery._data( elem, key, { + empty: jQuery.Callbacks("once memory").add(function() { + jQuery._removeData( elem, type + "queue" ); + jQuery._removeData( elem, key ); + }) + }); + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[0], type ); + } + + return data === undefined ? + this : + this.each(function() { + var queue = jQuery.queue( this, type, data ); + + // ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = jQuery._data( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +}); +var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var isHidden = function( elem, el ) { + // isHidden might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); + }; + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + length = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !jQuery.isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < length; i++ ) { + fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); + } + } + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + length ? fn( elems[0], key ) : emptyGet; +}; +var rcheckableType = (/^(?:checkbox|radio)$/i); + + + +(function() { + // Minified: var a,b,c + var input = document.createElement( "input" ), + div = document.createElement( "div" ), + fragment = document.createDocumentFragment(); + + // Setup + div.innerHTML = "
    a"; + + // IE strips leading whitespace when .innerHTML is used + support.leadingWhitespace = div.firstChild.nodeType === 3; + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + support.tbody = !div.getElementsByTagName( "tbody" ).length; + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + support.htmlSerialize = !!div.getElementsByTagName( "link" ).length; + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + support.html5Clone = + document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav>"; + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + input.type = "checkbox"; + input.checked = true; + fragment.appendChild( input ); + support.appendChecked = input.checked; + + // Make sure textarea (and checkbox) defaultValue is properly cloned + // Support: IE6-IE11+ + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; + + // #11217 - WebKit loses check when the name is after the checked attribute + fragment.appendChild( div ); + div.innerHTML = ""; + + // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 + // old WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE<9 + // Opera does not clone events (and typeof div.attachEvent === undefined). + // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() + support.noCloneEvent = true; + if ( div.attachEvent ) { + div.attachEvent( "onclick", function() { + support.noCloneEvent = false; + }); + + div.cloneNode( true ).click(); + } + + // Execute the test only if not already executed in another module. + if (support.deleteExpando == null) { + // Support: IE<9 + support.deleteExpando = true; + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + } +})(); + + +(function() { + var i, eventName, + div = document.createElement( "div" ); + + // Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event) + for ( i in { submit: true, change: true, focusin: true }) { + eventName = "on" + i; + + if ( !(support[ i + "Bubbles" ] = eventName in window) ) { + // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) + div.setAttribute( eventName, "t" ); + support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false; + } + } + + // Null elements to avoid leaks in IE. + div = null; +})(); + + +var rformElems = /^(?:input|select|textarea)$/i, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + var tmp, events, t, handleObjIn, + special, eventHandle, handleObj, + handlers, type, namespaces, origType, + elemData = jQuery._data( elem ); + + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !(events = elemData.events) ) { + events = elemData.events = {}; + } + if ( !(eventHandle = elemData.handle) ) { + eventHandle = elemData.handle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !(handlers = events[ type ]) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + var j, handleObj, tmp, + origCount, t, events, + special, handlers, type, + namespaces, origType, + elemData = jQuery.hasData( elem ) && jQuery._data( elem ); + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + delete elemData.handle; + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery._removeData( elem, "events" ); + } + }, + + trigger: function( event, data, elem, onlyHandlers ) { + var handle, ontype, cur, + bubbleType, special, tmp, i, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; + + cur = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf(".") >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf(":") < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join("."); + event.namespace_re = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === (elem.ownerDocument || document) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { + + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && jQuery.acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && + jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + try { + elem[ type ](); + } catch ( e ) { + // IE<9 dies on focus/blur to hidden element (#1486,#12518) + // only reproducible on winXP IE8 native, not IE9 in IE8 mode + } + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event ); + + var i, ret, handleObj, matched, j, + handlerQueue = [], + args = slice.call( arguments ), + handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { + + // Triggered event must either 1) have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( (event.result = ret) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var sel, handleObj, matches, i, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + // Black-hole SVG instance trees (#13180) + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { + + /* jshint eqeqeq: false */ + for ( ; cur != this; cur = cur.parentNode || this ) { + /* jshint eqeqeq: true */ + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) >= 0 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matches[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, handlers: matches }); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); + } + + return handlerQueue; + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, copy, + type = event.type, + originalEvent = event, + fixHook = this.fixHooks[ type ]; + + if ( !fixHook ) { + this.fixHooks[ type ] = fixHook = + rmouseEvent.test( type ) ? this.mouseHooks : + rkeyEvent.test( type ) ? this.keyHooks : + {}; + } + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = new jQuery.Event( originalEvent ); + + i = copy.length; + while ( i-- ) { + prop = copy[ i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Support: IE<9 + // Fix target property (#1925) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Support: Chrome 23+, Safari? + // Target should not be a text node (#504, #13143) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // Support: IE<9 + // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) + event.metaKey = !!event.metaKey; + + return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var body, eventDoc, doc, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + special: { + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + focus: { + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + try { + this.focus(); + return false; + } catch ( e ) { + // Support: IE<9 + // If we error on focus to hidden element (#1486, #12518), + // let .trigger() run the handlers + } + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + click: { + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { + this.click(); + return false; + } + }, + + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return jQuery.nodeName( event.target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + var name = "on" + type; + + if ( elem.detachEvent ) { + + // #8545, #7054, preventing memory leaks for custom events in IE6-8 + // detachEvent needed property on element, by name of that event, to properly expose it to GC + if ( typeof elem[ name ] === strundefined ) { + elem[ name ] = null; + } + + elem.detachEvent( name, handle ); + } + }; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + // Support: IE < 9, Android < 4.0 + src.returnValue === false ? + returnTrue : + returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + if ( !e ) { + return; + } + + // If preventDefault exists, run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // Support: IE + // Otherwise set the returnValue property of the original event to false + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + if ( !e ) { + return; + } + // If stopPropagation exists, run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + + // Support: IE + // Set the cancelBubble property of the original event to true + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && e.stopImmediatePropagation ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// IE submit delegation +if ( !support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !jQuery._data( form, "submitBubbles" ) ) { + jQuery.event.add( form, "submit._submit", function( event ) { + event._submit_bubble = true; + }); + jQuery._data( form, "submitBubbles", true ); + } + }); + // return undefined since we don't need an event listener + }, + + postDispatch: function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( event._submit_bubble ) { + delete event._submit_bubble; + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + } + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + } + // Allow triggered, simulated change events (#11500) + jQuery.event.simulate( "change", this, event, true ); + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + jQuery._data( elem, "changeBubbles", true ); + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return !rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler on the document while someone wants focusin/focusout + var handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + var doc = this.ownerDocument || this, + attaches = jQuery._data( doc, fix ); + + if ( !attaches ) { + doc.addEventListener( orig, handler, true ); + } + jQuery._data( doc, fix, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this, + attaches = jQuery._data( doc, fix ) - 1; + + if ( !attaches ) { + doc.removeEventListener( orig, handler, true ); + jQuery._removeData( doc, fix ); + } else { + jQuery._data( doc, fix, attaches ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var type, origFn; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on( types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + var elem = this[0]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +}); + + +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", + rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, + rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, + rtagName = /<([\w:]+)/, + rtbody = /\s*$/g, + + // We have to close these tags to support XHTML (#13200) + wrapMap = { + option: [ 1, "" ], + legend: [ 1, "
    ", "
    " ], + area: [ 1, "", "" ], + param: [ 1, "", "" ], + thead: [ 1, "", "
    " ], + tr: [ 2, "", "
    " ], + col: [ 2, "", "
    " ], + td: [ 3, "", "
    " ], + + // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, + // unless wrapped in a div with non-breaking characters in front of it. + _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X
    ", "
    " ] + }, + safeFragment = createSafeFragment( document ), + fragmentDiv = safeFragment.appendChild( document.createElement("div") ); + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +function getAll( context, tag ) { + var elems, elem, + i = 0, + found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : + typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : + undefined; + + if ( !found ) { + for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { + if ( !tag || jQuery.nodeName( elem, tag ) ) { + found.push( elem ); + } else { + jQuery.merge( found, getAll( elem, tag ) ); + } + } + } + + return tag === undefined || tag && jQuery.nodeName( context, tag ) ? + jQuery.merge( [ context ], found ) : + found; +} + +// Used in buildFragment, fixes the defaultChecked property +function fixDefaultChecked( elem ) { + if ( rcheckableType.test( elem.type ) ) { + elem.defaultChecked = elem.checked; + } +} + +// Support: IE<8 +// Manipulating tables requires a tbody +function manipulationTarget( elem, content ) { + return jQuery.nodeName( elem, "table" ) && + jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? + + elem.getElementsByTagName("tbody")[0] || + elem.appendChild( elem.ownerDocument.createElement("tbody") ) : + elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + if ( match ) { + elem.type = match[1]; + } else { + elem.removeAttribute("type"); + } + return elem; +} + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var elem, + i = 0; + for ( ; (elem = elems[i]) != null; i++ ) { + jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); + } +} + +function cloneCopyEvent( src, dest ) { + + if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { + return; + } + + var type, i, l, + oldData = jQuery._data( src ), + curData = jQuery._data( dest, oldData ), + events = oldData.events; + + if ( events ) { + delete curData.handle; + curData.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + + // make the cloned public data object a copy from the original + if ( curData.data ) { + curData.data = jQuery.extend( {}, curData.data ); + } +} + +function fixCloneNodeIssues( src, dest ) { + var nodeName, e, data; + + // We do not need to do anything for non-Elements + if ( dest.nodeType !== 1 ) { + return; + } + + nodeName = dest.nodeName.toLowerCase(); + + // IE6-8 copies events bound via attachEvent when using cloneNode. + if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { + data = jQuery._data( dest ); + + for ( e in data.events ) { + jQuery.removeEvent( dest, e, data.handle ); + } + + // Event data gets referenced instead of copied if the expando gets copied too + dest.removeAttribute( jQuery.expando ); + } + + // IE blanks contents when cloning scripts, and tries to evaluate newly-set text + if ( nodeName === "script" && dest.text !== src.text ) { + disableScript( dest ).text = src.text; + restoreScript( dest ); + + // IE6-10 improperly clones children of object elements using classid. + // IE10 throws NoModificationAllowedError if parent is null, #12132. + } else if ( nodeName === "object" ) { + if ( dest.parentNode ) { + dest.outerHTML = src.outerHTML; + } + + // This path appears unavoidable for IE9. When cloning an object + // element in IE9, the outerHTML strategy above is not sufficient. + // If the src has innerHTML and the destination does not, + // copy the src.innerHTML into the dest.innerHTML. #10324 + if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { + dest.innerHTML = src.innerHTML; + } + + } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + // IE6-8 fails to persist the checked state of a cloned checkbox + // or radio button. Worse, IE6-7 fail to give the cloned element + // a checked appearance if the defaultChecked value isn't also set + + dest.defaultChecked = dest.checked = src.checked; + + // IE6-7 get confused and end up setting the value of a cloned + // checkbox/radio button to an empty string instead of "on" + if ( dest.value !== src.value ) { + dest.value = src.value; + } + + // IE6-8 fails to return the selected option to the default selected + // state when cloning options + } else if ( nodeName === "option" ) { + dest.defaultSelected = dest.selected = src.defaultSelected; + + // IE6-8 fails to set the defaultValue to the correct value when + // cloning other types of input fields + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var destElements, node, clone, i, srcElements, + inPage = jQuery.contains( elem.ownerDocument, elem ); + + if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { + clone = elem.cloneNode( true ); + + // IE<=8 does not properly clone detached, unknown element nodes + } else { + fragmentDiv.innerHTML = elem.outerHTML; + fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); + } + + if ( (!support.noCloneEvent || !support.noCloneChecked) && + (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { + + // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + // Fix all IE cloning issues + for ( i = 0; (node = srcElements[i]) != null; ++i ) { + // Ensure that the destination node is not null; Fixes #9587 + if ( destElements[i] ) { + fixCloneNodeIssues( node, destElements[i] ); + } + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0; (node = srcElements[i]) != null; i++ ) { + cloneCopyEvent( node, destElements[i] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + destElements = srcElements = node = null; + + // Return the cloned set + return clone; + }, + + buildFragment: function( elems, context, scripts, selection ) { + var j, elem, contains, + tmp, tag, tbody, wrap, + l = elems.length, + + // Ensure a safe fragment + safe = createSafeFragment( context ), + + nodes = [], + i = 0; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( jQuery.type( elem ) === "object" ) { + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || safe.appendChild( context.createElement("div") ); + + // Deserialize a standard representation + tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + + tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[2]; + + // Descend through wrappers to the right content + j = wrap[0]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Manually add leading whitespace removed by IE + if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { + nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); + } + + // Remove IE's autoinserted from table fragments + if ( !support.tbody ) { + + // String was a , *may* have spurious + elem = tag === "table" && !rtbody.test( elem ) ? + tmp.firstChild : + + // String was a bare or + wrap[1] === "
    " && !rtbody.test( elem ) ? + tmp : + 0; + + j = elem && elem.childNodes.length; + while ( j-- ) { + if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { + elem.removeChild( tbody ); + } + } + } + + jQuery.merge( nodes, tmp.childNodes ); + + // Fix #12392 for WebKit and IE > 9 + tmp.textContent = ""; + + // Fix #12392 for oldIE + while ( tmp.firstChild ) { + tmp.removeChild( tmp.firstChild ); + } + + // Remember the top-level container for proper cleanup + tmp = safe.lastChild; + } + } + } + + // Fix #11356: Clear elements from fragment + if ( tmp ) { + safe.removeChild( tmp ); + } + + // Reset defaultChecked for any radios and checkboxes + // about to be appended to the DOM in IE 6/7 (#8060) + if ( !support.appendChecked ) { + jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); + } + + i = 0; + while ( (elem = nodes[ i++ ]) ) { + + // #4087 - If origin and destination elements are the same, and this is + // that element, do not do anything + if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( safe.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( (elem = tmp[ j++ ]) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + tmp = null; + + return safe; + }, + + cleanData: function( elems, /* internal */ acceptData ) { + var elem, type, id, data, + i = 0, + internalKey = jQuery.expando, + cache = jQuery.cache, + deleteExpando = support.deleteExpando, + special = jQuery.event.special; + + for ( ; (elem = elems[i]) != null; i++ ) { + if ( acceptData || jQuery.acceptData( elem ) ) { + + id = elem[ internalKey ]; + data = id && cache[ id ]; + + if ( data ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Remove cache only if it was not already removed by jQuery.event.remove + if ( cache[ id ] ) { + + delete cache[ id ]; + + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( deleteExpando ) { + delete elem[ internalKey ]; + + } else if ( typeof elem.removeAttribute !== strundefined ) { + elem.removeAttribute( internalKey ); + + } else { + elem[ internalKey ] = null; + } + + deletedIds.push( id ); + } + } + } + } + } +}); + +jQuery.fn.extend({ + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); + }, null, value, arguments.length ); + }, + + append: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + }); + }, + + before: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + }); + }, + + after: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + }); + }, + + remove: function( selector, keepData /* Internal Use Only */ ) { + var elem, + elems = selector ? jQuery.filter( selector, this ) : this, + i = 0; + + for ( ; (elem = elems[i]) != null; i++ ) { + + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem ) ); + } + + if ( elem.parentNode ) { + if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { + setGlobalEval( getAll( elem, "script" ) ); + } + elem.parentNode.removeChild( elem ); + } + } + + return this; + }, + + empty: function() { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + } + + // Remove any remaining nodes + while ( elem.firstChild ) { + elem.removeChild( elem.firstChild ); + } + + // If this is a select, ensure that it displays empty (#12336) + // Support: IE<9 + if ( elem.options && jQuery.nodeName( elem, "select" ) ) { + elem.options.length = 0; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map(function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + }); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined ) { + return elem.nodeType === 1 ? + elem.innerHTML.replace( rinlinejQuery, "" ) : + undefined; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + ( support.htmlSerialize || !rnoshimcache.test( value ) ) && + ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && + !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { + + value = value.replace( rxhtmlTag, "<$1>" ); + + try { + for (; i < l; i++ ) { + // Remove element nodes and prevent memory leaks + elem = this[i] || {}; + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch(e) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var arg = arguments[ 0 ]; + + // Make the changes, replacing each context element with the new content + this.domManip( arguments, function( elem ) { + arg = this.parentNode; + + jQuery.cleanData( getAll( this ) ); + + if ( arg ) { + arg.replaceChild( elem, this ); + } + }); + + // Force removal if there was no new content (e.g., from empty arguments) + return arg && (arg.length || arg.nodeType) ? this : this.remove(); + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, callback ) { + + // Flatten any nested arrays + args = concat.apply( [], args ); + + var first, node, hasScripts, + scripts, doc, fragment, + i = 0, + l = this.length, + set = this, + iNoClone = l - 1, + value = args[0], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return this.each(function( index ) { + var self = set.eq( index ); + if ( isFunction ) { + args[0] = value.call( this, index, self.html() ); + } + self.domManip( args, callback ); + }); + } + + if ( l ) { + fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + if ( first ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( this[i], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { + + if ( node.src ) { + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl ) { + jQuery._evalUrl( node.src ); + } + } else { + jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); + } + } + } + } + + // Fix #11809: Avoid leaking memory + fragment = first = null; + } + } + + return this; + } +}); + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + i = 0, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone(true); + jQuery( insert[i] )[ original ]( elems ); + + // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +}); + + +var iframe, + elemdisplay = {}; + +/** + * Retrieve the actual display of a element + * @param {String} name nodeName of the element + * @param {Object} doc Document object + */ +// Called only from within defaultDisplay +function actualDisplay( name, doc ) { + var style, + elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), + + // getDefaultComputedStyle might be reliably used only on attached element + display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? + + // Use of this method is a temporary fix (more like optmization) until something better comes along, + // since it was removed from specification and supported only in FF + style.display : jQuery.css( elem[ 0 ], "display" ); + + // We don't have any data stored on the element, + // so use "detach" method as fast way to get rid of the element + elem.detach(); + + return display; +} + +/** + * Try to determine the default display value of an element + * @param {String} nodeName + */ +function defaultDisplay( nodeName ) { + var doc = document, + display = elemdisplay[ nodeName ]; + + if ( !display ) { + display = actualDisplay( nodeName, doc ); + + // If the simple way fails, read from inside an iframe + if ( display === "none" || !display ) { + + // Use the already-created iframe if possible + iframe = (iframe || jQuery( "