[nhin-d] push by gm2...@cerner.com - Adding tag for config-manager-1.1 on 2015-01-20 13:19 GMT

0 views
Skip to first unread message

nhi...@googlecode.com

unread,
Jan 20, 2015, 8:20:16 AM1/20/15
to nhindirec...@googlegroups.com
Revision: 0af0be1c0a67
Branch: default
Author: gm2552
Date: Tue Jan 20 13:19:34 2015 UTC
Log: Adding tag for config-manager-1.1
https://code.google.com/p/nhin-d/source/detail?r=0af0be1c0a67

Added:
/java/tags/config-manager-1.1/pom.xml
/java/tags/config-manager-1.1/src/descriptors/distribution.xml

/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/CertCommands.java

/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/ConfigManager.java

/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/DNSRecordCommands.java

/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/DNSRecordParser.java

/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/PolicyCommands.java

/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/AbstractRecordPrinter.java

/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/CertRecordPrinter.java

/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/CertUtils.java

/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/DNSRecordPrinter.java

/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/DefaultDNSRecordPrinter.java

/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/PolicyGroupPrinter.java

/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/PolicyPrinter.java

/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/PolicyUsagePrinter.java

/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/RecordPrinter.java
Modified:
/java/config/config-manager/pom.xml

/java/config/config-manager/src/main/java/org/nhindirect/config/manager/CertCommands.java

=======================================
--- /dev/null
+++ /java/tags/config-manager-1.1/pom.xml Tue Jan 20 13:19:34 2015 UTC
@@ -0,0 +1,422 @@
+<?xml version="1.0"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.nhind</groupId>
+ <artifactId>config-manager</artifactId>
+ <version>1.1</version>
+ <packaging>jar</packaging>
+ <name>NHIN Direct Java configuration manager</name>
+ <description>NHIN Direct Java configuration manager</description>
+
<url>http://api.nhindirect.org/x/www/api.nhindirect.org/java/site/config/config-service-client/${project.version}</url>
+
+ <scm>
+ <url>https://nhin-d.googlecode.com/hg/java/config/config-manager</url>
+
<connection>scm:hg:https://nhin-d.googlecode.com/hg/nhin-d/java/config/config-manager</connection>
+ </scm>
+
+ <developers>
+ <developer>
+ <name>Greg Meyer</name>
+ <email>gm2...@cerner.com</email>
+ <roles>
+ <role>owner</role>
+ </roles>
+ </developer>
+ </developers>
+
+ <licenses>
+ <license>
+ <name>New BSD License</name>
+ <url>http://nhindirect.org/BSDLicense</url>
+ </license>
+ </licenses>
+
+ <issueManagement>
+ <system>Google Code</system>
+ <url>http://code.google.com/p/nhin-d/issues/list</url>
+ </issueManagement>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <cxf.maven.artifact.version>2.2.9</cxf.maven.artifact.version>
+ </properties>
+ <dependencies>
+ <dependency>
+ <groupId>org.nhind</groupId>
+ <artifactId>dns</artifactId>
+ <version>1.2.3</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-asm</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-aop</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-tx</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-orm</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-test</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-beans</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-context</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-entitymanager</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-annotations</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.google.inject</groupId>
+ <artifactId>guice</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.apache.geronimo.specs</groupId>
+ <artifactId>geronimo-jpa_2.0_spec</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.nhind</groupId>
+ <artifactId>config-service-client</artifactId>
+ <version>2.0</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-context</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.nhind</groupId>
+ <artifactId>direct-common</artifactId>
+ <version>1.4.2</version>
+ <exclusions>
+ <exclusion>
+ <groupId>com.google.inject</groupId>
+ <artifactId>guice</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.nhind</groupId>
+ <artifactId>agent</artifactId>
+ <version>2.0.11</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.apache.james</groupId>
+ <artifactId>apache-jsieve-mailet</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.google.inject</groupId>
+ <artifactId>guice</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>dnsjava</groupId>
+ <artifactId>dnsjava</artifactId>
+ <version>2.0.8</version>
+ </dependency>
+ </dependencies>
+ <build>
+ <pluginManagement>
+ <plugins>
+ <plugin>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <fork>true</fork>
+ <source>1.6</source>
+ <target>1.6</target>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-release-plugin</artifactId>
+ <version>2.0</version>
+ <configuration>
+
<tagBase>scm:hg:https://nhin-d.googlecode.com/hg/nhin-d/java/tags</tagBase>
+ </configuration>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-source-plugin</artifactId>
+ <version>2.0.3</version>
+ <executions>
+ <execution>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-dependency-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>copy</id>
+ <phase>compile</phase>
+ <goals>
+ <goal>copy</goal>
+ </goals>
+ <configuration>
+ <artifactItems>
+ <artifactItem>
+ <groupId>org.nhind</groupId>
+ <artifactId>config-service</artifactId>
+ <version>1.5</version>
+ <type>war</type>
+ <overWrite>true</overWrite>
+ <destFileName>config-service.war</destFileName>
+ </artifactItem>
+ </artifactItems>
+ <outputDirectory>
+ ${project.basedir}/war
+ </outputDirectory>
+ <overWriteReleases>true</overWriteReleases>
+ <overWriteSnapshots>true</overWriteSnapshots>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>appassembler-maven-plugin</artifactId>
+ <version>1.3</version>
+ <executions>
+ <execution>
+ <configuration>
+
<assembleDirectory>${project.build.directory}/appassembler/app/ConfigMgmtConsole</assembleDirectory>
+ <repositoryName>lib</repositoryName>
+ <repositoryLayout>flat</repositoryLayout>
+
<extraJvmArguments>-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog
-Dorg.apache.commons.logging.simplelog.defaultlog=error</extraJvmArguments>
+ <programs>
+ <program>
+
<mainClass>org.nhindirect.config.manager.ConfigManager</mainClass>
+ <name>ConfigMgmtConsole</name>
+ </program>
+ </programs>
+ </configuration>
+ <goals>
+ <goal>assemble</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <version>2.2</version>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ <configuration>
+ <appendAssemblyId>false</appendAssemblyId>
+ <includeModuleDirectory>false</includeModuleDirectory>
+ <finalName>configTools-${project.version}</finalName>
+ <descriptors>
+
<descriptor>src/descriptors/distribution.xml</descriptor>
+ </descriptors>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>com.atlassian.maven.plugins</groupId>
+ <artifactId>maven-clover2-plugin</artifactId>
+ <version>3.0.2</version>
+ <configuration>
+ <jdk>1.6</jdk>
+
<licenseLocation>${project.basedir}/../../licenses/clover.license</licenseLocation>
+ </configuration>
+ <executions>
+ <execution>
+ <phase>pre-site</phase>
+ <goals>
+ <goal>instrument</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <!-- for releases only
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <version>2.6.1</version>
+ <configuration>
+ <charset>UTF-8</charset>
+ <docencoding>UTF-8</docencoding>
+ <docfilessubdirs>true</docfilessubdirs>
+ <detectJavaApiLink>true</detectJavaApiLink>
+ <detectLinks>true</detectLinks>
+ <source>1.6</source>
+ <show>protected</show>
+ </configuration>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <id>attach-javadocs</id>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-gpg-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>sign-artifacts</id>
+ <phase>package</phase>
+ <goals>
+ <goal>sign</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ -->
+ </plugins>
+ </build>
+ <reporting>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-project-info-reports-plugin</artifactId>
+ <version>2.1</version>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <version>2.6.1</version>
+ <configuration>
+ <charset>UTF-8</charset>
+ <docencoding>UTF-8</docencoding>
+ <docfilessubdirs>true</docfilessubdirs>
+ <detectJavaApiLink>true</detectJavaApiLink>
+ <detectLinks>true</detectLinks>
+ <source>1.6</source>
+ <show>protected</show>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-pmd-plugin</artifactId>
+ <configuration>
+ <targetJdk>1.6</targetJdk>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-report-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jxr-plugin</artifactId>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-changelog-plugin</artifactId>
+ <configuration>
+ <dates>
+ <!-- Insert the date of the most recent release -->
+ <date>2007-01-01</date>
+ </dates>
+ <outputEncoding>UTF-8</outputEncoding>
+ <type>date</type>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>clirr-maven-plugin</artifactId>
+ <configuration>
+ <minSeverity>info</minSeverity>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>findbugs-maven-plugin</artifactId>
+ <version>1.2</version>
+ <configuration>
+ <effort>Max</effort>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>taglist-maven-plugin</artifactId>
+ <configuration>
+ <tags>
+ <tag>FIXME</tag>
+ <tag>TODO</tag>
+ <tag>WARN</tag>
+ <tag>@deprecated</tag>
+ </tags>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>com.atlassian.maven.plugins</groupId>
+ <artifactId>maven-clover2-plugin</artifactId>
+ <version>3.0.2</version>
+ <configuration>
+
<licenseLocation>${project.basedir}/../../licenses/clover.license</licenseLocation>
+ </configuration>
+ </plugin>
+ </plugins>
+ </reporting>
+
+ <distributionManagement>
+ <site>
+ <id>nhind-site</id>
+ <name>NHIN Direct API publication site</name>
+
<url>sftp://api.nhindirect.org/x/www/api.nhindirect.org/java/site/config/config-service-client/${project.version}</url>
+ </site>
+ <snapshotRepository>
+ <id>sonatype-snapshot</id>
+ <name>Sonatype OSS Maven SNAPSHOT Repository</name>
+
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
+ <uniqueVersion>false</uniqueVersion>
+ </snapshotRepository>
+ <repository>
+ <id>sonatype-release</id>
+ <name>Sonatype OSS Maven Release Repositor</name>
+
<url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
+ <uniqueVersion>false</uniqueVersion>
+ </repository>
+ </distributionManagement>
+
+</project>
=======================================
--- /dev/null
+++ /java/tags/config-manager-1.1/src/descriptors/distribution.xml Tue Jan
20 13:19:34 2015 UTC
@@ -0,0 +1,15 @@
+<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0
http://maven.apache.org/xsd/assembly-1.1.0.xsd">
+ <id>assembly</id>
+ <baseDirectory>ConfigTools</baseDirectory>
+ <formats>
+ <format>tar.gz</format>
+ </formats>
+ <fileSets>
+ <fileSet>
+
<directory>${project.build.directory}/appassembler/app/ConfigMgmtConsole</directory>
+ <outputDirectory>/ConfigMgmtConsole</outputDirectory>
+ </fileSet>
+ </fileSets>
+</assembly>
=======================================
--- /dev/null
+++
/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/CertCommands.java
Tue Jan 20 13:19:34 2015 UTC
@@ -0,0 +1,393 @@
+package org.nhindirect.config.manager;
+
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.security.Key;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.Arrays;
+import java.util.Enumeration;
+
+import org.apache.commons.io.FileUtils;
+import org.nhind.config.ConfigurationServiceProxy;
+import org.nhind.config.EntityStatus;
+import org.nhindirect.config.manager.printers.CertRecordPrinter;
+import org.nhindirect.config.manager.printers.CertUtils;
+import org.nhindirect.config.manager.printers.RecordPrinter;
+import org.nhindirect.dns.tools.utils.Command;
+import org.nhindirect.dns.tools.utils.StringArrayUtil;
+import org.nhindirect.stagent.CryptoExtensions;
+import org.nhindirect.stagent.NHINDException;
+import org.nhindirect.stagent.cert.X509CertificateEx;
+
+
+public class CertCommands
+{
+ private static final String LIST_CERTIFICATES_USAGE = "Lists
certificates in the system";
+
+ private static final String LIST_EMAIL_CERTIFICATES_USAGE = "Lists
certificates by a given email address or domain" +
+ "\r\n address" +
+ "\r\n\t address: The email address or domain to search for.
Certificates are searched on the subject alternative name field of legacy
email address of the certificate";
+
+ private static final String EXPORT_EMAIL_CERTIFICATES_USAGE = "Exports
certificates by a given email address or domain" +
+ "\r\n address" +
+ "\r\n\t address: The email address or domain to search for.
Certificates are searched on the subject alternative name field of legacy
email address of the certificate";
+
+ private static final String IMPORT_PUBLIC_CERT_USAGE = "Imports a
certificate that does not contain private key information" +
+ "\r\n certfile" +
+ "\r\n\t certfile: Fully qualified path and file name of the
X509 certificate file. Place the file name in quotes (\"\") if there are
spaces in the path or name.";
+
+ private static final String IMPORT_PRIVATE_CERT_USAGE = "Imports a
certificate with a private key an optional passphrase. \r\n" +
+ "Files should be in pkcs12 format." +
+ "\r\n certfile [passphrase]" +
+ "\r\n\t certfile: Fully qualified path and file name of the
pkcs12 certificate file. Place the file name in quotes (\"\") if there are
spaces in the path or name." +
+ "\r\n\t [passphrase]: Optional passphrase to decrypt the
pkcs12 file.";
+
+ private static final String ADD_IPKIX_CERT_USAGE = "Add an IPKIX
record with a subject and URL. \r\n" +
+ "\r\n subject URL" +
+ "\r\n subject: email address or domain name" +
+ "\r\n\t URL: Fully qualified URL to certificate";
+
+ private static final String REMOVED_CERTIFICATE_USAGE = "Removes a
certifacte from the system by owner." +
+ "\r\n owner" +
+ "\r\n\t owner: owner or URL of the certificate to be removed";
+
+
+ protected ConfigurationServiceProxy proxy;
+
+ protected RecordPrinter<org.nhind.config.Certificate> certPrinter;
+
+ public CertCommands(ConfigurationServiceProxy proxy)
+ {
+ this.proxy = proxy;
+
+ this.certPrinter = new CertRecordPrinter();
+ }
+
+ @Command(name = "ListCerts", usage = LIST_CERTIFICATES_USAGE)
+ public void listCerts(String[] args)
+ {
+ try
+ {
+ final org.nhind.config.Certificate[] certs = proxy.listCertificates(1,
1000, null);
+ if (certs == null || certs.length == 0)
+ System.out.println("No certificates found");
+ else
+ {
+ certPrinter.printRecords(Arrays.asList(certs));
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup certificates: " + e.getMessage());
+ }
+
+ }
+
+ @Command(name = "ListCertsByAddress", usage =
LIST_EMAIL_CERTIFICATES_USAGE)
+ public void listCertsByAddress(String[] args)
+ {
+ String owner = StringArrayUtil.getRequiredValue(args, 0);
+
+ try
+ {
+ final org.nhind.config.Certificate[] certs =
proxy.getCertificatesForOwner(owner, null);
+
+ if (certs == null || certs.length == 0)
+ System.out.println("No certificates found");
+ else
+ {
+ certPrinter.printRecords(Arrays.asList(certs));
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup certificates: " + e.getMessage());
+ }
+ }
+
+
+ @Command(name = "ExportCertByAddress", usage =
EXPORT_EMAIL_CERTIFICATES_USAGE)
+ public void exportCertByAddress(String[] args)
+ {
+ String owner = StringArrayUtil.getRequiredValue(args, 0);
+
+ try
+ {
+ final org.nhind.config.Certificate[] certs =
proxy.getCertificatesForOwner(owner, null);
+
+ if (certs == null || certs.length == 0)
+ System.out.println("No certificates found");
+ else
+ {
+ certPrinter.printRecords(Arrays.asList(certs));
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup certificates: " + e.getMessage());
+ }
+ }
+
+ @Command(name = "AddPublicCert", usage = IMPORT_PUBLIC_CERT_USAGE)
+ public void importPublicCert(String[] args)
+ {
+ final String fileLoc = StringArrayUtil.getRequiredValue(args, 0);
+ try
+ {
+ final X509Certificate cert = CertUtils.certFromFile(fileLoc);
+
+
+ final org.nhind.config.Certificate addCert = new
org.nhind.config.Certificate();
+ addCert.setData(cert.getEncoded());
+ addCert.setOwner(CryptoExtensions.getSubjectAddress(cert));
+ addCert.setPrivateKey(false);
+ addCert.setStatus(EntityStatus.ENABLED);
+
+ proxy.addCertificates(new org.nhind.config.Certificate[] {addCert});
+ System.out.println("Successfully imported public certificate.");
+
+ }
+ catch (IOException e)
+ {
+ System.out.println("Error reading file " + fileLoc + " : " +
e.getMessage());
+ return;
+ }
+ ///CLOVER:OFF
+ catch (Exception e)
+ {
+ System.out.println("Error importing certificate " + fileLoc + " : " +
e.getMessage());
+ }
+ ///CLOVER:ON
+
+ }
+
+ @Command(name = "AddPrivateCert", usage = IMPORT_PRIVATE_CERT_USAGE)
+ public void importPrivateCert(String[] args)
+ {
+ final String fileLoc = StringArrayUtil.getRequiredValue(args, 0);
+ final String passPhrase = StringArrayUtil.getOptionalValue(args, 1, "");
+ try
+ {
+
+ final byte[] certBytes = FileUtils.readFileToByteArray(new
File(fileLoc));
+
+ final byte[] insertBytes = (passPhrase == null ||
passPhrase.isEmpty()) ?
+ certBytes : CertUtils.pkcs12ToStrippedPkcs12(certBytes, passPhrase);
+
+ final X509Certificate cert = CertUtils.toX509Certificate(insertBytes);
+
+ org.nhind.config.Certificate addCert = new
org.nhind.config.Certificate();
+ addCert.setData(certBytes);
+ addCert.setOwner(CryptoExtensions.getSubjectAddress(cert));
+ addCert.setPrivateKey(cert instanceof X509CertificateEx);
+ addCert.setStatus(EntityStatus.ENABLED);
+
+ proxy.addCertificates(new org.nhind.config.Certificate[] {addCert});
+ System.out.println("Successfully imported private certificate.");
+
+ }
+ catch (IOException e)
+ {
+ System.out.println("Error reading file " + fileLoc + " : " +
e.getMessage());
+ return;
+ }
+ catch (Exception e)
+ {
+ System.out.println("Error importing certificate " + fileLoc + " : " +
e.getMessage());
+ }
+ }
+
+ @Command(name = "AddIPKIXCert", usage = ADD_IPKIX_CERT_USAGE)
+ public void addIPKIXCert(String[] args)
+ {
+ final String owner = StringArrayUtil.getRequiredValue(args, 0);
+ final String URL = StringArrayUtil.getRequiredValue(args, 1);
+
+ try
+ {
+
+ org.nhind.config.Certificate addCert = new
org.nhind.config.Certificate();
+ addCert.setData(URL.getBytes());
+ addCert.setOwner(owner);
+ addCert.setPrivateKey(false);
+ addCert.setStatus(EntityStatus.ENABLED);
+
+ proxy.addCertificates(new org.nhind.config.Certificate[] {addCert});
+ System.out.println("Successfully added IPKIX certificate URL.");
+
+
+ }
+ catch (Exception e)
+ {
+ System.out.println("Error add IPKIX URL: " + e.getMessage());
+ }
+ }
+
+ @Command(name = "RemoveCert", usage = REMOVED_CERTIFICATE_USAGE)
+ public void removeCert(String[] args)
+ {
+ final String owner = StringArrayUtil.getRequiredValue(args, 0);
+
+ try
+ {
+ proxy.removeCertificatesForOwner(owner);
+ System.out.println("Successfully removed certificate for owner." +
owner);
+ }
+ catch (Exception e)
+ {
+ System.out.println("Error removing certificate for owner " + owner
+ " : " + e.getMessage());
+ }
+ }
+
+ public void setRecordPrinter(RecordPrinter<org.nhind.config.Certificate>
printer)
+ {
+ this.certPrinter = printer;
+ }
+
+ public void setConfigurationProxy(ConfigurationServiceProxy proxy)
+ {
+ this.proxy = proxy;
+ }
+
+ protected void writeCertsToFiles(org.nhind.config.Certificate[] certs)
throws IOException
+ {
+ int idx = 1;
+ for (org.nhind.config.Certificate cert : certs)
+ {
+ X509Certificate transCert = this.certFromData(cert.getData());
+
+ String certFileName= "";
+ String extension = (transCert instanceof X509CertificateEx
) ? ".p12" : ".der";
+ String certFileHold = CryptoExtensions.getSubjectAddress(transCert) +
extension;
+ if (certs.length > 1)
+ {
+ int index = certFileHold.lastIndexOf(".");
+ if (index < 0)
+ certFileHold += "(" + idx + ")";
+ else
+ {
+ certFileName = certFileHold.substring(0, index - 1) + "(" + idx + ")"
+ certFileHold.substring(index);
+ }
+
+ }
+ else
+ certFileName = certFileHold;
+
+ File certFile = new File(certFileName);
+ if (certFile.exists())
+ certFile.delete();
+
+
+ System.out.println("Writing cert file: " + certFile.getAbsolutePath());
+ FileUtils.writeByteArrayToFile(certFile,
x509CertificateToBytes(transCert));
+
+ ++idx;
+ }
+ }
+
+ private X509Certificate certFromData(byte[] data)
+ {
+ X509Certificate retVal = null;
+ try
+ {
+ ByteArrayInputStream bais = new ByteArrayInputStream(data);
+
+ // lets try this a as a PKCS12 data stream first
+ try
+ {
+ KeyStore localKeyStore = KeyStore.getInstance("PKCS12",
CryptoExtensions.getJCEProviderName());
+
+ localKeyStore.load(bais, "".toCharArray());
+ Enumeration<String> aliases = localKeyStore.aliases();
+
+
+ // we are really expecting only one alias
+ if (aliases.hasMoreElements())
+ {
+ String alias = aliases.nextElement();
+ X509Certificate cert =
(X509Certificate)localKeyStore.getCertificate(alias);
+
+ // check if there is private key
+ Key key = localKeyStore.getKey(alias, "".toCharArray());
+ if (key != null && key instanceof PrivateKey)
+ {
+ retVal = X509CertificateEx.fromX509Certificate(cert,
(PrivateKey)key);
+ }
+ else
+ retVal = cert;
+
+ }
+ }
+ catch (Exception e)
+ {
+ // must not be a PKCS12 stream, go on to next step
+ }
+
+ if (retVal == null)
+ {
+ //try X509 certificate factory next
+ bais.reset();
+ bais = new ByteArrayInputStream(data);
+
+ retVal = (X509Certificate)
CertificateFactory.getInstance("X.509").generateCertificate(bais);
+ }
+ bais.close();
+ }
+ catch (Exception e)
+ {
+ throw new NHINDException("Data cannot be converted to a valid
X.509 Certificate", e);
+ }
+
+ return retVal;
+ }
+
+ public static byte[] x509CertificateToBytes(X509Certificate cert)
+ {
+ if (cert instanceof X509CertificateEx)
+ {
+ final ByteArrayOutputStream outStr = new ByteArrayOutputStream();
+ try
+ {
+ // return as a pkcs12 file with no encryption
+ final KeyStore convertKeyStore = KeyStore.getInstance("PKCS12",
CryptoExtensions.getJCEProviderName());
+ convertKeyStore.load(null, null);
+ final char[] emptyPass = "".toCharArray();
+
+ convertKeyStore.setKeyEntry("privCert", ((X509CertificateEx)
cert).getPrivateKey(), emptyPass, new java.security.cert.Certificate[]
{cert});
+ convertKeyStore.store(outStr, emptyPass);
+
+ return outStr.toByteArray();
+ }
+ ///CLOVER:OFF
+ catch (Exception e)
+ {
+ throw new NHINDException("Failed to convert certificate to a byte
stream.", e);
+ }
+ ///CLOVER:ON
+ finally
+ {
+ try {outStr.close(); }
+ catch (Exception e) {/* no-op */}
+ }
+ }
+ else
+ {
+ try
+ {
+ return cert.getEncoded();
+ }
+ ///CLOVER:OFF
+ catch (Exception e)
+ {
+ throw new NHINDException("Failed to convert certificate to a byte
stream.", e);
+ }
+ ///CLOVER:ON
+ }
+ }
+}
=======================================
--- /dev/null
+++
/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/ConfigManager.java
Tue Jan 20 13:19:34 2015 UTC
@@ -0,0 +1,119 @@
+package org.nhindirect.config.manager;
+
+import java.net.URL;
+import java.util.Arrays;
+
+import org.nhind.config.ConfigurationServiceProxy;
+import org.nhindirect.dns.tools.DNSRecordCommands;
+import org.nhindirect.dns.tools.utils.Commands;
+
+public class ConfigManager
+{
+ private static final String DEFAULT_CONFIG_URL
= "http://localhost:8081/config-service/ConfigurationService";
+
+ private final Commands commands;
+
+ private static boolean exitOnEndCommands = true;
+
+ /**
+ * Application entry point.
+ * @param args Command line arguments.
+ *
+ * @since 1.0
+ */
+ public static void main(String[] args)
+ {
+ String[] passArgs = null;
+ String configURL = null;
+
+ // get the config URL if it exist
+ if (args.length > 1)
+ {
+ // check if the first argument is the config url
+ if (args[0].equalsIgnoreCase("configurl"))
+ {
+ //the next argument should be the config URL
+ configURL = args[1];
+ if (args.length > 2)
+ passArgs = (String[])Arrays.copyOfRange(args, 2, args.length);
+ else
+ passArgs = new String[0];
+
+ }
+ }
+
+ if (configURL == null)
+ {
+ configURL = DEFAULT_CONFIG_URL;
+ passArgs = args;
+ }
+
+ ConfigManager manager = null;
+ try
+ {
+ manager = new ConfigManager(new URL(configURL));
+ }
+ catch (Exception e)
+ {
+ System.err.println("Invalid config URL");
+ }
+
+ boolean runCommand = false;
+
+ if (manager != null)
+ {
+ runCommand = manager.run(passArgs);
+ }
+
+ if (exitOnEndCommands)
+ System.exit(runCommand ? 0 : -1);
+ }
+
+ /**
+ * Constructor with the location of the configuration service.
+ * @param configURL URL containing the locations of the configuration
service.
+ *
+ * @since 1.0
+ */
+ public ConfigManager(URL configURL)
+ {
+ ConfigurationServiceProxy proxy = new
ConfigurationServiceProxy(configURL.toExternalForm());
+
+ commands = new Commands("Configuration Management Console");
+ commands.register(new DNSRecordCommands(proxy));
+ commands.register(new CertCommands(proxy));
+ commands.register(new PolicyCommands(proxy));
+
+ System.out.println("Configuration service URL: " +
configURL.toExternalForm());
+
+ }
+
+ /**
+ * Either executes commands from the command line or runs the manager
interactively.
+ * @param args Command arguments. If the arguments are empty, then the
manager runs interactively.
+ * @return True if the command was run successfully. False otherwise.
+ *
+ * @since 1.0
+ */
+ public boolean run(String[] args)
+ {
+ if (args != null && args.length > 0)
+ {
+ return commands.run(args);
+ }
+
+ commands.runInteractive();
+ System.out.println("Shutting Down Configuration Manager Console");
+ return true;
+ }
+
+ /**
+ * Determines if the application should exit when command processing is
complete. It may be desirable to set this
+ * to false if calling from another application context. The default is
true.
+ * @param exit True if the application should terminate on completing
processing commands. False otherwise.
+ */
+ public static void setExitOnEndCommands(boolean exit)
+ {
+ exitOnEndCommands = exit;
+ }
+}
=======================================
--- /dev/null
+++
/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/DNSRecordCommands.java
Tue Jan 20 13:19:34 2015 UTC
@@ -0,0 +1,692 @@
+/*
+Copyright (c) 2010, NHIN Direct Project
+All rights reserved.
+
+Authors:
+ Greg Meyer gm2...@cerner.com
+
+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 The NHIN Direct Project
(nhindirect.org).
+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 org.nhindirect.config.manager;
+
+import java.io.File;
+import java.rmi.RemoteException;
+import java.util.ArrayList;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.commons.io.FileUtils;
+import org.bouncycastle.util.Arrays;
+import org.nhind.config.ConfigurationServiceProxy;
+import org.nhind.config.DnsRecord;
+import org.nhindirect.config.manager.printers.DNSRecordPrinter;
+import org.nhindirect.config.manager.printers.DefaultDNSRecordPrinter;
+import org.nhindirect.dns.tools.utils.Command;
+import org.nhindirect.dns.tools.utils.StringArrayUtil;
+import org.xbill.DNS.Record;
+import org.xbill.DNS.Section;
+import org.xbill.DNS.Type;
+
+/**
+ * Command definition and logic for managing DNS records. Commands are
case-insensitive.
+ * @author Greg Meyer
+ *
+ * @since 1.0
+ */
+public class DNSRecordCommands
+{
+ private static final String IMPORT_MX_USAGE = "Import a new MX dns
record from a binary file." +
+ "\r\n\tfilepath " +
+ "\r\n\t filePath: path to the MX record binary file. Can have any
(or no extension)";
+
+ private static final String IMPORT_SOA_USAGE = "Import a new SOA dns
record from a binary file." +
+ "\r\n\tfilepath " +
+ "\r\n\t filePath: path to the SOA record binary file. Can have any
(or no extension)";
+
+ private static final String IMPORT_ADDRESS_USAGE = "Import a new A dns
record from a binary file." +
+ "\r\n\tfilepath " +
+ "\r\n\t filePath: path to the A record binary file. Can have any
(or no extension)";
+
+ private static final String ADD_MX_USAGE = "Add a new MX dns record." +
+ "\r\n" + DNSRecordParser.PARSE_MX_USAGE;
+
+ private static final String ENSURE_MX_USAGE = "Adds a new MX dns
record if an identical one does't already exist. " +
+ "\r\n" + DNSRecordParser.PARSE_MX_USAGE;
+
+ private static final String ADD_SOA_USAGE = "Add a new SOA dns
record." +
+ "\r\n" + DNSRecordParser.PARSE_SOA_USAGE;
+
+ private static final String ENSURE_SOA_USAGE = "Add a new SOA dns
record if an identical one does not exist." +
+ "\r\n" + DNSRecordParser.PARSE_SOA_USAGE;
+
+ private static final String ADD_ANAME_USAGE = "Add a new ANAME dns
record." +
+ "\r\n" + DNSRecordParser.PARSE_ANAME_USAGE;
+
+ private static final String ENSURE_ANAME_USAGE = "Add a new ANAME dns
record if an identical one does not exist." +
+ "\r\n" + DNSRecordParser.PARSE_ANAME_USAGE;
+
+ private static final String REMOVE_MX_USAGE = "Remove an existing MX
record by ID." +
+ "\r\n\trecordid" +
+ "\r\n\t recordid: record id to be removed from the database";
+
+
+ private static final String REMOVE_SOA_USAGE = "Remove an existing SOA
record by ID." +
+ "\r\n\trecordid" +
+ "\r\nt\t recordid: record id to be removed from the database";
+
+
+ private static final String REMOVE_ANAME_USAGE = "Remove an existing
ANAME record by ID." +
+ "\r\n\trecordid" +
+ "\r\n\t recordid: record id to be removed from the database";
+
+
+ private static final String GET_MX_USAGE = "Gets an existing MX record
by ID." +
+ "\r\n\trecordid" +
+ "\r\n\t recordid: record id to be retrieved from the database";
+
+
+ private static final String GET_SOA_USAGE = "Gets an existing SOA
record by ID." +
+ "\r\n\trecordid" +
+ "\r\n\t recordid: record id to be retrieved from the database";
+
+
+ private static final String GET_ANAME_USAGE = "Gets an existing ANAME
record by ID." +
+ "\r\n\trecordid";
+
+ private static final String GET_ALL_USAGE = "Gets all records in the
DNS store.";
+ private DNSRecordPrinter printer;
+ private DNSRecordParser parser;
+ private ConfigurationServiceProxy proxy;
+
+ /**
+ * Constructor that takes a reference to the configuration service
proxy.
+ * @param proxy Configuration service proxy for accessing the
configuration service.
+ *
+ * @since 1.0
+ */
+ public DNSRecordCommands(ConfigurationServiceProxy proxy)
+ {
+ parser = new DNSRecordParser();
+ printer = new DefaultDNSRecordPrinter();
+ this.proxy = proxy;
+ }
+
+ /*
+ * Convert a dnsjava record to a DnsRecord for use with the proxy.
+ */
+ private DnsRecord fromRecord(Record rec)
+ {
+ DnsRecord retVal = new DnsRecord();
+ retVal.setData(rec.rdataToWireCanonical());
+ retVal.setDclass(rec.getDClass());
+ retVal.setName(rec.getName().toString());
+ retVal.setTtl(rec.getTTL());
+ retVal.setType(rec.getType());
+
+ return retVal;
+ }
+
+ /*
+ * Loads a record from a file. Records are stored in raw wire format.
+ */
+ private DnsRecord loadAndVerifyDnsRecordFromBin(String path)
+ {
+ File recFile = new File(path);
+ if (!recFile.exists())
+ throw new IllegalArgumentException("Record file " +
recFile.getAbsolutePath() + " not found");
+
+ Record rec = null;
+ try
+ {
+ byte[] wire = FileUtils.readFileToByteArray(recFile);
+
+ rec = Record.fromWire(wire, Section.ANSWER);
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException("Error reading file " +
recFile.getAbsolutePath() + " : " + e.getMessage(), e);
+ }
+
+ return (rec != null) ? fromRecord(rec) : null;
+ }
+
+ /*
+ * Adds a DNS record to the configuration service.
+ */
+ private void addDNS(DnsRecord dnsRecord)
+ {
+ try
+ {
+ proxy.addDNS(new DnsRecord[] {dnsRecord});
+ System.out.println("Record added successfully.");
+ }
+ catch (RemoteException e)
+ {
+ throw new RuntimeException("Error adding DNS record: " +
e.getMessage(), e);
+ }
+
+ }
+
+ /*
+ * Removed a DNS record from the service
+ */
+ private void removeDNS(long recordId)
+ {
+ try
+ {
+ proxy.removeDNSByRecordId(recordId);
+ System.out.println("Record removed successfully.");
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException("Error accessing configuration service: " +
e.getMessage(), e);
+ }
+ }
+
+ /*
+ * Imports a specific DNS record type from a file.
+ */
+ private void importRecord(String path, int type)
+ {
+ DnsRecord dnsRecord = loadAndVerifyDnsRecordFromBin(path);
+
+ if (dnsRecord.getType() != type)
+ {
+ throw new IllegalArgumentException("File " + path + " does not contain
the requested record type");
+ }
+
+ addDNS(dnsRecord);
+ }
+
+ /**
+ * Imports an MX record from a file. The file contains the record in raw
DNS wire format.
+ * @param args The first entry in the array contains the file path
(required).
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_MX_Import", usage = IMPORT_MX_USAGE)
+ public void mXImport(String[] args)
+ {
+ String path = StringArrayUtil.getRequiredValue(args, 0);
+ importRecord(path, Type.MX);
+ }
+
+ /**
+ * Imports an SOA record from a file. The file contains the record in
raw DNS wire format.
+ * @param args The first entry in the array contains the file path
(required).
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_SOA_Import", usage = IMPORT_SOA_USAGE)
+ public void sOAImport(String[] args)
+ {
+ String path = StringArrayUtil.getRequiredValue(args, 0);
+ importRecord(path, Type.SOA);
+ }
+
+ /**
+ * Imports an A record from a file. The file contains the record in raw
DNS wire format.
+ * @param args The first entry in the array contains the file path
(required).
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_ANAME_Import", usage = IMPORT_ADDRESS_USAGE)
+ public void importAddress(String[] args)
+ {
+ String path = StringArrayUtil.getRequiredValue(args, 0);
+ importRecord(path, Type.A);
+ }
+
+ /**
+ * Adds an MX records to the configuration service.
+ * @param args Contains the MX record attributes.
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_MX_Add", usage = ADD_MX_USAGE)
+ public void addMX(String[] args)
+ {
+ DnsRecord record = fromRecord(parser.parseMX(args));
+
+ addDNS(record);
+ }
+
+ /**
+ * Adds an MX records to the configuration service only if the record
does not exist.
+ * @param args Contains the MX record attributes.
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_MX_Ensure", usage = ENSURE_MX_USAGE)
+ public void ensureMX(String[] args)
+ {
+ DnsRecord record = fromRecord(parser.parseMX(args));
+ if (!verifyIsUnique(record, false))
+ {
+ return;
+ }
+
+
+ addDNS(record);
+ }
+
+ /**
+ * Adds an SOA records to the configuration service.
+ * @param args Contains the SOA record attributes.
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_SOA_Add", usage = ADD_SOA_USAGE)
+ public void addSOA(String[] args)
+ {
+ DnsRecord record = fromRecord(parser.parseSOA(args));
+
+ addDNS(record);
+ }
+
+ /**
+ * Adds an SOA records to the configuration service only if the record
does not exist.
+ * @param args Contains the SOA record attributes.
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_SOA_Ensure", usage = ENSURE_SOA_USAGE)
+ public void ensureSOA(String[] args)
+ {
+ DnsRecord record = fromRecord(parser.parseSOA(args));
+ if (!verifyIsUnique(record, false))
+ {
+ return;
+ }
+
+ addDNS(record);
+ }
+
+ /**
+ * Adds an A records to the configuration service.
+ * @param args Contains the A record attributes.
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_ANAME_Add", usage = ADD_ANAME_USAGE)
+ public void addANAME(String[] args)
+ {
+ DnsRecord record = fromRecord(parser.parseANAME(args));
+ addDNS(record);
+ }
+
+
+ /**
+ * Adds an A records to the configuration service only if the record does
not exist.
+ * @param args Contains the A record attributes.
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_ANAME_Ensure", usage = ENSURE_ANAME_USAGE)
+ public void ensureANAME(String[] args)
+ {
+ DnsRecord record = fromRecord(parser.parseANAME(args));
+ if (!verifyIsUnique(record, false))
+ {
+ return;
+ }
+
+ addDNS(record);
+ }
+
+ /**
+ * Removes an MX record from the configuration service by record id.
+ * @param args The first entry in the array contains the record id
(required).
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_MX_Remove", usage = REMOVE_MX_USAGE)
+ public void removeMX(String[] args)
+ {
+ long recordID = Long.parseLong(StringArrayUtil.getRequiredValue(args,
0));
+ removeDNS(recordID);
+ }
+
+ /**
+ * Removes an SOA record from the configuration service by record id.
+ * @param args The first entry in the array contains the record id
(required).
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_SOA_Remove", usage = REMOVE_SOA_USAGE)
+ public void removeSOA(String[] args)
+ {
+ long recordID = Long.parseLong(StringArrayUtil.getRequiredValue(args,
0));
+ removeDNS(recordID);
+ }
+
+ /**
+ * Removes an A record from the configuration service by record id.
+ * @param args The first entry in the array contains the record id
(required).
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_ANAME_Remove", usage = REMOVE_ANAME_USAGE)
+ public void removeANAME(String[] args)
+ {
+ long recordID = Long.parseLong(StringArrayUtil.getRequiredValue(args,
0));
+ removeDNS(recordID);
+ }
+
+ /**
+ * Looks up an MX record by record id.
+ * @param args The first entry in the array contains the record id
(required).
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_MX_Get", usage = GET_MX_USAGE)
+ public void getMX(String[] args)
+ {
+ get(Long.parseLong(StringArrayUtil.getRequiredValue(args, 0)));
+ }
+
+ /**
+ * Looks up an SOA record by record id.
+ * @param args The first entry in the array contains the record id
(required).
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_SOA_Get", usage = GET_SOA_USAGE)
+ public void getSOA(String[] args)
+ {
+ get(Long.parseLong(StringArrayUtil.getRequiredValue(args, 0)));
+ }
+
+ /**
+ * Looks up an A record by record id.
+ * @param args The first entry in the array contains the record id
(required).
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_ANAME_Get", usage = GET_ANAME_USAGE)
+ public void getANAME(String[] args)
+ {
+ get(Long.parseLong(StringArrayUtil.getRequiredValue(args, 0)));
+ }
+
+ /**
+ * Retrieves and prints all records in the configuration store.
+ * @param args Empty
+ *
+ * @since 1.0
+ */
+ @Command(name= "Dns_Get_All", usage = GET_ALL_USAGE)
+ public void getAll(String[] args)
+ {
+ DnsRecord[] records = null;
+ try
+ {
+ records = proxy.getDNSByType(Type.ANY);
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException("Error accessing configuration service: " +
e.getMessage(), e);
+ }
+
+ if (records == null || records.length == 0)
+ {
+ System.out.println("No records found");
+ }
+ else
+ print(records);
+ }
+
+ /*
+ * Gets and prints a record by record is
+ */
+ private void get(long recordID)
+ {
+ DnsRecord record = getRecord(recordID);
+ if (record != null)
+ printer.print(record);
+ }
+
+ /**
+ * Looks up all records for a given domain and any sub domains.
+ * @param args The first entry in the array contains the domain name
(required).
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_Match", usage = "Resolve all records for the given
domain")
+ public void match(String[] args)
+ {
+ String domain = StringArrayUtil.getRequiredValue(args, 0);
+ DnsRecord[] records = null;
+ Pattern pattern = Pattern.compile(domain);
+ ArrayList<DnsRecord> matchedRecords = new ArrayList<DnsRecord>();
+ try
+ {
+ records = proxy.getDNSByType(Type.ANY);
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException("Error accessing configuration service: " +
e.getMessage(), e);
+ }
+
+ if (records == null || records.length == 0)
+ {
+ System.out.println("No records found");
+ return;
+ }
+ else
+ {
+ for (DnsRecord record : records)
+ {
+ Matcher matcher = pattern.matcher(record.getName());
+ if (matcher.find())
+ {
+ matchedRecords.add(record);
+ }
+ }
+ }
+
+ if (matchedRecords.size() == 0)
+ {
+ System.out.println("No records found");
+ return;
+ }
+
+ print(matchedRecords.toArray(new DnsRecord[matchedRecords.size()]));
+ }
+
+ /**
+ * Looks up SOA records for a given domain.
+ * @param args The first entry in the array contains the domain name
(required).
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_SOA_Match", usage = "Resolve SOA records for the
given domain")
+ public void matchSOA(String[] args)
+ {
+ match(StringArrayUtil.getRequiredValue(args, 0), Type.SOA);
+ }
+
+ /**
+ * Looks up A records for a given host name.
+ * @param args The first entry in the array contains the domain name
(required).
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_ANAME_Match", usage = "Resolve Address records for
the given domain")
+ public void matchAName(String[] args)
+ {
+ match(StringArrayUtil.getRequiredValue(args, 0), Type.A);
+ }
+
+ /**
+ * Looks up MX records for a given domain.
+ * @param args The first entry in the array contains the domain name
(required).
+ *
+ * @since 1.0
+ */
+ @Command(name = "Dns_MX_Match", usage = "Resolve MX records for the given
domain")
+ public void matchMX(String[] args)
+ {
+ match(StringArrayUtil.getRequiredValue(args, 0), Type.MX);
+ }
+
+ /*
+ * gets records for a domain name and sub domains for a specific type of
record
+ */
+ private void match(String domain, int type)
+ {
+ DnsRecord[] records = getRecords(domain, type);
+ if (records != null && records.length > 0)
+ print(records);
+ }
+
+ /*
+ * gets a record by record id
+ */
+ private DnsRecord getRecord(long recordID)
+ {
+ DnsRecord dr = null;
+ try
+ {
+ dr = proxy.getDNSByRecordId(recordID);
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException("Error accessing configuration service: " +
e.getMessage(), e);
+ }
+
+ if (dr == null)
+ {
+ System.out.println("No record found matching id.");
+ }
+
+ return dr;
+ }
+
+ /*
+ * gets records by name and type
+ */
+ private DnsRecord[] getRecords(String domain, int type)
+ {
+ if (!domain.endsWith("."))
+ domain += ".";
+
+ DnsRecord[] records = null;
+ try
+ {
+ records = proxy.getDNSByNameAndType(domain, type);
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException("Error accessing configuration service: " +
e.getMessage(), e);
+ }
+
+ if (records == null || records.length == 0)
+ {
+ System.out.println("No records found");
+ }
+ return records;
+ }
+
+ /*
+ * ensures that a record is unique in the configuration service
+ */
+ private boolean verifyIsUnique(DnsRecord record, boolean details)
+ {
+ DnsRecord existing = find(record);
+ if (existing != null)
+ {
+ System.out.println("Record already exists");
+
+ print(existing);
+
+ return false;
+ }
+
+ return true;
+ }
+
+ /*
+ * finds a specific record by name and type
+ */
+ private DnsRecord find(DnsRecord record)
+ {
+ DnsRecord[] existingRecords = null;
+ try
+ {
+ existingRecords = proxy.getDNSByNameAndType(record.getName(),
record.getType());
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException("Error accessing configuration service: " +
e.getMessage(), e);
+ }
+
+ if (existingRecords == null || existingRecords.length == 0)
+ {
+ return null;
+ }
+
+ for (DnsRecord existingRecord : existingRecords)
+ if (Arrays.areEqual(record.getData(), existingRecord.getData()))
+ return existingRecord;
+
+ return null;
+ }
+
+ /*
+ * prints the contents of an array of records
+ */
+ private void print(DnsRecord[] records)
+ {
+ if (records != null)
+ {
+ for(DnsRecord record : records)
+ {
+ print(record);
+
System.out.println("\r\n-------------------------------------------");
+ }
+ }
+ }
+
+ /*
+ * prints the contents of a specific record
+ */
+ private void print(DnsRecord dnsRecord)
+ {
+ System.out.println("RecordID: " + dnsRecord.getId());
+
+
+ printer.print(dnsRecord);
+
+ }
+
+ /**
+ * Sets the printer that will be used to print record query responses.
+ * @param printer The printer that will be used to print record query
responses.
+ */
+ public void setRecordPrinter(DNSRecordPrinter printer)
+ {
+ this.printer = printer;
+ }
+
+ /**
+ * Sets the printer that will be used to print record query responses.
+ * @param printer The printer that will be used to print record query
responses.
+ */
+ public void setConfigurationProxy(ConfigurationServiceProxy proxy)
+ {
+ this.proxy = proxy;
+ }
+}
=======================================
--- /dev/null
+++
/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/DNSRecordParser.java
Tue Jan 20 13:19:34 2015 UTC
@@ -0,0 +1,163 @@
+/*
+Copyright (c) 2010, NHIN Direct Project
+All rights reserved.
+
+Authors:
+ Greg Meyer gm2...@cerner.com
+
+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 The NHIN Direct Project
(nhindirect.org).
+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 org.nhindirect.config.manager;
+
+import java.net.InetAddress;
+
+import org.nhindirect.dns.tools.utils.StringArrayUtil;
+import org.xbill.DNS.ARecord;
+import org.xbill.DNS.DClass;
+import org.xbill.DNS.MXRecord;
+import org.xbill.DNS.Name;
+import org.xbill.DNS.SOARecord;
+
+/**
+ * Parses an array of strings into DNS records.
+ * @author Greg Meyer
+ *
+ * @since 1.0
+ */
+public class DNSRecordParser
+{
+ public static final String PARSE_ANAME_USAGE = " hostname ipaddress ttl
[notes]" +
+ "\r\n\t hostname: host name for the record" +
+ "\r\n\t ipaddress: IP address in dot notation" +
+ "\r\n\t ttl: time to live in seconds, 32bit int";
+
+ public static final String PARSE_SOA_USAGE = " domainname
primarysourcedomain responsibleemail serialnumber ttl [refresh] [retry]
[expire] [minimum] [notes]" +
+ "\r\n\t domainname: The domain name of the name server that was the
primary source for this zone" +
+ "\r\n\t responsibleemail: Email mailbox of the hostmaster" +
+ "\r\n\t serialnumber: Version number of the original copy of the
zone." +
+ "\r\n\t ttl: time to live in seconds, 32bit int" +
+ "\r\n\t [refresh]: Number of seconds before the zone should be
refreshed." +
+ "\r\n\t [retry]: Number of seconds before failed refresh should be
retried." +
+ "\r\n\t [expire]: Number of seconds before records should be
expired if not refreshed" +
+ "\r\n\t [minimum]: Minimum TTL for this zone.";
+
+ public static final String PARSE_MX_USAGE = " domainname exchange ttl
[preference] [notes]" +
+ "\r\n\t domainname: email domain name for the record" +
+ "\r\n\t exchange: smtp server host name for the domain" +
+ "\r\n\t ttl: time to live in seconds" +
+ "\r\n\t [preference]: short value indicating preference of the
record";
+
+ /**
+ * Default empty constructor
+ *
+ * @since 1.0
+ */
+ public DNSRecordParser()
+ {
+ }
+
+ /*
+ * converts a string to a dnsjava Name
+ */
+ private Name nameFromString(String str)
+ {
+ if (!str.endsWith("."))
+ str += ".";
+
+ try
+ {
+ return Name.fromString(str);
+ }
+ catch (Exception e)
+ {
+ throw new IllegalArgumentException("Invalid DNS name");
+ }
+ }
+
+ /*
+ * converts a string to a InetAddress object
+ */
+ private InetAddress inetFromString(String str)
+ {
+ try
+ {
+ return InetAddress.getByName(str);
+ }
+ catch (Exception e)
+ {
+ throw new IllegalArgumentException("Invalid ip address");
+ }
+ }
+
+ /**
+ * Converts A record configuration information to an ARecord
+ * @param args The A record configuration parameters.
+ * @return A DNS ARecord.
+ *
+ * @since 1.0
+ */
+ public ARecord parseANAME(String[] args)
+ {
+
+ String domainName = StringArrayUtil.getRequiredValue(args, 0);
+ String ipAddress = StringArrayUtil.getRequiredValue(args, 1);
+ int ttl = Integer.parseInt(StringArrayUtil.getRequiredValue(args, 2));
+
+ return new ARecord(nameFromString(domainName), DClass.IN, ttl,
inetFromString(ipAddress));
+
+ }
+
+ /**
+ * Converts SAO record configuration information to an SOARecord
+ * @param args The SOA record configuration parameters.
+ * @return A DNS SAORecord.
+ *
+ * @since 1.0
+ */
+ public SOARecord parseSOA(String[] args)
+ {
+ String domainName = StringArrayUtil.getRequiredValue(args, 0);
+ String primarySourceDomain = StringArrayUtil.getRequiredValue(args,
1);
+ String responsibleEmail = StringArrayUtil.getRequiredValue(args, 2);
+ int serialNumber =
Integer.parseInt(StringArrayUtil.getRequiredValue(args, 3));
+ int ttl = Integer.parseInt(StringArrayUtil.getRequiredValue(args, 4));
+
+ int refresh = Integer.parseInt(StringArrayUtil.getOptionalValue(args,
5, "0"));
+ int retry = Integer.parseInt(StringArrayUtil.getOptionalValue(args,
6, "0"));
+ int expire = Integer.parseInt(StringArrayUtil.getOptionalValue(args,
7, "0"));
+ int minimum = Integer.parseInt(StringArrayUtil.getOptionalValue(args,
8, "0"));
+
+ return new SOARecord(nameFromString(domainName), DClass.IN, ttl,
nameFromString(primarySourceDomain),
+ nameFromString(responsibleEmail), serialNumber, refresh, retry,
expire, minimum);
+
+ }
+
+ /**
+ * Converts MX record configuration information to an MXRecord
+ * @param args The MX record configuration parameters.
+ * @return A DNS MXRecord.
+ *
+ * @since 1.0
+ */
+ public MXRecord parseMX(String[] args)
+ {
+ String domainName = StringArrayUtil.getRequiredValue(args, 0);
+ String exchange = StringArrayUtil.getRequiredValue(args, 1);
+ int ttl = Integer.parseInt(StringArrayUtil.getRequiredValue(args, 2));
+ short pref = Short.parseShort(StringArrayUtil.getOptionalValue(args,
3, "0"));
+
+ return new MXRecord(nameFromString(domainName), DClass.IN, ttl, pref,
nameFromString(exchange));
+ }
+}
=======================================
--- /dev/null
+++
/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/PolicyCommands.java
Tue Jan 20 13:19:34 2015 UTC
@@ -0,0 +1,687 @@
+package org.nhindirect.config.manager;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.nhind.config.CertPolicyGroupDomainReltn;
+import org.nhind.config.ConfigurationServiceProxy;
+import org.nhind.config.Domain;
+import org.nhind.config.PolicyLexicon;
+import org.nhindirect.config.manager.printers.PolicyGroupPrinter;
+import org.nhindirect.config.manager.printers.PolicyPrinter;
+import org.nhindirect.config.manager.printers.PolicyUsagePrinter;
+import org.nhindirect.dns.tools.utils.Command;
+import org.nhindirect.dns.tools.utils.StringArrayUtil;
+import org.nhindirect.policy.PolicyLexiconParser;
+import org.nhindirect.policy.PolicyLexiconParserFactory;
+import org.nhindirect.policy.PolicyParseException;
+
+
+public class PolicyCommands
+{
+ private static final String LIST_POLICIES_USAGE = "Lists policies in
the system";
+
+ private static final String IMPORT_POLICY_USAGE = "Imports a policy
from a file with an optional lexicon definition." +
+ "\r\n policyName policyDefFile [lexicon]" +
+ "\r\n\t policyName: Name of the policy. Place the policy name
in quotes (\"\") if there are spaces in the name." +
+ "\r\n\t policyDefFile: Fully qualified path and file name of
the policy definition file. Place the file name in quotes (\"\") if there
are spaces in the path or name." +
+ "\r\n\t [lexicon]: Optional lexicon of the policy definition.
Default to SIMPLE_TEXT_V1 if not supplied.";
+
+ private static final String DELETE_POLICY_USAGE = "Deletes a policy
from the system by policy name." +
+ "\r\n policyName " +
+ "\r\n\t policyName: Name of the policy. Place the policy name
in quotes (\"\") if there are spaces in the name.";
+
+ private static final String LIST_POLICY_GROUPS_USAGE = "Lists policy
groups in the system";
+
+ private static final String ADD_POLICY_GROUP_USAGE = "Adds policy
group to the system" +
+ "\r\n groupName " +
+ "\r\n\t groupName: Name of the policy group. Place the policy
group name in quotes (\"\") if there are spaces in the name.";
+
+ private static final String DELETE_POLICY_GROUP_USAGE = "Deletes a
policy group from the system by policy group name." +
+ "\r\n groupName " +
+ "\r\n\t groupName: Name of the policy group. Place the policy
group name in quotes (\"\") if there are spaces in the name.";
+
+ private static final String LIST_GROUP_POLICIES_USAGE = "List policies
and usage within a policy group." +
+ "\r\n groupName " +
+ "\r\n\t groupName: Name of the policy group. Place the policy
group name in quotes (\"\") if there are spaces in the name.";
+
+ private static final String ADD_POLICY_TO_GROUP_USAGE = "Adds an
existing policy to a group with a provided usage." +
+ "\r\n policyName groupNames policyUse incoming outgoing" +
+ "\r\n\t policyName: Name of the policy to add to the group.
Place the policy name in quotes (\"\") if there are spaces in the name." +
+ "\r\n\t groupName: Name of the policy group to add the policy to.
Place the policy group name in quotes (\"\") if there are spaces in the
name." +
+ "\r\n\t policyUse: Usage name of the policy in the group. Must be
one of the following values: TRUST, PRIVATE_RESOLVER, PUBLIC_RESOLVER." +
+ "\r\n\t incoming: Indicates if policy is used for incoming
messages. Must be one of the following values: true, false" +
+ "\r\n\t outgoing: Indicates if policy is used for outgoing
messages. Must be one of the following values: true, false";
+
+ private static final String DELETE_POLICY_FROM_GROUP_USAGE = "Deletes
an existing policy from a group." +
+ "\r\n policyName groupName" +
+ "\r\n\t policyName: Name of the policy to delete from the
group. Place the policy name in quotes (\"\") if there are spaces in the
name." +
+ "\r\n\t groupName: Name of the policy group to delete the policy
from. Place the policy group name in quotes (\"\") if there are spaces in
the name.";
+
+ private static final String LIST_DOMAIN_POLICY_GROUPS = "List policy
groups within a domain" +
+ "\r\n domainName" +
+ "\r\n\t domainName: Name of the domain.";
+
+ private static final String ADD_GROUP_TO_DOMAIN_USAGE = "Adds an
existing policy group to an existing domain." +
+ "\r\n groupName domainName" +
+ "\r\n\t groupName: Name of the policy group to add to the domain.
Place the policy group name in quotes (\"\") if there are spaces in the
name." +
+ "\r\n\t domainName: Name of the domain to add the group to.";
+
+ private static final String DELETE_GROUP_FROM_DOMAIN_USAGE = "Deletes
an existing policy group from a domain." +
+ "\r\n groupName domainName " +
+ "\r\n\t groupName: Name of the policy group to delete from the
domain. Place the policy group name in quotes (\"\") if there are spaces
in the name." +
+ "\r\n\t domainName: Name of the domain to delete the policy group
from.";
+
+ protected ConfigurationServiceProxy proxy;
+
+ protected final PolicyPrinter policyPrinter;
+ protected final PolicyGroupPrinter groupPrinter;
+ protected final PolicyUsagePrinter policyUsagePrinter;
+
+ public PolicyCommands(ConfigurationServiceProxy proxy)
+ {
+ this.proxy = proxy;
+
+ policyPrinter = new PolicyPrinter();
+ groupPrinter = new PolicyGroupPrinter();
+ policyUsagePrinter = new PolicyUsagePrinter();
+ }
+
+ @Command(name = "ListPolicies", usage = LIST_POLICIES_USAGE)
+ public void listPolicies(String[] args)
+ {
+ try
+ {
+ final org.nhind.config.CertPolicy[] policies = proxy.getPolicies();
+ if (policies == null || policies.length == 0)
+ System.out.println("No policies found");
+ else
+ {
+ policyPrinter.printRecords(Arrays.asList(policies));
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup policies: " + e.getMessage());
+ }
+
+ }
+
+ @Command(name = "ImportPolicy", usage = IMPORT_POLICY_USAGE)
+ public void importPolicy(String[] args)
+ {
+ final String policyName = StringArrayUtil.getRequiredValue(args, 0);
+ final String fileLoc = StringArrayUtil.getRequiredValue(args, 1);
+ final String lexicon = StringArrayUtil.getOptionalValue(args, 2, "");
+
+ // check if the policy already exists
+ try
+ {
+ org.nhind.config.CertPolicy policy = proxy.getPolicyByName(policyName);
+ if (policy != null)
+ {
+ System.out.println("Policy with name " + policyName + " already
exists.");
+ return;
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup policy: " + e.getMessage());
+ return;
+ }
+
+ PolicyLexicon lex;
+
+
+ if (lexicon.isEmpty())
+ lex = PolicyLexicon.SIMPLE_TEXT_V1;
+ else
+ {
+ try
+ {
+ lex = PolicyLexicon.fromString(lexicon);
+ }
+ catch (Exception e)
+ {
+ System.out.println("Invalid lexicon name.");
+ return;
+ }
+ }
+
+ // validate the policy syntax
+ final org.nhindirect.policy.PolicyLexicon parseLexicon;
+ if (lex.equals(org.nhind.config.PolicyLexicon.JAVA_SER))
+ parseLexicon = org.nhindirect.policy.PolicyLexicon.JAVA_SER;
+ else if (lex.equals(org.nhind.config.PolicyLexicon.SIMPLE_TEXT_V1))
+ parseLexicon = org.nhindirect.policy.PolicyLexicon.SIMPLE_TEXT_V1;
+ else
+ parseLexicon = org.nhindirect.policy.PolicyLexicon.XML;
+
+ byte[] policyBytes;
+ InputStream inStr = null;
+ try
+ {
+ policyBytes = FileUtils.readFileToByteArray(new File(fileLoc));
+ inStr = new ByteArrayInputStream(policyBytes);
+
+ final PolicyLexiconParser parser =
PolicyLexiconParserFactory.getInstance(parseLexicon);
+ parser.parse(inStr);
+ }
+ catch (PolicyParseException e)
+ {
+ System.out.println("Syntax error in policy file " + fileLoc + " : " +
e.getMessage());
+ return;
+ }
+ catch (IOException e)
+ {
+ System.out.println("Error reading file " + fileLoc + " : " +
e.getMessage());
+ return;
+ }
+ finally
+ {
+ IOUtils.closeQuietly(inStr);
+ }
+
+
+ try
+ {
+ org.nhind.config.CertPolicy addPolicy = new
org.nhind.config.CertPolicy();
+ addPolicy.setPolicyData(policyBytes);
+ addPolicy.setPolicyName(policyName);
+ addPolicy.setLexicon(lex);
+
+ proxy.addPolicy(addPolicy);
+ System.out.println("Successfully imported policy.");
+
+ }
+ catch (IOException e)
+ {
+ System.out.println("Error reading file " + fileLoc + " : " +
e.getMessage());
+ return;
+ }
+ catch (Exception e)
+ {
+ System.out.println("Error importing certificate " + fileLoc + " : " +
e.getMessage());
+ }
+ }
+
+ @Command(name = "DeletePolicy", usage = DELETE_POLICY_USAGE)
+ public void deletePolicy(String[] args)
+ {
+ // make sure the policy exists
+ final String policyName = StringArrayUtil.getRequiredValue(args, 0);
+ org.nhind.config.CertPolicy policy = null;
+
+ try
+ {
+ policy = proxy.getPolicyByName(policyName);
+ if (policy == null)
+ {
+ System.out.println("No policy with name " + policyName + " found");
+ return;
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup policy: " + e.getMessage());
+ return;
+ }
+
+ // now delete the policy
+ try
+ {
+ proxy.deletePolicies(new Long[] {policy.getId()});
+ System.out.println("Policy successfully deleted");
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to delete policy: " + e.getMessage());
+ return;
+ }
+
+ }
+
+ @Command(name = "ListPolicyGroups", usage = LIST_POLICY_GROUPS_USAGE)
+ public void listPolicyGroups(String[] args)
+ {
+ try
+ {
+ org.nhind.config.CertPolicyGroup[] groups = proxy.getPolicyGroups();
+ if (groups == null || groups.length == 0)
+ System.out.println("No policy groups found");
+ else
+ {
+ groupPrinter.printRecords(Arrays.asList(groups));
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup policies: " + e.getMessage());
+ }
+ }
+
+ @Command(name = "AddPolicyGroup", usage = ADD_POLICY_GROUP_USAGE)
+ public void addPolicyGroup(String[] args)
+ {
+ final String policyGroupName = StringArrayUtil.getRequiredValue(args, 0);
+
+ // check if the group already exists
+ try
+ {
+ org.nhind.config.CertPolicyGroup policyGroup =
proxy.getPolicyGroupByName(policyGroupName);
+ if (policyGroup != null)
+ {
+ System.out.println("Policy group with name " + policyGroupName + "
already exists.");
+ return;
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup policy: " + e.getMessage());
+ return;
+ }
+
+ // now add the group
+ try
+ {
+ org.nhind.config.CertPolicyGroup policyGroup = new
org.nhind.config.CertPolicyGroup();
+ policyGroup.setPolicyGroupName(policyGroupName);
+
+ proxy.addPolicyGroup(policyGroup);
+
+ System.out.println("Successfully added policy group.");
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to add policy group: " + e.getMessage());
+ return;
+ }
+ }
+
+ @Command(name = "DeletePolicyGroup", usage = DELETE_POLICY_GROUP_USAGE)
+ public void deletePolicyGroup(String[] args)
+ {
+ // make sure the group exists
+ final String policyGroupName = StringArrayUtil.getRequiredValue(args, 0);
+ org.nhind.config.CertPolicyGroup group = null;
+
+ try
+ {
+ group = proxy.getPolicyGroupByName(policyGroupName);
+ if (group == null)
+ {
+ System.out.println("No policy group with name " + policyGroupName + "
found");
+ return;
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup policy group: " + e.getMessage());
+ return;
+ }
+
+ // now delete the policy group
+ try
+ {
+ proxy.deletePolicyGroups(new Long[] {group.getId()});
+ System.out.println("Policy groups successfully deleted");
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to delete policy group: " + e.getMessage());
+ return;
+ }
+
+ }
+
+ @Command(name = "ListGroupPolicies", usage = LIST_GROUP_POLICIES_USAGE)
+ public void listGroupPolicies(String[] args)
+ {
+ // make sure the group exists
+ final String policyGroupName = StringArrayUtil.getRequiredValue(args, 0);
+ org.nhind.config.CertPolicyGroup group = null;
+
+ try
+ {
+ group = proxy.getPolicyGroupByName(policyGroupName);
+ if (group == null)
+ {
+ System.out.println("No policy group with name " + policyGroupName + "
found");
+ return;
+ }
+ else if (group.getCertPolicyGroupReltn() == null ||
group.getCertPolicyGroupReltn().length == 0)
+ {
+ System.out.println("Group has no policies associated with it.");
+ return;
+ }
+
+
policyUsagePrinter.printRecords(Arrays.asList(group.getCertPolicyGroupReltn()));
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup policy group: " + e.getMessage());
+ return;
+ }
+ }
+
+ @Command(name = "AddPolicyToGroup", usage = ADD_POLICY_TO_GROUP_USAGE)
+ public void addPolicyToGroup(String[] args)
+ {
+ // make sure the group exists
+ final String policyName = StringArrayUtil.getRequiredValue(args, 0);
+ final String groupName = StringArrayUtil.getRequiredValue(args, 1);
+ final String policyUse = StringArrayUtil.getRequiredValue(args, 2);
+ final boolean incoming =
Boolean.parseBoolean(StringArrayUtil.getRequiredValue(args, 3));
+ final boolean outgoing =
Boolean.parseBoolean(StringArrayUtil.getRequiredValue(args, 4));
+
+ // make sure the policy exists
+ org.nhind.config.CertPolicy policy = null;
+ try
+ {
+ policy = proxy.getPolicyByName(policyName);
+ if (policy == null)
+ {
+ System.out.println("No policy with name " + policyName + " found");
+ return;
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup policy: " + e.getMessage());
+ return;
+ }
+
+ // make sure the group exists
+ org.nhind.config.CertPolicyGroup group = null;
+ try
+ {
+ group = proxy.getPolicyGroupByName(groupName);
+ if (group == null)
+ {
+ System.out.println("No policy group with name " + groupName + "
found");
+ return;
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup policy group: " + e.getMessage());
+ return;
+ }
+
+ final org.nhind.config.CertPolicyUse use =
org.nhind.config.CertPolicyUse.fromString(policyUse);
+ if (use == null)
+ {
+ System.out.println("Unknow usage type");
+ return;
+ }
+
+ try
+ {
+ proxy.addPolicyUseToGroup(group.getId(), policy.getId(), use, incoming,
outgoing);
+ System.out.println("Successfully added policy to group.");
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to add policy to group: " + e.getMessage());
+ return;
+ }
+ }
+
+ @Command(name = "DeletePolicyFromGroup", usage =
DELETE_POLICY_FROM_GROUP_USAGE)
+ public void deletePolicyFromGroup(String[] args)
+ {
+ // make sure the group exists
+ final String policyName = StringArrayUtil.getRequiredValue(args, 0);
+ final String groupName = StringArrayUtil.getRequiredValue(args, 1);
+ long policyReltnId = -1;
+
+ // make sure the group exists
+ org.nhind.config.CertPolicyGroup group = null;
+ try
+ {
+ group = proxy.getPolicyGroupByName(groupName);
+ if (group == null)
+ {
+ System.out.println("No policy group with name " + groupName + "
found");
+ return;
+ }
+ else
+ {
+ if (group.getCertPolicyGroupReltn() == null ||
group.getCertPolicyGroupReltn().length == 0)
+ {
+ System.out.println("Policy is not associated with group.");
+ return;
+ }
+ else
+ {
+ for (org.nhind.config.CertPolicyGroupReltn reltn :
group.getCertPolicyGroupReltn())
+ {
+ if
(reltn.getCertPolicy().getPolicyName().compareToIgnoreCase(policyName) == 0)
+ {
+ policyReltnId = reltn.getId();
+ break;
+ }
+
+ }
+ if (policyReltnId == -1)
+ {
+ System.out.println("Policy is not associated with group.");
+ return;
+ }
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup policy group: " + e.getMessage());
+ return;
+ }
+
+ try
+ {
+ proxy.removePolicyUseFromGroup(policyReltnId);
+ System.out.println("Successfully delete policy from group.");
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to delete policy from group: " +
e.getMessage());
+ return;
+ }
+ }
+
+ @Command(name = "ListDomainPolicyGroups", usage =
LIST_DOMAIN_POLICY_GROUPS)
+ public void listDomainPolicyGroups(String[] args)
+ {
+ final String domainName = StringArrayUtil.getRequiredValue(args, 0);
+
+ // make sure the domain exists
+ Domain[] domains;
+ try
+ {
+ domains = proxy.getDomains(new String[]{domainName}, null);
+ if (domains == null || domains.length == 0)
+ {
+ System.out.println("No domain with name " + domainName + " found");
+ return;
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup domain: " + e.getMessage());
+ return;
+ }
+
+ try
+ {
+ final CertPolicyGroupDomainReltn[] reltns =
proxy.getPolicyGroupsByDomain(domains[0].getId());
+ if (reltns == null || reltns.length == 0)
+ {
+ System.out.println("Domain does not have any policy groups associated
with it.");
+ return;
+ }
+
+ List<org.nhind.config.CertPolicyGroup> groups = new
ArrayList<org.nhind.config.CertPolicyGroup>();
+ for (CertPolicyGroupDomainReltn reltn : reltns)
+ groups.add(reltn.getCertPolicyGroup());
+
+ groupPrinter.printRecords(groups);
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup domain policy groups: " +
e.getMessage());
+ return;
+ }
+ }
+
+ @Command(name = "AddPolicyGroupToDomain", usage =
ADD_GROUP_TO_DOMAIN_USAGE)
+ public void addGroupToDomain(String[] args)
+ {
+ // make sure the group exists
+ final String groupName = StringArrayUtil.getRequiredValue(args, 0);
+ final String domainName = StringArrayUtil.getRequiredValue(args, 1);
+
+
+ // make sure the group exists
+ org.nhind.config.CertPolicyGroup group = null;
+ try
+ {
+ group = proxy.getPolicyGroupByName(groupName);
+ if (group == null)
+ {
+ System.out.println("No policy group with name " + groupName + "
found");
+ return;
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup policy group: " + e.getMessage());
+ return;
+ }
+
+ // make sure the domain exists
+ Domain[] domains;
+ try
+ {
+ domains = proxy.getDomains(new String[]{domainName}, null);
+ if (domains == null || domains.length == 0)
+ {
+ System.out.println("No domain with name " + domainName + " found");
+ return;
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup domain: " + e.getMessage());
+ return;
+ }
+
+ // make sure it's not already associated
+ try
+ {
+ final CertPolicyGroupDomainReltn[] reltns =
proxy.getPolicyGroupsByDomain(domains[0].getId());
+ if (reltns != null && reltns.length > 0)
+ {
+ boolean reltnExists = false;
+ for (CertPolicyGroupDomainReltn reltn : reltns)
+ {
+ if
(reltn.getCertPolicyGroup().getPolicyGroupName().compareToIgnoreCase(groupName)
== 0)
+ {
+ reltnExists = true;
+ break;
+ }
+ }
+ if (reltnExists)
+ {
+ System.out.println("Group " + groupName + " already associated with
domain " + domainName);
+ return;
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup existing group to domain
associations: " + e.getMessage());
+ return;
+ }
+
+ // now make the association
+ try
+ {
+ proxy.associatePolicyGroupToDomain(domains[0].getId(), group.getId());
+ System.out.println("Successfully added policy to group.");
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to add group to domain: " + e.getMessage());
+ return;
+ }
+ }
+
+ @Command(name = "DeletePolicyGroupFromDomain", usage =
DELETE_GROUP_FROM_DOMAIN_USAGE)
+ public void deletePolicyGroupFromDomain(String[] args)
+ {
+ // make sure the group exists
+ final String groupName = StringArrayUtil.getRequiredValue(args, 0);
+ final String domainName = StringArrayUtil.getRequiredValue(args, 1);
+ long policyGroupId = -1;
+
+ // make sure the domain exists
+ Domain[] domains;
+ try
+ {
+ domains = proxy.getDomains(new String[]{domainName}, null);
+ if (domains == null || domains.length == 0)
+ {
+ System.out.println("No domain with name " + domainName + " found");
+ return;
+ }
+
+ // make sure it's really associated
+ final CertPolicyGroupDomainReltn[] reltns =
proxy.getPolicyGroupsByDomain(domains[0].getId());
+ if (reltns == null || reltns.length == 0)
+ {
+ System.out.println("Policy group is not associated with domain.");
+ return;
+ }
+ else
+ {
+ for (org.nhind.config.CertPolicyGroupDomainReltn reltn : reltns)
+ {
+ if
(reltn.getCertPolicyGroup().getPolicyGroupName().compareToIgnoreCase(groupName)
== 0)
+ {
+ policyGroupId = reltn.getCertPolicyGroup().getId();
+ break;
+ }
+
+ }
+ if (policyGroupId == -1)
+ {
+ System.out.println("Policy group is not associated with domain.");
+ return;
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup domain: " + e.getMessage());
+ return;
+ }
+
+ try
+ {
+ proxy.disassociatePolicyGroupFromDomain(domains[0].getId(),
policyGroupId);
+ System.out.println("Successfully delete policy group from domain.");
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to delete policy group from domain: " +
e.getMessage());
+ return;
+ }
+ }
+}
=======================================
--- /dev/null
+++
/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/AbstractRecordPrinter.java
Tue Jan 20 13:19:34 2015 UTC
@@ -0,0 +1,139 @@
+package org.nhindirect.config.manager.printers;
+
+import java.lang.reflect.Method;
+import java.util.Arrays;
+import java.util.Collection;
+
+
+public abstract class AbstractRecordPrinter<T> implements RecordPrinter<T>
+{
+ protected final Collection<ReportColumn> reportColumns;
+ protected final int tableWidth;
+
+ protected static class ReportColumn
+ {
+ protected final String header;
+ protected final int width;
+ protected final String fieldName;
+
+ public ReportColumn(String header, int width, String fieldName)
+ {
+ this.header = header;
+ this.width = width;
+ this.fieldName = fieldName;
+ }
+ }
+
+ public AbstractRecordPrinter(int tableWidth, Collection<ReportColumn>
reportColumns)
+ {
+ this.tableWidth = tableWidth;
+ this.reportColumns = reportColumns;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public void printRecord(T record)
+ {
+ printRecords(Arrays.asList(record));
+ }
+
+ @Override
+ public void printRecords(Collection<T> records)
+ {
+ printHeader();
+
+ for (T record : records)
+ printRecordInternal(record);
+ }
+
+ protected void printRecordInternal(T record)
+ {
+ StringBuilder builder = new StringBuilder();
+
+ int cnt = 0;
+ for (ReportColumn column : reportColumns)
+ {
+
+
+ builder.append(" ");
+ String colValue = getColumnValue(column, record);
+ builder.append(colValue);
+ // pad the rest with spaces
+ int padSize = (column.width - 2 ) - colValue.length();
+ for (int i = 0; i < padSize; ++i)
+ builder.append(' ');
+
+ if (++cnt < reportColumns.size())
+ builder.append("|");
+ }
+
+ builder.append("\r\n");
+ for (int i = 0; i < tableWidth; ++i)
+ builder.append('-');
+
+ System.out.println(builder.toString());
+ }
+
+ protected String getColumnValue(ReportColumn column, T record)
+ {
+ // default is to get the field value by introspection using
+ // the field name
+ try
+ {
+ Method method = record.getClass().getDeclaredMethod("get" +
column.fieldName);
+ Object obj = method.invoke(record);
+ return obj.toString();
+ }
+ catch (Exception e)
+ {
+ return "ERROR: " + e.getMessage();
+ }
+ }
+
+ protected void printHeader()
+ {
+ StringBuilder builder = new StringBuilder();
+
+ // top of header
+ for (int i = 0; i < tableWidth; ++i)
+ builder.append('-');
+
+ builder.append("\r\n|");
+
+ int cnt = 0;
+ int widthUsed = 0;
+ for (ReportColumn column : reportColumns)
+ {
+ int currentWidth = 0;
+ if (++cnt >= reportColumns.size())
+ currentWidth = tableWidth - widthUsed;
+ else
+ currentWidth = column.width;
+
+ // center the header
+ int padding = (currentWidth - column.header.length()) / 2;
+
+ // add pre padding
+ for (int i = 0; i < padding; ++i)
+ builder.append(' ');
+
+ // print header
+ builder.append(column.header);
+
+ // add post padding
+ for (int i = 0; i < (padding -1); ++i)
+ builder.append(' ');
+
+ builder.append("|");
+
+ widthUsed += currentWidth;
+ }
+
+ // end of header
+ builder.append("\r\n");
+ for (int i = 0; i < tableWidth; ++i)
+ builder.append('-');
+
+ System.out.println(builder.toString());
+ }
+}
=======================================
--- /dev/null
+++
/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/CertRecordPrinter.java
Tue Jan 20 13:19:34 2015 UTC
@@ -0,0 +1,105 @@
+package org.nhindirect.config.manager.printers;
+
+
+import java.net.URL;
+
+import java.security.cert.X509Certificate;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Locale;
+
+import org.nhindirect.dns.DNSException;
+import org.nhindirect.stagent.cert.Thumbprint;
+
+public class CertRecordPrinter extends
AbstractRecordPrinter<org.nhind.config.Certificate>
+{
+
+ protected static final SimpleDateFormat dateFormatter;
+
+ protected static final String CERT_NAME_COL = "Subject Name/URL";
+ protected static final String RECORD_TYPE_COL = "Record Type";
+ protected static final String PRIVATE_IND_COL = "Private Key";
+ protected static final String TP_NAME_COL = "Thumbprint";
+ protected static final String EXPIRES_COL = "Expires";
+
+ protected static final Collection<ReportColumn> REPORT_COLS;
+
+ static
+ {
+ REPORT_COLS = new ArrayList<ReportColumn>();
+
+ REPORT_COLS.add(new ReportColumn(CERT_NAME_COL, 55, "getCertificate"));
+ REPORT_COLS.add(new ReportColumn(RECORD_TYPE_COL, 11, "getCertificate"));
+ REPORT_COLS.add(new ReportColumn(PRIVATE_IND_COL, 12, "getCertificate"));
+ REPORT_COLS.add(new ReportColumn(TP_NAME_COL, 55, "getCertificate"));
+ REPORT_COLS.add(new ReportColumn(EXPIRES_COL, 15, "getCertificate"));
+
+
+ dateFormatter = new SimpleDateFormat("MMM d yyyy" , Locale.getDefault());
+ }
+
+
+ public CertRecordPrinter()
+ {
+ super(150, REPORT_COLS);
+ }
+
+ @SuppressWarnings("unused")
+ @Override
+ protected String getColumnValue(ReportColumn column,
org.nhind.config.Certificate retCert)
+ {
+ String tpOrURL = null;
+ boolean isURL = false;
+
+ X509Certificate cert = null;
+
+ try
+ {
+ cert = CertUtils.toX509Certificate(retCert.getData());
+ tpOrURL = Thumbprint.toThumbprint(cert).toString();
+ }
+ catch (DNSException e)
+ {
+ // probably not an X509 CERT... might be a URL
+ }
+
+ if (tpOrURL == null)
+ {
+ try
+ {
+ tpOrURL = new String(retCert.getData());
+ URL url = new URL(tpOrURL);
+ isURL = true;
+ }
+ catch (Exception e)
+ {
+ // invalid URL
+ return "";
+ }
+ }
+
+
+
+ try
+ {
+ if (column.header.equals(CERT_NAME_COL))
+ return retCert.getOwner();
+ else if (column.header.equals(RECORD_TYPE_COL))
+ return (isURL) ? "IPKIX" : "PKIX";
+ else if (column.header.equals(TP_NAME_COL))
+ return isURL ? tpOrURL : Thumbprint.toThumbprint(cert).toString();
+ else if (column.header.equals(EXPIRES_COL))
+ return isURL ? "" : dateFormatter.format(cert.getNotAfter());
+ else if (column.header.equals(PRIVATE_IND_COL))
+ return retCert.isPrivateKey() ? "Y" : "N";
+ else
+ return super.getColumnValue(column, retCert);
+ }
+ catch (Exception e)
+ {
+ return "ERROR: " + e.getMessage();
+ }
+ }
+
+}
=======================================
--- /dev/null
+++
/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/CertUtils.java
Tue Jan 20 13:19:34 2015 UTC
@@ -0,0 +1,256 @@
+package org.nhindirect.config.manager.printers;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.security.Key;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.Security;
+import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
+import java.util.Enumeration;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nhindirect.dns.DNSException;
+import org.nhindirect.stagent.CryptoExtensions;
+import org.nhindirect.stagent.cert.X509CertificateEx;
+
+
+public class CertUtils
+{
+ private static final Log LOGGER =
LogFactory.getFactory().getInstance(CertUtils.class);
+ static
+ {
+ Security.addProvider(new
org.bouncycastle.jce.provider.BouncyCastleProvider());
+ }
+
+ /**
+ * Takes a PKCS12 byte stream and returns a PKCS12 byte stream with
the pass phrase protection and encryption removed.
+ * @param bytes The PKCS12 byte stream that will be stripped.
+ * @param passphrase The pass phrase of the PKCS12 byte stream. This
is used to decrypt the PKCS12 stream.
+ * @return A PKCS12 byte stream representation of the original PKCS12
stream with the pass phrase protection and encryption removed.
+ */
+ public static byte[] pkcs12ToStrippedPkcs12(byte[] bytes, String
passphrase) throws DNSException
+ {
+ if (bytes == null || bytes.length == 0)
+ throw new IllegalArgumentException("Pkcs byte stream cannot be null or
empty.");
+
+ if (passphrase == null)
+ throw new IllegalArgumentException("Passphrase cannot be null.");
+
+
+ byte[] retVal = null;
+ final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
+ final ByteArrayOutputStream outStr = new ByteArrayOutputStream();
+ // lets try this a as a PKCS12 data stream first
+ try
+ {
+ final KeyStore localKeyStore = KeyStore.getInstance("PKCS12",
CryptoExtensions.getJCEProviderName());
+
+ localKeyStore.load(bais, passphrase.toCharArray());
+ final Enumeration<String> aliases = localKeyStore.aliases();
+
+
+
+ // we are really expecting only one alias
+ if (aliases.hasMoreElements())
+ {
+ final String alias = aliases.nextElement();
+ X509Certificate cert =
(X509Certificate)localKeyStore.getCertificate(alias);
+
+ // check if there is private key
+ final Key key = localKeyStore.getKey(alias, "".toCharArray());
+ if (key != null && key instanceof PrivateKey)
+ {
+ // now convert to a pcks12 format without the passphrase
+ final char[] emptyPass = "".toCharArray();
+
+ localKeyStore.setKeyEntry("privCert", key, emptyPass, new
java.security.cert.Certificate[] {cert});
+
+ localKeyStore.store(outStr, emptyPass);
+
+ retVal = outStr.toByteArray();
+
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ throw new DNSException("Failed to strip encryption for PKCS
stream.");
+ }
+ finally
+ {
+ try {bais.close(); }
+ catch (Exception e) {/* no-op */}
+
+ try {outStr.close(); }
+ catch (Exception e) {/* no-op */}
+ }
+
+ return retVal;
+ }
+
+ /**
+ * Converts an X509Certificate to a byte stream representation. If the
certificate contains a private key, the returned representation
+ * is a PKCS12 byte stream with no pass phrase protection or encryption.
+ * @param cert The certificate to convert.
+ * @return A byte stream representation of the certificate.
+ */
+ public static byte[] x509CertificateToBytes(X509Certificate cert) throws
DNSException
+ {
+ if (cert instanceof X509CertificateEx)
+ {
+ final ByteArrayOutputStream outStr = new ByteArrayOutputStream();
+ try
+ {
+ // return as a pkcs12 file with no encryption
+ final KeyStore convertKeyStore = KeyStore.getInstance("PKCS12",
CryptoExtensions.getJCEProviderName());
+ convertKeyStore.load(null, null);
+ final char[] emptyPass = "".toCharArray();
+
+ convertKeyStore.setKeyEntry("privCert", ((X509CertificateEx)
cert).getPrivateKey(), emptyPass, new java.security.cert.Certificate[]
{cert});
+ convertKeyStore.store(outStr, emptyPass);
+
+ return outStr.toByteArray();
+ }
+ ///CLOVER:OFF
+ catch (Exception e)
+ {
+ throw new DNSException("Failed to convert certificate to a byte
stream.");
+ }
+ ///CLOVER:ON
+ finally
+ {
+ try {outStr.close(); }
+ catch (Exception e) {/* no-op */}
+ }
+ }
+ else
+ {
+ try
+ {
+ return cert.getEncoded();
+ }
+ ///CLOVER:OFF
+ catch (Exception e)
+ {
+ throw new DNSException("Failed to convert certificate to a byte
stream.");
+ }
+ ///CLOVER:ON
+ }
+ }
+
+ /**
+ * Converts a byte stream to an X509Certificate. The byte stream can
either be an encoded X509Certificate or a PKCS12 byte stream.
+ * <p>
+ * If the stream is a PKCS12 representation, then an empty ("") pass
phrase is used to decrypt the stream. In addition the resulting
X509Certificate
+ * implementation will contain the private key.
+ * @param data The byte stream representation to convert.
+ * @return An X509Certificate representation of the byte stream.
+ */
+ public static X509Certificate toX509Certificate(byte[] data) throws
DNSException
+ {
+ return toX509Certificate(data, "");
+ }
+
+ /**
+ * Converts a byte stream to an X509Certificate. The byte stream can
either be an encoded X509Certificate or a PKCS12 byte stream.
+ * <p>
+ * If the stream is a PKCS12 representation, then the pass phrase is used
to decrypt the stream. In addition the resulting X509Certificate
+ * implementation will contain the private key.
+ * @param data The byte stream representation to convert.
+ * @param passPhrase If the byte stream is a PKCS12 representation, then
the then the pass phrase is used to decrypt the stream. Can be
+ * null if the stream is an encoded X509Certificate and not a PKCS12 byte
stream.
+ * @return An X509Certificate representation of the byte stream.
+ */
+ public static X509Certificate toX509Certificate(byte[] data, String
passPhrase) throws DNSException
+ {
+ if (data == null || data.length == 0)
+ throw new IllegalArgumentException("Byte stream cannot be null or
empty.");
+
+ // do not use a null pass phrase
+ if (passPhrase == null)
+ passPhrase = "";
+
+ X509Certificate retVal = null;
+ ByteArrayInputStream bais = new ByteArrayInputStream(data);
+ try
+ {
+
+ // lets try this a as a PKCS12 data stream first
+ try
+ {
+ KeyStore localKeyStore = KeyStore.getInstance("PKCS12",
CryptoExtensions.getJCEProviderName());
+
+ localKeyStore.load(bais, passPhrase.toCharArray());
+ Enumeration<String> aliases = localKeyStore.aliases();
+
+
+ // we are really expecting only one alias
+ if (aliases.hasMoreElements())
+ {
+ String alias = aliases.nextElement();
+ X509Certificate cert =
(X509Certificate)localKeyStore.getCertificate(alias);
+
+ // check if there is private key
+ Key key = localKeyStore.getKey(alias, passPhrase.toCharArray());
+ if (key != null && key instanceof PrivateKey)
+ {
+ retVal = X509CertificateEx.fromX509Certificate(cert,
(PrivateKey)key);
+ }
+ }
+ }
+ catch (Exception e)
+ {
+ // must not be a PKCS12 stream, try next step
+ }
+
+ if (retVal == null)
+ {
+ //try X509 certificate factory next
+ bais.reset();
+ bais = new ByteArrayInputStream(data);
+
+ retVal = (X509Certificate)
CertificateFactory.getInstance("X.509").generateCertificate(bais);
+ }
+ }
+ catch (Exception e)
+ {
+ throw new DNSException("Failed to convert byte stream to a
certificate.");
+ }
+ finally
+ {
+ try {bais.close();} catch (IOException ex) {}
+ }
+
+ return retVal;
+ }
+
+ /**
+ * Creates an X509Certificate object from an existing file. The file
should be a DER encoded representation of the certificate.
+ * @param certFile The file to load into a certificate object.
+ * @return An X509Certificate loaded from the file.
+ */
+ public static X509Certificate certFromFile(String certFile)
+ {
+ final File theCertFile = new File(certFile);
+ try
+ {
+ LOGGER.trace("Full path of cert file to load: " +
theCertFile.getAbsolutePath());
+
+ return toX509Certificate(FileUtils.readFileToByteArray(theCertFile));
+ }
+ catch (Exception e)
+ {
+ // this is used as a factory method, so just return null if the
certificate could not be loaded
+ // instead of throwing an exception, but make sure the error is
logged
+ LOGGER.error("Failed to load certificate from file " +
theCertFile.getAbsolutePath(), e);
+ return null;
+ }
+ }
+}
+
=======================================
--- /dev/null
+++
/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/DNSRecordPrinter.java
Tue Jan 20 13:19:34 2015 UTC
@@ -0,0 +1,38 @@
+package org.nhindirect.config.manager.printers;
+
+import java.util.Collection;
+
+import org.nhind.config.DnsRecord;
+
+/**
+ * Interface for printing DNS records to an output Stream.
+ * @author Greg Meyer
+ *
+ * @since 1.0
+ */
+public interface DNSRecordPrinter
+{
+ /**
+ * Prints the contents of a collection of DNS records.
+ * @param records A collection of DNS records to print.
+ *
+ * @since 1.0
+ */
+ public void print(Collection<DnsRecord> records);
+
+ /**
+ * Prints the contents of an array of DNS records.
+ * @param records An array of DNS records to print.
+ *
+ * @since 1.0
+ */
+ public void print(DnsRecord[] records);
+
+ /**
+ * Prints the contents of a single DNS records.
+ * @param record DNS records to print.
+ *
+ * @since 1.0
+ */
+ public void print(DnsRecord record);
+}
=======================================
--- /dev/null
+++
/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/DefaultDNSRecordPrinter.java
Tue Jan 20 13:19:34 2015 UTC
@@ -0,0 +1,267 @@
+/*
+Copyright (c) 2010, NHIN Direct Project
+All rights reserved.
+
+Authors:
+ Greg Meyer gm2...@cerner.com
+
+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 The NHIN Direct Project
(nhindirect.org).
+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 org.nhindirect.config.manager.printers;
+
+import java.io.PrintWriter;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.util.Arrays;
+import java.util.Collection;
+
+import org.nhind.config.DnsRecord;
+import org.xbill.DNS.ARecord;
+import org.xbill.DNS.CERTRecord;
+import org.xbill.DNS.MXRecord;
+import org.xbill.DNS.Name;
+import org.xbill.DNS.Record;
+import org.xbill.DNS.SOARecord;
+import org.xbill.DNS.Type;
+import org.xbill.DNS.security.CERTConverter;
+
+/**
+ * Utility class for formatting and outputting the content of DNS records.
+ * @author Greg Meyer
+ *
+ * @since 1.0
+ */
+public class DefaultDNSRecordPrinter implements DNSRecordPrinter
+{
+ private final PrintWriter writer;
+
+ /**
+ * Default constructor. Create a writer that outputs to system console.
+ *
+ * @since 1.0
+ */
+ public DefaultDNSRecordPrinter()
+ {
+ writer = new PrintWriter(System.out);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void print(Collection<DnsRecord> records)
+ {
+ if (records == null || records.size() == 0)
+ {
+ writer.println("Empty record list");
+ return;
+ }
+
+ for (DnsRecord record : records)
+ {
+ print(record);
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void print(DnsRecord[] records)
+ {
+ if (records == null || records.length == 0)
+ {
+ writer.println("Empty record array");
+ return;
+ }
+
+ print(Arrays.asList(records));
+ }
+
+ /*
+ * Converts a DNS record type to a string representation
+ */
+ private String typeToString(int type)
+ {
+ switch (type)
+ {
+ case Type.A:
+ return "A";
+
+ case Type.MX:
+ return "MX";
+
+ case Type.SOA:
+ return "SOA";
+
+ case Type.CERT:
+ return "CERT";
+
+ default:
+ return "Unknown";
+ }
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public void print(DnsRecord record)
+ {
+ if (record == null)
+ {
+ writer.println("Null Resource Record");
+ return;
+ }
+
+ writer.println("-----------");
+ print("Record Name", record.getName());
+ print("Type", typeToString(record.getType()));
+ print("TTL", String.valueOf(record.getTtl()));
+ switch(record.getType())
+ {
+ default:
+ break;
+
+ case Type.A:
+ print((ARecord)toRecord(record));
+ break;
+
+ case Type.SOA:
+ print((SOARecord)toRecord(record));
+ break;
+
+ case Type.MX:
+ print((MXRecord)toRecord(record));
+ break;
+
+ case Type.CERT:
+ print((CERTRecord)toRecord(record));
+ break;
+ }
+
+ writer.flush();
+ }
+
+ /*
+ * converts a String to a DNS name
+ */
+ private Name nameFromString(String str)
+ {
+ if (!str.endsWith("."))
+ str += ".";
+
+ try
+ {
+ return Name.fromString(str);
+ }
+ catch (Exception e)
+ {
+ throw new IllegalArgumentException("Invalid DNS name");
+ }
+ }
+
+ /*
+ * converts a configuration service DnsRecord to a dnsjava Record
+ */
+ private Record toRecord(DnsRecord rec)
+ {
+ return Record.newRecord(nameFromString(rec.getName()), rec.getType(),
rec.getDclass(), rec.getTtl(), rec.getData());
+ }
+
+ /*
+ * prints the A record specific fields
+ */
+ private void print(ARecord body)
+ {
+ if (body == null)
+ {
+ print("Null A Record Body");
+ return;
+ }
+
+ this.print("IPAddress", body.getAddress().getHostAddress());
+ }
+
+ /*
+ * prints the MX record specific fields
+ */
+ private void print(MXRecord body)
+ {
+ if (body == null)
+ {
+ print("Null MX Record Body");
+ return;
+ }
+
+ print("Access Exchage Server", body.getTarget().toString());
+ print("Priority", String.valueOf(body.getPriority()));
+ }
+
+ /*
+ * prints the SOA record specific fields
+ */
+ private void print(SOARecord soa)
+ {
+ if (soa == null)
+ {
+ print("Null SOA Record Body");
+ return;
+ }
+
+
+ print("DomainName", soa.getName().toString());
+ print("Primary Name Server", soa.getHost().toString());
+ print("Refresh", String.valueOf(soa.getRefresh()));
+ print("Retry", String.valueOf(soa.getRetry()));
+ print("Expire", String.valueOf(soa.getExpire()));
+ print("Minimum", String.valueOf(soa.getMinimum()));
+ }
+
+ /*
+ * prints the CERT record specific fields
+ */
+ private void print(CERTRecord certbody)
+ {
+ if (certbody == null)
+ {
+ print("Null CERT Record Body");
+ return;
+ }
+
+
+ Certificate cert = CERTConverter.parseRecord(certbody);
+ if (cert instanceof X509Certificate) // may not be an X509Cert
+ {
+ X509Certificate xcert = (X509Certificate)cert;
+ print("Certificate Subject", xcert.getSubjectDN().getName());
+ }
+ }
+
+
+ /*
+ * prints a name value pair
+ */
+ private void print(String name, String value)
+ {
+ writer.println(name + ": " + value);
+ }
+
+ /*
+ * prints a specific string message
+ */
+ private void print(String message)
+ {
+ writer.println(message);
+ }
+
+}
=======================================
--- /dev/null
+++
/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/PolicyGroupPrinter.java
Tue Jan 20 13:19:34 2015 UTC
@@ -0,0 +1,44 @@
+package org.nhindirect.config.manager.printers;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+public class PolicyGroupPrinter extends
AbstractRecordPrinter<org.nhind.config.CertPolicyGroup>
+{
+ protected static final Collection<ReportColumn> REPORT_COLS;
+
+ protected static final String POLICY_GROUP_NAME_COL = "Policy Group Name";
+ protected static final String POLICY_NUMBER_COL = "Number of Policies";
+
+ static
+ {
+ REPORT_COLS = new ArrayList<ReportColumn>();
+
+ REPORT_COLS.add(new ReportColumn(POLICY_GROUP_NAME_COL,
40, "PolicyGroupName"));
+ REPORT_COLS.add(new ReportColumn(POLICY_NUMBER_COL, 16, "Policies"));
+ }
+
+ public PolicyGroupPrinter()
+ {
+ super(57, REPORT_COLS);
+ }
+
+ @Override
+ protected String getColumnValue(ReportColumn column,
org.nhind.config.CertPolicyGroup group)
+ {
+
+ try
+ {
+ if (column.header.equals(POLICY_NUMBER_COL))
+ {
+ return Integer.toString((group.getCertPolicyGroupReltn() == null) ?
0 : group.getCertPolicyGroupReltn().length);
+ }
+ else
+ return super.getColumnValue(column, group);
+ }
+ catch (Exception e)
+ {
+ return "ERROR: " + e.getMessage();
+ }
+ }
+}
=======================================
--- /dev/null
+++
/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/PolicyPrinter.java
Tue Jan 20 13:19:34 2015 UTC
@@ -0,0 +1,47 @@
+package org.nhindirect.config.manager.printers;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+
+public class PolicyPrinter extends
AbstractRecordPrinter<org.nhind.config.CertPolicy>
+{
+ protected static final Collection<ReportColumn> REPORT_COLS;
+
+ protected static final String POLICY_NAME_COL = "Policy Name";
+ protected static final String POLICY_TYPE_COL = "Lexicon";
+ protected static final String POLICY_DEF_COL = "Defintion";
+
+ static
+ {
+ REPORT_COLS = new ArrayList<ReportColumn>();
+
+ REPORT_COLS.add(new ReportColumn(POLICY_NAME_COL, 40, "PolicyName"));
+ REPORT_COLS.add(new ReportColumn(POLICY_TYPE_COL, 20, "Lexicon"));
+ REPORT_COLS.add(new ReportColumn(POLICY_DEF_COL, 90, "PolicyData"));
+ }
+
+ public PolicyPrinter()
+ {
+ super(150, REPORT_COLS);
+ }
+
+ @Override
+ protected String getColumnValue(ReportColumn column,
org.nhind.config.CertPolicy policy)
+ {
+
+ try
+ {
+ if (column.header.equals(POLICY_DEF_COL))
+ {
+ return new String(policy.getPolicyData());
+ }
+ else
+ return super.getColumnValue(column, policy);
+ }
+ catch (Exception e)
+ {
+ return "ERROR: " + e.getMessage();
+ }
+ }
+}
=======================================
--- /dev/null
+++
/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/PolicyUsagePrinter.java
Tue Jan 20 13:19:34 2015 UTC
@@ -0,0 +1,61 @@
+package org.nhindirect.config.manager.printers;
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+public class PolicyUsagePrinter extends
AbstractRecordPrinter<org.nhind.config.CertPolicyGroupReltn>
+{
+ protected static final Collection<ReportColumn> REPORT_COLS;
+
+ protected static final String POLICY_NAME_COL = "Policy Name";
+ protected static final String POLICY_LEXICON_COL = "Lexicon";
+ protected static final String POLICY_USAGE_COL = "Usage";
+ protected static final String INCOMING_COL = "Incoming";
+ protected static final String OUTGOING_COL = "Outgoing";
+
+ static
+ {
+ REPORT_COLS = new ArrayList<ReportColumn>();
+
+ REPORT_COLS.add(new ReportColumn(POLICY_NAME_COL, 40, "PolicyName"));
+ REPORT_COLS.add(new ReportColumn(POLICY_LEXICON_COL, 20, "Lexicon"));
+ REPORT_COLS.add(new ReportColumn(POLICY_USAGE_COL, 20, "PolicyUse"));
+ REPORT_COLS.add(new ReportColumn(INCOMING_COL, 12, "Incoming"));
+ REPORT_COLS.add(new ReportColumn(OUTGOING_COL, 12, "Outgoing"));
+ }
+
+ public PolicyUsagePrinter()
+ {
+ super(110, REPORT_COLS);
+ }
+
+ @Override
+ protected String getColumnValue(ReportColumn column,
org.nhind.config.CertPolicyGroupReltn reltn)
+ {
+ try
+ {
+ if (column.header.equals(POLICY_NAME_COL))
+ {
+ return reltn.getCertPolicy().getPolicyName();
+ }
+ else if (column.header.equals(POLICY_LEXICON_COL))
+ {
+ return reltn.getCertPolicy().getLexicon().toString();
+ }
+ else if (column.header.equals(INCOMING_COL))
+ {
+ return Boolean.toString(reltn.isIncoming());
+ }
+ else if (column.header.equals(OUTGOING_COL))
+ {
+ return Boolean.toString(reltn.isOutgoing());
+ }
+ else
+ return super.getColumnValue(column, reltn);
+ }
+ catch (Exception e)
+ {
+ return "ERROR: " + e.getMessage();
+ }
+ }
+}
=======================================
--- /dev/null
+++
/java/tags/config-manager-1.1/src/main/java/org/nhindirect/config/manager/printers/RecordPrinter.java
Tue Jan 20 13:19:34 2015 UTC
@@ -0,0 +1,10 @@
+package org.nhindirect.config.manager.printers;
+
+import java.util.Collection;
+
+public interface RecordPrinter<T>
+{
+ public void printRecord(T rec);
+
+ public void printRecords(Collection<T> recs);
+}
=======================================
--- /java/config/config-manager/pom.xml Wed Jun 26 18:09:24 2013 UTC
+++ /java/config/config-manager/pom.xml Tue Jan 20 13:19:34 2015 UTC
@@ -3,7 +3,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.nhind</groupId>
<artifactId>config-manager</artifactId>
- <version>1.1-SNAPSHOT</version>
+ <version>1.2-SNAPSHOT</version>
<packaging>jar</packaging>
<name>NHIN Direct Java configuration manager</name>
<description>NHIN Direct Java configuration manager</description>
@@ -44,22 +44,102 @@
<dependency>
<groupId>org.nhind</groupId>
<artifactId>dns</artifactId>
- <version>1.2.2</version>
+ <version>1.2.3</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-asm</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-aop</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-tx</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-orm</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-test</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-beans</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-context</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-entitymanager</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-annotations</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.google.inject</groupId>
+ <artifactId>guice</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.apache.geronimo.specs</groupId>
+ <artifactId>geronimo-jpa_2.0_spec</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.nhind</groupId>
<artifactId>config-service-client</artifactId>
- <version>1.4</version>
+ <version>2.0</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-context</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.nhind</groupId>
<artifactId>direct-common</artifactId>
- <version>1.2</version>
+ <version>1.4.2</version>
+ <exclusions>
+ <exclusion>
+ <groupId>com.google.inject</groupId>
+ <artifactId>guice</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.nhind</groupId>
<artifactId>agent</artifactId>
- <version>2.0</version>
+ <version>2.0.11</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.apache.james</groupId>
+ <artifactId>apache-jsieve-mailet</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.google.inject</groupId>
+ <artifactId>guice</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>dnsjava</groupId>
=======================================
---
/java/config/config-manager/src/main/java/org/nhindirect/config/manager/CertCommands.java
Fri May 31 14:21:37 2013 UTC
+++
/java/config/config-manager/src/main/java/org/nhindirect/config/manager/CertCommands.java
Tue Jan 20 13:19:34 2015 UTC
@@ -1,10 +1,17 @@
package org.nhindirect.config.manager;


+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
+import java.security.Key;
+import java.security.KeyStore;
+import java.security.PrivateKey;
+import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
+import java.util.Enumeration;

import org.apache.commons.io.FileUtils;
import org.nhind.config.ConfigurationServiceProxy;
@@ -15,16 +22,22 @@
import org.nhindirect.dns.tools.utils.Command;
import org.nhindirect.dns.tools.utils.StringArrayUtil;
import org.nhindirect.stagent.CryptoExtensions;
+import org.nhindirect.stagent.NHINDException;
import org.nhindirect.stagent.cert.X509CertificateEx;

+
public class CertCommands
{
private static final String LIST_CERTIFICATES_USAGE = "Lists
certificates in the system";

private static final String LIST_EMAIL_CERTIFICATES_USAGE = "Lists
certificates by a given email address or domain" +
"\r\n address" +
- "\r\n\t address: The email address or domain to search for.
Certificates are mathed on the subject alternative name field of legacy
email address of the certificate";
+ "\r\n\t address: The email address or domain to search for.
Certificates are searched on the subject alternative name field of legacy
email address of the certificate";

+ private static final String EXPORT_EMAIL_CERTIFICATES_USAGE = "Exports
certificates by a given email address or domain" +
+ "\r\n address" +
+ "\r\n\t address: The email address or domain to search for.
Certificates are searched on the subject alternative name field of legacy
email address of the certificate";
+
private static final String IMPORT_PUBLIC_CERT_USAGE = "Imports a
certificate that does not contain private key information" +
"\r\n certfile" +
"\r\n\t certfile: Fully qualified path and file name of the
X509 certificate file. Place the file name in quotes (\"\") if there are
spaces in the path or name.";
@@ -97,6 +110,29 @@
System.out.println("Failed to lookup certificates: " + e.getMessage());
}
}
+
+
+ @Command(name = "ExportCertByAddress", usage =
EXPORT_EMAIL_CERTIFICATES_USAGE)
+ public void exportCertByAddress(String[] args)
+ {
+ String owner = StringArrayUtil.getRequiredValue(args, 0);
+
+ try
+ {
+ final org.nhind.config.Certificate[] certs =
proxy.getCertificatesForOwner(owner, null);
+
+ if (certs == null || certs.length == 0)
+ System.out.println("No certificates found");
+ else
+ {
+ certPrinter.printRecords(Arrays.asList(certs));
+ }
+ }
+ catch (Exception e)
+ {
+ System.out.println("Failed to lookup certificates: " + e.getMessage());
+ }
+ }

@Command(name = "AddPublicCert", usage = IMPORT_PUBLIC_CERT_USAGE)
public void importPublicCert(String[] args)
@@ -218,4 +254,140 @@
{
this.proxy = proxy;
}
+
+ protected void writeCertsToFiles(org.nhind.config.Certificate[] certs)
throws IOException
+ {
+ int idx = 1;
+ for (org.nhind.config.Certificate cert : certs)
+ {
+ X509Certificate transCert = this.certFromData(cert.getData());
+
+ String certFileName= "";
+ String extension = (transCert instanceof X509CertificateEx
) ? ".p12" : ".der";
+ String certFileHold = CryptoExtensions.getSubjectAddress(transCert) +
extension;
+ if (certs.length > 1)
+ {
+ int index = certFileHold.lastIndexOf(".");
+ if (index < 0)
+ certFileHold += "(" + idx + ")";
+ else
+ {
+ certFileName = certFileHold.substring(0, index - 1) + "(" + idx + ")"
+ certFileHold.substring(index);
+ }
+
+ }
+ else
+ certFileName = certFileHold;
+
+ File certFile = new File(certFileName);
+ if (certFile.exists())
+ certFile.delete();
+
+
+ System.out.println("Writing cert file: " + certFile.getAbsolutePath());
+ FileUtils.writeByteArrayToFile(certFile,
x509CertificateToBytes(transCert));
+
+ ++idx;
+ }
+ }
+
+ private X509Certificate certFromData(byte[] data)
+ {
+ X509Certificate retVal = null;
+ try
+ {
+ ByteArrayInputStream bais = new ByteArrayInputStream(data);
+
+ // lets try this a as a PKCS12 data stream first
+ try
+ {
+ KeyStore localKeyStore = KeyStore.getInstance("PKCS12",
CryptoExtensions.getJCEProviderName());
+
+ localKeyStore.load(bais, "".toCharArray());
+ Enumeration<String> aliases = localKeyStore.aliases();
+
+
+ // we are really expecting only one alias
+ if (aliases.hasMoreElements())
+ {
+ String alias = aliases.nextElement();
+ X509Certificate cert =
(X509Certificate)localKeyStore.getCertificate(alias);
+
+ // check if there is private key
+ Key key = localKeyStore.getKey(alias, "".toCharArray());
+ if (key != null && key instanceof PrivateKey)
+ {
+ retVal = X509CertificateEx.fromX509Certificate(cert,
(PrivateKey)key);
+ }
+ else
+ retVal = cert;
+
+ }
+ }
+ catch (Exception e)
+ {
+ // must not be a PKCS12 stream, go on to next step
+ }
+
+ if (retVal == null)
+ {
+ //try X509 certificate factory next
+ bais.reset();
+ bais = new ByteArrayInputStream(data);
+
+ retVal = (X509Certificate)
CertificateFactory.getInstance("X.509").generateCertificate(bais);
+ }
+ bais.close();
+ }
+ catch (Exception e)
+ {
+ throw new NHINDException("Data cannot be converted to a valid
X.509 Certificate", e);
+ }
+
+ return retVal;
+ }
+
+ public static byte[] x509CertificateToBytes(X509Certificate cert)
+ {
+ if (cert instanceof X509CertificateEx)
+ {
+ final ByteArrayOutputStream outStr = new ByteArrayOutputStream();
+ try
+ {
+ // return as a pkcs12 file with no encryption
+ final KeyStore convertKeyStore = KeyStore.getInstance("PKCS12",
CryptoExtensions.getJCEProviderName());
+ convertKeyStore.load(null, null);
+ final char[] emptyPass = "".toCharArray();
+
+ convertKeyStore.setKeyEntry("privCert", ((X509CertificateEx)
cert).getPrivateKey(), emptyPass, new java.security.cert.Certificate[]
{cert});
+ convertKeyStore.store(outStr, emptyPass);
+
+ return outStr.toByteArray();
+ }
+ ///CLOVER:OFF
+ catch (Exception e)
+ {
+ throw new NHINDException("Failed to convert certificate to a byte
stream.", e);
+ }
+ ///CLOVER:ON
+ finally
+ {
+ try {outStr.close(); }
+ catch (Exception e) {/* no-op */}
+ }
+ }
+ else
+ {
+ try
+ {
+ return cert.getEncoded();
+ }
+ ///CLOVER:OFF
+ catch (Exception e)
+ {
+ throw new NHINDException("Failed to convert certificate to a byte
stream.", e);
+ }
+ ///CLOVER:ON
+ }
+ }
}
Reply all
Reply to author
Forward
0 new messages