aboutsummaryrefslogtreecommitdiffstats
path: root/openecomp-be/backend/openecomp-sdc-vendor-software-product-manager/src/main/java/org/openecomp/sdc/vendorsoftwareproduct/security/SecurityManager.java
blob: 53728c0489838d45d4824072ceb0921e7100d67c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
/*-
 * ============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.sdc.vendorsoftwareproduct.security;

import com.google.common.collect.ImmutableSet;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.cert.CertPathBuilder;
import java.security.cert.CertStore;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.CollectionCertStoreParameters;
import java.security.cert.PKIXBuilderParameters;
import java.security.cert.PKIXCertPathBuilderResult;
import java.security.cert.TrustAnchor;
import java.security.cert.X509CertSelector;
import java.security.cert.X509Certificate;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSProcessableFile;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.operator.OperatorCreationException;
import org.openecomp.sdc.be.csar.storage.ArtifactInfo;
import org.openecomp.sdc.be.csar.storage.ArtifactStorageConfig;
import org.openecomp.sdc.be.csar.storage.ArtifactStorageManager;
import org.openecomp.sdc.be.csar.storage.StorageFactory;
import org.openecomp.sdc.logging.api.Logger;
import org.openecomp.sdc.logging.api.LoggerFactory;
import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardSignedPackage;

/**
 * This is temporary solution. When AAF provides functionality for verifying trustedCertificates, this class should be reviewed Class is responsible
 * for providing root trustedCertificates from configured location in onboarding container.
 */
public class SecurityManager {

    public static final Set<String> ALLOWED_SIGNATURE_EXTENSIONS = Set.of("cms");
    public static final Set<String> ALLOWED_CERTIFICATE_EXTENSIONS = Set.of("cert", "crt");
    private static final String CERTIFICATE_DEFAULT_LOCATION = "cert";
    private static final Logger LOGGER = LoggerFactory.getLogger(SecurityManager.class);
    private static final String UNEXPECTED_ERROR_OCCURRED_DURING_SIGNATURE_VALIDATION = "Unexpected error occurred during signature validation!";
    private static final String COULD_NOT_VERIFY_SIGNATURE = "Could not verify signature!";
    private static final String EXTERNAL_CSAR_STORE = "externalCsarStore";

    static {
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
    }

    private Set<X509Certificate> trustedCertificates = new HashSet<>();
    private Set<X509Certificate> trustedCertificatesFromPackage = new HashSet<>();
    private File certificateDirectory;

    private SecurityManager() {
        certificateDirectory = this.getcertDirectory(System.getenv("SDC_CERT_DIR"));
    }

    // Package level constructor use in tests to avoid power mock
    SecurityManager(String sdcCertDir) {
        certificateDirectory = this.getcertDirectory(sdcCertDir);
    }

    public static SecurityManager getInstance() {
        return SecurityManagerInstanceHolder.instance;
    }

    /**
     * Checks the configured location for available trustedCertificates
     *
     * @return set of trustedCertificates
     * @throws SecurityManagerException
     */
    public Set<X509Certificate> getTrustedCertificates() throws SecurityManagerException {
        //if file number in certificate directory changed reload certs
        String[] certFiles = certificateDirectory.list();
        if (certFiles == null) {
            LOGGER.error("Certificate directory is empty!");
            return ImmutableSet.copyOf(new HashSet<>());
        }
        if (trustedCertificates.size() != certFiles.length) {
            trustedCertificates = new HashSet<>();
            processCertificateDir();
        }
        if (!trustedCertificatesFromPackage.isEmpty()) {
            return Stream.concat(trustedCertificatesFromPackage.stream(), trustedCertificates.stream()).collect(Collectors.toUnmodifiableSet());
        }
        return ImmutableSet.copyOf(trustedCertificates);
    }

    /**
     * Cleans certificate collection
     */
    public void cleanTrustedCertificates() {
        trustedCertificates.clear();
    }

    /**
     * Verifies if packaged signed with trusted certificate
     *
     * @param messageSyntaxSignature - signature data in cms format
     * @param packageCert            - package certificate if not part of cms signature, can be null
     * @param innerPackageFile       data package signed with cms signature
     * @return true if signature verified
     * @throws SecurityManagerException
     */
    public boolean verifySignedData(final byte[] messageSyntaxSignature,
                                    final byte[] packageCert,
                                    final byte[] innerPackageFile) throws SecurityManagerException {
        try (final ByteArrayInputStream signatureStream = new ByteArrayInputStream(messageSyntaxSignature);
            final PEMParser pemParser = new PEMParser(new InputStreamReader(signatureStream))) {
            final Object parsedObject = pemParser.readObject();
            if (!(parsedObject instanceof ContentInfo)) {
                throw new SecurityManagerException("Signature is not recognized");
            }
            return verify(packageCert, new CMSSignedData(new CMSProcessableByteArray(innerPackageFile), ContentInfo.getInstance(parsedObject)));
        } catch (final IOException | CMSException e) {
            LOGGER.error(e.getMessage(), e);
            throw new SecurityManagerException(UNEXPECTED_ERROR_OCCURRED_DURING_SIGNATURE_VALIDATION, e);
        }
    }

    public boolean verifyPackageSignedData(final OnboardSignedPackage signedPackage, final ArtifactInfo artifactInfo)
        throws SecurityManagerException {
        boolean fail = false;

        final StorageFactory storageFactory = new StorageFactory();
        final ArtifactStorageManager artifactStorageManager = storageFactory.createArtifactStorageManager();
        final ArtifactStorageConfig storageConfiguration = artifactStorageManager.getStorageConfiguration();

        final var fileContentHandler = signedPackage.getFileContentHandler();
        byte[] packageCert = null;
        final Optional<String> certificateFilePath = signedPackage.getCertificateFilePath();
        if (certificateFilePath.isPresent()) {
            packageCert = fileContentHandler.getFileContent(certificateFilePath.get());
        }

        final Path folder = Path.of(storageConfiguration.getTempPath());
        try {
            Files.createDirectories(folder);
        } catch (final IOException e) {
            fail = true;
            throw new SecurityManagerException(String.format("Failed to create directory '%s'", folder), e);
        }

        final var target = folder.resolve(UUID.randomUUID().toString());

        try (final var signatureStream = new ByteArrayInputStream(fileContentHandler.getFileContent(signedPackage.getSignatureFilePath()));
            final var pemParser = new PEMParser(new InputStreamReader(signatureStream))) {
            final var parsedObject = pemParser.readObject();
            if (!(parsedObject instanceof ContentInfo)) {
                fail = true;
                throw new SecurityManagerException("Signature is not recognized");
            }

            try (final InputStream inputStream = artifactStorageManager.get(artifactInfo)) {
                if (!findCSARandExtract(inputStream, target)) {
                    fail = true;
                    return false;
                }
            }
            final var verify = verify(packageCert, new CMSSignedData(new CMSProcessableFile(target.toFile()), ContentInfo.getInstance(parsedObject)));
            fail = !verify;
            return verify;
        } catch (final IOException e) {
            fail = true;
            LOGGER.error(e.getMessage(), e);
            throw new SecurityManagerException(UNEXPECTED_ERROR_OCCURRED_DURING_SIGNATURE_VALIDATION, e);
        } catch (final CMSException e) {
            fail = true;
            throw new SecurityManagerException(COULD_NOT_VERIFY_SIGNATURE, e);
        } catch (final SecurityManagerException e) {
            fail = true;
            throw e;
        } finally {
            deleteFile(target);
            if (fail) {
                artifactStorageManager.delete(artifactInfo);
            }
        }
    }

    private void deleteFile(final Path filePath) {
        try {
            Files.delete(filePath);
        } catch (final IOException e) {
            LOGGER.warn("Failed to delete '{}' after verifying package signed data", filePath, e);
        }
    }

    private boolean verify(final byte[] packageCert, final CMSSignedData signedData) throws SecurityManagerException {
        final SignerInformation firstSigner = signedData.getSignerInfos().getSigners().iterator().next();
        final X509Certificate cert;
        Collection<X509CertificateHolder> certs;
        if (packageCert == null) {
            certs = signedData.getCertificates().getMatches(null);
            cert = readSignCert(certs, firstSigner)
                .orElseThrow(() -> new SecurityManagerException("No certificate found in cms signature that should contain one!"));
        } else {
            try {
                certs = parseCertsFromPem(packageCert);
            } catch (final IOException e) {
                throw new SecurityManagerException("Failed to parse certificate from PEM", e);
            }
            cert = readSignCert(certs, firstSigner)
                .orElseThrow(() -> new SecurityManagerException("No matching certificate found in certificate file that should contain one!"));
        }
        trustedCertificatesFromPackage = readTrustedCerts(certs, firstSigner);
        if (verifyCertificate(cert, getTrustedCertificates()) == null) {
            return false;
        }
        try {
            return firstSigner.verify(new JcaSimpleSignerInfoVerifierBuilder().build(cert));
        } catch (CMSException | OperatorCreationException e) {
            throw new SecurityManagerException("Failed to verify package signed data", e);
        }
    }

    private boolean findCSARandExtract(final InputStream inputStream, final Path target) throws IOException {
        final AtomicBoolean found = new AtomicBoolean(false);

        final var zipInputStream = new ZipInputStream(inputStream);
        ZipEntry zipEntry;
        byte[] buffer = new byte[2048];
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            final var entryName = zipEntry.getName();
            if (!zipEntry.isDirectory() && entryName.toLowerCase().endsWith(".csar")) {
                try (final FileOutputStream fos = new FileOutputStream(target.toFile());
                    final BufferedOutputStream bos = new BufferedOutputStream(fos, buffer.length)) {

                    int len;
                    while ((len = zipInputStream.read(buffer)) > 0) {
                        bos.write(buffer, 0, len);
                    }
                }
                found.set(true);
            }
        }
        return found.get();
    }

    private Optional<X509Certificate> readSignCert(final Collection<X509CertificateHolder> certs, final SignerInformation firstSigner) {
        return certs.stream().filter(crt -> firstSigner.getSID().match(crt)).findAny().map(this::loadCertificate);
    }

    private Set<X509Certificate> readTrustedCerts(final Collection<X509CertificateHolder> certs, final SignerInformation firstSigner) {
        return certs.stream().filter(crt -> !firstSigner.getSID().match(crt)).map(this::loadCertificate).filter(Predicate.not(this::isSelfSigned))
            .collect(Collectors.toSet());
    }

    private Set<X509CertificateHolder> parseCertsFromPem(final byte[] packageCert) throws IOException {
        final ByteArrayInputStream packageCertStream = new ByteArrayInputStream(packageCert);
        final PEMParser pemParser = new PEMParser(new InputStreamReader(packageCertStream));
        Object readObject = pemParser.readObject();
        Set<X509CertificateHolder> allCerts = new HashSet<>();
        while (readObject != null) {
            if (readObject instanceof X509CertificateHolder) {
                allCerts.add((X509CertificateHolder) readObject);
            }
            readObject = pemParser.readObject();
        }
        return allCerts;
    }

    private void processCertificateDir() throws SecurityManagerException {
        if (!certificateDirectory.exists() || !certificateDirectory.isDirectory()) {
            LOGGER.error("Issue with certificate directory, check if exists!");
            return;
        }
        File[] files = certificateDirectory.listFiles();
        if (files == null) {
            LOGGER.error("Certificate directory is empty!");
            return;
        }
        for (File f : files) {
            trustedCertificates.add(loadCertificate(f));
        }
    }

    private File getcertDirectory(String sdcCertDir) {
        String certDirLocation = sdcCertDir;
        if (certDirLocation == null) {
            certDirLocation = CERTIFICATE_DEFAULT_LOCATION;
        }
        return new File(certDirLocation);
    }

    private X509Certificate loadCertificate(File certFile) throws SecurityManagerException {
        try (FileInputStream fi = new FileInputStream(certFile)) {
            return loadCertificateFactory(fi);
        } catch (IOException e) {
            throw new SecurityManagerException("Error during loading Certificate from file!", e);
        }
    }

    private X509Certificate loadCertificate(X509CertificateHolder cert) {
        try {
            return loadCertificateFactory(new ByteArrayInputStream(cert.getEncoded()));
        } catch (IOException | SecurityManagerException e) {
            throw new RuntimeException("Error during loading Certificate from bytes!", e);
        }
    }

    private X509Certificate loadCertificateFactory(InputStream in) throws SecurityManagerException {
        try {
            CertificateFactory factory = CertificateFactory.getInstance("X.509");
            return (X509Certificate) factory.generateCertificate(in);
        } catch (CertificateException e) {
            throw new SecurityManagerException("Error during loading Certificate from bytes!", e);
        }
    }

    private PKIXCertPathBuilderResult verifyCertificate(final X509Certificate cert,
                                                        final Set<X509Certificate> additionalCerts) throws SecurityManagerException {
        if (null == cert) {
            throw new SecurityManagerException("The certificate is empty!");
        }
        if (isExpired(cert)) {
            throw new SecurityManagerException("The certificate expired on: " + cert.getNotAfter());
        }
        if (isSelfSigned(cert)) {
            throw new SecurityManagerException("The certificate is self-signed.");
        }
        Set<X509Certificate> trustedRootCerts = new HashSet<>();
        Set<X509Certificate> intermediateCerts = new HashSet<>();
        for (X509Certificate additionalCert : additionalCerts) {
            if (isSelfSigned(additionalCert)) {
                trustedRootCerts.add(additionalCert);
            } else {
                intermediateCerts.add(additionalCert);
            }
        }
        try {
            return verifyCertificate(cert, trustedRootCerts, intermediateCerts);
        } catch (final GeneralSecurityException e) {
            throw new SecurityManagerException("Failed to verify certificate", e);
        }
    }

    private PKIXCertPathBuilderResult verifyCertificate(X509Certificate cert, Set<X509Certificate> allTrustedRootCerts,
                                                        Set<X509Certificate> allIntermediateCerts) throws GeneralSecurityException {
        // Create the selector that specifies the starting certificate
        X509CertSelector selector = new X509CertSelector();
        selector.setCertificate(cert);
        // Create the trust anchors (set of root CA certificates)
        Set<TrustAnchor> trustAnchors = new HashSet<>();
        for (X509Certificate trustedRootCert : allTrustedRootCerts) {
            trustAnchors.add(new TrustAnchor(trustedRootCert, null));
        }
        // Configure the PKIX certificate builder algorithm parameters
        PKIXBuilderParameters pkixParams;
        try {
            pkixParams = new PKIXBuilderParameters(trustAnchors, selector);
        } catch (InvalidAlgorithmParameterException ex) {
            throw new InvalidAlgorithmParameterException("No root CA has been found for this certificate", ex);
        }
        // Not supporting CRL checks for now
        pkixParams.setRevocationEnabled(false);
        Set<X509Certificate> certSet = new HashSet<>();
        certSet.add(cert);
        pkixParams.addCertStore(createCertStore(certSet));
        pkixParams.addCertStore(createCertStore(allIntermediateCerts));
        pkixParams.addCertStore(createCertStore(allTrustedRootCerts));
        CertPathBuilder builder = CertPathBuilder.getInstance(CertPathBuilder.getDefaultType(), BouncyCastleProvider.PROVIDER_NAME);
        return (PKIXCertPathBuilderResult) builder.build(pkixParams);
    }

    private CertStore createCertStore(Set<X509Certificate> certificateSet)
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
        return CertStore.getInstance("Collection", new CollectionCertStoreParameters(certificateSet), BouncyCastleProvider.PROVIDER_NAME);
    }

    private boolean isExpired(X509Certificate cert) {
        try {
            cert.checkValidity();
        } catch (CertificateExpiredException e) {
            LOGGER.error(e.getMessage(), e);
            return true;
        } catch (CertificateNotYetValidException e) {
            LOGGER.error(e.getMessage(), e);
            return false;
        }
        return false;
    }

    private boolean isSelfSigned(X509Certificate cert) {
        return cert.getIssuerDN().equals(cert.getSubjectDN());
    }

    /**
     * Initialization on demand class / synchronized singleton pattern.
     */
    private static class SecurityManagerInstanceHolder {

        private static final SecurityManager instance = new SecurityManager();
    }
}