Store the opendaylight's certificate and network Node's certificates to mdsal 14/36514/17
authorMohamed El-Serngawy <melserngawy@inocybe.com>
Mon, 21 Mar 2016 20:48:23 +0000 (16:48 -0400)
committerMohamed El-Serngawy <melserngawy@inocybe.ca>
Thu, 4 Aug 2016 12:27:30 +0000 (12:27 +0000)
Opendaylight uses java keystore to store certificates. The keystore is used to establish a secure
SSL communication between Opendaylight and different protocols such as openflow and netconf. aaa-cert provides Opendaylight with
the ability to create different keytstores for each protocol and store these keystores into mdsal. As mdsal has its shard
data process across Opendaylight cluster nodes, the keystores will be syncronized across the cluster nodes.

Change-Id: I29ea84e4f2be9d66f7da74727baaf9ba343d1f9f
Signed-off-by: Mohamed El-Serngawy <melserngawy@inocybe.com>
26 files changed:
aaa-cert/pom.xml
aaa-cert/src/main/java/org/opendaylight/aaa/cert/api/IAaaCertMdsalProvider.java [new file with mode: 0644]
aaa-cert/src/main/java/org/opendaylight/aaa/cert/api/IAaaCertProvider.java
aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/AaaCertMdsalProvider.java [new file with mode: 0644]
aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/AaaCertProvider.java
aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/ConnectionConfigurationImpl.java [deleted file]
aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/KeyStoreConstant.java [moved from aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/KeyStoreUtilis.java with 75% similarity]
aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/ODLKeyTool.java
aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/ODLMdsalKeyTool.java [new file with mode: 0644]
aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/TlsConfigurationImp.java [deleted file]
aaa-cert/src/main/java/org/opendaylight/aaa/cert/utils/KeyStoresDataUtils.java [new file with mode: 0644]
aaa-cert/src/main/java/org/opendaylight/aaa/cert/utils/MdsalUtils.java [new file with mode: 0644]
aaa-cert/src/main/java/org/opendaylight/yang/gen/v1/urn/opendaylight/yang/aaa/cert/mdsal/rev160321/AaaCertMdsalProviderModule.java [new file with mode: 0644]
aaa-cert/src/main/java/org/opendaylight/yang/gen/v1/urn/opendaylight/yang/aaa/cert/mdsal/rev160321/AaaCertMdsalProviderModuleFactory.java [new file with mode: 0644]
aaa-cert/src/main/java/org/opendaylight/yang/gen/v1/urn/opendaylight/yang/aaa/cert/rev151126/AaaCertProviderModule.java
aaa-cert/src/main/resources/initial/08-aaa-cert-config.xml
aaa-cert/src/main/test/org/opendaylight/aaa/cert/test/AaaCertProviderTest.java
aaa-cert/src/main/test/org/opendaylight/aaa/cert/test/KeyStoreUtilisTest.java
aaa-cert/src/main/test/org/opendaylight/aaa/cert/test/ODLKeyToolTest.java
aaa-cert/src/main/yang/aaa-cert-mdsal.yang [new file with mode: 0644]
aaa-cert/src/main/yang/aaa-cert-rpc.yang
aaa-cert/src/main/yang/aaa-cert.yang
aaa-encrypt-service/src/main/java/org/opendaylight/aaa/encrypt/AAAEncryptionService.java
aaa-encrypt-service/src/main/java/org/opendaylight/aaa/encrypt/AAAEncryptionServiceImpl.java
features/aaa-cert/pom.xml
features/aaa-cert/src/main/features/features.xml

index 599cdff3343a844c2f3d9be51da346d778fee133..bf65c7cbc7de96baa6d44874c3bbcab0dd4bcd9e 100755 (executable)
@@ -18,17 +18,15 @@ and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL
   <artifactId>aaa-cert</artifactId>
   <packaging>bundle</packaging>
 
-  <properties>
-    <openflowplugin.version>0.3.0-SNAPSHOT</openflowplugin.version>
-    <openflow.protocol.spi.version>0.8.0-SNAPSHOT</openflow.protocol.spi.version>
-  </properties>
-
-
   <dependencies>
     <dependency>
       <groupId>org.opendaylight.controller</groupId>
       <artifactId>sal-binding-config</artifactId>
     </dependency>
+    <dependency>
+      <groupId>org.opendaylight.aaa</groupId>
+      <artifactId>aaa-encrypt-service</artifactId>
+    </dependency>
 
     <!-- Bouncy Castle dependency -->
     <dependency>
@@ -40,21 +38,6 @@ and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL
         <artifactId>commons-codec</artifactId>
     </dependency>
 
-    <!-- openflow dependency -->
-    <dependency>
-      <groupId>org.opendaylight.openflowplugin</groupId>
-      <artifactId>features-openflowplugin</artifactId>
-      <classifier>features</classifier>
-      <version>${openflowplugin.version}</version>
-      <type>xml</type>
-      <scope>runtime</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.openflowjava</groupId>
-      <artifactId>openflow-protocol-spi</artifactId>
-      <version>${openflow.protocol.spi.version}</version>
-    </dependency>
-
     <!-- Testing Dependencies -->
     <dependency>
       <groupId>junit</groupId>
diff --git a/aaa-cert/src/main/java/org/opendaylight/aaa/cert/api/IAaaCertMdsalProvider.java b/aaa-cert/src/main/java/org/opendaylight/aaa/cert/api/IAaaCertMdsalProvider.java
new file mode 100644 (file)
index 0000000..01b691c
--- /dev/null
@@ -0,0 +1,197 @@
+/*
+ * 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 org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.key.stores.SslData;
+
+/**
+ * IAaaCertMdsalProvider define the basic API required by AaaCertMdsalProvider
+ *
+ * @author mserngawy
+ *
+ */
+public interface IAaaCertMdsalProvider {
+
+    /**
+     * Add SslData object to Mdsal with default values of keyAlg=RSA, keySize=2048, validity=356
+     * and signAlg=SHA1WithRSAEncryption
+     *
+     * @param bundleName name of the bundle that will use the keystores
+     * @param odlKeystoreName odl Keystore Name
+     * @param odlKeystorePwd odl Keystore Password
+     * @param odlKeystoreAlias odl Keystore Alias
+     * @param odlKeystoreDname odl Keystore Dname
+     * @param trustKeystoreName Trust Keystore Name
+     * @param trustKeystorePwd Trust Keystore Password
+     * @param cipherSuites cipher suites that will be used by the SSL connection
+     * @return the created SslData object
+     */
+    SslData addSslDataKeystores(@Nonnull String bundleName, @Nonnull String odlKeystoreName, @Nonnull String odlKeystorePwd,
+            @Nonnull String odlKeystoreAlias, @Nonnull String odlKeystoreDname, @Nonnull String trustKeystoreName,
+            @Nonnull String trustKeystorePwd, @Nonnull String[] cipherSuites);
+
+    /**
+     * Add SslData object to Mdsal
+     *
+     * @param bundleName name of the bundle that will use the keystores
+     * @param odlKeystoreName odl Keystore Name
+     * @param odlKeystorePwd odl Keystore Password
+     * @param odlKeystoreAlias odl Keystore Alias
+     * @param odlKeystoreDname odl Keystore Dname
+     * @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 trustKeystoreName Trust Keystore Name
+     * @param trustKeystorePwd Trust Keystore Password
+     * @param cipherSuites cipher suites that will be used by the SSL connection
+     * @return the created SslData object
+     */
+    SslData addSslDataKeystores(@Nonnull String bundleName, @Nonnull String odlKeystoreName, @Nonnull String odlKeystorePwd,
+            @Nonnull String odlKeystoreAlias, @Nonnull String odlKeystoreDname, @Nonnull String odlKeystoreKeyAlg,
+            @Nonnull String odlKeystoreSignAlg, @Nonnull int odlKeystoreKeysize, @Nonnull int odlKeystoreValidity,
+            @Nonnull String trustKeystoreName, @Nonnull String trustKeystorePwd, @Nonnull String[] cipherSuites);
+
+    /**
+     * add a ODL signed certificate that is signed by a CA based on a certificate request generated by
+     * ODL keystore
+     *
+     * @param bundleName name of the bundle that will use the keystores
+     * @param alias for the certificate
+     * @param certificate as string
+     * @return true for successful added certificate
+     */
+    boolean addODLStoreSignedCertificate(@Nonnull String bundleName, @Nonnull String alias, @Nonnull String certificate);
+
+    /**
+     * Add a network node certificate to the trust keystore
+     *
+     * @param bundleName name of the bundle that will use the keystores
+     * @param alias certificate alias
+     * @param certificate as string
+     * @return true for successful added certificate
+     */
+    boolean addTrustNodeCertificate(@Nonnull String bundleName, @Nonnull String alias, @Nonnull String certificate);
+
+    /**
+     * Export the ODL keystore and Trust keystore to a file under karaf ssl/ directory
+     *
+     * @param bundleName name of the bundle that will use the keystores
+     */
+    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
+     *
+     * @param bundleName name of the bundle that will use the keystores
+     * @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);
+
+    /**
+     * Get the ODL keystore certificate
+     *
+     * @param bundleName name of the bundle that will use the keystores
+     * @param withTag  boolean to add cert tag to the return string
+     * @return certificate as string
+     */
+    String getODLStoreCertificate(@Nonnull String bundleName, boolean withTag);
+
+    /**
+     * Get a Network node certificate from the Trust keystore
+     *
+     * @param bundleName name of the bundle that will use the keystores
+     * @param alias of the certificate
+     * @param withTag  boolean to add cert tag to the return string
+     * @return certificate as string
+     */
+    String getTrustStoreCertificate(@Nonnull String bundleName, @Nonnull String alias,  boolean withTag);
+
+    /**
+     * Get the SslData
+     *
+     * @param bundleName name of the bundle that will use the keystores
+     * @return the SslData
+     */
+    SslData getSslData(@Nonnull String bundleName);
+
+    /**
+     * Get the ODL keystore object to be used by the SSLContext to establish the SSL connection.
+     *
+     * @param bundleName name of the bundle that will use the keystores
+     * @return ODL keystore
+     */
+    KeyStore getODLKeyStore(@Nonnull String bundleName);
+
+    /**
+     * Get the trust keystore object to be used by the SSLContext to establish the SSL connection.
+     *
+     * @param bundleName name of the bundle that will use the keystores
+     * @return Trust keystore
+     */
+    KeyStore getTrustKeyStore(@Nonnull String bundleName);
+
+    /**
+     * Get array of cipher suites that will be used in to establish the SSL connection.
+     *
+     * @param bundleName name of the bundle that will use the keystores
+     * @return Cipher Suites
+     */
+    String[] getCipherSuites(@Nonnull String bundleName);
+
+    /**
+     * Create SslData based on pre-established keystores for ODL and network nodes.
+     *
+     * @param bundleName name of the bundle that will use the keystores
+     * @param odlKeystoreName odl Keystore Name
+     * @param odlKeystorePwd must be the same as the imported ODL keystore's password
+     * @param odlKeystoreAlias must be the same as the imported ODL keystore's certificate alias
+     * @param odlKeyStore a valid keystore
+     * @param trustKeystoreName trust Keystore Name
+     * @param trustKeystorePwd must be the same as the imported Trust keystore's password
+     * @param trustKeyStore a valid keystore
+     * @param cipherSuites cipher suites that will be used by the SSL connection
+     * @return the created SslData object
+     */
+    SslData importSslDataKeystores(@Nonnull String bundleName, @Nonnull String odlKeystoreName, @Nonnull String odlKeystorePwd,
+                        @Nonnull String odlKeystoreAlias, @Nonnull KeyStore odlKeyStore, @Nonnull String trustKeystoreName,
+                        @Nonnull String trustKeystorePwd, @Nonnull KeyStore trustKeyStore, @Nonnull String[] cipherSuites);
+
+    /**
+     * Delete the SslData from Mdsal
+     *
+     * @param bundleName name of the bundle that will use the keystores
+     * @return true for succeed delete
+     */
+    boolean removeSslData(@Nonnull String bundleName);
+
+    /**
+     * Update the SslData
+     *
+     * @param sslData SSL Data
+     * @return the updated SslData object
+     */
+    SslData updateSslData(@Nonnull SslData sslData);
+
+}
index 36372c03dac678ce3c674b6426c595e91ec53c65..f050723fc512f29dd4ae4e9acd73cc8e1bbe944b 100644 (file)
@@ -10,29 +10,97 @@ package org.opendaylight.aaa.cert.api;
 
 import java.security.KeyStore;
 
+import javax.annotation.Nonnull;
+
 /**
+ * IAaaCertProvider defines the basic operation for certificates management
  *
  * @author mserngawy
  *
- * IAaaCertProvider define the basic operation for certificates management
  */
 public interface IAaaCertProvider extends java.lang.AutoCloseable {
 
-    boolean addCertificateODLKeyStore(String storePasswd, String alias, String certificate);
+    /**
+     * Add certificate to ODL keystore, the certificate should be signed by a CA (Certificate Authority) based on a certificate
+     * request generated by the ODL keystore.
+     *
+     * @param storePasswd ODL keystore password
+     * @param alias certificate alias
+     * @param certificate certificate @Nonnull String
+     * @return true at successful adding certificate
+     */
+    boolean addCertificateODLKeyStore(@Nonnull String storePasswd, @Nonnull String alias, @Nonnull String certificate);
 
-    boolean addCertificateTrustStore(String storePasswd, String alias, String certificate);
+    /**
+     * Add certificate to Trust keystore.
+     *
+     * @param storePasswd ODL keystore password
+     * @param alias certificate alias
+     * @param certificate certificate @Nonnull String
+     * @return true at successful adding certificate
+     */
+    boolean addCertificateTrustStore(@Nonnull String storePasswd, @Nonnull String alias, @Nonnull String certificate);
 
-    String createODLKeyStore(String keyStore, String storePasswd, String alias, String dName, int validity);
+    /**
+     * 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);
 
-    String createTrustKeyStore(String keyStore, String storePasswd, String alias);
+    /**
+     * 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);
 
-    String genODLKeyStorCertificateReq(String storePasswd, 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
+     * @return the certificate request
+     */
+    @Nonnull String genODLKeyStorCertificateReq(@Nonnull String storePasswd, @Nonnull String alias);
 
-    String getCertificateTrustStore(String storePasswd, String aliase);
+    /**
+     * Get certificate from the Trust keystore
+     *
+     * @param storePasswd Trust keystore password
+     * @param aliase the certificate alias
+     * @return certificate
+     */
+    @Nonnull String getCertificateTrustStore(@Nonnull String storePasswd, @Nonnull String aliase);
 
-    String getODLKeyStorCertificate(String storePasswd, String alias);
+    /**
+     * Get ODL keystore certificate.
+     *
+     * @param storePasswd ODL keystore password
+     * @param alias ODL keystore alias
+     * @return certificate
+     */
+    @Nonnull String getODLKeyStorCertificate(@Nonnull String storePasswd, @Nonnull String alias);
 
+    /**
+     * Get ODL Keystore as java keystore object
+     *
+     * @return ODL keystore
+     */
     KeyStore getODLKeyStore();
 
+    /**
+     * Get Trust Keystore as java keystore object
+     *
+     * @return Trust keystore
+     */
     KeyStore getTrustKeyStore();
-}
+}
\ No newline at end of file
diff --git a/aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/AaaCertMdsalProvider.java b/aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/AaaCertMdsalProvider.java
new file mode 100644 (file)
index 0000000..8a63cdb
--- /dev/null
@@ -0,0 +1,260 @@
+/*
+ * 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.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;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.cipher.suite.CipherSuitesBuilder;
+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;
+
+/**
+ * AaaCertMdsalProvider use to manage the certificates manipulation operations using Mdsal as data store
+ *
+ * @author mserngawy
+ *
+ */
+public class AaaCertMdsalProvider implements AutoCloseable, BindingAwareProvider, IAaaCertMdsalProvider {
+
+    private final static Logger LOG = LoggerFactory.getLogger(AaaCertMdsalProvider.class);
+    private ServiceRegistration<IAaaCertMdsalProvider> aaaCertMdsalServiceRegisteration;
+    private DataBroker dataBroker;
+    private KeyStoresDataUtils keyStoresData;
+    private final ODLMdsalKeyTool odlKeyTool;
+
+    public AaaCertMdsalProvider() {
+        odlKeyTool = new ODLMdsalKeyTool();
+        LOG.info("AaaCertMdsalProvider Initialized");
+    }
+
+    @Override
+    public boolean addODLStoreSignedCertificate(final String bundleName, final String alias, final String certificate) {
+        final SslData sslData = keyStoresData.getSslData(dataBroker, bundleName);
+        if (sslData != null) {
+            if (sslData.getOdlKeystore() != null) {
+                KeyStore keystore = odlKeyTool.loadKeyStore(sslData.getOdlKeystore().getKeystoreFile(), sslData.getOdlKeystore().getStorePassword());
+                keystore = odlKeyTool.addCertificate(keystore, certificate, alias, false);
+                if (keystore != null) {
+                    final OdlKeystore odlKeystore = KeyStoresDataUtils.updateOdlKeystore(sslData.getOdlKeystore(), odlKeyTool.convertKeystoreToBytes(keystore,
+                            sslData.getOdlKeystore().getStorePassword()));
+                    return keyStoresData.updateSslDataOdlKeystore(dataBroker, sslData, odlKeystore);
+                }
+            }
+        }
+        return false;
+    }
+
+    @Override
+    public SslData addSslDataKeystores(final String bundleName, final String odlKeystoreName, final String odlKeystorePwd,
+            final String odlKeystoreAlias, final String odlKeystoreDname, final String odlKeystoreKeyAlg, final String odlKeystoreSignAlg,
+            final int odlKeystoreKeysize, final int odlKeystoreValidity, final String trustKeystoreName, final String trustKeystorePwd,
+            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 List<CipherSuites> cipherSuitesList = new ArrayList<>();
+        if (cipherSuites != null) {
+            for (final String suite : cipherSuites) {
+                final CipherSuites cipherSuite = new CipherSuitesBuilder().setSuiteName(suite).build();
+                cipherSuitesList.add(cipherSuite);
+            }
+        }
+        return keyStoresData.addSslData(dataBroker, bundleName, odlKeystore, trustKeystore, cipherSuitesList);
+    }
+
+    @Override
+    public SslData addSslDataKeystores(final String bundleName, final String odlKeystoreName, final String odlKeystorePwd,
+            final String odlKeystoreAlias, final String odlKeystoreDname, final String trustKeystoreName, final String trustKeystorePwd,
+            final String[] cipherSuites) {
+        return addSslDataKeystores(bundleName, odlKeystoreName, odlKeystorePwd, odlKeystoreAlias, odlKeystoreDname,
+                KeyStoreConstant.DEFAULT_KEY_ALG, KeyStoreConstant.DEFAULT_SIGN_ALG, KeyStoreConstant.DEFAULT_KEY_SIZE,
+                KeyStoreConstant.DEFAULT_VALIDITY, trustKeystoreName, trustKeystorePwd, cipherSuites);
+    }
+
+    @Override
+    public boolean addTrustNodeCertificate(final String bundleName, final String alias, final String certificate) {
+        final SslData sslData = keyStoresData.getSslData(dataBroker, bundleName);
+        if (sslData != null) {
+            if (sslData.getTrustKeystore() != null) {
+                KeyStore keystore = odlKeyTool.loadKeyStore(sslData.getTrustKeystore().getKeystoreFile(), sslData.getTrustKeystore().getStorePassword());
+                keystore = odlKeyTool.addCertificate(keystore, certificate, alias, true);
+                if (keystore != null) {
+                    final TrustKeystore trustKeystore = keyStoresData.updateTrustKeystore(sslData.getTrustKeystore(), odlKeyTool.convertKeystoreToBytes(keystore,
+                            sslData.getTrustKeystore().getStorePassword()));
+                    return keyStoresData.updateSslDataTrustKeystore(dataBroker, sslData, trustKeystore);
+                }
+            }
+        }
+        return false;
+    }
+
+    @Override
+    public void close() throws Exception {
+        LOG.info("Aaa Certificate Mdsal Service Closed");
+        aaaCertMdsalServiceRegisteration.unregister();
+    }
+
+    @Override
+    public void exportSslDataKeystores(final String bundleName) {
+        final SslData sslData = keyStoresData.getSslData(dataBroker, bundleName);
+        if (sslData != null) {
+            KeyStore keystore = odlKeyTool.loadKeyStore(sslData.getTrustKeystore().getKeystoreFile(),
+                    sslData.getTrustKeystore().getStorePassword());
+            odlKeyTool.exportKeystore(keystore, sslData.getTrustKeystore().getStorePassword(), bundleName + "_trustKeystore");
+            keystore = odlKeyTool.loadKeyStore(sslData.getOdlKeystore().getKeystoreFile(),
+                    sslData.getOdlKeystore().getStorePassword());
+            odlKeyTool.exportKeystore(keystore, sslData.getOdlKeystore().getStorePassword(), bundleName + "_odlKeystore");
+        }
+    }
+
+    @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) {
+        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 null;
+    }
+
+    @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();
+            }
+        }
+        return null;
+    }
+
+    @Override
+    public KeyStore getODLKeyStore(final String bundleName) {
+        final SslData sslData = keyStoresData.getSslData(dataBroker, bundleName);
+        if (sslData != null) {
+            if (sslData.getOdlKeystore() != null) {
+                return odlKeyTool.loadKeyStore(sslData.getOdlKeystore().getKeystoreFile(), sslData.getOdlKeystore().getStorePassword());
+            }
+        }
+        return null;
+    }
+
+    @Override
+    public String getODLStoreCertificate(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(), odlKeyStore.getStorePassword());
+            return odlKeyTool.getCertificate(keystore, odlKeyStore.getStorePassword(), odlKeyStore.getAlias(), withTag);
+        }
+        return null;
+    }
+
+    @Override
+    public SslData getSslData(final String bundleName) {
+        return keyStoresData.getSslData(dataBroker, bundleName);
+    }
+
+    @Override
+    public KeyStore getTrustKeyStore(final String bundleName) {
+        final SslData sslData = keyStoresData.getSslData(dataBroker, bundleName);
+        if (sslData != null) {
+            if (sslData.getTrustKeystore() != null) {
+                return odlKeyTool.loadKeyStore(sslData.getTrustKeystore().getKeystoreFile(), sslData.getTrustKeystore().getStorePassword());
+            }
+        }
+        return null;
+    }
+
+    @Override
+    public String getTrustStoreCertificate(final String bundleName, final String alias, final boolean withTag) {
+        final SslData sslData = keyStoresData.getSslData(dataBroker, bundleName);
+        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 null;
+    }
+
+    @Override
+    public SslData importSslDataKeystores(final String bundleName, final String odlKeystoreName, final String odlKeystorePwd,
+            final String odlKeystoreAlias, final KeyStore odlKeyStore, final String trustKeystoreName, final String trustKeystorePwd,
+            final KeyStore trustKeyStore, final String[] cipherSuites) {
+        final OdlKeystore odlKeystore = keyStoresData.createOdlKeystore(odlKeystoreName, odlKeystoreAlias, odlKeystorePwd,
+                                    odlKeyTool.convertKeystoreToBytes(odlKeyStore, odlKeystorePwd));
+        final TrustKeystore trustKeystore = keyStoresData.createTrustKeystore(trustKeystoreName, trustKeystorePwd,
+                                    odlKeyTool.convertKeystoreToBytes(trustKeyStore, trustKeystorePwd));
+        final List<CipherSuites> cipherSuitesList = new ArrayList<>();
+        for (final String suit : cipherSuites) {
+            final CipherSuites cipherSuite = new CipherSuitesBuilder().setSuiteName(suit).build();
+            cipherSuitesList.add(cipherSuite);
+        }
+        return keyStoresData.addSslData(dataBroker, bundleName, odlKeystore, trustKeystore, cipherSuitesList);
+    }
+
+    @Override
+    public void onSessionInitiated(final ProviderContext session) {
+        LOG.info("Aaa Certificate Mdsal Service Session Initiated");
+        final BundleContext context = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
+        aaaCertMdsalServiceRegisteration = context.registerService(IAaaCertMdsalProvider.class, this, null);
+
+        // Retrieve the data broker to create transactions
+        dataBroker =  session.getSALService(DataBroker.class);
+        final KeyStores keyStoreData = new KeyStoresBuilder().setId(KeyStoresDataUtils.KEYSTORES_DATA_TREE).build();
+        MdsalUtils.initalizeDatastore(LogicalDatastoreType.CONFIGURATION, dataBroker, KeyStoresDataUtils.getKeystoresIid(), keyStoreData);
+        final ServiceReference<?> serviceReference = context.getServiceReference(AAAEncryptionService.class);
+        if (serviceReference != null) {
+            final AAAEncryptionService encryptionSrv = (AAAEncryptionService) context.getService(serviceReference);
+            keyStoresData = new KeyStoresDataUtils(encryptionSrv);
+        }
+    }
+
+    @Override
+    public boolean removeSslData(final String bundleName) {
+        return keyStoresData.removeSslData(dataBroker, bundleName);
+    }
+
+    @Override
+    public SslData updateSslData(final SslData sslData) {
+        if (keyStoresData.updateSslData(dataBroker, sslData)) {
+            return sslData;
+        }
+        return null;
+    }
+}
index e945d06f9db9b3443d95453f1f3fdf1c238b3a80..2342792eb90c38ef5899ed6db06e2192c2ffe1dd 100644 (file)
@@ -35,9 +35,10 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
+ * AaaCertProvider use to manage the certificates manipulation operations add, revoke and update
  *
  * @author mserngawy
- * AaaCertProvider use to manage the certificates manipulation operations add, revoke and update
+ *
  */
 public class AaaCertProvider implements AutoCloseable, IAaaCertProvider, BindingAwareProvider, AaaCertRpcService {
 
@@ -112,7 +113,7 @@ public class AaaCertProvider implements AutoCloseable, IAaaCertProvider, Binding
     @Override
     public String genODLKeyStorCertificateReq(final String storePasswd, final String alias) {
         return odlKeyTool.generateCertificateReq(ctlKeyStore.getName(), storePasswd,
-                     alias,KeyStoreUtilis.defaultSignAlg, true);
+                     alias, KeyStoreConstant.DEFAULT_SIGN_ALG, true);
     }
 
     @Override
@@ -156,7 +157,7 @@ public class AaaCertProvider implements AutoCloseable, IAaaCertProvider, Binding
     public Future<RpcResult<GetODLCertificateReqOutput>> getODLCertificateReq() {
         final SettableFuture<RpcResult<GetODLCertificateReqOutput>> futureResult = SettableFuture.create();
         final String certReq = odlKeyTool.generateCertificateReq(ctlKeyStore.getName(), ctlKeyStore.getStorePassword(),
-                                 ctlKeyStore.getAlias(), KeyStoreUtilis.defaultSignAlg, true);
+                                 ctlKeyStore.getAlias(), KeyStoreConstant.DEFAULT_SIGN_ALG, true);
         if (certReq != null) {
             final GetODLCertificateReqOutput odlCertReqOutput = new GetODLCertificateReqOutputBuilder()
                                                         .setOdlCertReq(certReq)
@@ -219,4 +220,4 @@ public class AaaCertProvider implements AutoCloseable, IAaaCertProvider, Binding
         }
         return futureResult;
     }
-}
+}
\ No newline at end of file
diff --git a/aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/ConnectionConfigurationImpl.java b/aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/ConnectionConfigurationImpl.java
deleted file mode 100644 (file)
index f7716e6..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.cert.impl;
-
-import java.net.InetAddress;
-
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionConfiguration;
-import org.opendaylight.openflowjava.protocol.api.connection.ThreadConfiguration;
-import org.opendaylight.openflowjava.protocol.api.connection.TlsConfiguration;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.TransportProtocol;
-
-public class ConnectionConfigurationImpl implements ConnectionConfiguration {
-
-    private final ConnectionConfiguration connConfig;
-    private final TlsConfiguration tlsConfig;
-
-    public ConnectionConfigurationImpl(final ConnectionConfiguration baseConnConfig, final TlsConfiguration tlsConfig) {
-        connConfig = baseConnConfig;
-        this.tlsConfig = tlsConfig;
-    }
-
-    @Override
-    public InetAddress getAddress() {
-        return connConfig.getAddress();
-    }
-
-    @Override
-    public int getPort() {
-        return connConfig.getPort();
-    }
-
-    @Override
-    public Object getSslContext() {
-        return connConfig.getSslContext();
-    }
-
-    @Override
-    public long getSwitchIdleTimeout() {
-        return connConfig.getSwitchIdleTimeout();
-    }
-
-    @Override
-    public ThreadConfiguration getThreadConfiguration() {
-        return connConfig.getThreadConfiguration();
-    }
-
-    @Override
-    public TlsConfiguration getTlsConfiguration() {
-        return tlsConfig;
-    }
-
-    @Override
-    public Object getTransferProtocol() {
-        return TransportProtocol.TLS;
-    }
-
-    @Override
-    public boolean useBarrier() {
-        return connConfig.useBarrier();
-    }
-
-}
similarity index 75%
rename from aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/KeyStoreUtilis.java
rename to aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/KeyStoreConstant.java
index 46ba778834237cb6636fc10f29c68ff1f96aa5cd..6d4866c3f7af01b52792224db896432173852a23 100644 (file)
@@ -16,26 +16,29 @@ import java.io.IOException;
 import java.nio.charset.StandardCharsets;
 
 /**
+ * Default values class for aaa-cert bundle
  *
  * @author mserngawy
- * Utility class for aaa-cert bundle
+ *
  */
-public class KeyStoreUtilis {
+public class KeyStoreConstant {
 
     public static final String BEGIN_CERTIFICATE = "-----BEGIN CERTIFICATE-----";
 
     public static final String BEGIN_CERTIFICATE_REQUEST = "-----BEGIN CERTIFICATE REQUEST-----";
-    public static String defaultKeyAlg = "RSA"; //DES
-    public static int defaultKeySize = 2048; //1024
-    public static String defaultSignAlg = "SHA1WithRSAEncryption"; //MD5WithRSAEncryption
+    // Day time in millisecond
+    public static final long DAY_TIME = 1000L * 60 * 60 * 24;
+    public static final String DEFAULT_KEY_ALG = "RSA"; //DES
+    public static final int DEFAULT_KEY_SIZE = 2048; //1024
+    public static final String DEFAULT_SIGN_ALG = "SHA1WithRSAEncryption"; //MD5WithRSAEncryption
 
-    public static int defaultValidity = 365;
+    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 String keyStorePath = "configuration" + File.separator + "ssl" + File.separator;
+    public static String KEY_STORE_PATH = "configuration" + File.separator + "ssl" + File.separator;
 
     public static boolean checkKeyStoreFile(final String fileName) {
-        final File file = new File(keyStorePath + fileName);
+        final File file = new File(KEY_STORE_PATH + fileName);
         return file.exists();
     }
 
@@ -53,7 +56,7 @@ public class KeyStoreUtilis {
         }
 
         try {
-            final FileInputStream fInputStream = new FileInputStream(keyStorePath + certFile);
+            final FileInputStream fInputStream = new FileInputStream(KEY_STORE_PATH + certFile);
             final byte[] certBytes = new byte[fInputStream.available()];
             fInputStream.read(certBytes);
             fInputStream.close();
@@ -71,7 +74,7 @@ public class KeyStoreUtilis {
 
         BufferedWriter out;
         try {
-            out = new BufferedWriter(new FileWriter(keyStorePath + fileName));
+            out = new BufferedWriter(new FileWriter(KEY_STORE_PATH + fileName));
             out.write(cert);
             out.close();
             return true;
index e6e249f1364d9a3d39e78ee9f57ac01f25ba9cbf..07f413edb9cf709ba761be2cef98309af3074972 100644 (file)
@@ -42,25 +42,24 @@ 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
  *
- * ODLKeyTool has the basic operation to manage the Java keyStores such as generate, add and delete certificates
  */
 public class ODLKeyTool {
 
     private final static Logger LOG = LoggerFactory.getLogger(ODLKeyTool.class);
-    // Day time in millisecond
-    private final long dayTime = 1000L * 60 * 60 * 24;
-    private String workingDir = KeyStoreUtilis.keyStorePath;
+    private final String workingDir;
 
     protected ODLKeyTool() {
-        KeyStoreUtilis.createDir(workingDir);
+        workingDir = KeyStoreConstant.KEY_STORE_PATH;
+        KeyStoreConstant.createDir(workingDir);
     }
 
     public ODLKeyTool(final String workingDirectory) {
         workingDir = workingDirectory;
-        KeyStoreUtilis.createDir(workingDir);
+        KeyStoreConstant.createDir(workingDir);
     }
 
     public boolean addCertificate(final String keyStoreName, final String keyStorePwd, final String certificate, final String alias) {
@@ -77,7 +76,7 @@ public class ODLKeyTool {
             LOG.info("Certificate {}  Added to keyStore {}", alias, keyStoreName);
             return true;
         } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException | IOException e) {
-            LOG.error("failed to add certificate {}", e.getMessage());
+            LOG.error("failed to add certificate", e);
             return false;
         }
     }
@@ -87,8 +86,8 @@ public class ODLKeyTool {
         try {
             trustKeyStore = KeyStore.getInstance("JKS");
             trustKeyStore.load(null, keyStorePwd.toCharArray());
-            if(KeyStoreUtilis.checkKeyStoreFile(certFile)) {
-                final String certificate = KeyStoreUtilis.readFile(certFile);
+            if(KeyStoreConstant.checkKeyStoreFile(certFile)) {
+                final String certificate = KeyStoreConstant.readFile(certFile);
                 final X509Certificate newCert = getCertificate(certificate);
                 trustKeyStore.setCertificateEntry(alias, newCert);
             }
@@ -96,24 +95,24 @@ public class ODLKeyTool {
             LOG.info("{} is created", keyStoreName);
             return true;
         } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
-            LOG.error("Failed to create keystore {}", keyStoreName);
+            LOG.error("Failed to create keystore {}", keyStoreName, e);
             return false;
         }
     }
 
     public boolean createKeyStoreWithSelfSignCert(final String keyStoreName, final String keyStorePwd, final String dName, final String keyAlias, final int validity) {
         try {
-            final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyStoreUtilis.defaultKeyAlg);
-            keyPairGenerator.initialize(KeyStoreUtilis.defaultKeySize);
+            final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyStoreConstant.DEFAULT_KEY_ALG);
+            keyPairGenerator.initialize(KeyStoreConstant.DEFAULT_KEY_SIZE);
             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() + (dayTime * validity)));
+            x509V3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (KeyStoreConstant.DAY_TIME * validity)));
             x509V3CertGen.setSubjectDN(new X509Principal(dName));
             x509V3CertGen.setPublicKey(keyPair.getPublic());
-            x509V3CertGen.setSignatureAlgorithm(KeyStoreUtilis.defaultSignAlg);
+            x509V3CertGen.setSignatureAlgorithm(KeyStoreConstant.DEFAULT_SIGN_ALG);
             final X509Certificate x509Cert = x509V3CertGen.generateX509Certificate(keyPair.getPrivate());
             final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
             ctlKeyStore.load(null, keyStorePwd.toCharArray());
@@ -125,7 +124,7 @@ public class ODLKeyTool {
             return true;
         }
         catch (NoSuchAlgorithmException | InvalidKeyException | SecurityException | SignatureException | KeyStoreException | CertificateException | IOException e) {
-            LOG.error("Fatal error creating key cert: {}", e.getMessage());
+            LOG.error("Fatal error creating key", e);
             return false;
         }
     }
@@ -148,11 +147,11 @@ public class ODLKeyTool {
                 final String certReq = DatatypeConverter.printBase64Binary(csr.getEncoded());
                 if (withTag) {
                     final StringBuilder sb = new StringBuilder();
-                    sb.append(KeyStoreUtilis.BEGIN_CERTIFICATE_REQUEST);
+                    sb.append(KeyStoreConstant.BEGIN_CERTIFICATE_REQUEST);
                     sb.append("\n");
                     sb.append(certReq);
                     sb.append("\n");
-                    sb.append(KeyStoreUtilis.END_CERTIFICATE_REQUEST);
+                    sb.append(KeyStoreConstant.END_CERTIFICATE_REQUEST);
                     return sb.toString();
                 }
                 return certReq;
@@ -171,9 +170,9 @@ public class ODLKeyTool {
             return null;
         }
 
-        if (certificate.contains(KeyStoreUtilis.BEGIN_CERTIFICATE)) {
-            final int fIdx = certificate.indexOf(KeyStoreUtilis.BEGIN_CERTIFICATE) + KeyStoreUtilis.BEGIN_CERTIFICATE.length();
-            final int sIdx = certificate.indexOf(KeyStoreUtilis.END_CERTIFICATE);
+        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);
@@ -200,11 +199,11 @@ public class ODLKeyTool {
                 final String cert = DatatypeConverter.printBase64Binary(odlCert.getEncoded());
                 if (withTag) {
                     final StringBuilder sb = new StringBuilder();
-                    sb.append(KeyStoreUtilis.BEGIN_CERTIFICATE);
+                    sb.append(KeyStoreConstant.BEGIN_CERTIFICATE);
                     sb.append("\n");
                     sb.append(cert);
                     sb.append("\n");
-                    sb.append(KeyStoreUtilis.END_CERTIFICATE);
+                    sb.append(KeyStoreConstant.END_CERTIFICATE);
                     return sb.toString();
                 }
                 return cert;
@@ -234,4 +233,4 @@ public class ODLKeyTool {
         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
new file mode 100644 (file)
index 0000000..d06154b
--- /dev/null
@@ -0,0 +1,252 @@
+/*
+ * 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;
+        }
+    }
+}
diff --git a/aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/TlsConfigurationImp.java b/aaa-cert/src/main/java/org/opendaylight/aaa/cert/impl/TlsConfigurationImp.java
deleted file mode 100644 (file)
index 91206ef..0000000
+++ /dev/null
@@ -1,98 +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.util.List;
-
-import org.opendaylight.openflowjava.protocol.api.connection.TlsConfiguration;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.KeystoreType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.PathType;
-
-/**
- *
- * @author mserngawy
- * TlsConfigurationImp has configurations of the TLS connection
- */
-public class TlsConfigurationImp implements TlsConfiguration{
-
-    private final String certPwd;
-    private final String tlsKeyStore;
-    private final PathType tlsKeystorePathType;
-    private final String tlsKeyStorePwd;
-    private final KeystoreType tlsKeyStoreType;
-    private final String trustKeyStore;
-    private final PathType trustKeystorePathType;
-    private final String trustKeyStorePwd;
-    private final KeystoreType trustKeyStoreType;
-
-    public TlsConfigurationImp(final String tlsKeyStore, final String trustKeyStore, final String tlsKeyStorePwd,
-            final String trustKeyStorePwd, final String certPwd, final KeystoreType tlsKeyStoreType,final KeystoreType trustKeyStoreTy,
-            final PathType tlsKeystorePathType, final PathType trustKeystorePathType) {
-        this.tlsKeyStore = tlsKeyStore;
-        this.trustKeyStore = trustKeyStore;
-        this.tlsKeyStorePwd = tlsKeyStorePwd;
-        this.trustKeyStorePwd = trustKeyStorePwd;
-        this.certPwd = certPwd;
-        this.tlsKeyStoreType = tlsKeyStoreType;
-        this.trustKeyStoreType = trustKeyStoreTy;
-        this.tlsKeystorePathType = tlsKeystorePathType;
-        this.trustKeystorePathType = trustKeystorePathType;
-    }
-
-    @Override
-    public String getCertificatePassword() {
-        return certPwd;
-    }
-
-    @Override
-    public List<String> getCipherSuites() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
-    @Override
-    public String getKeystorePassword() {
-        return tlsKeyStorePwd;
-    }
-
-    @Override
-    public String getTlsKeystore() {
-        return tlsKeyStore;
-    }
-
-    @Override
-    public PathType getTlsKeystorePathType() {
-        return tlsKeystorePathType;
-    }
-
-    @Override
-    public KeystoreType getTlsKeystoreType() {
-        return tlsKeyStoreType;
-    }
-
-    @Override
-    public String getTlsTruststore() {
-        return trustKeyStore;
-    }
-
-    @Override
-    public PathType getTlsTruststorePathType() {
-        return trustKeystorePathType;
-    }
-
-    @Override
-    public KeystoreType getTlsTruststoreType() {
-        return trustKeyStoreType;
-    }
-
-    @Override
-    public String getTruststorePassword() {
-        return trustKeyStorePwd;
-    }
-}
diff --git a/aaa-cert/src/main/java/org/opendaylight/aaa/cert/utils/KeyStoresDataUtils.java b/aaa-cert/src/main/java/org/opendaylight/aaa/cert/utils/KeyStoresDataUtils.java
new file mode 100644 (file)
index 0000000..33e4f78
--- /dev/null
@@ -0,0 +1,250 @@
+/*
+ * 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.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.encrypt.AAAEncryptionService;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+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.cipher.suite.CipherSuites;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.cipher.suite.CipherSuitesBuilder;
+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;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.ssl.data.TrustKeystoreBuilder;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * KeyStoresDataUtils manage the SslData operations add, delete and update
+ *
+ * @author mserngawy
+ *
+ */
+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";
+
+    public static InstanceIdentifier<KeyStores> getKeystoresIid() {
+        return InstanceIdentifier.builder(KeyStores.class).build();
+    }
+
+    public static InstanceIdentifier<SslData> getSslDataIid() {
+        return InstanceIdentifier.create(KeyStores.class).child(SslData.class);
+    }
+
+    public static InstanceIdentifier<SslData> getSslDataIid(final String bundleName) {
+        final SslDataKey sslDataKey = new SslDataKey(bundleName);
+        return InstanceIdentifier.create(KeyStores.class).child(SslData.class, sslDataKey);
+    }
+
+    public static OdlKeystore updateOdlKeystore(final OdlKeystore baseOdlKeyStore, final byte[] keyStoreBytes) {
+        final OdlKeystore odlKeystore = new OdlKeystoreBuilder(baseOdlKeyStore)
+                                .setKeystoreFile(keyStoreBytes)
+                                .build();
+        return odlKeystore;
+    }
+
+    public KeyStoresDataUtils(final AAAEncryptionService encryService) {
+        this.encryService = encryService;
+    }
+
+    public SslData addSslData(final DataBroker dataBroker, final String bundleName, final OdlKeystore odlKeystore,
+            final TrustKeystore trustKeystore, final List<CipherSuites> cipherSuites) {
+        final SslDataKey sslDataKey = new SslDataKey(bundleName);
+        final SslData sslData = new SslDataBuilder()
+                            .setKey(sslDataKey)
+                            .setOdlKeystore(encryptOdlKeyStore(odlKeystore))
+                            .setTrustKeystore(encryptTrustKeystore(trustKeystore))
+                            .setCipherSuites(cipherSuites)
+                            .build();
+
+        if (MdsalUtils.put(dataBroker, LogicalDatastoreType.CONFIGURATION, getSslDataIid(bundleName), sslData)) {
+            return new SslDataBuilder().setKey(sslDataKey)
+                    .setOdlKeystore(odlKeystore)
+                    .setTrustKeystore(trustKeystore)
+                    .setCipherSuites(cipherSuites)
+                    .build();
+        } else {
+            return null;
+        }
+    }
+
+    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)
+                                    .build();
+        return cipherSuite;
+    }
+
+    public OdlKeystore createOdlKeystore(final String name, final String alias, final String password, final byte[] keyStoreBytes) {
+        final OdlKeystore odlKeystore = new OdlKeystoreBuilder()
+                                .setKeystoreFile(keyStoreBytes)
+                                .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) {
+        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 byte[] keyStoreBytes = odlKeyTool.convertKeystoreToBytes(odlKeyTool.createKeyStoreWithSelfSignCert(name, password,
+                dname, alias, validity, keyAlg, keySize, sigAlg), password);
+        LOG.info("Odl keystore string {} ", keyStoreBytes);
+        final OdlKeystore odlKeystore = new OdlKeystoreBuilder()
+                                    .setKeystoreFile(keyStoreBytes)
+                                    .setAlias(alias)
+                                    .setDname(dname)
+                                    .setKeyAlg(keyAlg)
+                                    .setKeysize(keySize)
+                                    .setName(name)
+                                    .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)
+                                        .build();
+        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);
+        final TrustKeystore trustKeystore = new TrustKeystoreBuilder()
+                                        .setCertificates(certificates)
+                                        .setKeystoreFile(keyStoreBytes)
+                                        .setName(name)
+                                        .setStorePassword(password)
+                                        .build();
+        return trustKeystore;
+    }
+
+    private OdlKeystore decryptOdlKeyStore(final OdlKeystore odlKeystore) {
+        final OdlKeystoreBuilder odlKeystoreBuilder = new OdlKeystoreBuilder(odlKeystore);
+        odlKeystoreBuilder.setKeystoreFile(encryService.decrypt(odlKeystore.getKeystoreFile()));
+        odlKeystoreBuilder.setStorePassword(encryService.decrypt(odlKeystore.getStorePassword()));
+        return odlKeystoreBuilder.build();
+    }
+
+    private SslData decryptSslData(final SslData sslData) {
+        final SslDataBuilder sslDataBuilder = new SslDataBuilder(sslData)
+                .setOdlKeystore(decryptOdlKeyStore(sslData.getOdlKeystore()))
+                .setTrustKeystore(decryptTrustKeystore(sslData.getTrustKeystore()));
+        return sslDataBuilder.build();
+    }
+
+    private TrustKeystore decryptTrustKeystore(final TrustKeystore trustKeyStore) {
+        final TrustKeystoreBuilder trustKeyStoreBuilder = new TrustKeystoreBuilder(trustKeyStore);
+        trustKeyStoreBuilder.setKeystoreFile(encryService.decrypt(trustKeyStore.getKeystoreFile()));
+        trustKeyStoreBuilder.setStorePassword(encryService.decrypt(trustKeyStore.getStorePassword()));
+        return trustKeyStoreBuilder.build();
+    }
+
+    private OdlKeystore encryptOdlKeyStore(final OdlKeystore odlKeystore) {
+        final OdlKeystoreBuilder odlKeystoreBuilder = new OdlKeystoreBuilder(odlKeystore);
+        odlKeystoreBuilder.setKeystoreFile(encryService.encrypt(odlKeystore.getKeystoreFile()));
+        odlKeystoreBuilder.setStorePassword(encryService.encrypt(odlKeystore.getStorePassword()));
+        return odlKeystoreBuilder.build();
+    }
+
+    private SslData encryptSslData(final SslData sslData) {
+        final SslDataBuilder sslDataBuilder = new SslDataBuilder(sslData)
+                                        .setOdlKeystore(encryptOdlKeyStore(sslData.getOdlKeystore()))
+                                        .setTrustKeystore(encryptTrustKeystore(sslData.getTrustKeystore()));
+        return sslDataBuilder.build();
+    }
+
+    private TrustKeystore encryptTrustKeystore(final TrustKeystore trustKeyStore) {
+        final TrustKeystoreBuilder trustKeyStoreBuilder = new TrustKeystoreBuilder(trustKeyStore);
+        trustKeyStoreBuilder.setKeystoreFile(encryService.encrypt(trustKeyStore.getKeystoreFile()));
+        trustKeyStoreBuilder.setStorePassword(encryService.encrypt(trustKeyStore.getStorePassword()));
+        return trustKeyStoreBuilder.build();
+    }
+
+    public SslData getSslData(final DataBroker dataBroker, final String bundleName) {
+        final InstanceIdentifier<SslData> sslDataIid = getSslDataIid(bundleName);
+        return decryptSslData(MdsalUtils.read(dataBroker, LogicalDatastoreType.CONFIGURATION, sslDataIid));
+    }
+
+    public boolean removeSslData(final DataBroker dataBroker, final String bundleName) {
+        final InstanceIdentifier<SslData> sslDataIid = getSslDataIid(bundleName);
+        return MdsalUtils.delete(dataBroker, LogicalDatastoreType.CONFIGURATION, sslDataIid);
+    }
+
+    public boolean updateSslData(final DataBroker dataBroker, final SslData sslData) {
+        final InstanceIdentifier<SslData> sslDataIid = getSslDataIid(sslData.getBundleName());
+        return MdsalUtils.merge(dataBroker, LogicalDatastoreType.CONFIGURATION, sslDataIid, encryptSslData(sslData));
+    }
+
+    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());
+    }
+
+    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());
+    }
+
+    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());
+    }
+
+    public TrustKeystore updateTrustKeystore(final TrustKeystore baseTrustKeyStore, final byte[] keyStoreBytes) {
+        final TrustKeystore trustKeystore = new TrustKeystoreBuilder(baseTrustKeyStore)
+                                .setKeystoreFile(keyStoreBytes)
+                                .build();
+        return trustKeystore;
+    }
+}
diff --git a/aaa-cert/src/main/java/org/opendaylight/aaa/cert/utils/MdsalUtils.java b/aaa-cert/src/main/java/org/opendaylight/aaa/cert/utils/MdsalUtils.java
new file mode 100644 (file)
index 0000000..2447eb1
--- /dev/null
@@ -0,0 +1,165 @@
+/*
+ * 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.utils;
+
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+
+/**
+ * MdsalUtils manages all the mdsal data operation delete, merger, put and read.
+ *
+ * @author mserngawy
+ *
+ */
+public class MdsalUtils {
+    private static final Logger LOG = LoggerFactory.getLogger(MdsalUtils.class);
+
+    /**
+     * Executes delete as a blocking transaction.
+     *
+     * @param dataBroker Mdsal data Broker
+     * @param store {@link LogicalDatastoreType} which should be modified
+     * @param path {@link InstanceIdentifier} to read from
+     * @param <D> the data object type
+     * @return the result of the request
+     */
+    public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> boolean delete(
+            final DataBroker dataBroker, final LogicalDatastoreType store, final InstanceIdentifier<D> path)  {
+        boolean result = false;
+        final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
+        transaction.delete(store, path);
+        final CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit();
+        try {
+            future.checkedGet();
+            result = true;
+        } catch (final TransactionCommitFailedException e) {
+            LOG.warn("Failed to delete {} ", path, e);
+        }
+        return result;
+    }
+
+    /**
+     * initialize the data tree for the given InstanceIdentifier type
+     *
+     * @param type data store type
+     * @param dataBroker Mdsal data Broker
+     * @param iid InstanceIdentifier type
+     * @param object data object
+     */
+    public static <T extends DataObject> void initalizeDatastore(final LogicalDatastoreType type,
+            final DataBroker dataBroker, final InstanceIdentifier<T> iid, final T object) {
+        // Put data to MD-SAL data store
+        final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
+        transaction.put(type, iid, object);
+
+        // Perform the transaction.submit asynchronously
+        Futures.addCallback(transaction.submit(), new FutureCallback<Void>() {
+            @Override
+            public void onFailure(final Throwable throwable) {
+                LOG.error("initDatastore: transaction failed");
+            }
+
+            @Override
+            public void onSuccess(final Void result) {
+                LOG.debug("initDatastore: transaction succeeded");
+            }
+        });
+        LOG.info("initDatastore: data populated: {}, {}, {}", type, iid, object);
+    }
+
+    /**
+     * Executes merge as a blocking transaction.
+     *
+     * @param dataBroker Mdsal data Broker
+     * @param logicalDatastoreType {@link LogicalDatastoreType} which should be modified
+     * @param path {@link InstanceIdentifier} for path to read
+     * @param <D> the data object type
+     * @return the result of the request
+     */
+    public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> boolean merge(
+            final DataBroker dataBroker, final LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<D> path, final D data) {
+        boolean result = false;
+        final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
+        transaction.merge(logicalDatastoreType, path, data, true);
+        final CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit();
+        try {
+            future.checkedGet();
+            result = true;
+        } catch (final TransactionCommitFailedException e) {
+            LOG.warn("Failed to merge {} ", path, e);
+        }
+        return result;
+    }
+
+    /**
+     * Executes put as a blocking transaction.
+     *
+     * @param dataBroker Mdsal data Broker
+     * @param logicalDatastoreType {@link LogicalDatastoreType} which should be modified
+     * @param path {@link InstanceIdentifier} for path to read
+     * @param <D> the data object type
+     * @return the result of the request
+     */
+    public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> boolean put(
+            final DataBroker dataBroker, final LogicalDatastoreType logicalDatastoreType, final InstanceIdentifier<D> path, final D data)  {
+        boolean result = false;
+        final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
+        transaction.put(logicalDatastoreType, path, data, true);
+        final CheckedFuture<Void, TransactionCommitFailedException> future = transaction.submit();
+        try {
+            future.checkedGet();
+            result = true;
+        } catch (final TransactionCommitFailedException e) {
+            LOG.warn("Failed to put {} ", path, e);
+        }
+        return result;
+    }
+
+    /**
+     * Executes read as a blocking transaction.
+     *
+     * @param store {@link LogicalDatastoreType} to read
+     * @param path {@link InstanceIdentifier} for path to read
+     * @param <D> the data object type
+     * @return the result as the data object requested
+     */
+    public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> D read(
+            final DataBroker dataBroker, final LogicalDatastoreType store, final InstanceIdentifier<D> path)  {
+        D result = null;
+        final ReadOnlyTransaction transaction = dataBroker.newReadOnlyTransaction();
+        Optional<D> optionalDataObject;
+        final CheckedFuture<Optional<D>, ReadFailedException> future = transaction.read(store, path);
+        try {
+            optionalDataObject = future.checkedGet();
+            if (optionalDataObject.isPresent()) {
+                result = optionalDataObject.get();
+            } else {
+                LOG.debug("{}: Failed to read {}",
+                        Thread.currentThread().getStackTrace()[1], path);
+            }
+        } catch (final ReadFailedException e) {
+            LOG.warn("Failed to read {} ", path, e);
+        }
+        transaction.close();
+        return result;
+    }
+}
diff --git a/aaa-cert/src/main/java/org/opendaylight/yang/gen/v1/urn/opendaylight/yang/aaa/cert/mdsal/rev160321/AaaCertMdsalProviderModule.java b/aaa-cert/src/main/java/org/opendaylight/yang/gen/v1/urn/opendaylight/yang/aaa/cert/mdsal/rev160321/AaaCertMdsalProviderModule.java
new file mode 100644 (file)
index 0000000..ad8d3c8
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * 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.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321;
+
+import org.opendaylight.aaa.cert.impl.AaaCertMdsalProvider;
+
+public class AaaCertMdsalProviderModule extends AbstractAaaCertMdsalProviderModule {
+
+    public AaaCertMdsalProviderModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
+        super(identifier, dependencyResolver);
+    }
+
+    public AaaCertMdsalProviderModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, final org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.AaaCertMdsalProviderModule oldModule, final java.lang.AutoCloseable oldInstance) {
+        super(identifier, dependencyResolver, oldModule, oldInstance);
+    }
+
+    @Override
+    public java.lang.AutoCloseable createInstance() {
+        final AaaCertMdsalProvider aaaCertMdsal = new AaaCertMdsalProvider();
+        getAaaBrokerDependency().registerProvider(aaaCertMdsal);
+        return aaaCertMdsal;
+    }
+
+    @Override
+    public void customValidation() {
+
+    }
+
+}
diff --git a/aaa-cert/src/main/java/org/opendaylight/yang/gen/v1/urn/opendaylight/yang/aaa/cert/mdsal/rev160321/AaaCertMdsalProviderModuleFactory.java b/aaa-cert/src/main/java/org/opendaylight/yang/gen/v1/urn/opendaylight/yang/aaa/cert/mdsal/rev160321/AaaCertMdsalProviderModuleFactory.java
new file mode 100644 (file)
index 0000000..599f417
--- /dev/null
@@ -0,0 +1,13 @@
+/*
+* Generated file
+*
+* Generated from: yang module name: aaa-cert-mdsal yang module local name: aaa-cert-mdsal
+* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
+* Generated at: Mon Mar 21 16:18:48 EDT 2016
+*
+* Do not modify this file unless it is present under src/main directory
+*/
+package org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321;
+public class AaaCertMdsalProviderModuleFactory extends org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.mdsal.rev160321.AbstractAaaCertMdsalProviderModuleFactory {
+
+}
index 9ec349f8eef7297842c34ca0a335e5fa8a6860a4..50f42c355a4ddcb44b5e61c6d34a81f9feb1922f 100644 (file)
@@ -8,22 +8,12 @@
 
 package org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rev151126;
 
-import java.util.List;
-
 import org.opendaylight.aaa.cert.impl.AaaCertProvider;
-import org.opendaylight.aaa.cert.impl.ConnectionConfigurationImpl;
-import org.opendaylight.aaa.cert.impl.KeyStoreUtilis;
-import org.opendaylight.aaa.cert.impl.TlsConfigurationImp;
-import org.opendaylight.openflowjava.protocol.api.connection.ConnectionConfiguration;
-import org.opendaylight.openflowjava.protocol.api.connection.TlsConfiguration;
-import org.opendaylight.openflowjava.protocol.spi.connection.SwitchConnectionProvider;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.KeystoreType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.config.rev140630.PathType;
+import org.opendaylight.aaa.cert.impl.KeyStoreConstant;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- *
  * @author mserngawy
  * AaaCertProviderModule create and intialize the AaaCertProvider services
  */
@@ -44,35 +34,19 @@ public class AaaCertProviderModule extends org.opendaylight.yang.gen.v1.urn.open
         final CtlKeystore ctlKeyStore = this.getCtlKeystore();
         final TrustKeystore trust = this.getTrustKeystore();
         final AaaCertProvider aaaCertProvider = new AaaCertProvider(ctlKeyStore, trust);
-        if (this.getUseConfig() && !KeyStoreUtilis.checkKeyStoreFile(ctlKeyStore.getName())) {
+        if (this.getUseConfig() && !KeyStoreConstant.checkKeyStoreFile(ctlKeyStore.getName())) {
             LOG.info("Creating keystore based on given configuration");
             aaaCertProvider.createODLKeyStore();
             aaaCertProvider.createTrustKeyStore();
         }
 
-        final List<SwitchConnectionProvider> listSwitchConnectionProvider = this.getOpenflowSwitchConnectionDependency();
-        for (final SwitchConnectionProvider switchConnProvider : listSwitchConnectionProvider) {
-            if (switchConnProvider.getConfiguration() != null) {
-                LOG.info("Set TLS config then restart the connections ");
-                final ConnectionConfiguration connConfig = switchConnProvider.getConfiguration();
-                final TlsConfiguration tlsConfig = new TlsConfigurationImp(KeyStoreUtilis.keyStorePath + ctlKeyStore.getName(),
-                             KeyStoreUtilis.keyStorePath + trust.getName(), ctlKeyStore.getStorePassword(), trust.getStorePassword(),
-                             trust.getStorePassword(), KeystoreType.JKS, KeystoreType.JKS,
-                             PathType.PATH, PathType.PATH);
-                final ConnectionConfigurationImpl connConfigImpl = new ConnectionConfigurationImpl(connConfig, tlsConfig);
-                switchConnProvider.shutdown();
-                switchConnProvider.setConfiguration(connConfigImpl);
-                switchConnProvider.startup();
-            }
-        }
-
         getBrokerDependency().registerProvider(aaaCertProvider);
         return aaaCertProvider;
     }
 
     @Override
     public void customValidation() {
-        // add custom validation form module attributes here.
+
     }
 
 }
index acf7c52ca256cb2e3abaf7eb9457fd56ab351920..612a5ac9e1df22e36781cfd7ce214c93794dfb5a 100644 (file)
@@ -8,6 +8,7 @@ and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL
 <snapshot>
   <required-capabilities>
       <capability>urn:opendaylight:yang:aaa:cert?module=aaa-cert&amp;revision=2015-11-26</capability>
+      <capability>urn:opendaylight:yang:aaa:cert:mdsal?module=aaa-cert-mdsal&amp;revision=2016-03-21</capability>
       <capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding?module=opendaylight-md-sal-binding&amp;revision=2013-10-28</capability>
   </required-capabilities>
   <configuration>
@@ -20,15 +21,7 @@ and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL
             <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-broker-osgi-registry</type>
             <name>binding-osgi-broker</name>
           </broker>
-          <openflow-switch-connection>
-            <type xmlns:ofSwitch="urn:opendaylight:params:xml:ns:yang:openflow:switch:connection:provider">ofSwitch:openflow-switch-connection-provider</type>
-            <name>openflow-switch-connection-provider-legacy</name>
-          </openflow-switch-connection>
-          <openflow-switch-connection>
-            <type xmlns:ofSwitch="urn:opendaylight:params:xml:ns:yang:openflow:switch:connection:provider">ofSwitch:openflow-switch-connection-provider</type>
-            <name>openflow-switch-connection-provider-default</name>
-          </openflow-switch-connection>
-          <useConfig>true</useConfig>
+          <useConfig>false</useConfig>
           <ctlKeystore>
             <name>ctl.jks</name>
             <alias>controller</alias>
@@ -43,6 +36,14 @@ and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL
             <certFile>cacert.pem</certFile>
           </trustKeystore>
         </module>
+        <module>
+          <type xmlns:prefix="urn:opendaylight:yang:aaa:cert:mdsal">prefix:aaa-cert-mdsal</type>
+          <name>aaa-cert-mdsal</name>
+          <aaa-broker>
+            <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-broker-osgi-registry</type>
+            <name>binding-osgi-broker</name>
+          </aaa-broker>
+        </module>
       </modules>
     </data>
   </configuration>
index 9c4137760814fd9003382e02ccd216d05005f112..19e63de9d3f0743489d95774a3aa0779871804d7 100644 (file)
@@ -23,7 +23,7 @@ import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.Mockito;
 import org.opendaylight.aaa.cert.impl.AaaCertProvider;
-import org.opendaylight.aaa.cert.impl.KeyStoreUtilis;
+import org.opendaylight.aaa.cert.impl.KeyStoreConstant;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rev151126.CtlKeystore;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rev151126.TrustKeystore;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.aaa.cert.rpc.rev151215.GetNodeCertifcateInput;
@@ -43,7 +43,7 @@ public class AaaCertProviderTest {
     private static TrustKeystore trustKeyStore;
 
     private String dummyAlias = "fooAlias";
-    private String dummyCert = KeyStoreUtilis.BEGIN_CERTIFICATE +
+    private String dummyCert = KeyStoreConstant.BEGIN_CERTIFICATE +
                           "MIIDLjCCAhagAwIBAgIELsFzhjANBgkqhkiG9w0BAQUFADBZMQwwCgYDV"+
                           "QQDDANPREwxDDAKBgNVBAsMA0RldjEYMBYGA1UECgwPTGludXhGb3VuZG"+
                           "F0aW9uMRQwEgYDVQQHDAtRQyBNb250cmVhbDELMAkGA1UEBhMCQ0EwHhc"+
@@ -63,11 +63,11 @@ public class AaaCertProviderTest {
                           "OT0fAjQi6Mypje08OstA2sklTSPfYtrDFJUpJW7+5fGic/wf5ITPmMVJl"+
                           "rt6aSStfyOLhCSAWXmU/1Pn1pixltJvaLnd0HYQdhcFOS9XG5LfA3Mlqm"+
                           "ZEwGEjhpmk810dJyRjoCEsokljWyhmJGW6hTK1j+2V+PCHqyawghiTB0jQFRTt2zo="+
-                          KeyStoreUtilis.END_CERTIFICATE;
+                          KeyStoreConstant.END_CERTIFICATE;
 
     @BeforeClass
     public static void setUpBeforeClass() throws Exception {
-        KeyStoreUtilis.keyStorePath = "target" + File.separator + "test" + File.separator;
+        KeyStoreConstant.KEY_STORE_PATH = "target" + File.separator + "test" + File.separator;
         String dName = "CN=ODL, OU=Dev, O=LinuxFoundation, L=QC Montreal, C=CA";
         Security.addProvider(new BouncyCastleProvider());
         ctlKeyStore = new CtlKeystore();
@@ -75,7 +75,7 @@ public class AaaCertProviderTest {
         ctlKeyStore.setDname(dName);
         ctlKeyStore.setName("fooTest.jks");
         ctlKeyStore.setStorePassword("passWord");
-        ctlKeyStore.setValidity(KeyStoreUtilis.defaultValidity);
+        ctlKeyStore.setValidity(KeyStoreConstant.DEFAULT_VALIDITY);
         trustKeyStore = new TrustKeystore();
         trustKeyStore.setAlias("trustTest");
         trustKeyStore.setCertFile("cacert.pem");
@@ -106,7 +106,7 @@ public class AaaCertProviderTest {
         assertTrue(rpc.isSuccessful());
         String certReq = rpc.getResult().getOdlCertReq();
         assertTrue(certReq != null);
-        assertTrue(certReq.contains(KeyStoreUtilis.BEGIN_CERTIFICATE_REQUEST));
+        assertTrue(certReq.contains(KeyStoreConstant.BEGIN_CERTIFICATE_REQUEST));
     }
 
     @Test
index 91e3241ee2e7a593f02101e8f6ae3d23733cd215..ed4fb8f8c6899086368d7ac6240182fd5145a5d4 100644 (file)
@@ -15,7 +15,7 @@ import java.io.File;
 
 import org.junit.BeforeClass;
 import org.junit.Test;
-import org.opendaylight.aaa.cert.impl.KeyStoreUtilis;
+import org.opendaylight.aaa.cert.impl.KeyStoreConstant;
 
 public class KeyStoreUtilisTest {
 
@@ -24,12 +24,12 @@ public class KeyStoreUtilisTest {
 
     @BeforeClass
     public static void setUpBeforeClass() throws Exception {
-        KeyStoreUtilis.keyStorePath = "target" + File.separator + "test" + File.separator;
+        KeyStoreConstant.KEY_STORE_PATH = "target" + File.separator + "test" + File.separator;
     }
 
     @Test
     public void testCreateDir() {
-        final String path = KeyStoreUtilis.createDir(KeyStoreUtilis.keyStorePath);
+        final String path = KeyStoreConstant.createDir(KeyStoreConstant.KEY_STORE_PATH);
         assertTrue(!path.isEmpty());
         final File dir = new File(path);
         assertTrue(dir.exists());
@@ -37,18 +37,18 @@ public class KeyStoreUtilisTest {
 
     @Test
     public void testSaveCert() {
-        assertTrue(KeyStoreUtilis.saveCert(fileName, txt));
+        assertTrue(KeyStoreConstant.saveCert(fileName, txt));
     }
 
     @Test
     public void testCheckKeyStoreFile() {
-        assertTrue(KeyStoreUtilis.checkKeyStoreFile(fileName));
-        assertTrue(!KeyStoreUtilis.checkKeyStoreFile("notExist.txt"));
+        assertTrue(KeyStoreConstant.checkKeyStoreFile(fileName));
+        assertTrue(!KeyStoreConstant.checkKeyStoreFile("notExist.txt"));
     }
 
     @Test
     public void testReadFile() {
-        final String readTxt = KeyStoreUtilis.readFile(fileName);
+        final String readTxt = KeyStoreConstant.readFile(fileName);
         assertEquals(txt, readTxt);
     }
 }
index 74dfcbfb13f040258e0f993119869e4b32a76f3b..095498e8169f5d89f1338d7199ee98d86be7c726 100644 (file)
@@ -17,7 +17,7 @@ import java.security.Security;
 import org.bouncycastle.jce.provider.BouncyCastleProvider;
 import org.junit.BeforeClass;
 import org.junit.Test;
-import org.opendaylight.aaa.cert.impl.KeyStoreUtilis;
+import org.opendaylight.aaa.cert.impl.KeyStoreConstant;
 import org.opendaylight.aaa.cert.impl.ODLKeyTool;
 
 public class ODLKeyToolTest {
@@ -36,7 +36,7 @@ public class ODLKeyToolTest {
 
     @BeforeClass
     public static void setUpBeforeClass() throws Exception {
-        KeyStoreUtilis.keyStorePath = testPath;
+        KeyStoreConstant.KEY_STORE_PATH = testPath;
         odlKeyTool = new ODLKeyTool(testPath);
     }
 
@@ -44,7 +44,7 @@ public class ODLKeyToolTest {
     public void testCreateKeyStoreWithSelfSignCert() {
         final String dName = "CN=ODL, OU=Dev, O=LinuxFoundation, L=QC Montreal, C=CA";
         assertTrue(odlKeyTool.createKeyStoreWithSelfSignCert(keyStore, passwd, dName, alias,
-                KeyStoreUtilis.defaultValidity));
+                KeyStoreConstant.DEFAULT_VALIDITY));
     }
 
     @Test
@@ -52,30 +52,30 @@ public class ODLKeyToolTest {
         String cert = odlKeyTool.getCertificate(keyStore, passwd, alias, false);
         assertTrue(cert != null && cert.length() > 0);
         cert = odlKeyTool.getCertificate(keyStore, passwd, alias, true);
-        assertTrue(cert.contains(KeyStoreUtilis.BEGIN_CERTIFICATE));
+        assertTrue(cert.contains(KeyStoreConstant.BEGIN_CERTIFICATE));
     }
 
     @Test
     public void testGenerateCertificateReq() {
         String certReq = odlKeyTool.generateCertificateReq(keyStore, passwd, alias,
-                KeyStoreUtilis.defaultSignAlg, false);
+                KeyStoreConstant.DEFAULT_SIGN_ALG, false);
         assertTrue(certReq != null && certReq.length() > 0);
         certReq = odlKeyTool.generateCertificateReq(keyStore, passwd, alias,
-                KeyStoreUtilis.defaultSignAlg, true);
-        assertTrue(certReq.contains(KeyStoreUtilis.BEGIN_CERTIFICATE_REQUEST));
+                KeyStoreConstant.DEFAULT_SIGN_ALG, true);
+        assertTrue(certReq.contains(KeyStoreConstant.BEGIN_CERTIFICATE_REQUEST));
     }
 
     @Test
     public void testCreateKeyStoreImportCert() {
         assertTrue(odlKeyTool.createKeyStoreImportCert(trustKeyStore, passwd, null, alias));
         final String cert = odlKeyTool.getCertificate(keyStore, passwd, alias, false);
-        KeyStoreUtilis.saveCert(certFile, cert);
+        KeyStoreConstant.saveCert(certFile, cert);
         assertTrue(odlKeyTool.createKeyStoreImportCert(trustKeyStore, passwd, certFile, alias));
     }
 
     @Test
     public void testAddCertificate() {
-        final String cert = KeyStoreUtilis.readFile(certFile);
+        final String cert = KeyStoreConstant.readFile(certFile);
         assertTrue(odlKeyTool.addCertificate(trustKeyStore, passwd, cert, alias));
     }
 
diff --git a/aaa-cert/src/main/yang/aaa-cert-mdsal.yang b/aaa-cert/src/main/yang/aaa-cert-mdsal.yang
new file mode 100644 (file)
index 0000000..ed7da41
--- /dev/null
@@ -0,0 +1,147 @@
+/*
+Copyright (c) 2016 Inocybe Technology 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 INTERNAL
+*/
+module aaa-cert-mdsal {
+    yang-version 1;
+    namespace "urn:opendaylight:yang:aaa:cert:mdsal";
+    prefix "aaa-cert-mdsal";
+
+    import config {
+        prefix config;
+        revision-date 2013-04-05;
+    }
+
+    import opendaylight-md-sal-binding {
+        prefix md-sal-binding;
+        revision-date 2013-10-28;
+    }
+
+    revision 2016-03-21 {
+        description "Initial revision";
+    }
+
+    description
+        "Yang model definition for aaa certificate using MDSAL";
+
+    contact
+        "melserngawy@inocybe.com";
+
+    grouping node-certificate {
+        leaf alias {
+            description "network node certificate alias";
+            type string;
+        }
+        leaf x500-certificate {
+            description "network node certificate";
+            type string;
+        }
+    }
+
+    grouping keystore {
+        leaf name {
+            description "keystore name";
+            type string;
+        }
+        leaf alias {
+            description "key alias";
+            type string;
+        }
+        leaf store-password {
+            description "keystore password";
+            type string;
+        }
+        leaf dname {
+            description "X.500 Distinguished Names should be in the following formate
+                CN=commonName
+                OU=organizationUnit
+                O=organizationName
+                L=localityName
+                S=stateName
+                C=country";
+            type string;
+        }
+        leaf validity {
+            description "validity";
+            type int32;
+        }
+        leaf key-alg {
+            description "supported key geneartion algorithmes are DSA and RSA";
+            type string;
+        }
+        leaf sign-alg {
+            description "supported sign algorithmes for DSA the default sign Alg is SHA1withDSA and for RSA the
+                default sign Alg is MD5withRSA";
+            type string;
+        }
+        leaf keysize {
+            description "key size is 1024 or 2048";
+            type int32;
+        }
+        leaf keystoreFile {
+            description "keystore file as Binary";
+            type binary;
+        }
+        list certificates {
+            description "list of certificates that exist in the keystore";
+            uses node-certificate;
+        }
+    }
+
+    grouping cipher-suite {
+        list cipher-suites {
+             leaf suiteName {
+                 type string;
+             }
+        }
+    }
+
+    grouping ssl-data {
+        leaf bundle-name {
+            description "bundle name";
+            type string;
+            mandatory true;
+        }
+        container odl-keystore {
+            uses keystore;
+        }
+        container trust-keystore {
+            uses keystore;
+        }
+        uses cipher-suite;
+    }
+
+    container key-stores {
+        leaf id {
+            type string;
+            mandatory true;
+        }
+        list ssl-data {
+            key bundle-name;
+            uses ssl-data;
+        }
+    }
+
+    identity aaa-cert-mdsal {
+        base config:module-type;
+        config:java-name-prefix AaaCertMdsalProvider;
+    }
+
+    augment "/config:modules/config:module/config:configuration" {
+        case aaa-cert-mdsal {
+            when "/config:modules/config:module/config:type = 'aaa-cert-mdsal'";
+            container aaa-broker {
+                uses config:service-ref {
+                    refine type {
+                        mandatory false;
+                        config:required-identity md-sal-binding:binding-broker-osgi-registry;
+                    }
+                }
+            }
+        }
+    }
+
+}
\ No newline at end of file
index 5d1aa694bf8455133555add1e0d94107a172559e..84ae65703957f03e9b06d8a014f71d4df54dcca2 100644 (file)
@@ -22,17 +22,6 @@ module aaa-cert-rpc {
             "Initial revision.";
     }
 
-    grouping node-certificate {
-        leaf alias {
-            description "ovs node certificate alias";
-            type string;
-        }
-        leaf certificate {
-            description "ovs node certificate";
-            type string;
-        }
-    }
-
     rpc getODLCertificate {
         description
             "Get the ctl.jks keystore certificate";
index 32a16ff20620d8a308b28754beeecb4b1836205c..75a42f0f7b5b183a8487870faab0774067c993d0 100644 (file)
@@ -21,11 +21,6 @@ module aaa-cert {
         revision-date 2013-10-28;
     }
 
-    import openflow-switch-connection-provider {
-        prefix openflow-switch-connection-provider;
-        revision-date 2014-03-28;
-    }
-
     description
         "Service definition for aaa certificate";
 
@@ -53,14 +48,6 @@ module aaa-cert {
                     }
                 }
             }
-            list openflow-switch-connection {
-                uses config:service-ref {
-                    refine type {
-                        mandatory true;
-                        config:required-identity openflow-switch-connection-provider:openflow-switch-connection-provider;
-                    }
-                }
-            }
             leaf useConfig {
                 description "Use the configuration data to create the keystores";
                 type boolean;
index 6814b8794e7ff9435ba25f4297f1410af5588a34..40516f5c8f7f5fd3025a55e20785bb3e88cc61fa 100644 (file)
@@ -12,6 +12,12 @@ package org.opendaylight.aaa.encrypt;
  */
 
 public interface AAAEncryptionService {
+
     public String encrypt(String data);
+
     public String decrypt(String encData);
+
+    public byte[] encrypt(byte[] data);
+
+    public byte[] decrypt(byte[] encData);
 }
index 70e1cc6fa6141c42b04390dc4e43e10c1dbeed2c..7f238996802431c7e69a5530776e10cd455d91ca 100644 (file)
@@ -89,7 +89,7 @@ public class AAAEncryptionServiceImpl implements AAAEncryptionService {
                 return encryptTag + cryptostring;
             }
         } catch (IllegalBlockSizeException | BadPaddingException e) {
-            LOG.error("Failed to encrypt data.",e);
+            LOG.error("Failed to encrypt data.", e);
         }
 
         return data;
@@ -98,7 +98,7 @@ public class AAAEncryptionServiceImpl implements AAAEncryptionService {
     @Override
     public String decrypt(String encData) {
         if (key == null || encData == null || encData.length() == 0 || !encData.startsWith(encryptTag)) {
-            LOG.warn("String {} was not decrypted.",encData);
+            LOG.warn("String {} was not decrypted.", encData);
             return encData;
         }
 
@@ -107,7 +107,40 @@ public class AAAEncryptionServiceImpl implements AAAEncryptionService {
             byte[] clearbytes = decryptCipher.doFinal(cryptobytes);
             return new String(clearbytes);
         } catch (IllegalBlockSizeException | BadPaddingException e){
-            LOG.error("Failed to decrypt encoded data",e);
+            LOG.error("Failed to decrypt encoded data", e);
+        }
+        return encData;
+    }
+
+    @Override
+    public byte[] encrypt(byte[] data) {
+        //We could not instantiate the encryption key, hence no encryption or decryption will be done.
+        if (key == null) {
+            LOG.warn("Encryption Key is NULL, will not encrypt data.");
+            return data;
+        }
+
+        try {
+            synchronized(encryptCipher) {
+                return encryptCipher.doFinal(data);
+            }
+        } catch (IllegalBlockSizeException | BadPaddingException e) {
+            LOG.error("Failed to encrypt data.", e);
+        }
+        return data;
+    }
+
+    @Override
+    public byte[] decrypt(byte[] encData) {
+        if (encData == null) {
+            LOG.warn("encData is null.");
+            return encData;
+        }
+
+        try {
+            return decryptCipher.doFinal(encData);
+        } catch (IllegalBlockSizeException | BadPaddingException e){
+            LOG.error("Failed to decrypt encoded data", e);
         }
         return encData;
     }
index e71977ed655a669ef23403b22395a296f7c8aea0..05ce563d3891b88ce8bfa57157fe3858c21a1f70 100644 (file)
@@ -35,7 +35,7 @@ and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL
     </dependencyManagement>
 
   <properties>
-    <openflowplugin.version>0.3.0-SNAPSHOT</openflowplugin.version>
+    <mdsal.model.version>0.9.0-SNAPSHOT</mdsal.model.version>
     <controller.mdsal.version>1.4.0-SNAPSHOT</controller.mdsal.version>
   </properties>
 
@@ -57,10 +57,14 @@ and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL
       <type>xml</type>
     </dependency>
     <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>features-mdsal</artifactId>
-      <classifier>features</classifier>
+      <groupId>org.opendaylight.aaa</groupId>
+      <artifactId>aaa-encrypt-service</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.aaa</groupId>
+      <artifactId>aaa-encrypt-service</artifactId>
       <type>xml</type>
+      <classifier>config</classifier>
     </dependency>
     <dependency>
     <groupId>org.apache.maven</groupId>
@@ -69,11 +73,12 @@ and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL
       <scope>test</scope>
     </dependency>
     <dependency>
-      <groupId>org.opendaylight.openflowplugin</groupId>
-      <artifactId>features-openflowplugin</artifactId>
-      <version>${openflowplugin.version}</version>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>features-mdsal</artifactId>
       <classifier>features</classifier>
+      <version>${controller.mdsal.version}</version>
       <type>xml</type>
+      <scope>runtime</scope>
     </dependency>
     <dependency>
       <groupId>org.bouncycastle</groupId>
index 9f9d03d8b92e3da0e07be9717cbdede2f261062b..3ff7f3e7b276dbcf59eb1f9bea1b503e993759c2 100644 (file)
@@ -12,12 +12,11 @@ and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL
 
     <repository>mvn:org.opendaylight.mdsal/features-mdsal/{{VERSION}}/xml/features</repository>
     <repository>mvn:org.opendaylight.aaa/features-aaa/{{VERSION}}/xml/features</repository>
-    <repository>mvn:org.opendaylight.openflowplugin/features-openflowplugin/{{VERSION}}/xml/features</repository>
 
     <feature name='odl-aaa-cert' description='OpenDaylight :: AAA :: aaa opendaylight certificate Plugin'
              version='${project.version}'>
         <feature version='${controller.mdsal.version}'>odl-mdsal-broker</feature>
-        <feature version="${openflowplugin.version}">odl-openflowplugin-southbound</feature>
+        <feature version='${project.version}'>odl-aaa-encryption-service</feature>
 
         <bundle>mvn:org.bouncycastle/bcprov-jdk15on/{{VERSION}}</bundle>
         <bundle>mvn:commons-codec/commons-codec/{{VERSION}}</bundle>