From 48f8fb4a58628eb113a0009f45694272111bacac Mon Sep 17 00:00:00 2001 From: zheng1771 <353263628+zheng1771@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:45:42 +0000 Subject: [PATCH] Preserve and verify checksums for ISO uploads --- .../upload/params/IsoUploadParams.java | 6 + .../upload/params/UploadParamsBase.java | 4 + .../cloud/template/TemplateAdapterBase.java | 2 +- .../template/IsoPostUploadChecksumTest.java | 67 +++++++++++ .../resource/NfsSecondaryStorageResource.java | 27 +++-- .../NfsSecondaryStorageResourceTest.java | 106 ++++++++++++++++++ 6 files changed, 204 insertions(+), 8 deletions(-) create mode 100644 server/src/test/java/com/cloud/template/IsoPostUploadChecksumTest.java diff --git a/server/src/main/java/com/cloud/storage/upload/params/IsoUploadParams.java b/server/src/main/java/com/cloud/storage/upload/params/IsoUploadParams.java index 7c2b5799e962..4f579feefb98 100644 --- a/server/src/main/java/com/cloud/storage/upload/params/IsoUploadParams.java +++ b/server/src/main/java/com/cloud/storage/upload/params/IsoUploadParams.java @@ -21,6 +21,12 @@ public class IsoUploadParams extends UploadParamsBase { + public IsoUploadParams(long userId, String name, String displayText, Boolean isPublic, Boolean isFeatured, + Boolean isExtractable, Long osTypeId, Long zoneId, Boolean bootable, long ownerId, String checksum) { + this(userId, name, displayText, isPublic, isFeatured, isExtractable, osTypeId, zoneId, bootable, ownerId); + setChecksum(checksum); + } + public IsoUploadParams(long userId, String name, String displayText, Boolean isPublic, Boolean isFeatured, Boolean isExtractable, Long osTypeId, Long zoneId, Boolean bootable, long ownerId) { super(userId, name, displayText, isPublic, isFeatured, isExtractable, osTypeId, zoneId, bootable, ownerId); diff --git a/server/src/main/java/com/cloud/storage/upload/params/UploadParamsBase.java b/server/src/main/java/com/cloud/storage/upload/params/UploadParamsBase.java index 945551a9318c..71af09ee3dfd 100644 --- a/server/src/main/java/com/cloud/storage/upload/params/UploadParamsBase.java +++ b/server/src/main/java/com/cloud/storage/upload/params/UploadParamsBase.java @@ -179,6 +179,10 @@ public String getChecksum() { return checksum; } + void setChecksum(String checksum) { + this.checksum = checksum; + } + @Override public boolean isBootable() { return bootable; diff --git a/server/src/main/java/com/cloud/template/TemplateAdapterBase.java b/server/src/main/java/com/cloud/template/TemplateAdapterBase.java index 5f04f582a1dd..33b61c80bfaa 100644 --- a/server/src/main/java/com/cloud/template/TemplateAdapterBase.java +++ b/server/src/main/java/com/cloud/template/TemplateAdapterBase.java @@ -529,7 +529,7 @@ public TemplateProfile prepare(GetUploadParamsForIsoCmd cmd) throws ResourceAllo UploadParams params = new IsoUploadParams(CallContext.current().getCallingUserId(), cmd.getName(), cmd.getDisplayText(), BooleanUtils.toBoolean(cmd.isPublic()), BooleanUtils.toBoolean(cmd.isFeatured()), BooleanUtils.toBoolean(cmd.isExtractable()), cmd.getOsTypeId(), - cmd.getZoneId(), BooleanUtils.toBoolean(cmd.isBootable()), cmd.getEntityOwnerId()); + cmd.getZoneId(), BooleanUtils.toBoolean(cmd.isBootable()), cmd.getEntityOwnerId(), cmd.getChecksum()); return prepareUploadParamsInternal(cmd, params); } diff --git a/server/src/test/java/com/cloud/template/IsoPostUploadChecksumTest.java b/server/src/test/java/com/cloud/template/IsoPostUploadChecksumTest.java new file mode 100644 index 000000000000..e8edcb7edabf --- /dev/null +++ b/server/src/test/java/com/cloud/template/IsoPostUploadChecksumTest.java @@ -0,0 +1,67 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +package com.cloud.template; + +import java.util.concurrent.atomic.AtomicReference; + +import com.cloud.storage.TemplateProfile; +import com.cloud.user.Account; +import com.cloud.user.AccountManager; +import com.cloud.user.User; +import org.apache.cloudstack.api.command.user.iso.GetUploadParamsForIsoCmd; +import org.apache.cloudstack.context.CallContext; +import org.apache.cloudstack.storage.datastore.db.ImageStoreDao; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Mockito; + +public class IsoPostUploadChecksumTest { + @Test + public void preparePreservesIsoChecksum() throws Exception { + verifyPreparedChecksum("{SHA-256}" + "a".repeat(64)); + } + + @Test + public void prepareAllowsIsoWithoutChecksum() throws Exception { + verifyPreparedChecksum(null); + } + + private void verifyPreparedChecksum(String expectedChecksum) throws Exception { + AtomicReference preparedChecksum = new AtomicReference<>(); + TemplateProfile profile = Mockito.mock(TemplateProfile.class); + HypervisorTemplateAdapter adapter = Mockito.mock(HypervisorTemplateAdapter.class, invocation -> { + if (invocation.getMethod().getName().equals("prepare") && invocation.getArguments().length == 29) { + preparedChecksum.set(invocation.getArgument(16)); + return profile; + } + return Mockito.CALLS_REAL_METHODS.answer(invocation); + }); + adapter._accountMgr = Mockito.mock(AccountManager.class); + adapter._imgStoreDao = Mockito.mock(ImageStoreDao.class); + ((TemplateAdapterBase) adapter).templateMgr = Mockito.mock(TemplateManager.class); + GetUploadParamsForIsoCmd cmd = Mockito.mock(GetUploadParamsForIsoCmd.class); + Mockito.when(cmd.getChecksum()).thenReturn(expectedChecksum); + CallContext.register(Mockito.mock(User.class), Mockito.mock(Account.class)); + try { + Assert.assertSame(profile, adapter.prepare(cmd)); + Assert.assertEquals(expectedChecksum, preparedChecksum.get()); + } finally { + CallContext.unregister(); + } + } +} diff --git a/services/secondary-storage/server/src/main/java/org/apache/cloudstack/storage/resource/NfsSecondaryStorageResource.java b/services/secondary-storage/server/src/main/java/org/apache/cloudstack/storage/resource/NfsSecondaryStorageResource.java index 740d39aa2263..428f3ca9c9c7 100644 --- a/services/secondary-storage/server/src/main/java/org/apache/cloudstack/storage/resource/NfsSecondaryStorageResource.java +++ b/services/secondary-storage/server/src/main/java/org/apache/cloudstack/storage/resource/NfsSecondaryStorageResource.java @@ -3461,6 +3461,22 @@ private int getSizeInGB(long sizeInBytes) { return (int)Math.ceil(sizeInBytes * 1.0d / (1024 * 1024 * 1024)); } + protected String validatePostUploadChecksum(String checksum, String filename) { + if (StringUtils.isBlank(checksum)) { + return null; + } + try (InputStream input = new FileInputStream(filename)) { + DigestHelper.validateChecksumString(checksum); + if (!DigestHelper.check(checksum, input)) { + return "Uploaded file checksum does not match the provided checksum."; + } + } catch (IOException | NoSuchAlgorithmException | IllegalArgumentException e) { + logger.error("Unable to verify uploaded file checksum", e); + return "Unable to verify uploaded file checksum."; + } + return null; + } + public String postUpload(String uuid, String filename, long processTimeout) { UploadEntity uploadEntity = uploadEntityStateMap.get(uuid); if (uploadEntity == null) { @@ -3494,6 +3510,10 @@ public String postUpload(String uuid, String filename, long processTimeout) { logger.error(errorMessage); return errorMessage; } + String checksumError = validatePostUploadChecksum(uploadEntity.getChksum(), fileSavedTempLocation); + if (checksumError != null) { + return checksumError; + } imgSizeGigs++; // add one just in case long timeout = (long)imgSizeGigs * installTimeoutPerGig; Script scr = new Script(getScriptLocation(resourceType), timeout, logger); @@ -3505,10 +3525,6 @@ public String postUpload(String uuid, String filename, long processTimeout) { if (uploadEntity.isHvm()) { scr.add("-h"); } - String checkSum = uploadEntity.getChksum(); - if (StringUtils.isNotBlank(checkSum)) { - scr.add("-c", checkSum); - } // add options common to ISO and template String extension = uploadEntity.getFormat().getFileExtension(); @@ -3532,9 +3548,6 @@ public String postUpload(String uuid, String filename, long processTimeout) { scr.add("-t", resourcePath); scr.add("-f", fileSavedTempLocation); // this is the temporary // template file downloaded - if (uploadEntity.getChksum() != null && uploadEntity.getChksum().length() > 1) { - scr.add("-c", uploadEntity.getChksum()); - } scr.add("-u"); // cleanup String result; result = scr.execute(); diff --git a/services/secondary-storage/server/src/test/java/org/apache/cloudstack/storage/resource/NfsSecondaryStorageResourceTest.java b/services/secondary-storage/server/src/test/java/org/apache/cloudstack/storage/resource/NfsSecondaryStorageResourceTest.java index 5917e1287639..94ad6a1df864 100644 --- a/services/secondary-storage/server/src/test/java/org/apache/cloudstack/storage/resource/NfsSecondaryStorageResourceTest.java +++ b/services/secondary-storage/server/src/test/java/org/apache/cloudstack/storage/resource/NfsSecondaryStorageResourceTest.java @@ -23,6 +23,7 @@ import static org.mockito.Mockito.times; import java.io.File; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; @@ -38,6 +39,9 @@ import org.apache.logging.log4j.Logger; import org.junit.Assert; import org.junit.Test; +import org.junit.Rule; +import org.junit.rules.TemporaryFolder; +import org.mockito.MockedConstruction; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockedStatic; @@ -50,10 +54,112 @@ import com.cloud.exception.InvalidParameterValueException; import com.cloud.utils.EncryptionUtil; import com.cloud.utils.net.NetUtils; +import com.cloud.storage.Storage; +import com.cloud.storage.StorageLayer; +import com.cloud.storage.template.TemplateLocation; +import com.cloud.utils.script.Script; +import org.apache.cloudstack.storage.template.DownloadManager; +import org.apache.cloudstack.storage.template.UploadEntity; +import org.apache.cloudstack.utils.imagestore.ImageStoreUtil; +import org.apache.commons.codec.digest.DigestUtils; @RunWith(MockitoJUnitRunner.class) public class NfsSecondaryStorageResourceTest { + @Rule + public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + public void postUploadChecksumAcceptsSha256AndLegacyMd5() throws Exception { + byte[] bytes = "uploaded ISO content".getBytes(StandardCharsets.UTF_8); + File file = temporaryFolder.newFile(); + Files.write(file.toPath(), bytes); + + Assert.assertNull(resource.validatePostUploadChecksum("{SHA-256}" + DigestUtils.sha256Hex(bytes), file.getPath())); + Assert.assertNull(resource.validatePostUploadChecksum(DigestUtils.md5Hex(bytes), file.getPath())); + } + + @Test + public void postUploadChecksumRejectsMismatchAndInvalidAlgorithm() throws Exception { + File file = temporaryFolder.newFile(); + Files.writeString(file.toPath(), "uploaded ISO content"); + + Assert.assertNotNull(resource.validatePostUploadChecksum("{SHA-256}" + "0".repeat(64), file.getPath())); + Assert.assertNotNull(resource.validatePostUploadChecksum("{INVALID}abcdef", file.getPath())); + Assert.assertNotNull(resource.validatePostUploadChecksum("{SHA-256}short", file.getPath())); + } + + @Test + public void postUploadChecksumHandlesMissingFileAndOmittedChecksum() { + String missing = new File(temporaryFolder.getRoot(), "missing.iso").getPath(); + + Assert.assertNotNull(resource.validatePostUploadChecksum("{SHA-256}" + "0".repeat(64), missing)); + Assert.assertNull(resource.validatePostUploadChecksum(null, missing)); + Assert.assertNull(resource.validatePostUploadChecksum("", missing)); + } + + @Test + public void postUploadRejectsMismatchBeforeInstallation() throws Exception { + UploadEntity entity = preparePostUpload("{SHA-256}" + "0".repeat(64)); + try (MockedStatic imageStore = Mockito.mockStatic(ImageStoreUtil.class); + MockedConstruction