-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
KeyStoreScannerTest.java
498 lines (417 loc) · 18.6 KB
/
KeyStoreScannerTest.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
//
// ========================================================================
// Copyright (c) 1995-2022 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.test;
import java.io.IOException;
import java.net.URL;
import java.nio.file.FileSystemException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Calendar;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.logging.StacklessLogging;
import org.eclipse.jetty.server.HttpConfiguration;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.SecureRequestCustomizer;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.toolchain.test.FS;
import org.eclipse.jetty.toolchain.test.MavenTestingUtils;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDir;
import org.eclipse.jetty.toolchain.test.jupiter.WorkDirExtension;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.util.ssl.KeyStoreScanner;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeFalse;
@ExtendWith(WorkDirExtension.class)
public class KeyStoreScannerTest
{
public WorkDir testdir;
private Server server;
private Path keystoreDir;
private KeyStoreScanner keyStoreScanner;
@BeforeEach
public void before()
{
keystoreDir = testdir.getEmptyPathDir();
}
@FunctionalInterface
public interface Configuration
{
void configure(SslContextFactory sslContextFactory) throws Exception;
}
public void start() throws Exception
{
start(sslContextFactory ->
{
String keystorePath = useKeystore("oldKeyStore").toString();
sslContextFactory.setKeyStorePath(keystorePath);
sslContextFactory.setKeyStorePassword("storepwd");
sslContextFactory.setKeyManagerPassword("keypwd");
});
}
public void start(Configuration configuration) throws Exception
{
SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
configuration.configure(sslContextFactory);
server = new Server();
SslConnectionFactory sslConnectionFactory = new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString());
HttpConfiguration httpsConfig = new HttpConfiguration();
httpsConfig.addCustomizer(new SecureRequestCustomizer());
HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory(httpsConfig);
ServerConnector connector = new ServerConnector(server, sslConnectionFactory, httpConnectionFactory);
server.addConnector(connector);
// Configure Keystore Reload.
keyStoreScanner = new KeyStoreScanner(sslContextFactory);
keyStoreScanner.setScanInterval(0);
server.addBean(keyStoreScanner);
server.start();
}
@AfterEach
public void stop() throws Exception
{
LifeCycle.stop(server);
}
@Test
public void testKeystoreHotReload() throws Exception
{
start();
// Check the original certificate expiry.
X509Certificate cert1 = getCertificateFromServer();
assertThat(getExpiryYear(cert1), is(2015));
// Switch to use newKeyStore which has a later expiry date.
useKeystore("newKeyStore");
assertTrue(keyStoreScanner.scan(5000));
// The scanner should have detected the updated keystore, expiry should be renewed.
X509Certificate cert2 = getCertificateFromServer();
assertThat(getExpiryYear(cert2), is(2020));
}
@Test
public void testReloadWithBadKeystore() throws Exception
{
start();
// Check the original certificate expiry.
X509Certificate cert1 = getCertificateFromServer();
assertThat(getExpiryYear(cert1), is(2015));
// Switch to use badKeystore which has the incorrect passwords.
try (StacklessLogging ignored = new StacklessLogging(KeyStoreScanner.class))
{
useKeystore("badKeystore");
keyStoreScanner.scan(5000);
}
// The good keystore is removed, now the bad keystore now causes an exception.
assertThrows(Throwable.class, this::getCertificateFromServer);
}
@Test
public void testKeystoreRemoval() throws Exception
{
start();
// Check the original certificate expiry.
X509Certificate cert1 = getCertificateFromServer();
assertThat(getExpiryYear(cert1), is(2015));
// Delete the keystore.
try (StacklessLogging ignored = new StacklessLogging(KeyStoreScanner.class))
{
Path keystorePath = keystoreDir.resolve("keystore");
assertTrue(Files.deleteIfExists(keystorePath));
keyStoreScanner.scan(5000);
}
// The good keystore is removed, having no keystore causes an exception.
assertThrows(Throwable.class, this::getCertificateFromServer);
// Switch to use keystore2 which has a later expiry date.
useKeystore("newKeyStore");
keyStoreScanner.scan(5000);
X509Certificate cert2 = getCertificateFromServer();
assertThat(getExpiryYear(cert2), is(2020));
}
@Test
public void testReloadChangingSymbolicLink() throws Exception
{
assumeFileSystemSupportsSymlink();
Path newKeyStore = useKeystore("newKeyStore", "newKeyStore");
Path oldKeyStore = useKeystore("oldKeyStore", "oldKeyStore");
Path symlinkKeystorePath = keystoreDir.resolve("symlinkKeystore");
start(sslContextFactory ->
{
Files.createSymbolicLink(symlinkKeystorePath, oldKeyStore);
sslContextFactory.setKeyStorePath(symlinkKeystorePath.toString());
sslContextFactory.setKeyStorePassword("storepwd");
sslContextFactory.setKeyManagerPassword("keypwd");
});
// Check the original certificate expiry.
X509Certificate cert1 = getCertificateFromServer();
assertThat(getExpiryYear(cert1), is(2015));
// Change the symlink to point to the newKeyStore file location which has a later expiry date.
Files.delete(symlinkKeystorePath);
Files.createSymbolicLink(symlinkKeystorePath, newKeyStore);
keyStoreScanner.scan(5000);
// The scanner should have detected the updated keystore, expiry should be renewed.
X509Certificate cert2 = getCertificateFromServer();
assertThat(getExpiryYear(cert2), is(2020));
}
@Test
public void testReloadChangingTargetOfSymbolicLink() throws Exception
{
assumeFileSystemSupportsSymlink();
Path keystoreLink = keystoreDir.resolve("symlinkKeystore");
Path oldKeyStoreSrc = MavenTestingUtils.getTestResourcePathFile("oldKeyStore");
Path newKeyStoreSrc = MavenTestingUtils.getTestResourcePathFile("newKeyStore");
Path target = keystoreDir.resolve("keystore");
start(sslContextFactory ->
{
Files.copy(oldKeyStoreSrc, target);
Files.createSymbolicLink(keystoreLink, target);
sslContextFactory.setKeyStorePath(keystoreLink.toString());
sslContextFactory.setKeyStorePassword("storepwd");
sslContextFactory.setKeyManagerPassword("keypwd");
});
// Check the original certificate expiry.
X509Certificate cert1 = getCertificateFromServer();
assertThat(getExpiryYear(cert1), is(2015));
// Change the target file of the symlink to the newKeyStore which has a later expiry date.
Files.copy(newKeyStoreSrc, target, StandardCopyOption.REPLACE_EXISTING);
System.err.println("### Triggering scan");
keyStoreScanner.scan(5000);
// The scanner should have detected the updated keystore, expiry should be renewed.
X509Certificate cert2 = getCertificateFromServer();
assertThat(getExpiryYear(cert2), is(2020));
}
@Test
public void testReloadChangingLinkTargetOfSymbolicLink() throws Exception
{
assumeFileSystemSupportsSymlink();
Path oldKeyStoreSrc = MavenTestingUtils.getTestResourcePathFile("oldKeyStore");
Path newKeyStoreSrc = MavenTestingUtils.getTestResourcePathFile("newKeyStore");
Path sslDir = keystoreDir.resolve("ssl");
Path optDir = keystoreDir.resolve("opt");
Path optKeystoreLink = optDir.resolve("keystore");
Path optKeystore1 = optDir.resolve("keystore.1");
Path optKeystore2 = optDir.resolve("keystore.2");
Path keystoreFile = sslDir.resolve("keystore");
start(sslContextFactory ->
{
// What we want is ..
// (link) ssl/keystore -> opt/keystore
// (link) opt/keystore -> opt/keystore.1
// (file) opt/keystore.1 (actual certificate)
FS.ensureEmpty(sslDir);
FS.ensureEmpty(optDir);
Files.copy(oldKeyStoreSrc, optKeystore1);
Files.createSymbolicLink(optKeystoreLink, optKeystore1);
Files.createSymbolicLink(keystoreFile, optKeystoreLink);
sslContextFactory.setKeyStorePath(keystoreFile.toString());
sslContextFactory.setKeyStorePassword("storepwd");
sslContextFactory.setKeyManagerPassword("keypwd");
});
// Check the original certificate expiry.
X509Certificate cert1 = getCertificateFromServer();
assertThat(getExpiryYear(cert1), is(2015));
// Create a new keystore file opt/keystore.2 with new expiry
Files.copy(newKeyStoreSrc, optKeystore2);
// Change (link) opt/keystore -> opt/keystore.2
Files.delete(optKeystoreLink);
Files.createSymbolicLink(optKeystoreLink, optKeystore2);
System.err.println("### Triggering scan");
keyStoreScanner.scan(5000);
// The scanner should have detected the updated keystore, expiry should be renewed.
X509Certificate cert2 = getCertificateFromServer();
assertThat(getExpiryYear(cert2), is(2020));
}
/**
* Test a keystore, where the monitored directory is a symlink.
*/
@Test
public void testSymlinkedMonitoredDirectory() throws Exception
{
assumeFileSystemSupportsSymlink();
Path oldKeyStoreSrc = MavenTestingUtils.getTestResourcePathFile("oldKeyStore");
Path newKeyStoreSrc = MavenTestingUtils.getTestResourcePathFile("newKeyStore");
Path dataLinkDir = keystoreDir.resolve("data_symlink");
Path dataDir = keystoreDir.resolve("data");
Path etcDir = keystoreDir.resolve("etc");
Path dataLinkKeystore = dataLinkDir.resolve("keystore");
Path dataKeystore = dataDir.resolve("keystore");
Path etcKeystore = etcDir.resolve("keystore");
start(sslContextFactory ->
{
// What we want is ..
// (link) data_symlink/ -> data/
// (link) data/keystore -> etc/keystore
// (file) etc/keystore (actual certificate)
FS.ensureEmpty(etcDir);
FS.ensureEmpty(dataDir);
Files.copy(oldKeyStoreSrc, etcKeystore);
Files.createSymbolicLink(dataLinkDir, dataDir);
Files.createSymbolicLink(dataKeystore, etcKeystore);
sslContextFactory.setKeyStorePath(dataLinkKeystore.toString());
sslContextFactory.setKeyStorePassword("storepwd");
sslContextFactory.setKeyManagerPassword("keypwd");
});
// Check the original certificate expiry.
X509Certificate cert1 = getCertificateFromServer();
assertThat(getExpiryYear(cert1), is(2015));
// Update etc/keystore
Files.copy(newKeyStoreSrc, etcKeystore, StandardCopyOption.REPLACE_EXISTING);
System.err.println("### Triggering scan");
keyStoreScanner.scan(5000);
// The scanner should have detected the updated keystore, expiry should be renewed.
X509Certificate cert2 = getCertificateFromServer();
assertThat(getExpiryYear(cert2), is(2020));
}
/**
* Test a doubly-linked keystore, and refreshing by only modifying the middle symlink.
*/
@Test
public void testDoublySymlinkedTimestampedDir() throws Exception
{
assumeFileSystemSupportsSymlink();
Path oldKeyStoreSrc = MavenTestingUtils.getTestResourcePathFile("oldKeyStore");
Path newKeyStoreSrc = MavenTestingUtils.getTestResourcePathFile("newKeyStore");
Path sslDir = keystoreDir.resolve("ssl");
Path dataDir = sslDir.resolve("data");
Path timestampNovDir = sslDir.resolve("2022-11");
Path timestampDecDir = sslDir.resolve("2022-12");
Path targetNov = timestampNovDir.resolve("keystore.p12");
Path targetDec = timestampDecDir.resolve("keystore.p12");
start(sslContextFactory ->
{
// What we want is ..
// (link) keystore.p12 -> data/keystore.p12
// (link) data/ -> 2022-11/
// (file) 2022-11/keystore.p12 (actual certificate)
FS.ensureEmpty(sslDir);
FS.ensureEmpty(timestampNovDir);
FS.ensureEmpty(timestampDecDir);
Files.copy(oldKeyStoreSrc, targetNov);
Files.copy(newKeyStoreSrc, targetDec);
// Create symlink of data/ to 2022-11/
Files.createSymbolicLink(dataDir, timestampNovDir.getFileName());
// Create symlink of keystore.p12 to data/keystore.p12
Path keystoreLink = sslDir.resolve("keystore.p12");
Files.createSymbolicLink(keystoreLink, Paths.get("data/keystore.p12"));
sslContextFactory.setKeyStorePath(keystoreLink.toString());
sslContextFactory.setKeyStorePassword("storepwd");
sslContextFactory.setKeyManagerPassword("keypwd");
});
// Check the original certificate expiry.
X509Certificate cert1 = getCertificateFromServer();
assertThat(getExpiryYear(cert1), is(2015));
// Replace keystore link
Files.delete(dataDir);
Files.createSymbolicLink(dataDir, timestampDecDir.getFileName());
// (link) data/ -> 2022-12/
// now keystore.p12 points to data/keystore.p12 which points to 2022-12/keystore.p12
System.err.println("### Triggering scan");
keyStoreScanner.scan(5000);
// The scanner should have detected the updated keystore, expiry should be renewed.
X509Certificate cert2 = getCertificateFromServer();
assertThat(getExpiryYear(cert2), is(2020));
}
public Path useKeystore(String keystoreToUse, String keystorePath) throws Exception
{
return useKeystore(MavenTestingUtils.getTestResourcePath(keystoreToUse), keystoreDir.resolve(keystorePath));
}
public Path useKeystore(Path keystoreToUse, Path keystorePath) throws Exception
{
if (Files.exists(keystorePath))
Files.delete(keystorePath);
Files.copy(keystoreToUse, keystorePath);
if (!Files.exists(keystorePath))
throw new IllegalStateException("keystore file was not created");
return keystorePath.toAbsolutePath();
}
public Path useKeystore(String keystore) throws Exception
{
Path keystorePath = keystoreDir.resolve("keystore");
if (Files.exists(keystorePath))
Files.delete(keystorePath);
Files.copy(MavenTestingUtils.getTestResourcePath(keystore), keystorePath);
if (!Files.exists(keystorePath))
throw new IllegalStateException("keystore file was not created");
return keystorePath.toAbsolutePath();
}
public static int getExpiryYear(X509Certificate cert)
{
Calendar instance = Calendar.getInstance();
instance.setTime(cert.getNotAfter());
return instance.get(Calendar.YEAR);
}
public X509Certificate getCertificateFromServer() throws Exception
{
URL serverUrl = server.getURI().toURL();
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
HttpsURLConnection connection = (HttpsURLConnection)serverUrl.openConnection();
connection.setHostnameVerifier((a, b) -> true);
connection.setRequestProperty("Connection", "close");
connection.connect();
Certificate[] certs = connection.getServerCertificates();
connection.disconnect();
assertThat(certs.length, is(1));
return (X509Certificate)certs[0];
}
private void assumeFileSystemSupportsSymlink() throws IOException
{
// Make symlink
Path dir = MavenTestingUtils.getTargetTestingPath("symlink-test");
FS.ensureEmpty(dir);
Path foo = dir.resolve("foo");
Path bar = dir.resolve("bar");
try
{
Files.createFile(foo);
Files.createSymbolicLink(bar, foo);
}
catch (UnsupportedOperationException | FileSystemException e)
{
// if unable to create symlink, no point testing the rest
// this is the path that Microsoft Windows takes.
assumeFalse(true, "Not supported");
}
}
private static class DefaultTrustManager implements X509TrustManager
{
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
{
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
{
}
@Override
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
}
}