Search in sources :

Example 1 with TimestampToken

use of sun.security.timestamp.TimestampToken in project jdk8u_jdk by JetBrains.

the class TimestampCheck method checkTimestamp.

static void checkTimestamp(String file, String policyId, String digestAlg) throws Exception {
    try (JarFile jf = new JarFile(file)) {
        JarEntry je = jf.getJarEntry("META-INF/OLD.RSA");
        try (InputStream is = jf.getInputStream(je)) {
            byte[] content = IOUtils.readFully(is, -1, true);
            PKCS7 p7 = new PKCS7(content);
            SignerInfo[] si = p7.getSignerInfos();
            if (si == null || si.length == 0) {
                throw new Exception("Not signed");
            }
            PKCS9Attribute p9 = si[0].getUnauthenticatedAttributes().getAttribute(PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID);
            PKCS7 tsToken = new PKCS7((byte[]) p9.getValue());
            TimestampToken tt = new TimestampToken(tsToken.getContentInfo().getData());
            if (!tt.getHashAlgorithm().toString().equals(digestAlg)) {
                throw new Exception("Digest alg different");
            }
            if (!tt.getPolicyID().equals(policyId)) {
                throw new Exception("policyId different");
            }
        }
    }
}
Also used : SignerInfo(sun.security.pkcs.SignerInfo) PKCS9Attribute(sun.security.pkcs.PKCS9Attribute) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) PKCS7(sun.security.pkcs.PKCS7) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) IOException(java.io.IOException) TimestampToken(sun.security.timestamp.TimestampToken)

Example 2 with TimestampToken

use of sun.security.timestamp.TimestampToken in project jdk8u_jdk by JetBrains.

the class SignerInfo method getTimestamp.

/*
     * Extracts a timestamp from a PKCS7 SignerInfo.
     *
     * Examines the signer's unsigned attributes for a
     * {@code signatureTimestampToken} attribute. If present,
     * then it is parsed to extract the date and time at which the
     * timestamp was generated.
     *
     * @param info A signer information element of a PKCS 7 block.
     *
     * @return A timestamp token or null if none is present.
     * @throws IOException if an error is encountered while parsing the
     *         PKCS7 data.
     * @throws NoSuchAlgorithmException if an error is encountered while
     *         verifying the PKCS7 object.
     * @throws SignatureException if an error is encountered while
     *         verifying the PKCS7 object.
     * @throws CertificateException if an error is encountered while generating
     *         the TSA's certpath.
     */
public Timestamp getTimestamp() throws IOException, NoSuchAlgorithmException, SignatureException, CertificateException {
    if (timestamp != null || !hasTimestamp)
        return timestamp;
    PKCS7 tsToken = getTsToken();
    if (tsToken == null) {
        hasTimestamp = false;
        return null;
    }
    // Extract the content (an encoded timestamp token info)
    byte[] encTsTokenInfo = tsToken.getContentInfo().getData();
    // Extract the signer (the Timestamping Authority)
    // while verifying the content
    SignerInfo[] tsa = tsToken.verify(encTsTokenInfo);
    // Expect only one signer
    ArrayList<X509Certificate> chain = tsa[0].getCertificateChain(tsToken);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    CertPath tsaChain = cf.generateCertPath(chain);
    // Create a timestamp token info object
    TimestampToken tsTokenInfo = new TimestampToken(encTsTokenInfo);
    // Check that the signature timestamp applies to this signature
    verifyTimestamp(tsTokenInfo);
    // Create a timestamp object
    timestamp = new Timestamp(tsTokenInfo.getDate(), tsaChain);
    return timestamp;
}
Also used : CertPath(java.security.cert.CertPath) CertificateFactory(java.security.cert.CertificateFactory) Timestamp(java.security.Timestamp) X509Certificate(java.security.cert.X509Certificate) TimestampToken(sun.security.timestamp.TimestampToken)

Example 3 with TimestampToken

use of sun.security.timestamp.TimestampToken in project jdk8u_jdk by JetBrains.

the class SignatureFile method verifyJar.

void verifyJar(String jarName) throws Exception {
    // if there exists entry inside jar signed
    boolean anySigned = false;
    JarFile jf = null;
    Map<String, String> digestMap = new HashMap<>();
    Map<String, PKCS7> sigMap = new HashMap<>();
    Map<String, String> sigNameMap = new HashMap<>();
    Map<String, String> unparsableSignatures = new HashMap<>();
    try {
        jf = new JarFile(jarName, true);
        Vector<JarEntry> entriesVec = new Vector<>();
        byte[] buffer = new byte[8192];
        Enumeration<JarEntry> entries = jf.entries();
        while (entries.hasMoreElements()) {
            JarEntry je = entries.nextElement();
            entriesVec.addElement(je);
            try (InputStream is = jf.getInputStream(je)) {
                String name = je.getName();
                if (signatureRelated(name) && SignatureFileVerifier.isBlockOrSF(name)) {
                    String alias = name.substring(name.lastIndexOf('/') + 1, name.lastIndexOf('.'));
                    try {
                        if (name.endsWith(".SF")) {
                            Manifest sf = new Manifest(is);
                            boolean found = false;
                            for (Object obj : sf.getMainAttributes().keySet()) {
                                String key = obj.toString();
                                if (key.endsWith("-Digest-Manifest")) {
                                    digestMap.put(alias, key.substring(0, key.length() - 16));
                                    found = true;
                                    break;
                                }
                            }
                            if (!found) {
                                unparsableSignatures.putIfAbsent(alias, String.format(rb.getString("history.unparsable"), name));
                            }
                        } else {
                            sigNameMap.put(alias, name);
                            sigMap.put(alias, new PKCS7(is));
                        }
                    } catch (IOException ioe) {
                        unparsableSignatures.putIfAbsent(alias, String.format(rb.getString("history.unparsable"), name));
                    }
                } else {
                    while (is.read(buffer, 0, buffer.length) != -1) {
                    // we just read. this will throw a SecurityException
                    // if  a signature/digest check fails.
                    }
                }
            }
        }
        Manifest man = jf.getManifest();
        boolean hasSignature = false;
        // The map to record display info, only used when -verbose provided
        //      key: signer info string
        //      value: the list of files with common key
        Map<String, List<String>> output = new LinkedHashMap<>();
        if (man != null) {
            if (verbose != null)
                System.out.println();
            Enumeration<JarEntry> e = entriesVec.elements();
            String tab = rb.getString("6SPACE");
            while (e.hasMoreElements()) {
                JarEntry je = e.nextElement();
                String name = je.getName();
                hasSignature = hasSignature || SignatureFileVerifier.isBlockOrSF(name);
                CodeSigner[] signers = je.getCodeSigners();
                boolean isSigned = (signers != null);
                anySigned |= isSigned;
                hasUnsignedEntry |= !je.isDirectory() && !isSigned && !signatureRelated(name);
                int inStoreOrScope = inKeyStore(signers);
                boolean inStore = (inStoreOrScope & IN_KEYSTORE) != 0;
                boolean inScope = (inStoreOrScope & IN_SCOPE) != 0;
                notSignedByAlias |= (inStoreOrScope & NOT_ALIAS) != 0;
                if (keystore != null) {
                    aliasNotInStore |= isSigned && (!inStore && !inScope);
                }
                // Only used when -verbose provided
                StringBuffer sb = null;
                if (verbose != null) {
                    sb = new StringBuffer();
                    boolean inManifest = ((man.getAttributes(name) != null) || (man.getAttributes("./" + name) != null) || (man.getAttributes("/" + name) != null));
                    sb.append((isSigned ? rb.getString("s") : rb.getString("SPACE")) + (inManifest ? rb.getString("m") : rb.getString("SPACE")) + (inStore ? rb.getString("k") : rb.getString("SPACE")) + (inScope ? rb.getString("i") : rb.getString("SPACE")) + ((inStoreOrScope & NOT_ALIAS) != 0 ? "X" : " ") + rb.getString("SPACE"));
                    sb.append("|");
                }
                // lines at the beginning and end.
                if (isSigned) {
                    if (showcerts)
                        sb.append('\n');
                    for (CodeSigner signer : signers) {
                        // signerInfo() must be called even if -verbose
                        // not provided. The method updates various
                        // warning flags.
                        String si = signerInfo(signer, tab);
                        if (showcerts) {
                            sb.append(si);
                            sb.append('\n');
                        }
                    }
                } else if (showcerts && !verbose.equals("all")) {
                    // to be consistent with old behavior.
                    if (signatureRelated(name)) {
                        sb.append("\n" + tab + rb.getString(".Signature.related.entries.") + "\n\n");
                    } else {
                        sb.append("\n" + tab + rb.getString(".Unsigned.entries.") + "\n\n");
                    }
                }
                if (verbose != null) {
                    String label = sb.toString();
                    if (signatureRelated(name)) {
                        // Entries inside META-INF and other unsigned
                        // entries are grouped separately.
                        label = "-" + label;
                    }
                    if (!output.containsKey(label)) {
                        output.put(label, new ArrayList<String>());
                    }
                    StringBuffer fb = new StringBuffer();
                    String s = Long.toString(je.getSize());
                    for (int i = 6 - s.length(); i > 0; --i) {
                        fb.append(' ');
                    }
                    fb.append(s).append(' ').append(new Date(je.getTime()).toString());
                    fb.append(' ').append(name);
                    output.get(label).add(fb.toString());
                }
            }
        }
        if (verbose != null) {
            for (Entry<String, List<String>> s : output.entrySet()) {
                List<String> files = s.getValue();
                String key = s.getKey();
                if (key.charAt(0) == '-') {
                    // the signature-related group
                    key = key.substring(1);
                }
                int pipe = key.indexOf('|');
                if (verbose.equals("all")) {
                    for (String f : files) {
                        System.out.println(key.substring(0, pipe) + f);
                        System.out.printf(key.substring(pipe + 1));
                    }
                } else {
                    if (verbose.equals("grouped")) {
                        for (String f : files) {
                            System.out.println(key.substring(0, pipe) + f);
                        }
                    } else if (verbose.equals("summary")) {
                        System.out.print(key.substring(0, pipe));
                        if (files.size() > 1) {
                            System.out.println(files.get(0) + " " + String.format(rb.getString(".and.d.more."), files.size() - 1));
                        } else {
                            System.out.println(files.get(0));
                        }
                    }
                    System.out.printf(key.substring(pipe + 1));
                }
            }
            System.out.println();
            System.out.println(rb.getString(".s.signature.was.verified."));
            System.out.println(rb.getString(".m.entry.is.listed.in.manifest"));
            System.out.println(rb.getString(".k.at.least.one.certificate.was.found.in.keystore"));
            System.out.println(rb.getString(".i.at.least.one.certificate.was.found.in.identity.scope"));
            if (ckaliases.size() > 0) {
                System.out.println(rb.getString(".X.not.signed.by.specified.alias.es."));
            }
        }
        if (man == null) {
            System.out.println();
            System.out.println(rb.getString("no.manifest."));
        }
        // must be generated so seeWeak can be updated.
        if (!digestMap.isEmpty() || !sigMap.isEmpty() || !unparsableSignatures.isEmpty()) {
            if (verbose != null) {
                System.out.println();
            }
            for (String s : sigMap.keySet()) {
                if (!digestMap.containsKey(s)) {
                    unparsableSignatures.putIfAbsent(s, String.format(rb.getString("history.nosf"), s));
                }
            }
            for (String s : digestMap.keySet()) {
                PKCS7 p7 = sigMap.get(s);
                if (p7 != null) {
                    String history;
                    try {
                        SignerInfo si = p7.getSignerInfos()[0];
                        X509Certificate signer = si.getCertificate(p7);
                        String digestAlg = digestMap.get(s);
                        String sigAlg = AlgorithmId.makeSigAlg(si.getDigestAlgorithmId().getName(), si.getDigestEncryptionAlgorithmId().getName());
                        PublicKey key = signer.getPublicKey();
                        PKCS7 tsToken = si.getTsToken();
                        if (tsToken != null) {
                            SignerInfo tsSi = tsToken.getSignerInfos()[0];
                            X509Certificate tsSigner = tsSi.getCertificate(tsToken);
                            byte[] encTsTokenInfo = tsToken.getContentInfo().getData();
                            TimestampToken tsTokenInfo = new TimestampToken(encTsTokenInfo);
                            PublicKey tsKey = tsSigner.getPublicKey();
                            String tsDigestAlg = tsTokenInfo.getHashAlgorithm().getName();
                            String tsSigAlg = AlgorithmId.makeSigAlg(tsSi.getDigestAlgorithmId().getName(), tsSi.getDigestEncryptionAlgorithmId().getName());
                            Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.getDefault(Locale.Category.FORMAT));
                            c.setTime(tsTokenInfo.getDate());
                            history = String.format(rb.getString("history.with.ts"), signer.getSubjectX500Principal(), withWeak(digestAlg, DIGEST_PRIMITIVE_SET), withWeak(sigAlg, SIG_PRIMITIVE_SET), withWeak(key), c, tsSigner.getSubjectX500Principal(), withWeak(tsDigestAlg, DIGEST_PRIMITIVE_SET), withWeak(tsSigAlg, SIG_PRIMITIVE_SET), withWeak(tsKey));
                        } else {
                            history = String.format(rb.getString("history.without.ts"), signer.getSubjectX500Principal(), withWeak(digestAlg, DIGEST_PRIMITIVE_SET), withWeak(sigAlg, SIG_PRIMITIVE_SET), withWeak(key));
                        }
                    } catch (Exception e) {
                        // The only usage of sigNameMap, remember the name
                        // of the block file if it's invalid.
                        history = String.format(rb.getString("history.unparsable"), sigNameMap.get(s));
                    }
                    if (verbose != null) {
                        System.out.println(history);
                    }
                } else {
                    unparsableSignatures.putIfAbsent(s, String.format(rb.getString("history.nobk"), s));
                }
            }
            if (verbose != null) {
                for (String s : unparsableSignatures.keySet()) {
                    System.out.println(unparsableSignatures.get(s));
                }
            }
        }
        System.out.println();
        if (!anySigned) {
            if (seeWeak) {
                if (verbose != null) {
                    System.out.println(rb.getString("jar.treated.unsigned.see.weak.verbose"));
                    System.out.println("\n  " + DisabledAlgorithmConstraints.PROPERTY_JAR_DISABLED_ALGS + "=" + Security.getProperty(DisabledAlgorithmConstraints.PROPERTY_JAR_DISABLED_ALGS));
                } else {
                    System.out.println(rb.getString("jar.treated.unsigned.see.weak"));
                }
            } else if (hasSignature) {
                System.out.println(rb.getString("jar.treated.unsigned"));
            } else {
                System.out.println(rb.getString("jar.is.unsigned"));
            }
        } else {
            boolean warningAppeared = false;
            boolean errorAppeared = false;
            if (badKeyUsage || badExtendedKeyUsage || badNetscapeCertType || notYetValidCert || chainNotValidated || hasExpiredCert || hasUnsignedEntry || aliasNotInStore || notSignedByAlias) {
                if (strict) {
                    System.out.println(rb.getString("jar.verified.with.signer.errors."));
                    System.out.println();
                    System.out.println(rb.getString("Error."));
                    errorAppeared = true;
                } else {
                    System.out.println(rb.getString("jar.verified."));
                    System.out.println();
                    System.out.println(rb.getString("Warning."));
                    warningAppeared = true;
                }
                if (badKeyUsage) {
                    System.out.println(rb.getString("This.jar.contains.entries.whose.signer.certificate.s.KeyUsage.extension.doesn.t.allow.code.signing."));
                }
                if (badExtendedKeyUsage) {
                    System.out.println(rb.getString("This.jar.contains.entries.whose.signer.certificate.s.ExtendedKeyUsage.extension.doesn.t.allow.code.signing."));
                }
                if (badNetscapeCertType) {
                    System.out.println(rb.getString("This.jar.contains.entries.whose.signer.certificate.s.NetscapeCertType.extension.doesn.t.allow.code.signing."));
                }
                if (hasUnsignedEntry) {
                    System.out.println(rb.getString("This.jar.contains.unsigned.entries.which.have.not.been.integrity.checked."));
                }
                if (hasExpiredCert) {
                    System.out.println(rb.getString("This.jar.contains.entries.whose.signer.certificate.has.expired."));
                }
                if (notYetValidCert) {
                    System.out.println(rb.getString("This.jar.contains.entries.whose.signer.certificate.is.not.yet.valid."));
                }
                if (chainNotValidated) {
                    System.out.println(rb.getString("This.jar.contains.entries.whose.certificate.chain.is.not.validated."));
                }
                if (notSignedByAlias) {
                    System.out.println(rb.getString("This.jar.contains.signed.entries.which.is.not.signed.by.the.specified.alias.es."));
                }
                if (aliasNotInStore) {
                    System.out.println(rb.getString("This.jar.contains.signed.entries.that.s.not.signed.by.alias.in.this.keystore."));
                }
            } else {
                System.out.println(rb.getString("jar.verified."));
            }
            if (hasExpiringCert || noTimestamp) {
                if (!warningAppeared) {
                    System.out.println();
                    System.out.println(rb.getString("Warning."));
                    warningAppeared = true;
                }
                if (hasExpiringCert) {
                    System.out.println(rb.getString("This.jar.contains.entries.whose.signer.certificate.will.expire.within.six.months."));
                }
                if (noTimestamp) {
                    System.out.println(String.format(rb.getString("no.timestamp.verifying"), expireDate));
                }
            }
            if (warningAppeared || errorAppeared) {
                if (!(verbose != null && showcerts)) {
                    System.out.println();
                    System.out.println(rb.getString("Re.run.with.the.verbose.and.certs.options.for.more.details."));
                }
            }
        }
        return;
    } catch (Exception e) {
        System.out.println(rb.getString("jarsigner.") + e);
        if (debug) {
            e.printStackTrace();
        }
    } finally {
        // close the resource
        if (jf != null) {
            jf.close();
        }
    }
    System.exit(1);
}
Also used : TimestampToken(sun.security.timestamp.TimestampToken) PathList(sun.security.tools.PathList) PKCS7(sun.security.pkcs.PKCS7) X509Certificate(java.security.cert.X509Certificate) URISyntaxException(java.net.URISyntaxException) CertificateNotYetValidException(java.security.cert.CertificateNotYetValidException) CertificateExpiredException(java.security.cert.CertificateExpiredException) SocketTimeoutException(java.net.SocketTimeoutException) CertificateException(java.security.cert.CertificateException) SignerInfo(sun.security.pkcs.SignerInfo)

Example 4 with TimestampToken

use of sun.security.timestamp.TimestampToken in project Bytecoder by mirkosertic.

the class SignerInfo method getTimestamp.

/*
     * Extracts a timestamp from a PKCS7 SignerInfo.
     *
     * Examines the signer's unsigned attributes for a
     * {@code signatureTimestampToken} attribute. If present,
     * then it is parsed to extract the date and time at which the
     * timestamp was generated.
     *
     * @param info A signer information element of a PKCS 7 block.
     *
     * @return A timestamp token or null if none is present.
     * @throws IOException if an error is encountered while parsing the
     *         PKCS7 data.
     * @throws NoSuchAlgorithmException if an error is encountered while
     *         verifying the PKCS7 object.
     * @throws SignatureException if an error is encountered while
     *         verifying the PKCS7 object.
     * @throws CertificateException if an error is encountered while generating
     *         the TSA's certpath.
     */
public Timestamp getTimestamp() throws IOException, NoSuchAlgorithmException, SignatureException, CertificateException {
    if (timestamp != null || !hasTimestamp)
        return timestamp;
    PKCS7 tsToken = getTsToken();
    if (tsToken == null) {
        hasTimestamp = false;
        return null;
    }
    // Extract the content (an encoded timestamp token info)
    byte[] encTsTokenInfo = tsToken.getContentInfo().getData();
    // Extract the signer (the Timestamping Authority)
    // while verifying the content
    SignerInfo[] tsa = tsToken.verify(encTsTokenInfo);
    // Expect only one signer
    ArrayList<X509Certificate> chain = tsa[0].getCertificateChain(tsToken);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    CertPath tsaChain = cf.generateCertPath(chain);
    // Create a timestamp token info object
    TimestampToken tsTokenInfo = new TimestampToken(encTsTokenInfo);
    // Check that the signature timestamp applies to this signature
    verifyTimestamp(tsTokenInfo);
    // Create a timestamp object
    timestamp = new Timestamp(tsTokenInfo.getDate(), tsaChain);
    return timestamp;
}
Also used : CertPath(java.security.cert.CertPath) CertificateFactory(java.security.cert.CertificateFactory) Timestamp(java.security.Timestamp) X509Certificate(java.security.cert.X509Certificate) TimestampToken(sun.security.timestamp.TimestampToken)

Example 5 with TimestampToken

use of sun.security.timestamp.TimestampToken in project j2objc by google.

the class SignatureFileVerifier method getTimestamp.

/*
     * Examines a signature timestamp token to generate a timestamp object.
     *
     * Examines the signer's unsigned attributes for a
     * <tt>signatureTimestampToken</tt> attribute. If present,
     * then it is parsed to extract the date and time at which the
     * timestamp was generated.
     *
     * @param info A signer information element of a PKCS 7 block.
     *
     * @return A timestamp token or null if none is present.
     * @throws IOException if an error is encountered while parsing the
     *         PKCS7 data.
     * @throws NoSuchAlgorithmException if an error is encountered while
     *         verifying the PKCS7 object.
     * @throws SignatureException if an error is encountered while
     *         verifying the PKCS7 object.
     * @throws CertificateException if an error is encountered while generating
     *         the TSA's certpath.
     */
private Timestamp getTimestamp(SignerInfo info) throws IOException, NoSuchAlgorithmException, SignatureException, CertificateException {
    Timestamp timestamp = null;
    // Extract the signer's unsigned attributes
    PKCS9Attributes unsignedAttrs = info.getUnauthenticatedAttributes();
    if (unsignedAttrs != null) {
        PKCS9Attribute timestampTokenAttr = unsignedAttrs.getAttribute("signatureTimestampToken");
        if (timestampTokenAttr != null) {
            PKCS7 timestampToken = new PKCS7((byte[]) timestampTokenAttr.getValue());
            // Extract the content (an encoded timestamp token info)
            byte[] encodedTimestampTokenInfo = timestampToken.getContentInfo().getData();
            // Extract the signer (the Timestamping Authority)
            // while verifying the content
            SignerInfo[] tsa = timestampToken.verify(encodedTimestampTokenInfo);
            // Expect only one signer
            ArrayList<X509Certificate> chain = tsa[0].getCertificateChain(timestampToken);
            CertPath tsaChain = certificateFactory.generateCertPath(chain);
            // Create a timestamp token info object
            TimestampToken timestampTokenInfo = new TimestampToken(encodedTimestampTokenInfo);
            // Check that the signature timestamp applies to this signature
            verifyTimestamp(timestampTokenInfo, info.getEncryptedDigest());
            // Create a timestamp object
            timestamp = new Timestamp(timestampTokenInfo.getDate(), tsaChain);
        }
    }
    return timestamp;
}
Also used : CertPath(java.security.cert.CertPath) X509Certificate(java.security.cert.X509Certificate) TimestampToken(sun.security.timestamp.TimestampToken)

Aggregations

TimestampToken (sun.security.timestamp.TimestampToken)5 X509Certificate (java.security.cert.X509Certificate)4 CertPath (java.security.cert.CertPath)3 Timestamp (java.security.Timestamp)2 CertificateFactory (java.security.cert.CertificateFactory)2 PKCS7 (sun.security.pkcs.PKCS7)2 SignerInfo (sun.security.pkcs.SignerInfo)2 FileInputStream (java.io.FileInputStream)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 SocketTimeoutException (java.net.SocketTimeoutException)1 URISyntaxException (java.net.URISyntaxException)1 CertificateException (java.security.cert.CertificateException)1 CertificateExpiredException (java.security.cert.CertificateExpiredException)1 CertificateNotYetValidException (java.security.cert.CertificateNotYetValidException)1 JarEntry (java.util.jar.JarEntry)1 JarFile (java.util.jar.JarFile)1 PKCS9Attribute (sun.security.pkcs.PKCS9Attribute)1 PathList (sun.security.tools.PathList)1