2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.protocol_plugin.openflow.core.internal;
11 import java.io.FileInputStream;
12 import java.io.FileNotFoundException;
13 import java.io.IOException;
14 import java.nio.ByteBuffer;
15 import java.nio.channels.AsynchronousCloseException;
16 import java.nio.channels.SelectionKey;
17 import java.nio.channels.Selector;
18 import java.nio.channels.SocketChannel;
19 import java.security.KeyStore;
20 import java.security.SecureRandom;
21 import java.util.List;
23 import javax.net.ssl.KeyManagerFactory;
24 import javax.net.ssl.SSLContext;
25 import javax.net.ssl.SSLEngine;
26 import javax.net.ssl.SSLEngineResult;
27 import javax.net.ssl.SSLEngineResult.HandshakeStatus;
28 import javax.net.ssl.SSLSession;
29 import javax.net.ssl.TrustManagerFactory;
31 import org.opendaylight.controller.protocol_plugin.openflow.core.IMessageReadWrite;
32 import org.openflow.protocol.OFMessage;
33 import org.openflow.protocol.factory.BasicFactory;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
38 * This class implements methods to read/write messages over an established
39 * socket channel. The data exchange is encrypted/decrypted by SSLEngine.
41 public class SecureMessageReadWriteService implements IMessageReadWrite {
42 private static final Logger logger = LoggerFactory
43 .getLogger(SecureMessageReadWriteService.class);
45 private Selector selector;
46 private SocketChannel socket;
47 private BasicFactory factory;
49 private SSLEngine sslEngine;
50 private SSLEngineResult sslEngineResult; // results from sslEngine last operation
51 private ByteBuffer myAppData; // clear text message to be sent
52 private ByteBuffer myNetData; // encrypted message to be sent
53 private ByteBuffer peerAppData; // clear text message received from the
55 private ByteBuffer peerNetData; // encrypted message from the switch
56 private FileInputStream kfd = null, tfd = null;
58 public SecureMessageReadWriteService(SocketChannel socket, Selector selector)
61 this.selector = selector;
62 this.factory = new BasicFactory();
65 createSecureChannel(socket);
66 createBuffers(sslEngine);
67 } catch (Exception e) {
68 logger.warn("Failed to setup TLS connection {} {}", socket, e);
75 * Bring up secure channel using SSL Engine
81 private void createSecureChannel(SocketChannel socket) throws Exception {
82 String keyStoreFile = System.getProperty("controllerKeyStore");
83 String keyStorePassword = System
84 .getProperty("controllerKeyStorePassword");
85 String trustStoreFile = System.getProperty("controllerTrustStore");
86 String trustStorePassword = System
87 .getProperty("controllerTrustStorePassword");
89 if (keyStoreFile != null) {
90 keyStoreFile = keyStoreFile.trim();
92 if ((keyStoreFile == null) || keyStoreFile.isEmpty()) {
93 throw new FileNotFoundException("TLS KeyStore file not found.");
95 if (keyStorePassword != null) {
96 keyStorePassword = keyStorePassword.trim();
98 if ((keyStorePassword == null) || keyStorePassword.isEmpty()) {
99 throw new FileNotFoundException("TLS KeyStore Password not provided.");
101 if (trustStoreFile != null) {
102 trustStoreFile = trustStoreFile.trim();
104 if ((trustStoreFile == null) || trustStoreFile.isEmpty()) {
105 throw new FileNotFoundException("TLS TrustStore file not found");
107 if (trustStorePassword != null) {
108 trustStorePassword = trustStorePassword.trim();
110 if ((trustStorePassword == null) || trustStorePassword.isEmpty()) {
111 throw new FileNotFoundException("TLS TrustStore Password not provided.");
114 KeyStore ks = KeyStore.getInstance("JKS");
115 KeyStore ts = KeyStore.getInstance("JKS");
116 KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
117 TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
118 kfd = new FileInputStream(keyStoreFile);
119 tfd = new FileInputStream(trustStoreFile);
120 ks.load(kfd, keyStorePassword.toCharArray());
121 ts.load(tfd, trustStorePassword.toCharArray());
122 kmf.init(ks, keyStorePassword.toCharArray());
125 SecureRandom random = new SecureRandom();
128 SSLContext sslContext = SSLContext.getInstance("TLS");
129 sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), random);
130 sslEngine = sslContext.createSSLEngine();
131 sslEngine.setUseClientMode(false);
132 sslEngine.setNeedClientAuth(true);
133 sslEngine.setEnabledCipherSuites(new String[] {
134 "SSL_RSA_WITH_RC4_128_MD5",
135 "SSL_RSA_WITH_RC4_128_SHA",
136 "TLS_RSA_WITH_AES_128_CBC_SHA",
137 "TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
138 "TLS_DHE_DSS_WITH_AES_128_CBC_SHA",
139 "SSL_RSA_WITH_3DES_EDE_CBC_SHA",
140 "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA",
141 "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA",
142 "SSL_RSA_WITH_DES_CBC_SHA",
143 "SSL_DHE_RSA_WITH_DES_CBC_SHA",
144 "SSL_DHE_DSS_WITH_DES_CBC_SHA",
145 "SSL_RSA_EXPORT_WITH_RC4_40_MD5",
146 "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA",
147 "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA",
148 "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA",
149 "TLS_EMPTY_RENEGOTIATION_INFO_SCSV"});
151 // Do initial handshake
152 doHandshake(socket, sslEngine);
154 this.socket.register(this.selector, SelectionKey.OP_READ);
158 * Sends the OF message out over the socket channel. The message is
159 * encrypted by SSL Engine.
162 * OF message to be sent
166 public void asyncSend(OFMessage msg) throws Exception {
167 synchronized (myAppData) {
168 int msgLen = msg.getLengthU();
169 if (myAppData.remaining() < msgLen) {
170 // increase the buffer size so that it can contain this message
171 ByteBuffer newBuffer = ByteBuffer.allocateDirect(myAppData
172 .capacity() + msgLen);
174 newBuffer.put(myAppData);
175 myAppData = newBuffer;
178 synchronized (myAppData) {
179 msg.writeTo(myAppData);
181 sslEngineResult = sslEngine.wrap(myAppData, myNetData);
182 logger.trace("asyncSend sslEngine wrap: {}", sslEngineResult);
183 runDelegatedTasks(sslEngineResult, sslEngine);
185 if (!socket.isOpen()) {
190 socket.write(myNetData);
191 if (myNetData.hasRemaining()) {
197 if (myAppData.hasRemaining()) {
199 this.socket.register(this.selector, SelectionKey.OP_WRITE, this);
202 this.socket.register(this.selector, SelectionKey.OP_READ, this);
205 logger.trace("Message sent: {}", msg);
210 * Resumes sending the remaining messages in the outgoing buffer
215 public void resumeSend() throws Exception {
216 synchronized (myAppData) {
218 sslEngineResult = sslEngine.wrap(myAppData, myNetData);
219 logger.trace("resumeSend sslEngine wrap: {}", sslEngineResult);
220 runDelegatedTasks(sslEngineResult, sslEngine);
222 if (!socket.isOpen()) {
227 socket.write(myNetData);
228 if (myNetData.hasRemaining()) {
234 if (myAppData.hasRemaining()) {
236 this.socket.register(this.selector, SelectionKey.OP_WRITE, this);
239 this.socket.register(this.selector, SelectionKey.OP_READ, this);
245 * Reads the incoming network data from the socket, decryptes them and then
246 * retrieves the OF messages.
248 * @return list of OF messages
252 public List<OFMessage> readMessages() throws Exception {
253 if (!socket.isOpen()) {
257 List<OFMessage> msgs = null;
261 bytesRead = socket.read(peerNetData);
263 logger.debug("Message read operation failed");
264 throw new AsynchronousCloseException();
269 sslEngineResult = sslEngine.unwrap(peerNetData, peerAppData);
270 if (peerNetData.hasRemaining()) {
271 peerNetData.compact();
275 logger.trace("sslEngine unwrap result: {}", sslEngineResult);
276 runDelegatedTasks(sslEngineResult, sslEngine);
277 } while ((sslEngineResult.getStatus() == SSLEngineResult.Status.OK)
278 && peerNetData.hasRemaining() && (--countDown > 0));
280 if (countDown == 0) {
281 logger.trace("countDown reaches 0. peerNetData pos {} lim {}",
282 peerNetData.position(), peerNetData.limit());
286 msgs = factory.parseMessages(peerAppData);
287 if (peerAppData.hasRemaining()) {
288 peerAppData.compact();
293 this.socket.register(this.selector, SelectionKey.OP_READ, this);
299 * If the result indicates that we have outstanding tasks to do, go ahead
300 * and run them in this thread.
302 private void runDelegatedTasks(SSLEngineResult result, SSLEngine engine)
305 if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
307 while ((runnable = engine.getDelegatedTask()) != null) {
308 logger.debug("\trunning delegated task...");
311 HandshakeStatus hsStatus = engine.getHandshakeStatus();
312 if (hsStatus == HandshakeStatus.NEED_TASK) {
313 throw new Exception("handshake shouldn't need additional tasks");
315 logger.debug("\tnew HandshakeStatus: {}", hsStatus);
319 private void doHandshake(SocketChannel socket, SSLEngine engine)
321 SSLSession session = engine.getSession();
322 ByteBuffer myAppData = ByteBuffer.allocate(session
323 .getApplicationBufferSize());
324 ByteBuffer peerAppData = ByteBuffer.allocate(session
325 .getApplicationBufferSize());
326 ByteBuffer myNetData = ByteBuffer.allocate(session
327 .getPacketBufferSize());
328 ByteBuffer peerNetData = ByteBuffer.allocate(session
329 .getPacketBufferSize());
332 engine.beginHandshake();
333 SSLEngineResult.HandshakeStatus hs = engine.getHandshakeStatus();
335 // Process handshaking message
336 while (hs != SSLEngineResult.HandshakeStatus.FINISHED
337 && hs != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
340 // Receive handshaking data from peer
341 if (socket.read(peerNetData) < 0) {
342 throw new AsynchronousCloseException();
345 // Process incoming handshaking data
347 SSLEngineResult res = engine.unwrap(peerNetData, peerAppData);
348 peerNetData.compact();
349 hs = res.getHandshakeStatus();
352 switch (res.getStatus()) {
360 // Empty the local network packet buffer.
363 // Generate handshaking data
364 res = engine.wrap(myAppData, myNetData);
365 hs = res.getHandshakeStatus();
368 switch (res.getStatus()) {
372 // Send the handshaking data to peer
373 while (myNetData.hasRemaining()) {
374 if (socket.write(myNetData) < 0) {
375 throw new AsynchronousCloseException();
383 // Handle blocking tasks
385 while ((runnable = engine.getDelegatedTask()) != null) {
386 logger.debug("\trunning delegated task...");
389 hs = engine.getHandshakeStatus();
390 if (hs == HandshakeStatus.NEED_TASK) {
392 "handshake shouldn't need additional tasks");
394 logger.debug("\tnew HandshakeStatus: {}", hs);
400 private void createBuffers(SSLEngine engine) {
401 SSLSession session = engine.getSession();
402 this.myAppData = ByteBuffer
403 .allocate(session.getApplicationBufferSize());
404 this.peerAppData = ByteBuffer.allocate(session
405 .getApplicationBufferSize());
406 this.myNetData = ByteBuffer.allocate(session.getPacketBufferSize());
407 this.peerNetData = ByteBuffer.allocate(session.getPacketBufferSize());
411 public void stop() throws IOException {
412 this.sslEngine = null;
413 this.sslEngineResult = null;
414 this.myAppData = null;
415 this.myNetData = null;
416 this.peerAppData = null;
417 this.peerNetData = null;
419 if (this.kfd != null) {
423 if (this.tfd != null) {