Refactor the aaa-cert bundle 69/47369/10
authormelserngawy <melserngawy@inocybe.com>
Fri, 21 Oct 2016 21:27:36 +0000 (17:27 -0400)
committerMohamed El-Serngawy <melserngawy@inocybe.com>
Tue, 1 Nov 2016 14:02:14 +0000 (10:02 -0400)
Refactoring the aaa-cert bundle to have one service managing
the certificates and keystores in ODL.

Change-Id: Ie17a1c868fb9d2a22772ffe4dc4237e594b9e87b
Signed-off-by: melserngawy <melserngawy@inocybe.com>
27 files changed:
aaa-cert/pom.xml
aaa-cert/src/main/java/org/opendaylight/aaa/cert/api/IAaaCertMdsalProvider.java
aaa-cert/src/main/java/org/opendaylight/aaa/cert/api/IAaaCertProvider.java
aaa-cert/src/main/java/org/opendaylight/aaa/cert/api/ICertificateManager.java [new file with mode: 0644]
aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/AaaCertMdsalProvider.java
aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/AaaCertProvider.java
aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/AaaCertRpcServiceImpl.java
aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/CertificateManagerService.java [new file with mode: 0644]
aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/DefaultMdsalSslData.java [new file with mode: 0644]
aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/KeyStoreConstant.java
aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/ODLKeyTool.java
aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/ODLMdsalKeyTool.java [deleted file]
aaa-cert/src/main/java/org/opendaylight/aaa/cert/utils/KeyStoresDataUtils.java
aaa-cert/src/main/resources/initial/aaa-cert-config.xml
aaa-cert/src/main/resources/org/opendaylight/blueprint/aaaCert.xml
aaa-cert/src/main/yang/aaa-cert-mdsal.yang
aaa-cert/src/main/yang/aaa-cert-rpc.yang
aaa-cert/src/main/yang/aaa-cert.yang
aaa-cli/src/main/java/org/opendaylight/aaa/cli/AddCertODLKeyStore.java [deleted file]
aaa-cli/src/main/java/org/opendaylight/aaa/cli/AddCertTrustStore.java [deleted file]
aaa-cli/src/main/java/org/opendaylight/aaa/cli/CreateODLKeyStore.java [deleted file]
aaa-cli/src/main/java/org/opendaylight/aaa/cli/CreateTrustKeyStore.java [deleted file]
aaa-cli/src/main/java/org/opendaylight/aaa/cli/GenerateCertReq.java
aaa-cli/src/main/java/org/opendaylight/aaa/cli/GetODLSelfSignCert.java
aaa-cli/src/main/java/org/opendaylight/aaa/cli/GetTrustStoreCert.java
aaa-cli/src/main/resources/OSGI-INF/blueprint/commands.xml
aaa-encrypt-service/src/main/java/org/opendaylight/aaa/encrypt/AAAEncryptionServiceImpl.java

index d0b5968d0881dcf29bda82b22e9347fc108aec88..463ea16fb5442ef9e3475e7e0101c68af46eedf1 100755 (executable)
@@ -87,6 +87,20 @@ and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL
 
   <build>
     <plugins>
+      <plugin>
+        <groupId>org.apache.felix</groupId>
+        <artifactId>maven-bundle-plugin</artifactId>
+        <extensions>true</extensions>
+        <configuration>
+          <instructions>
+            <Export-Package>
+              org.opendaylight.aaa.cert.api.*,
+              org.opendaylight.aaa.cert.impl.*,
+              org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rev151126.*
+            </Export-Package>
+          </instructions>
+        </configuration>
+      </plugin>
       <plugin>
         <groupId>org.codehaus.mojo</groupId>
         <artifactId>build-helper-maven-plugin</artifactId>
index 01b691c645c25dc8e5ad76d03ad3f44e1298bab0..fe62147207856c77a2ab26f618d3c7e1b48e3c9e 100644 (file)
@@ -9,9 +9,7 @@
 package org.opendaylight.aaa.cert.api;
 
 import java.security.KeyStore;
-
 import javax.annotation.Nonnull;
-
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.key.stores.SslData;
 
 /**
@@ -51,7 +49,7 @@ public interface IAaaCertMdsalProvider {
      * @param odlKeystoreKeyAlg Key algorithm to create secret key i.e RSA
      * @param odlKeystoreSignAlg sign algorithm i.e SHA1WithRSAEncryption
      * @param odlKeystoreKeysize the key size i.e 1024
-     * @param odlKeystoreValidity validity if the key
+     * @param odlKeystoreValidity validity of the key
      * @param trustKeystoreName Trust Keystore Name
      * @param trustKeystorePwd Trust Keystore Password
      * @param cipherSuites cipher suites that will be used by the SSL connection
@@ -90,16 +88,6 @@ public interface IAaaCertMdsalProvider {
      */
     void exportSslDataKeystores(@Nonnull String bundleName);
 
-    /**
-     * Generate a certificate request to be signed by a CA.
-     *
-     * @param bundleName name of the bundle that will use the keystores
-     * @param signAlg the sign algorithm
-     * @param withTag boolean to add cert-req tag to the return string
-     * @return certificate request as string
-     */
-    String genODLKeyStoreCertificateReq(@Nonnull String bundleName, @Nonnull String signAlg, boolean withTag);
-
     /**
      * Generate a certificate request to be signed by a CA with default sign algorithm SHA1WithRSAEncryption
      *
@@ -107,7 +95,7 @@ public interface IAaaCertMdsalProvider {
      * @param withTag boolean to add cert-req tag to the return string
      * @return certificate request as string
      */
-    public String genODLKeyStoreCertificateReq(@Nonnull String bundleName, boolean withTag);
+    String genODLKeyStoreCertificateReq(@Nonnull String bundleName, boolean withTag);
 
     /**
      * Get the ODL keystore certificate
@@ -194,4 +182,8 @@ public interface IAaaCertMdsalProvider {
      */
     SslData updateSslData(@Nonnull SslData sslData);
 
+    /**
+     * Initialize the Keystore data tree at Mdsal
+     */
+    void initializeKeystoreDataTree();
 }
index b19df2a3c84ac4434414ce96d6df53404c398037..504f678ff693e799125e1df1e746de5bdd4c2de6 100644 (file)
@@ -61,46 +61,22 @@ public interface IAaaCertProvider {
      */
     boolean addCertificateTrustStore(@Nonnull String alias, @Nonnull String certificate);
 
-    /**
-     * Create ODL keyStore.
-     *
-     * @param keyStoreName keystore Name
-     * @param storePasswd keystore password
-     * @param alias key alias
-     * @param dName of the keystore
-     * @param validity of the keystore
-     * @return succeed or failed message
-     */
-    @Nonnull String createODLKeyStore(@Nonnull String keyStoreName, @Nonnull String storePasswd, @Nonnull String alias, @Nonnull String dName, int validity);
-
-    /**
-     * Create Trust keyStore.
-     *
-     * @param keyStoreName keystore Name
-     * @param storePasswd keystore password
-     * @param alias key alias
-     * @return succeed or failed message
-     */
-    @Nonnull String createTrustKeyStore(@Nonnull String keyStoreName, @Nonnull String storePasswd, @Nonnull String alias);
-
     /**
      * Generate certificate request from the ODL keystore to be signed by a CA
      *
      * @param storePasswd ODL keystore password
-     * @param alias ODL keystore alias
      * @param withTag return the certificate Req string with tag if true
      * @return the certificate request
      */
-    @Nonnull String genODLKeyStoreCertificateReq(@Nonnull String storePasswd, @Nonnull String alias, boolean withTag);
+    @Nonnull String genODLKeyStoreCertificateReq(@Nonnull String storePasswd, boolean withTag);
 
     /**
      * Generate certificate request from the ODL keystore to be signed by a CA
      *
-     * @param alias ODL keystore alias
      * @param withTag return the certificate Req string with tag if true
      * @return the certificate request
      */
-    @Nonnull String genODLKeyStoreCertificateReq(@Nonnull String alias, boolean withTag);
+    @Nonnull String genODLKeyStoreCertificateReq(boolean withTag);
 
     /**
      * Get certificate from the Trust keystore
@@ -125,20 +101,18 @@ public interface IAaaCertProvider {
      * Get ODL keystore certificate.
      *
      * @param storePasswd ODL keystore password
-     * @param alias ODL keystore alias
      * @param withTag return certificate string with tag if true
      * @return the certificate
      */
-    @Nonnull String getODLKeyStoreCertificate(@Nonnull String storePasswd, @Nonnull String alias, boolean withTag);
+    @Nonnull String getODLKeyStoreCertificate(@Nonnull String storePasswd, boolean withTag);
 
     /**
      * Get ODL keystore certificate
      *
-     * @param alias ODL keystore alias
      * @param withTag return certificate string with tag if true
      * @return the certificate
      */
-    @Nonnull String getODLKeyStoreCertificate(@Nonnull String alias, boolean withTag);
+    @Nonnull String getODLKeyStoreCertificate(boolean withTag);
 
     /**
      * Get ODL Keystore as java keystore object
@@ -176,12 +150,9 @@ public interface IAaaCertProvider {
     CtlKeystore getOdlKeyStoreInfo();
 
     /**
-     * Create the ODL keystore based on the CtlKeystore given data
-     */
-    void createODLKeyStore();
-
-    /**
-     * Create the Trust keystore based on the TrustKeystore given data
+     * Create the ODL and Trust keystores based on the CtlKeystore and TrustKeystore data
+     *
+     * @return true if success
      */
-    void createTrustKeyStore();
+    boolean createKeyStores();
 }
\ No newline at end of file
diff --git a/aaa-cert/src/main/java/org/opendaylight/aaa/cert/api/ICertificateManager.java b/aaa-cert/src/main/java/org/opendaylight/aaa/cert/api/ICertificateManager.java
new file mode 100644 (file)
index 0000000..016e8ce
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2016 Inocybe Technologies. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.aaa.cert.api;
+
+import java.security.KeyStore;
+import javax.annotation.Nonnull;
+import javax.net.ssl.SSLContext;
+
+/**
+ * ICertifcateManager defines the basic functions that are consumed by other bundles to establish the SSLContext
+ *
+ * @author mserngawy
+ *
+ */
+public interface ICertificateManager {
+
+    /**
+     * Get ODL Keystore as java keystore object
+     *
+     * @return ODL keystore
+     */
+    KeyStore getODLKeyStore();
+
+    /**
+     * Get Trust Keystore as java keystore object
+     *
+     * @return Trust keystore
+     */
+    KeyStore getTrustKeyStore();
+
+    /**
+     * Get list of of the allowed cipher suites otherwise empty array
+     *
+     * @return Cipher suites
+     */
+    String[] getCipherSuites();
+
+    /**
+     * Get certificate from the Trust keystore
+     *
+     * @param storePasswd Trust keystore password
+     * @param alias the certificate alias
+     * @param withTag return the certificate string with tag if true
+     * @return the certificate
+     */
+    @Nonnull String getCertificateTrustStore(@Nonnull String storePasswd, @Nonnull String alias, boolean withTag);
+
+    /**
+     * Get ODL keystore certificate.
+     *
+     * @param storePasswd ODL keystore password
+     * @param withTag return certificate string with tag if true
+     * @return the certificate
+     */
+    @Nonnull String getODLKeyStoreCertificate(@Nonnull String storePasswd, boolean withTag);
+
+    /**
+     * Generate certificate request from the ODL keystore to be signed by a CA
+     *
+     * @param storePasswd ODL keystore password
+     * @param withTag return the certificate Req string with tag if true
+     * @return the certificate request
+     */
+    @Nonnull String genODLKeyStoreCertificateReq(@Nonnull String storePasswd, boolean withTag);
+
+    /**
+     * Get the SSL Context that will be used to establish the connection
+     *
+     * @return SSLContext object
+     */
+    SSLContext getServerContext();
+}
index f96802ffd5aaa7218e045f3e3866e5208c666075..5b1ac1926cc3ec6ea4bb3f1a83253b496ce9a945 100644 (file)
@@ -10,15 +10,12 @@ package org.opendaylight.aaa.cert.impl;
 import java.security.KeyStore;
 import java.util.ArrayList;
 import java.util.List;
-
 import org.opendaylight.aaa.cert.api.IAaaCertMdsalProvider;
 import org.opendaylight.aaa.cert.utils.KeyStoresDataUtils;
 import org.opendaylight.aaa.cert.utils.MdsalUtils;
 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ProviderContext;
-import org.opendaylight.controller.sal.binding.api.BindingAwareProvider;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.KeyStores;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.KeyStoresBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.cipher.suite.CipherSuites;
@@ -26,10 +23,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev1603
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.key.stores.SslData;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.ssl.data.OdlKeystore;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.ssl.data.TrustKeystore;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.FrameworkUtil;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -45,14 +38,12 @@ public class AaaCertMdsalProvider implements IAaaCertMdsalProvider {
 
     private final DataBroker dataBroker;
     private final KeyStoresDataUtils keyStoresData;
-    private final ODLMdsalKeyTool odlKeyTool;
+    private final ODLKeyTool odlKeyTool;
 
     public AaaCertMdsalProvider(final DataBroker dataBroker, final AAAEncryptionService encryptionSrv) {
         this.dataBroker = dataBroker;
-        final KeyStores keyStoreData = new KeyStoresBuilder().setId(KeyStoresDataUtils.KEYSTORES_DATA_TREE).build();
-        MdsalUtils.initalizeDatastore(LogicalDatastoreType.CONFIGURATION, dataBroker, KeyStoresDataUtils.getKeystoresIid(), keyStoreData);
         keyStoresData = new KeyStoresDataUtils(encryptionSrv);
-        odlKeyTool = new ODLMdsalKeyTool();
+        odlKeyTool = new ODLKeyTool();
         LOG.info("AaaCertMdsalProvider Initialized");
     }
 
@@ -80,7 +71,7 @@ public class AaaCertMdsalProvider implements IAaaCertMdsalProvider {
             final String[] cipherSuites) {
         final OdlKeystore odlKeystore = keyStoresData.createOdlKeystore(odlKeystoreName, odlKeystoreAlias, odlKeystorePwd,
                     odlKeystoreDname, odlKeystoreSignAlg, odlKeystoreKeyAlg, odlKeystoreValidity, odlKeystoreKeysize, odlKeyTool);
-        final TrustKeystore trustKeystore = keyStoresData.createTrustKeystore(trustKeystoreName, trustKeystorePwd, null, odlKeyTool);
+        final TrustKeystore trustKeystore = keyStoresData.createTrustKeystore(trustKeystoreName, trustKeystorePwd, odlKeyTool);
         final List<CipherSuites> cipherSuitesList = new ArrayList<>();
         if (cipherSuites != null) {
             for (final String suite : cipherSuites) {
@@ -130,18 +121,14 @@ public class AaaCertMdsalProvider implements IAaaCertMdsalProvider {
         }
     }
 
-    @Override
-    public String genODLKeyStoreCertificateReq(final String bundleName, final boolean withTag) {
-        return genODLKeyStoreCertificateReq(bundleName, KeyStoreConstant.DEFAULT_SIGN_ALG, withTag);
-    }
 
     @Override
-    public String genODLKeyStoreCertificateReq(final String bundleName, final String signAlg, final boolean withTag) {
+    public String genODLKeyStoreCertificateReq(final String bundleName, final boolean withTag) {
         final SslData sslData = keyStoresData.getSslData(dataBroker, bundleName);
         if (sslData != null) {
             final OdlKeystore odlKeyStore = sslData.getOdlKeystore();
             final KeyStore keystore = odlKeyTool.loadKeyStore(odlKeyStore.getKeystoreFile(), sslData.getOdlKeystore().getStorePassword());
-            return odlKeyTool.generateCertificateReq(keystore, odlKeyStore.getStorePassword(), odlKeyStore.getAlias(), signAlg, withTag);
+            return odlKeyTool.generateCertificateReq(keystore, odlKeyStore.getStorePassword(), odlKeyStore.getAlias(), odlKeyStore.getSignAlg(), withTag);
         }
         return null;
     }
@@ -149,16 +136,11 @@ public class AaaCertMdsalProvider implements IAaaCertMdsalProvider {
     @Override
     public String[] getCipherSuites(final String bundleName) {
         final SslData sslData = keyStoresData.getSslData(dataBroker, bundleName);
-        if (sslData != null) {
-            if (sslData.getCipherSuites() != null) {
-                final List<String> cipherSuites = new ArrayList<>();
-                for (final CipherSuites suite : sslData.getCipherSuites()) {
-                    cipherSuites.add(suite.getSuiteName());
-                }
-                return (String[]) cipherSuites.toArray();
-            }
+        final List<String> suites = new ArrayList<String>();
+        if (sslData != null && sslData.getCipherSuites() != null && !sslData.getCipherSuites().isEmpty()) {
+           sslData.getCipherSuites().stream().forEach(cs -> { suites.add(cs.getSuiteName()); });
         }
-        return null;
+        return suites.toArray(new String[suites.size()]);
     }
 
     @Override
@@ -178,7 +160,7 @@ public class AaaCertMdsalProvider implements IAaaCertMdsalProvider {
         if (sslData != null) {
             final OdlKeystore odlKeyStore = sslData.getOdlKeystore();
             final KeyStore keystore = odlKeyTool.loadKeyStore(odlKeyStore.getKeystoreFile(), odlKeyStore.getStorePassword());
-            return odlKeyTool.getCertificate(keystore, odlKeyStore.getStorePassword(), odlKeyStore.getAlias(), withTag);
+            return odlKeyTool.getCertificate(keystore, odlKeyStore.getAlias(), withTag);
         }
         return null;
     }
@@ -205,7 +187,7 @@ public class AaaCertMdsalProvider implements IAaaCertMdsalProvider {
         if (sslData != null) {
             final TrustKeystore trustKeyStore = sslData.getTrustKeystore();
             final KeyStore keystore = odlKeyTool.loadKeyStore(trustKeyStore.getKeystoreFile(), trustKeyStore.getStorePassword());
-            return odlKeyTool.getCertificate(keystore, trustKeyStore.getStorePassword(), alias, withTag);
+            return odlKeyTool.getCertificate(keystore, alias, withTag);
         }
         return null;
     }
@@ -238,4 +220,12 @@ public class AaaCertMdsalProvider implements IAaaCertMdsalProvider {
         }
         return null;
     }
+
+    @Override
+    public void initializeKeystoreDataTree() {
+        if (MdsalUtils.read(dataBroker, LogicalDatastoreType.CONFIGURATION, KeyStoresDataUtils.getKeystoresIid()) == null) {
+            final KeyStores keyStoreData = new KeyStoresBuilder().setId(KeyStoresDataUtils.KEYSTORES_DATA_TREE).build();
+            MdsalUtils.initalizeDatastore(LogicalDatastoreType.CONFIGURATION, dataBroker, KeyStoresDataUtils.getKeystoresIid(), keyStoreData);
+        }
+    }
 }
index 0d6c18c6106718b8187ae5f03e3bdac9a0ba7779..e8dace5f36ecd372807f079f1d13b5cb9b42413c 100644 (file)
@@ -13,11 +13,8 @@ import java.util.ArrayList;
 import java.util.List;
 
 import org.opendaylight.aaa.cert.api.IAaaCertProvider;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rev151126.AaaCertServiceConfig;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rev151126.aaa.cert.service.config.CtlKeystore;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rev151126.aaa.cert.service.config.CtlKeystoreBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rev151126.aaa.cert.service.config.TrustKeystore;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rev151126.aaa.cert.service.config.TrustKeystoreBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rev151126.aaa.cert.service.config.ctlkeystore.CipherSuites;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -30,20 +27,16 @@ import org.slf4j.LoggerFactory;
  */
 public class AaaCertProvider implements IAaaCertProvider {
 
-    private final static Logger LOG = LoggerFactory.getLogger(AaaCertProvider.class);
-    private CtlKeystore ctlKeyStore;
+    private static final Logger LOG = LoggerFactory.getLogger(AaaCertProvider.class);
+
+    private final CtlKeystore ctlKeyStore;
     private final ODLKeyTool odlKeyTool;
-    private TrustKeystore trustKeyStore;
+    private final TrustKeystore trustKeyStore;
 
-    public AaaCertProvider(final AaaCertServiceConfig aaaCertServiceConfig) {
+    public AaaCertProvider(final CtlKeystore ctlKeyStore, final TrustKeystore trustKeyStore) {
         odlKeyTool = new ODLKeyTool();
-        this.ctlKeyStore = aaaCertServiceConfig.getCtlKeystore();
-        this.trustKeyStore = aaaCertServiceConfig.getTrustKeystore();
-        if (aaaCertServiceConfig.isUseConfig() && !KeyStoreConstant.checkKeyStoreFile(ctlKeyStore.getName())) {
-            LOG.info("Creating keystore based on given configuration");
-            this.createODLKeyStore();
-            this.createTrustKeyStore();
-        }
+        this.ctlKeyStore = ctlKeyStore;
+        this.trustKeyStore = trustKeyStore;
         LOG.info("aaa Certificate Service Initalized");
     }
 
@@ -59,7 +52,8 @@ public class AaaCertProvider implements IAaaCertProvider {
 
     @Override
     public boolean addCertificateODLKeyStore(final String storePasswd, final String alias, final String certificate) {
-        return odlKeyTool.addCertificate(ctlKeyStore.getName(), storePasswd, certificate, alias);
+        final KeyStore keyStore = odlKeyTool.addCertificate(odlKeyTool.loadKeyStore(ctlKeyStore.getName(), storePasswd), certificate, alias, true);
+        return odlKeyTool.exportKeystore(keyStore, storePasswd, ctlKeyStore.getName());
     }
 
     @Override
@@ -69,7 +63,8 @@ public class AaaCertProvider implements IAaaCertProvider {
 
     @Override
     public boolean addCertificateTrustStore(final String storePasswd, final String alias, final String certificate) {
-        return odlKeyTool.addCertificate(trustKeyStore.getName(), storePasswd, certificate, alias);
+        final KeyStore keyStore = odlKeyTool.addCertificate(odlKeyTool.loadKeyStore(trustKeyStore.getName(), storePasswd), certificate, alias, true);
+        return odlKeyTool.exportKeystore(keyStore, storePasswd, trustKeyStore.getName());
     }
 
     @Override
@@ -78,60 +73,36 @@ public class AaaCertProvider implements IAaaCertProvider {
     }
 
     @Override
-    public void createODLKeyStore() {
-        createODLKeyStore(ctlKeyStore.getName(),ctlKeyStore.getStorePassword(), ctlKeyStore.getAlias(),
-                  ctlKeyStore.getDname(), ctlKeyStore.getValidity());
-    }
-
-    @Override
-    public String createODLKeyStore(final String keyStore, final String storePasswd, final String alias,
-            final String dName, final int validity) {
-        ctlKeyStore = new CtlKeystoreBuilder().setAlias(alias)
-                                              .setDname(dName)
-                                              .setName(keyStore)
-                                              .setStorePassword(storePasswd)
-                                              .setValidity(validity)
-                                              .build();
-        if(odlKeyTool.createKeyStoreWithSelfSignCert(keyStore, storePasswd, dName, alias, validity)) {
-            return keyStore + " Keystore created.";
-        } else {
-            return "Failed to create keystore " + keyStore;
+    public boolean createKeyStores() {
+        if (!KeyStoreConstant.checkKeyStoreFile(ctlKeyStore.getName())) {
+            final KeyStore keyStore = odlKeyTool.createKeyStoreWithSelfSignCert(ctlKeyStore.getName(), ctlKeyStore.getStorePassword(), ctlKeyStore.getDname(),
+                    ctlKeyStore.getAlias(), ctlKeyStore.getValidity(), ctlKeyStore.getKeyAlg(), ctlKeyStore.getKeysize(), ctlKeyStore.getSignAlg());
+             if(!odlKeyTool.exportKeystore(keyStore, ctlKeyStore.getStorePassword(), ctlKeyStore.getName())) {
+                return false;
+             }
         }
-    }
-
-    @Override
-    public void createTrustKeyStore() {
-        odlKeyTool.createKeyStoreImportCert(trustKeyStore.getName(), trustKeyStore.getStorePassword(),
-                trustKeyStore.getCertFile(), trustKeyStore.getAlias());
-    }
-
-    @Override
-    public String createTrustKeyStore(final String keyStore, final String storePasswd, final String alias) {
-        trustKeyStore = new TrustKeystoreBuilder().setAlias(alias)
-                                                  .setName(keyStore)
-                                                  .setStorePassword(storePasswd)
-                                                  .build();
-        if(odlKeyTool.createKeyStoreImportCert(keyStore, storePasswd, trustKeyStore.getCertFile(), alias)) {
-            return keyStore + " Keystore created.";
-        } else {
-            return "Failed to create keystore " + keyStore;
+        if (!KeyStoreConstant.checkKeyStoreFile(trustKeyStore.getName())) {
+            final KeyStore keyStore = odlKeyTool.createEmptyKeyStore(trustKeyStore.getStorePassword());
+            if (!odlKeyTool.exportKeystore(keyStore, trustKeyStore.getStorePassword(), trustKeyStore.getName()))
+                return false;
         }
+        return true;
     }
 
     @Override
-    public String genODLKeyStoreCertificateReq(final String storePasswd, final String alias, final boolean withTag) {
-        return odlKeyTool.generateCertificateReq(ctlKeyStore.getName(), storePasswd,
-                     alias, KeyStoreConstant.DEFAULT_SIGN_ALG, withTag);
+    public String genODLKeyStoreCertificateReq(final String storePasswd, final boolean withTag) {
+        return odlKeyTool.generateCertificateReq(odlKeyTool.loadKeyStore(ctlKeyStore.getName(), storePasswd),
+                storePasswd, ctlKeyStore.getAlias(), ctlKeyStore.getSignAlg(), withTag);
     }
 
     @Override
-    public String genODLKeyStoreCertificateReq(final String alias, final boolean withTag) {
-        return genODLKeyStoreCertificateReq(ctlKeyStore.getStorePassword(), alias, withTag);
+    public String genODLKeyStoreCertificateReq(final boolean withTag) {
+        return genODLKeyStoreCertificateReq(ctlKeyStore.getStorePassword(), withTag);
     }
 
     @Override
     public String getCertificateTrustStore(final String storePasswd, final String aliase, final boolean withTag) {
-        return odlKeyTool.getCertificate(trustKeyStore.getName(), storePasswd, aliase, withTag);
+        return odlKeyTool.getCertificate(odlKeyTool.loadKeyStore(trustKeyStore.getName(), storePasswd), aliase, withTag);
     }
 
     @Override
@@ -140,33 +111,32 @@ public class AaaCertProvider implements IAaaCertProvider {
     }
 
     @Override
-    public String getODLKeyStoreCertificate(final String storePasswd, final String alias, final boolean withTag) {
-        return odlKeyTool.getCertificate(ctlKeyStore.getName(), storePasswd, alias, withTag);
+    public String getODLKeyStoreCertificate(final String storePasswd, final boolean withTag) {
+        return odlKeyTool.getCertificate(odlKeyTool.loadKeyStore(ctlKeyStore.getName(), storePasswd), ctlKeyStore.getAlias(), withTag);
     }
 
     @Override
-    public String getODLKeyStoreCertificate(final String alias, final boolean withTag) {
-        return odlKeyTool.getCertificate(ctlKeyStore.getName(), ctlKeyStore.getStorePassword(), alias, withTag);
+    public String getODLKeyStoreCertificate(final boolean withTag) {
+        return getODLKeyStoreCertificate(ctlKeyStore.getStorePassword(), withTag);
     }
 
     @Override
     public KeyStore getODLKeyStore() {
-        return odlKeyTool.getKeyStore(ctlKeyStore.getName(), ctlKeyStore.getStorePassword());
+        return odlKeyTool.loadKeyStore(ctlKeyStore.getName(), ctlKeyStore.getStorePassword());
     }
 
     @Override
     public KeyStore getTrustKeyStore() {
-        return odlKeyTool.getKeyStore(trustKeyStore.getName(), trustKeyStore.getStorePassword());
+        return odlKeyTool.loadKeyStore(trustKeyStore.getName(), trustKeyStore.getStorePassword());
     }
 
     @Override
     public String[] getCipherSuites() {
-        List<String> suites = new ArrayList<>();
-        if (ctlKeyStore.getCipherSuites() != null && !ctlKeyStore.getCipherSuites().isEmpty()) {
-            for (CipherSuites cipherSuite : ctlKeyStore.getCipherSuites()) {
-                suites.add(cipherSuite.getSuiteName());
-            }
+        final List<String> suites = new ArrayList<String>();
+        final List<CipherSuites> cipherSuites = ctlKeyStore.getCipherSuites();
+        if ( cipherSuites != null && !cipherSuites.isEmpty()) {
+            cipherSuites.stream().forEach(cs -> { suites.add(cs.getSuiteName()); });
         }
-        return (String[]) suites.toArray();
+        return suites.toArray(new String[suites.size()]);
     }
 }
\ No newline at end of file
index ea74bf6fa2a5245d7c70a5527a977aa70640e8d2..cf1be2374b22a2573a114683a409769373e0efc1 100644 (file)
@@ -9,18 +9,17 @@
 package org.opendaylight.aaa.cert.impl;
 
 import com.google.common.util.concurrent.SettableFuture;
-
 import java.util.concurrent.Future;
-
 import org.opendaylight.aaa.cert.api.IAaaCertProvider;
+import org.opendaylight.aaa.encrypt.AAAEncryptionService;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rev151126.AaaCertServiceConfig;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rpc.rev151215.AaaCertRpcService;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rpc.rev151215.GetNodeCertifcateInput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rpc.rev151215.GetNodeCertifcateOutput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rpc.rev151215.GetNodeCertifcateOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rpc.rev151215.GetODLCertificateInput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rpc.rev151215.GetODLCertificateOutput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rpc.rev151215.GetODLCertificateOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rpc.rev151215.GetODLCertificateReqInput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rpc.rev151215.GetODLCertificateReqOutput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rpc.rev151215.GetODLCertificateReqOutputBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rpc.rev151215.SetNodeCertifcateInput;
@@ -30,15 +29,34 @@ import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+/**
+ * AaaCertRpcServiceImpl Implements the basic RPCs operation that add and retrieve certificates to and from the keystores.
+ * These RPCs are accessible only for by the ODL's user who has the admin role and can be disabled. Check the shiro.ini file for more info.
+ *
+ * @author mserngawy
+ *
+ */
 public class AaaCertRpcServiceImpl implements AaaCertRpcService {
 
     private static final Logger LOG = LoggerFactory.getLogger(AaaCertRpcServiceImpl.class);
 
     private final IAaaCertProvider aaaCertProvider;
 
-    public AaaCertRpcServiceImpl(IAaaCertProvider aaaCertProvider) {
-        this.aaaCertProvider = aaaCertProvider;
-        LOG.info("AaaCert Rpc Service has been Initalized");
+    public AaaCertRpcServiceImpl(final AaaCertServiceConfig aaaCertServiceConfig, final DataBroker dataBroker, final AAAEncryptionService encryptionSrv) {
+        if (aaaCertServiceConfig.isUseConfig()) {
+            if (aaaCertServiceConfig.isUseMdsal()) {
+                aaaCertProvider = new DefaultMdsalSslData(new AaaCertMdsalProvider(dataBroker, encryptionSrv), aaaCertServiceConfig.getBundleName(),
+                        aaaCertServiceConfig.getCtlKeystore(), aaaCertServiceConfig.getTrustKeystore());
+                LOG.debug("Using default mdsal SslData as aaaCertProvider");
+            } else {
+                aaaCertProvider = new AaaCertProvider(aaaCertServiceConfig.getCtlKeystore(), aaaCertServiceConfig.getTrustKeystore());
+                LOG.debug("Using default keystore files as aaaCertProvider");
+            }
+            LOG.info("AaaCert Rpc Service has been initialized");
+        } else {
+            aaaCertProvider = null;
+            LOG.info("AaaCert Rpc Service has not been initialized, change the initial aaa-cert-config data and restart Opendaylight");
+        }
     }
 
     @Override
@@ -69,9 +87,9 @@ public class AaaCertRpcServiceImpl implements AaaCertRpcService {
     }
 
     @Override
-    public Future<RpcResult<GetODLCertificateOutput>> getODLCertificate(GetODLCertificateInput input) {
+    public Future<RpcResult<GetODLCertificateOutput>> getODLCertificate() {
         final SettableFuture<RpcResult<GetODLCertificateOutput>> futureResult = SettableFuture.create();
-        final String cert = aaaCertProvider.getODLKeyStoreCertificate(input.getCertAlias(), false);
+        final String cert = aaaCertProvider.getODLKeyStoreCertificate(false);
         if (cert != null && !cert.isEmpty()) {
             final GetODLCertificateOutput odlCertOutput = new GetODLCertificateOutputBuilder()
                                                         .setOdlCert(cert)
@@ -84,9 +102,9 @@ public class AaaCertRpcServiceImpl implements AaaCertRpcService {
     }
 
     @Override
-    public Future<RpcResult<GetODLCertificateReqOutput>> getODLCertificateReq(GetODLCertificateReqInput input) {
+    public Future<RpcResult<GetODLCertificateReqOutput>> getODLCertificateReq() {
         final SettableFuture<RpcResult<GetODLCertificateReqOutput>> futureResult = SettableFuture.create();
-        final String certReq = aaaCertProvider.genODLKeyStoreCertificateReq(input.getCertReqAlias(), false);
+        final String certReq = aaaCertProvider.genODLKeyStoreCertificateReq(false);
         if (certReq != null && !certReq.isEmpty()) {
             final GetODLCertificateReqOutput odlCertReqOutput = new GetODLCertificateReqOutputBuilder()
                                                         .setOdlCertReq(certReq)
diff --git a/aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/CertificateManagerService.java b/aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/CertificateManagerService.java
new file mode 100644 (file)
index 0000000..b61a120
--- /dev/null
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2016 Inocybe Technologies. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.aaa.cert.impl;
+
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.Security;
+import java.security.UnrecoverableKeyException;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManagerFactory;
+import org.opendaylight.aaa.cert.api.IAaaCertProvider;
+import org.opendaylight.aaa.cert.api.ICertificateManager;
+import org.opendaylight.aaa.encrypt.AAAEncryptionService;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rev151126.AaaCertServiceConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * CertificateManagerService implements ICertificateManager and work as adapter to which AaaCertProvider is used.
+ *
+ * @author mserngawy
+ *
+ */
+public class CertificateManagerService implements ICertificateManager {
+
+    private final static Logger LOG = LoggerFactory.getLogger(CertificateManagerService.class);
+
+    private final IAaaCertProvider aaaCertProvider;
+
+    public CertificateManagerService(final AaaCertServiceConfig aaaCertServiceConfig, final DataBroker dataBroker, final AAAEncryptionService encryptionSrv) {
+       if (aaaCertServiceConfig.isUseConfig()) {
+            if (aaaCertServiceConfig.isUseMdsal()) {
+                aaaCertProvider = new DefaultMdsalSslData(new AaaCertMdsalProvider(dataBroker, encryptionSrv), aaaCertServiceConfig.getBundleName(),
+                        aaaCertServiceConfig.getCtlKeystore(), aaaCertServiceConfig.getTrustKeystore());
+                LOG.debug("Using default mdsal SslData as aaaCertProvider");
+            } else {
+                aaaCertProvider = new AaaCertProvider(aaaCertServiceConfig.getCtlKeystore(), aaaCertServiceConfig.getTrustKeystore());
+                LOG.debug("Using default keystore files as aaaCertProvider");
+            }
+            aaaCertProvider.createKeyStores();
+            LOG.info("Certificate Manager service has been initialized");
+        } else {
+            aaaCertProvider = null;
+            LOG.info("Certificate Manager service has not been initialized, change the initial aaa-cert-config data and restart Opendaylight");
+        }
+    }
+
+    @Override
+    public KeyStore getODLKeyStore() {
+        return aaaCertProvider.getODLKeyStore();
+    }
+
+    @Override
+    public KeyStore getTrustKeyStore() {
+        return aaaCertProvider.getTrustKeyStore();
+    }
+
+    @Override
+    public String[] getCipherSuites() {
+        return aaaCertProvider.getCipherSuites();
+    }
+
+    @Override
+    public String getCertificateTrustStore(String storePasswd, String alias, boolean withTag) {
+        return aaaCertProvider.getCertificateTrustStore(storePasswd, alias, withTag);
+    }
+
+    @Override
+    public String getODLKeyStoreCertificate(String storePasswd, boolean withTag) {
+        return aaaCertProvider.getODLKeyStoreCertificate(storePasswd, withTag);
+    }
+
+    @Override
+    public String genODLKeyStoreCertificateReq(String storePasswd, boolean withTag) {
+        return aaaCertProvider.genODLKeyStoreCertificateReq(storePasswd, withTag);
+    }
+
+    @Override
+    public SSLContext getServerContext() {
+        String algorithm = Security
+                .getProperty("ssl.KeyManagerFactory.algorithm");
+        if (algorithm == null) {
+            algorithm = "SunX509";
+        }
+        SSLContext serverContext = null;
+        try {
+            KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
+            kmf.init(aaaCertProvider.getODLKeyStore(), aaaCertProvider.getOdlKeyStoreInfo().getStorePassword().toCharArray());
+            TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
+            tmf.init(aaaCertProvider.getTrustKeyStore());
+
+            serverContext = SSLContext.getInstance(KeyStoreConstant.TLS_PROTOCOL);
+            serverContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
+        } catch (final NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | KeyManagementException  e) {
+            LOG.error("Error while creating SSLContext ", e);
+        }
+        return serverContext;
+    }
+}
diff --git a/aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/DefaultMdsalSslData.java b/aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/DefaultMdsalSslData.java
new file mode 100644 (file)
index 0000000..763b4b4
--- /dev/null
@@ -0,0 +1,161 @@
+/*
+ * Copyright (c) 2016 Inocybe Technologies. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.aaa.cert.impl;
+
+import java.security.KeyStore;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.lang3.StringUtils;
+import org.opendaylight.aaa.cert.api.IAaaCertProvider;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rev151126.aaa.cert.service.config.CtlKeystore;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rev151126.aaa.cert.service.config.TrustKeystore;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rev151126.aaa.cert.service.config.ctlkeystore.CipherSuites;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * DefaultMdsalSslData Implements the default Mdsal SslData based on the configuration exist in the aaa-cert-config.xml
+ *
+ * @author mserngawy
+ *
+ */
+public class DefaultMdsalSslData implements IAaaCertProvider {
+
+    private static final Logger LOG = LoggerFactory.getLogger(DefaultMdsalSslData.class);
+    private static final String errorMessage = "password is not correct or keystore has been corrupted";
+
+    private final AaaCertMdsalProvider aaaCertMdsalProv;
+    private final CtlKeystore ctlKeyStore;
+    private final TrustKeystore trustKeyStore;
+    private final String bundleName;
+
+    public DefaultMdsalSslData(final AaaCertMdsalProvider aaaCertMdsalProv, final String bundleName,
+            final CtlKeystore ctlKeyStore, final TrustKeystore trustKeyStore) {
+        this.bundleName = bundleName;
+        this.aaaCertMdsalProv = aaaCertMdsalProv;
+        this.ctlKeyStore = ctlKeyStore;
+        this.trustKeyStore = trustKeyStore;
+        this.aaaCertMdsalProv.initializeKeystoreDataTree();
+    }
+
+    @Override
+    public boolean addCertificateODLKeyStore(String storePasswd, String alias, String certificate) {
+        if (!aaaCertMdsalProv.getSslData(bundleName).getOdlKeystore().getStorePassword().equals(storePasswd)) {
+            LOG.debug(errorMessage);
+            return false;
+        }
+        return aaaCertMdsalProv.addODLStoreSignedCertificate(bundleName, alias, certificate);
+    }
+
+    @Override
+    public boolean addCertificateODLKeyStore(String alias, String certificate) {
+        return aaaCertMdsalProv.addODLStoreSignedCertificate(bundleName, alias, certificate);
+    }
+
+    @Override
+    public boolean addCertificateTrustStore(String storePasswd, String alias, String certificate) {
+        if (aaaCertMdsalProv.getSslData(bundleName).getTrustKeystore().getStorePassword().equals(storePasswd)) {
+            LOG.debug(errorMessage);
+            return false;
+        }
+        return aaaCertMdsalProv.addTrustNodeCertificate(bundleName, alias, certificate);
+    }
+
+    @Override
+    public boolean addCertificateTrustStore(String alias, String certificate) {
+        return aaaCertMdsalProv.addTrustNodeCertificate(bundleName, alias, certificate);
+    }
+
+    @Override
+    public String genODLKeyStoreCertificateReq(String storePasswd, boolean withTag) {
+        if (!aaaCertMdsalProv.getSslData(bundleName).getOdlKeystore().getStorePassword().equals(storePasswd)) {
+            LOG.debug(errorMessage);
+            return StringUtils.EMPTY;
+        }
+        return aaaCertMdsalProv.genODLKeyStoreCertificateReq(bundleName, withTag);
+    }
+
+    @Override
+    public String genODLKeyStoreCertificateReq(boolean withTag) {
+        return aaaCertMdsalProv.genODLKeyStoreCertificateReq(bundleName, withTag);
+    }
+
+    @Override
+    public String getCertificateTrustStore(String storePasswd, String alias, boolean withTag) {
+        if (!aaaCertMdsalProv.getSslData(bundleName).getTrustKeystore().getStorePassword().equals(storePasswd)) {
+            LOG.debug(errorMessage);
+            return StringUtils.EMPTY;
+        }
+        return aaaCertMdsalProv.getTrustStoreCertificate(bundleName, alias, withTag);
+    }
+
+    @Override
+    public String getCertificateTrustStore(String alias, boolean withTag) {
+        return aaaCertMdsalProv.getTrustStoreCertificate(bundleName, alias, withTag);
+    }
+
+    @Override
+    public String getODLKeyStoreCertificate(String storePasswd, boolean withTag) {
+        if (!aaaCertMdsalProv.getSslData(bundleName).getOdlKeystore().getStorePassword().equals(storePasswd)) {
+            LOG.debug(errorMessage);
+            return StringUtils.EMPTY;
+        }
+        return aaaCertMdsalProv.getODLStoreCertificate(bundleName, withTag);
+    }
+
+    @Override
+    public String getODLKeyStoreCertificate(final boolean withTag) {
+        return aaaCertMdsalProv.getODLStoreCertificate(bundleName, withTag);
+    }
+
+    @Override
+    public KeyStore getODLKeyStore() {
+        return aaaCertMdsalProv.getODLKeyStore(bundleName);
+    }
+
+    @Override
+    public KeyStore getTrustKeyStore() {
+        return aaaCertMdsalProv.getTrustKeyStore(bundleName);
+    }
+
+    @Override
+    public String[] getCipherSuites() {
+        return aaaCertMdsalProv.getCipherSuites(bundleName);
+    }
+
+    @Override
+    public TrustKeystore getTrustKeyStoreInfo() {
+        return trustKeyStore;
+    }
+
+    @Override
+    public CtlKeystore getOdlKeyStoreInfo() {
+        return ctlKeyStore;
+    }
+
+    @Override
+    public boolean createKeyStores() {
+        if (aaaCertMdsalProv.getSslData(bundleName) == null) {
+            return aaaCertMdsalProv.addSslDataKeystores(bundleName, ctlKeyStore.getName(), ctlKeyStore.getStorePassword(),
+                    ctlKeyStore.getAlias(), ctlKeyStore.getDname(), ctlKeyStore.getKeyAlg(), ctlKeyStore.getSignAlg(),
+                    ctlKeyStore.getKeysize(), ctlKeyStore.getValidity(), trustKeyStore.getName(), trustKeyStore.getStorePassword(),
+                    getCipherSuites(ctlKeyStore.getCipherSuites())) != null;
+        }
+        return true;
+    }
+
+    private String[] getCipherSuites(final List<CipherSuites> cipherSuites) {
+        final List<String> suites = new ArrayList<String>();
+        if (cipherSuites != null & !cipherSuites.isEmpty()) {
+            cipherSuites.stream().forEach(cs -> { suites.add(cs.getSuiteName()); });
+        }
+        return suites.toArray(new String[suites.size()]);
+    }
+}
index 6d4866c3f7af01b52792224db896432173852a23..9527413a8d20f2c1ff3c72ccf158f9f849080ce1 100644 (file)
@@ -35,6 +35,7 @@ public class KeyStoreConstant {
     public static final int DEFAULT_VALIDITY = 365;
     public static final String END_CERTIFICATE = "-----END CERTIFICATE-----";
     public static final String END_CERTIFICATE_REQUEST = "-----END CERTIFICATE REQUEST-----";
+    public static final String TLS_PROTOCOL = "TLS";
     public static String KEY_STORE_PATH = "configuration" + File.separator + "ssl" + File.separator;
 
     public static boolean checkKeyStoreFile(final String fileName) {
index 07f413edb9cf709ba761be2cef98309af3074972..1d878b80121e0e52ca1a0b195e0015ec92a076a6 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015 Inocybe Technologies. and others.  All rights reserved.
+ * Copyright (c) 2016 Inocybe Technologies and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
@@ -9,6 +9,7 @@
 package org.opendaylight.aaa.cert.impl;
 
 import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
@@ -30,10 +31,9 @@ import java.security.cert.CertificateException;
 import java.security.cert.CertificateFactory;
 import java.security.cert.X509Certificate;
 import java.util.Date;
-
 import javax.xml.bind.DatatypeConverter;
-
 import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.lang3.StringUtils;
 import org.bouncycastle.asn1.x509.X509Name;
 import org.bouncycastle.jce.PKCS10CertificationRequest;
 import org.bouncycastle.jce.X509Principal;
@@ -42,14 +42,15 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * ODLKeyTool has the basic operation to manage the Java keyStores such as generate, add and delete certificates
+ * ODLKeyTool implements the basic operations that manage the Java keyStores such as create, generate, add and delete certificates.
  *
  * @author mserngawy
  *
  */
 public class ODLKeyTool {
 
-    private final static Logger LOG = LoggerFactory.getLogger(ODLKeyTool.class);
+    private static final Logger LOG = LoggerFactory.getLogger(ODLKeyTool.class);
+
     private final String workingDir;
 
     protected ODLKeyTool() {
@@ -62,48 +63,85 @@ public class ODLKeyTool {
         KeyStoreConstant.createDir(workingDir);
     }
 
-    public boolean addCertificate(final String keyStoreName, final String keyStorePwd, final String certificate, final String alias) {
+    /**
+     * Add certificate to the given keystore
+     *
+     * @param keyStore java keystore object
+     * @param certificate to add as string
+     * @param alias of the certificate
+     * @param deleteOld true to delete the old certificate that has the same alias otherwise it will fail if there is a certificate has same given alias.
+     * @return the given Keystore containing the certificate otherwise return null.
+     */
+    public KeyStore addCertificate(final KeyStore keyStore, final String certificate, final String alias, final boolean deleteOld) {
         try {
             final X509Certificate newCert = getCertificate(certificate);
-            final KeyStore keyStore = KeyStore.getInstance("JKS");
-            final FileInputStream fInputStream = new FileInputStream(workingDir + keyStoreName);
-            keyStore.load(fInputStream, keyStorePwd.toCharArray());
-            if(keyStore.isCertificateEntry(alias)) {
+            if(keyStore.isCertificateEntry(alias) && deleteOld) {
                 keyStore.deleteEntry(alias);
             }
-            keyStore.setCertificateEntry(alias, newCert);
-            keyStore.store( new FileOutputStream(workingDir + keyStoreName), keyStorePwd.toCharArray());
-            LOG.info("Certificate {}  Added to keyStore {}", alias, keyStoreName);
-            return true;
-        } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException | IOException e) {
+            if (newCert != null ) {
+                keyStore.setCertificateEntry(alias, newCert);
+            } else {
+                LOG.warn("{} Not a valid certificate {}", alias, certificate);
+                return null;
+            }
+            return keyStore;
+        } catch (final KeyStoreException e) {
             LOG.error("failed to add certificate", e);
-            return false;
+            return null;
         }
     }
 
-    public boolean createKeyStoreImportCert(final String keyStoreName, final String keyStorePwd, final String certFile, final String alias) {
-        KeyStore trustKeyStore;
+    /**
+     * Convert the given java keystore object to byte array
+     *
+     * @param keyStore object
+     * @param keystorePassword the password of the given keystore
+     * @return byte array
+     */
+    public byte[] convertKeystoreToBytes(final KeyStore keyStore, final String keystorePassword) {
+        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
         try {
-            trustKeyStore = KeyStore.getInstance("JKS");
-            trustKeyStore.load(null, keyStorePwd.toCharArray());
-            if(KeyStoreConstant.checkKeyStoreFile(certFile)) {
-                final String certificate = KeyStoreConstant.readFile(certFile);
-                final X509Certificate newCert = getCertificate(certificate);
-                trustKeyStore.setCertificateEntry(alias, newCert);
-            }
-            trustKeyStore.store( new FileOutputStream(workingDir + keyStoreName), keyStorePwd.toCharArray());
-            LOG.info("{} is created", keyStoreName);
-            return true;
-        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
-            LOG.error("Failed to create keystore {}", keyStoreName, e);
-            return false;
+            keyStore.store(byteArrayOutputStream, keystorePassword.toCharArray());
+        } catch (final KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
+            LOG.error("Fatal error convert keystore to bytes", e);
         }
+        return byteArrayOutputStream.toByteArray();
+    }
+
+    /**
+     * Create a keystore that has self sign private/public keys using the default key algorithm (RSA), size (2048)
+     * and signing algorithm (SHA1WithRSAEncryption)
+     *
+     * @param keyStoreName the keystore name
+     * @param keystorePassword the keystore password
+     * @param dName the generated key's Dname
+     * @param keyAlias the private key alias
+     * @param validity the key validity
+     * @return keystore object
+     */
+    public KeyStore createKeyStoreWithSelfSignCert(final String keyStoreName, final String keystorePassword, final String dName, final String keyAlias, final int validity) {
+        return createKeyStoreWithSelfSignCert(keyStoreName, keystorePassword, dName, keyAlias, validity, KeyStoreConstant.DEFAULT_KEY_ALG,
+                KeyStoreConstant.DEFAULT_KEY_SIZE, KeyStoreConstant.DEFAULT_SIGN_ALG);
     }
 
-    public boolean createKeyStoreWithSelfSignCert(final String keyStoreName, final String keyStorePwd, final String dName, final String keyAlias, final int validity) {
+    /**
+     * Create a keystore that has self sign private/public keys
+     *
+     * @param keyStoreName the keystore name
+     * @param keystorePassword the keystore password
+     * @param dName the generated key's Dname
+     * @param keyAlias the private key alias
+     * @param validity the key validity
+     * @param keyAlg the algorithm that will be used to generate the key
+     * @param keySize the key size
+     * @param signAlg the signing algorithm
+     * @return keystore object
+     */
+    public KeyStore createKeyStoreWithSelfSignCert(final String keyStoreName, final String keystorePassword, final String dName,
+            final String keyAlias, final int validity, final String keyAlg, final int keySize, final String signAlg) {
         try {
-            final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyStoreConstant.DEFAULT_KEY_ALG);
-            keyPairGenerator.initialize(KeyStoreConstant.DEFAULT_KEY_SIZE);
+            final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyAlg);
+            keyPairGenerator.initialize(keySize);
             final KeyPair keyPair = keyPairGenerator.generateKeyPair();
             final X509V3CertificateGenerator x509V3CertGen = new X509V3CertificateGenerator();
             x509V3CertGen.setSerialNumber(getSecureRandomeInt());
@@ -112,33 +150,76 @@ public class ODLKeyTool {
             x509V3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (KeyStoreConstant.DAY_TIME * validity)));
             x509V3CertGen.setSubjectDN(new X509Principal(dName));
             x509V3CertGen.setPublicKey(keyPair.getPublic());
-            x509V3CertGen.setSignatureAlgorithm(KeyStoreConstant.DEFAULT_SIGN_ALG);
+            x509V3CertGen.setSignatureAlgorithm(signAlg);
             final X509Certificate x509Cert = x509V3CertGen.generateX509Certificate(keyPair.getPrivate());
             final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
-            ctlKeyStore.load(null, keyStorePwd.toCharArray());
-            ctlKeyStore.setKeyEntry(keyAlias, keyPair.getPrivate(), keyStorePwd.toCharArray(),
+            ctlKeyStore.load(null, keystorePassword.toCharArray());
+            ctlKeyStore.setKeyEntry(keyAlias, keyPair.getPrivate(), keystorePassword.toCharArray(),
                        new java.security.cert.Certificate[]{x509Cert});
-            final FileOutputStream fOutputStream = new FileOutputStream(workingDir + keyStoreName);
-            ctlKeyStore.store( fOutputStream, keyStorePwd.toCharArray());
             LOG.info("{} is created", keyStoreName);
-            return true;
+            return ctlKeyStore;
         }
-        catch (NoSuchAlgorithmException | InvalidKeyException | SecurityException | SignatureException | KeyStoreException | CertificateException | IOException e) {
-            LOG.error("Fatal error creating key", e);
+        catch (final NoSuchAlgorithmException | InvalidKeyException | SecurityException | SignatureException | KeyStoreException | CertificateException | IOException e) {
+            LOG.error("Fatal error creating keystore", e);
+            return null;
+        }
+    }
+
+    /**
+     * Create empty keystore does not has private or public key.
+     *
+     * @param keystorePassword the keystore password
+     * @return keystore object
+     */
+    public KeyStore createEmptyKeyStore(final String keystorePassword) {
+        try {
+            final KeyStore trustKeyStore = KeyStore.getInstance("JKS");
+            trustKeyStore.load(null, keystorePassword.toCharArray());
+            return trustKeyStore;
+        } catch (final KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
+            LOG.error("Failed to create trust keystore", e);
+            return null;
+        }
+    }
+
+    /**
+     * Export the given keystore as a file under the working directory
+     *
+     * @param keystore object
+     * @param keystorePassword the keystore password
+     * @param fileName of the keystore
+     * @return true if successes to export the keystore
+     */
+    public boolean exportKeystore(final KeyStore keystore, final String keystorePassword, final String fileName) {
+        if (keystore == null) {
+            return false;
+        }
+        try (final FileOutputStream fOutputStream = new FileOutputStream(workingDir + fileName)) {
+            keystore.store(fOutputStream, keystorePassword.toCharArray());
+            return true;
+        } catch (final KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
+            LOG.error("Fatal error export keystore", e);
             return false;
         }
     }
 
-    public String generateCertificateReq(final String keyStoreName, final String keyStorePwd, final String keyAlias, final String signAlg,
-                  final boolean withTag) {
+    /**
+     * Generate a certificate signing request based on the given keystore private/public key
+     *
+     * @param keyStore object
+     * @param keystorePassword the keystore password
+     * @param keyAlias Alias of the given keystore's private key.
+     * @param signAlg the signing algorithm
+     * @param withTag true to add the certificate request tag to the certificate request string.
+     * @return certificate request as string.
+     */
+    public String generateCertificateReq(final KeyStore keyStore, final String keystorePassword, final String keyAlias, final String signAlg,
+            final boolean withTag) {
         try {
-            final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
-            final FileInputStream fInputStream = new FileInputStream(workingDir + keyStoreName);
-            ctlKeyStore.load(fInputStream, keyStorePwd.toCharArray());
-            if (ctlKeyStore.containsAlias(keyAlias)) {
-                final X509Certificate odlCert = (X509Certificate)ctlKeyStore.getCertificate(keyAlias);
+            if (keyStore.containsAlias(keyAlias)) {
+                final X509Certificate odlCert = (X509Certificate)keyStore.getCertificate(keyAlias);
                 final PublicKey pubKey = odlCert.getPublicKey();
-                final PrivateKey privKey = (PrivateKey)ctlKeyStore.getKey(keyAlias, keyStorePwd.toCharArray());
+                final PrivateKey privKey = (PrivateKey)keyStore.getKey(keyAlias, keystorePassword.toCharArray());
                 final String subject = odlCert.getSubjectDN().getName();
                 final X509Name xname = new X509Name(subject);
                 final String signatureAlgorithm = signAlg;
@@ -156,15 +237,53 @@ public class ODLKeyTool {
                 }
                 return certReq;
             }
-            LOG.info("{} KeyStore does not contain alias {}", keyStoreName, keyAlias);
-            return null;
-        } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException |
+            LOG.info("KeyStore does not contain alias {}", keyAlias);
+            return StringUtils.EMPTY;
+        } catch (final NoSuchAlgorithmException | KeyStoreException |
                  UnrecoverableKeyException | InvalidKeyException | NoSuchProviderException | SignatureException e) {
-            LOG.error("Failed to generate certificate request {}", e.getMessage());
-            return null;
+            LOG.error("Failed to generate certificate request", e);
+            return StringUtils.EMPTY;
+        }
+}
+
+    /**
+     * Get a certificate as String based on the given alias
+     *
+     * @param keyStore keystore that has the certificate
+     * @param certAlias certificate alias
+     * @param withTag true to add the certificate tag to the certificate string.
+     * @return certificate as string.
+     */
+    public String getCertificate(final KeyStore keyStore, final String certAlias, final boolean withTag) {
+        try {
+            if (keyStore.containsAlias(certAlias)) {
+                final X509Certificate odlCert = (X509Certificate) keyStore.getCertificate(certAlias);
+                final String cert = DatatypeConverter.printBase64Binary(odlCert.getEncoded());
+                if (withTag) {
+                    final StringBuilder sb = new StringBuilder();
+                    sb.append(KeyStoreConstant.BEGIN_CERTIFICATE);
+                    sb.append("\n");
+                    sb.append(cert);
+                    sb.append("\n");
+                    sb.append(KeyStoreConstant.END_CERTIFICATE);
+                    return sb.toString();
+                }
+                return cert;
+            }
+            LOG.info("KeyStore does not contain alias {}", certAlias);
+            return StringUtils.EMPTY;
+        } catch (final CertificateException | KeyStoreException e) {
+            LOG.error("Failed to get Certificate", e);
+            return StringUtils.EMPTY;
         }
     }
 
+    /**
+     * Get a X509Certificate object based on given certificate string.
+     *
+     * @param certificate as string
+     * @return X509Certificate if the certificate string is not well formated will return null
+     */
     private X509Certificate getCertificate(String certificate) {
         if (certificate.isEmpty()) {
             return null;
@@ -184,53 +303,56 @@ public class ODLKeyTool {
             newCert.checkValidity();
             return newCert;
         } catch (final CertificateException e) {
-            LOG.error("Failed to get certificate {}", e.getMessage());
+            LOG.error("Failed to get certificate", e);
             return null;
         }
     }
 
-    public String getCertificate(final String keyStoreName, final String keyStorePwd, final String certAlias, final boolean withTag) {
+    /**
+     * generate secure random number
+     *
+     * @return secure random number as BigInteger.
+     */
+    private BigInteger getSecureRandomeInt() {
+        final SecureRandom secureRandom = new SecureRandom();
+        final BigInteger bigInt = BigInteger.valueOf(secureRandom.nextInt());
+        return new BigInteger(1, bigInt.toByteArray());
+    }
+
+    /**
+     * Load the keystore object from the given byte array
+     *
+     * @param keyStoreBytes array of byte contain keystore object
+     * @param keystorePassword the keystore password
+     * @return keystore object otherwise return null if it fails to load.
+     */
+    public KeyStore loadKeyStore(final byte[] keyStoreBytes, final String keystorePassword) {
         try {
-            final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
-            final FileInputStream fInputStream = new FileInputStream(workingDir + keyStoreName);
-            ctlKeyStore.load(fInputStream, keyStorePwd.toCharArray());
-            if (ctlKeyStore.containsAlias(certAlias)) {
-                final X509Certificate odlCert = (X509Certificate)ctlKeyStore.getCertificate(certAlias);
-                final String cert = DatatypeConverter.printBase64Binary(odlCert.getEncoded());
-                if (withTag) {
-                    final StringBuilder sb = new StringBuilder();
-                    sb.append(KeyStoreConstant.BEGIN_CERTIFICATE);
-                    sb.append("\n");
-                    sb.append(cert);
-                    sb.append("\n");
-                    sb.append(KeyStoreConstant.END_CERTIFICATE);
-                    return sb.toString();
-                }
-                return cert;
-            }
-            LOG.info("{} KeyStore does not contain alias {}", keyStoreName, certAlias);
-            return null;
-        } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException e) {
-            LOG.error("Failed to get Certificate {}", e.getMessage());
+            final KeyStore keyStore = KeyStore.getInstance("JKS");
+            keyStore.load(new ByteArrayInputStream(keyStoreBytes), keystorePassword.toCharArray());
+            return keyStore;
+        } catch (final KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
+            LOG.error("Fatal error load keystore", e);
             return null;
         }
     }
 
-    public KeyStore getKeyStore(final String keyStoreName, final String keyStorePwd) {
+    /**
+     * Load the keystore from the working directory
+     *
+     * @param keyStoreName keystore file name
+     * @param keystorePassword keystore password
+     * @return keystore object otherwise return null if it fails to load.
+     */
+    public KeyStore loadKeyStore(final String keyStoreName, final String keystorePassword) {
         try {
             final KeyStore keyStore = KeyStore.getInstance("JKS");
             final FileInputStream fInputStream = new FileInputStream(workingDir + keyStoreName);
-            keyStore.load(fInputStream, keyStorePwd.toCharArray());
+            keyStore.load(fInputStream, keystorePassword.toCharArray());
             return keyStore;
         } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException e) {
             LOG.error("failed to get keystore {}", e.getMessage());
             return null;
         }
     }
-
-    private BigInteger getSecureRandomeInt() {
-        final SecureRandom secureRandom = new SecureRandom();
-        final BigInteger bigInt = BigInteger.valueOf(secureRandom.nextInt());
-        return new BigInteger(1, bigInt.toByteArray());
-    }
-}
\ No newline at end of file
+}
diff --git a/aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/ODLMdsalKeyTool.java b/aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/ODLMdsalKeyTool.java
deleted file mode 100644 (file)
index d06154b..0000000
+++ /dev/null
@@ -1,252 +0,0 @@
-/*
- * Copyright (c) 2016 Inocybe Technologies and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.aaa.cert.impl;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.math.BigInteger;
-import java.security.InvalidKeyException;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.security.SecureRandom;
-import java.security.SignatureException;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import java.util.Date;
-import java.util.List;
-
-import javax.xml.bind.DatatypeConverter;
-
-import org.apache.commons.codec.binary.Base64;
-import org.bouncycastle.asn1.x509.X509Name;
-import org.bouncycastle.jce.PKCS10CertificationRequest;
-import org.bouncycastle.jce.X509Principal;
-import org.bouncycastle.x509.X509V3CertificateGenerator;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.keystore.Certificates;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * ODLKeyTool has the basic operation to manage the Java keyStores such as generate, add and delete certificates
- *
- * @author mserngawy
- *
- */
-public class ODLMdsalKeyTool {
-
-    private final static Logger LOG = LoggerFactory.getLogger(ODLMdsalKeyTool.class);
-    private final String workingDir;
-
-    protected ODLMdsalKeyTool() {
-        workingDir = KeyStoreConstant.KEY_STORE_PATH;
-        KeyStoreConstant.createDir(workingDir);
-    }
-
-    public ODLMdsalKeyTool(final String workingDirectory) {
-        workingDir = workingDirectory;
-        KeyStoreConstant.createDir(workingDir);
-    }
-
-    public KeyStore addCertificate(final KeyStore keyStore, final String certificate, final String alias, final boolean deleteOld) {
-        try {
-            final X509Certificate newCert = getCertificate(certificate);
-            if(keyStore.isCertificateEntry(alias) && deleteOld) {
-                keyStore.deleteEntry(alias);
-            }
-            if (newCert != null ) {
-                keyStore.setCertificateEntry(alias, newCert);
-            } else {
-                LOG.warn("{} Not a valid certificate {}", alias, certificate);
-                return null;
-            }
-            return keyStore;
-        } catch (final KeyStoreException e) {
-            LOG.error("failed to add certificate", e);
-            return null;
-        }
-    }
-
-    public byte[] convertKeystoreToBytes(final KeyStore keyStore, final String keyStorePwd) {
-        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
-        try {
-            keyStore.store(byteArrayOutputStream, keyStorePwd.toCharArray());
-        } catch (final KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
-            LOG.error("Fatal error convert keystore to bytes", e);
-        }
-        return byteArrayOutputStream.toByteArray();
-    }
-
-    public KeyStore createKeyStoreWithSelfSignCert(final String keyStoreName, final String keyStorePwd, final String dName, final String keyAlias, final int validity) {
-        return createKeyStoreWithSelfSignCert(keyStoreName, keyStorePwd, dName, keyAlias, validity, KeyStoreConstant.DEFAULT_KEY_ALG,
-                KeyStoreConstant.DEFAULT_KEY_SIZE, KeyStoreConstant.DEFAULT_SIGN_ALG);
-    }
-
-    public KeyStore createKeyStoreWithSelfSignCert(final String keyStoreName, final String keyStorePwd, final String dName,
-            final String keyAlias, final int validity, final String keyAlg, final int keySize, final String signAlg) {
-        try {
-            final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyAlg);
-            keyPairGenerator.initialize(keySize);
-            final KeyPair keyPair = keyPairGenerator.generateKeyPair();
-            final X509V3CertificateGenerator x509V3CertGen = new X509V3CertificateGenerator();
-            x509V3CertGen.setSerialNumber(getSecureRandomeInt());
-            x509V3CertGen.setIssuerDN(new X509Principal(dName));
-            x509V3CertGen.setNotBefore(new Date(System.currentTimeMillis()));
-            x509V3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (KeyStoreConstant.DAY_TIME * validity)));
-            x509V3CertGen.setSubjectDN(new X509Principal(dName));
-            x509V3CertGen.setPublicKey(keyPair.getPublic());
-            x509V3CertGen.setSignatureAlgorithm(signAlg);
-            final X509Certificate x509Cert = x509V3CertGen.generateX509Certificate(keyPair.getPrivate());
-            final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
-            ctlKeyStore.load(null, keyStorePwd.toCharArray());
-            ctlKeyStore.setKeyEntry(keyAlias, keyPair.getPrivate(), keyStorePwd.toCharArray(),
-                       new java.security.cert.Certificate[]{x509Cert});
-            LOG.info("{} is created", keyStoreName);
-            return ctlKeyStore;
-        }
-        catch (final NoSuchAlgorithmException | InvalidKeyException | SecurityException | SignatureException | KeyStoreException | CertificateException | IOException e) {
-            LOG.error("Fatal error creating keystore", e);
-            return null;
-        }
-    }
-
-    public KeyStore createTrustKeyStoreImportCert(final String keyStorePwd, final List<Certificates> certificates) {
-        try {
-            final KeyStore trustKeyStore = KeyStore.getInstance("JKS");
-            trustKeyStore.load(null, keyStorePwd.toCharArray());
-            for (final Certificates certificate: certificates) {
-                final X509Certificate newCert = getCertificate(certificate.getX500Certificate());
-                if (newCert != null) {
-                    trustKeyStore.setCertificateEntry(certificate.getAlias(), newCert);
-                }
-            }
-            LOG.info("trust keystore is created");
-            return trustKeyStore;
-        } catch (final KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
-            LOG.error("Failed to create trust keystore", e);
-            return null;
-        }
-    }
-
-    public void exportKeystore(final KeyStore keystore, final String keystorePassword, final String fileName) {
-        try (final FileOutputStream fOutputStream = new FileOutputStream(workingDir + fileName)) {
-        keystore.store(fOutputStream, keystorePassword.toCharArray());
-        } catch (final KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
-            LOG.error("Fatal error export keystore", e);
-        }
-    }
-
-    public String generateCertificateReq(final KeyStore odlKeyStore, final String keyStorePwd, final String keyAlias, final String signAlg,
-            final boolean withTag) {
-        try {
-            if (odlKeyStore.containsAlias(keyAlias)) {
-                final X509Certificate odlCert = (X509Certificate)odlKeyStore.getCertificate(keyAlias);
-                final PublicKey pubKey = odlCert.getPublicKey();
-                final PrivateKey privKey = (PrivateKey)odlKeyStore.getKey(keyAlias, keyStorePwd.toCharArray());
-                final String subject = odlCert.getSubjectDN().getName();
-                final X509Name xname = new X509Name(subject);
-                final String signatureAlgorithm = signAlg;
-                final PKCS10CertificationRequest csr =
-                        new PKCS10CertificationRequest(signatureAlgorithm, xname, pubKey, null, privKey);
-                final String certReq = DatatypeConverter.printBase64Binary(csr.getEncoded());
-                if (withTag) {
-                    final StringBuilder sb = new StringBuilder();
-                    sb.append(KeyStoreConstant.BEGIN_CERTIFICATE_REQUEST);
-                    sb.append("\n");
-                    sb.append(certReq);
-                    sb.append("\n");
-                    sb.append(KeyStoreConstant.END_CERTIFICATE_REQUEST);
-                    return sb.toString();
-                }
-                return certReq;
-            }
-            LOG.info("KeyStore does not contain alias {}", keyAlias);
-            return null;
-        } catch (final NoSuchAlgorithmException | KeyStoreException |
-                 UnrecoverableKeyException | InvalidKeyException | NoSuchProviderException | SignatureException e) {
-            LOG.error("Failed to generate certificate request", e);
-            return null;
-        }
-}
-
-    public String getCertificate(final KeyStore keyStore, final String keyStorePwd, final String certAlias, final boolean withTag) {
-        try {
-            if (keyStore.containsAlias(certAlias)) {
-                final X509Certificate odlCert = (X509Certificate) keyStore.getCertificate(certAlias);
-                final String cert = DatatypeConverter.printBase64Binary(odlCert.getEncoded());
-                if (withTag) {
-                    final StringBuilder sb = new StringBuilder();
-                    sb.append(KeyStoreConstant.BEGIN_CERTIFICATE);
-                    sb.append("\n");
-                    sb.append(cert);
-                    sb.append("\n");
-                    sb.append(KeyStoreConstant.END_CERTIFICATE);
-                    return sb.toString();
-                }
-                return cert;
-            }
-            LOG.info("KeyStore does not contain alias {}", certAlias);
-            return null;
-        } catch (final CertificateException | KeyStoreException e) {
-            LOG.error("Failed to get Certificate", e);
-            return null;
-        }
-    }
-
-    private X509Certificate getCertificate(String certificate) {
-        if (certificate.isEmpty()) {
-            return null;
-        }
-
-        if (certificate.contains(KeyStoreConstant.BEGIN_CERTIFICATE)) {
-            final int fIdx = certificate.indexOf(KeyStoreConstant.BEGIN_CERTIFICATE) + KeyStoreConstant.BEGIN_CERTIFICATE.length();
-            final int sIdx = certificate.indexOf(KeyStoreConstant.END_CERTIFICATE);
-            certificate = certificate.substring(fIdx, sIdx);
-        }
-        final byte[] byteCert = Base64.decodeBase64(certificate);
-        final InputStream inputStreamCert = new ByteArrayInputStream(byteCert);
-        CertificateFactory certFactory;
-        try {
-            certFactory = CertificateFactory.getInstance("X.509");
-            final X509Certificate newCert = (X509Certificate) certFactory.generateCertificate(inputStreamCert);
-            newCert.checkValidity();
-            return newCert;
-        } catch (final CertificateException e) {
-            LOG.error("Failed to get certificate", e);
-            return null;
-        }
-    }
-
-    private BigInteger getSecureRandomeInt() {
-        final SecureRandom secureRandom = new SecureRandom();
-        final BigInteger bigInt = BigInteger.valueOf(secureRandom.nextInt());
-        return new BigInteger(1, bigInt.toByteArray());
-    }
-
-    public KeyStore loadKeyStore(final byte[] keyStoreBytes, final String keyStorePwd) {
-        try {
-            final KeyStore keyStore = KeyStore.getInstance("JKS");
-            keyStore.load(new ByteArrayInputStream(keyStoreBytes), keyStorePwd.toCharArray());
-            return keyStore;
-        } catch (final KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
-            LOG.error("Fatal error load keystore", e);
-            return null;
-        }
-    }
-}
index 33e4f7811c875c3909ecb86d741843f35920aa49..0b7d2bfd65b9302d40e218aa4d5f8a1fb7c656bd 100644 (file)
@@ -8,11 +8,9 @@
 
 package org.opendaylight.aaa.cert.utils;
 
-import java.util.ArrayList;
 import java.util.List;
-
 import org.opendaylight.aaa.cert.impl.KeyStoreConstant;
-import org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool;
+import org.opendaylight.aaa.cert.impl.ODLKeyTool;
 import org.opendaylight.aaa.encrypt.AAAEncryptionService;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
@@ -22,8 +20,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev1603
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.key.stores.SslData;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.key.stores.SslDataBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.key.stores.SslDataKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.keystore.Certificates;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.keystore.CertificatesBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.ssl.data.OdlKeystore;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.ssl.data.OdlKeystoreBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.ssl.data.TrustKeystore;
@@ -40,10 +36,11 @@ import org.slf4j.LoggerFactory;
  */
 public class KeyStoresDataUtils {
 
-    private final AAAEncryptionService encryService;
     private static final Logger LOG = LoggerFactory.getLogger(KeyStoresDataUtils.class);
     public static final String KEYSTORES_DATA_TREE = "KeyStores:1";
 
+    private final AAAEncryptionService encryService;
+
     public static InstanceIdentifier<KeyStores> getKeystoresIid() {
         return InstanceIdentifier.builder(KeyStores.class).build();
     }
@@ -89,14 +86,6 @@ public class KeyStoresDataUtils {
         }
     }
 
-    public Certificates createCertificates(final String alias, final String x509Cert) {
-        final Certificates cert = new CertificatesBuilder()
-                            .setAlias(alias)
-                            .setX500Certificate(x509Cert)
-                            .build();
-        return cert;
-    }
-
     public CipherSuites createCipherSuite(final String suiteName) {
         final CipherSuites cipherSuite = new CipherSuitesBuilder()
                                     .setSuiteName(suiteName)
@@ -110,22 +99,21 @@ public class KeyStoresDataUtils {
                                 .setAlias(alias)
                                 .setName(name)
                                 .setStorePassword(password)
-                                .setCertificates(new ArrayList<>())
                                 .build();
         return odlKeystore;
         }
 
     public OdlKeystore createOdlKeystore(final String name, final String alias, final String password, final String dname,
-                                                final ODLMdsalKeyTool odlKeyTool) {
+                                                final ODLKeyTool odlKeyTool) {
         return createOdlKeystore(name, alias, password, dname, KeyStoreConstant.DEFAULT_SIGN_ALG, KeyStoreConstant.DEFAULT_KEY_ALG,
                 KeyStoreConstant.DEFAULT_VALIDITY, KeyStoreConstant.DEFAULT_KEY_SIZE, odlKeyTool);
     }
 
     public OdlKeystore createOdlKeystore(final String name, final String alias, final String password, final String dname,
-                        final String sigAlg, final String keyAlg, final int validity, final int keySize, final ODLMdsalKeyTool odlKeyTool) {
+                        final String sigAlg, final String keyAlg, final int validity, final int keySize, final ODLKeyTool odlKeyTool) {
         final byte[] keyStoreBytes = odlKeyTool.convertKeystoreToBytes(odlKeyTool.createKeyStoreWithSelfSignCert(name, password,
                 dname, alias, validity, keyAlg, keySize, sigAlg), password);
-        LOG.info("Odl keystore string {} ", keyStoreBytes);
+        LOG.debug("Odl keystore string {} ", keyStoreBytes);
         final OdlKeystore odlKeystore = new OdlKeystoreBuilder()
                                     .setKeystoreFile(keyStoreBytes)
                                     .setAlias(alias)
@@ -136,14 +124,12 @@ public class KeyStoresDataUtils {
                                     .setSignAlg(sigAlg)
                                     .setStorePassword(password)
                                     .setValidity(validity)
-                                    .setCertificates(new ArrayList<>())
                                     .build();
         return odlKeystore;
     }
 
     public TrustKeystore createTrustKeystore(final String name, final String password, final byte[] keyStoreBytes) {
         final TrustKeystore trustKeystore = new TrustKeystoreBuilder()
-                                        .setCertificates(new ArrayList<>())
                                         .setKeystoreFile(keyStoreBytes)
                                         .setName(name)
                                         .setStorePassword(password)
@@ -151,11 +137,10 @@ public class KeyStoresDataUtils {
         return trustKeystore;
     }
 
-    public TrustKeystore createTrustKeystore(final String name, final String password, final List<Certificates> certificates, final ODLMdsalKeyTool odlKeyTool) {
-        final byte[] keyStoreBytes = odlKeyTool.convertKeystoreToBytes(odlKeyTool.createTrustKeyStoreImportCert(password, certificates), password);
-        LOG.info("trust keystore string {} ", keyStoreBytes);
+    public TrustKeystore createTrustKeystore(final String name, final String password, final ODLKeyTool odlKeyTool) {
+        final byte[] keyStoreBytes = odlKeyTool.convertKeystoreToBytes(odlKeyTool.createEmptyKeyStore(password), password);
+        LOG.debug("trust keystore string {} ", keyStoreBytes);
         final TrustKeystore trustKeystore = new TrustKeystoreBuilder()
-                                        .setCertificates(certificates)
                                         .setKeystoreFile(keyStoreBytes)
                                         .setName(name)
                                         .setStorePassword(password)
@@ -164,6 +149,9 @@ public class KeyStoresDataUtils {
     }
 
     private OdlKeystore decryptOdlKeyStore(final OdlKeystore odlKeystore) {
+        if (odlKeystore == null) {
+            return null;
+        }
         final OdlKeystoreBuilder odlKeystoreBuilder = new OdlKeystoreBuilder(odlKeystore);
         odlKeystoreBuilder.setKeystoreFile(encryService.decrypt(odlKeystore.getKeystoreFile()));
         odlKeystoreBuilder.setStorePassword(encryService.decrypt(odlKeystore.getStorePassword()));
@@ -171,6 +159,9 @@ public class KeyStoresDataUtils {
     }
 
     private SslData decryptSslData(final SslData sslData) {
+        if (sslData == null) {
+            return null;
+        }
         final SslDataBuilder sslDataBuilder = new SslDataBuilder(sslData)
                 .setOdlKeystore(decryptOdlKeyStore(sslData.getOdlKeystore()))
                 .setTrustKeystore(decryptTrustKeystore(sslData.getTrustKeystore()));
@@ -178,6 +169,9 @@ public class KeyStoresDataUtils {
     }
 
     private TrustKeystore decryptTrustKeystore(final TrustKeystore trustKeyStore) {
+        if (trustKeyStore == null) {
+            return null;
+        }
         final TrustKeystoreBuilder trustKeyStoreBuilder = new TrustKeystoreBuilder(trustKeyStore);
         trustKeyStoreBuilder.setKeystoreFile(encryService.decrypt(trustKeyStore.getKeystoreFile()));
         trustKeyStoreBuilder.setStorePassword(encryService.decrypt(trustKeyStore.getStorePassword()));
@@ -223,22 +217,19 @@ public class KeyStoresDataUtils {
     public boolean updateSslDataCipherSuites(final DataBroker dataBroker, final SslData baseSslData, final List<CipherSuites> cipherSuites) {
         final SslDataBuilder sslDataBuilder = new SslDataBuilder(baseSslData)
                                         .setCipherSuites(cipherSuites);
-        return MdsalUtils.merge(dataBroker, LogicalDatastoreType.CONFIGURATION, getSslDataIid(baseSslData.getBundleName()),
-                sslDataBuilder.build());
+        return updateSslData(dataBroker, sslDataBuilder.build());
     }
 
     public boolean updateSslDataOdlKeystore(final DataBroker dataBroker, final SslData baseSslData, final OdlKeystore odlKeyStore) {
         final SslDataBuilder sslDataBuilder = new SslDataBuilder(baseSslData)
-                                        .setOdlKeystore(encryptOdlKeyStore(odlKeyStore));
-        return MdsalUtils.merge(dataBroker, LogicalDatastoreType.CONFIGURATION, getSslDataIid(baseSslData.getBundleName()),
-                sslDataBuilder.build());
+                                        .setOdlKeystore(odlKeyStore);
+        return updateSslData(dataBroker, sslDataBuilder.build());
     }
 
     public boolean updateSslDataTrustKeystore(final DataBroker dataBroker, final SslData baseSslData, final TrustKeystore trustKeyStore) {
         final SslDataBuilder sslDataBuilder = new SslDataBuilder(baseSslData)
-                                        .setTrustKeystore(encryptTrustKeystore(trustKeyStore));
-        return MdsalUtils.merge(dataBroker, LogicalDatastoreType.CONFIGURATION, getSslDataIid(baseSslData.getBundleName()),
-                sslDataBuilder.build());
+                                        .setTrustKeystore(trustKeyStore);
+        return updateSslData(dataBroker, sslDataBuilder.build());
     }
 
     public TrustKeystore updateTrustKeystore(final TrustKeystore baseTrustKeyStore, final byte[] keyStoreBytes) {
index 6879dfa3192789faf39ef27decf7478be9aeb9f6..fd441fad551fdab45755f05065f557a1d69be1f1 100644 (file)
@@ -1,19 +1,22 @@
 <aaa-cert-service-config xmlns="urn:opendaylight:yang:aaa:cert">
-  <useConfig>false</useConfig>
+  <use-config>false</use-config>
+  <use-mdsal>false</use-mdsal>
+  <bundle-name>opendaylight</bundle-name>
   <ctlKeystore>
     <name>ctl.jks</name>
     <alias>controller</alias>
-    <storePassword>storePassword</storePassword>
+    <store-password>storePassword</store-password>
     <dname>CN=ODL, OU=Dev, O=LinuxFoundation, L=QC Montreal, C=CA</dname>
     <validity>365</validity>
+    <key-alg>RSA</key-alg>
+    <sign-alg>SHA1WithRSAEncryption</sign-alg>
+    <keysize>1024</keysize>
     <cipher-suites>
-      <suiteName />
+      <suite-name />
     </cipher-suites>
   </ctlKeystore>
   <trustKeystore>
     <name>truststore.jks</name>
-    <alias>controller</alias>
-    <storePassword>storePassword</storePassword>
-    <certFile>cacert.pem</certFile>
+    <store-password>storePassword</store-password>
   </trustKeystore>
 </aaa-cert-service-config>
\ No newline at end of file
index 0c15236131064c7ba0687bd19577cc37e89325c2..71af6d731fd684b07bd66197df829e37de516264 100644 (file)
@@ -3,31 +3,27 @@
                  xmlns:odl="http://opendaylight.org/xmlns/blueprint/v1.0.0">
 
   <odl:clustered-app-config id="aaaCertDefaultConfig" default-config-file-name="aaa-cert-config.xml"
-                            binding-class="org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rev151126.AaaCertServiceConfig"
-                            list-key-value="aaa-cert-provider">
+                            binding-class="org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rev151126.AaaCertServiceConfig">
   </odl:clustered-app-config>
 
-  <bean id="aaaCert" class="org.opendaylight.aaa.cert.impl.AaaCertProvider">
-      <argument ref="aaaCertDefaultConfig"/>
-  </bean>
+  <reference id="dataBroker" interface="org.opendaylight.controller.md.sal.binding.api.DataBroker" odl:type="default"/>
 
-  <service ref="aaaCert" interface="org.opendaylight.aaa.cert.api.IAaaCertProvider"/>
+  <reference id="encryService" interface="org.opendaylight.aaa.encrypt.AAAEncryptionService"/>
 
-  <bean id="aaaCertRpcService" class="org.opendaylight.aaa.cert.impl.AaaCertRpcServiceImpl">
-      <argument ref="aaaCert"/>
+  <bean id="certManager" class="org.opendaylight.aaa.cert.impl.CertificateManagerService">
+      <argument ref="aaaCertDefaultConfig"/>
+      <argument ref="dataBroker"/>
+      <argument ref="encryService"/>
   </bean>
 
-  <odl:rpc-implementation ref="aaaCertRpcService"/>
-
-  <reference id="dataBroker" interface="org.opendaylight.controller.md.sal.binding.api.DataBroker"/>
-
-  <reference id="encryService" interface="org.opendaylight.aaa.encrypt.AAAEncryptionService"/>
+  <service ref="certManager" interface="org.opendaylight.aaa.cert.api.ICertificateManager" odl:type="default-certificate-manager"/>
 
-  <bean id="aaaCertMdsal" class="org.opendaylight.aaa.cert.impl.AaaCertMdsalProvider">
+  <bean id="aaaCertRpcService" class="org.opendaylight.aaa.cert.impl.AaaCertRpcServiceImpl">
+      <argument ref="aaaCertDefaultConfig"/>
       <argument ref="dataBroker"/>
       <argument ref="encryService"/>
   </bean>
 
-  <service ref="aaaCertMdsal" interface="org.opendaylight.aaa.cert.api.IAaaCertMdsalProvider"/>
+  <odl:rpc-implementation ref="aaaCertRpcService" />
 
 </blueprint>
\ No newline at end of file
index 1da9a389a00e72d2724dbea26bda85999b64ab81..9101dbc6594c5d9a2f308eeb7e075518c15efdf0 100644 (file)
@@ -85,10 +85,6 @@ module aaa-cert-mdsal {
             description "keystore file as Binary";
             type binary;
         }
-        list certificates {
-            description "list of certificates that exist in the keystore";
-            uses node-certificate;
-        }
     }
 
     grouping cipher-suite {
index 0121afb405e3be9b7557b8ff95c8c436432a8e5f..fe3d21ce0574fa673b7e3c159cd98586c5c024bf 100644 (file)
@@ -24,12 +24,7 @@ module aaa-cert-rpc {
 
     rpc getODLCertificate {
         description
-            "Get the ctl.jks keystore certificate";
-        input {
-            leaf cert-alias {
-                type string;
-            }
-         }
+            "Get the ODL keystore certificate";
         output {
            leaf odl-cert {
                type string;
@@ -39,12 +34,7 @@ module aaa-cert-rpc {
 
     rpc getODLCertificateReq {
         description
-            "Generate a certificate request from the ctl.jks keystore to be signed by a CA";
-        input {
-            leaf cert-req-alias {
-                type string;
-            }
-         }
+            "Generate a certificate request from the ODL keystore to be signed by a CA";
         output {
            leaf odl-cert-req {
                type string;
index e94fb2ef481f1fb8165d5befc3278a3a12d44feb..6e689b842531df4585675559f0f4cd20f38ec83a 100644 (file)
@@ -23,11 +23,20 @@ module aaa-cert {
     }
 
     container aaa-cert-service-config {
-        leaf useConfig {
+        leaf use-config {
             description "Use the configuration data to create the keystores";
             type boolean;
             default false;
         }
+        leaf use-mdsal {
+            description "Use Mdsal as Data store for the keystore and certificates";
+            type boolean;
+            default false;
+        }
+        leaf bundle-name {
+            description "bundle name of the default TLS config in MdsaL";
+            type string;
+        }
         container ctlKeystore {
             leaf name {
                 description "keystore name default is ctl";
@@ -37,7 +46,7 @@ module aaa-cert {
                 description "key alias";
                 type string;
             }
-            leaf storePassword {
+            leaf store-password {
                 description "keystore password";
                 type string;
             }
@@ -55,8 +64,20 @@ module aaa-cert {
                 description "validity";
                 type int32;
             }
+            leaf key-alg {
+                description "The supported key generation algorithms i.e: DSA or RSA";
+                type string;
+            }
+            leaf sign-alg {
+                description "The supported sign algorithmes i.e: SHA1withDSA or SHA1withRSA";
+                type string;
+            }
+            leaf keysize {
+                description "the key size i.e: 1024";
+                type int32;
+            }
             list cipher-suites {
-                 leaf suiteName {
+                 leaf suite-name {
                      type string;
                  }
             }
@@ -66,18 +87,10 @@ module aaa-cert {
                 description "keystore name default is truststore";
                 type string;
             }
-            leaf alias {
-                description "key alias";
-                type string;
-            }
-            leaf storePassword {
+            leaf store-password {
                 description "keystore password";
                 type string;
             }
-            leaf certFile {
-                description "path to CA certificate pem file";
-                type string;
-            }
         }
     }
 }
diff --git a/aaa-cli/src/main/java/org/opendaylight/aaa/cli/AddCertODLKeyStore.java b/aaa-cli/src/main/java/org/opendaylight/aaa/cli/AddCertODLKeyStore.java
deleted file mode 100644 (file)
index 189439d..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (c) 2016 Inocybe Technologies. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.aaa.cli;
-
-import java.io.FileInputStream;
-import java.nio.charset.StandardCharsets;
-
-import org.apache.karaf.shell.commands.Command;
-import org.apache.karaf.shell.commands.Option;
-import org.apache.karaf.shell.console.OsgiCommandSupport;
-import org.opendaylight.aaa.cert.api.IAaaCertProvider;
-
-@Command(name = "add-odl-cert", scope = "aaa", description = "Add ODL signed certificaet to ODL key store.")
-
-/**
- *
- * @author mserngawy
- * AddCertODLKeyStore adding certificate to the ODL keyStore
- */
-public class AddCertODLKeyStore extends OsgiCommandSupport {
-
-    protected IAaaCertProvider certProvider;
-
-    @Option(name = "-cert",
-            aliases = { "--CertFile" },
-            description = "The ODL certificate file.\n-file / --should be accesable by the karaf command line",
-            required = true,
-            multiValued = false)
-    private String certFile = "";
-
-    @Option(name = "-storepass",
-            aliases = { "--KeyStorePass" },
-            description = "The ODL keystore password.\n-storepass",
-            required = true,
-            multiValued = false)
-    private String keyStorePassword = "";
-
-    @Option(name = "-alias",
-            aliases = { "--alias" },
-            description = "The alias.\n-alias / ODL alias default is controller as the configuration",
-            required = false,
-            multiValued = false)
-    private String alias = "controller";
-
-    public AddCertODLKeyStore(final IAaaCertProvider aaaCertProvider) {
-        this.certProvider = aaaCertProvider;
-    }
-
-    @Override
-    protected Object doExecute() throws Exception {
-        final FileInputStream fInputStream = new FileInputStream(certFile);
-        final byte[] certBytes = new byte[fInputStream.available()];
-        fInputStream.read(certBytes);
-        fInputStream.close();
-        final String certificate = new String(certBytes, StandardCharsets.UTF_8);
-        if (certProvider.addCertificateODLKeyStore(keyStorePassword, alias, certificate)) {
-            return alias + " certificate successfully added to ODL keystore";
-        } else {
-            return "Failed to add " + alias + " certificate to ODL keystore";
-        }
-    }
-
-}
diff --git a/aaa-cli/src/main/java/org/opendaylight/aaa/cli/AddCertTrustStore.java b/aaa-cli/src/main/java/org/opendaylight/aaa/cli/AddCertTrustStore.java
deleted file mode 100644 (file)
index a4056b6..0000000
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (c) 2016 Inocybe Technologies. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.aaa.cli;
-
-import java.io.FileInputStream;
-import java.nio.charset.StandardCharsets;
-
-import org.apache.karaf.shell.commands.Command;
-import org.apache.karaf.shell.commands.Option;
-import org.apache.karaf.shell.console.OsgiCommandSupport;
-import org.opendaylight.aaa.cert.api.IAaaCertProvider;
-
-@Command(name = "add-trust-cert", scope = "aaa", description = "Add node certificaet to trust key store.")
-
-/**
-*
-* @author mserngawy
-* AddCertTrustStore adding certificate to the ODL keyStore
-*/
-public class AddCertTrustStore extends OsgiCommandSupport {
-
-    protected IAaaCertProvider certProvider;
-
-    @Option(name = "-cert",
-            aliases = { "--CertFile" },
-            description = "The node certificate file.\n-file / --should be accesable by the karaf command line",
-            required = true,
-            multiValued = false)
-    private String certFile = "";
-
-    @Option(name = "-storepass",
-            aliases = { "--KeyStorePass" },
-            description = "The Trust keystore password.\n-storepass",
-            required = true,
-            multiValued = false)
-    private String keyStorePassword = "";
-
-    @Option(name = "-alias",
-            aliases = { "--alias" },
-            description = "The alias.\n-alias / node alias should be unique",
-            required = true,
-            multiValued = false)
-    private String alias = "";
-
-    public AddCertTrustStore(final IAaaCertProvider aaaCertProvider) {
-        this.certProvider = aaaCertProvider;
-    }
-
-    @Override
-    protected Object doExecute() throws Exception {
-        final FileInputStream fInputStream = new FileInputStream(certFile);
-        final byte[] certBytes = new byte[fInputStream.available()];
-        fInputStream.read(certBytes);
-        fInputStream.close();
-        final String certificate = new String(certBytes, StandardCharsets.UTF_8);
-        if (certProvider.addCertificateTrustStore(keyStorePassword, alias, certificate)) {
-            return alias + " certificate successfully added to trust keystore";
-        } else {
-            return "Failed to add " + alias + " certificate to trust keystore";
-        }
-    }
-}
diff --git a/aaa-cli/src/main/java/org/opendaylight/aaa/cli/CreateODLKeyStore.java b/aaa-cli/src/main/java/org/opendaylight/aaa/cli/CreateODLKeyStore.java
deleted file mode 100644 (file)
index fb3e5f0..0000000
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (c) 2016 Inocybe Technologies. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.aaa.cli;
-
-import org.apache.karaf.shell.commands.Command;
-import org.apache.karaf.shell.commands.Option;
-import org.apache.karaf.shell.console.OsgiCommandSupport;
-import org.opendaylight.aaa.cert.api.IAaaCertProvider;
-
-@Command(name = "gen-odl-ks", scope = "aaa", description = "Create the default keystore for the opendaylight controller.")
-
-/**
- *
- * @author mserngawy
- * CreateODLKeyStore create the ODL keystore with new configuration.
- */
-public class CreateODLKeyStore extends OsgiCommandSupport{
-
-    protected IAaaCertProvider certProvider;
-
-    @Option(name = "-keystore",
-            aliases = { "--KeyStore" },
-            description = "The keystore name.\n-keystore / --default is ctl.jks",
-            required = false,
-            multiValued = false)
-    private String keyStoreName = "ctl.jks";
-
-    @Option(name = "-storepass",
-            aliases = { "--KeyStorePass" },
-            description = "The keystore password.\n-storepass",
-            required = true,
-            multiValued = false)
-    private String keyStorePassword = "";
-
-    @Option(name = "-alias",
-            aliases = { "--alias" },
-            description = "The alias.\n-alias / --default is controller",
-            required = false,
-            multiValued = false)
-    private String alias = "controller";
-
-    @Option(name = "-validity",
-            aliases = { "--validity" },
-            description = "The validity.\n-validity of the keystore certificate / --default is 365",
-            required = false,
-            multiValued = false)
-    private int validity = 365;
-
-    @Option(name = "-dName",
-            aliases = { "--dName" },
-            description = "The dName.\n-dName / --should be in the following formate CN=, OU=, O=, L= C=",
-            required = false,
-            multiValued = false)
-    private String dName = "CN=ODL, OU=Dev, O=LinuxFoundation, L=QC. Montreal, C=CA";
-
-    public CreateODLKeyStore(final IAaaCertProvider aaaCertProvider) {
-        this.certProvider = aaaCertProvider;
-    }
-
-    @Override
-    protected Object doExecute() throws Exception {
-        final StringBuilder sb = new StringBuilder();
-        sb.append(certProvider.createODLKeyStore(keyStoreName, keyStorePassword, alias, dName, validity));
-        sb.append("\n");
-        sb.append("08-aaa-cert-config.xml file should be updated with new keystore info");
-        return sb.toString();
-    }
-}
\ No newline at end of file
diff --git a/aaa-cli/src/main/java/org/opendaylight/aaa/cli/CreateTrustKeyStore.java b/aaa-cli/src/main/java/org/opendaylight/aaa/cli/CreateTrustKeyStore.java
deleted file mode 100644 (file)
index 1abe662..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (c) 2016 Inocybe Technologies. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.aaa.cli;
-
-import org.apache.karaf.shell.commands.Command;
-import org.apache.karaf.shell.commands.Option;
-import org.apache.karaf.shell.console.OsgiCommandSupport;
-import org.opendaylight.aaa.cert.api.IAaaCertProvider;
-
-@Command(name = "gen-trust-ks", scope = "aaa", description = "Create the trust keystore for the opendaylight controller.")
-
-/**
- *
- * @author mserngawy
- * CreateTrustKeyStore create trust key store with new configuration
- */
-public class CreateTrustKeyStore extends OsgiCommandSupport{
-
-    protected IAaaCertProvider certProvider;
-
-    @Option(name = "-keystore",
-            aliases = { "--KeyStore" },
-            description = "The keystore name.\n-keystore / --default is truststore.jks",
-            required = false,
-            multiValued = false)
-    private String keyStoreName = "truststore.jks";
-
-    @Option(name = "-storepass",
-            aliases = { "--KeyStorePass" },
-            description = "The keystore password.\n-storepass",
-            required = true,
-            multiValued = false)
-    private String keyStorePassword = "";
-
-    @Option(name = "-alias",
-            aliases = { "--alias" },
-            description = "The alias.\n-alias / --default is node",
-            required = false,
-            multiValued = false)
-    private String alias = "node";
-
-    public CreateTrustKeyStore(final IAaaCertProvider aaaCertProvider) {
-        this.certProvider = aaaCertProvider;
-    }
-
-    @Override
-    protected Object doExecute() throws Exception {
-        final StringBuilder sb = new StringBuilder();
-        sb.append(certProvider.createTrustKeyStore(keyStoreName, keyStorePassword, alias));
-        sb.append("\n");
-        sb.append("08-aaa-cert-config.xml file should be updated with new keystore info");
-        return sb.toString();
-    }
-
-}
index c84300f76e6a3d9aceb6e83c6003b997afdcf721..dfe6f4778ecddf0ba327ccc3d904f806034e6688 100644 (file)
@@ -11,21 +11,19 @@ package org.opendaylight.aaa.cli;
 import org.apache.karaf.shell.commands.Command;
 import org.apache.karaf.shell.commands.Option;
 import org.apache.karaf.shell.console.OsgiCommandSupport;
-import org.opendaylight.aaa.cert.api.IAaaCertProvider;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.opendaylight.aaa.cert.api.ICertificateManager;
 
 @Command(name = "gen-cert-req", scope = "aaa", description = "generate a certificate request for the opendaylight controller.")
 
 /**
+ * GenerateCertReq from the ODL key store to be signed by the Certificate Authority 'CA'
  *
  * @author mserngawy
- * GenerateCertReq from the ODL key store to be signed by the Certificate Authority 'CA'
+ *
  */
 public class GenerateCertReq extends OsgiCommandSupport{
 
-    private static final Logger LOG = LoggerFactory.getLogger(GenerateCertReq.class);
-    protected IAaaCertProvider certProvider;
+    protected ICertificateManager certProvider;
 
     @Option(name = "-storepass",
             aliases = { "--KeyStorePass" },
@@ -34,20 +32,13 @@ public class GenerateCertReq extends OsgiCommandSupport{
             multiValued = false)
     private String keyStorePassword = "";
 
-    @Option(name = "-alias",
-            aliases = { "--alias" },
-            description = "The alias.\n-alias / --default is controller",
-            required = false,
-            multiValued = false)
-    private String alias = "controller";
-
-    public GenerateCertReq(final IAaaCertProvider aaaCertProvider) {
+    public GenerateCertReq(final ICertificateManager aaaCertProvider) {
         this.certProvider = aaaCertProvider;
     }
 
     @Override
     protected Object doExecute() throws Exception {
-        return certProvider.genODLKeyStoreCertificateReq(keyStorePassword, alias, true);
+        return certProvider.genODLKeyStoreCertificateReq(keyStorePassword, true);
     }
 
 }
index a1f490189dbc6a335c8cf95d21051f5a434c4f40..c4a4ba3f43af05ea3e135c0a08b74530bb1028ec 100644 (file)
@@ -11,18 +11,19 @@ package org.opendaylight.aaa.cli;
 import org.apache.karaf.shell.commands.Command;
 import org.apache.karaf.shell.commands.Option;
 import org.apache.karaf.shell.console.OsgiCommandSupport;
-import org.opendaylight.aaa.cert.api.IAaaCertProvider;
+import org.opendaylight.aaa.cert.api.ICertificateManager;
 
 @Command(name = "get-odl-cert", scope = "aaa", description = "get self sign certificate for the opendaylight controller.")
 
 /**
+ * GetODLSelfSignCert get the ODL key store self sign certificate.
  *
  * @author mserngawy
- * GetODLSelfSignCert get the ODL key store self sign certificate.
+ *
  */
 public class GetODLSelfSignCert extends OsgiCommandSupport{
 
-    protected IAaaCertProvider certProvider;
+    protected ICertificateManager certProvider;
 
     @Option(name = "-storepass",
             aliases = { "--KeyStorePass" },
@@ -38,13 +39,13 @@ public class GetODLSelfSignCert extends OsgiCommandSupport{
             multiValued = false)
     private String alias = "controller";
 
-    public GetODLSelfSignCert(final IAaaCertProvider aaaCertProvider) {
+    public GetODLSelfSignCert(final ICertificateManager aaaCertProvider) {
         this.certProvider = aaaCertProvider;
     }
 
     @Override
     protected Object doExecute() throws Exception {
-        return certProvider.getODLKeyStoreCertificate(keyStorePassword, alias, true);
+        return certProvider.getODLKeyStoreCertificate(keyStorePassword, true);
     }
 
 }
index 7f6f6a4f98fa55adc51b93cccc80d8b790f7ac3e..fbf70dc1b2c1ed6cc350b55d5f6df0db944fe69b 100644 (file)
@@ -11,21 +11,19 @@ package org.opendaylight.aaa.cli;
 import org.apache.karaf.shell.commands.Command;
 import org.apache.karaf.shell.commands.Option;
 import org.apache.karaf.shell.console.OsgiCommandSupport;
-import org.opendaylight.aaa.cert.api.IAaaCertProvider;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import org.opendaylight.aaa.cert.api.ICertificateManager;
 
 @Command(name = "get-node-cert", scope = "aaa", description = "get node certificate form the opendaylight trust keystore .")
 
 /**
+ * GetTrustStoreCert get a certain certificate stored in the trust key store using the its alias
  *
  * @author mserngawy
- * GetTrustStoreCert get a certain certificate stored in the trust key store using the its alias
+ *
  */
 public class GetTrustStoreCert  extends OsgiCommandSupport{
 
-    private static final Logger LOG = LoggerFactory.getLogger(GetTrustStoreCert.class);
-    protected IAaaCertProvider certProvider;
+    protected ICertificateManager certProvider;
 
     @Option(name = "-storepass",
             aliases = { "--KeyStorePass" },
@@ -41,7 +39,7 @@ public class GetTrustStoreCert  extends OsgiCommandSupport{
             multiValued = false)
     private String alias = "";
 
-    public GetTrustStoreCert(final IAaaCertProvider aaaCertProvider) {
+    public GetTrustStoreCert(final ICertificateManager aaaCertProvider) {
         this.certProvider = aaaCertProvider;
     }
 
index 5185343c488602fd99e43dd4a8fe99e709358043..e4d49cf9c5609dfede24d101e35cdc07cf6b9aaf 100644 (file)
@@ -1,15 +1,10 @@
 <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
 
     <reference id="KeyStoreConsoleProvider" availability="mandatory"
-        activation="eager" interface="org.opendaylight.aaa.cert.api.IAaaCertProvider">
+        activation="eager" interface="org.opendaylight.aaa.cert.api.ICertificateManager">
     </reference>
 
     <command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.1.0">
-        <command>
-            <action class="org.opendaylight.aaa.cli.CreateODLKeyStore">
-                <argument ref="KeyStoreConsoleProvider" />
-            </action>
-        </command>
         <command>
             <action class="org.opendaylight.aaa.cli.GetODLSelfSignCert">
                 <argument ref="KeyStoreConsoleProvider" />
                 <argument ref="KeyStoreConsoleProvider" />
             </action>
         </command>
-        <command>
-            <action class="org.opendaylight.aaa.cli.CreateTrustKeyStore">
-                <argument ref="KeyStoreConsoleProvider" />
-            </action>
-        </command>
         <command>
             <action class="org.opendaylight.aaa.cli.GetTrustStoreCert">
                 <argument ref="KeyStoreConsoleProvider" />
             </action>
         </command>
-        <command>
-            <action class="org.opendaylight.aaa.cli.AddCertTrustStore">
-                <argument ref="KeyStoreConsoleProvider" />
-            </action>
-        </command>
-        <command>
-            <action class="org.opendaylight.aaa.cli.AddCertODLKeyStore">
-                <argument ref="KeyStoreConsoleProvider" />
-            </action>
-        </command>
     </command-bundle>
 
 </blueprint>
\ No newline at end of file
index b190e509b31b42ae5cfb631451b2f37a5d363c79..9b37ebe743c7890440f2919041dcafc64f4a0bb4 100644 (file)
@@ -166,4 +166,4 @@ public class AAAEncryptionServiceImpl implements AAAEncryptionService {
         return salt;
     }
 
-}
+}
\ No newline at end of file