[OOM-CERT-SERVICE] Fix sonar and checkstyle issues, code cleanup
[oom/platform/cert-service.git] / certService / src / main / java / org / onap / oom / certservice / cmpv2client / validation / CmpCertificationValidator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2020 Nordix Foundation.
4  * ================================================================================
5  * Modification copyright 2021 Nokia
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  *
19  * SPDX-License-Identifier: Apache-2.0
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.oom.certservice.cmpv2client.validation;
24
25 import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseValidationHelper.checkImplicitConfirm;
26 import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseValidationHelper.verifyPasswordBasedProtection;
27 import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseValidationHelper.verifySignature;
28
29 import java.security.PublicKey;
30 import java.util.Date;
31 import java.util.Objects;
32 import java.util.Optional;
33 import org.apache.http.impl.client.CloseableHttpClient;
34 import org.bouncycastle.asn1.ASN1ObjectIdentifier;
35 import org.bouncycastle.asn1.cmp.CertResponse;
36 import org.bouncycastle.asn1.cmp.PKIHeader;
37 import org.bouncycastle.asn1.cmp.PKIMessage;
38 import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
39 import org.onap.oom.certservice.certification.configuration.model.CaMode;
40 import org.onap.oom.certservice.certification.configuration.model.Cmpv2Server;
41 import org.onap.oom.certservice.certification.model.CsrModel;
42 import org.onap.oom.certservice.cmpv2client.exceptions.CmpClientException;
43 import org.onap.oom.certservice.cmpv2client.exceptions.CmpServerException;
44 import org.onap.oom.certservice.cmpv2client.impl.CmpUtil;
45 import org.onap.oom.certservice.cmpv2client.impl.PkiStatus;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 public class CmpCertificationValidator {
50     private static final String DEFAULT_CA_NAME = "Certification Authority";
51     private static final String DEFAULT_PROFILE = CaMode.RA.getProfile();
52     private static final ASN1ObjectIdentifier PASSWORD_BASED_MAC = new ASN1ObjectIdentifier("1.2.840.113533.7.66.13");
53     private static final Logger LOG = LoggerFactory.getLogger(CmpCertificationValidator.class);
54
55     public void validate(
56         final CsrModel csrModel,
57         final Cmpv2Server server,
58         final CloseableHttpClient httpClient,
59         final Date notBefore,
60         final Date notAfter) {
61
62         String caName = CmpUtil.isNullOrEmpty(server.getCaName()) ? server.getCaName() : DEFAULT_CA_NAME;
63         String profile = server.getCaMode() != null ? server.getCaMode().getProfile() : DEFAULT_PROFILE;
64         LOG.info(
65             "Validate before creating Certificate Request for CA :{} in Mode {} ", caName, profile);
66
67         CmpUtil.notNull(csrModel, "CsrModel Instance");
68         CmpUtil.notNull(csrModel.getSubjectData(), "Subject DN");
69         CmpUtil.notNull(csrModel.getPrivateKey(), "Subject private key");
70         CmpUtil.notNull(csrModel.getPublicKey(), "Subject public key");
71         CmpUtil.notNull(server.getIssuerDN(), "Issuer DN");
72         CmpUtil.notNull(server.getUrl(), "External CA URL");
73         CmpUtil.notNull(server.getAuthentication().getIak(), "IAK/RV Password");
74         CmpUtil.notNull(httpClient, "Closeable Http Client");
75
76         if (notBefore != null && notAfter != null && notBefore.compareTo(notAfter) > 0) {
77             throw new IllegalArgumentException("Before Date is set after the After Date");
78         }
79     }
80
81     public void checkCmpResponse(final PKIMessage respPkiMessage, final PublicKey publicKey, final String initAuthPassword)
82         throws CmpClientException {
83         final PKIHeader header = respPkiMessage.getHeader();
84         final AlgorithmIdentifier protectionAlgo = header.getProtectionAlg();
85         verifySignatureWithPublicKey(respPkiMessage, publicKey);
86         if (isPasswordBasedMacAlgorithm(protectionAlgo)) {
87             LOG.info("CMP response is protected by Password Base Mac Algorithm. Attempt to verify protection");
88             verifyPasswordBasedMacProtection(respPkiMessage, initAuthPassword, header, protectionAlgo);
89         }
90     }
91
92     public void checkServerResponse(CertResponse certResponse) {
93         if (certResponse.getStatus() != null && certResponse.getStatus().getStatus() != null) {
94             logServerResponse(certResponse);
95             if (certResponse.getStatus().getStatus().intValue() == PkiStatus.REJECTED.getCode()) {
96                 String serverMessage = certResponse.getStatus().getStatusString().getStringAt(0).getString();
97                 throw new CmpServerException(Optional.ofNullable(serverMessage).orElse("N/A"));
98             }
99         }
100     }
101
102     private boolean isPasswordBasedMacAlgorithm(AlgorithmIdentifier protectionAlgo) throws CmpClientException {
103         if (Objects.isNull(protectionAlgo)) {
104             LOG.error("CMP response does not contain Protection Algorithm field");
105             throw new CmpClientException("CMP response does not contain Protection Algorithm field");
106         }
107         return PASSWORD_BASED_MAC.equals(protectionAlgo.getAlgorithm());
108     }
109
110     private void verifySignatureWithPublicKey(PKIMessage respPkiMessage, PublicKey publicKey)
111         throws CmpClientException {
112         if (Objects.nonNull(publicKey)) {
113             LOG.debug("Verifying signature of the response.");
114             verifySignature(respPkiMessage, publicKey);
115         } else {
116             LOG.error("Public Key is not available, therefore cannot verify signature");
117             throw new CmpClientException(
118                 "Public Key is not available, therefore cannot verify signature");
119         }
120     }
121
122     private void verifyPasswordBasedMacProtection(PKIMessage respPkiMessage, String initAuthPassword,
123         PKIHeader header, AlgorithmIdentifier protectionAlgo)
124         throws CmpClientException {
125         LOG.debug("Verifying PasswordBased Protection of the Response.");
126         verifyPasswordBasedProtection(respPkiMessage, initAuthPassword, protectionAlgo);
127         checkImplicitConfirm(header);
128     }
129
130     private void logServerResponse(CertResponse certResponse) {
131         if (LOG.isInfoEnabled()) {
132             LOG.info("Response status code: {}", certResponse.getStatus().getStatus());
133         }
134         if (certResponse.getStatus().getStatusString() != null) {
135             String serverMessage = certResponse.getStatus().getStatusString().getStringAt(0).getString();
136             LOG.warn("Response status text: {}", serverMessage);
137         }
138         if (LOG.isWarnEnabled() && certResponse.getStatus().getFailInfo() != null) {
139             LOG.warn("Response fail info:   {}", certResponse.getStatus().getFailInfo());
140         }
141     }
142 }