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  * @run main/timeout=600 TimestampCheck
  72  */
  73 public class TimestampCheck {
  74 
  75     static final String defaultPolicyId = "2.3.4";
  76     static String host = null;
  77 
  78     static class Handler implements HttpHandler, AutoCloseable {
  79 
  80         private final HttpServer httpServer;
  81         private final String keystore;
  82 
  83         @Override
  84         public void handle(HttpExchange t) throws IOException {
  85             int len = 0;
  86             for (String h: t.getRequestHeaders().keySet()) {
  87                 if (h.equalsIgnoreCase("Content-length")) {
  88                     len = Integer.valueOf(t.getRequestHeaders().get(h).get(0));
  89                 }
  90             }
  91             byte[] input = new byte[len];
  92             t.getRequestBody().read(input);
  93 
  94             try {
  95                 String path = t.getRequestURI().getPath().substring(1);
  96                 byte[] output = sign(input, path);
  97                 Headers out = t.getResponseHeaders();
  98                 out.set("Content-Type", "application/timestamp-reply");
  99 
 100                 t.sendResponseHeaders(200, output.length);
 101                 OutputStream os = t.getResponseBody();
 102                 os.write(output);
 103             } catch (Exception e) {
 104                 e.printStackTrace();
 105                 t.sendResponseHeaders(500, 0);
 106             }
 107             t.close();
 108         }
 109 
 110         /**
 111          * @param input The data to sign
 112          * @param path different cases to simulate, impl on URL path
 113          * @returns the signed
 114          */
 115         byte[] sign(byte[] input, String path) throws Exception {
 116 
 117             DerValue value = new DerValue(input);
 118             System.err.println("\nIncoming Request\n===================");
 119             System.err.println("Version: " + value.data.getInteger());
 120             DerValue messageImprint = value.data.getDerValue();
 121             AlgorithmId aid = AlgorithmId.parse(
 122                     messageImprint.data.getDerValue());
 123             System.err.println("AlgorithmId: " + aid);
 124 
 125             ObjectIdentifier policyId = new ObjectIdentifier(defaultPolicyId);
 126             BigInteger nonce = null;
 127             while (value.data.available() > 0) {
 128                 DerValue v = value.data.getDerValue();
 129                 if (v.tag == DerValue.tag_Integer) {
 130                     nonce = v.getBigInteger();
 131                     System.err.println("nonce: " + nonce);
 132                 } else if (v.tag == DerValue.tag_Boolean) {
 133                     System.err.println("certReq: " + v.getBoolean());
 134                 } else if (v.tag == DerValue.tag_ObjectId) {
 135                     policyId = v.getOID();
 136                     System.err.println("PolicyID: " + policyId);
 137                 }
 138             }
 139 
 140             System.err.println("\nResponse\n===================");
 141             KeyStore ks = KeyStore.getInstance(
 142                     new File(keystore), "changeit".toCharArray());
 143 
 144             String alias = "ts";
 145             if (path.startsWith("bad") || path.equals("weak")) {
 146                 alias = "ts" + path;
 147             }
 148 
 149             if (path.equals("diffpolicy")) {
 150                 policyId = new ObjectIdentifier(defaultPolicyId);
 151             }
 152 
 153             DerOutputStream statusInfo = new DerOutputStream();
 154             statusInfo.putInteger(0);
 155 
 156             AlgorithmId[] algorithms = {aid};
 157             Certificate[] chain = ks.getCertificateChain(alias);
 158             X509Certificate[] signerCertificateChain;
 159             X509Certificate signer = (X509Certificate)chain[0];
 160 
 161             if (path.equals("fullchain")) {   // Only case 5 uses full chain
 162                 signerCertificateChain = new X509Certificate[chain.length];
 163                 for (int i=0; i<chain.length; i++) {
 164                     signerCertificateChain[i] = (X509Certificate)chain[i];
 165                 }
 166             } else if (path.equals("nocert")) {
 167                 signerCertificateChain = new X509Certificate[0];
 168             } else {
 169                 signerCertificateChain = new X509Certificate[1];
 170                 signerCertificateChain[0] = (X509Certificate)chain[0];
 171             }
 172 
 173             DerOutputStream tst = new DerOutputStream();
 174 
 175             tst.putInteger(1);
 176             tst.putOID(policyId);
 177 
 178             if (!path.equals("baddigest") && !path.equals("diffalg")) {
 179                 tst.putDerValue(messageImprint);
 180             } else {
 181                 byte[] data = messageImprint.toByteArray();
 182                 if (path.equals("diffalg")) {
 183                     data[6] = (byte)0x01;
 184                 } else {
 185                     data[data.length-1] = (byte)0x01;
 186                     data[data.length-2] = (byte)0x02;
 187                     data[data.length-3] = (byte)0x03;
 188                 }
 189                 tst.write(data);
 190             }
 191 
 192             tst.putInteger(1);
 193 
 194             Calendar cal = Calendar.getInstance();
 195             tst.putGeneralizedTime(cal.getTime());
 196 
 197             if (path.equals("diffnonce")) {
 198                 tst.putInteger(1234);
 199             } else if (path.equals("nononce")) {
 200                 // no noce
 201             } else {
 202                 tst.putInteger(nonce);
 203             }
 204 
 205             DerOutputStream tstInfo = new DerOutputStream();
 206             tstInfo.write(DerValue.tag_Sequence, tst);
 207 
 208             DerOutputStream tstInfo2 = new DerOutputStream();
 209             tstInfo2.putOctetString(tstInfo.toByteArray());
 210 
 211             // Always use the same algorithm at timestamp signing
 212             // so it is different from the hash algorithm.
 213             Signature sig = Signature.getInstance("SHA1withRSA");
 214             sig.initSign((PrivateKey)(ks.getKey(
 215                     alias, "changeit".toCharArray())));
 216             sig.update(tstInfo.toByteArray());
 217 
 218             ContentInfo contentInfo = new ContentInfo(new ObjectIdentifier(
 219                     "1.2.840.113549.1.9.16.1.4"),
 220                     new DerValue(tstInfo2.toByteArray()));
 221 
 222             System.err.println("Signing...");
 223             System.err.println(new X500Name(signer
 224                     .getIssuerX500Principal().getName()));
 225             System.err.println(signer.getSerialNumber());
 226 
 227             SignerInfo signerInfo = new SignerInfo(
 228                     new X500Name(signer.getIssuerX500Principal().getName()),
 229                     signer.getSerialNumber(),
 230                     AlgorithmId.get("SHA-1"), AlgorithmId.get("RSA"), sig.sign());
 231 
 232             SignerInfo[] signerInfos = {signerInfo};
 233             PKCS7 p7 = new PKCS7(algorithms, contentInfo,
 234                     signerCertificateChain, signerInfos);
 235             ByteArrayOutputStream p7out = new ByteArrayOutputStream();
 236             p7.encodeSignedData(p7out);
 237 
 238             DerOutputStream response = new DerOutputStream();
 239             response.write(DerValue.tag_Sequence, statusInfo);
 240             response.putDerValue(new DerValue(p7out.toByteArray()));
 241 
 242             DerOutputStream out = new DerOutputStream();
 243             out.write(DerValue.tag_Sequence, response);
 244 
 245             return out.toByteArray();
 246         }
 247 
 248         private Handler(HttpServer httpServer, String keystore) {
 249             this.httpServer = httpServer;
 250             this.keystore = keystore;
 251         }
 252 
 253         /**
 254          * Initialize TSA instance.
 255          *
 256          * Extended Key Info extension of certificate that is used for
 257          * signing TSA responses should contain timeStamping value.
 258          */
 259         static Handler init(int port, String keystore) throws IOException {
 260             HttpServer httpServer = HttpServer.create(
 261                     new InetSocketAddress(port), 0);
 262             Handler tsa = new Handler(httpServer, keystore);
 263             httpServer.createContext("/", tsa);
 264             return tsa;
 265         }
 266 
 267         /**
 268          * Start TSA service.
 269          */
 270         void start() {
 271             httpServer.start();
 272         }
 273 
 274         /**
 275          * Stop TSA service.
 276          */
 277         void stop() {
 278             httpServer.stop(0);
 279         }
 280 
 281         /**
 282          * Return server port number.
 283          */
 284         int getPort() {
 285             return httpServer.getAddress().getPort();
 286         }
 287 
 288         @Override
 289         public void close() throws Exception {
 290             stop();
 291         }
 292     }
 293 
 294     public static void main(String[] args) throws Throwable {
 295 
 296         prepare();
 297 
 298         try (Handler tsa = Handler.init(0, "tsks");) {
 299             tsa.start();
 300             int port = tsa.getPort();
 301             host = "http://localhost:" + port + "/";
 302 
 303             if (args.length == 0) {         // Run this test
 304                 sign("none")
 305                         .shouldContain("is not timestamped")
 306                         .shouldHaveExitValue(0);
 307 
 308                 sign("badku")
 309                         .shouldHaveExitValue(0);
 310                 checkBadKU("badku.jar");
 311 
 312                 sign("normal")
 313                         .shouldNotContain("is not timestamped")
 314                         .shouldHaveExitValue(0);
 315 
 316                 sign("nononce")
 317                         .shouldHaveExitValue(1);
 318                 sign("diffnonce")
 319                         .shouldHaveExitValue(1);
 320                 sign("baddigest")
 321                         .shouldHaveExitValue(1);
 322                 sign("diffalg")
 323                         .shouldHaveExitValue(1);
 324                 sign("fullchain")
 325                         .shouldHaveExitValue(0);   // Success, 6543440 solved.
 326                 sign("bad1")
 327                         .shouldHaveExitValue(1);
 328                 sign("bad2")
 329                         .shouldHaveExitValue(1);
 330                 sign("bad3")
 331                         .shouldHaveExitValue(1);
 332                 sign("nocert")
 333                         .shouldHaveExitValue(1);
 334 
 335                 sign("policy", "-tsapolicyid",  "1.2.3")
 336                         .shouldHaveExitValue(0);
 337                 checkTimestamp("policy.jar", "1.2.3", "SHA-256");
 338 
 339                 sign("diffpolicy", "-tsapolicyid", "1.2.3")
 340                         .shouldHaveExitValue(1);
 341 
 342                 sign("tsaalg", "-tsadigestalg", "SHA")
 343                         .shouldHaveExitValue(0);
 344                 checkTimestamp("tsaalg.jar", defaultPolicyId, "SHA-1");
 345 
 346                 sign("weak", "-digestalg", "MD5",
 347                                 "-sigalg", "MD5withRSA", "-tsadigestalg", "MD5")
 348                         .shouldHaveExitValue(0)
 349                         .shouldMatch("MD5.*-digestalg.*risk")
 350                         .shouldMatch("MD5.*-tsadigestalg.*risk")
 351                         .shouldMatch("MD5withRSA.*-sigalg.*risk");
 352                 checkWeak("weak.jar");
 353 
 354                 signWithAliasAndTsa("halfWeak", "old.jar", "old", "-digestalg", "MD5")
 355                         .shouldHaveExitValue(0);
 356                 checkHalfWeak("halfWeak.jar");
 357 
 358                 // sign with DSA key
 359                 signWithAliasAndTsa("sign1", "old.jar", "dsakey")
 360                         .shouldHaveExitValue(0);
 361                 // sign with RSAkeysize < 1024
 362                 signWithAliasAndTsa("sign2", "sign1.jar", "weakkeysize")
 363                         .shouldHaveExitValue(0);
 364                 checkMultiple("sign2.jar");
 365 
 366                 // When .SF or .RSA is missing or invalid
 367                 checkMissingOrInvalidFiles("normal.jar");
 368             } else {                        // Run as a standalone server
 369                 System.err.println("Press Enter to quit server");
 370                 System.in.read();
 371             }
 372         }
 373     }
 374 
 375     private static void checkMissingOrInvalidFiles(String s)
 376             throws Throwable {
 377         JarUtils.updateJar(s, "1.jar", "-", "META-INF/OLD.SF");
 378         verify("1.jar", "-verbose")
 379                 .shouldHaveExitValue(0)
 380                 .shouldContain("treated as unsigned")
 381                 .shouldContain("Missing signature-related file META-INF/OLD.SF");
 382         JarUtils.updateJar(s, "2.jar", "-", "META-INF/OLD.RSA");
 383         verify("2.jar", "-verbose")
 384                 .shouldHaveExitValue(0)
 385                 .shouldContain("treated as unsigned")
 386                 .shouldContain("Missing block file for signature-related file META-INF/OLD.SF");
 387         JarUtils.updateJar(s, "3.jar", "META-INF/OLD.SF");
 388         verify("3.jar", "-verbose")
 389                 .shouldHaveExitValue(0)
 390                 .shouldContain("treated as unsigned")
 391                 .shouldContain("Unparsable signature-related file META-INF/OLD.SF");
 392         JarUtils.updateJar(s, "4.jar", "META-INF/OLD.RSA");
 393         verify("4.jar", "-verbose")
 394                 .shouldHaveExitValue(0)
 395                 .shouldContain("treated as unsigned")
 396                 .shouldContain("Unparsable signature-related file META-INF/OLD.RSA");
 397     }
 398 
 399     static OutputAnalyzer jarsigner(List<String> extra)
 400             throws Throwable {
 401         JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("jarsigner")
 402                 .addVMArg("-Duser.language=en")
 403                 .addVMArg("-Duser.country=US")
 404                 .addToolArg("-keystore")
 405                 .addToolArg("tsks")
 406                 .addToolArg("-storepass")
 407                 .addToolArg("changeit");
 408         for (String s : extra) {
 409             if (s.startsWith("-J")) {
 410                 launcher.addVMArg(s.substring(2));
 411             } else {
 412                 launcher.addToolArg(s);
 413             }
 414         }
 415         return ProcessTools.executeCommand(launcher.getCommand());
 416     }
 417 
 418     static OutputAnalyzer verify(String file, String... extra)
 419             throws Throwable {
 420         List<String> args = new ArrayList<>();
 421         args.add("-verify");
 422         args.add(file);
 423         args.addAll(Arrays.asList(extra));
 424         return jarsigner(args);
 425     }
 426 
 427     static void checkBadKU(String file) throws Throwable {
 428         verify(file)
 429                 .shouldHaveExitValue(0)
 430                 .shouldContain("treated as unsigned")
 431                 .shouldContain("re-run jarsigner with debug enabled");
 432         verify(file, "-verbose")
 433                 .shouldHaveExitValue(0)
 434                 .shouldContain("Signed by")
 435                 .shouldContain("treated as unsigned")
 436                 .shouldContain("re-run jarsigner with debug enabled");
 437         verify(file, "-J-Djava.security.debug=jar")
 438                 .shouldHaveExitValue(0)
 439                 .shouldContain("SignatureException: Key usage restricted")
 440                 .shouldContain("treated as unsigned")
 441                 .shouldContain("re-run jarsigner with debug enabled");
 442     }
 443 
 444     static void checkWeak(String file) throws Throwable {
 445         verify(file)
 446                 .shouldHaveExitValue(0)
 447                 .shouldContain("treated as unsigned")
 448                 .shouldMatch("weak algorithm that is now disabled.")
 449                 .shouldMatch("Re-run jarsigner with the -verbose option for more details");
 450         verify(file, "-verbose")
 451                 .shouldHaveExitValue(0)
 452                 .shouldContain("treated as unsigned")
 453                 .shouldMatch("weak algorithm that is now disabled by")
 454                 .shouldMatch("Digest algorithm: .*weak")
 455                 .shouldMatch("Signature algorithm: .*weak")
 456                 .shouldMatch("Timestamp digest algorithm: .*weak")
 457                 .shouldNotMatch("Timestamp signature algorithm: .*weak.*weak")
 458                 .shouldMatch("Timestamp signature algorithm: .*key.*weak");
 459         verify(file, "-J-Djava.security.debug=jar")
 460                 .shouldHaveExitValue(0)
 461                 .shouldMatch("SignatureException:.*disabled");
 462 
 463         // For 8171319: keytool should print out warnings when reading or
 464         //              generating cert/cert req using weak algorithms.
 465         // Must call keytool the command, otherwise doPrintCert() might not
 466         // be able to reset "jdk.certpath.disabledAlgorithms".
 467         String sout = SecurityTools.keytool("-printcert -jarfile weak.jar")
 468                 .stderrShouldContain("The TSA certificate uses a 512-bit RSA key" +
 469                         " which is considered a security risk.")
 470                 .getStdout();
 471         if (sout.indexOf("weak", sout.indexOf("Timestamp:")) < 0) {
 472             throw new RuntimeException("timestamp not weak: " + sout);
 473         }
 474     }
 475 
 476     static void checkHalfWeak(String file) throws Throwable {
 477         verify(file)
 478                 .shouldHaveExitValue(0)
 479                 .shouldContain("treated as unsigned")
 480                 .shouldMatch("weak algorithm that is now disabled.")
 481                 .shouldMatch("Re-run jarsigner with the -verbose option for more details");
 482         verify(file, "-verbose")
 483                 .shouldHaveExitValue(0)
 484                 .shouldContain("treated as unsigned")
 485                 .shouldMatch("weak algorithm that is now disabled by")
 486                 .shouldMatch("Digest algorithm: .*weak")
 487                 .shouldNotMatch("Signature algorithm: .*weak")
 488                 .shouldNotMatch("Timestamp digest algorithm: .*weak")
 489                 .shouldNotMatch("Timestamp signature algorithm: .*weak.*weak")
 490                 .shouldNotMatch("Timestamp signature algorithm: .*key.*weak");
 491      }
 492 
 493     static void checkMultiple(String file) throws Throwable {
 494         verify(file)
 495                 .shouldHaveExitValue(0)
 496                 .shouldContain("jar verified");
 497         verify(file, "-verbose", "-certs")
 498                 .shouldHaveExitValue(0)
 499                 .shouldContain("jar verified")
 500                 .shouldMatch("X.509.*CN=dsakey")
 501                 .shouldNotMatch("X.509.*CN=weakkeysize")
 502                 .shouldMatch("Signed by .*CN=dsakey")
 503                 .shouldMatch("Signed by .*CN=weakkeysize")
 504                 .shouldMatch("Signature algorithm: .*key.*weak");
 505      }
 506 
 507     static void checkTimestamp(String file, String policyId, String digestAlg)
 508             throws Exception {
 509         try (JarFile jf = new JarFile(file)) {
 510             JarEntry je = jf.getJarEntry("META-INF/OLD.RSA");
 511             try (InputStream is = jf.getInputStream(je)) {
 512                 byte[] content = is.readAllBytes();
 513                 PKCS7 p7 = new PKCS7(content);
 514                 SignerInfo[] si = p7.getSignerInfos();
 515                 if (si == null || si.length == 0) {
 516                     throw new Exception("Not signed");
 517                 }
 518                 PKCS9Attribute p9 = si[0].getUnauthenticatedAttributes()
 519                         .getAttribute(PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID);
 520                 PKCS7 tsToken = new PKCS7((byte[]) p9.getValue());
 521                 TimestampToken tt =
 522                         new TimestampToken(tsToken.getContentInfo().getData());
 523                 if (!tt.getHashAlgorithm().toString().equals(digestAlg)) {
 524                     throw new Exception("Digest alg different");
 525                 }
 526                 if (!tt.getPolicyID().equals(policyId)) {
 527                     throw new Exception("policyId different");
 528                 }
 529             }
 530         }
 531     }
 532 
 533     static int which = 0;
 534 
 535     /**
 536      * @param extra more args given to jarsigner
 537      */
 538     static OutputAnalyzer sign(String path, String... extra)
 539             throws Throwable {
 540         String alias = path.equals("badku") ? "badku" : "old";
 541         return signWithAliasAndTsa(path, "old.jar", alias, extra);
 542     }
 543 
 544     static OutputAnalyzer signWithAliasAndTsa (String path, String jar,
 545             String alias, String...extra) throws Throwable {
 546         which++;
 547         System.err.println("\n>> Test #" + which + ": " + Arrays.toString(extra));
 548         List<String> args = List.of("-J-Djava.security.egd=file:/dev/./urandom",
 549                 "-debug", "-signedjar", path + ".jar", jar, alias);
 550         args = new ArrayList<>(args);
 551         if (!path.equals("none") && !path.equals("badku")) {
 552             args.add("-tsa");
 553             args.add(host + path);
 554         }
 555         args.addAll(Arrays.asList(extra));
 556         return jarsigner(args);
 557     }
 558 
 559     static void prepare() throws Exception {
 560         JarUtils.createJar("old.jar", "A");
 561         Files.deleteIfExists(Paths.get("tsks"));
 562         keytool("-alias ca -genkeypair -ext bc -dname CN=CA");
 563         keytool("-alias old -genkeypair -dname CN=old");
 564         keytool("-alias dsakey -genkeypair -keyalg DSA -dname CN=dsakey");
 565         keytool("-alias weakkeysize -genkeypair -keysize 512 -dname CN=weakkeysize");
 566         keytool("-alias badku -genkeypair -dname CN=badku");
 567         keytool("-alias ts -genkeypair -dname CN=ts");
 568         keytool("-alias tsweak -genkeypair -keysize 512 -dname CN=tsbad1");
 569         keytool("-alias tsbad1 -genkeypair -dname CN=tsbad1");
 570         keytool("-alias tsbad2 -genkeypair -dname CN=tsbad2");
 571         keytool("-alias tsbad3 -genkeypair -dname CN=tsbad3");
 572 
 573         gencert("old");
 574         gencert("dsakey");
 575         gencert("weakkeysize");
 576         gencert("badku", "-ext ku:critical=keyAgreement");
 577         gencert("ts", "-ext eku:critical=ts");
 578         gencert("tsweak", "-ext eku:critical=ts");
 579         gencert("tsbad1");
 580         gencert("tsbad2", "-ext eku=ts");
 581         gencert("tsbad3", "-ext eku:critical=cs");
 582     }
 583 
 584     static void gencert(String alias, String... extra) throws Exception {
 585         keytool("-alias " + alias + " -certreq -file " + alias + ".req");
 586         String genCmd = "-gencert -alias ca -infile " +
 587                 alias + ".req -outfile " + alias + ".cert";
 588         for (String s : extra) {
 589             genCmd += " " + s;
 590         }
 591         keytool(genCmd);
 592         keytool("-alias " + alias + " -importcert -file " + alias + ".cert");
 593     }
 594 
 595     static void keytool(String cmd) throws Exception {
 596         cmd = "-keystore tsks -storepass changeit -keypass changeit " +
 597                 "-keyalg rsa -validity 200 " + cmd;
 598         sun.security.tools.keytool.Main.main(cmd.split(" "));
 599     }
 600 }