1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.testsuite.transport.socket;
17
18 import io.netty.bootstrap.Bootstrap;
19 import io.netty.bootstrap.ServerBootstrap;
20 import io.netty.buffer.ByteBuf;
21 import io.netty.buffer.ByteBufAllocator;
22 import io.netty.channel.Channel;
23 import io.netty.channel.ChannelHandlerContext;
24 import io.netty.channel.ChannelInitializer;
25 import io.netty.channel.ChannelPipeline;
26 import io.netty.channel.SimpleChannelInboundHandler;
27 import io.netty.handler.logging.LogLevel;
28 import io.netty.handler.logging.LoggingHandler;
29 import io.netty.handler.ssl.OpenSsl;
30 import io.netty.handler.ssl.SslContext;
31 import io.netty.handler.ssl.SslContextBuilder;
32 import io.netty.handler.ssl.SslHandler;
33 import io.netty.handler.ssl.SslHandshakeCompletionEvent;
34 import io.netty.handler.ssl.SslProvider;
35 import io.netty.handler.ssl.util.SelfSignedCertificate;
36 import io.netty.util.internal.PlatformDependent;
37 import io.netty.util.internal.logging.InternalLogger;
38 import io.netty.util.internal.logging.InternalLoggerFactory;
39 import org.junit.jupiter.api.TestInfo;
40 import org.junit.jupiter.api.Timeout;
41 import org.junit.jupiter.api.function.Executable;
42 import org.junit.jupiter.params.ParameterizedTest;
43 import org.junit.jupiter.params.provider.MethodSource;
44
45 import javax.net.ssl.SSLPeerUnverifiedException;
46 import javax.net.ssl.SSLSession;
47 import java.io.File;
48 import java.io.IOException;
49 import java.security.cert.CertificateException;
50 import java.util.ArrayList;
51 import java.util.Collection;
52 import java.util.List;
53 import java.util.concurrent.CountDownLatch;
54 import java.util.concurrent.Executor;
55 import java.util.concurrent.ExecutorService;
56 import java.util.concurrent.Executors;
57 import java.util.concurrent.TimeUnit;
58 import java.util.concurrent.atomic.AtomicReference;
59
60 import static org.junit.jupiter.api.Assertions.assertEquals;
61 import static org.junit.jupiter.api.Assertions.assertFalse;
62 import static org.junit.jupiter.api.Assertions.assertThrows;
63 import static org.junit.jupiter.api.Assertions.assertTrue;
64 import static org.junit.jupiter.api.Assertions.fail;
65
66 public class SocketSslGreetingTest extends AbstractSocketTest {
67
68 private static final InternalLogger logger = InternalLoggerFactory.getInstance(SocketSslGreetingTest.class);
69
70 private static final LogLevel LOG_LEVEL = LogLevel.TRACE;
71 private static final File CERT_FILE;
72 private static final File KEY_FILE;
73
74 static {
75 SelfSignedCertificate ssc;
76 try {
77 ssc = new SelfSignedCertificate();
78 } catch (CertificateException e) {
79 throw new Error(e);
80 }
81 CERT_FILE = ssc.certificate();
82 KEY_FILE = ssc.privateKey();
83 }
84
85 public static Collection<Object[]> data() throws Exception {
86 List<SslContext> serverContexts = new ArrayList<SslContext>();
87 serverContexts.add(SslContextBuilder.forServer(CERT_FILE, KEY_FILE).sslProvider(SslProvider.JDK).build());
88
89 List<SslContext> clientContexts = new ArrayList<SslContext>();
90 clientContexts.add(SslContextBuilder.forClient().sslProvider(SslProvider.JDK).trustManager(CERT_FILE).build());
91
92 boolean hasOpenSsl = OpenSsl.isAvailable();
93 if (hasOpenSsl) {
94 serverContexts.add(SslContextBuilder.forServer(CERT_FILE, KEY_FILE)
95 .sslProvider(SslProvider.OPENSSL).build());
96 clientContexts.add(SslContextBuilder.forClient().sslProvider(SslProvider.OPENSSL)
97 .trustManager(CERT_FILE).build());
98 } else {
99 logger.warn("OpenSSL is unavailable and thus will not be tested.", OpenSsl.unavailabilityCause());
100 }
101
102 List<Object[]> params = new ArrayList<Object[]>();
103 for (SslContext sc: serverContexts) {
104 for (SslContext cc: clientContexts) {
105 params.add(new Object[] { sc, cc, true });
106 params.add(new Object[] { sc, cc, false });
107 }
108 }
109 return params;
110 }
111
112 private static SslHandler newSslHandler(SslContext sslCtx, ByteBufAllocator allocator, Executor executor) {
113 if (executor == null) {
114 return sslCtx.newHandler(allocator);
115 } else {
116 return sslCtx.newHandler(allocator, executor);
117 }
118 }
119
120
121 @ParameterizedTest(name = "{index}: serverEngine = {0}, clientEngine = {1}, delegate = {2}")
122 @MethodSource("data")
123 @Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
124 public void testSslGreeting(final SslContext serverCtx, final SslContext clientCtx, final boolean delegate,
125 TestInfo testInfo) throws Throwable {
126 run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
127 @Override
128 public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
129 testSslGreeting(sb, cb, serverCtx, clientCtx, delegate);
130 }
131 });
132 }
133
134 public void testSslGreeting(ServerBootstrap sb, Bootstrap cb, final SslContext serverCtx,
135 final SslContext clientCtx, boolean delegate) throws Throwable {
136 final ServerHandler sh = new ServerHandler();
137 final ClientHandler ch = new ClientHandler();
138
139 final ExecutorService executorService = delegate ? Executors.newCachedThreadPool() : null;
140 try {
141 sb.childHandler(new ChannelInitializer<Channel>() {
142 @Override
143 public void initChannel(Channel sch) throws Exception {
144 ChannelPipeline p = sch.pipeline();
145 p.addLast(newSslHandler(serverCtx, sch.alloc(), executorService));
146 p.addLast(new LoggingHandler(LOG_LEVEL));
147 p.addLast(sh);
148 }
149 });
150
151 cb.handler(new ChannelInitializer<Channel>() {
152 @Override
153 public void initChannel(Channel sch) throws Exception {
154 ChannelPipeline p = sch.pipeline();
155 p.addLast(newSslHandler(clientCtx, sch.alloc(), executorService));
156 p.addLast(new LoggingHandler(LOG_LEVEL));
157 p.addLast(ch);
158 }
159 });
160
161 Channel sc = sb.bind().sync().channel();
162 Channel cc = cb.connect(sc.localAddress()).sync().channel();
163
164 ch.latch.await();
165
166 sh.channel.close().awaitUninterruptibly();
167 cc.close().awaitUninterruptibly();
168 sc.close().awaitUninterruptibly();
169
170 if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
171 throw sh.exception.get();
172 }
173 if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) {
174 throw ch.exception.get();
175 }
176 if (sh.exception.get() != null) {
177 throw sh.exception.get();
178 }
179 if (ch.exception.get() != null) {
180 throw ch.exception.get();
181 }
182 } finally {
183 if (executorService != null) {
184 executorService.shutdown();
185 assertTrue(executorService.awaitTermination(5, TimeUnit.SECONDS));
186 }
187 }
188 }
189
190 private static class ClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
191
192 final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
193 final CountDownLatch latch = new CountDownLatch(1);
194
195 @Override
196 public void channelRead0(ChannelHandlerContext ctx, ByteBuf buf) throws Exception {
197 assertEquals('a', buf.readByte());
198 assertFalse(buf.isReadable());
199 latch.countDown();
200 ctx.close();
201 }
202
203 @Override
204 public void exceptionCaught(ChannelHandlerContext ctx,
205 Throwable cause) throws Exception {
206 if (logger.isWarnEnabled()) {
207 logger.warn("Unexpected exception from the client side", cause);
208 }
209
210 exception.compareAndSet(null, cause);
211 ctx.close();
212 }
213 }
214
215 private static class ServerHandler extends SimpleChannelInboundHandler<String> {
216 volatile Channel channel;
217 final AtomicReference<Throwable> exception = new AtomicReference<Throwable>();
218
219 @Override
220 protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
221
222 }
223
224 @Override
225 public void channelActive(ChannelHandlerContext ctx)
226 throws Exception {
227 channel = ctx.channel();
228 channel.writeAndFlush(ctx.alloc().buffer().writeByte('a'));
229 }
230
231 @Override
232 public void exceptionCaught(ChannelHandlerContext ctx,
233 Throwable cause) throws Exception {
234 if (logger.isWarnEnabled()) {
235 logger.warn("Unexpected exception from the server side", cause);
236 }
237
238 exception.compareAndSet(null, cause);
239 ctx.close();
240 }
241
242 @Override
243 public void userEventTriggered(final ChannelHandlerContext ctx, final Object evt) throws Exception {
244 if (evt instanceof SslHandshakeCompletionEvent) {
245 final SslHandshakeCompletionEvent event = (SslHandshakeCompletionEvent) evt;
246 if (event.isSuccess()) {
247 final SSLSession session = ctx.pipeline().get(SslHandler.class).engine().getSession();
248 assertThrows(SSLPeerUnverifiedException.class, new Executable() {
249 @Override
250 public void execute() throws Throwable {
251 session.getPeerCertificates();
252 }
253 });
254 try {
255 session.getPeerCertificateChain();
256 fail();
257 } catch (SSLPeerUnverifiedException e) {
258
259 } catch (UnsupportedOperationException e) {
260
261
262 if (PlatformDependent.javaVersion() < 15) {
263 throw e;
264 }
265 }
266 assertThrows(SSLPeerUnverifiedException.class, new Executable() {
267 @Override
268 public void execute() throws Throwable {
269 session.getPeerPrincipal();
270 }
271 });
272 }
273 }
274 ctx.fireUserEventTriggered(evt);
275 }
276 }
277 }