View Javadoc
1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License.
18   *
19   */
20  package org.apache.mina.filter.ssl;
21  
22  import java.net.InetSocketAddress;
23  import java.util.ArrayList;
24  import java.util.List;
25  
26  import javax.net.ssl.SSLContext;
27  import javax.net.ssl.SSLEngine;
28  import javax.net.ssl.SSLException;
29  import javax.net.ssl.SSLHandshakeException;
30  import javax.net.ssl.SSLSession;
31  
32  import org.apache.mina.core.buffer.IoBuffer;
33  import org.apache.mina.core.filterchain.IoFilter;
34  import org.apache.mina.core.filterchain.IoFilterAdapter;
35  import org.apache.mina.core.filterchain.IoFilterChain;
36  import org.apache.mina.core.future.DefaultWriteFuture;
37  import org.apache.mina.core.future.IoFuture;
38  import org.apache.mina.core.future.IoFutureListener;
39  import org.apache.mina.core.future.WriteFuture;
40  import org.apache.mina.core.service.IoAcceptor;
41  import org.apache.mina.core.service.IoHandler;
42  import org.apache.mina.core.session.AttributeKey;
43  import org.apache.mina.core.session.IoSession;
44  import org.apache.mina.core.write.DefaultWriteRequest;
45  import org.apache.mina.core.write.WriteRequest;
46  import org.apache.mina.core.write.WriteToClosedSessionException;
47  import org.slf4j.Logger;
48  import org.slf4j.LoggerFactory;
49  
50  /**
51   * An SSL filter that encrypts and decrypts the data exchanged in the session.
52   * Adding this filter triggers SSL handshake procedure immediately by sending
53   * a SSL 'hello' message, so you don't need to call
54   * {@link #startSsl(IoSession)} manually unless you are implementing StartTLS
55   * (see below).  If you don't want the handshake procedure to start
56   * immediately, please specify {@code false} as {@code autoStart} parameter in
57   * the constructor.
58   * <p>
59   * This filter uses an {@link SSLEngine} which was introduced in Java 5, so
60   * Java version 5 or above is mandatory to use this filter. And please note that
61   * this filter only works for TCP/IP connections.
62   *
63   * <h2>Implementing StartTLS</h2>
64   * <p>
65   * You can use {@link #DISABLE_ENCRYPTION_ONCE} attribute to implement StartTLS:
66   * <pre>
67   * public void messageReceived(IoSession session, Object message) {
68   *    if (message instanceof MyStartTLSRequest) {
69   *        // Insert SSLFilter to get ready for handshaking
70   *        session.getFilterChain().addFirst(sslFilter);
71   *
72   *        // Disable encryption temporarily.
73   *        // This attribute will be removed by SSLFilter
74   *        // inside the Session.write() call below.
75   *        session.setAttribute(SSLFilter.DISABLE_ENCRYPTION_ONCE, Boolean.TRUE);
76   *
77   *        // Write StartTLSResponse which won't be encrypted.
78   *        session.write(new MyStartTLSResponse(OK));
79   *
80   *        // Now DISABLE_ENCRYPTION_ONCE attribute is cleared.
81   *        assert session.getAttribute(SSLFilter.DISABLE_ENCRYPTION_ONCE) == null;
82   *    }
83   * }
84   * </pre>
85   *
86   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
87   * @org.apache.xbean.XBean
88   */
89  public class SslFilter extends IoFilterAdapter {
90      /** The logger */
91      private static final Logger LOGGER = LoggerFactory.getLogger(SslFilter.class);
92  
93      /**
94       * A session attribute key that stores underlying {@link SSLSession}
95       * for each session.
96       */
97      public static final AttributeKeyteKey.html#AttributeKey">AttributeKey SSL_SESSION = new AttributeKey(SslFilter.class, "session");
98  
99      /**
100      * A session attribute key that makes next one write request bypass
101      * this filter (not encrypting the data).  This is a marker attribute,
102      * which means that you can put whatever as its value. ({@link Boolean#TRUE}
103      * is preferred.)  The attribute is automatically removed from the session
104      * attribute map as soon as {@link IoSession#write(Object)} is invoked,
105      * and therefore should be put again if you want to make more messages
106      * bypass this filter.  This is especially useful when you implement
107      * StartTLS.
108      */
109     public static final AttributeKeyttributeKey">AttributeKey DISABLE_ENCRYPTION_ONCE = new AttributeKey(SslFilter.class, "disableOnce");
110 
111     /**
112      * A session attribute key that makes this filter to emit a
113      * {@link IoHandler#messageReceived(IoSession, Object)} event with a
114      * special message ({@link SslEvent#SECURED} or {@link SslEvent#UNSECURED}).
115      * This is a marker attribute, which means that you can put whatever as its
116      * value. ({@link Boolean#TRUE} is preferred.)  By default, this filter
117      * doesn't emit any events related with SSL session flow control.
118      */
119     public static final AttributeKey.html#AttributeKey">AttributeKey USE_NOTIFICATION = new AttributeKey(SslFilter.class, "useNotification");
120 
121     /**
122      * A session attribute key that should be set to an {@link InetSocketAddress}.
123      * Setting this attribute causes
124      * {@link SSLContext#createSSLEngine(String, int)} to be called passing the
125      * hostname and port of the {@link InetSocketAddress} to get an
126      * {@link SSLEngine} instance. If not set {@link SSLContext#createSSLEngine()}
127      * will be called.
128      * <br>
129      * Using this feature {@link SSLSession} objects may be cached and reused
130      * when in client mode.
131      *
132      * @see SSLContext#createSSLEngine(String, int)
133      */
134     public static final AttributeKeyeKey.html#AttributeKey">AttributeKey PEER_ADDRESS = new AttributeKey(SslFilter.class, "peerAddress");
135 
136     /** An attribute containing the next filter */
137     private static final AttributeKeyteKey.html#AttributeKey">AttributeKey NEXT_FILTER = new AttributeKey(SslFilter.class, "nextFilter");
138 
139     private static final AttributeKeyteKey.html#AttributeKey">AttributeKey SSL_HANDLER = new AttributeKey(SslFilter.class, "handler");
140 
141     /** The SslContext used */
142     /* No qualifier */final SSLContext sslContext;
143 
144     /** A flag used to tell the filter to start the handshake immediately */
145     private final boolean autoStart;
146 
147     /** A flag used to determinate if the handshake should start immediately */
148     public static final boolean START_HANDSHAKE = true;
149 
150     /** A flag used to determinate if the handshake should wait for the client to initiate the handshake */
151     public static final boolean CLIENT_HANDSHAKE = false;
152 
153     private boolean client;
154 
155     private boolean needClientAuth;
156 
157     private boolean wantClientAuth;
158 
159     private String[] enabledCipherSuites;
160 
161     private String[] enabledProtocols;
162 
163     /**
164      * Creates a new SSL filter using the specified {@link SSLContext}.
165      * The handshake will start immediately after the filter has been added
166      * to the chain.
167      * 
168      * @param sslContext The SSLContext to use
169      */
170     public SslFilter(SSLContext sslContext) {
171         this(sslContext, START_HANDSHAKE);
172     }
173 
174     /**
175      * Creates a new SSL filter using the specified {@link SSLContext}.
176      * If the <tt>autostart</tt> flag is set to <tt>true</tt>, the
177      * handshake will start immediately after the filter has been added
178      * to the chain.
179      * 
180      * @param sslContext The SSLContext to use
181      * @param autoStart The flag used to tell the filter to start the handshake immediately
182      */
183     public SslFilter(SSLContext sslContext, boolean autoStart) {
184         if (sslContext == null) {
185             throw new IllegalArgumentException("sslContext");
186         }
187 
188         this.sslContext = sslContext;
189         this.autoStart = autoStart;
190     }
191 
192     /**
193      * Returns the underlying {@link SSLSession} for the specified session.
194      *
195      * @param session The current session 
196      * @return <tt>null</tt> if no {@link SSLSession} is initialized yet.
197      */
198     public SSLSession getSslSession(IoSession session) {
199         return (SSLSession) session.getAttribute(SSL_SESSION);
200     }
201 
202     /**
203      * (Re)starts SSL session for the specified <tt>session</tt> if not started yet.
204      * Please note that SSL session is automatically started by default, and therefore
205      * you don't need to call this method unless you've used TLS closure.
206      *
207      * @param session The session that will be switched to SSL mode
208      * @return <tt>true</tt> if the SSL session has been started, <tt>false</tt> if already started.
209      * @throws SSLException if failed to start the SSL session
210      */
211     public boolean startSsl(IoSession session) throws SSLException {
212         SslHandler sslHandler = getSslSessionHandler(session);
213         boolean started;
214 
215         try {
216             synchronized (sslHandler) {
217                 if (sslHandler.isOutboundDone()) {
218                     NextFilter nextFilter = (NextFilter) session.getAttribute(NEXT_FILTER);
219                     sslHandler.destroy();
220                     sslHandler.init();
221                     sslHandler.handshake(nextFilter);
222                     started = true;
223                 } else {
224                     started = false;
225                 }
226             }
227 
228             sslHandler.flushScheduledEvents();
229         } catch (SSLException se) {
230             sslHandler.release();
231             throw se;
232         }
233 
234         return started;
235     }
236 
237     /**
238      * An extended toString() method for sessions. If the SSL handshake
239      * is not yet completed, we will print (ssl) in small caps. Once it's
240      * completed, we will use SSL capitalized.
241      */
242     /* no qualifier */String getSessionInfo(IoSession session) {
243         StringBuilder sb = new StringBuilder();
244 
245         if (session.getService() instanceof IoAcceptor) {
246             sb.append("Session Server");
247 
248         } else {
249             sb.append("Session Client");
250         }
251 
252         sb.append('[').append(session.getId()).append(']');
253 
254         SslHandler/../../org/apache/mina/filter/ssl/SslHandler.html#SslHandler">SslHandler sslHandler = (SslHandler) session.getAttribute(SSL_HANDLER);
255 
256         if (sslHandler == null) {
257             sb.append("(no sslEngine)");
258         } else if (isSslStarted(session)) {
259             if (sslHandler.isHandshakeComplete()) {
260                 sb.append("(SSL)");
261             } else {
262                 sb.append("(ssl...)");
263             }
264         }
265 
266         return sb.toString();
267     }
268 
269     /**
270      * @return <tt>true</tt> if and only if the specified <tt>session</tt> is
271      * encrypted/decrypted over SSL/TLS currently. This method will start
272      * to return <tt>false</tt> after TLS <tt>close_notify</tt> message
273      * is sent and any messages written after then is not going to get encrypted.
274      * 
275      * @param session the session we want to check
276      */
277     public boolean isSslStarted(IoSession session) {
278         SslHandler/../../org/apache/mina/filter/ssl/SslHandler.html#SslHandler">SslHandler sslHandler = (SslHandler) session.getAttribute(SSL_HANDLER);
279 
280         if (sslHandler == null) {
281             return false;
282         }
283 
284         synchronized (sslHandler) {
285             return !sslHandler.isOutboundDone();
286         }
287     }
288 
289     /**
290      * @return <tt>true</tt> if and only if the conditions for
291      * {@link #isSslStarted(IoSession)} are met, and the handhake has
292      * completed.
293      *
294      * @param session the session we want to check
295      */
296     public boolean isSecured(IoSession session) {
297         SslHandler/../../org/apache/mina/filter/ssl/SslHandler.html#SslHandler">SslHandler sslHandler = (SslHandler) session.getAttribute(SSL_HANDLER);
298 
299         if (sslHandler == null) {
300             return false;
301         }
302 
303         synchronized (sslHandler) {
304             return !sslHandler.isOutboundDone() && sslHandler.isHandshakeComplete();
305         }
306     }
307 
308 
309     /**
310      * Stops the SSL session by sending TLS <tt>close_notify</tt> message to
311      * initiate TLS closure.
312      *
313      * @param session the {@link IoSession} to initiate TLS closure
314      * @return The Future for the initiated closure
315      * @throws SSLException if failed to initiate TLS closure
316      */
317     public WriteFuture stopSsl(IoSession session) throws SSLException {
318         SslHandler sslHandler = getSslSessionHandler(session);
319         NextFilter nextFilter = (NextFilter) session.getAttribute(NEXT_FILTER);
320         WriteFuture future;
321 
322         try {
323             synchronized (sslHandler) {
324                 future = initiateClosure(nextFilter, session);
325             }
326 
327             sslHandler.flushScheduledEvents();
328         } catch (SSLException se) {
329             sslHandler.release();
330             throw se;
331         }
332 
333         return future;
334     }
335 
336     /**
337      * @return <tt>true</tt> if the engine is set to use client mode
338      * when handshaking.
339      */
340     public boolean isUseClientMode() {
341         return client;
342     }
343 
344     /**
345      * Configures the engine to use client (or server) mode when handshaking.
346      * 
347      * @param clientMode <tt>true</tt> when we are in client mode, <tt>false</tt> when in server mode
348      */
349     public void setUseClientMode(boolean clientMode) {
350         this.client = clientMode;
351     }
352 
353     /**
354      * @return <tt>true</tt> if the engine will <em>require</em> client authentication.
355      * This option is only useful to engines in the server mode.
356      */
357     public boolean isNeedClientAuth() {
358         return needClientAuth;
359     }
360 
361     /**
362      * Configures the engine to <em>require</em> client authentication.
363      * This option is only useful for engines in the server mode.
364      * 
365      * @param needClientAuth A flag set when we need to authenticate the client
366      */
367     public void setNeedClientAuth(boolean needClientAuth) {
368         this.needClientAuth = needClientAuth;
369     }
370 
371     /**
372      * @return <tt>true</tt> if the engine will <em>request</em> client authentication.
373      * This option is only useful to engines in the server mode.
374      */
375     public boolean isWantClientAuth() {
376         return wantClientAuth;
377     }
378 
379     /**
380      * Configures the engine to <em>request</em> client authentication.
381      * This option is only useful for engines in the server mode.
382      * 
383      * @param wantClientAuth A flag set when we want to check the client authentication
384      */
385     public void setWantClientAuth(boolean wantClientAuth) {
386         this.wantClientAuth = wantClientAuth;
387     }
388 
389     /**
390      * @return the list of cipher suites to be enabled when {@link SSLEngine}
391      * is initialized. <tt>null</tt> means 'use {@link SSLEngine}'s default.'
392      */
393     public String[] getEnabledCipherSuites() {
394         return enabledCipherSuites;
395     }
396 
397     /**
398      * Sets the list of cipher suites to be enabled when {@link SSLEngine}
399      * is initialized.
400      *
401      * @param cipherSuites <tt>null</tt> means 'use {@link SSLEngine}'s default.'
402      */
403     public void setEnabledCipherSuites(String[] cipherSuites) {
404         this.enabledCipherSuites = cipherSuites;
405     }
406 
407     /**
408      * @return the list of protocols to be enabled when {@link SSLEngine}
409      * is initialized. <tt>null</tt> means 'use {@link SSLEngine}'s default.'
410      */
411     public String[] getEnabledProtocols() {
412         return enabledProtocols;
413     }
414 
415     /**
416      * Sets the list of protocols to be enabled when {@link SSLEngine}
417      * is initialized.
418      *
419      * @param protocols <tt>null</tt> means 'use {@link SSLEngine}'s default.'
420      */
421     public void setEnabledProtocols(String[] protocols) {
422         this.enabledProtocols = protocols;
423     }
424 
425     /**
426      * Executed just before the filter is added into the chain, we do :
427      * <ul>
428      * <li>check that we don't have a SSL filter already present
429      * <li>we update the next filter
430      * <li>we create the SSL handler helper class
431      * <li>and we store it into the session's Attributes
432      * </ul>
433      */
434     @Override
435     public void onPreAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws SSLException {
436         // Check that we don't have a SSL filter already present in the chain
437         if (parent.contains(SslFilter.class)) {
438             String msg = "Only one SSL filter is permitted in a chain.";
439             LOGGER.error(msg);
440             throw new IllegalStateException(msg);
441         }
442 
443         if (LOGGER.isDebugEnabled()) {
444             LOGGER.debug("Adding the SSL Filter {} to the chain", name);
445         }
446 
447         IoSession session = parent.getSession();
448         session.setAttribute(NEXT_FILTER, nextFilter);
449 
450         // Create a SSL handler and start handshake.
451         SslHandlerdler.html#SslHandler">SslHandler sslHandler = new SslHandler(this, session);
452         
453         // Adding the supported ciphers in the SSLHandler
454         if ((enabledCipherSuites == null) || (enabledCipherSuites.length == 0)) {
455             enabledCipherSuites = sslContext.getServerSocketFactory().getSupportedCipherSuites();
456         }
457 
458         sslHandler.init();
459 
460         session.setAttribute(SSL_HANDLER, sslHandler);
461     }
462 
463     @Override
464     public void onPostAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws SSLException {
465         if (autoStart == START_HANDSHAKE) {
466             initiateHandshake(nextFilter, parent.getSession());
467         }
468     }
469 
470     @Override
471     public void onPreRemove(IoFilterChain parent, String name, NextFilter nextFilter) throws SSLException {
472         IoSession session = parent.getSession();
473         stopSsl(session);
474         session.removeAttribute(NEXT_FILTER);
475         session.removeAttribute(SSL_HANDLER);
476     }
477 
478     // IoFilter impl.
479     @Override
480     public void sessionClosed(NextFilter nextFilter, IoSession session) throws SSLException {
481         SslHandler sslHandler = getSslSessionHandler(session);
482 
483         try {
484             synchronized (sslHandler) {
485                 // release resources
486                 sslHandler.destroy();
487             }
488         } finally {
489             // notify closed session
490             nextFilter.sessionClosed(session);
491         }
492     }
493 
494     @Override
495     public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws SSLException {
496         if (LOGGER.isDebugEnabled()) {
497             LOGGER.debug("{}: Message received : {}", getSessionInfo(session), message);
498         }
499 
500         SslHandler sslHandler = getSslSessionHandler(session);
501 
502         synchronized (sslHandler) {
503             if (!isSslStarted(session) && sslHandler.isInboundDone()) {
504                 // The SSL session must be established first before we
505                 // can push data to the application. Store the incoming
506                 // data into a queue for a later processing
507                 sslHandler.scheduleMessageReceived(nextFilter, message);
508             } else {
509                 IoBuffer"../../../../../org/apache/mina/core/buffer/IoBuffer.html#IoBuffer">IoBuffer buf = (IoBuffer) message;
510 
511                 try {
512                     if (sslHandler.isOutboundDone()) {
513                         sslHandler.destroy();
514                         throw new SSLException("Outbound done");
515                     }
516                     
517                     // forward read encrypted data to SSL handler
518                     sslHandler.messageReceived(nextFilter, buf.buf());
519 
520                     // Handle data to be forwarded to application or written to net
521                     handleSslData(nextFilter, sslHandler);
522 
523                     if (sslHandler.isInboundDone()) {
524                         if (sslHandler.isOutboundDone()) {
525                             sslHandler.destroy();
526                         } else {
527                             initiateClosure(nextFilter, session);
528                         }
529 
530                         if (buf.hasRemaining()) {
531                             // Forward the data received after closure.
532                             sslHandler.scheduleMessageReceived(nextFilter, buf);
533                         }
534                     }
535                 } catch (SSLException ssle) {
536                     if (!sslHandler.isHandshakeComplete()) {
537                         SSLException newSsle = new SSLHandshakeException("SSL handshake failed.");
538                         newSsle.initCause(ssle);
539                         ssle = newSsle;
540                         
541                         // Close the session immediately, the handshake has failed
542                         session.closeNow();
543                     } else {
544                         // Free the SSL Handler buffers
545                         sslHandler.release();
546                     }
547 
548                     throw ssle;
549                 }
550             }
551         }
552 
553         sslHandler.flushScheduledEvents();
554     }
555 
556     @Override
557     public void messageSent(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) {
558         if (writeRequest instanceof EncryptedWriteRequest) {
559             EncryptedWriteRequest wrappedRequest = (EncryptedWriteRequest) writeRequest;
560             nextFilter.messageSent(session, wrappedRequest.getParentRequest());
561         } else {
562             // ignore extra buffers used for handshaking
563         }
564     }
565 
566     @Override
567     public void exceptionCaught(NextFilter nextFilter, IoSession session, Throwable cause) throws Exception {
568 
569         if (cause instanceof WriteToClosedSessionException) {
570             // Filter out SSL close notify, which is likely to fail to flush
571             // due to disconnection.
572             WriteToClosedSessionException/apache/mina/core/write/WriteToClosedSessionException.html#WriteToClosedSessionException">WriteToClosedSessionException e = (WriteToClosedSessionException) cause;
573             List<WriteRequest> failedRequests = e.getRequests();
574             boolean containsCloseNotify = false;
575 
576             for (WriteRequest r : failedRequests) {
577                 if (isCloseNotify(r.getMessage())) {
578                     containsCloseNotify = true;
579                     break;
580                 }
581             }
582 
583             if (containsCloseNotify) {
584                 if (failedRequests.size() == 1) {
585                     // close notify is the only failed request; bail out.
586                     return;
587                 }
588 
589                 List<WriteRequest> newFailedRequests = new ArrayList<>(failedRequests.size() - 1);
590 
591                 for (WriteRequest r : failedRequests) {
592                     if (!isCloseNotify(r.getMessage())) {
593                         newFailedRequests.add(r);
594                     }
595                 }
596 
597                 if (newFailedRequests.isEmpty()) {
598                     // the failedRequests were full with close notify; bail out.
599                     return;
600                 }
601 
602                 cause = new WriteToClosedSessionException(newFailedRequests, cause.getMessage(), cause.getCause());
603             }
604         }
605 
606         nextFilter.exceptionCaught(session, cause);
607     }
608 
609     private boolean isCloseNotify(Object message) {
610         if (!(message instanceof IoBuffer)) {
611             return false;
612         }
613 
614         IoBuffer"../../../../../org/apache/mina/core/buffer/IoBuffer.html#IoBuffer">IoBuffer buf = (IoBuffer) message;
615         int offset = buf.position();
616 
617         return (buf.get(offset + 0) == 0x15) /* Alert */
618                 && (buf.get(offset + 1) == 0x03) /* TLS/SSL */
619                 && ((buf.get(offset + 2) == 0x00) /* SSL 3.0 */
620                         || (buf.get(offset + 2) == 0x01) /* TLS 1.0 */
621                         || (buf.get(offset + 2) == 0x02) /* TLS 1.1 */
622                         || (buf.get(offset + 2) == 0x03)) /* TLS 1.2 */
623                         && (buf.get(offset + 3) == 0x00); /* close_notify */
624     }
625 
626     @Override
627     public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws SSLException {
628         if (LOGGER.isDebugEnabled()) {
629             LOGGER.debug("{}: Writing Message : {}", getSessionInfo(session), writeRequest);
630         }
631 
632         boolean needsFlush = true;
633         SslHandler sslHandler = getSslSessionHandler(session);
634 
635         try {
636             synchronized (sslHandler) {
637                 if (!isSslStarted(session)) {
638                     sslHandler.scheduleFilterWrite(nextFilter, writeRequest);
639                 }
640                 // Don't encrypt the data if encryption is disabled.
641                 else if (session.containsAttribute(DISABLE_ENCRYPTION_ONCE)) {
642                     // Remove the marker attribute because it is temporary.
643                     session.removeAttribute(DISABLE_ENCRYPTION_ONCE);
644                     sslHandler.scheduleFilterWrite(nextFilter, writeRequest);
645                 } else {
646                     // Otherwise, encrypt the buffer.
647                     IoBuffer"../../../../../org/apache/mina/core/buffer/IoBuffer.html#IoBuffer">IoBuffer buf = (IoBuffer) writeRequest.getMessage();
648 
649                     if (sslHandler.isWritingEncryptedData()) {
650                         // data already encrypted; simply return buffer
651                         sslHandler.scheduleFilterWrite(nextFilter, writeRequest);
652                     } else if (sslHandler.isHandshakeComplete()) {
653                         // SSL encrypt
654                         sslHandler.encrypt(buf.buf());
655                         IoBuffer encryptedBuffer = sslHandler.fetchOutNetBuffer();
656                         writeRequest.setMessage( encryptedBuffer );
657                         sslHandler.scheduleFilterWrite(nextFilter, new EncryptedWriteRequest(writeRequest,
658                             encryptedBuffer));
659                     } else {
660                         if (session.isConnected()) {
661                             // Handshake not complete yet.
662                             sslHandler.schedulePreHandshakeWriteRequest(nextFilter, writeRequest);
663                         }
664 
665                         needsFlush = false;
666                     }
667                 }
668             }
669 
670             if (needsFlush) {
671                 sslHandler.flushScheduledEvents();
672             }
673         } catch (SSLException se) {
674             sslHandler.release();
675             throw se;
676         }
677     }
678 
679     @Override
680     public void filterClose(final NextFilter nextFilter, final IoSession session) throws SSLException {
681         SslHandler/../../org/apache/mina/filter/ssl/SslHandler.html#SslHandler">SslHandler sslHandler = (SslHandler) session.getAttribute(SSL_HANDLER);
682 
683         if (sslHandler == null) {
684             // The connection might already have closed, or
685             // SSL might have not started yet.
686             nextFilter.filterClose(session);
687             return;
688         }
689 
690         WriteFuture future = null;
691 
692         try {
693             synchronized (sslHandler) {
694                 if (isSslStarted(session)) {
695                     future = initiateClosure(nextFilter, session);
696                     future.addListener(new IoFutureListener<IoFuture>() {
697                         @Override
698                         public void operationComplete(IoFuture future) {
699                             nextFilter.filterClose(session);
700                         }
701                     });
702                 }
703             }
704 
705             sslHandler.flushScheduledEvents();
706         } catch (SSLException se) {
707             sslHandler.release();
708             throw se;
709         } finally {
710             if (future == null) {
711                 nextFilter.filterClose(session);
712             }
713         }
714     }
715 
716     /**
717      * Initiate the SSL handshake. This can be invoked if you have set the 'autoStart' to
718      * false when creating the SslFilter instance.
719      * 
720      * @param session The session for which the SSL handshake should be done
721      * @throws SSLException If the handshake failed
722      */
723     public void initiateHandshake(IoSession session) throws SSLException {
724         IoFilterChain filterChain = session.getFilterChain();
725         
726         if (filterChain == null) {
727             throw new SSLException("No filter chain");
728         }
729         
730         IoFilter.NextFilter nextFilter = filterChain.getNextFilter(SslFilter.class);
731         
732         if (nextFilter == null) {
733             throw new SSLException("No SSL next filter in the chain");
734         }
735         
736         initiateHandshake(nextFilter, session);
737     }
738 
739     private void initiateHandshake(NextFilter nextFilter, IoSession session) throws SSLException {
740         if (LOGGER.isDebugEnabled()) {
741             LOGGER.debug("{} : Starting the first handshake", getSessionInfo(session));
742         }
743         
744         SslHandler sslHandler = getSslSessionHandler(session);
745 
746         try {
747             synchronized (sslHandler) {
748                 sslHandler.handshake(nextFilter);
749             }
750 
751             sslHandler.flushScheduledEvents();
752         } catch (SSLException se) {
753             sslHandler.release();
754             throw se;
755         }
756     }
757 
758     private WriteFuture initiateClosure(NextFilter nextFilter, IoSession session) throws SSLException {
759         SslHandler sslHandler = getSslSessionHandler(session);
760         WriteFuture future = null;
761 
762         // if already shut down
763         try {
764             synchronized(sslHandler) {
765                 if (!sslHandler.closeOutbound()) {
766                     return DefaultWriteFuture.newNotWrittenFuture(session, new IllegalStateException(
767                             "SSL session is shut down already."));
768                 }
769     
770                 // there might be data to write out here?
771                 future = sslHandler.writeNetBuffer(nextFilter);
772     
773                 if (future == null) {
774                     future = DefaultWriteFuture.newWrittenFuture(session);
775                 }
776     
777                 if (sslHandler.isInboundDone()) {
778                     sslHandler.destroy();
779                 }
780             }
781 
782             // Inform that the session is not any more secured
783             session.getFilterChain().fireEvent(SslEvent.UNSECURED);
784         } catch (SSLException se) {
785             sslHandler.release();
786             throw se;
787         }
788 
789         return future;
790     }
791 
792     // Utilities
793     private void handleSslData(NextFilter nextFilter, SslHandler sslHandler) throws SSLException {
794         if (LOGGER.isDebugEnabled()) {
795             LOGGER.debug("{}: Processing the SSL Data ", getSessionInfo(sslHandler.getSession()));
796         }
797 
798         // Flush any buffered write requests occurred before handshaking.
799         if (sslHandler.isHandshakeComplete()) {
800             sslHandler.flushPreHandshakeEvents();
801         }
802 
803         // Write encrypted data to be written (if any)
804         sslHandler.writeNetBuffer(nextFilter);
805 
806         // handle app. data read (if any)
807         handleAppDataRead(nextFilter, sslHandler);
808     }
809 
810     private void handleAppDataRead(NextFilter nextFilter, SslHandler sslHandler) {
811         // forward read app data
812         IoBuffer readBuffer = sslHandler.fetchAppBuffer();
813 
814         if (readBuffer.hasRemaining()) {
815             sslHandler.scheduleMessageReceived(nextFilter, readBuffer);
816         }
817     }
818 
819     private SslHandler getSslSessionHandler(IoSession session) {
820         SslHandler/../../org/apache/mina/filter/ssl/SslHandler.html#SslHandler">SslHandler sslHandler = (SslHandler) session.getAttribute(SSL_HANDLER);
821 
822         if (sslHandler == null) {
823             throw new IllegalStateException();
824         }
825 
826         synchronized(sslHandler) {
827             if (sslHandler.getSslFilter() != this) {
828                 throw new IllegalArgumentException("Not managed by this filter.");
829             }
830         }
831 
832         return sslHandler;
833     }
834 
835     /**
836      * A message that is sent from {@link SslFilter} when the connection became
837      * secure or is not secure anymore.
838      *
839      * @author <a href="http://mina.apache.org">Apache MINA Project</a>
840      */
841     public static class SslFilterMessage {
842         private final String name;
843 
844         private SslFilterMessage(String name) {
845             this.name = name;
846         }
847 
848         @Override
849         public String toString() {
850             return name;
851         }
852     }
853     
854     /**
855      * A private class used to store encrypted messages. This is necessary
856      * to be able to emit the messageSent event with the proper original
857      * message, but not for handshake messages, which will be swallowed.
858      *
859      */
860     /* package protected */ static class EncryptedWriteRequest extends DefaultWriteRequest {
861         // Thee encrypted messagee
862         private final IoBuffer encryptedMessage;
863         
864         // The original message
865         private WriteRequest parentRequest;
866 
867         /**
868          * Create a new instance of an EncryptedWriteRequest
869          * @param writeRequest The parent request
870          * @param encryptedMessage The encrypted message
871          */
872         private EncryptedWriteRequest(WriteRequest writeRequest, IoBuffer encryptedMessage) {
873             super(encryptedMessage);
874             parentRequest = writeRequest;
875             this.encryptedMessage = encryptedMessage;
876         }
877 
878         /**
879          * @return teh encrypted message
880          */
881         @Override
882         public Object getMessage() {
883             return encryptedMessage;
884         }
885 
886         /**
887          * @return The parent WriteRequest
888          */
889         public WriteRequest getParentRequest() {
890             return parentRequest;
891         }
892     }
893 }