use of java.util.jar.Attributes in project android_frameworks_base by crdroidandroid.
the class StrictJarVerifier method initEntry.
/**
* Invoked for each new JAR entry read operation from the input
* stream. This method constructs and returns a new {@link VerifierEntry}
* which contains the certificates used to sign the entry and its hash value
* as specified in the JAR MANIFEST format.
*
* @param name
* the name of an entry in a JAR file which is <b>not</b> in the
* {@code META-INF} directory.
* @return a new instance of {@link VerifierEntry} which can be used by
* callers as an {@link OutputStream}.
*/
VerifierEntry initEntry(String name) {
// been found, do not verify.
if (manifest == null || signatures.isEmpty()) {
return null;
}
Attributes attributes = manifest.getAttributes(name);
// entry has no digest
if (attributes == null) {
return null;
}
ArrayList<Certificate[]> certChains = new ArrayList<Certificate[]>();
Iterator<Map.Entry<String, HashMap<String, Attributes>>> it = signatures.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, HashMap<String, Attributes>> entry = it.next();
HashMap<String, Attributes> hm = entry.getValue();
if (hm.get(name) != null) {
// Found an entry for entry name in .SF file
String signatureFile = entry.getKey();
List<Certificate[]> certChain = certificates.get(signatureFile);
if (certChain != null) {
certChains.addAll(certChain);
}
}
}
// entry is not signed
if (certChains.isEmpty()) {
return null;
}
Certificate[][] certChainsArray = certChains.toArray(new Certificate[certChains.size()][]);
for (int i = 0; i < DIGEST_ALGORITHMS.length; i++) {
final String algorithm = DIGEST_ALGORITHMS[i];
final String hash = attributes.getValue(algorithm + "-Digest");
if (hash == null) {
continue;
}
byte[] hashBytes = hash.getBytes(StandardCharsets.ISO_8859_1);
try {
return new VerifierEntry(name, MessageDigest.getInstance(algorithm), hashBytes, certChainsArray, verifiedEntries);
} catch (NoSuchAlgorithmException ignored) {
}
}
return null;
}
use of java.util.jar.Attributes in project bnd by bndtools.
the class JustAnotherPackageManager method verify.
public String verify(JarFile jar, String... algorithms) throws IOException {
if (algorithms == null || algorithms.length == 0)
algorithms = new String[] { "MD5", "SHA" };
else if (algorithms.length == 1 && algorithms[0].equals("-"))
return null;
try {
Manifest m = jar.getManifest();
if (m.getEntries().isEmpty())
return "No name sections";
for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements(); ) {
JarEntry je = e.nextElement();
if (MANIFEST_ENTRY.matcher(je.getName()).matches())
continue;
Attributes nameSection = m.getAttributes(je.getName());
if (nameSection == null)
return "No name section for " + je.getName();
for (String algorithm : algorithms) {
try {
MessageDigest md = MessageDigest.getInstance(algorithm);
String expected = nameSection.getValue(algorithm + "-Digest");
if (expected != null) {
byte[] digest = Base64.decodeBase64(expected);
copy(jar.getInputStream(je), md);
if (!Arrays.equals(digest, md.digest()))
return "Invalid digest for " + je.getName() + ", " + expected + " != " + Base64.encodeBase64(md.digest());
} else
reporter.error("could not find digest for %s-Digest", algorithm);
} catch (NoSuchAlgorithmException nsae) {
return "Missing digest algorithm " + algorithm;
}
}
}
} catch (Exception e) {
return "Failed to verify due to exception: " + e;
}
return null;
}
use of java.util.jar.Attributes in project bnd by bndtools.
the class JustAnotherPackageManager method parseCommandData.
public CommandData parseCommandData(ArtifactData artifact) throws Exception {
File source = new File(artifact.file);
if (!source.isFile())
throw new FileNotFoundException();
CommandData data = new CommandData();
data.sha = artifact.sha;
data.jpmRepoDir = repoDir.getCanonicalPath();
try (JarFile jar = new JarFile(source)) {
logger.debug("Parsing {}", source);
Manifest m = jar.getManifest();
Attributes main = m.getMainAttributes();
data.name = data.bsn = main.getValue(Constants.BUNDLE_SYMBOLICNAME);
String version = main.getValue(Constants.BUNDLE_VERSION);
if (version == null)
data.version = Version.LOWEST;
else
data.version = new Version(version);
data.main = main.getValue("Main-Class");
data.description = main.getValue(Constants.BUNDLE_DESCRIPTION);
data.title = main.getValue("JPM-Name");
if (main.getValue("Class-Path") != null) {
File parent = source.getParentFile();
for (String entry : main.getValue("Class-Path").split("\\s+")) {
File child = new File(parent, entry);
if (!child.isFile()) {
reporter.error("Target specifies Class-Path in JAR but the indicated file %s is not found", child);
} else {
ArtifactData x = put(child.toURI());
data.dependencies.add(x.sha);
}
}
}
logger.debug("name {} {} {}", data.name, data.main, data.title);
DependencyCollector path = new DependencyCollector(this);
path.add(artifact);
DependencyCollector bundles = new DependencyCollector(this);
if (main.getValue("JPM-Classpath") != null) {
Parameters requires = OSGiHeader.parseHeader(main.getValue("JPM-Classpath"));
for (Map.Entry<String, Attrs> e : requires.entrySet()) {
// coordinate
path.add(e.getKey(), e.getValue().get("name"));
}
} else if (!artifact.local) {
// No JPM-Classpath, falling back to
// server's revision
// Iterable<RevisionRef> closure =
// library.getClosure(artifact.sha,
// false);
// System.out.println("getting closure " + artifact.url + " " +
// Strings.join("\n",closure));
// if (closure != null) {
// for (RevisionRef ref : closure) {
// path.add(Hex.toHexString(ref.revision));
// }
// }
}
if (main.getValue("JPM-Runbundles") != null) {
Parameters jpmrunbundles = OSGiHeader.parseHeader(main.getValue("JPM-Runbundles"));
for (Map.Entry<String, Attrs> e : jpmrunbundles.entrySet()) {
bundles.add(e.getKey(), e.getValue().get("name"));
}
}
logger.debug("collect digests runpath");
data.dependencies.addAll(path.getDigests());
logger.debug("collect digests bundles");
data.runbundles.addAll(bundles.getDigests());
Parameters command = OSGiHeader.parseHeader(main.getValue("JPM-Command"));
if (command.size() > 1)
reporter.error("Only one command can be specified");
for (Map.Entry<String, Attrs> e : command.entrySet()) {
data.name = e.getKey();
Attrs attrs = e.getValue();
if (attrs.containsKey("jvmargs"))
data.jvmArgs = attrs.get("jvmargs");
if (attrs.containsKey("title"))
data.title = attrs.get("title");
if (data.title != null)
data.title = data.name;
}
return data;
}
}
use of java.util.jar.Attributes in project bnd by bndtools.
the class RemoteCommand method _distro.
public void _distro(DistroOptions opts) throws Exception {
List<String> args = opts._arguments();
String bsn;
String version;
bsn = args.remove(0);
if (!Verifier.isBsn(bsn)) {
error("Not a bundle symbolic name %s", bsn);
}
if (args.isEmpty())
version = "0";
else {
version = args.remove(0);
if (!Version.isVersion(version)) {
error("Invalid version %s", version);
}
}
File output = getFile(opts.output("distro.jar"));
if (output.getParentFile() == null || !output.getParentFile().isDirectory()) {
error("Cannot write to %s because parent not a directory", output);
}
if (output.isFile() && !output.canWrite()) {
error("Cannot write to %s", output);
}
logger.debug("Starting distro {};{}", bsn, version);
List<BundleRevisionDTO> bundleRevisons = agent.getBundleRevisons();
logger.debug("Found {} bundle revisions", bundleRevisons.size());
Parameters packages = new Parameters();
List<Parameters> provided = new ArrayList<>();
for (BundleRevisionDTO brd : bundleRevisons) {
for (CapabilityDTO c : brd.capabilities) {
CapabilityBuilder cb = new CapabilityBuilder(c.namespace);
for (Entry<String, Object> e : c.attributes.entrySet()) {
String key = e.getKey();
Object value = e.getValue();
if (key.equals("version")) {
if (value instanceof Collection || value.getClass().isArray())
value = Converter.cnv(tref, value);
else
value = new Version((String) value);
}
cb.addAttribute(key, value);
}
cb.addDirectives(c.directives);
Attrs attrs = cb.toAttrs();
if (cb.isPackage()) {
attrs.remove(Constants.BUNDLE_SYMBOLIC_NAME_ATTRIBUTE);
attrs.remove(Constants.BUNDLE_VERSION_ATTRIBUTE);
String pname = attrs.remove(PackageNamespace.PACKAGE_NAMESPACE);
if (pname == null) {
warning("Invalid package capability found %s", c);
} else
packages.put(pname, attrs);
logger.debug("P: {};{}", pname, attrs);
} else if (NativeNamespace.NATIVE_NAMESPACE.equals(c.namespace)) {
Attrs newAttrs = new Attrs();
for (Entry<String, String> entry : attrs.entrySet()) {
if (entry.getKey().startsWith(NativeNamespace.NATIVE_NAMESPACE)) {
newAttrs.put(entry.getKey(), entry.getValue());
}
}
Parameters p = new Parameters();
p.put(c.namespace, newAttrs);
provided.add(p);
} else if (!IGNORED_NAMESPACES.contains(c.namespace)) {
logger.debug("C {};{}", c.namespace, attrs);
Parameters p = new Parameters();
p.put(c.namespace, attrs);
provided.add(p);
}
}
}
if (isOk()) {
Manifest m = new Manifest();
Attributes main = m.getMainAttributes();
main.putValue(Constants.BUNDLE_MANIFESTVERSION, "2");
main.putValue(Constants.BUNDLE_SYMBOLICNAME, bsn);
main.putValue(Constants.BUNDLE_VERSION, version);
main.putValue(Constants.EXPORT_PACKAGE, packages.toString());
// Make distro unresolvable
Parameters unresolveable = new Parameters("osgi.unresolvable; filter:='(&(must.not.resolve=*)(!(must.not.resolve=*)))'");
main.putValue(Constants.REQUIRE_CAPABILITY, unresolveable.toString());
provided.add(new Parameters("osgi.unresolvable"));
StringBuilder sb = new StringBuilder();
for (Parameters parameter : provided) {
sb.append(parameter.toString());
sb.append(",");
}
String capabilities = sb.toString().substring(0, sb.length() - 1);
main.putValue(Constants.PROVIDE_CAPABILITY, capabilities);
if (opts.description() != null)
main.putValue(Constants.BUNDLE_DESCRIPTION, opts.description());
if (opts.license() != null)
main.putValue(Constants.BUNDLE_LICENSE, opts.license());
if (opts.copyright() != null)
main.putValue(Constants.BUNDLE_COPYRIGHT, opts.copyright());
if (opts.vendor() != null)
main.putValue(Constants.BUNDLE_VENDOR, opts.vendor());
Jar jar = new Jar("distro");
jar.setManifest(m);
Verifier v = new Verifier(jar);
v.setProperty(Constants.FIXUPMESSAGES, "osgi.* namespace must not be specified with generic capabilities");
v.verify();
v.getErrors();
if (isFailOk() || v.isOk()) {
jar.updateModified(System.currentTimeMillis(), "Writing distro jar");
jar.write(output);
} else
getInfo(v);
}
}
use of java.util.jar.Attributes in project sling by apache.
the class SubsystemBaseTransformer method transform.
public TransformationResult[] transform(RegisteredResource resource) {
// TODO start level of the subsystem
if (resource.getType().equals(InstallableResource.TYPE_FILE)) {
if (resource.getURL().endsWith("." + TYPE_SUBSYSTEM_BASE)) {
logger.info("Found subsystem-base resource {}", resource);
try {
SubsystemData ssd = createSubsystemFile(resource);
TransformationResult tr = new TransformationResult();
Attributes mfAttributes = ssd.manifest.getMainAttributes();
tr.setId(mfAttributes.getValue(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME));
tr.setVersion(new Version(mfAttributes.getValue(SubsystemConstants.SUBSYSTEM_VERSION)));
tr.setResourceType("esa");
tr.setInputStream(new DeleteOnCloseFileInputStream(ssd.file));
Map<String, Object> attr = new HashMap<String, Object>();
attr.put(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME, mfAttributes.getValue(SubsystemConstants.SUBSYSTEM_SYMBOLICNAME));
attr.put(SubsystemConstants.SUBSYSTEM_VERSION, mfAttributes.getValue(SubsystemConstants.SUBSYSTEM_VERSION));
tr.setAttributes(attr);
return new TransformationResult[] { tr };
} catch (IOException ioe) {
logger.error("Problem processing subsystem-base file " + resource, ioe);
}
}
}
return null;
}
Aggregations