View Javadoc
1   /*
2    * Copyright 2017 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.ssl;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.ByteBufAllocator;
20  import io.netty.handler.ssl.JdkApplicationProtocolNegotiator.ProtocolSelectionListener;
21  import io.netty.handler.ssl.JdkApplicationProtocolNegotiator.ProtocolSelector;
22  import io.netty.util.internal.SystemPropertyUtil;
23  import org.conscrypt.AllocatedBuffer;
24  import org.conscrypt.BufferAllocator;
25  import org.conscrypt.Conscrypt;
26  import org.conscrypt.HandshakeListener;
27  
28  import java.nio.ByteBuffer;
29  import java.util.Collections;
30  import java.util.LinkedHashSet;
31  import java.util.List;
32  
33  import javax.net.ssl.SSLEngine;
34  import javax.net.ssl.SSLEngineResult;
35  import javax.net.ssl.SSLException;
36  
37  import static io.netty.handler.ssl.SslUtils.toSSLHandshakeException;
38  import static io.netty.util.internal.ObjectUtil.checkNotNull;
39  import static java.lang.Math.min;
40  
41  /**
42   * A {@link JdkSslEngine} that uses the Conscrypt provider or SSL with ALPN.
43   */
44  abstract class ConscryptAlpnSslEngine extends JdkSslEngine {
45      private static final boolean USE_BUFFER_ALLOCATOR = SystemPropertyUtil.getBoolean(
46              "io.netty.handler.ssl.conscrypt.useBufferAllocator", true);
47  
48      static ConscryptAlpnSslEngine newClientEngine(SSLEngine engine, ByteBufAllocator alloc,
49              JdkApplicationProtocolNegotiator applicationNegotiator) {
50          return new ClientEngine(engine, alloc, applicationNegotiator);
51      }
52  
53      static ConscryptAlpnSslEngine newServerEngine(SSLEngine engine, ByteBufAllocator alloc,
54              JdkApplicationProtocolNegotiator applicationNegotiator) {
55          return new ServerEngine(engine, alloc, applicationNegotiator);
56      }
57  
58      private ConscryptAlpnSslEngine(SSLEngine engine, ByteBufAllocator alloc, List<String> protocols) {
59          super(engine);
60  
61          // Configure the Conscrypt engine to use Netty's buffer allocator. This is a trade-off of memory vs
62          // performance.
63          //
64          // If no allocator is provided, the engine will internally allocate a direct buffer of max packet size in
65          // order to optimize JNI calls (this happens the first time it is provided a non-direct buffer from the
66          // application).
67          //
68          // Alternatively, if an allocator is provided, no internal buffer will be created and direct buffers will be
69          // retrieved from the allocator on-demand.
70          if (USE_BUFFER_ALLOCATOR) {
71              Conscrypt.setBufferAllocator(engine, new BufferAllocatorAdapter(alloc));
72          }
73  
74          // Set the list of supported ALPN protocols on the engine.
75          Conscrypt.setApplicationProtocols(engine, protocols.toArray(new String[protocols.size()]));
76      }
77  
78      /**
79       * Calculates the maximum size of the encrypted output buffer required to wrap the given plaintext bytes. Assumes
80       * as a worst case that there is one TLS record per buffer.
81       *
82       * @param plaintextBytes the number of plaintext bytes to be wrapped.
83       * @param numBuffers the number of buffers that the plaintext bytes are spread across.
84       * @return the maximum size of the encrypted output buffer required for the wrap operation.
85       */
86      final int calculateOutNetBufSize(int plaintextBytes, int numBuffers) {
87          // Assuming a max of one frame per component in a composite buffer.
88          long maxOverhead = (long) Conscrypt.maxSealOverhead(getWrappedEngine()) * numBuffers;
89          // TODO(nmittler): update this to use MAX_ENCRYPTED_PACKET_LENGTH instead of Integer.MAX_VALUE
90          return (int) min(Integer.MAX_VALUE, plaintextBytes + maxOverhead);
91      }
92  
93      final SSLEngineResult unwrap(ByteBuffer[] srcs, ByteBuffer[] dests) throws SSLException {
94          return Conscrypt.unwrap(getWrappedEngine(), srcs, dests);
95      }
96  
97      private static final class ClientEngine extends ConscryptAlpnSslEngine {
98          private final ProtocolSelectionListener protocolListener;
99  
100         ClientEngine(SSLEngine engine, ByteBufAllocator alloc,
101                 JdkApplicationProtocolNegotiator applicationNegotiator) {
102             super(engine, alloc, applicationNegotiator.protocols());
103             // Register for completion of the handshake.
104             Conscrypt.setHandshakeListener(engine, new HandshakeListener() {
105                 @Override
106                 public void onHandshakeFinished() throws SSLException {
107                     selectProtocol();
108                 }
109             });
110 
111             protocolListener = checkNotNull(applicationNegotiator
112                             .protocolListenerFactory().newListener(this, applicationNegotiator.protocols()),
113                     "protocolListener");
114         }
115 
116         private void selectProtocol() throws SSLException {
117             String protocol = Conscrypt.getApplicationProtocol(getWrappedEngine());
118             try {
119                 protocolListener.selected(protocol);
120             } catch (Throwable e) {
121                 throw toSSLHandshakeException(e);
122             }
123         }
124     }
125 
126     private static final class ServerEngine extends ConscryptAlpnSslEngine {
127         private final ProtocolSelector protocolSelector;
128 
129         ServerEngine(SSLEngine engine, ByteBufAllocator alloc,
130                      JdkApplicationProtocolNegotiator applicationNegotiator) {
131             super(engine, alloc, applicationNegotiator.protocols());
132 
133             // Register for completion of the handshake.
134             Conscrypt.setHandshakeListener(engine, new HandshakeListener() {
135                 @Override
136                 public void onHandshakeFinished() throws SSLException {
137                     selectProtocol();
138                 }
139             });
140 
141             protocolSelector = checkNotNull(applicationNegotiator.protocolSelectorFactory()
142                             .newSelector(this,
143                                     new LinkedHashSet<String>(applicationNegotiator.protocols())),
144                     "protocolSelector");
145         }
146 
147         private void selectProtocol() throws SSLException {
148             try {
149                 String protocol = Conscrypt.getApplicationProtocol(getWrappedEngine());
150                 protocolSelector.select(protocol != null ? Collections.singletonList(protocol)
151                         : Collections.<String>emptyList());
152             } catch (Throwable e) {
153                 throw toSSLHandshakeException(e);
154             }
155         }
156     }
157 
158     private static final class BufferAllocatorAdapter extends BufferAllocator {
159         private final ByteBufAllocator alloc;
160 
161         BufferAllocatorAdapter(ByteBufAllocator alloc) {
162             this.alloc = alloc;
163         }
164 
165         @Override
166         public AllocatedBuffer allocateDirectBuffer(int capacity) {
167             return new BufferAdapter(alloc.directBuffer(capacity));
168         }
169     }
170 
171     private static final class BufferAdapter extends AllocatedBuffer {
172         private final ByteBuf nettyBuffer;
173         private final ByteBuffer buffer;
174 
175         BufferAdapter(ByteBuf nettyBuffer) {
176             this.nettyBuffer = nettyBuffer;
177             buffer = nettyBuffer.nioBuffer(0, nettyBuffer.capacity());
178         }
179 
180         @Override
181         public ByteBuffer nioBuffer() {
182             return buffer;
183         }
184 
185         @Override
186         public AllocatedBuffer retain() {
187             nettyBuffer.retain();
188             return this;
189         }
190 
191         @Override
192         public AllocatedBuffer release() {
193             nettyBuffer.release();
194             return this;
195         }
196     }
197 }