This commit is contained in:
Jesper Wilhelmsson 2021-07-22 00:46:18 +00:00
commit c36755dedf
33 changed files with 483 additions and 114 deletions

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2010, 2019, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2010, 2021, 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
@ -151,7 +151,7 @@ class NTLM {
int readShort(int offset) throws NTLMException {
try {
return (internal[offset] & 0xff) +
((internal[offset+1] & 0xff << 8));
(((internal[offset+1] & 0xff) << 8));
} catch (ArrayIndexOutOfBoundsException ex) {
throw new NTLMException(NTLMException.PACKET_READ_ERROR,
"Input message incorrect size");

View file

@ -430,7 +430,10 @@ public final class ZoneRules implements Serializable {
}
/**
* Reads the state from the stream.
* Reads the state from the stream. The 1,024 limit to the lengths
* of stdTrans and savSize is intended to be the size well enough
* to accommodate the max number of transitions in current tzdb data
* (203 for Asia/Tehran).
*
* @param in the input stream, not null
* @return the created object, not null
@ -438,6 +441,9 @@ public final class ZoneRules implements Serializable {
*/
static ZoneRules readExternal(DataInput in) throws IOException, ClassNotFoundException {
int stdSize = in.readInt();
if (stdSize > 1024) {
throw new InvalidObjectException("Too many transitions");
}
long[] stdTrans = (stdSize == 0) ? EMPTY_LONG_ARRAY
: new long[stdSize];
for (int i = 0; i < stdSize; i++) {
@ -448,6 +454,9 @@ public final class ZoneRules implements Serializable {
stdOffsets[i] = Ser.readOffset(in);
}
int savSize = in.readInt();
if (savSize > 1024) {
throw new InvalidObjectException("Too many saving offsets");
}
long[] savTrans = (savSize == 0) ? EMPTY_LONG_ARRAY
: new long[savSize];
for (int i = 0; i < savSize; i++) {
@ -458,6 +467,9 @@ public final class ZoneRules implements Serializable {
savOffsets[i] = Ser.readOffset(in);
}
int ruleSize = in.readByte();
if (ruleSize > 16) {
throw new InvalidObjectException("Too many transition rules");
}
ZoneOffsetTransitionRule[] rules = (ruleSize == 0) ?
EMPTY_LASTRULES : new ZoneOffsetTransitionRule[ruleSize];
for (int i = 0; i < ruleSize; i++) {

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2021, 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
@ -419,7 +419,13 @@ public class JarFile extends ZipFile {
if (verify) {
byte[] b = getBytes(manEntry);
if (!jvInitialized) {
jv = new JarVerifier(b);
if (JUZFA.getManifestNum(this) == 1) {
jv = new JarVerifier(manEntry.getName(), b);
} else {
if (JarVerifier.debug != null) {
JarVerifier.debug.println("Multiple MANIFEST.MF found. Treat JAR file as unsigned");
}
}
}
man = new Manifest(jv, new ByteArrayInputStream(b), getName());
} else {
@ -745,7 +751,7 @@ public class JarFile extends ZipFile {
mev = new ManifestEntryVerifier
(getManifestFromReference());
}
if (name.equals(MANIFEST_NAME)) {
if (name.equalsIgnoreCase(MANIFEST_NAME)) {
b = jv.manifestRawBytes;
} else {
b = getBytes(e);

View file

@ -94,7 +94,7 @@ public class JarInputStream extends ZipInputStream {
man.read(new ByteArrayInputStream(bytes));
closeEntry();
if (doVerify) {
jv = new JarVerifier(bytes);
jv = new JarVerifier(e.getName(), bytes);
mev = new ManifestEntryVerifier(man);
}
return (JarEntry)super.getNextEntry();

View file

@ -84,6 +84,9 @@ class JarVerifier {
/** the bytes for the manDig object */
byte manifestRawBytes[] = null;
/** the manifest name this JarVerifier is created upon */
final String manifestName;
/** controls eager signature validation */
boolean eagerValidation;
@ -93,7 +96,8 @@ class JarVerifier {
/** collect -DIGEST-MANIFEST values for deny list */
private List<Object> manifestDigests;
public JarVerifier(byte rawBytes[]) {
public JarVerifier(String name, byte rawBytes[]) {
manifestName = name;
manifestRawBytes = rawBytes;
sigFileSigners = new Hashtable<>();
verifiedSigners = new Hashtable<>();
@ -180,7 +184,7 @@ class JarVerifier {
// only set the jev object for entries that have a signature
// (either verified or not)
if (!name.equals(JarFile.MANIFEST_NAME)) {
if (!name.equalsIgnoreCase(JarFile.MANIFEST_NAME)) {
if (sigFileSigners.get(name) != null ||
verifiedSigners.get(name) != null) {
mev.setEntry(name, je);
@ -270,7 +274,8 @@ class JarVerifier {
}
sfv.setSignatureFile(bytes);
sfv.process(sigFileSigners, manifestDigests);
sfv.process(sigFileSigners, manifestDigests,
manifestName);
}
}
return;
@ -313,7 +318,7 @@ class JarVerifier {
sfv.setSignatureFile(bytes);
}
}
sfv.process(sigFileSigners, manifestDigests);
sfv.process(sigFileSigners, manifestDigests, manifestName);
} catch (IOException | CertificateException |
NoSuchAlgorithmException | SignatureException e) {
@ -419,9 +424,9 @@ class JarVerifier {
manDig = null;
// MANIFEST.MF is always treated as signed and verified,
// move its signers from sigFileSigners to verifiedSigners.
if (sigFileSigners.containsKey(JarFile.MANIFEST_NAME)) {
CodeSigner[] codeSigners = sigFileSigners.remove(JarFile.MANIFEST_NAME);
verifiedSigners.put(JarFile.MANIFEST_NAME, codeSigners);
if (sigFileSigners.containsKey(manifestName)) {
CodeSigner[] codeSigners = sigFileSigners.remove(manifestName);
verifiedSigners.put(manifestName, codeSigners);
}
}
@ -873,7 +878,7 @@ class JarVerifier {
*/
boolean isTrustedManifestEntry(String name) {
// How many signers? MANIFEST.MF is always verified
CodeSigner[] forMan = verifiedSigners.get(JarFile.MANIFEST_NAME);
CodeSigner[] forMan = verifiedSigners.get(manifestName);
if (forMan == null) {
return true;
}

View file

@ -226,6 +226,7 @@ public class ZipFile implements ZipConstants, Closeable {
Integer.toHexString(mode));
}
String name = file.getPath();
file = new File(name);
@SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
@ -1032,6 +1033,18 @@ public class ZipFile implements ZipConstants, Closeable {
}
}
/**
* Returns the number of the META-INF/MANIFEST.MF entries, case insensitive.
* When this number is greater than 1, JarVerifier will treat a file as
* unsigned.
*/
private int getManifestNum() {
synchronized (this) {
ensureOpen();
return res.zsrc.manifestNum;
}
}
/**
* Returns the name of the META-INF/MANIFEST.MF entry, ignoring
* case. If {@code onlyIfSignatureRelatedFiles} is true, we only return the
@ -1079,6 +1092,10 @@ public class ZipFile implements ZipConstants, Closeable {
return ((ZipFile)jar).getManifestAndSignatureRelatedFiles();
}
@Override
public int getManifestNum(JarFile jar) {
return ((ZipFile)jar).getManifestNum();
}
@Override
public String getManifestName(JarFile jar, boolean onlyIfHasSignatureRelatedFiles) {
return ((ZipFile)jar).getManifestName(onlyIfHasSignatureRelatedFiles);
}
@ -1131,6 +1148,7 @@ public class ZipFile implements ZipConstants, Closeable {
private byte[] comment; // zip file comment
// list of meta entries in META-INF dir
private int manifestPos = -1; // position of the META-INF/MANIFEST.MF, if exists
private int manifestNum = 0; // number of META-INF/MANIFEST.MF, case insensitive
private int[] signatureMetaNames; // positions of signature related entries, if such exist
private int[] metaVersions; // list of unique versions found in META-INF/versions/
private final boolean startsWithLoc; // true, if zip file starts with LOCSIG (usually true)
@ -1313,6 +1331,7 @@ public class ZipFile implements ZipConstants, Closeable {
entries = null;
table = null;
manifestPos = -1;
manifestNum = 0;
signatureMetaNames = null;
metaVersions = EMPTY_META_VERSIONS;
}
@ -1504,6 +1523,7 @@ public class ZipFile implements ZipConstants, Closeable {
int pos = 0;
int entryPos = CENHDR;
int limit = cen.length - ENDHDR;
manifestNum = 0;
while (entryPos <= limit) {
if (idx >= entriesLength) {
// This will only happen if the zip file has an incorrect
@ -1522,6 +1542,7 @@ public class ZipFile implements ZipConstants, Closeable {
// nlen is at least META_INF_LENGTH
if (isManifestName(entryPos + META_INF_LEN, nlen - META_INF_LEN)) {
manifestPos = pos;
manifestNum++;
} else {
if (isSignatureRelated(entryPos, nlen)) {
if (signatureNames == null)

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2013, 2021, 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
@ -37,6 +37,7 @@ public interface JavaUtilZipFileAccess {
public boolean startsWithLocHeader(ZipFile zip);
public List<String> getManifestAndSignatureRelatedFiles(JarFile zip);
public String getManifestName(JarFile zip, boolean onlyIfSignatureRelatedFiles);
public int getManifestNum(JarFile zip);
public int[] getMetaInfVersions(JarFile zip);
public Enumeration<JarEntry> entries(ZipFile zip);
public Stream<JarEntry> stream(ZipFile zip);

View file

@ -538,6 +538,9 @@ public class ClassReader {
} else if (Constants.SYNTHETIC.equals(attributeName)) {
accessFlags |= Opcodes.ACC_SYNTHETIC;
} else if (Constants.SOURCE_DEBUG_EXTENSION.equals(attributeName)) {
if (attributeLength > classFileBuffer.length - currentAttributeOffset) {
throw new IllegalArgumentException();
}
sourceDebugExtension =
readUtf(currentAttributeOffset, attributeLength, new char[attributeLength]);
} else if (Constants.RUNTIME_INVISIBLE_ANNOTATIONS.equals(attributeName)) {
@ -1548,6 +1551,9 @@ public class ClassReader {
final int maxLocals = readUnsignedShort(currentOffset + 2);
final int codeLength = readInt(currentOffset + 4);
currentOffset += 8;
if (codeLength > classFileBuffer.length - currentOffset) {
throw new IllegalArgumentException();
}
// Read the bytecode 'code' array to create a label for each referenced instruction.
final int bytecodeStartOffset = currentOffset;

View file

@ -24,16 +24,36 @@
*/
package sun.net.ftp.impl;
import java.net.*;
import java.io.*;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.text.DateFormat;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
@ -44,7 +64,11 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import sun.net.ftp.*;
import sun.net.ftp.FtpDirEntry;
import sun.net.ftp.FtpDirParser;
import sun.net.ftp.FtpProtocolException;
import sun.net.ftp.FtpReplyCode;
import sun.net.util.IPAddressUtil;
import sun.util.logging.PlatformLogger;
@ -107,13 +131,15 @@ public class FtpClient extends sun.net.ftp.FtpClient {
private static Pattern[] patterns;
private static Pattern linkp = Pattern.compile("(\\p{Print}+) \\-\\> (\\p{Print}+)$");
private DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, java.util.Locale.US);
private static final boolean acceptPasvAddressVal;
static {
final int vals[] = {0, 0};
final String acceptPasvAddress[] = {null};
@SuppressWarnings("removal")
final String enc = AccessController.doPrivileged(
new PrivilegedAction<String>() {
public String run() {
acceptPasvAddress[0] = System.getProperty("jdk.net.ftp.trustPasvAddress", "false");
vals[0] = Integer.getInteger("sun.net.client.defaultReadTimeout", 300_000).intValue();
vals[1] = Integer.getInteger("sun.net.client.defaultConnectTimeout", 300_000).intValue();
return System.getProperty("file.encoding", "ISO8859_1");
@ -144,6 +170,8 @@ public class FtpClient extends sun.net.ftp.FtpClient {
for (int i = 0; i < patStrings.length; i++) {
patterns[i] = Pattern.compile(patStrings[i]);
}
acceptPasvAddressVal = Boolean.parseBoolean(acceptPasvAddress[0]);
}
/**
@ -610,7 +638,6 @@ public class FtpClient extends sun.net.ftp.FtpClient {
//
// The regular expression is a bit more complex this time, because
// the parenthesis are optionals and we have to use 3 groups.
if (pasvPat == null) {
pasvPat = Pattern.compile("227 .* \\(?(\\d{1,3},\\d{1,3},\\d{1,3},\\d{1,3}),(\\d{1,3}),(\\d{1,3})\\)?");
}
@ -622,8 +649,15 @@ public class FtpClient extends sun.net.ftp.FtpClient {
port = Integer.parseInt(m.group(3)) + (Integer.parseInt(m.group(2)) << 8);
// IP address is simple
String s = m.group(1).replace(',', '.');
dest = new InetSocketAddress(s, port);
if (!IPAddressUtil.isIPv4LiteralAddress(s))
throw new FtpProtocolException("PASV failed : " + serverAnswer);
if (acceptPasvAddressVal) {
dest = new InetSocketAddress(s, port);
} else {
dest = validatePasvAddress(port, s, server.getInetAddress());
}
}
// Got everything, let's open the socket!
Socket s;
if (proxy != null) {
@ -678,6 +712,80 @@ public class FtpClient extends sun.net.ftp.FtpClient {
return s;
}
static final String ERROR_MSG = "Address should be the same as originating server";
/**
* Returns an InetSocketAddress, based on value of acceptPasvAddressVal
* and other conditions such as the server address returned by pasv
* is not a hostname, is a socks proxy, or the loopback. An exception
* is thrown if none of the valid conditions are met.
*/
private InetSocketAddress validatePasvAddress(int port, String s, InetAddress address)
throws FtpProtocolException
{
if (address == null) {
return InetSocketAddress.createUnresolved(serverAddr.getHostName(), port);
}
String serverAddress = address.getHostAddress();
if (serverAddress.equals(s)) {
return new InetSocketAddress(s, port);
} else if (address.isLoopbackAddress() && s.startsWith("127.")) { // can be 127.0
return new InetSocketAddress(s, port);
} else if (address.isLoopbackAddress()) {
if (privilegedLocalHost().getHostAddress().equals(s)) {
return new InetSocketAddress(s, port);
} else {
throw new FtpProtocolException(ERROR_MSG);
}
} else if (s.startsWith("127.")) {
if (privilegedLocalHost().equals(address)) {
return new InetSocketAddress(s, port);
} else {
throw new FtpProtocolException(ERROR_MSG);
}
}
String hostName = address.getHostName();
if (!(IPAddressUtil.isIPv4LiteralAddress(hostName) || IPAddressUtil.isIPv6LiteralAddress(hostName))) {
InetAddress[] names = privilegedGetAllByName(hostName);
String resAddress = Arrays
.stream(names)
.map(InetAddress::getHostAddress)
.filter(s::equalsIgnoreCase)
.findFirst()
.orElse(null);
if (resAddress != null) {
return new InetSocketAddress(s, port);
}
}
throw new FtpProtocolException(ERROR_MSG);
}
private static InetAddress privilegedLocalHost() throws FtpProtocolException {
PrivilegedExceptionAction<InetAddress> action = InetAddress::getLocalHost;
try {
@SuppressWarnings("removal")
var tmp = AccessController.doPrivileged(action);
return tmp;
} catch (Exception e) {
var ftpEx = new FtpProtocolException(ERROR_MSG);
ftpEx.initCause(e);
throw ftpEx;
}
}
private static InetAddress[] privilegedGetAllByName(String hostName) throws FtpProtocolException {
PrivilegedExceptionAction<InetAddress[]> pAction = () -> InetAddress.getAllByName(hostName);
try {
@SuppressWarnings("removal")
var tmp =AccessController.doPrivileged(pAction);
return tmp;
} catch (Exception e) {
var ftpEx = new FtpProtocolException(ERROR_MSG);
ftpEx.initCause(e);
throw ftpEx;
}
}
/**
* Opens a data connection with the server according to the set mode
* (ACTIVE or PASSIVE) then send the command passed as an argument.
@ -688,7 +796,6 @@ public class FtpClient extends sun.net.ftp.FtpClient {
*/
private Socket openDataConnection(String cmd) throws sun.net.ftp.FtpProtocolException, IOException {
Socket clientSocket;
if (passiveMode) {
try {
return openPassiveDataConnection(cmd);

View file

@ -331,7 +331,18 @@ public class SignerInfo implements DerEncoder {
throws NoSuchAlgorithmException, SignatureException {
try {
Timestamp timestamp = getTimestamp();
Timestamp timestamp = null;
try {
timestamp = getTimestamp();
} catch (Exception e) {
// Log exception and continue. This allows for the case
// where, if there are no other errors, the code is
// signed but w/o a timestamp.
if (debug != null) {
debug.println("Unexpected exception while getting" +
" timestamp: " + e);
}
}
ContentInfo content = block.getContentInfo();
if (data == null) {
@ -471,7 +482,7 @@ public class SignerInfo implements DerEncoder {
if (sig.verify(encryptedDigest)) {
return this;
}
} catch (IOException | CertificateException e) {
} catch (IOException e) {
throw new SignatureException("Error verifying signature", e);
}
return null;

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1997, 2021, 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
@ -270,7 +270,7 @@ public class SignatureFileVerifier {
*
*/
public void process(Hashtable<String, CodeSigner[]> signers,
List<Object> manifestDigests)
List<Object> manifestDigests, String manifestName)
throws IOException, SignatureException, NoSuchAlgorithmException,
JarException, CertificateException
{
@ -279,7 +279,7 @@ public class SignatureFileVerifier {
Object obj = null;
try {
obj = Providers.startJarVerification();
processImpl(signers, manifestDigests);
processImpl(signers, manifestDigests, manifestName);
} finally {
Providers.stopJarVerification(obj);
}
@ -287,7 +287,7 @@ public class SignatureFileVerifier {
}
private void processImpl(Hashtable<String, CodeSigner[]> signers,
List<Object> manifestDigests)
List<Object> manifestDigests, String manifestName)
throws IOException, SignatureException, NoSuchAlgorithmException,
JarException, CertificateException
{
@ -368,7 +368,7 @@ public class SignatureFileVerifier {
}
// MANIFEST.MF is always regarded as signed
updateSigners(newSigners, signers, JarFile.MANIFEST_NAME);
updateSigners(newSigners, signers, manifestName);
}
/**