97bc375eb84b6ee69e92ee2d55854c71895f749e
[sdc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2019, Nordix Foundation. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20 package org.openecomp.sdcrests.vsp.rest.data;
21
22 import java.io.IOException;
23 import java.security.cert.CertificateException;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Optional;
27 import org.apache.commons.io.FilenameUtils;
28 import org.apache.commons.lang3.tuple.Pair;
29 import org.apache.cxf.jaxrs.ext.multipart.Attachment;
30 import org.openecomp.core.utilities.file.FileContentHandler;
31 import org.openecomp.sdc.common.utils.CommonUtil;
32 import org.openecomp.sdc.logging.api.Logger;
33 import org.openecomp.sdc.logging.api.LoggerFactory;
34 import org.openecomp.sdc.vendorsoftwareproduct.security.SecurityManager;
35 import org.openecomp.sdc.vendorsoftwareproduct.security.SecurityManagerException;
36
37 /**
38  * Class responsible for processing zip archive and verify if this package corresponds SOL004 option 2 signed package
39  * format, verifies the cms signature if package is signed
40  */
41 public class PackageArchive {
42
43     private static final Logger LOG = LoggerFactory.getLogger(PackageArchive.class);
44     private static final String[] ALLOWED_ARCHIVE_EXTENSIONS = {"csar", "zip"};
45     private static final String[] ALLOWED_SIGNATURE_EXTENSIONS = {"cms"};
46     private static final String[] ALLOWED_CERTIFICATE_EXTENSIONS = {"cert"};
47     private static final int NUMBER_OF_FILES_FOR_SIGNATURE_WITH_CERT_INSIDE = 2;
48     private static final int NUMBER_OF_FILES_FOR_SIGNATURE_WITHOUT_CERT_INSIDE = 3;
49     private final SecurityManager securityManager;
50     private final byte[] outerPackageFileBytes;
51     private Pair<FileContentHandler, List<String>> handlerPair;
52     private Boolean signatureValid;
53
54     public PackageArchive(Attachment uploadedFile) {
55         this(uploadedFile.getObject(byte[].class));
56     }
57
58     public PackageArchive(byte[] outerPackageFileBytes) {
59         this.outerPackageFileBytes = outerPackageFileBytes;
60         this.securityManager = SecurityManager.getInstance();
61         try {
62             handlerPair = CommonUtil.getFileContentMapFromOrchestrationCandidateZip(
63                 outerPackageFileBytes);
64         } catch (IOException exception) {
65             LOG.error("Error reading files inside archive", exception);
66         }
67     }
68
69     /**
70      * Checks if package matches required format {package.csar/zip, package.cms, package.cert(optional)}
71      *
72      * @return true if structure matches sol004 option 2 structure
73      */
74     public boolean isSigned() {
75         return isPackageSizeMatches() && getSignatureFileName().isPresent();
76     }
77
78     /**
79      * Gets csar/zip package name with extension only if package is signed
80      *
81      * @return csar package name
82      */
83     public Optional<String> getArchiveFileName() {
84         if (isSigned()) {
85             return getFileByExtension(ALLOWED_ARCHIVE_EXTENSIONS);
86         }
87         return Optional.empty();
88     }
89
90     /**
91      * Gets csar/zip package content from zip archive
92      *
93      * @return csar package content
94      * @throws SecurityManagerException
95      */
96     public byte[] getPackageFileContents() throws SecurityManagerException {
97         try {
98             if (isSignatureValid()) {
99                 return handlerPair.getKey().getFiles().get(getArchiveFileName().orElseThrow(CertificateException::new));
100             }
101         } catch (CertificateException exception) {
102             LOG.info("Error verifying signature ", exception);
103         }
104         return outerPackageFileBytes;
105     }
106
107     /**
108      * Validates package signature against trusted certificates
109      *
110      * @return true if signature verified
111      * @throws SecurityManagerException
112      */
113     public boolean isSignatureValid() throws SecurityManagerException {
114         if (signatureValid == null) {
115             final Map<String, byte[]> files = handlerPair.getLeft().getFiles();
116             final Optional<String> signatureFileName = getSignatureFileName();
117             final Optional<String> archiveFileName = getArchiveFileName();
118             if (files.isEmpty() || !signatureFileName.isPresent() || !archiveFileName.isPresent()) {
119                 signatureValid = false;
120             } else {
121                 final Optional<String> certificateFile = getCertificateFileName();
122                 signatureValid = securityManager.verifySignedData(files.get(signatureFileName.get()),
123                     certificateFile.map(files::get).orElse(null), files.get(archiveFileName.get()));
124             }
125
126         }
127         return signatureValid;
128     }
129
130     private boolean isPackageSizeMatches() {
131         return handlerPair.getRight().isEmpty()
132             && (handlerPair.getLeft().getFiles().size() == NUMBER_OF_FILES_FOR_SIGNATURE_WITH_CERT_INSIDE
133             || handlerPair.getLeft().getFiles().size() == NUMBER_OF_FILES_FOR_SIGNATURE_WITHOUT_CERT_INSIDE);
134     }
135
136     private Optional<String> getSignatureFileName() {
137         return getFileByExtension(ALLOWED_SIGNATURE_EXTENSIONS);
138     }
139
140     private Optional<String> getFileByExtension(String[] extensions) {
141         for (String fileName : handlerPair.getLeft().getFileList()) {
142             for (String extension : extensions) {
143                 if (extension.equalsIgnoreCase(FilenameUtils.getExtension(fileName))) {
144                     return Optional.of(fileName);
145                 }
146             }
147         }
148         return Optional.empty();
149     }
150
151     private Optional<String> getCertificateFileName() {
152         Optional<String> certFileName = getFileByExtension(ALLOWED_CERTIFICATE_EXTENSIONS);
153         if (!certFileName.isPresent()) {
154             return Optional.empty();
155         }
156         String certNameWithoutExtension = FilenameUtils.removeExtension(certFileName.get());
157         if (certNameWithoutExtension.equals(FilenameUtils.removeExtension(getArchiveFileName().orElse("")))) {
158             return certFileName;
159         }
160         //cert file name should be the same as package name, e.g. vnfpackage.scar-->vnfpackage.cert
161         return Optional.empty();
162     }
163 }