Search in sources :

Example 6 with SignerInfo

use of sun.security.pkcs.SignerInfo in project jdk8u_jdk by JetBrains.

the class SignatureFileVerifier method processImpl.

private void processImpl(Hashtable<String, CodeSigner[]> signers, List<Object> manifestDigests) throws IOException, SignatureException, NoSuchAlgorithmException, JarException, CertificateException {
    Manifest sf = new Manifest();
    sf.read(new ByteArrayInputStream(sfBytes));
    String version = sf.getMainAttributes().getValue(Attributes.Name.SIGNATURE_VERSION);
    if ((version == null) || !(version.equalsIgnoreCase("1.0"))) {
        // for now we just ignore this signature file
        return;
    }
    SignerInfo[] infos = block.verify(sfBytes);
    if (infos == null) {
        throw new SecurityException("cannot verify signature block file " + name);
    }
    CodeSigner[] newSigners = getSigners(infos, block);
    // make sure we have something to do all this work for...
    if (newSigners == null)
        return;
    /*
         * Look for the latest timestamp in the signature block.  If an entry
         * has no timestamp, use current time (aka null).
         */
    for (CodeSigner s : newSigners) {
        if (debug != null) {
            debug.println("Gathering timestamp for:  " + s.toString());
        }
        if (s.getTimestamp() == null) {
            timestamp = null;
            break;
        } else if (timestamp == null) {
            timestamp = s.getTimestamp();
        } else {
            if (timestamp.getTimestamp().before(s.getTimestamp().getTimestamp())) {
                timestamp = s.getTimestamp();
            }
        }
    }
    Iterator<Map.Entry<String, Attributes>> entries = sf.getEntries().entrySet().iterator();
    // see if we can verify the whole manifest first
    boolean manifestSigned = verifyManifestHash(sf, md, manifestDigests);
    // verify manifest main attributes
    if (!manifestSigned && !verifyManifestMainAttrs(sf, md)) {
        throw new SecurityException("Invalid signature file digest for Manifest main attributes");
    }
    // go through each section in the signature file
    while (entries.hasNext()) {
        Map.Entry<String, Attributes> e = entries.next();
        String name = e.getKey();
        if (manifestSigned || (verifySection(e.getValue(), name, md))) {
            if (name.startsWith("./"))
                name = name.substring(2);
            if (name.startsWith("/"))
                name = name.substring(1);
            updateSigners(newSigners, signers, name);
            if (debug != null) {
                debug.println("processSignature signed name = " + name);
            }
        } else if (debug != null) {
            debug.println("processSignature unsigned name = " + name);
        }
    }
    // MANIFEST.MF is always regarded as signed
    updateSigners(newSigners, signers, JarFile.MANIFEST_NAME);
}
Also used : Attributes(java.util.jar.Attributes) GeneralSecurityException(java.security.GeneralSecurityException) Manifest(java.util.jar.Manifest) SignerInfo(sun.security.pkcs.SignerInfo) ByteArrayInputStream(java.io.ByteArrayInputStream) HashMap(java.util.HashMap) Map(java.util.Map) CodeSigner(java.security.CodeSigner)

Example 7 with SignerInfo

use of sun.security.pkcs.SignerInfo in project android_frameworks_base by crdroidandroid.

the class StrictJarVerifier method verifyBytes.

/**
     * Verifies that the signature computed from {@code sfBytes} matches
     * that specified in {@code blockBytes} (which is a PKCS7 block). Returns
     * certificates listed in the PKCS7 block. Throws a {@code GeneralSecurityException}
     * if something goes wrong during verification.
     */
static Certificate[] verifyBytes(byte[] blockBytes, byte[] sfBytes) throws GeneralSecurityException {
    Object obj = null;
    try {
        obj = Providers.startJarVerification();
        PKCS7 block = new PKCS7(blockBytes);
        SignerInfo[] verifiedSignerInfos = block.verify(sfBytes);
        if ((verifiedSignerInfos == null) || (verifiedSignerInfos.length == 0)) {
            throw new GeneralSecurityException("Failed to verify signature: no verified SignerInfos");
        }
        // Ignore any SignerInfo other than the first one, to be compatible with older Android
        // platforms which have been doing this for years. See
        // libcore/luni/src/main/java/org/apache/harmony/security/utils/JarUtils.java
        // verifySignature method of older platforms.
        SignerInfo verifiedSignerInfo = verifiedSignerInfos[0];
        List<X509Certificate> verifiedSignerCertChain = verifiedSignerInfo.getCertificateChain(block);
        if (verifiedSignerCertChain == null) {
            // Should never happen
            throw new GeneralSecurityException("Failed to find verified SignerInfo certificate chain");
        } else if (verifiedSignerCertChain.isEmpty()) {
            // Should never happen
            throw new GeneralSecurityException("Verified SignerInfo certificate chain is emtpy");
        }
        return verifiedSignerCertChain.toArray(new X509Certificate[verifiedSignerCertChain.size()]);
    } catch (IOException e) {
        throw new GeneralSecurityException("IO exception verifying jar cert", e);
    } finally {
        Providers.stopJarVerification(obj);
    }
}
Also used : SignerInfo(sun.security.pkcs.SignerInfo) PKCS7(sun.security.pkcs.PKCS7) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate)

Example 8 with SignerInfo

use of sun.security.pkcs.SignerInfo in project android_frameworks_base by AOSPA.

the class StrictJarVerifier method verifyBytes.

/**
     * Verifies that the signature computed from {@code sfBytes} matches
     * that specified in {@code blockBytes} (which is a PKCS7 block). Returns
     * certificates listed in the PKCS7 block. Throws a {@code GeneralSecurityException}
     * if something goes wrong during verification.
     */
static Certificate[] verifyBytes(byte[] blockBytes, byte[] sfBytes) throws GeneralSecurityException {
    Object obj = null;
    try {
        obj = Providers.startJarVerification();
        PKCS7 block = new PKCS7(blockBytes);
        SignerInfo[] verifiedSignerInfos = block.verify(sfBytes);
        if ((verifiedSignerInfos == null) || (verifiedSignerInfos.length == 0)) {
            throw new GeneralSecurityException("Failed to verify signature: no verified SignerInfos");
        }
        // Ignore any SignerInfo other than the first one, to be compatible with older Android
        // platforms which have been doing this for years. See
        // libcore/luni/src/main/java/org/apache/harmony/security/utils/JarUtils.java
        // verifySignature method of older platforms.
        SignerInfo verifiedSignerInfo = verifiedSignerInfos[0];
        List<X509Certificate> verifiedSignerCertChain = verifiedSignerInfo.getCertificateChain(block);
        if (verifiedSignerCertChain == null) {
            // Should never happen
            throw new GeneralSecurityException("Failed to find verified SignerInfo certificate chain");
        } else if (verifiedSignerCertChain.isEmpty()) {
            // Should never happen
            throw new GeneralSecurityException("Verified SignerInfo certificate chain is emtpy");
        }
        return verifiedSignerCertChain.toArray(new X509Certificate[verifiedSignerCertChain.size()]);
    } catch (IOException e) {
        throw new GeneralSecurityException("IO exception verifying jar cert", e);
    } finally {
        Providers.stopJarVerification(obj);
    }
}
Also used : SignerInfo(sun.security.pkcs.SignerInfo) PKCS7(sun.security.pkcs.PKCS7) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate)

Example 9 with SignerInfo

use of sun.security.pkcs.SignerInfo in project Payara by payara.

the class JarSigner method signJar.

/**
 * Signs a JAR, adding caller-specified attributes to the manifest's main attrs and also
 * inserting (and signing) additional caller-supplied content as new entries in the
 * zip output stream.
 * @param input input JAR file
 * @param zout Zip output stream created
 * @param alias signing alias in the keystore
 * @param additionalAttrs additional attributes to add to the manifest's main attrs (null if none)
 * @param additionalEntries entry-name/byte[] pairs of additional content to add to the signed output
 * @throws IOException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws UnrecoverableKeyException
 * @throws SignatureException
 */
public void signJar(File input, ZipOutputStream zout, String alias, final Attributes additionalAttrs, Map<String, byte[]> additionalEntries) throws IOException, KeyStoreException, NoSuchAlgorithmException, InvalidKeyException, UnrecoverableKeyException, SignatureException {
    JarFile jf = new JarFile(input);
    try {
        Enumeration<JarEntry> jes;
        // manifestEntries is content of META-INF/MANIFEST.MF
        StringBuilder manifestEntries = new StringBuilder();
        byte[] manifestContent;
        byte[] sigFileContent = getExistingSignatureFile(jf);
        boolean signed = (sigFileContent != null);
        if (!signed || !additionalEntries.isEmpty()) {
            // manifestHeader is header of META-INF/MANIFEST.MF, initialized to default
            jes = jf.entries();
            Manifest manifest = retrieveManifest(jf);
            StringBuilder manifestHeader = new StringBuilder();
            Attributes mfAttrs = manifest.getMainAttributes();
            if (additionalAttrs != null) {
                mfAttrs.putAll(additionalAttrs);
            }
            appendAttributes(manifestHeader, mfAttrs);
            // sigFileEntries is content of META-INF/ME.SF
            StringBuilder sigFileEntries = new StringBuilder();
            while (jes.hasMoreElements()) {
                JarEntry je = jes.nextElement();
                String name = je.getName();
                if ((je.isDirectory() && manifest.getAttributes(name) == null) || name.equals(JarFile.MANIFEST_NAME)) {
                    continue;
                }
                processMetadataForEntry(manifest, manifestEntries, sigFileEntries, name, readJarEntry(jf, je));
            }
            if (additionalEntries != null) {
                for (Map.Entry<String, byte[]> entry : additionalEntries.entrySet()) {
                    processMetadataForEntry(manifest, manifestEntries, sigFileEntries, entry.getKey(), entry.getValue());
                }
            }
            // META-INF/ME.SF
            StringBuilder sigFile = new StringBuilder("Signature-Version: 1.0\r\n").append(digestAlgorithm).append("-Digest-Manifest-Main-Attributes: ").append(hash(manifestHeader.toString())).append("\r\n").append("Created-By: ").append(System.getProperty("java.version")).append(" (").append(System.getProperty("java.vendor")).append(")\r\n");
            // Combine header and content of MANIFEST.MF, and rehash
            manifestHeader.append(manifestEntries);
            sigFile.append(digestAlgorithm).append("-Digest-Manifest: ").append(hash(manifestHeader.toString())).append("\r\n\r\n");
            // Combine header and content of ME.SF
            sigFile.append(sigFileEntries);
            manifestContent = manifestHeader.toString().getBytes();
            sigFileContent = sigFile.toString().getBytes();
        } else {
            manifestContent = readJarEntry(jf, jf.getJarEntry(JarFile.MANIFEST_NAME));
        }
        X509Certificate[] certChain = null;
        PrivateKey privKey = null;
        KeyStore[] ks = securitySupport.getKeyStores();
        for (int i = 0; i < ks.length; i++) {
            privKey = securitySupport.getPrivateKeyForAlias(alias, i);
            if (privKey != null) {
                Certificate[] cs = ks[i].getCertificateChain(alias);
                certChain = new X509Certificate[cs.length];
                for (int j = 0; j < cs.length; j++) {
                    certChain[j] = (X509Certificate) cs[j];
                }
            }
        }
        // Sign ME.SF
        Signature sig = Signature.getInstance(digestAlgorithm + "with" + keyAlgorithm);
        sig.initSign(privKey);
        sig.update(sigFileContent);
        // Create PKCS7 block
        PKCS7 pkcs7 = new PKCS7(new AlgorithmId[] { AlgorithmId.get(digestAlgorithm) }, new ContentInfo(sigFileContent), certChain, new SignerInfo[] { new SignerInfo((X500Name) certChain[0].getIssuerDN(), certChain[0].getSerialNumber(), AlgorithmId.get(digestAlgorithm), AlgorithmId.get(keyAlgorithm), sig.sign()) });
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        pkcs7.encodeSignedData(bout);
        // Write output
        zout.putNextEntry((signed) ? getZipEntry(jf.getJarEntry(JarFile.MANIFEST_NAME)) : new ZipEntry(JarFile.MANIFEST_NAME));
        zout.write(manifestContent);
        zout.putNextEntry(new ZipEntry("META-INF/" + alias.toUpperCase(Locale.US) + ".SF"));
        zout.write(sigFileContent);
        zout.putNextEntry(new ZipEntry("META-INF/" + alias.toUpperCase(Locale.US) + "." + keyAlgorithm));
        zout.write(bout.toByteArray());
        jes = jf.entries();
        while (jes.hasMoreElements()) {
            JarEntry je = jes.nextElement();
            String name = je.getName();
            if (!name.equals(JarFile.MANIFEST_NAME)) {
                zout.putNextEntry(getZipEntry(je));
                byte[] data = readJarEntry(jf, je);
                zout.write(data);
            }
        }
        if (additionalEntries != null) {
            for (Map.Entry<String, byte[]> entry : additionalEntries.entrySet()) {
                final ZipEntry newZipEntry = new ZipEntry(entry.getKey());
                zout.putNextEntry(newZipEntry);
                zout.write(entry.getValue());
            }
        }
    } finally {
        jf.close();
    }
}
Also used : PrivateKey(java.security.PrivateKey) ZipEntry(java.util.zip.ZipEntry) Attributes(java.util.jar.Attributes) X500Name(sun.security.x509.X500Name) ContentInfo(sun.security.pkcs.ContentInfo) PKCS7(sun.security.pkcs.PKCS7) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) Manifest(java.util.jar.Manifest) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) SignerInfo(sun.security.pkcs.SignerInfo) Signature(java.security.Signature) Map(java.util.Map) Collections.emptyMap(java.util.Collections.emptyMap) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 10 with SignerInfo

use of sun.security.pkcs.SignerInfo in project portal by ixinportal.

the class SignTool method verifyP7.

/**
 * 验证签名(无CRL)
 *
 * @param signature
 *            签名签名结果
 * @param data
 *            被签名数据
 * @param dn
 *            签名证书dn, 如果为空则不做匹配验证
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws SignatureException
 * @throws InvalidKeyException
 * @throws CertificateException
 * @throws NoSuchProviderException
 */
public void verifyP7(String signature, byte[] data, String dn) throws IOException, NoSuchAlgorithmException, SignatureException, InvalidKeyException, CertificateException, NoSuchProviderException {
    if (mode != VERIFIER)
        throw new IllegalStateException("call a PKCS7Tool instance not for verify.");
    byte[] sign = new BASE64Decoder().decodeBuffer(signature);
    PKCS7 p7 = new PKCS7(sign);
    X509Certificate[] certs = p7.getCertificates();
    if (debug)
        for (int i = 0; i < certs.length; i++) {
            X509Certificate cert = certs[i];
            System.out.println("SIGNER " + i + "=\n" + cert);
            System.out.println("SIGNER " + i + "=\n" + new BASE64Encoder().encode(cert.getEncoded()));
        }
    // 验证签名本身、证书用法、证书扩展
    SignerInfo[] sis = p7.verify(data);
    // check the results of the verification
    if (sis == null)
        throw new SignatureException("Signature failed verification, data has been tampered");
    for (int i = 0; i < sis.length; i++) {
        SignerInfo si = sis[i];
        X509Certificate cert = si.getCertificate(p7);
        // 证书是否过期验证,如果不用系统日期可用cert.checkValidity(date);
        cert.checkValidity();
        if (!cert.equals(rootCertificate)) {
            // 验证证书签名
            cert.verify(rootCertificate.getPublicKey());
        }
        // 验证dn
        if (i == 0 && dn != null) {
            X500Principal name = cert.getSubjectX500Principal();
            if (!dn.equals(name.getName(X500Principal.RFC1779)) && !new X500Principal(dn).equals(name))
                throw new SignatureException("Signer dn '" + name.getName(X500Principal.RFC1779) + "' does not matchs '" + dn + "'");
        }
    }
}
Also used : SignerInfo(sun.security.pkcs.SignerInfo) PKCS7(sun.security.pkcs.PKCS7) BASE64Encoder(sun.misc.BASE64Encoder) X500Principal(javax.security.auth.x500.X500Principal) SignatureException(java.security.SignatureException) BASE64Decoder(sun.misc.BASE64Decoder) X509Certificate(java.security.cert.X509Certificate)

Aggregations

SignerInfo (sun.security.pkcs.SignerInfo)25 PKCS7 (sun.security.pkcs.PKCS7)21 X509Certificate (java.security.cert.X509Certificate)19 IOException (java.io.IOException)11 ByteArrayInputStream (java.io.ByteArrayInputStream)8 GeneralSecurityException (java.security.GeneralSecurityException)7 ContentInfo (sun.security.pkcs.ContentInfo)7 InputStream (java.io.InputStream)6 SignatureException (java.security.SignatureException)6 RandomAccessFile (java.io.RandomAccessFile)5 PublicKey (java.security.PublicKey)5 CodeSigner (java.security.CodeSigner)4 Map (java.util.Map)4 X500Name (sun.security.x509.X500Name)4 Signature (java.security.Signature)3 HashMap (java.util.HashMap)3 Attributes (java.util.jar.Attributes)3 Manifest (java.util.jar.Manifest)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 CertPath (java.security.cert.CertPath)2