Search in sources :

Example 21 with Attributes

use of java.util.jar.Attributes in project intellij-community by JetBrains.

the class ManifestFileUtil method updateManifest.

public static void updateManifest(@NotNull final VirtualFile file, @Nullable final String mainClass, @Nullable final List<String> classpath, final boolean replaceValues) {
    final Manifest manifest = readManifest(file);
    final Attributes mainAttributes = manifest.getMainAttributes();
    if (mainClass != null) {
        mainAttributes.put(Attributes.Name.MAIN_CLASS, mainClass);
    } else if (replaceValues) {
        mainAttributes.remove(Attributes.Name.MAIN_CLASS);
    }
    if (classpath != null && !classpath.isEmpty()) {
        List<String> updatedClasspath;
        if (replaceValues) {
            updatedClasspath = classpath;
        } else {
            updatedClasspath = new ArrayList<>();
            final String oldClasspath = (String) mainAttributes.get(Attributes.Name.CLASS_PATH);
            if (!StringUtil.isEmpty(oldClasspath)) {
                updatedClasspath.addAll(StringUtil.split(oldClasspath, " "));
            }
            for (String path : classpath) {
                if (!updatedClasspath.contains(path)) {
                    updatedClasspath.add(path);
                }
            }
        }
        mainAttributes.put(Attributes.Name.CLASS_PATH, StringUtil.join(updatedClasspath, " "));
    } else if (replaceValues) {
        mainAttributes.remove(Attributes.Name.CLASS_PATH);
    }
    ManifestBuilder.setVersionAttribute(mainAttributes);
    ApplicationManager.getApplication().runWriteAction(() -> {
        try {
            final OutputStream outputStream = file.getOutputStream(ManifestFileUtil.class);
            try {
                manifest.write(outputStream);
            } finally {
                outputStream.close();
            }
        } catch (IOException e) {
            LOG.info(e);
        }
    });
}
Also used : OutputStream(java.io.OutputStream) Attributes(java.util.jar.Attributes) IOException(java.io.IOException) Manifest(java.util.jar.Manifest)

Example 22 with Attributes

use of java.util.jar.Attributes in project android_frameworks_base by DirtyUnicorns.

the class StrictJarManifest method write.

/**
     * Writes out the attribute information of the specified manifest to the
     * specified {@code OutputStream}
     *
     * @param manifest
     *            the manifest to write out.
     * @param out
     *            The {@code OutputStream} to write to.
     * @throws IOException
     *             If an error occurs writing the {@code StrictJarManifest}.
     */
static void write(StrictJarManifest manifest, OutputStream out) throws IOException {
    CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder();
    ByteBuffer buffer = ByteBuffer.allocate(LINE_LENGTH_LIMIT);
    Attributes.Name versionName = Attributes.Name.MANIFEST_VERSION;
    String version = manifest.mainAttributes.getValue(versionName);
    if (version == null) {
        versionName = Attributes.Name.SIGNATURE_VERSION;
        version = manifest.mainAttributes.getValue(versionName);
    }
    if (version != null) {
        writeEntry(out, versionName, version, encoder, buffer);
        Iterator<?> entries = manifest.mainAttributes.keySet().iterator();
        while (entries.hasNext()) {
            Attributes.Name name = (Attributes.Name) entries.next();
            if (!name.equals(versionName)) {
                writeEntry(out, name, manifest.mainAttributes.getValue(name), encoder, buffer);
            }
        }
    }
    out.write(LINE_SEPARATOR);
    Iterator<String> i = manifest.getEntries().keySet().iterator();
    while (i.hasNext()) {
        String key = i.next();
        writeEntry(out, Attributes.Name.NAME, key, encoder, buffer);
        Attributes attributes = manifest.entries.get(key);
        Iterator<?> entries = attributes.keySet().iterator();
        while (entries.hasNext()) {
            Attributes.Name name = (Attributes.Name) entries.next();
            writeEntry(out, name, attributes.getValue(name), encoder, buffer);
        }
        out.write(LINE_SEPARATOR);
    }
}
Also used : Attributes(java.util.jar.Attributes) CharsetEncoder(java.nio.charset.CharsetEncoder) ByteBuffer(java.nio.ByteBuffer)

Example 23 with Attributes

use of java.util.jar.Attributes in project android_frameworks_base by DirtyUnicorns.

the class StrictJarVerifier method verifyCertificate.

/**
     * @param certFile
     */
private void verifyCertificate(String certFile) {
    // Found Digital Sig, .SF should already have been read
    String signatureFile = certFile.substring(0, certFile.lastIndexOf('.')) + ".SF";
    byte[] sfBytes = metaEntries.get(signatureFile);
    if (sfBytes == null) {
        return;
    }
    byte[] manifestBytes = metaEntries.get(JarFile.MANIFEST_NAME);
    // Manifest entry is required for any verifications.
    if (manifestBytes == null) {
        return;
    }
    byte[] sBlockBytes = metaEntries.get(certFile);
    try {
        Certificate[] signerCertChain = verifyBytes(sBlockBytes, sfBytes);
        if (signerCertChain != null) {
            certificates.put(signatureFile, signerCertChain);
        }
    } catch (GeneralSecurityException e) {
        throw failedVerification(jarName, signatureFile, e);
    }
    // Verify manifest hash in .sf file
    Attributes attributes = new Attributes();
    HashMap<String, Attributes> entries = new HashMap<String, Attributes>();
    try {
        StrictJarManifestReader im = new StrictJarManifestReader(sfBytes, attributes);
        im.readEntries(entries, null);
    } catch (IOException e) {
        return;
    }
    // If requested, check whether APK Signature Scheme v2 signature was stripped.
    if (signatureSchemeRollbackProtectionsEnforced) {
        String apkSignatureSchemeIdList = attributes.getValue(ApkSignatureSchemeV2Verifier.SF_ATTRIBUTE_ANDROID_APK_SIGNED_NAME);
        if (apkSignatureSchemeIdList != null) {
            // This field contains a comma-separated list of APK signature scheme IDs which
            // were used to sign this APK. If an ID is known to us, it means signatures of that
            // scheme were stripped from the APK because otherwise we wouldn't have fallen back
            // to verifying the APK using the JAR signature scheme.
            boolean v2SignatureGenerated = false;
            StringTokenizer tokenizer = new StringTokenizer(apkSignatureSchemeIdList, ",");
            while (tokenizer.hasMoreTokens()) {
                String idText = tokenizer.nextToken().trim();
                if (idText.isEmpty()) {
                    continue;
                }
                int id;
                try {
                    id = Integer.parseInt(idText);
                } catch (Exception ignored) {
                    continue;
                }
                if (id == ApkSignatureSchemeV2Verifier.SF_ATTRIBUTE_ANDROID_APK_SIGNED_ID) {
                    // This APK was supposed to be signed with APK Signature Scheme v2 but no
                    // such signature was found.
                    v2SignatureGenerated = true;
                    break;
                }
            }
            if (v2SignatureGenerated) {
                throw new SecurityException(signatureFile + " indicates " + jarName + " is signed using APK Signature Scheme v2, but no such signature was" + " found. Signature stripped?");
            }
        }
    }
    // Do we actually have any signatures to look at?
    if (attributes.get(Attributes.Name.SIGNATURE_VERSION) == null) {
        return;
    }
    boolean createdBySigntool = false;
    String createdBy = attributes.getValue("Created-By");
    if (createdBy != null) {
        createdBySigntool = createdBy.indexOf("signtool") != -1;
    }
    // such verification.
    if (mainAttributesEnd > 0 && !createdBySigntool) {
        String digestAttribute = "-Digest-Manifest-Main-Attributes";
        if (!verify(attributes, digestAttribute, manifestBytes, 0, mainAttributesEnd, false, true)) {
            throw failedVerification(jarName, signatureFile);
        }
    }
    // Use .SF to verify the whole manifest.
    String digestAttribute = createdBySigntool ? "-Digest" : "-Digest-Manifest";
    if (!verify(attributes, digestAttribute, manifestBytes, 0, manifestBytes.length, false, false)) {
        Iterator<Map.Entry<String, Attributes>> it = entries.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Attributes> entry = it.next();
            StrictJarManifest.Chunk chunk = manifest.getChunk(entry.getKey());
            if (chunk == null) {
                return;
            }
            if (!verify(entry.getValue(), "-Digest", manifestBytes, chunk.start, chunk.end, createdBySigntool, false)) {
                throw invalidDigest(signatureFile, entry.getKey(), jarName);
            }
        }
    }
    metaEntries.put(signatureFile, null);
    signatures.put(signatureFile, entries);
}
Also used : HashMap(java.util.HashMap) GeneralSecurityException(java.security.GeneralSecurityException) Attributes(java.util.jar.Attributes) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) StringTokenizer(java.util.StringTokenizer) HashMap(java.util.HashMap) Map(java.util.Map) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 24 with Attributes

use of java.util.jar.Attributes in project XobotOS by xamarin.

the class PackageParser method collectCertificates.

public boolean collectCertificates(Package pkg, int flags) {
    pkg.mSignatures = null;
    WeakReference<byte[]> readBufferRef;
    byte[] readBuffer = null;
    synchronized (mSync) {
        readBufferRef = mReadBuffer;
        if (readBufferRef != null) {
            mReadBuffer = null;
            readBuffer = readBufferRef.get();
        }
        if (readBuffer == null) {
            readBuffer = new byte[8192];
            readBufferRef = new WeakReference<byte[]>(readBuffer);
        }
    }
    try {
        JarFile jarFile = new JarFile(mArchiveSourcePath);
        Certificate[] certs = null;
        if ((flags & PARSE_IS_SYSTEM) != 0) {
            // If this package comes from the system image, then we
            // can trust it...  we'll just use the AndroidManifest.xml
            // to retrieve its signatures, not validating all of the
            // files.
            JarEntry jarEntry = jarFile.getJarEntry(ANDROID_MANIFEST_FILENAME);
            certs = loadCertificates(jarFile, jarEntry, readBuffer);
            if (certs == null) {
                Slog.e(TAG, "Package " + pkg.packageName + " has no certificates at entry " + jarEntry.getName() + "; ignoring!");
                jarFile.close();
                mParseError = PackageManager.INSTALL_PARSE_FAILED_NO_CERTIFICATES;
                return false;
            }
            if (DEBUG_JAR) {
                Slog.i(TAG, "File " + mArchiveSourcePath + ": entry=" + jarEntry + " certs=" + (certs != null ? certs.length : 0));
                if (certs != null) {
                    final int N = certs.length;
                    for (int i = 0; i < N; i++) {
                        Slog.i(TAG, "  Public key: " + certs[i].getPublicKey().getEncoded() + " " + certs[i].getPublicKey());
                    }
                }
            }
        } else {
            Enumeration<JarEntry> entries = jarFile.entries();
            final Manifest manifest = jarFile.getManifest();
            while (entries.hasMoreElements()) {
                final JarEntry je = entries.nextElement();
                if (je.isDirectory())
                    continue;
                final String name = je.getName();
                if (name.startsWith("META-INF/"))
                    continue;
                if (ANDROID_MANIFEST_FILENAME.equals(name)) {
                    final Attributes attributes = manifest.getAttributes(name);
                    pkg.manifestDigest = ManifestDigest.fromAttributes(attributes);
                }
                final Certificate[] localCerts = loadCertificates(jarFile, je, readBuffer);
                if (DEBUG_JAR) {
                    Slog.i(TAG, "File " + mArchiveSourcePath + " entry " + je.getName() + ": certs=" + certs + " (" + (certs != null ? certs.length : 0) + ")");
                }
                if (localCerts == null) {
                    Slog.e(TAG, "Package " + pkg.packageName + " has no certificates at entry " + je.getName() + "; ignoring!");
                    jarFile.close();
                    mParseError = PackageManager.INSTALL_PARSE_FAILED_NO_CERTIFICATES;
                    return false;
                } else if (certs == null) {
                    certs = localCerts;
                } else {
                    // Ensure all certificates match.
                    for (int i = 0; i < certs.length; i++) {
                        boolean found = false;
                        for (int j = 0; j < localCerts.length; j++) {
                            if (certs[i] != null && certs[i].equals(localCerts[j])) {
                                found = true;
                                break;
                            }
                        }
                        if (!found || certs.length != localCerts.length) {
                            Slog.e(TAG, "Package " + pkg.packageName + " has mismatched certificates at entry " + je.getName() + "; ignoring!");
                            jarFile.close();
                            mParseError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
                            return false;
                        }
                    }
                }
            }
        }
        jarFile.close();
        synchronized (mSync) {
            mReadBuffer = readBufferRef;
        }
        if (certs != null && certs.length > 0) {
            final int N = certs.length;
            pkg.mSignatures = new Signature[certs.length];
            for (int i = 0; i < N; i++) {
                pkg.mSignatures[i] = new Signature(certs[i].getEncoded());
            }
        } else {
            Slog.e(TAG, "Package " + pkg.packageName + " has no certificates; ignoring!");
            mParseError = PackageManager.INSTALL_PARSE_FAILED_NO_CERTIFICATES;
            return false;
        }
    } catch (CertificateEncodingException e) {
        Slog.w(TAG, "Exception reading " + mArchiveSourcePath, e);
        mParseError = PackageManager.INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING;
        return false;
    } catch (IOException e) {
        Slog.w(TAG, "Exception reading " + mArchiveSourcePath, e);
        mParseError = PackageManager.INSTALL_PARSE_FAILED_CERTIFICATE_ENCODING;
        return false;
    } catch (RuntimeException e) {
        Slog.w(TAG, "Exception reading " + mArchiveSourcePath, e);
        mParseError = PackageManager.INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION;
        return false;
    }
    return true;
}
Also used : Attributes(java.util.jar.Attributes) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) JarFile(java.util.jar.JarFile) JarEntry(java.util.jar.JarEntry) Manifest(java.util.jar.Manifest) Certificate(java.security.cert.Certificate)

Example 25 with Attributes

use of java.util.jar.Attributes in project GNS by MobilityFirst.

the class GNSConfig method readBuildVersion.

/**
   * Attempts to look for a MANIFEST file in that contains the Build-Version
   * attribute.
   *
   * @return a build version
   */
public static String readBuildVersion() {
    String result = null;
    Enumeration<URL> resources = null;
    try {
        resources = GNSConfig.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
    } catch (IOException E) {
    // handle
    }
    if (resources != null) {
        while (resources.hasMoreElements()) {
            try {
                Manifest manifest = new Manifest(resources.nextElement().openStream());
                // check that this is your manifest and do what you need or
                // get the next one
                Attributes attr = manifest.getMainAttributes();
                result = attr.getValue("Build-Version");
            } catch (IOException E) {
            // handle
            }
        }
    }
    return result;
}
Also used : Attributes(java.util.jar.Attributes) IOException(java.io.IOException) Manifest(java.util.jar.Manifest) URL(java.net.URL)

Aggregations

Attributes (java.util.jar.Attributes)631 Manifest (java.util.jar.Manifest)358 IOException (java.io.IOException)152 File (java.io.File)143 JarFile (java.util.jar.JarFile)106 URL (java.net.URL)92 Map (java.util.Map)78 InputStream (java.io.InputStream)62 HashMap (java.util.HashMap)62 Jar (aQute.bnd.osgi.Jar)49 Builder (aQute.bnd.osgi.Builder)43 ArrayList (java.util.ArrayList)43 ByteArrayOutputStream (java.io.ByteArrayOutputStream)42 Test (org.junit.Test)41 ZipEntry (java.util.zip.ZipEntry)39 FileOutputStream (java.io.FileOutputStream)37 JarOutputStream (java.util.jar.JarOutputStream)36 ByteArrayInputStream (java.io.ByteArrayInputStream)33 FileInputStream (java.io.FileInputStream)33 JarEntry (java.util.jar.JarEntry)32