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