Skip to content

Commit fb0862f

Browse files
authored
fix: validate downloaded node (#20821)
Validate downloaded node against the provided sha256 hash. Fixes #20661
1 parent 07d230e commit fb0862f

5 files changed

Lines changed: 176 additions & 5 deletions

File tree

‎flow-server/src/main/java/com/vaadin/flow/internal/MessageDigestUtil.java‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717

1818
import java.nio.charset.Charset;
1919
import java.nio.charset.StandardCharsets;
20+
import java.nio.file.Files;
2021
import java.security.MessageDigest;
2122
import java.security.NoSuchAlgorithmException;
2223

@@ -75,6 +76,39 @@ public static byte[] sha256(String string, byte[] salt, Charset charset) {
7576
return getSha256(salt).digest(string.getBytes(charset));
7677
}
7778

79+
/**
80+
* Calculates the SHA-256 hash of the given byte array.
81+
*
82+
* @param content
83+
* the byte array to hash
84+
*
85+
* @return sha256 hash string
86+
*/
87+
public static String sha256Hex(byte[] content) {
88+
return sha256Hex(content, null);
89+
}
90+
91+
/**
92+
* Calculates the SHA-256 hash of the given byte array with the given salt.
93+
*
94+
* @param content
95+
* the byte array to hash
96+
* @param salt
97+
* salt to be added to the calculation
98+
* @return sha256 hash string
99+
*/
100+
public static String sha256Hex(byte[] content, byte[] salt) {
101+
byte[] digest = getSha256(salt).digest(content);
102+
final StringBuilder hexString = new StringBuilder();
103+
for (int i = 0; i < digest.length; i++) {
104+
final String hex = Integer.toHexString(0xff & digest[i]);
105+
if (hex.length() == 1)
106+
hexString.append('0');
107+
hexString.append(hex);
108+
}
109+
return hexString.toString();
110+
}
111+
78112
private static MessageDigest getSha256(byte[] salt) {
79113
try {
80114
MessageDigest digest = MessageDigest.getInstance("SHA-256");

‎flow-server/src/main/java/com/vaadin/flow/server/frontend/installer/NodeInstaller.java‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import org.slf4j.Logger;
3535
import org.slf4j.LoggerFactory;
3636

37+
import com.vaadin.flow.internal.MessageDigestUtil;
3738
import com.vaadin.flow.internal.Pair;
3839
import com.vaadin.flow.server.frontend.FrontendUtils;
3940
import com.vaadin.flow.server.frontend.FrontendVersion;
@@ -55,6 +56,8 @@ public class NodeInstaller {
5556

5657
public static final String UNOFFICIAL_NODEJS_DOWNLOAD_ROOT = "https://unofficial-builds.nodejs.org/download/release/";
5758

59+
public static final String SHA_SUMS_FILE = "SHASUMS256.txt";
60+
5861
private static final String NODE_WINDOWS = INSTALL_PATH.replaceAll("/",
5962
"\\\\") + "\\node.exe";
6063
private static final String NODE_DEFAULT = INSTALL_PATH + "/node";
@@ -64,6 +67,7 @@ public class NodeInstaller {
6467
private static final int MAX_DOWNLOAD_ATTEMPS = 5;
6568

6669
private static final int DOWNLOAD_ATTEMPT_DELAY = 5;
70+
public static final String ACCEPT_MISSING_SHA = "vaadin.node.download.acceptMissingSHA";
6771

6872
private final Object lock = new Object();
6973

@@ -524,6 +528,8 @@ private void downloadFileIfMissing(URI downloadUrl, File destination,
524528
try {
525529
fileDownloader.download(downloadUrl, destination, userName,
526530
password, null);
531+
532+
verifyArchive(destination);
527533
return;
528534
} catch (DownloadException e) {
529535
if (i == MAX_DOWNLOAD_ATTEMPS - 1) {
@@ -538,10 +544,85 @@ private void downloadFileIfMissing(URI downloadUrl, File destination,
538544
try {
539545
Thread.sleep(DOWNLOAD_ATTEMPT_DELAY * 1000);
540546
} catch (InterruptedException e1) {
547+
Thread.currentThread().interrupt();
548+
}
549+
} catch (VerificationException ve) {
550+
getLogger().warn(
551+
"SHA256 verification of downloaded node archive failed.");
552+
if (i == MAX_DOWNLOAD_ATTEMPS - 1) {
553+
removeArchiveFile(destination);
554+
throw new DownloadException(
555+
"Failed to download node matching SHA256.");
541556
}
542557
}
558+
}
559+
} else {
560+
try {
561+
verifyArchive(destination);
562+
} catch (VerificationException de) {
563+
removeArchiveFile(destination);
564+
downloadFileIfMissing(downloadUrl, destination, userName,
565+
password);
566+
}
567+
}
568+
}
543569

570+
private void verifyArchive(File archive)
571+
throws DownloadException, VerificationException {
572+
try {
573+
URI shaSumsURL = nodeDownloadRoot
574+
.resolve(nodeVersion + "/" + SHA_SUMS_FILE);
575+
if ("file".equalsIgnoreCase(shaSumsURL.getScheme())) {
576+
// The file is local so it can't be expected to have a SHA file
577+
return;
544578
}
579+
580+
File shaSums = new File(installDirectory, "node-" + SHA_SUMS_FILE);
581+
582+
getLogger().debug("Downloading {} to {}", shaSumsURL, shaSums);
583+
584+
try {
585+
fileDownloader.download(shaSumsURL, shaSums, userName, password,
586+
null);
587+
} catch (DownloadException e) {
588+
if (Boolean.getBoolean(ACCEPT_MISSING_SHA)) {
589+
getLogger().warn(
590+
"Could not verify SHA256 sum of downloaded node in {}. Accepting missing checksum verification as set in '{}' system property.",
591+
archive, ACCEPT_MISSING_SHA);
592+
return;
593+
} else {
594+
getLogger().info(
595+
"Download of {} failed. If failure persists, use system property '{}' to skip verification or download node manually.",
596+
SHA_SUMS_FILE, ACCEPT_MISSING_SHA);
597+
throw e;
598+
}
599+
}
600+
601+
String archiveSHA256 = MessageDigestUtil
602+
.sha256Hex(Files.readAllBytes(archive.toPath()));
603+
604+
List<String> sha256sums = Files.readAllLines(shaSums.toPath());
605+
String archiveTargetSHA256 = sha256sums.stream()
606+
.filter(sum -> sum
607+
.endsWith(archive.getName()))
608+
.map(sum -> sum
609+
.substring(0,
610+
sum.length() - archive.getName().length())
611+
.trim())
612+
.findFirst().orElse("-1");
613+
614+
shaSums.delete();
615+
616+
if (!archiveSHA256.equals(archiveTargetSHA256)) {
617+
getLogger().error(
618+
"Expected SHA256 [{}] for downloaded node archive, got [{}]",
619+
archiveTargetSHA256, archiveSHA256);
620+
throw new VerificationException(
621+
"SHA256 sums did not match for downloaded node");
622+
}
623+
} catch (IOException e) {
624+
throw new VerificationException("Failed to validate archive hash.",
625+
e);
545626
}
546627
}
547628

‎flow-server/src/main/java/com/vaadin/flow/server/frontend/installer/ProxyConfig.java‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,9 @@ public Proxy getProxyForUrl(String requestUrl) {
7070
+ "development-mode/node-js#proxy-settings-for-downloading-"
7171
+ "frontend-toolchain for information on proxy configuration.";
7272
if (proxies.isEmpty()) {
73-
getLogger().info("No proxies configured. "
74-
+ "If you are behind a proxy server, " + docLink);
73+
getLogger().debug(
74+
"No proxies configured. If you are behind a proxy server, {}",
75+
docLink);
7576
return null;
7677
}
7778
final URI uri = URI.create(requestUrl);
@@ -80,9 +81,8 @@ public Proxy getProxyForUrl(String requestUrl) {
8081
return proxy;
8182
}
8283
}
83-
getLogger().info(
84-
"Could not find matching proxy for host: {}" + " - " + docLink,
85-
uri.getHost());
84+
getLogger().info("Could not find matching proxy for host: {} - {}",
85+
uri.getHost(), docLink);
8686
return null;
8787
}
8888

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
* Copyright 2000-2024 Vaadin Ltd.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5+
* use this file except in compliance with the License. You may obtain a copy of
6+
* the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations under
14+
* the License.
15+
*/
16+
package com.vaadin.flow.server.frontend.installer;
17+
18+
/**
19+
* Exception indicating a failure during downloaded archive verification.
20+
* <p>
21+
* For internal use only. May be renamed or removed in a future release.
22+
*
23+
* @since
24+
*/
25+
public final class VerificationException extends Exception {
26+
27+
/**
28+
* Exceptioon with message.
29+
*
30+
* @param message
31+
* exception message
32+
*/
33+
public VerificationException(String message) {
34+
super(message);
35+
}
36+
37+
/**
38+
* Exceptioon with message and cause.
39+
*
40+
* @param message
41+
* exception message
42+
* @param cause
43+
* cause for exception
44+
*/
45+
VerificationException(String message, Throwable cause) {
46+
super(message, cause);
47+
}
48+
}

‎flow-server/src/test/java/com/vaadin/flow/server/frontend/FrontendToolsTest.java‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,9 @@ public void nodeIsBeingLocated_supportedNodeInstalled_autoUpdateTrue_NodeUpdated
182182
@Test
183183
public void nodeIsBeingLocated_unsupportedNodeInstalled_defaultNodeVersionInstalledToAlternativeDirectory()
184184
throws FrontendUtils.UnknownVersionException, IOException {
185+
Assume.assumeFalse(
186+
"Skipping test on windows until a fake node.exe that isn't caught by Window defender can be created.",
187+
FrontendUtils.isWindows());
185188
// Unsupported node version
186189
FrontendStubs.ToolStubInfo nodeStub = FrontendStubs.ToolStubInfo
187190
.builder(FrontendStubs.Tool.NODE).withVersion("8.9.3").build();
@@ -204,6 +207,9 @@ public void nodeIsBeingLocated_unsupportedNodeInstalled_defaultNodeVersionInstal
204207
@Test
205208
public void nodeIsBeingLocated_unsupportedNodeInstalled_fallbackToNodeInstalledToAlternativeDirectory()
206209
throws IOException, FrontendUtils.UnknownVersionException {
210+
Assume.assumeFalse(
211+
"Skipping test on windows until a fake node.exe that isn't caught by Window defender can be created.",
212+
FrontendUtils.isWindows());
207213
// Unsupported node version
208214
FrontendStubs.ToolStubInfo nodeStub = FrontendStubs.ToolStubInfo
209215
.builder(FrontendStubs.Tool.NODE).withVersion("8.9.3").build();
@@ -730,6 +736,8 @@ public void getSuitablePnpm_supportedGlobalVersionInstalled_accepted() {
730736

731737
@Test
732738
public void getSuitablePnpm_useGlobalPnpm_noPnpmInstalled_throws() {
739+
Assume.assumeFalse("Skipping test on windows.",
740+
FrontendUtils.isWindows());
733741
Optional<File> pnpm = frontendToolsLocator.tryLocateTool("pnpm");
734742
Assume.assumeFalse("Skip this test once globally installed pnpm is "
735743
+ "discovered", pnpm.isPresent());

0 commit comments

Comments
 (0)