securing the openflow channel

Change-Id: Ifae379e7e372baeb14a4ad919f014c64752c3a7f
diff --git a/openflow/ctl/src/main/java/org/onosproject/openflow/controller/impl/Controller.java b/openflow/ctl/src/main/java/org/onosproject/openflow/controller/impl/Controller.java
index 3b473b8..9d35515 100644
--- a/openflow/ctl/src/main/java/org/onosproject/openflow/controller/impl/Controller.java
+++ b/openflow/ctl/src/main/java/org/onosproject/openflow/controller/impl/Controller.java
@@ -39,9 +39,15 @@
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
+import javax.net.ssl.TrustManagerFactory;
+import java.io.FileInputStream;
 import java.lang.management.ManagementFactory;
 import java.lang.management.RuntimeMXBean;
 import java.net.InetSocketAddress;
+import java.security.KeyStore;
 import java.util.Dictionary;
 import java.util.HashMap;
 import java.util.List;
@@ -66,6 +72,8 @@
 
     protected static final OFFactory FACTORY13 = OFFactories.getFactory(OFVersion.OF_13);
     protected static final OFFactory FACTORY10 = OFFactories.getFactory(OFVersion.OF_10);
+    private static final boolean TLS_DISABLED = false;
+    private static final short MIN_KS_LENGTH = 6;
 
     protected HashMap<String, String> controllerNodeIPsCache;
 
@@ -82,9 +90,16 @@
 
     private NioServerSocketChannelFactory execFactory;
 
+    protected String ksLocation;
+    protected String tsLocation;
+    protected char[] ksPwd;
+    protected char[] tsPwd;
+    private SSLEngine serverSSLEngine;
+
     // Perf. related configuration
     protected static final int SEND_BUFFER_SIZE = 4 * 1024 * 1024;
     private DriverService driverService;
+    private boolean enableOFTLS = TLS_DISABLED;
 
     // ***************
     // Getters/Setters
@@ -134,7 +149,7 @@
             bootstrap.setOption("child.sendBufferSize", Controller.SEND_BUFFER_SIZE);
 
             ChannelPipelineFactory pfact =
-                    new OpenflowPipelineFactory(this, null);
+                    new OpenflowPipelineFactory(this, null, serverSSLEngine);
             bootstrap.setPipelineFactory(pfact);
             cg = new DefaultChannelGroup();
             openFlowPorts.forEach(port -> {
@@ -189,6 +204,68 @@
         this.controllerNodeIPsCache = new HashMap<>();
 
         this.systemStartTime = System.currentTimeMillis();
+
+        try {
+            getTLSParameters();
+            if (enableOFTLS) {
+                initSSL();
+            }
+        } catch (Exception ex) {
+            log.error("SSL init failed: {}", ex.getMessage());
+        }
+
+    }
+
+    private void getTLSParameters() {
+        String tempString = System.getProperty("enableOFTLS");
+        enableOFTLS = Strings.isNullOrEmpty(tempString) ? TLS_DISABLED : Boolean.parseBoolean(tempString);
+        log.info("OpenFlow Security is {}", enableOFTLS ? "enabled" : "disabled");
+        if (enableOFTLS) {
+            ksLocation = System.getProperty("javax.net.ssl.keyStore");
+            if (Strings.isNullOrEmpty(ksLocation)) {
+                enableOFTLS = TLS_DISABLED;
+                return;
+            }
+            tsLocation = System.getProperty("javax.net.ssl.trustStore");
+            if (Strings.isNullOrEmpty(tsLocation)) {
+                enableOFTLS = TLS_DISABLED;
+                return;
+            }
+            ksPwd = System.getProperty("javax.net.ssl.keyStorePassword").toCharArray();
+            if (MIN_KS_LENGTH > ksPwd.length) {
+                enableOFTLS = TLS_DISABLED;
+                return;
+            }
+            tsPwd = System.getProperty("javax.net.ssl.trustStorePassword").toCharArray();
+            if (MIN_KS_LENGTH > tsPwd.length) {
+                enableOFTLS = TLS_DISABLED;
+                return;
+            }
+        }
+    }
+
+    private void initSSL() throws Exception {
+
+        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
+        KeyStore ts = KeyStore.getInstance("JKS");
+        ts.load(new FileInputStream(tsLocation), tsPwd);
+        tmFactory.init(ts);
+
+        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+        KeyStore ks = KeyStore.getInstance("JKS");
+        ks.load(new FileInputStream(ksLocation), ksPwd);
+        kmf.init(ks, ksPwd);
+
+        SSLContext serverContext = SSLContext.getInstance("TLS");
+        serverContext.init(kmf.getKeyManagers(), tmFactory.getTrustManagers(), null);
+
+        serverSSLEngine = serverContext.createSSLEngine();
+
+        serverSSLEngine.setNeedClientAuth(true);
+        serverSSLEngine.setUseClientMode(false);
+        serverSSLEngine.setEnabledProtocols(serverSSLEngine.getSupportedProtocols());
+        serverSSLEngine.setEnabledCipherSuites(serverSSLEngine.getSupportedCipherSuites());
+        serverSSLEngine.setEnableSessionCreation(true);
     }
 
     // **************
diff --git a/openflow/ctl/src/main/java/org/onosproject/openflow/controller/impl/OpenflowPipelineFactory.java b/openflow/ctl/src/main/java/org/onosproject/openflow/controller/impl/OpenflowPipelineFactory.java
index c7ba105..1467520 100644
--- a/openflow/ctl/src/main/java/org/onosproject/openflow/controller/impl/OpenflowPipelineFactory.java
+++ b/openflow/ctl/src/main/java/org/onosproject/openflow/controller/impl/OpenflowPipelineFactory.java
@@ -27,6 +27,10 @@
 import org.jboss.netty.util.ExternalResourceReleasable;
 import org.jboss.netty.util.HashedWheelTimer;
 import org.jboss.netty.util.Timer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.net.ssl.SSLEngine;
 
 /**
  * Creates a ChannelPipeline for a server-side openflow channel.
@@ -34,6 +38,9 @@
 public class OpenflowPipelineFactory
     implements ChannelPipelineFactory, ExternalResourceReleasable {
 
+    private final Logger log = LoggerFactory.getLogger(getClass());
+
+    private final SSLEngine sslEngine;
     protected Controller controller;
     protected ThreadPoolExecutor pipelineExecutor;
     protected Timer timer;
@@ -41,13 +48,15 @@
     protected ReadTimeoutHandler readTimeoutHandler;
 
     public OpenflowPipelineFactory(Controller controller,
-                                   ThreadPoolExecutor pipelineExecutor) {
+                                   ThreadPoolExecutor pipelineExecutor,
+                                   SSLEngine sslEngine) {
         super();
         this.controller = controller;
         this.pipelineExecutor = pipelineExecutor;
         this.timer = new HashedWheelTimer();
         this.idleHandler = new IdleStateHandler(timer, 20, 25, 0);
         this.readTimeoutHandler = new ReadTimeoutHandler(timer, 30);
+        this.sslEngine = sslEngine;
     }
 
     @Override
@@ -55,6 +64,13 @@
         OFChannelHandler handler = new OFChannelHandler(controller);
 
         ChannelPipeline pipeline = Channels.pipeline();
+        if (sslEngine != null) {
+            log.info("OpenFlow SSL enabled.");
+            pipeline.addLast("ssl",
+                             new org.jboss.netty.handler.ssl.SslHandler(sslEngine));
+        } else {
+            log.info("OpenFlow SSL disabled");
+        }
         pipeline.addLast("ofmessagedecoder", new OFMessageDecoder());
         pipeline.addLast("ofmessageencoder", new OFMessageEncoder());
         pipeline.addLast("idle", idleHandler);