Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,10 @@ public String getChecksum() {
return checksum;
}

void setChecksum(String checksum) {
this.checksum = checksum;
}

@Override
public boolean isBootable() {
return bootable;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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<String> 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();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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);
Expand All @@ -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();
Expand All @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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<ImageStoreUtil> imageStore = Mockito.mockStatic(ImageStoreUtil.class);
MockedConstruction<Script> scripts = Mockito.mockConstruction(Script.class);
MockedConstruction<TemplateLocation> locations = Mockito.mockConstruction(TemplateLocation.class)) {
Assert.assertNotNull(resource.postUpload(UUID, "upload.iso", 60));

Assert.assertTrue(scripts.constructed().isEmpty());
Assert.assertTrue(locations.constructed().isEmpty());
Assert.assertEquals(UploadEntity.Status.IN_PROGRESS, entity.getUploadState());
}
}

@Test
public void postUploadInstallsVerifiedFileWithoutChecksumScriptOption() throws Exception {
verifyPostUploadInstallation("{SHA-256}" + DigestUtils.sha256Hex("uploaded ISO content"));
}

@Test
public void postUploadInstallsWithoutOptionalChecksum() throws Exception {
verifyPostUploadInstallation(null);
}

private void verifyPostUploadInstallation(String checksum) throws Exception {
UploadEntity entity = preparePostUpload(checksum);
resource._params = new HashMap<>();
DownloadManager downloadManager = Mockito.mock(DownloadManager.class);
ReflectionTestUtils.setField(resource, "_dlMgr", downloadManager);
try (MockedStatic<ImageStoreUtil> imageStore = Mockito.mockStatic(ImageStoreUtil.class);
MockedConstruction<Script> scripts = Mockito.mockConstruction(Script.class);
MockedConstruction<TemplateLocation> locations = Mockito.mockConstruction(TemplateLocation.class,
(location, context) -> Mockito.when(location.save()).thenReturn(true))) {
Assert.assertNull(resource.postUpload(UUID, "upload.iso", 60));

Script script = scripts.constructed().get(0);
Mockito.verify(script, Mockito.never()).add(Mockito.eq("-c"), Mockito.anyString());
TemplateLocation location = locations.constructed().get(0);
org.mockito.InOrder order = Mockito.inOrder(resource, script, location);
order.verify(resource).validatePostUploadChecksum(checksum, entity.getInstallPathPrefix() + "/upload.iso");
order.verify(script).execute();
order.verify(location).create(entity.getEntityId(), true, entity.getFilename());
order.verify(location).save();
Assert.assertEquals(UploadEntity.Status.COMPLETED, entity.getUploadState());
}
}

@SuppressWarnings("unchecked")
private UploadEntity preparePostUpload(String checksum) throws Exception {
File directory = temporaryFolder.newFolder();
Files.writeString(new File(directory, "upload.iso").toPath(), "uploaded ISO content");
UploadEntity entity = new UploadEntity(UUID, 1L, UploadEntity.Status.IN_PROGRESS, "test.iso", directory.getPath());
entity.setFormat(Storage.ImageFormat.ISO);
entity.setResourceType(UploadEntity.ResourceType.TEMPLATE);
entity.setMaxSizeInGB(1);
entity.setChksum(checksum);
resource._storage = Mockito.mock(StorageLayer.class);
Map<String, UploadEntity> entities = (Map<String, UploadEntity>) ReflectionTestUtils.getField(resource, "uploadEntityStateMap");
entities.put(UUID, entity);
return entity;
}

@Spy
private NfsSecondaryStorageResource resource;

Expand Down