1 /* 2 * Copyright (c) 2003, 2017, 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 import java.io.ByteArrayOutputStream; 26 import java.io.File; 27 import java.io.IOException; 28 import java.io.InputStream; 29 import java.io.OutputStream; 30 import java.math.BigInteger; 31 import java.net.InetSocketAddress; 32 import java.nio.file.Files; 33 import java.nio.file.Paths; 34 import java.security.KeyStore; 35 import java.security.PrivateKey; 36 import java.security.Signature; 37 import java.security.cert.Certificate; 38 import java.security.cert.X509Certificate; 39 import java.util.ArrayList; 40 import java.util.Arrays; 41 import java.util.Calendar; 42 import java.util.List; 43 import java.util.jar.JarEntry; 44 import java.util.jar.JarFile; 45 46 import jdk.test.lib.SecurityTools; 47 import jdk.testlibrary.*; 48 import jdk.test.lib.util.JarUtils; 49 import sun.security.pkcs.ContentInfo; 50 import sun.security.pkcs.PKCS7; 51 import sun.security.pkcs.PKCS9Attribute; 52 import sun.security.pkcs.SignerInfo; 53 import sun.security.timestamp.TimestampToken; 54 import sun.security.util.DerOutputStream; 55 import sun.security.util.DerValue; 56 import sun.security.util.ObjectIdentifier; 57 import sun.security.x509.AlgorithmId; 58 import sun.security.x509.X500Name; 59 60 /* 61 * @test 62 * @bug 6543842 6543440 6939248 8009636 8024302 8163304 8169911 63 * @summary checking response of timestamp 64 * @modules java.base/sun.security.pkcs 65 * java.base/sun.security.timestamp 66 * java.base/sun.security.x509 67 * java.base/sun.security.util 68 * java.base/sun.security.tools.keytool 69 * @library /lib/testlibrary 70 * @library /test/lib 71 * @build jdk.test.lib.util.JarUtils 72 * jdk.test.lib.SecurityTools 73 * jdk.test.lib.Utils 74 * jdk.test.lib.Asserts 75 * jdk.test.lib.JDKToolFinder 76 * jdk.test.lib.JDKToolLauncher 77 * jdk.test.lib.Platform 78 * jdk.test.lib.process.* 79 * @run main/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 125 DerValue value = new DerValue(input); 126 System.err.println("\nIncoming Request\n==================="); 127 System.err.println("Version: " + value.data.getInteger()); 128 DerValue messageImprint = value.data.getDerValue(); 129 AlgorithmId aid = AlgorithmId.parse( 130 messageImprint.data.getDerValue()); 131 System.err.println("AlgorithmId: " + aid); 132 133 ObjectIdentifier policyId = new ObjectIdentifier(defaultPolicyId); 134 BigInteger nonce = null; 135 while (value.data.available() > 0) { 136 DerValue v = value.data.getDerValue(); 137 if (v.tag == DerValue.tag_Integer) { 138 nonce = v.getBigInteger(); 139 System.err.println("nonce: " + nonce); 140 } else if (v.tag == DerValue.tag_Boolean) { 141 System.err.println("certReq: " + v.getBoolean()); 142 } else if (v.tag == DerValue.tag_ObjectId) { 143 policyId = v.getOID(); 144 System.err.println("PolicyID: " + policyId); 145 } 146 } 147 148 System.err.println("\nResponse\n==================="); 149 KeyStore ks = KeyStore.getInstance( 150 new File(keystore), "changeit".toCharArray()); 151 152 String alias = "ts"; 153 if (path.startsWith("bad") || path.equals("weak")) { 154 alias = "ts" + path; 155 } 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 Calendar cal = Calendar.getInstance(); 203 tst.putGeneralizedTime(cal.getTime()); 204 205 if (path.equals("diffnonce")) { 206 tst.putInteger(1234); 207 } else if (path.equals("nononce")) { 208 // no noce 209 } else { 210 tst.putInteger(nonce); 211 } 212 213 DerOutputStream tstInfo = new DerOutputStream(); 214 tstInfo.write(DerValue.tag_Sequence, tst); 215 216 DerOutputStream tstInfo2 = new DerOutputStream(); 217 tstInfo2.putOctetString(tstInfo.toByteArray()); 218 219 // Always use the same algorithm at timestamp signing 220 // so it is different from the hash algorithm. 221 Signature sig = Signature.getInstance("SHA1withRSA"); 222 sig.initSign((PrivateKey)(ks.getKey( 223 alias, "changeit".toCharArray()))); 224 sig.update(tstInfo.toByteArray()); 225 226 ContentInfo contentInfo = new ContentInfo(new ObjectIdentifier( 227 "1.2.840.113549.1.9.16.1.4"), 228 new DerValue(tstInfo2.toByteArray())); 229 230 System.err.println("Signing..."); 231 System.err.println(new X500Name(signer 232 .getIssuerX500Principal().getName())); 233 System.err.println(signer.getSerialNumber()); 234 235 SignerInfo signerInfo = new SignerInfo( 236 new X500Name(signer.getIssuerX500Principal().getName()), 237 signer.getSerialNumber(), 238 AlgorithmId.get("SHA-1"), AlgorithmId.get("RSA"), sig.sign()); 239 240 SignerInfo[] signerInfos = {signerInfo}; 241 PKCS7 p7 = new PKCS7(algorithms, contentInfo, 242 signerCertificateChain, signerInfos); 243 ByteArrayOutputStream p7out = new ByteArrayOutputStream(); 244 p7.encodeSignedData(p7out); 245 246 DerOutputStream response = new DerOutputStream(); 247 response.write(DerValue.tag_Sequence, statusInfo); 248 response.putDerValue(new DerValue(p7out.toByteArray())); 249 250 DerOutputStream out = new DerOutputStream(); 251 out.write(DerValue.tag_Sequence, response); 252 253 return out.toByteArray(); 254 } 255 256 private Handler(HttpServer httpServer, String keystore) { 257 this.httpServer = httpServer; 258 this.keystore = keystore; 259 } 260 261 /** 262 * Initialize TSA instance. 263 * 264 * Extended Key Info extension of certificate that is used for 265 * signing TSA responses should contain timeStamping value. 266 */ 267 static Handler init(int port, String keystore) throws IOException { 268 HttpServer httpServer = HttpServer.create( 269 new InetSocketAddress(port), 0); 270 Handler tsa = new Handler(httpServer, keystore); 271 httpServer.createContext("/", tsa); 272 return tsa; 273 } 274 275 /** 276 * Start TSA service. 277 */ 278 void start() { 279 httpServer.start(); 280 } 281 282 /** 283 * Stop TSA service. 284 */ 285 void stop() { 286 httpServer.stop(0); 287 } 288 289 /** 290 * Return server port number. 291 */ 292 int getPort() { 293 return httpServer.getAddress().getPort(); 294 } 295 296 @Override 297 public void close() throws Exception { 298 stop(); 299 } 300 } 301 302 public static void main(String[] args) throws Throwable { 303 304 prepare(); 305 306 try (Handler tsa = Handler.init(0, "tsks");) { 307 tsa.start(); 308 int port = tsa.getPort(); 309 host = "http://localhost:" + port + "/"; 310 311 if (args.length == 0) { // Run this test 312 sign("none") 313 .shouldContain("is not timestamped") 314 .shouldHaveExitValue(0); 315 316 sign("badku") 317 .shouldHaveExitValue(0); 318 checkBadKU("badku.jar"); 319 320 sign("normal") 321 .shouldNotContain("is not timestamped") 322 .shouldHaveExitValue(0); 323 324 sign("nononce") 325 .shouldHaveExitValue(1); 326 sign("diffnonce") 327 .shouldHaveExitValue(1); 328 sign("baddigest") 329 .shouldHaveExitValue(1); 330 sign("diffalg") 331 .shouldHaveExitValue(1); 332 sign("fullchain") 333 .shouldHaveExitValue(0); // Success, 6543440 solved. 334 sign("bad1") 335 .shouldHaveExitValue(1); 336 sign("bad2") 337 .shouldHaveExitValue(1); 338 sign("bad3") 339 .shouldHaveExitValue(1); 340 sign("nocert") 341 .shouldHaveExitValue(1); 342 343 sign("policy", "-tsapolicyid", "1.2.3") 344 .shouldHaveExitValue(0); 345 checkTimestamp("policy.jar", "1.2.3", "SHA-256"); 346 347 sign("diffpolicy", "-tsapolicyid", "1.2.3") 348 .shouldHaveExitValue(1); 349 350 sign("tsaalg", "-tsadigestalg", "SHA") 351 .shouldHaveExitValue(0); 352 checkTimestamp("tsaalg.jar", defaultPolicyId, "SHA-1"); 353 354 sign("weak", "-digestalg", "MD5", 355 "-sigalg", "MD5withRSA", "-tsadigestalg", "MD5") 356 .shouldHaveExitValue(0) 357 .shouldMatch("MD5.*-digestalg.*risk") 358 .shouldMatch("MD5.*-tsadigestalg.*risk") 359 .shouldMatch("MD5withRSA.*-sigalg.*risk"); 360 checkWeak("weak.jar"); 361 362 signWithAliasAndTsa("halfWeak", "old.jar", "old", "-digestalg", "MD5") 363 .shouldHaveExitValue(0); 364 checkHalfWeak("halfWeak.jar"); 365 366 // sign with DSA key 367 signWithAliasAndTsa("sign1", "old.jar", "dsakey") 368 .shouldHaveExitValue(0); 369 // sign with RSAkeysize < 1024 370 signWithAliasAndTsa("sign2", "sign1.jar", "weakkeysize") 371 .shouldHaveExitValue(0); 372 checkMultiple("sign2.jar"); 373 374 // When .SF or .RSA is missing or invalid 375 checkMissingOrInvalidFiles("normal.jar"); 376 } else { // Run as a standalone server 377 System.err.println("Press Enter to quit server"); 378 System.in.read(); 379 } 380 } 381 } 382 383 private static void checkMissingOrInvalidFiles(String s) 384 throws Throwable { 385 JarUtils.updateJar(s, "1.jar", "-", "META-INF/OLD.SF"); 386 verify("1.jar", "-verbose") 387 .shouldHaveExitValue(0) 388 .shouldContain("treated as unsigned") 389 .shouldContain("Missing signature-related file META-INF/OLD.SF"); 390 JarUtils.updateJar(s, "2.jar", "-", "META-INF/OLD.RSA"); 391 verify("2.jar", "-verbose") 392 .shouldHaveExitValue(0) 393 .shouldContain("treated as unsigned") 394 .shouldContain("Missing block file for signature-related file META-INF/OLD.SF"); 395 JarUtils.updateJar(s, "3.jar", "META-INF/OLD.SF"); 396 verify("3.jar", "-verbose") 397 .shouldHaveExitValue(0) 398 .shouldContain("treated as unsigned") 399 .shouldContain("Unparsable signature-related file META-INF/OLD.SF"); 400 JarUtils.updateJar(s, "4.jar", "META-INF/OLD.RSA"); 401 verify("4.jar", "-verbose") 402 .shouldHaveExitValue(0) 403 .shouldContain("treated as unsigned") 404 .shouldContain("Unparsable signature-related file META-INF/OLD.RSA"); 405 } 406 407 static OutputAnalyzer jarsigner(List<String> extra) 408 throws Throwable { 409 JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("jarsigner") 410 .addVMArg("-Duser.language=en") 411 .addVMArg("-Duser.country=US") 412 .addToolArg("-keystore") 413 .addToolArg("tsks") 414 .addToolArg("-storepass") 415 .addToolArg("changeit"); 416 for (String s : extra) { 417 if (s.startsWith("-J")) { 418 launcher.addVMArg(s.substring(2)); 419 } else { 420 launcher.addToolArg(s); 421 } 422 } 423 return ProcessTools.executeCommand(launcher.getCommand()); 424 } 425 426 static OutputAnalyzer verify(String file, String... extra) 427 throws Throwable { 428 List<String> args = new ArrayList<>(); 429 args.add("-verify"); 430 args.add(file); 431 args.addAll(Arrays.asList(extra)); 432 return jarsigner(args); 433 } 434 435 static void checkBadKU(String file) throws Throwable { 436 verify(file) 437 .shouldHaveExitValue(0) 438 .shouldContain("treated as unsigned") 439 .shouldContain("re-run jarsigner with debug enabled"); 440 verify(file, "-verbose") 441 .shouldHaveExitValue(0) 442 .shouldContain("Signed by") 443 .shouldContain("treated as unsigned") 444 .shouldContain("re-run jarsigner with debug enabled"); 445 verify(file, "-J-Djava.security.debug=jar") 446 .shouldHaveExitValue(0) 447 .shouldContain("SignatureException: Key usage restricted") 448 .shouldContain("treated as unsigned") 449 .shouldContain("re-run jarsigner with debug enabled"); 450 } 451 452 static void checkWeak(String file) throws Throwable { 453 verify(file) 454 .shouldHaveExitValue(0) 455 .shouldContain("treated as unsigned") 456 .shouldMatch("weak algorithm that is now disabled.") 457 .shouldMatch("Re-run jarsigner with the -verbose option for more details"); 458 verify(file, "-verbose") 459 .shouldHaveExitValue(0) 460 .shouldContain("treated as unsigned") 461 .shouldMatch("weak algorithm that is now disabled by") 462 .shouldMatch("Digest algorithm: .*weak") 463 .shouldMatch("Signature algorithm: .*weak") 464 .shouldMatch("Timestamp digest algorithm: .*weak") 465 .shouldNotMatch("Timestamp signature algorithm: .*weak.*weak") 466 .shouldMatch("Timestamp signature algorithm: .*key.*weak"); 467 verify(file, "-J-Djava.security.debug=jar") 468 .shouldHaveExitValue(0) 469 .shouldMatch("SignatureException:.*disabled"); 470 471 // For 8171319: keytool should print out warnings when reading or 472 // generating cert/cert req using weak algorithms. 473 // Must call keytool the command, otherwise doPrintCert() might not 474 // be able to reset "jdk.certpath.disabledAlgorithms". 475 String sout = SecurityTools.keytool("-printcert -jarfile weak.jar") 476 .stderrShouldContain("The TSA certificate uses a 512-bit RSA key" + 477 " which is considered a security risk.") 478 .getStdout(); 479 if (sout.indexOf("weak", sout.indexOf("Timestamp:")) < 0) { 480 throw new RuntimeException("timestamp not weak: " + sout); 481 } 482 } 483 484 static void checkHalfWeak(String file) throws Throwable { 485 verify(file) 486 .shouldHaveExitValue(0) 487 .shouldContain("treated as unsigned") 488 .shouldMatch("weak algorithm that is now disabled.") 489 .shouldMatch("Re-run jarsigner with the -verbose option for more details"); 490 verify(file, "-verbose") 491 .shouldHaveExitValue(0) 492 .shouldContain("treated as unsigned") 493 .shouldMatch("weak algorithm that is now disabled by") 494 .shouldMatch("Digest algorithm: .*weak") 495 .shouldNotMatch("Signature algorithm: .*weak") 496 .shouldNotMatch("Timestamp digest algorithm: .*weak") 497 .shouldNotMatch("Timestamp signature algorithm: .*weak.*weak") 498 .shouldNotMatch("Timestamp signature algorithm: .*key.*weak"); 499 } 500 501 static void checkMultiple(String file) throws Throwable { 502 verify(file) 503 .shouldHaveExitValue(0) 504 .shouldContain("jar verified"); 505 verify(file, "-verbose", "-certs") 506 .shouldHaveExitValue(0) 507 .shouldContain("jar verified") 508 .shouldMatch("X.509.*CN=dsakey") 509 .shouldNotMatch("X.509.*CN=weakkeysize") 510 .shouldMatch("Signed by .*CN=dsakey") 511 .shouldMatch("Signed by .*CN=weakkeysize") 512 .shouldMatch("Signature algorithm: .*key.*weak"); 513 } 514 515 static void checkTimestamp(String file, String policyId, String digestAlg) 516 throws Exception { 517 try (JarFile jf = new JarFile(file)) { 518 JarEntry je = jf.getJarEntry("META-INF/OLD.RSA"); 519 try (InputStream is = jf.getInputStream(je)) { 520 byte[] content = is.readAllBytes(); 521 PKCS7 p7 = new PKCS7(content); 522 SignerInfo[] si = p7.getSignerInfos(); 523 if (si == null || si.length == 0) { 524 throw new Exception("Not signed"); 525 } 526 PKCS9Attribute p9 = si[0].getUnauthenticatedAttributes() 527 .getAttribute(PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID); 528 PKCS7 tsToken = new PKCS7((byte[]) p9.getValue()); 529 TimestampToken tt = 530 new TimestampToken(tsToken.getContentInfo().getData()); 531 if (!tt.getHashAlgorithm().toString().equals(digestAlg)) { 532 throw new Exception("Digest alg different"); 533 } 534 if (!tt.getPolicyID().equals(policyId)) { 535 throw new Exception("policyId different"); 536 } 537 } 538 } 539 } 540 541 static int which = 0; 542 543 /** 544 * @param extra more args given to jarsigner 545 */ 546 static OutputAnalyzer sign(String path, String... extra) 547 throws Throwable { 548 String alias = path.equals("badku") ? "badku" : "old"; 549 return signWithAliasAndTsa(path, "old.jar", alias, extra); 550 } 551 552 static OutputAnalyzer signWithAliasAndTsa (String path, String jar, 553 String alias, String...extra) throws Throwable { 554 which++; 555 System.err.println("\n>> Test #" + which + ": " + Arrays.toString(extra)); 556 List<String> args = List.of("-J-Djava.security.egd=file:/dev/./urandom", 557 "-debug", "-signedjar", path + ".jar", jar, alias); 558 args = new ArrayList<>(args); 559 if (!path.equals("none") && !path.equals("badku")) { 560 args.add("-tsa"); 561 args.add(host + path); 562 } 563 args.addAll(Arrays.asList(extra)); 564 return jarsigner(args); 565 } 566 567 static void prepare() throws Exception { 568 JarUtils.createJar("old.jar", "A"); 569 Files.deleteIfExists(Paths.get("tsks")); 570 keytool("-alias ca -genkeypair -ext bc -dname CN=CA"); 571 keytool("-alias old -genkeypair -dname CN=old"); 572 keytool("-alias dsakey -genkeypair -keyalg DSA -dname CN=dsakey"); 573 keytool("-alias weakkeysize -genkeypair -keysize 512 -dname CN=weakkeysize"); 574 keytool("-alias badku -genkeypair -dname CN=badku"); 575 keytool("-alias ts -genkeypair -dname CN=ts"); 576 keytool("-alias tsweak -genkeypair -keysize 512 -dname CN=tsbad1"); 577 keytool("-alias tsbad1 -genkeypair -dname CN=tsbad1"); 578 keytool("-alias tsbad2 -genkeypair -dname CN=tsbad2"); 579 keytool("-alias tsbad3 -genkeypair -dname CN=tsbad3"); 580 581 gencert("old"); 582 gencert("dsakey"); 583 gencert("weakkeysize"); 584 gencert("badku", "-ext ku:critical=keyAgreement"); 585 gencert("ts", "-ext eku:critical=ts"); 586 gencert("tsweak", "-ext eku:critical=ts"); 587 gencert("tsbad1"); 588 gencert("tsbad2", "-ext eku=ts"); 589 gencert("tsbad3", "-ext eku:critical=cs"); 590 } 591 592 static void gencert(String alias, String... extra) throws Exception { 593 keytool("-alias " + alias + " -certreq -file " + alias + ".req"); 594 String genCmd = "-gencert -alias ca -infile " + 595 alias + ".req -outfile " + alias + ".cert"; 596 for (String s : extra) { 597 genCmd += " " + s; 598 } 599 keytool(genCmd); 600 keytool("-alias " + alias + " -importcert -file " + alias + ".cert"); 601 } 602 603 static void keytool(String cmd) throws Exception { 604 cmd = "-keystore tsks -storepass changeit -keypass changeit " + 605 "-keyalg rsa -validity 200 " + cmd; 606 sun.security.tools.keytool.Main.main(cmd.split(" ")); 607 } 608 }