From b2f9dc5d3bc02564b4d952caa0bf2ccd20dfc6af Mon Sep 17 00:00:00 2001 From: kooper Date: Tue, 2 Apr 2019 09:22:01 +0000 Subject: Verify signature Change-Id: I8fc5d50d74d3dd8031c96ee16708489dc7c789b8 Issue-ID: SDC-2163 Signed-off-by: kooper --- .../sdcrests/vsp/rest/data/PackageArchive.java | 160 +++++++++++++++++++++ .../OrchestrationTemplateCandidateException.java | 27 ++++ .../OrchestrationTemplateCandidateImpl.java | 55 +++++-- 3 files changed, 232 insertions(+), 10 deletions(-) create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/data/PackageArchive.java create mode 100644 openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/OrchestrationTemplateCandidateException.java (limited to 'openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp') diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/data/PackageArchive.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/data/PackageArchive.java new file mode 100644 index 0000000000..bf029fb29e --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/data/PackageArchive.java @@ -0,0 +1,160 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019, Nordix Foundation. All rights reserved. + * ================================================================================ + * Licensed 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. + * ============LICENSE_END========================================================= + */ +package org.openecomp.sdcrests.vsp.rest.data; + +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.openecomp.core.utilities.file.FileContentHandler; +import org.openecomp.sdc.common.utils.CommonUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.vendorsoftwareproduct.security.SecurityManager; +import org.openecomp.sdc.vendorsoftwareproduct.security.SecurityManagerException; + +import java.io.IOException; +import java.security.cert.CertificateException; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +/** + * Class responsible for processing zip archive and verify if this package corresponds + * SOL004 option 2 signed package format, verifies the cms signature if package is signed + */ +public class PackageArchive { + private static final Logger LOG = LoggerFactory.getLogger(PackageArchive.class); + private static final String[] ALLOWED_ARCHIVE_EXTENSIONS = {"csar", "zip"}; + private static final String[] ALLOWED_SIGNATURE_EXTENSIONS = {"cms"}; + private static final String[] ALLOWED_CERTIFICATE_EXTENSIONS = {"cert"}; + private static final int NUMBER_OF_FILES_FOR_SIGNATURE_WITH_CERT_INSIDE = 2; + private static final int NUMBER_OF_FILES_FOR_SIGNATURE_WITHOUT_CERT_INSIDE = 3; + private final SecurityManager securityManager; + private final byte[] outerPackageFileBytes; + private Pair> handlerPair; + + public PackageArchive(Attachment uploadedFile) { + this(uploadedFile.getObject(byte[].class)); + } + + public PackageArchive(byte[] outerPackageFileBytes) { + this.outerPackageFileBytes = outerPackageFileBytes; + this.securityManager = SecurityManager.getInstance(); + try { + handlerPair = CommonUtil.getFileContentMapFromOrchestrationCandidateZip( + outerPackageFileBytes); + } catch (IOException exception) { + LOG.error("Error reading files inside archive", exception); + } + } + + /** + * Checks if package matches required format {package.csar/zip, package.cms, package.cert(optional)} + * + * @return true if structure matches sol004 option 2 structure + */ + public boolean isSigned() { + return isPackageSizeMatches() && getSignatureFileName().isPresent(); + } + + /** + * Gets csar/zip package name with extension only if package is signed + * + * @return csar package name + */ + public Optional getArchiveFileName() { + if (isSigned()) { + return getFileByExtension(ALLOWED_ARCHIVE_EXTENSIONS); + } + return Optional.empty(); + } + + /** + * Gets csar/zip package content from zip archive + * @return csar package content + * @throws SecurityManagerException + */ + public byte[] getPackageFileContents() throws SecurityManagerException { + try { + if (isSignatureValid()) { + return handlerPair.getKey().getFiles().get(getArchiveFileName().orElseThrow(CertificateException::new)); + } + } catch (CertificateException exception) { + LOG.info("Error verifying signature " + exception); + } + return outerPackageFileBytes; + } + + /** + * Validates package signature against trusted certificates + * @return true if signature verified + * @throws SecurityManagerException + */ + public boolean isSignatureValid() throws SecurityManagerException { + Map files = handlerPair.getLeft().getFiles(); + Optional signatureFileName = getSignatureFileName(); + Optional archiveFileName = getArchiveFileName(); + if (files.isEmpty() || !signatureFileName.isPresent() || !archiveFileName.isPresent()) { + return false; + } + Optional certificateFile = getCertificateFileName(); + if(certificateFile.isPresent()){ + return securityManager.verifySignedData(files.get(signatureFileName.get()), + files.get(certificateFile.get()), files.get(archiveFileName.get())); + }else { + return securityManager.verifySignedData(files.get(signatureFileName.get()), + null, files.get(archiveFileName.get())); + } + } + + private boolean isPackageSizeMatches() { + return handlerPair.getRight().isEmpty() + && (handlerPair.getLeft().getFiles().size() == NUMBER_OF_FILES_FOR_SIGNATURE_WITH_CERT_INSIDE + || handlerPair.getLeft().getFiles().size() == NUMBER_OF_FILES_FOR_SIGNATURE_WITHOUT_CERT_INSIDE); + } + + private Optional getSignatureFileName() { + return getFileByExtension(ALLOWED_SIGNATURE_EXTENSIONS); + } + + private Optional getFileByExtension(String[] extensions) { + for (String fileName : handlerPair.getLeft().getFileList()) { + for (String extension : extensions) { + if (extension.equalsIgnoreCase(FilenameUtils.getExtension(fileName))) { + return Optional.of(fileName); + } + } + } + return Optional.empty(); + } + + private Optional getCertificateFileName() { + Optional certFileName = getFileByExtension(ALLOWED_CERTIFICATE_EXTENSIONS); + if(!certFileName.isPresent()){ + return Optional.empty(); + } + String certNameWithoutExtension = FilenameUtils.removeExtension(certFileName.get()); + if (certNameWithoutExtension.equals(FilenameUtils.removeExtension(getArchiveFileName().orElse("")))) { + return certFileName; + } + //cert file name should be the same as package name, e.g. vnfpackage.scar-->vnfpackage.cert + return Optional.empty(); + } +} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/OrchestrationTemplateCandidateException.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/OrchestrationTemplateCandidateException.java new file mode 100644 index 0000000000..a7e65a7e6f --- /dev/null +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/OrchestrationTemplateCandidateException.java @@ -0,0 +1,27 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2019, Nordix Foundation. All rights reserved. + * ================================================================================ + * Licensed 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. + * ============LICENSE_END========================================================= + */ +package org.openecomp.sdcrests.vsp.rest.services; + +public class OrchestrationTemplateCandidateException extends Exception{ + + public OrchestrationTemplateCandidateException(String message, Throwable t){ + super(message, t); + } +} diff --git a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/OrchestrationTemplateCandidateImpl.java b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/OrchestrationTemplateCandidateImpl.java index bdc422d580..4978b3fb34 100644 --- a/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/OrchestrationTemplateCandidateImpl.java +++ b/openecomp-be/api/openecomp-sdc-rest-webapp/vendor-software-products-rest/vendor-software-products-rest-services/src/main/java/org/openecomp/sdcrests/vsp/rest/services/OrchestrationTemplateCandidateImpl.java @@ -25,6 +25,7 @@ import org.openecomp.sdc.activitylog.ActivityLogManagerFactory; import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity; import org.openecomp.sdc.activitylog.dao.type.ActivityType; import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.logging.api.Logger; @@ -33,6 +34,7 @@ import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateMan import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory; import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager; import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory; +import org.openecomp.sdc.vendorsoftwareproduct.security.SecurityManagerException; import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse; import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse; @@ -43,6 +45,7 @@ import org.openecomp.sdcrests.vendorsoftwareproducts.types.OrchestrationTemplate import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto; import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto; import org.openecomp.sdcrests.vsp.rest.OrchestrationTemplateCandidate; +import org.openecomp.sdcrests.vsp.rest.data.PackageArchive; import org.openecomp.sdcrests.vsp.rest.mapping.MapFilesDataStructureToDto; import org.openecomp.sdcrests.vsp.rest.mapping.MapUploadFileResponseToUploadFileResponseDto; import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto; @@ -51,9 +54,13 @@ import org.springframework.stereotype.Service; import javax.inject.Named; import javax.ws.rs.core.Response; +import java.io.ByteArrayInputStream; import java.io.IOException; -import java.io.InputStream; import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.Optional; import static org.openecomp.core.utilities.file.FileUtils.getFileExtension; @@ -75,18 +82,46 @@ public class OrchestrationTemplateCandidateImpl implements OrchestrationTemplate @Override public Response upload(String vspId, String versionId, Attachment fileToUpload, String user) { + PackageArchive archive = new PackageArchive(fileToUpload.getObject(byte[].class)); + UploadFileResponseDto uploadFileResponseDto; + try { + if (archive.isSigned() && !archive.isSignatureValid()) { + ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR, + getErrorWithParameters(Messages.FAILED_TO_VERIFY_SIGNATURE.getErrorMessage(), "")); + LOGGER.error(errorMessage.getMessage()); + uploadFileResponseDto = buildUploadResponseWithError(errorMessage); + //returning OK as SDC UI won't show error message if NOT OK error code. + return Response.ok(uploadFileResponseDto).build(); + } - String filename = fileToUpload.getContentDisposition().getParameter("filename"); - UploadFileResponse uploadFileResponse = candidateManager - .upload(vspId, new Version(versionId), fileToUpload.getObject(InputStream.class), - getFileExtension(filename), getNetworkPackageName(filename)); - - UploadFileResponseDto uploadFileResponseDto = new MapUploadFileResponseToUploadFileResponseDto() - .applyMapping(uploadFileResponse, UploadFileResponseDto.class); - + String filename = archive.getArchiveFileName().orElse(fileToUpload.getContentDisposition().getFilename()); + UploadFileResponse uploadFileResponse = candidateManager + .upload(vspId, new Version(versionId), new ByteArrayInputStream(archive.getPackageFileContents()), + getFileExtension(filename), getNetworkPackageName(filename)); + + uploadFileResponseDto = new MapUploadFileResponseToUploadFileResponseDto() + .applyMapping(uploadFileResponse, UploadFileResponseDto.class); + } catch (SecurityManagerException e) { + ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR, + getErrorWithParameters(e.getMessage(), "")); + LOGGER.error(errorMessage.getMessage(), e); + uploadFileResponseDto = buildUploadResponseWithError(errorMessage); + //returning OK as SDC UI won't show error message if NOT OK error code. + return Response.ok(uploadFileResponseDto).build(); + } return Response.ok(uploadFileResponseDto).build(); } + private UploadFileResponseDto buildUploadResponseWithError(ErrorMessage errorMessage) { + UploadFileResponseDto uploadFileResponseDto = new UploadFileResponseDto(); + Map> errorMap = new HashMap<>(); + List errorMessages = new ArrayList<>(); + errorMessages.add(errorMessage); + errorMap.put(SdcCommon.UPLOAD_FILE, errorMessages); + uploadFileResponseDto.setErrors(errorMap); + return uploadFileResponseDto; + } + @Override public Response get(String vspId, String versionId, String user) throws IOException { Optional> zipFile = candidateManager.get(vspId, new Version(versionId)); @@ -146,7 +181,7 @@ public class OrchestrationTemplateCandidateImpl implements OrchestrationTemplate String errorWithParameters = ErrorMessagesFormatBuilder .getErrorWithParameters(Messages.MAPPING_OBJECTS_FAILURE.getErrorMessage(), fileDataStructureDto.toString(), fileDataStructure.toString()); - throw new Exception(errorWithParameters, exception); + throw new OrchestrationTemplateCandidateException(errorWithParameters, exception); } ValidationResponse response = candidateManager .updateFilesDataStructure(vspId, new Version(versionId), fileDataStructure); -- cgit 1.2.3-korg