8309841: Jarsigner should print a warning if an entry is removed

Reviewed-by: andrew
Backport-of: bdfb41f977258831e4b0ceaef5d016d095ab6e7f
This commit is contained in:
Roman Marchenko 2025-03-27 17:10:33 +00:00 committed by Andrew John Hughes
parent fd8e509772
commit 55af9ec313
5 changed files with 246 additions and 1 deletions

View File

@ -181,6 +181,7 @@ public class Main {
private boolean hasExpiringCert = false;
private boolean hasExpiringTsaCert = false;
private boolean noTimestamp = true;
private boolean hasNonexistentEntries = false;
// Expiration date. The value could be null if signed by a trusted cert.
private Date expireDate = null;
@ -635,6 +636,7 @@ public class Main {
Map<String,PKCS7> sigMap = new HashMap<>();
Map<String,String> sigNameMap = new HashMap<>();
Map<String,String> unparsableSignatures = new HashMap<>();
Map<String,Set<String>> entriesInSF = new HashMap<>();
try {
jf = new JarFile(jarName, true);
@ -671,6 +673,7 @@ public class Main {
break;
}
}
entriesInSF.put(alias, sf.getEntries().keySet());
if (!found) {
unparsableSignatures.putIfAbsent(alias,
String.format(
@ -769,6 +772,9 @@ public class Main {
sb.append('\n');
}
}
for (Set<String> signed : entriesInSF.values()) {
signed.remove(name);
}
} else if (showcerts && !verbose.equals("all")) {
// Print no info for unsigned entries when -verbose:all,
// to be consistent with old behavior.
@ -951,6 +957,13 @@ public class Main {
if (verbose != null) {
System.out.println(history);
}
Set<String> signed = entriesInSF.get(s);
if (!signed.isEmpty()) {
if (verbose != null) {
System.out.println(rb.getString("history.nonexistent.entries") + signed);
}
hasNonexistentEntries = true;
}
} else {
unparsableSignatures.putIfAbsent(s, String.format(
rb.getString("history.nobk"), s));
@ -1180,6 +1193,7 @@ public class Main {
if (hasExpiringCert ||
(hasExpiringTsaCert && expireDate != null) ||
(noTimestamp && expireDate != null) ||
hasNonexistentEntries ||
(hasExpiredTsaCert && signerNotExpired)) {
if (hasExpiredTsaCert && signerNotExpired) {
@ -1217,6 +1231,9 @@ public class Main {
: "no.timestamp.verifying"), expireDate));
}
}
if (hasNonexistentEntries) {
warnings.add(rb.getString("nonexistent.entries.found"));
}
}
System.out.println(result);

View File

@ -155,6 +155,7 @@ public class Resources extends java.util.ListResourceBundle {
{"history.with.ts", "- Signed by \"%1$s\"\n Digest algorithm: %2$s\n Signature algorithm: %3$s, %4$s\n Timestamped by \"%6$s\" on %5$tc\n Timestamp digest algorithm: %7$s\n Timestamp signature algorithm: %8$s, %9$s"},
{"history.without.ts", "- Signed by \"%1$s\"\n Digest algorithm: %2$s\n Signature algorithm: %3$s, %4$s"},
{"history.nonexistent.entries", " Warning: nonexistent signed entries: "},
{"history.unparsable", "- Unparsable signature-related file %s"},
{"history.nosf", "- Missing signature-related file META-INF/%s.SF"},
{"history.nobk", "- Missing block file for signature-related file META-INF/%s.SF"},
@ -165,6 +166,7 @@ public class Resources extends java.util.ListResourceBundle {
{"key.bit.weak", "%d-bit key (weak)"},
{"key.bit.disabled", "%d-bit key (disabled)"},
{"unknown.size", "unknown size"},
{"nonexistent.entries.found", "This jar contains signed entries for files that do not exist. See the -verbose output for more details."},
{"jarsigner.", "jarsigner: "},
{"signature.filename.must.consist.of.the.following.characters.A.Z.0.9.or.",

View File

@ -0,0 +1,79 @@
/*
* Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 8309841
* @summary Unit Test for a common Test API in jdk.testlibrary.JarUtils
* @library /lib/testlibrary
*/
import jdk.testlibrary.Asserts;
import jdk.testlibrary.JarUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashSet;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
public class JarUtilsTest {
public static void main(String[] args) throws Exception {
Files.createDirectory(Paths.get("bx"));
JarUtils.createJarFile(Paths.get("a.jar"),
Paths.get("."),
Files.write(Paths.get("a"), "".getBytes(StandardCharsets.UTF_8)),
Files.write(Paths.get("b1"), "".getBytes(StandardCharsets.UTF_8)),
Files.write(Paths.get("b2"), "".getBytes(StandardCharsets.UTF_8)),
Files.write(Paths.get("bx/x"), "".getBytes(StandardCharsets.UTF_8)),
Files.write(Paths.get("c"), "".getBytes(StandardCharsets.UTF_8)),
Files.write(Paths.get("e1"), "".getBytes(StandardCharsets.UTF_8)),
Files.write(Paths.get("e2"), "".getBytes(StandardCharsets.UTF_8)));
checkContent("a", "b1", "b2", "bx/x", "c", "e1", "e2");
JarUtils.deleteEntries(Paths.get("a.jar"), "a");
checkContent("b1", "b2", "bx/x", "c", "e1", "e2");
// Note: b* covers everything starting with b, even bx/x
JarUtils.deleteEntries(Paths.get("a.jar"), "b*");
checkContent("c", "e1", "e2");
// d* does not match
JarUtils.deleteEntries(Paths.get("a.jar"), "d*");
checkContent("c", "e1", "e2");
// multiple patterns
JarUtils.deleteEntries(Paths.get("a.jar"), "d*", "e*");
checkContent("c");
}
static void checkContent(String... expected) throws IOException {
try (JarFile jf = new JarFile("a.jar")) {
Asserts.assertEquals(new HashSet<>(Arrays.asList(expected)),
jf.stream().map(JarEntry::getName).collect(Collectors.toSet()));
}
}
}

View File

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2015, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@ -34,6 +34,7 @@ import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
@ -247,6 +248,57 @@ public final class JarUtils {
updateJar(src, dest, map);
}
/**
* Remove entries from a ZIP file.
*
* Each entry can be a name or a name ending with "*".
*
* @return number of removed entries
* @throws IOException if there is any I/O error
*/
public static int deleteEntries(Path jarfile, String... patterns)
throws IOException {
Path tmpfile = Files.createTempFile("jar", "jar");
int count = 0;
try (OutputStream out = Files.newOutputStream(tmpfile);
JarOutputStream jos = new JarOutputStream(out)) {
try (JarFile jf = new JarFile(jarfile.toString())) {
Enumeration<JarEntry> jentries = jf.entries();
top: while (jentries.hasMoreElements()) {
JarEntry jentry = jentries.nextElement();
String name = jentry.getName();
for (String pattern : patterns) {
if (pattern.endsWith("*")) {
if (name.startsWith(pattern.substring(
0, pattern.length() - 1))) {
// Go directly to next entry. This
// one is not written into `jos` and
// therefore removed.
count++;
continue top;
}
} else {
if (name.equals(pattern)) {
// Same as above
count++;
continue top;
}
}
}
// No pattern matched, file retained
jos.putNextEntry(copyEntry(jentry));
Utils.transferTo(jf.getInputStream(jentry), jos);
}
}
}
// replace the original JAR file
Files.move(tmpfile, jarfile, StandardCopyOption.REPLACE_EXISTING);
return count;
}
private static void updateEntry(JarOutputStream jos, String name, Object content)
throws IOException {
if (content instanceof Boolean) {

View File

@ -0,0 +1,95 @@
/*
* Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8309841
* @summary Jarsigner should print a warning if an entry is removed
* @library /lib/testlibrary
*/
import jdk.testlibrary.SecurityTools;
import jdk.testlibrary.JarUtils;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.jar.Attributes;
import java.util.jar.Manifest;
public class RemovedFiles {
private static final String NONEXISTENT_ENTRIES_FOUND
= "This jar contains signed entries for files that do not exist. See the -verbose output for more details.";
public static void main(String[] args) throws Exception {
JarUtils.createJarFile(
Paths.get("a.jar"),
Paths.get("."),
Files.write(Paths.get("a"), "a".getBytes(StandardCharsets.UTF_8)),
Files.write(Paths.get("b"), "b".getBytes(StandardCharsets.UTF_8)));
SecurityTools.keytool("-genkeypair -storepass changeit -keystore ks -alias x -dname CN=x -keyalg RSA");
SecurityTools.jarsigner("-storepass changeit -keystore ks a.jar x");
// All is fine at the beginning.
SecurityTools.jarsigner("-verify a.jar")
.shouldNotContain(NONEXISTENT_ENTRIES_FOUND);
// Remove an entry after signing. There will be a warning.
JarUtils.deleteEntries(Paths.get("a.jar"), "a");
SecurityTools.jarsigner("-verify a.jar")
.shouldContain(NONEXISTENT_ENTRIES_FOUND);
SecurityTools.jarsigner("-verify -verbose a.jar")
.shouldContain(NONEXISTENT_ENTRIES_FOUND)
.shouldContain("Warning: nonexistent signed entries: [a]");
// Remove one more entry.
JarUtils.deleteEntries(Paths.get("a.jar"), "b");
SecurityTools.jarsigner("-verify a.jar")
.shouldContain(NONEXISTENT_ENTRIES_FOUND);
SecurityTools.jarsigner("-verify -verbose a.jar")
.shouldContain(NONEXISTENT_ENTRIES_FOUND)
.shouldContain("Warning: nonexistent signed entries: [a, b]");
// Re-sign will not clear the warning.
SecurityTools.jarsigner("-storepass changeit -keystore ks a.jar x");
SecurityTools.jarsigner("-verify a.jar")
.shouldContain(NONEXISTENT_ENTRIES_FOUND);
// Unfortunately, if there is a non-file entry in manifest, there will be
// a false alarm. See https://bugs.openjdk.org/browse/JDK-8334261.
Manifest man = new Manifest();
man.getMainAttributes().putValue("Manifest-Version", "1.0");
man.getEntries().computeIfAbsent("Hello", key -> new Attributes())
.putValue("Foo", "Bar");
JarUtils.createJarFile(Paths.get("b.jar"),
man,
Paths.get("."),
Paths.get("a"));
SecurityTools.jarsigner("-storepass changeit -keystore ks b.jar x");
SecurityTools.jarsigner("-verbose -verify b.jar")
.shouldContain("Warning: nonexistent signed entries: [Hello]")
.shouldContain(NONEXISTENT_ENTRIES_FOUND);
}
}