Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/openjdk-multiarch-jdk8u
Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java
38853 views
1
/*
2
* Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved.
3
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4
*
5
* This code is free software; you can redistribute it and/or modify it
6
* under the terms of the GNU General Public License version 2 only, as
7
* published by the Free Software Foundation.
8
*
9
* This code is distributed in the hope that it will be useful, but WITHOUT
10
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12
* version 2 for more details (a copy is included in the LICENSE file that
13
* accompanied this code).
14
*
15
* You should have received a copy of the GNU General Public License version
16
* 2 along with this work; if not, write to the Free Software Foundation,
17
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
*
19
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20
* or visit www.oracle.com if you need additional information or have any
21
* questions.
22
*/
23
24
import com.sun.net.httpserver.*;
25
26
import java.io.ByteArrayInputStream;
27
import java.io.ByteArrayOutputStream;
28
import java.io.File;
29
import java.io.FileInputStream;
30
import java.io.IOException;
31
import java.io.InputStream;
32
import java.io.OutputStream;
33
import java.math.BigInteger;
34
import java.net.InetSocketAddress;
35
import java.nio.file.Files;
36
import java.nio.file.Paths;
37
import java.security.KeyStore;
38
import java.security.PrivateKey;
39
import java.security.Signature;
40
import java.security.cert.Certificate;
41
import java.security.cert.CertificateException;
42
import java.security.cert.CertificateFactory;
43
import java.security.cert.X509Certificate;
44
import java.time.Instant;
45
import java.time.temporal.ChronoUnit;
46
import java.util.*;
47
import java.util.jar.JarEntry;
48
import java.util.jar.JarFile;
49
50
import sun.misc.IOUtils;
51
import jdk.testlibrary.SecurityTools;
52
import jdk.testlibrary.OutputAnalyzer;
53
import jdk.testlibrary.JarUtils;
54
import sun.security.pkcs.ContentInfo;
55
import sun.security.pkcs.PKCS7;
56
import sun.security.pkcs.PKCS9Attribute;
57
import sun.security.pkcs.SignerInfo;
58
import sun.security.timestamp.TimestampToken;
59
import sun.security.util.DerOutputStream;
60
import sun.security.util.DerValue;
61
import sun.security.util.ObjectIdentifier;
62
import sun.security.x509.AlgorithmId;
63
import sun.security.x509.X500Name;
64
65
import jdk.testlibrary.Utils;
66
67
/*
68
* @test
69
* @bug 6543842 6543440 6939248 8009636 8024302 8163304 8169911 8169688 8171121
70
* 8180289 8172404
71
* @summary checking response of timestamp
72
* @modules java.base/sun.security.pkcs
73
* java.base/sun.security.timestamp
74
* java.base/sun.security.x509
75
* java.base/sun.security.util
76
* java.base/sun.security.tools.keytool
77
* @library /lib/testlibrary
78
* @compile -XDignore.symbol.file TimestampCheck.java
79
* @run main/othervm/timeout=600 TimestampCheck
80
*/
81
public class TimestampCheck {
82
83
static final String defaultPolicyId = "2.3.4";
84
static String host = null;
85
86
static class Handler implements HttpHandler, AutoCloseable {
87
88
private final HttpServer httpServer;
89
private final String keystore;
90
91
@Override
92
public void handle(HttpExchange t) throws IOException {
93
int len = 0;
94
for (String h: t.getRequestHeaders().keySet()) {
95
if (h.equalsIgnoreCase("Content-length")) {
96
len = Integer.valueOf(t.getRequestHeaders().get(h).get(0));
97
}
98
}
99
byte[] input = new byte[len];
100
t.getRequestBody().read(input);
101
102
try {
103
String path = t.getRequestURI().getPath().substring(1);
104
byte[] output = sign(input, path);
105
Headers out = t.getResponseHeaders();
106
out.set("Content-Type", "application/timestamp-reply");
107
108
t.sendResponseHeaders(200, output.length);
109
OutputStream os = t.getResponseBody();
110
os.write(output);
111
} catch (Exception e) {
112
e.printStackTrace();
113
t.sendResponseHeaders(500, 0);
114
}
115
t.close();
116
}
117
118
/**
119
* @param input The data to sign
120
* @param path different cases to simulate, impl on URL path
121
* @returns the signed
122
*/
123
byte[] sign(byte[] input, String path) throws Exception {
124
DerValue value = new DerValue(input);
125
System.out.println("#\n# Incoming Request\n===================");
126
System.out.println("# Version: " + value.data.getInteger());
127
DerValue messageImprint = value.data.getDerValue();
128
AlgorithmId aid = AlgorithmId.parse(
129
messageImprint.data.getDerValue());
130
System.out.println("# AlgorithmId: " + aid);
131
132
ObjectIdentifier policyId = new ObjectIdentifier(defaultPolicyId);
133
BigInteger nonce = null;
134
while (value.data.available() > 0) {
135
DerValue v = value.data.getDerValue();
136
if (v.tag == DerValue.tag_Integer) {
137
nonce = v.getBigInteger();
138
System.out.println("# nonce: " + nonce);
139
} else if (v.tag == DerValue.tag_Boolean) {
140
System.out.println("# certReq: " + v.getBoolean());
141
} else if (v.tag == DerValue.tag_ObjectId) {
142
policyId = v.getOID();
143
System.out.println("# PolicyID: " + policyId);
144
}
145
}
146
147
System.out.println("#\n# Response\n===================");
148
FileInputStream is = new FileInputStream(keystore);
149
KeyStore ks = KeyStore.getInstance("JCEKS");
150
ks.load(is, "changeit".toCharArray());
151
is.close();
152
153
// If path starts with "ts", use the TSA it points to.
154
// Otherwise, always use "ts".
155
String alias = path.startsWith("ts") ? path : "ts";
156
157
if (path.equals("diffpolicy")) {
158
policyId = new ObjectIdentifier(defaultPolicyId);
159
}
160
161
DerOutputStream statusInfo = new DerOutputStream();
162
statusInfo.putInteger(0);
163
164
AlgorithmId[] algorithms = {aid};
165
Certificate[] chain = ks.getCertificateChain(alias);
166
X509Certificate[] signerCertificateChain;
167
X509Certificate signer = (X509Certificate)chain[0];
168
169
if (path.equals("fullchain")) { // Only case 5 uses full chain
170
signerCertificateChain = new X509Certificate[chain.length];
171
for (int i=0; i<chain.length; i++) {
172
signerCertificateChain[i] = (X509Certificate)chain[i];
173
}
174
} else if (path.equals("nocert")) {
175
signerCertificateChain = new X509Certificate[0];
176
} else {
177
signerCertificateChain = new X509Certificate[1];
178
signerCertificateChain[0] = (X509Certificate)chain[0];
179
}
180
181
DerOutputStream tst = new DerOutputStream();
182
183
tst.putInteger(1);
184
tst.putOID(policyId);
185
186
if (!path.equals("baddigest") && !path.equals("diffalg")) {
187
tst.putDerValue(messageImprint);
188
} else {
189
byte[] data = messageImprint.toByteArray();
190
if (path.equals("diffalg")) {
191
data[6] = (byte)0x01;
192
} else {
193
data[data.length-1] = (byte)0x01;
194
data[data.length-2] = (byte)0x02;
195
data[data.length-3] = (byte)0x03;
196
}
197
tst.write(data);
198
}
199
200
tst.putInteger(1);
201
202
Instant instant = Instant.now();
203
if (path.equals("tsold")) {
204
instant = instant.minus(20, ChronoUnit.DAYS);
205
}
206
tst.putGeneralizedTime(Date.from(instant));
207
208
if (path.equals("diffnonce")) {
209
tst.putInteger(1234);
210
} else if (path.equals("nononce")) {
211
// no noce
212
} else {
213
tst.putInteger(nonce);
214
}
215
216
DerOutputStream tstInfo = new DerOutputStream();
217
tstInfo.write(DerValue.tag_Sequence, tst);
218
219
DerOutputStream tstInfo2 = new DerOutputStream();
220
tstInfo2.putOctetString(tstInfo.toByteArray());
221
222
// Always use the same algorithm at timestamp signing
223
// so it is different from the hash algorithm.
224
String sigAlg = "SHA256withRSA";
225
Signature sig = Signature.getInstance(sigAlg);
226
sig.initSign((PrivateKey)(ks.getKey(
227
alias, "changeit".toCharArray())));
228
sig.update(tstInfo.toByteArray());
229
230
ContentInfo contentInfo = new ContentInfo(new ObjectIdentifier(
231
"1.2.840.113549.1.9.16.1.4"),
232
new DerValue(tstInfo2.toByteArray()));
233
234
System.out.println("# Signing...");
235
System.out.println("# " + new X500Name(signer
236
.getIssuerX500Principal().getName()));
237
System.out.println("# " + signer.getSerialNumber());
238
239
SignerInfo signerInfo = new SignerInfo(
240
new X500Name(signer.getIssuerX500Principal().getName()),
241
signer.getSerialNumber(),
242
AlgorithmId.get(AlgorithmId.getDigAlgFromSigAlg(sigAlg)),
243
AlgorithmId.get(AlgorithmId.getEncAlgFromSigAlg(sigAlg)),
244
sig.sign());
245
246
SignerInfo[] signerInfos = {signerInfo};
247
PKCS7 p7 = new PKCS7(algorithms, contentInfo,
248
signerCertificateChain, signerInfos);
249
ByteArrayOutputStream p7out = new ByteArrayOutputStream();
250
p7.encodeSignedData(p7out);
251
252
DerOutputStream response = new DerOutputStream();
253
response.write(DerValue.tag_Sequence, statusInfo);
254
response.putDerValue(new DerValue(p7out.toByteArray()));
255
256
DerOutputStream out = new DerOutputStream();
257
out.write(DerValue.tag_Sequence, response);
258
259
return out.toByteArray();
260
}
261
262
private Handler(HttpServer httpServer, String keystore) {
263
this.httpServer = httpServer;
264
this.keystore = keystore;
265
}
266
267
/**
268
* Initialize TSA instance.
269
*
270
* Extended Key Info extension of certificate that is used for
271
* signing TSA responses should contain timeStamping value.
272
*/
273
static Handler init(int port, String keystore) throws IOException {
274
HttpServer httpServer = HttpServer.create(
275
new InetSocketAddress(port), 0);
276
Handler tsa = new Handler(httpServer, keystore);
277
httpServer.createContext("/", tsa);
278
return tsa;
279
}
280
281
/**
282
* Start TSA service.
283
*/
284
void start() {
285
httpServer.start();
286
}
287
288
/**
289
* Stop TSA service.
290
*/
291
void stop() {
292
httpServer.stop(0);
293
}
294
295
/**
296
* Return server port number.
297
*/
298
int getPort() {
299
return httpServer.getAddress().getPort();
300
}
301
302
@Override
303
public void close() throws Exception {
304
stop();
305
}
306
}
307
308
public static void main(String[] args) throws Throwable {
309
310
try (Handler tsa = Handler.init(0, "ks");) {
311
tsa.start();
312
int port = tsa.getPort();
313
314
host = "http://localhost:" + port + "/";
315
316
if (args.length == 0) { // Run this test
317
318
prepare();
319
320
sign("normal")
321
.shouldNotContain("Warning")
322
.shouldContain("The signer certificate will expire on")
323
.shouldContain("The timestamp will expire on")
324
.shouldHaveExitValue(0);
325
326
verify("normal.jar")
327
.shouldNotContain("Warning")
328
.shouldHaveExitValue(0);
329
330
verify("normal.jar", "-verbose")
331
.shouldNotContain("Warning")
332
.shouldContain("The signer certificate will expire on")
333
.shouldContain("The timestamp will expire on")
334
.shouldHaveExitValue(0);
335
336
// Simulate signing at a previous date:
337
// 1. tsold will create a timestamp of 20 days ago.
338
// 2. oldsigner expired 10 days ago.
339
signVerbose("tsold", "unsigned.jar", "tsold.jar", "oldsigner")
340
.shouldNotContain("Warning")
341
.shouldMatch("signer certificate expired on .*. "
342
+ "However, the JAR will be valid")
343
.shouldHaveExitValue(0);
344
345
// It verifies perfectly.
346
verify("tsold.jar", "-verbose", "-certs")
347
.shouldNotContain("Warning")
348
.shouldMatch("signer certificate expired on .*. "
349
+ "However, the JAR will be valid")
350
.shouldHaveExitValue(0);
351
352
// No timestamp
353
signVerbose(null, "unsigned.jar", "none.jar", "signer")
354
.shouldContain("is not timestamped")
355
.shouldContain("The signer certificate will expire on")
356
.shouldHaveExitValue(0);
357
358
verify("none.jar", "-verbose")
359
.shouldContain("do not include a timestamp")
360
.shouldContain("The signer certificate will expire on")
361
.shouldHaveExitValue(0);
362
363
// Error cases
364
365
signVerbose(null, "unsigned.jar", "badku.jar", "badku")
366
.shouldContain("KeyUsage extension doesn't allow code signing")
367
.shouldHaveExitValue(8);
368
checkBadKU("badku.jar");
369
370
// 8180289: unvalidated TSA cert chain
371
sign("tsnoca")
372
.shouldContain("The TSA certificate chain is invalid. "
373
+ "Reason: Path does not chain with any of the trust anchors")
374
.shouldHaveExitValue(64);
375
376
verify("tsnoca.jar", "-verbose", "-certs")
377
.shouldHaveExitValue(64)
378
.shouldContain("jar verified")
379
.shouldContain("Invalid TSA certificate chain: "
380
+ "Path does not chain with any of the trust anchors")
381
.shouldContain("TSA certificate chain is invalid."
382
+ " Reason: Path does not chain with any of the trust anchors");
383
384
sign("nononce")
385
.shouldContain("Nonce missing in timestamp token")
386
.shouldHaveExitValue(1);
387
sign("diffnonce")
388
.shouldContain("Nonce changed in timestamp token")
389
.shouldHaveExitValue(1);
390
sign("baddigest")
391
.shouldContain("Digest octets changed in timestamp token")
392
.shouldHaveExitValue(1);
393
sign("diffalg")
394
.shouldContain("Digest algorithm not")
395
.shouldHaveExitValue(1);
396
397
sign("fullchain")
398
.shouldHaveExitValue(0); // Success, 6543440 solved.
399
400
sign("tsbad1")
401
.shouldContain("Certificate is not valid for timestamping")
402
.shouldHaveExitValue(1);
403
sign("tsbad2")
404
.shouldContain("Certificate is not valid for timestamping")
405
.shouldHaveExitValue(1);
406
sign("tsbad3")
407
.shouldContain("Certificate is not valid for timestamping")
408
.shouldHaveExitValue(1);
409
sign("nocert")
410
.shouldContain("Certificate not included in timestamp token")
411
.shouldHaveExitValue(1);
412
413
sign("policy", "-tsapolicyid", "1.2.3")
414
.shouldHaveExitValue(0);
415
checkTimestamp("policy.jar", "1.2.3", "SHA-256");
416
417
sign("diffpolicy", "-tsapolicyid", "1.2.3")
418
.shouldContain("TSAPolicyID changed in timestamp token")
419
.shouldHaveExitValue(1);
420
421
sign("sha384alg", "-tsadigestalg", "SHA-384")
422
.shouldHaveExitValue(0);
423
checkTimestamp("sha384alg.jar", defaultPolicyId, "SHA-384");
424
425
// Legacy algorithms
426
signVerbose(null, "unsigned.jar", "sha1alg.jar", "signer",
427
"-strict", "-digestalg", "SHA-1")
428
.shouldHaveExitValue(0)
429
.shouldContain("jar signed, with signer errors")
430
.shouldMatch("SHA-1.*-digestalg.*will be disabled");
431
verify("sha1alg.jar", "-strict")
432
.shouldHaveExitValue(0)
433
.shouldContain("jar verified, with signer errors")
434
.shouldContain("SHA-1 digest algorithm is considered a security risk")
435
.shouldContain("This algorithm will be disabled in a future update")
436
.shouldNotContain("is disabled");
437
438
sign("sha1tsaalg", "-tsadigestalg", "SHA-1", "-strict")
439
.shouldHaveExitValue(0)
440
.shouldContain("jar signed, with signer errors")
441
.shouldMatch("SHA-1.*-tsadigestalg.*will be disabled")
442
.shouldNotContain("is disabled");
443
verify("sha1tsaalg.jar", "-strict")
444
.shouldHaveExitValue(0)
445
.shouldContain("jar verified, with signer errors")
446
.shouldContain("SHA-1 digest algorithm is considered a security risk")
447
.shouldNotContain("is disabled");
448
449
// Disabled algorithms
450
sign("tsdisabled", "-digestalg", "MD5",
451
"-sigalg", "MD5withRSA", "-tsadigestalg", "MD5")
452
.shouldHaveExitValue(68)
453
.shouldContain("TSA certificate chain is invalid")
454
.shouldMatch("MD5.*-digestalg.*is disabled")
455
.shouldMatch("MD5.*-tsadigestalg.*is disabled")
456
.shouldMatch("MD5withRSA.*-sigalg.*is disabled");
457
checkDisabled("tsdisabled.jar");
458
459
signVerbose("tsdisabled", "unsigned.jar", "tsdisabled2.jar", "signer")
460
.shouldHaveExitValue(64)
461
.shouldContain("TSA certificate chain is invalid");
462
463
// Disabled timestamp is an error and jar treated unsigned
464
verify("tsdisabled2.jar", "-verbose")
465
.shouldHaveExitValue(16)
466
.shouldContain("treated as unsigned")
467
.shouldMatch("Timestamp.*512.*(disabled)");
468
469
// Algorithm used in signing is disabled
470
signVerbose("normal", "unsigned.jar", "halfDisabled.jar", "signer",
471
"-digestalg", "MD5")
472
.shouldContain("-digestalg option is considered a security risk and is disabled")
473
.shouldHaveExitValue(4);
474
checkHalfDisabled("halfDisabled.jar");
475
476
// sign with DSA key
477
signVerbose("normal", "unsigned.jar", "sign1.jar", "dsakey")
478
.shouldHaveExitValue(0);
479
480
// sign with RSAkeysize < 1024
481
signVerbose("normal", "sign1.jar", "sign2.jar", "disabledkeysize")
482
.shouldContain("Algorithm constraints check failed on keysize")
483
.shouldHaveExitValue(4);
484
checkMultiple("sign2.jar");
485
486
// Legacy algorithms
487
sign("tsweak", "-digestalg", "SHA1",
488
"-sigalg", "SHA1withRSA", "-tsadigestalg", "SHA1")
489
.shouldHaveExitValue(0)
490
.shouldMatch("SHA1.*-digestalg.*will be disabled")
491
.shouldMatch("SHA1.*-tsadigestalg.*will be disabled")
492
.shouldMatch("SHA1withRSA.*-sigalg.*will be disabled");
493
checkWeak("tsweak.jar");
494
495
signVerbose("tsweak", "unsigned.jar", "tsweak2.jar", "signer")
496
.shouldHaveExitValue(0);
497
498
verify("tsweak2.jar", "-verbose")
499
.shouldHaveExitValue(0)
500
.shouldContain("jar verified")
501
.shouldMatch("Timestamp.*1024.*(weak)");
502
503
// Algorithm used in signing is weak
504
signVerbose("normal", "unsigned.jar", "halfWeak.jar", "signer",
505
"-digestalg", "SHA1")
506
.shouldContain("-digestalg option is considered a security risk.")
507
.shouldContain("This algorithm will be disabled in a future update.")
508
.shouldHaveExitValue(0);
509
checkHalfWeak("halfWeak.jar");
510
511
// sign with DSA key
512
signVerbose("normal", "unsigned.jar", "sign1.jar", "dsakey")
513
.shouldHaveExitValue(0);
514
515
// sign with RSAkeysize < 2048
516
signVerbose("normal", "sign1.jar", "sign2.jar", "weakkeysize")
517
.shouldNotContain("Algorithm constraints check failed on keysize")
518
.shouldHaveExitValue(0);
519
checkMultipleWeak("sign2.jar");
520
521
522
// 8191438: jarsigner should print when a timestamp will expire
523
checkExpiration();
524
525
// When .SF or .RSA is missing or invalid
526
checkMissingOrInvalidFiles("normal.jar");
527
528
if (Files.exists(Paths.get("ts2.cert"))) {
529
checkInvalidTsaCertKeyUsage();
530
}
531
} else { // Run as a standalone server
532
System.out.println("TSA started at " + host
533
+ ". Press Enter to quit server");
534
System.in.read();
535
}
536
}
537
}
538
539
private static void checkExpiration() throws Exception {
540
541
// Warning when expired or expiring
542
signVerbose(null, "unsigned.jar", "expired.jar", "expired")
543
.shouldContain("signer certificate has expired")
544
.shouldHaveExitValue(4);
545
verify("expired.jar")
546
.shouldContain("signer certificate has expired")
547
.shouldHaveExitValue(4);
548
signVerbose(null, "unsigned.jar", "expiring.jar", "expiring")
549
.shouldContain("signer certificate will expire within")
550
.shouldHaveExitValue(0);
551
verify("expiring.jar")
552
.shouldContain("signer certificate will expire within")
553
.shouldHaveExitValue(0);
554
// Info for long
555
signVerbose(null, "unsigned.jar", "long.jar", "long")
556
.shouldNotContain("signer certificate has expired")
557
.shouldNotContain("signer certificate will expire within")
558
.shouldContain("signer certificate will expire on")
559
.shouldHaveExitValue(0);
560
verify("long.jar")
561
.shouldNotContain("signer certificate has expired")
562
.shouldNotContain("signer certificate will expire within")
563
.shouldNotContain("The signer certificate will expire")
564
.shouldHaveExitValue(0);
565
verify("long.jar", "-verbose")
566
.shouldContain("The signer certificate will expire")
567
.shouldHaveExitValue(0);
568
569
// Both expired
570
signVerbose("tsexpired", "unsigned.jar",
571
"tsexpired-expired.jar", "expired")
572
.shouldContain("The signer certificate has expired.")
573
.shouldContain("The timestamp has expired.")
574
.shouldHaveExitValue(4);
575
verify("tsexpired-expired.jar")
576
.shouldContain("signer certificate has expired")
577
.shouldContain("timestamp has expired.")
578
.shouldHaveExitValue(4);
579
580
// TS expired but signer still good
581
signVerbose("tsexpired", "unsigned.jar",
582
"tsexpired-long.jar", "long")
583
.shouldContain("The timestamp expired on")
584
.shouldHaveExitValue(0);
585
verify("tsexpired-long.jar")
586
.shouldMatch("timestamp expired on.*However, the JAR will be valid")
587
.shouldNotContain("Error")
588
.shouldHaveExitValue(0);
589
590
signVerbose("tsexpired", "unsigned.jar",
591
"tsexpired-ca.jar", "ca")
592
.shouldContain("The timestamp has expired.")
593
.shouldHaveExitValue(4);
594
verify("tsexpired-ca.jar")
595
.shouldNotContain("timestamp has expired")
596
.shouldNotContain("Error")
597
.shouldHaveExitValue(0);
598
599
// Warning when expiring
600
sign("tsexpiring")
601
.shouldContain("timestamp will expire within")
602
.shouldHaveExitValue(0);
603
verify("tsexpiring.jar")
604
.shouldContain("timestamp will expire within")
605
.shouldNotContain("still valid")
606
.shouldHaveExitValue(0);
607
608
signVerbose("tsexpiring", "unsigned.jar",
609
"tsexpiring-ca.jar", "ca")
610
.shouldContain("self-signed")
611
.stderrShouldNotMatch("The.*expir")
612
.shouldHaveExitValue(4); // self-signed
613
verify("tsexpiring-ca.jar")
614
.stderrShouldNotMatch("The.*expir")
615
.shouldHaveExitValue(0);
616
617
signVerbose("tsexpiringsoon", "unsigned.jar",
618
"tsexpiringsoon-long.jar", "long")
619
.shouldContain("The timestamp will expire")
620
.shouldHaveExitValue(0);
621
verify("tsexpiringsoon-long.jar")
622
.shouldMatch("timestamp will expire.*However, the JAR will be valid until")
623
.shouldHaveExitValue(0);
624
625
// Info for long
626
sign("tslong")
627
.shouldNotContain("timestamp has expired")
628
.shouldNotContain("timestamp will expire within")
629
.shouldContain("timestamp will expire on")
630
.shouldContain("signer certificate will expire on")
631
.shouldHaveExitValue(0);
632
verify("tslong.jar")
633
.shouldNotContain("timestamp has expired")
634
.shouldNotContain("timestamp will expire within")
635
.shouldNotContain("timestamp will expire on")
636
.shouldNotContain("signer certificate will expire on")
637
.shouldHaveExitValue(0);
638
verify("tslong.jar", "-verbose")
639
.shouldContain("timestamp will expire on")
640
.shouldContain("signer certificate will expire on")
641
.shouldHaveExitValue(0);
642
}
643
644
private static void checkInvalidTsaCertKeyUsage() throws Exception {
645
646
// Hack: Rewrite the TSA cert inside normal.jar into ts2.jar.
647
648
// Both the cert and the serial number must be rewritten.
649
byte[] tsCert = Files.readAllBytes(Paths.get("ts.cert"));
650
byte[] ts2Cert = Files.readAllBytes(Paths.get("ts2.cert"));
651
byte[] tsSerial = getCert(tsCert)
652
.getSerialNumber().toByteArray();
653
byte[] ts2Serial = getCert(ts2Cert)
654
.getSerialNumber().toByteArray();
655
656
byte[] oldBlock;
657
try (JarFile normal = new JarFile("normal.jar")) {
658
oldBlock = Utils.readAllBytes(normal.getInputStream(
659
normal.getJarEntry("META-INF/SIGNER.RSA")));
660
}
661
662
JarUtils.updateJar("normal.jar", "ts2.jar",
663
mapOf("META-INF/SIGNER.RSA",
664
updateBytes(updateBytes(oldBlock, tsCert, ts2Cert),
665
tsSerial, ts2Serial)));
666
667
verify("ts2.jar", "-verbose", "-certs")
668
.shouldHaveExitValue(64)
669
.shouldContain("jar verified")
670
.shouldContain("Invalid TSA certificate chain: Extended key usage does not permit use for TSA server");
671
}
672
673
public static X509Certificate getCert(byte[] data)
674
throws CertificateException, IOException {
675
return (X509Certificate)
676
CertificateFactory.getInstance("X.509")
677
.generateCertificate(new ByteArrayInputStream(data));
678
}
679
680
private static byte[] updateBytes(byte[] old, byte[] from, byte[] to) {
681
int pos = 0;
682
while (true) {
683
if (pos + from.length > old.length) {
684
return null;
685
}
686
if (Arrays.equals(Arrays.copyOfRange(old, pos, pos+from.length), from)) {
687
byte[] result = old.clone();
688
System.arraycopy(to, 0, result, pos, from.length);
689
return result;
690
}
691
pos++;
692
}
693
}
694
695
private static void checkMissingOrInvalidFiles(String s)
696
throws Throwable {
697
698
JarUtils.updateJar(s, "1.jar", mapOf("META-INF/SIGNER.SF", Boolean.FALSE));
699
verify("1.jar", "-verbose")
700
.shouldHaveExitValue(16)
701
.shouldContain("treated as unsigned")
702
.shouldContain("Missing signature-related file META-INF/SIGNER.SF");
703
JarUtils.updateJar(s, "2.jar", mapOf("META-INF/SIGNER.RSA", Boolean.FALSE));
704
verify("2.jar", "-verbose")
705
.shouldHaveExitValue(16)
706
.shouldContain("treated as unsigned")
707
.shouldContain("Missing block file for signature-related file META-INF/SIGNER.SF");
708
JarUtils.updateJar(s, "3.jar", mapOf("META-INF/SIGNER.SF", "dummy"));
709
verify("3.jar", "-verbose")
710
.shouldHaveExitValue(16)
711
.shouldContain("treated as unsigned")
712
.shouldContain("Unparsable signature-related file META-INF/SIGNER.SF");
713
JarUtils.updateJar(s, "4.jar", mapOf("META-INF/SIGNER.RSA", "dummy"));
714
verify("4.jar", "-verbose")
715
.shouldHaveExitValue(16)
716
.shouldContain("treated as unsigned")
717
.shouldContain("Unparsable signature-related file META-INF/SIGNER.RSA");
718
}
719
720
static OutputAnalyzer jarsigner(List<String> extra)
721
throws Exception {
722
List<String> args = new ArrayList<>(
723
listOf("-keystore", "ks", "-storepass", "changeit"));
724
args.addAll(extra);
725
return SecurityTools.jarsigner(args);
726
}
727
728
static OutputAnalyzer verify(String file, String... extra)
729
throws Exception {
730
List<String> args = new ArrayList<>();
731
args.add("-verify");
732
args.add("-strict");
733
args.add(file);
734
args.addAll(Arrays.asList(extra));
735
return jarsigner(args);
736
}
737
738
static void checkBadKU(String file) throws Exception {
739
System.err.println("BadKU: " + file);
740
verify(file)
741
.shouldHaveExitValue(16)
742
.shouldContain("treated as unsigned")
743
.shouldContain("re-run jarsigner with debug enabled");
744
verify(file, "-verbose")
745
.shouldHaveExitValue(16)
746
.shouldContain("Signed by")
747
.shouldContain("treated as unsigned")
748
.shouldContain("re-run jarsigner with debug enabled");
749
verify(file, "-J-Djava.security.debug=jar")
750
.shouldHaveExitValue(16)
751
.shouldContain("SignatureException: Key usage restricted")
752
.shouldContain("treated as unsigned")
753
.shouldContain("re-run jarsigner with debug enabled");
754
}
755
756
static void checkDisabled(String file) throws Exception {
757
verify(file)
758
.shouldHaveExitValue(16)
759
.shouldContain("treated as unsigned")
760
.shouldMatch("weak algorithm that is now disabled.")
761
.shouldMatch("Re-run jarsigner with the -verbose option for more details");
762
verify(file, "-verbose")
763
.shouldHaveExitValue(16)
764
.shouldContain("treated as unsigned")
765
.shouldMatch("weak algorithm that is now disabled by")
766
.shouldMatch("Digest algorithm: .*(disabled)")
767
.shouldMatch("Signature algorithm: .*(disabled)")
768
.shouldMatch("Timestamp digest algorithm: .*(disabled)")
769
.shouldNotMatch("Timestamp signature algorithm: .*(weak).*(weak)")
770
.shouldMatch("Timestamp signature algorithm: .*key.*(disabled)");
771
verify(file, "-J-Djava.security.debug=jar")
772
.shouldHaveExitValue(16)
773
.shouldMatch("SignatureException:.*keysize");
774
}
775
776
static void checkHalfWeak(String file) throws Exception {
777
verify(file)
778
.shouldHaveExitValue(0)
779
.shouldNotContain("treated as unsigned");
780
verify(file, "-verbose")
781
.shouldHaveExitValue(0)
782
.shouldNotContain("treated as unsigned")
783
.shouldMatch("Digest algorithm: .*(weak)")
784
.shouldNotMatch("Signature algorithm: .*(weak)")
785
.shouldNotMatch("Signature algorithm: .*(disabled)")
786
.shouldNotMatch("Timestamp digest algorithm: .*(weak)")
787
.shouldNotMatch("Timestamp signature algorithm: .*(weak).*(weak)")
788
.shouldNotMatch("Timestamp signature algorithm: .*(disabled).*(disabled)")
789
.shouldNotMatch("Timestamp signature algorithm: .*key.*(weak)")
790
.shouldNotMatch("Timestamp signature algorithm: .*key.*(disabled)");
791
}
792
793
static void checkMultiple(String file) throws Exception {
794
verify(file)
795
.shouldHaveExitValue(0)
796
.shouldContain("jar verified");
797
verify(file, "-verbose", "-certs")
798
.shouldHaveExitValue(0)
799
.shouldContain("jar verified")
800
.shouldMatch("X.509.*CN=dsakey")
801
.shouldNotMatch("X.509.*CN=disabledkeysize")
802
.shouldMatch("Signed by .*CN=dsakey")
803
.shouldMatch("Signed by .*CN=disabledkeysize")
804
.shouldMatch("Signature algorithm: .*key.*(disabled)");
805
}
806
807
static void checkWeak(String file) throws Exception {
808
verify(file)
809
.shouldHaveExitValue(0)
810
.shouldNotContain("treated as unsigned");
811
verify(file, "-verbose")
812
.shouldHaveExitValue(0)
813
.shouldNotContain("treated as unsigned")
814
.shouldMatch("Digest algorithm: .*(weak)")
815
.shouldMatch("Signature algorithm: .*(weak)")
816
.shouldMatch("Timestamp digest algorithm: .*(weak)")
817
.shouldNotMatch("Timestamp signature algorithm: .*(weak).*(weak)")
818
.shouldMatch("Timestamp signature algorithm: .*key.*(weak)");
819
verify(file, "-J-Djava.security.debug=jar")
820
.shouldHaveExitValue(0)
821
.shouldNotMatch("SignatureException:.*disabled");
822
823
// keytool should print out warnings when reading or
824
// generating cert/cert req using legacy algorithms.
825
String sout = SecurityTools.keytool("-printcert -jarfile " + file)
826
.stderrShouldContain("The TSA certificate uses a 1024-bit RSA key" +
827
" which is considered a security risk." +
828
" This key size will be disabled in a future update.")
829
.getStdout();
830
if (sout.indexOf("weak", sout.indexOf("Timestamp:")) < 0) {
831
throw new RuntimeException("timestamp not weak: " + sout);
832
}
833
}
834
835
static void checkHalfDisabled(String file) throws Exception {
836
verify(file)
837
.shouldHaveExitValue(16)
838
.shouldContain("treated as unsigned")
839
.shouldMatch("weak algorithm that is now disabled.")
840
.shouldMatch("Re-run jarsigner with the -verbose option for more details");
841
verify(file, "-verbose")
842
.shouldHaveExitValue(16)
843
.shouldContain("treated as unsigned")
844
.shouldMatch("weak algorithm that is now disabled by")
845
.shouldMatch("Digest algorithm: .*(disabled)")
846
.shouldNotMatch("Signature algorithm: .*(weak)")
847
.shouldNotMatch("Signature algorithm: .*(disabled)")
848
.shouldNotMatch("Timestamp digest algorithm: .*(disabled)")
849
.shouldNotMatch("Timestamp signature algorithm: .*(weak).*(weak)")
850
.shouldNotMatch("Timestamp signature algorithm: .*(disabled).*(disabled)")
851
.shouldNotMatch("Timestamp signature algorithm: .*key.*(weak)")
852
.shouldNotMatch("Timestamp signature algorithm: .*key.*(disabled)");
853
}
854
855
static void checkMultipleWeak(String file) throws Exception {
856
verify(file)
857
.shouldHaveExitValue(0)
858
.shouldContain("jar verified");
859
verify(file, "-verbose", "-certs")
860
.shouldHaveExitValue(0)
861
.shouldContain("jar verified")
862
.shouldMatch("X.509.*CN=dsakey")
863
.shouldMatch("X.509.*CN=weakkeysize")
864
.shouldMatch("Signed by .*CN=dsakey")
865
.shouldMatch("Signed by .*CN=weakkeysize")
866
.shouldMatch("Signature algorithm: .*key.*(weak)");
867
}
868
869
static void checkTimestamp(String file, String policyId, String digestAlg)
870
throws Exception {
871
try (JarFile jf = new JarFile(file)) {
872
JarEntry je = jf.getJarEntry("META-INF/SIGNER.RSA");
873
try (InputStream is = jf.getInputStream(je)) {
874
byte[] content = IOUtils.readAllBytes(is);
875
PKCS7 p7 = new PKCS7(content);
876
SignerInfo[] si = p7.getSignerInfos();
877
if (si == null || si.length == 0) {
878
throw new Exception("Not signed");
879
}
880
PKCS9Attribute p9 = si[0].getUnauthenticatedAttributes()
881
.getAttribute(PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID);
882
PKCS7 tsToken = new PKCS7((byte[]) p9.getValue());
883
TimestampToken tt =
884
new TimestampToken(tsToken.getContentInfo().getData());
885
if (!tt.getHashAlgorithm().toString().equals(digestAlg)) {
886
throw new Exception("Digest alg different");
887
}
888
if (!tt.getPolicyID().equals(policyId)) {
889
throw new Exception("policyId different");
890
}
891
}
892
}
893
}
894
895
static int which = 0;
896
897
/**
898
* Sign with a TSA path. Always use alias "signer" to sign "unsigned.jar".
899
* The signed jar name is always path.jar.
900
*
901
* @param extra more args given to jarsigner
902
*/
903
static OutputAnalyzer sign(String path, String... extra)
904
throws Exception {
905
return signVerbose(
906
path,
907
"unsigned.jar",
908
path + ".jar",
909
"signer",
910
extra);
911
}
912
913
static OutputAnalyzer signVerbose(
914
String path, // TSA URL path
915
String oldJar,
916
String newJar,
917
String alias, // signer
918
String...extra) throws Exception {
919
which++;
920
System.out.println("\n>> Test #" + which);
921
List<String> args = new ArrayList<>();
922
args.add("-strict");
923
args.add("-verbose");
924
args.add("-debug");
925
args.add("-signedjar");
926
args.add(newJar);
927
args.add(oldJar);
928
args.add(alias);
929
if (path != null) {
930
args.add("-tsa");
931
args.add(host + path);
932
}
933
args.addAll(Arrays.asList(extra));
934
return jarsigner(args);
935
}
936
937
static void prepare() throws Exception {
938
JarUtils.createJar("unsigned.jar", "A");
939
Files.deleteIfExists(Paths.get("ks"));
940
keytool("-alias signer -genkeypair -ext bc -dname CN=signer");
941
keytool("-alias oldsigner -genkeypair -dname CN=oldsigner");
942
keytool("-alias dsakey -genkeypair -keyalg DSA -dname CN=dsakey");
943
keytool("-alias weakkeysize -genkeypair -keysize 1024 -dname CN=weakkeysize");
944
keytool("-alias disabledkeysize -genkeypair -keysize 512 -dname CN=disabledkeysize");
945
keytool("-alias badku -genkeypair -dname CN=badku");
946
keytool("-alias ts -genkeypair -dname CN=ts");
947
keytool("-alias tsold -genkeypair -dname CN=tsold");
948
keytool("-alias tsweak -genkeypair -keysize 1024 -dname CN=tsweak");
949
keytool("-alias tsdisabled -genkeypair -keysize 512 -dname CN=tsdisabled");
950
keytool("-alias tsbad1 -genkeypair -dname CN=tsbad1");
951
keytool("-alias tsbad2 -genkeypair -dname CN=tsbad2");
952
keytool("-alias tsbad3 -genkeypair -dname CN=tsbad3");
953
keytool("-alias tsnoca -genkeypair -dname CN=tsnoca");
954
955
keytool("-alias expired -genkeypair -dname CN=expired");
956
keytool("-alias expiring -genkeypair -dname CN=expiring");
957
keytool("-alias long -genkeypair -dname CN=long");
958
keytool("-alias tsexpired -genkeypair -dname CN=tsexpired");
959
keytool("-alias tsexpiring -genkeypair -dname CN=tsexpiring");
960
keytool("-alias tsexpiringsoon -genkeypair -dname CN=tsexpiringsoon");
961
keytool("-alias tslong -genkeypair -dname CN=tslong");
962
963
// tsnoca's issuer will be removed from keystore later
964
keytool("-alias ca -genkeypair -ext bc -dname CN=CA");
965
gencert("tsnoca", "-ext eku:critical=ts");
966
keytool("-delete -alias ca");
967
keytool("-alias ca -genkeypair -ext bc -dname CN=CA -startdate -40d");
968
969
gencert("signer");
970
gencert("oldsigner", "-startdate -30d -validity 20");
971
gencert("dsakey");
972
gencert("weakkeysize");
973
gencert("disabledkeysize");
974
gencert("badku", "-ext ku:critical=keyAgreement");
975
gencert("ts", "-ext eku:critical=ts -validity 500");
976
977
gencert("expired", "-validity 10 -startdate -12d");
978
gencert("expiring", "-validity 178");
979
gencert("long", "-validity 182");
980
gencert("tsexpired", "-ext eku:critical=ts -validity 10 -startdate -12d");
981
gencert("tsexpiring", "-ext eku:critical=ts -validity 364");
982
gencert("tsexpiringsoon", "-ext eku:critical=ts -validity 170"); // earlier than expiring
983
gencert("tslong", "-ext eku:critical=ts -validity 367");
984
985
986
for (int i = 0; i < 5; i++) {
987
// Issue another cert for "ts" with a different EKU.
988
// Length might be different because serial number is
989
// random. Try several times until a cert with the same
990
// length is generated so we can substitute ts.cert
991
// embedded in the PKCS7 block with ts2.cert.
992
// If cannot create one, related test will be ignored.
993
keytool("-gencert -alias ca -infile ts.req -outfile ts2.cert " +
994
"-ext eku:critical=1.3.6.1.5.5.7.3.9");
995
if (Files.size(Paths.get("ts.cert")) != Files.size(Paths.get("ts2.cert"))) {
996
Files.delete(Paths.get("ts2.cert"));
997
System.out.println("Warning: cannot create same length");
998
} else {
999
break;
1000
}
1001
}
1002
1003
gencert("tsold", "-ext eku:critical=ts -startdate -40d -validity 500");
1004
1005
gencert("tsweak", "-ext eku:critical=ts");
1006
gencert("tsdisabled", "-ext eku:critical=ts");
1007
gencert("tsbad1");
1008
gencert("tsbad2", "-ext eku=ts");
1009
gencert("tsbad3", "-ext eku:critical=cs");
1010
}
1011
1012
static void gencert(String alias, String... extra) throws Exception {
1013
keytool("-alias " + alias + " -certreq -file " + alias + ".req");
1014
String genCmd = "-gencert -alias ca -infile " +
1015
alias + ".req -outfile " + alias + ".cert";
1016
for (String s : extra) {
1017
genCmd += " " + s;
1018
}
1019
keytool(genCmd);
1020
keytool("-alias " + alias + " -importcert -file " + alias + ".cert");
1021
}
1022
1023
static void keytool(String cmd) throws Exception {
1024
cmd = "-keystore ks -storepass changeit -keypass changeit " +
1025
"-keyalg rsa -validity 200 " + cmd;
1026
sun.security.tools.keytool.Main.main(cmd.split(" "));
1027
}
1028
1029
static <K,V> Map<K,V> mapOf(K k1, V v1) {
1030
return Collections.singletonMap(k1, v1);
1031
}
1032
1033
static <E> List<E> listOf(E... elements) {
1034
return Arrays.asList(elements);
1035
}
1036
}
1037
1038