/
SSLFilter.java
648 lines (567 loc) · 23.1 KB
/
SSLFilter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.mina.filter;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSession;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.ByteBufferProxy;
import org.apache.mina.common.IoFilterAdapter;
import org.apache.mina.common.IoFilterChain;
import org.apache.mina.common.IoFuture;
import org.apache.mina.common.IoFutureListener;
import org.apache.mina.common.IoHandler;
import org.apache.mina.common.IoSession;
import org.apache.mina.common.WriteFuture;
import org.apache.mina.common.support.DefaultWriteFuture;
import org.apache.mina.filter.support.SSLHandler;
import org.apache.mina.util.SessionLog;
/**
* An SSL filter that encrypts and decrypts the data exchanged in the session.
* Adding this filter triggers SSL handshake procedure immediately by sending
* a SSL 'hello' message, so you don't need to call
* {@link #startSSL(IoSession)} manually unless you are implementing StartTLS
* (see below).
* <p>
* This filter uses an {@link SSLEngine} which was introduced in Java 5, so
* Java version 5 or above is mandatory to use this filter. And please note that
* this filter only works for TCP/IP connections.
* <p>
* This filter logs debug information using {@link SessionLog}.
*
* <h2>Implementing StartTLS</h2>
* <p>
* You can use {@link #DISABLE_ENCRYPTION_ONCE} attribute to implement StartTLS:
* <pre>
* public void messageReceived(IoSession session, Object message) {
* if (message instanceof MyStartTLSRequest) {
* // Insert SSLFilter to get ready for handshaking
* session.getFilterChain().addFirst(sslFilter);
*
* // Disable encryption temporarilly.
* // This attribute will be removed by SSLFilter
* // inside the Session.write() call below.
* session.setAttribute(SSLFilter.DISABLE_ENCRYPTION_ONCE, Boolean.TRUE);
*
* // Write StartTLSResponse which won't be encrypted.
* session.write(new MyStartTLSResponse(OK));
*
* // Now DISABLE_ENCRYPTION_ONCE attribute is cleared.
* assert session.getAttribute(SSLFilter.DISABLE_ENCRYPTION_ONCE) == null;
* }
* }
* </pre>
*
* @author The Apache Directory Project (mina-dev@directory.apache.org)
* @version $Rev$, $Date$
*/
public class SSLFilter extends IoFilterAdapter {
/**
* A session attribute key that stores underlying {@link SSLSession}
* for each session.
*/
public static final String SSL_SESSION = SSLFilter.class.getName()
+ ".SSLSession";
/**
* A session attribute key that makes next one write request bypass
* this filter (not encrypting the data). This is a marker attribute,
* which means that you can put whatever as its value. ({@link Boolean#TRUE}
* is preferred.) The attribute is automatically removed from the session
* attribute map as soon as {@link IoSession#write(Object)} is invoked,
* and therefore should be put again if you want to make more messages
* bypass this filter. This is especially useful when you implement
* StartTLS.
*/
public static final String DISABLE_ENCRYPTION_ONCE = SSLFilter.class
.getName()
+ ".DisableEncryptionOnce";
/**
* A session attribute key that makes this filter to emit a
* {@link IoHandler#messageReceived(IoSession, Object)} event with a
* special message ({@link #SESSION_SECURED} or {@link #SESSION_UNSECURED}).
* This is a marker attribute, which means that you can put whatever as its
* value. ({@link Boolean#TRUE} is preferred.) By default, this filter
* doesn't emit any events related with SSL session flow control.
*/
public static final String USE_NOTIFICATION = SSLFilter.class.getName()
+ ".UseNotification";
/**
* A special message object which is emitted with a {@link IoHandler#messageReceived(IoSession, Object)}
* event when the session is secured and its {@link #USE_NOTIFICATION}
* attribute is set.
*/
public static final SSLFilterMessage SESSION_SECURED = new SSLFilterMessage(
"SESSION_SECURED");
/**
* A special message object which is emitted with a {@link IoHandler#messageReceived(IoSession, Object)}
* event when the session is not secure anymore and its {@link #USE_NOTIFICATION}
* attribute is set.
*/
public static final SSLFilterMessage SESSION_UNSECURED = new SSLFilterMessage(
"SESSION_UNSECURED");
private static final String NEXT_FILTER = SSLFilter.class.getName()
+ ".NextFilter";
private static final String SSL_HANDLER = SSLFilter.class.getName()
+ ".SSLHandler";
// SSL Context
private SSLContext sslContext;
private boolean client;
private boolean needClientAuth;
private boolean wantClientAuth;
private String[] enabledCipherSuites;
private String[] enabledProtocols;
/**
* Creates a new SSL filter using the specified {@link SSLContext}.
*/
public SSLFilter(SSLContext sslContext) {
if (sslContext == null) {
throw new NullPointerException("sslContext");
}
this.sslContext = sslContext;
}
/**
* Returns the underlying {@link SSLSession} for the specified session.
*
* @return <tt>null</tt> if no {@link SSLSession} is initialized yet.
*/
public SSLSession getSSLSession(IoSession session) {
return (SSLSession) session.getAttribute(SSL_SESSION);
}
/**
* (Re)starts SSL session for the specified <tt>session</tt> if not started yet.
* Please note that SSL session is automatically started by default, and therefore
* you don't need to call this method unless you've used TLS closure.
*
* @return <tt>true</tt> if the SSL session has been started, <tt>false</tt> if already started.
* @throws SSLException if failed to start the SSL session
*/
public boolean startSSL(IoSession session) throws SSLException {
SSLHandler handler = getSSLSessionHandler(session);
boolean started;
synchronized (handler) {
if (handler.isOutboundDone()) {
NextFilter nextFilter = (NextFilter) session
.getAttribute(NEXT_FILTER);
handler.destroy();
handler.init();
handler.handshake(nextFilter);
started = true;
} else {
started = false;
}
}
handler.flushScheduledEvents();
return started;
}
/**
* Returns <tt>true</tt> if and only if the specified <tt>session</tt> is
* encrypted/decrypted over SSL/TLS currently. This method will start
* to retun <tt>false</tt> after TLS <tt>close_notify</tt> message
* is sent and any messages written after then is not goinf to get encrypted.
*/
public boolean isSSLStarted(IoSession session) {
SSLHandler handler = getSSLSessionHandler0(session);
if (handler == null) {
return false;
}
synchronized (handler) {
return !handler.isOutboundDone();
}
}
/**
* Stops the SSL session by sending TLS <tt>close_notify</tt> message to
* initiate TLS closure.
*
* @param session the {@link IoSession} to initiate TLS closure
* @throws SSLException if failed to initiate TLS closure
* @throws IllegalArgumentException if this filter is not managing the specified session
*/
public WriteFuture stopSSL(IoSession session) throws SSLException {
SSLHandler handler = getSSLSessionHandler(session);
NextFilter nextFilter = (NextFilter) session.getAttribute(NEXT_FILTER);
WriteFuture future;
synchronized (handler) {
future = initiateClosure(nextFilter, session);
}
handler.flushScheduledEvents();
return future;
}
/**
* Returns <tt>true</tt> if the engine is set to use client mode
* when handshaking.
*/
public boolean isUseClientMode() {
return client;
}
/**
* Configures the engine to use client (or server) mode when handshaking.
*/
public void setUseClientMode(boolean clientMode) {
this.client = clientMode;
}
/**
* Returns <tt>true</tt> if the engine will <em>require</em> client authentication.
* This option is only useful to engines in the server mode.
*/
public boolean isNeedClientAuth() {
return needClientAuth;
}
/**
* Configures the engine to <em>require</em> client authentication.
* This option is only useful for engines in the server mode.
*/
public void setNeedClientAuth(boolean needClientAuth) {
this.needClientAuth = needClientAuth;
}
/**
* Returns <tt>true</tt> if the engine will <em>request</em> client authentication.
* This option is only useful to engines in the server mode.
*/
public boolean isWantClientAuth() {
return wantClientAuth;
}
/**
* Configures the engine to <em>request</em> client authentication.
* This option is only useful for engines in the server mode.
*/
public void setWantClientAuth(boolean wantClientAuth) {
this.wantClientAuth = wantClientAuth;
}
/**
* Returns the list of cipher suites to be enabled when {@link SSLEngine}
* is initialized.
*
* @return <tt>null</tt> means 'use {@link SSLEngine}'s default.'
*/
public String[] getEnabledCipherSuites() {
return enabledCipherSuites;
}
/**
* Sets the list of cipher suites to be enabled when {@link SSLEngine}
* is initialized.
*
* @param cipherSuites <tt>null</tt> means 'use {@link SSLEngine}'s default.'
*/
public void setEnabledCipherSuites(String[] cipherSuites) {
this.enabledCipherSuites = cipherSuites;
}
/**
* Returns the list of protocols to be enabled when {@link SSLEngine}
* is initialized.
*
* @return <tt>null</tt> means 'use {@link SSLEngine}'s default.'
*/
public String[] getEnabledProtocols() {
return enabledProtocols;
}
/**
* Sets the list of protocols to be enabled when {@link SSLEngine}
* is initialized.
*
* @param protocols <tt>null</tt> means 'use {@link SSLEngine}'s default.'
*/
public void setEnabledProtocols(String[] protocols) {
this.enabledProtocols = protocols;
}
public void onPreAdd(IoFilterChain parent, String name,
NextFilter nextFilter) throws SSLException {
if (parent.contains(SSLFilter.class)) {
throw new IllegalStateException(
"A filter chain cannot contain more than one SSLFilter.");
}
IoSession session = parent.getSession();
session.setAttribute(NEXT_FILTER, nextFilter);
// Create an SSL handler and start handshake.
SSLHandler handler = new SSLHandler(this, sslContext, session);
session.setAttribute(SSL_HANDLER, handler);
}
public void onPostAdd(IoFilterChain parent, String name,
NextFilter nextFilter) throws SSLException {
SSLHandler handler = getSSLSessionHandler(parent.getSession());
synchronized (handler) {
handler.handshake(nextFilter);
}
handler.flushScheduledEvents();
}
public void onPreRemove(IoFilterChain parent, String name,
NextFilter nextFilter) throws SSLException {
IoSession session = parent.getSession();
stopSSL(session);
session.removeAttribute(NEXT_FILTER);
session.removeAttribute(SSL_HANDLER);
}
// IoFilter impl.
public void sessionClosed(NextFilter nextFilter, IoSession session)
throws SSLException {
SSLHandler handler = getSSLSessionHandler(session);
try {
synchronized (handler) {
if (isSSLStarted(session)) {
if (SessionLog.isDebugEnabled(session)) {
SessionLog.debug(session, " Closed: "
+ getSSLSessionHandler(session));
}
}
// release resources
handler.destroy();
}
handler.flushScheduledEvents();
} finally {
// notify closed session
nextFilter.sessionClosed(session);
}
}
public void messageReceived(NextFilter nextFilter, IoSession session,
Object message) throws SSLException {
SSLHandler handler = getSSLSessionHandler(session);
synchronized (handler) {
if (!isSSLStarted(session) && handler.isInboundDone()) {
handler.scheduleMessageReceived(nextFilter, message);
} else {
ByteBuffer buf = (ByteBuffer) message;
if (SessionLog.isDebugEnabled(session)) {
SessionLog.debug(session, " Data Read: " + handler + " ("
+ buf + ')');
}
try {
// forward read encrypted data to SSL handler
handler.messageReceived(nextFilter, buf.buf());
// Handle data to be forwarded to application or written to net
handleSSLData(nextFilter, handler);
if (handler.isInboundDone()) {
if (handler.isOutboundDone()) {
if (SessionLog.isDebugEnabled(session)) {
SessionLog.debug(session,
" SSL Session closed.");
}
handler.destroy();
} else {
initiateClosure(nextFilter, session);
}
if (buf.hasRemaining()) {
handler.scheduleMessageReceived(nextFilter,
buf);
}
}
} catch (SSLException ssle) {
if (!handler.isInitialHandshakeComplete()) {
SSLException newSSLE = new SSLHandshakeException(
"Initial SSL handshake failed.");
newSSLE.initCause(ssle);
ssle = newSSLE;
}
throw ssle;
}
}
}
handler.flushScheduledEvents();
}
public void messageSent(NextFilter nextFilter, IoSession session,
Object message) {
if (message instanceof EncryptedBuffer) {
EncryptedBuffer buf = (EncryptedBuffer) message;
buf.release();
nextFilter.messageSent(session, buf.originalBuffer);
} else {
// ignore extra buffers used for handshaking
}
}
public void filterWrite(NextFilter nextFilter, IoSession session,
WriteRequest writeRequest) throws SSLException {
boolean needsFlush = true;
SSLHandler handler = getSSLSessionHandler(session);
synchronized (handler) {
if (!isSSLStarted(session)) {
handler.scheduleFilterWrite(nextFilter,
writeRequest);
}
// Don't encrypt the data if encryption is disabled.
else if (session.containsAttribute(DISABLE_ENCRYPTION_ONCE)) {
// Remove the marker attribute because it is temporary.
session.removeAttribute(DISABLE_ENCRYPTION_ONCE);
handler.scheduleFilterWrite(nextFilter,
writeRequest);
} else {
// Otherwise, encrypt the buffer.
ByteBuffer buf = (ByteBuffer) writeRequest.getMessage();
if (SessionLog.isDebugEnabled(session)) {
SessionLog.debug(session, " Filtered Write: " + handler);
}
if (handler.isWritingEncryptedData()) {
// data already encrypted; simply return buffer
if (SessionLog.isDebugEnabled(session)) {
SessionLog.debug(session, " already encrypted: "
+ buf);
}
handler.scheduleFilterWrite(nextFilter,
writeRequest);
} else if (handler.isInitialHandshakeComplete()) {
// SSL encrypt
if (SessionLog.isDebugEnabled(session)) {
SessionLog.debug(session, " encrypt: " + buf);
}
int pos = buf.position();
handler.encrypt(buf.buf());
buf.position(pos);
ByteBuffer encryptedBuffer = new EncryptedBuffer(SSLHandler
.copy(handler.getOutNetBuffer()), buf);
if (SessionLog.isDebugEnabled(session)) {
SessionLog.debug(session, " encrypted buf: "
+ encryptedBuffer);
}
handler.scheduleFilterWrite(nextFilter,
new WriteRequest(encryptedBuffer, writeRequest
.getFuture()));
} else {
if (!session.isConnected()) {
if (SessionLog.isDebugEnabled(session)) {
SessionLog.debug(session,
" Write request on closed session.");
}
} else {
if (SessionLog.isDebugEnabled(session)) {
SessionLog
.debug(session,
" Handshaking is not complete yet. Buffering write request.");
}
handler.schedulePreHandshakeWriteRequest(nextFilter,
writeRequest);
}
needsFlush = false;
}
}
}
if (needsFlush) {
handler.flushScheduledEvents();
}
}
public void filterClose(final NextFilter nextFilter, final IoSession session)
throws SSLException {
SSLHandler handler = getSSLSessionHandler0(session);
if (handler == null) {
// The connection might already have closed, or
// SSL might have not started yet.
nextFilter.filterClose(session);
return;
}
WriteFuture future = null;
try {
synchronized (handler) {
if (isSSLStarted(session)) {
future = initiateClosure(nextFilter, session);
}
}
handler.flushScheduledEvents();
} finally {
if (future == null) {
nextFilter.filterClose(session);
} else {
future.addListener(new IoFutureListener() {
public void operationComplete(IoFuture future) {
nextFilter.filterClose(session);
}
});
}
}
}
private WriteFuture initiateClosure(NextFilter nextFilter, IoSession session)
throws SSLException {
SSLHandler handler = getSSLSessionHandler(session);
// if already shut down
if (!handler.closeOutbound()) {
return DefaultWriteFuture.newNotWrittenFuture(session);
}
// there might be data to write out here?
WriteFuture future = handler.writeNetBuffer(nextFilter);
if (handler.isInboundDone()) {
handler.destroy();
}
if (session.containsAttribute(USE_NOTIFICATION)) {
handler.scheduleMessageReceived(nextFilter, SESSION_UNSECURED);
}
return future;
}
// Utiliities
private void handleSSLData(NextFilter nextFilter, SSLHandler handler)
throws SSLException {
// Flush any buffered write requests occurred before handshaking.
if (handler.isInitialHandshakeComplete()) {
handler.flushPreHandshakeEvents();
}
// Write encrypted data to be written (if any)
handler.writeNetBuffer(nextFilter);
// handle app. data read (if any)
handleAppDataRead(nextFilter, handler);
}
private void handleAppDataRead(NextFilter nextFilter, SSLHandler handler) {
IoSession session = handler.getSession();
if (!handler.getAppBuffer().hasRemaining()) {
return;
}
if (SessionLog.isDebugEnabled(session)) {
SessionLog.debug(session, " appBuffer: " + handler.getAppBuffer());
}
// forward read app data
ByteBuffer readBuffer = SSLHandler.copy(handler.getAppBuffer());
if (SessionLog.isDebugEnabled(session)) {
SessionLog.debug(session, " app data read: " + readBuffer + " ("
+ readBuffer.getHexDump() + ')');
}
handler.scheduleMessageReceived(nextFilter, readBuffer);
}
private SSLHandler getSSLSessionHandler(IoSession session) {
SSLHandler handler = getSSLSessionHandler0(session);
if (handler == null) {
throw new IllegalStateException();
}
if (handler.getParent() != this) {
throw new IllegalArgumentException("Not managed by this filter.");
}
return handler;
}
private SSLHandler getSSLSessionHandler0(IoSession session) {
return (SSLHandler) session.getAttribute(SSL_HANDLER);
}
/**
* A message that is sent from {@link SSLFilter} when the connection became
* secure or is not secure anymore.
*
* @author The Apache Directory Project (mina-dev@directory.apache.org)
* @version $Rev$, $Date$
*/
public static class SSLFilterMessage {
private final String name;
private SSLFilterMessage(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
private static class EncryptedBuffer extends ByteBufferProxy {
private final ByteBuffer originalBuffer;
private EncryptedBuffer(ByteBuffer buf, ByteBuffer originalBuffer) {
super(buf);
this.originalBuffer = originalBuffer;
}
}
}