1 /*
   2  * Copyright (c) 2003, 2015, 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.BufferedReader;
  26 import java.io.ByteArrayOutputStream;
  27 import java.io.FileInputStream;
  28 import java.io.IOException;
  29 import java.io.InputStream;
  30 import java.io.InputStreamReader;
  31 import java.io.OutputStream;
  32 import java.math.BigInteger;
  33 import java.net.InetSocketAddress;
  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.Calendar;
  40 import java.util.jar.JarEntry;
  41 import java.util.jar.JarFile;
  42 
  43 import sun.security.pkcs.ContentInfo;
  44 import sun.security.pkcs.PKCS7;
  45 import sun.security.pkcs.PKCS9Attribute;
  46 import sun.security.pkcs.SignerInfo;
  47 import sun.security.timestamp.TimestampToken;
  48 import sun.security.util.DerOutputStream;
  49 import sun.security.util.DerValue;
  50 import sun.security.util.ObjectIdentifier;
  51 import sun.security.x509.AlgorithmId;
  52 import sun.security.x509.X500Name;
  53 
  54 public class TimestampCheck {
  55     static final String TSKS = "tsks";
  56     static final String JAR = "old.jar";
  57 
  58     static final String defaultPolicyId = "2.3.4.5";
  59 
  60     static class Handler implements HttpHandler, AutoCloseable {
  61 
  62         private final HttpServer httpServer;
  63         private final String keystore;
  64 
  65         @Override
  66         public void handle(HttpExchange t) throws IOException {
  67             int len = 0;
  68             for (String h: t.getRequestHeaders().keySet()) {
  69                 if (h.equalsIgnoreCase("Content-length")) {
  70                     len = Integer.valueOf(t.getRequestHeaders().get(h).get(0));
  71                 }
  72             }
  73             byte[] input = new byte[len];
  74             t.getRequestBody().read(input);
  75 
  76             try {
  77                 int path = 0;
  78                 if (t.getRequestURI().getPath().length() > 1) {
  79                     path = Integer.parseInt(
  80                             t.getRequestURI().getPath().substring(1));
  81                 }
  82                 byte[] output = sign(input, path);
  83                 Headers out = t.getResponseHeaders();
  84                 out.set("Content-Type", "application/timestamp-reply");
  85 
  86                 t.sendResponseHeaders(200, output.length);
  87                 OutputStream os = t.getResponseBody();
  88                 os.write(output);
  89             } catch (Exception e) {
  90                 e.printStackTrace();
  91                 t.sendResponseHeaders(500, 0);
  92             }
  93             t.close();
  94         }
  95 
  96         /**
  97          * @param input The data to sign
  98          * @param path different cases to simulate, impl on URL path
  99          * 0: normal
 100          * 1: Missing nonce
 101          * 2: Different nonce
 102          * 3: Bad digets octets in messageImprint
 103          * 4: Different algorithmId in messageImprint
 104          * 5: whole chain in cert set
 105          * 6: extension is missing
 106          * 7: extension is non-critical
 107          * 8: extension does not have timestamping
 108          * 9: no cert in response
 109          * 10: normal
 110          * 11: always return default policy id
 111          * 12: normal
 112          * otherwise: normal
 113          * @returns the signed
 114          */
 115         byte[] sign(byte[] input, int path) throws Exception {
 116             // Read TSRequest
 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             // Write TSResponse
 141             System.err.println("\nResponse\n===================");
 142             KeyStore ks = KeyStore.getInstance("JKS");
 143             try (FileInputStream fis = new FileInputStream(keystore)) {
 144                 ks.load(fis, "changeit".toCharArray());
 145             }
 146 
 147             String alias = "ts";
 148             if (path == 6) alias = "tsbad1";
 149             if (path == 7) alias = "tsbad2";
 150             if (path == 8) alias = "tsbad3";
 151 
 152             if (path == 11) {
 153                 policyId = new ObjectIdentifier(defaultPolicyId);
 154             }
 155 
 156             DerOutputStream statusInfo = new DerOutputStream();
 157             statusInfo.putInteger(0);
 158 
 159             DerOutputStream token = new DerOutputStream();
 160             AlgorithmId[] algorithms = {aid};
 161             Certificate[] chain = ks.getCertificateChain(alias);
 162             X509Certificate[] signerCertificateChain = null;
 163             X509Certificate signer = (X509Certificate)chain[0];
 164             if (path == 5) {   // Only case 5 uses full chain
 165                 signerCertificateChain = new X509Certificate[chain.length];
 166                 for (int i=0; i<chain.length; i++) {
 167                     signerCertificateChain[i] = (X509Certificate)chain[i];
 168                 }
 169             } else if (path == 9) {
 170                 signerCertificateChain = new X509Certificate[0];
 171             } else {
 172                 signerCertificateChain = new X509Certificate[1];
 173                 signerCertificateChain[0] = (X509Certificate)chain[0];
 174             }
 175 
 176             DerOutputStream tst = new DerOutputStream();
 177 
 178             tst.putInteger(1);
 179             tst.putOID(policyId);
 180 
 181             if (path != 3 && path != 4) {
 182                 tst.putDerValue(messageImprint);
 183             } else {
 184                 byte[] data = messageImprint.toByteArray();
 185                 if (path == 4) {
 186                     data[6] = (byte)0x01;
 187                 } else {
 188                     data[data.length-1] = (byte)0x01;
 189                     data[data.length-2] = (byte)0x02;
 190                     data[data.length-3] = (byte)0x03;
 191                 }
 192                 tst.write(data);
 193             }
 194 
 195             tst.putInteger(1);
 196 
 197             Calendar cal = Calendar.getInstance();
 198             tst.putGeneralizedTime(cal.getTime());
 199 
 200             if (path == 2) {
 201                 tst.putInteger(1234);
 202             } else if (path == 1) {
 203                 // do nothing
 204             } else {
 205                 tst.putInteger(nonce);
 206             }
 207 
 208             DerOutputStream tstInfo = new DerOutputStream();
 209             tstInfo.write(DerValue.tag_Sequence, tst);
 210 
 211             DerOutputStream tstInfo2 = new DerOutputStream();
 212             tstInfo2.putOctetString(tstInfo.toByteArray());
 213 
 214             Signature sig = Signature.getInstance("SHA1withRSA");
 215             sig.initSign((PrivateKey)(ks.getKey(
 216                     alias, "changeit".toCharArray())));
 217             sig.update(tstInfo.toByteArray());
 218 
 219             ContentInfo contentInfo = new ContentInfo(new ObjectIdentifier(
 220                     "1.2.840.113549.1.9.16.1.4"),
 221                     new DerValue(tstInfo2.toByteArray()));
 222 
 223             System.err.println("Signing...");
 224             System.err.println(new X500Name(signer
 225                     .getIssuerX500Principal().getName()));
 226             System.err.println(signer.getSerialNumber());
 227 
 228             SignerInfo signerInfo = new SignerInfo(
 229                     new X500Name(signer.getIssuerX500Principal().getName()),
 230                     signer.getSerialNumber(),
 231                     aid, AlgorithmId.get("RSA"), sig.sign());
 232 
 233             SignerInfo[] signerInfos = {signerInfo};
 234             PKCS7 p7 =
 235                     new PKCS7(algorithms, contentInfo, signerCertificateChain,
 236                     signerInfos);
 237             ByteArrayOutputStream p7out = new ByteArrayOutputStream();
 238             p7.encodeSignedData(p7out);
 239 
 240             DerOutputStream response = new DerOutputStream();
 241             response.write(DerValue.tag_Sequence, statusInfo);
 242             response.putDerValue(new DerValue(p7out.toByteArray()));
 243 
 244             DerOutputStream out = new DerOutputStream();
 245             out.write(DerValue.tag_Sequence, response);
 246 
 247             return out.toByteArray();
 248         }
 249 
 250         private Handler(HttpServer httpServer, String keystore) {
 251             this.httpServer = httpServer;
 252             this.keystore = keystore;
 253         }
 254 
 255         /**
 256          * Initialize TSA instance.
 257          *
 258          * Extended Key Info extension of certificate that is used for
 259          * signing TSA responses should contain timeStamping value.
 260          */
 261         static Handler init(int port, String keystore) throws IOException {
 262             HttpServer httpServer = HttpServer.create(
 263                     new InetSocketAddress(port), 0);
 264             Handler tsa = new Handler(httpServer, keystore);
 265             httpServer.createContext("/", tsa);
 266             return tsa;
 267         }
 268 
 269         /**
 270          * Start TSA service.
 271          */
 272         void start() {
 273             httpServer.start();
 274         }
 275 
 276         /**
 277          * Stop TSA service.
 278          */
 279         void stop() {
 280             httpServer.stop(0);
 281         }
 282 
 283         /**
 284          * Return server port number.
 285          */
 286         int getPort() {
 287             return httpServer.getAddress().getPort();
 288         }
 289 
 290         @Override
 291         public void close() throws Exception {
 292             stop();
 293         }
 294     }
 295 
 296     public static void main(String[] args) throws Exception {
 297         try (Handler tsa = Handler.init(0, TSKS);) {
 298             tsa.start();
 299             int port = tsa.getPort();
 300 
 301             String cmd;
 302             // Use -J-Djava.security.egd=file:/dev/./urandom to speed up
 303             // nonce generation in timestamping request. Not avaibale on
 304             // Windows and defaults to thread seed generator, not too bad.
 305             if (System.getProperty("java.home").endsWith("jre")) {
 306                 cmd = System.getProperty("java.home") + "/../bin/jarsigner";
 307             } else {
 308                 cmd = System.getProperty("java.home") + "/bin/jarsigner";
 309             }
 310 
 311             cmd += " " + System.getProperty("test.tool.vm.opts")
 312                     + " -J-Djava.security.egd=file:/dev/./urandom"
 313                     + " -debug -keystore " + TSKS + " -storepass changeit"
 314                     + " -tsa http://localhost:" + port + "/%d"
 315                     + " -signedjar new_%d.jar " + JAR + " old";
 316 
 317             if (args.length == 0) {         // Run this test
 318                 jarsigner(cmd, 0, true);    // Success, normal call
 319                 jarsigner(cmd, 1, false);   // These 4 should fail
 320                 jarsigner(cmd, 2, false);
 321                 jarsigner(cmd, 3, false);
 322                 jarsigner(cmd, 4, false);
 323                 jarsigner(cmd, 5, true);    // Success, 6543440 solved.
 324                 jarsigner(cmd, 6, false);   // tsbad1
 325                 jarsigner(cmd, 7, false);   // tsbad2
 326                 jarsigner(cmd, 8, false);   // tsbad3
 327                 jarsigner(cmd, 9, false);   // no cert in timestamp
 328                 jarsigner(cmd + " -tsapolicyid 1.2.3.4", 10, true);
 329                 checkTimestamp("new_10.jar", "1.2.3.4", "SHA-256");
 330                 jarsigner(cmd + " -tsapolicyid 1.2.3.5", 11, false);
 331                 jarsigner(cmd + " -tsadigestalg SHA", 12, true);
 332                 checkTimestamp("new_12.jar", defaultPolicyId, "SHA-1");
 333             } else {                        // Run as a standalone server
 334                 System.err.println("Press Enter to quit server");
 335                 System.in.read();
 336             }
 337         }
 338     }
 339 
 340     static void checkTimestamp(String file, String policyId, String digestAlg)
 341             throws Exception {
 342         try (JarFile jf = new JarFile(file)) {
 343             JarEntry je = jf.getJarEntry("META-INF/OLD.RSA");
 344             try (InputStream is = jf.getInputStream(je)) {
 345                 byte[] content = is.readAllBytes();
 346                 PKCS7 p7 = new PKCS7(content);
 347                 SignerInfo[] si = p7.getSignerInfos();
 348                 if (si == null || si.length == 0) {
 349                     throw new Exception("Not signed");
 350                 }
 351                 PKCS9Attribute p9 = si[0].getUnauthenticatedAttributes()
 352                         .getAttribute(PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID);
 353                 PKCS7 tsToken = new PKCS7((byte[]) p9.getValue());
 354                 TimestampToken tt =
 355                         new TimestampToken(tsToken.getContentInfo().getData());
 356                 if (!tt.getHashAlgorithm().toString().equals(digestAlg)) {
 357                     throw new Exception("Digest alg different");
 358                 }
 359                 if (!tt.getPolicyID().equals(policyId)) {
 360                     throw new Exception("policyId different");
 361                 }
 362             }
 363         }
 364     }
 365 
 366     /**
 367      * @param cmd the command line (with a hole to plug in)
 368      * @param path the path in the URL, i.e, http://localhost/path
 369      * @param expected if this command should succeed
 370      */
 371     static void jarsigner(String cmd, int path, boolean expected)
 372             throws Exception {
 373         System.err.println("Test " + path);
 374         Process p = Runtime.getRuntime().exec(String.format(cmd, path, path));
 375         BufferedReader reader = new BufferedReader(
 376                 new InputStreamReader(p.getErrorStream()));
 377         while (true) {
 378             String s = reader.readLine();
 379             if (s == null) break;
 380             System.err.println(s);
 381         }
 382 
 383         // Will not see noTimestamp warning
 384         boolean seeWarning = false;
 385         reader = new BufferedReader(
 386                 new InputStreamReader(p.getInputStream()));
 387         while (true) {
 388             String s = reader.readLine();
 389             if (s == null) break;
 390             System.err.println(s);
 391             if (s.indexOf("Warning:") >= 0) {
 392                 seeWarning = true;
 393             }
 394         }
 395         int result = p.waitFor();
 396         if (expected && result != 0 || !expected && result == 0) {
 397             throw new Exception("Failed");
 398         }
 399         if (seeWarning) {
 400             throw new Exception("See warning");
 401         }
 402     }
 403 }