aboutsummaryrefslogtreecommitdiffstats
path: root/certService/src/main/java/org/onap/oom/certservice/cmpv2client/impl/CmpClientImpl.java
blob: 549cf6b9863b4afb48624fc578238333c3c9d506 (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
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2020 Nordix Foundation.
 * ================================================================================
 * Modification copyright 2021 Nokia
 * ================================================================================
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.oom.certservice.cmpv2client.impl;

import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseHelper.checkIfCmpResponseContainsError;
import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseHelper.getCertFromByteArray;
import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseHelper.verifyAndReturnCertChainAndTrustSTore;
import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseValidationHelper.checkImplicitConfirm;
import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseValidationHelper.verifyPasswordBasedProtection;
import static org.onap.oom.certservice.cmpv2client.impl.CmpResponseValidationHelper.verifySignature;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.util.Collections;
import java.util.Date;
import java.util.Objects;
import java.util.Optional;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.impl.client.CloseableHttpClient;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.cmp.CMPCertificate;
import org.bouncycastle.asn1.cmp.CertRepMessage;
import org.bouncycastle.asn1.cmp.CertResponse;
import org.bouncycastle.asn1.cmp.PKIBody;
import org.bouncycastle.asn1.cmp.PKIHeader;
import org.bouncycastle.asn1.cmp.PKIMessage;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.Certificate;
import org.bouncycastle.util.io.pem.PemReader;
import org.onap.oom.certservice.certification.configuration.model.CaMode;
import org.onap.oom.certservice.certification.configuration.model.Cmpv2Server;
import org.onap.oom.certservice.certification.exception.KeyDecryptionException;
import org.onap.oom.certservice.certification.model.CertificateUpdateModel;
import org.onap.oom.certservice.certification.model.CsrModel;
import org.onap.oom.certservice.cmpv2client.api.CmpClient;
import org.onap.oom.certservice.cmpv2client.exceptions.CmpClientException;
import org.onap.oom.certservice.cmpv2client.exceptions.CmpServerException;
import org.onap.oom.certservice.cmpv2client.model.Cmpv2CertificationModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Implementation of the CmpClient Interface conforming to RFC4210 (Certificate Management Protocol
 * (CMP)) and RFC4211 (Certificate Request Message Format (CRMF)) standards.
 */
public class CmpClientImpl implements CmpClient {

    private static final Logger LOG = LoggerFactory.getLogger(CmpClientImpl.class);
    private final CloseableHttpClient httpClient;

    private static final String DEFAULT_CA_NAME = "Certification Authority";
    private static final String DEFAULT_PROFILE = CaMode.RA.getProfile();
    private static final ASN1ObjectIdentifier PASSWORD_BASED_MAC = new ASN1ObjectIdentifier("1.2.840.113533.7.66.13");

    public CmpClientImpl(CloseableHttpClient httpClient) {
        this.httpClient = httpClient;
    }

    @Override
    public Cmpv2CertificationModel createCertificate(
            CsrModel csrModel,
            Cmpv2Server server,
            Date notBefore,
            Date notAfter)
            throws CmpClientException {

        validate(csrModel, server, httpClient, notBefore, notAfter);
        final CreateCertRequest certRequest = getIakRvRequest(csrModel, server, notBefore, notAfter, PKIBody.TYPE_INIT_REQ);
        return executeCmpRequest(csrModel, server, certRequest);
    }

    @Override
    public Cmpv2CertificationModel createCertificate(CsrModel csrModel, Cmpv2Server server)
            throws CmpClientException {
        return createCertificate(csrModel, server, null, null);
    }

    @Override
    public Cmpv2CertificationModel updateCertificate(CsrModel csrModel, Cmpv2Server cmpv2Server,
        CertificateUpdateModel certificateUpdateModel) throws CmpClientException {
        validate(csrModel, cmpv2Server, httpClient, null, null);

        final PkiMessageProtection pkiMessageProtection = getSignatureProtection(certificateUpdateModel);
        final CreateCertRequest certRequest =
            getCmpMessageBuilderWithCommonRequestValues(csrModel, cmpv2Server)
                .with(CreateCertRequest::setCmpRequestType, PKIBody.TYPE_KEY_UPDATE_REQ)
                .with(CreateCertRequest::setExtraCerts, getCMPCertificateFromPem(certificateUpdateModel.getEncodedOldCert()))
                .with(CreateCertRequest::setProtection, pkiMessageProtection)
                .build();

        return executeCmpRequest(csrModel, cmpv2Server, certRequest);

    }

    @Override
    public Cmpv2CertificationModel certificationRequest(CsrModel csrModel, Cmpv2Server cmpv2Server) throws CmpClientException {

        validate(csrModel, cmpv2Server, httpClient, null, null);
        final CreateCertRequest certRequest = getIakRvRequest(csrModel, cmpv2Server, null, null, PKIBody.TYPE_CERT_REQ);
        return executeCmpRequest(csrModel, cmpv2Server, certRequest);
    }

    private CreateCertRequest getIakRvRequest(
        CsrModel csrModel,
        Cmpv2Server server,
        Date notBefore,
        Date notAfter,
        int requestType) {

        final String iak = server.getAuthentication().getIak();
        final PkiMessageProtection pkiMessageProtection = new PasswordBasedProtection(iak);
        return getCmpMessageBuilderWithCommonRequestValues(csrModel, server)
            .with(CreateCertRequest::setNotBefore, notBefore)
            .with(CreateCertRequest::setNotAfter, notAfter)
            .with(CreateCertRequest::setSenderKid, server.getAuthentication().getRv())
            .with(CreateCertRequest::setCmpRequestType, requestType)
            .with(CreateCertRequest::setProtection, pkiMessageProtection)
            .build();
    }

    private Cmpv2CertificationModel executeCmpRequest(CsrModel csrModel, Cmpv2Server cmpv2Server,
        CreateCertRequest certRequest) throws CmpClientException {
        final PKIMessage pkiMessage = certRequest.generateCertReq();
        Cmpv2HttpClient cmpv2HttpClient = new Cmpv2HttpClient(httpClient);
        return retrieveCertificates(csrModel, cmpv2Server, pkiMessage, cmpv2HttpClient);
    }

    private CmpMessageBuilder<CreateCertRequest> getCmpMessageBuilderWithCommonRequestValues(CsrModel csrModel,
        Cmpv2Server cmpv2Server) {
        KeyPair keyPair = new KeyPair(csrModel.getPublicKey(), csrModel.getPrivateKey());
        return CmpMessageBuilder.of(CreateCertRequest::new)
            .with(CreateCertRequest::setIssuerDn, cmpv2Server.getIssuerDN())
            .with(CreateCertRequest::setSubjectDn, csrModel.getSubjectData())
            .with(CreateCertRequest::setSansArray, csrModel.getSans())
            .with(CreateCertRequest::setSubjectKeyPair, keyPair);
    }

    private SignatureProtection getSignatureProtection(CertificateUpdateModel certificateUpdateModel)
        throws CmpClientException {
        try {
            PrivateKey oldPrivateKey = certificateUpdateModel.getOldPrivateKeyObject();
            return new SignatureProtection(oldPrivateKey);
        } catch (NoSuchAlgorithmException | KeyDecryptionException | InvalidKeySpecException e) {
            throw new CmpClientException("Cannot parse old private key ", e);
        }

    }

    private CMPCertificate[] getCMPCertificateFromPem(String encodedCertPem) throws CmpClientException {
        try {
            Certificate certificate = Certificate.getInstance(
                new PemReader(
                    new InputStreamReader(
                        new ByteArrayInputStream(
                            Base64.decodeBase64(encodedCertPem))))
                .readPemObject().getContent());
            CMPCertificate cert = new CMPCertificate(certificate);
            return new CMPCertificate[]{cert};
        } catch (IOException | NullPointerException e ) {
            throw new CmpClientException("Cannot parse old certificate", e);
        }
    }

    private void checkCmpResponse(
            final PKIMessage respPkiMessage, final PublicKey publicKey, final String initAuthPassword)
            throws CmpClientException {
        final PKIHeader header = respPkiMessage.getHeader();
        final AlgorithmIdentifier protectionAlgo = header.getProtectionAlg();
        verifySignatureWithPublicKey(respPkiMessage, publicKey);
        if (isPasswordBasedMacAlgorithm(protectionAlgo)) {
            LOG.info("CMP response is protected by Password Base Mac Algorithm. Attempt to verify protection");
            verifyPasswordBasedMacProtection(respPkiMessage, initAuthPassword, header, protectionAlgo);
        }
    }

    private boolean isPasswordBasedMacAlgorithm(AlgorithmIdentifier protectionAlgo) throws CmpClientException {
        if (Objects.isNull(protectionAlgo)) {
            LOG.error("CMP response does not contain Protection Algorithm field");
            throw new CmpClientException("CMP response does not contain Protection Algorithm field");
        }
        return PASSWORD_BASED_MAC.equals(protectionAlgo.getAlgorithm());
    }

    private void verifySignatureWithPublicKey(PKIMessage respPkiMessage, PublicKey publicKey)
            throws CmpClientException {
        if (Objects.nonNull(publicKey)) {
            LOG.debug("Verifying signature of the response.");
            verifySignature(respPkiMessage, publicKey);
        } else {
            LOG.error("Public Key is not available, therefore cannot verify signature");
            throw new CmpClientException(
                    "Public Key is not available, therefore cannot verify signature");
        }
    }

    private void verifyPasswordBasedMacProtection(PKIMessage respPkiMessage, String initAuthPassword,
        PKIHeader header, AlgorithmIdentifier protectionAlgo)
        throws CmpClientException {
        LOG.debug("Verifying PasswordBased Protection of the Response.");
        verifyPasswordBasedProtection(respPkiMessage, initAuthPassword, protectionAlgo);
        checkImplicitConfirm(header);
    }

    private Cmpv2CertificationModel checkCmpCertRepMessage(final PKIMessage respPkiMessage)
            throws CmpClientException {
        final PKIBody pkiBody = respPkiMessage.getBody();
        if (Objects.nonNull(pkiBody) && pkiBody.getContent() instanceof CertRepMessage) {
            final CertRepMessage certRepMessage = (CertRepMessage) pkiBody.getContent();
            if (Objects.nonNull(certRepMessage)) {
                try {
                    CertResponse certResponse = getCertificateResponseContainingNewCertificate(certRepMessage);
                    checkServerResponse(certResponse);
                    return verifyReturnCertChainAndTrustStore(respPkiMessage, certRepMessage, certResponse);
                } catch (IOException | CertificateParsingException ex) {
                    CmpClientException cmpClientException =
                            new CmpClientException(
                                    "Exception occurred while retrieving Certificates from response", ex);
                    LOG.error("Exception occurred while retrieving Certificates from response", ex);
                    throw cmpClientException;
                }
            } else {
                return new Cmpv2CertificationModel(Collections.emptyList(), Collections.emptyList());
            }
        }
        return new Cmpv2CertificationModel(Collections.emptyList(), Collections.emptyList());
    }

    private void checkServerResponse(CertResponse certResponse) {
        if (certResponse.getStatus() != null && certResponse.getStatus().getStatus() != null) {
            logServerResponse(certResponse);
            if (certResponse.getStatus().getStatus().intValue() == PkiStatus.REJECTED.getCode()) {
                String serverMessage = certResponse.getStatus().getStatusString().getStringAt(0).getString();
                throw new CmpServerException(Optional.ofNullable(serverMessage).orElse("N/A"));
            }
        }
    }

    private void logServerResponse(CertResponse certResponse) {
        if (LOG.isInfoEnabled()) {
            LOG.info("Response status code: {}", certResponse.getStatus().getStatus());
        }
        if (certResponse.getStatus().getStatusString() != null) {
            String serverMessage = certResponse.getStatus().getStatusString().getStringAt(0).getString();
            LOG.warn("Response status text: {}", serverMessage);
        }
        if (LOG.isWarnEnabled() && certResponse.getStatus().getFailInfo() != null) {
            LOG.warn("Response fail info:   {}", certResponse.getStatus().getFailInfo());
        }
    }

    private Cmpv2CertificationModel verifyReturnCertChainAndTrustStore(
            PKIMessage respPkiMessage, CertRepMessage certRepMessage, CertResponse certResponse)
            throws CertificateParsingException, CmpClientException, IOException {
        LOG.info("Verifying certificates returned as part of CertResponse.");
        final CMPCertificate cmpCertificate =
                certResponse.getCertifiedKeyPair().getCertOrEncCert().getCertificate();
        final Optional<X509Certificate> leafCertificate =
                getCertFromByteArray(cmpCertificate.getEncoded(), X509Certificate.class);
        if (leafCertificate.isPresent()) {
            return verifyAndReturnCertChainAndTrustSTore(
                    respPkiMessage, certRepMessage, leafCertificate.get());
        }
        return new Cmpv2CertificationModel(Collections.emptyList(), Collections.emptyList());
    }

    private CertResponse getCertificateResponseContainingNewCertificate(
            CertRepMessage certRepMessage) {
        return certRepMessage.getResponse()[0];
    }

    /**
     * Validate inputs for Certificate Creation.
     *
     * @param csrModel Certificate Signing Request model. Must not be {@code null}.
     * @param server   CMPv2 Server. Must not be {@code null}.
     * @throws IllegalArgumentException if Before Date is set after the After Date.
     */
    private static void validate(
            final CsrModel csrModel,
            final Cmpv2Server server,
            final CloseableHttpClient httpClient,
            final Date notBefore,
            final Date notAfter) {

        String caName = CmpUtil.isNullOrEmpty(server.getCaName()) ? server.getCaName() : DEFAULT_CA_NAME;
        String profile = server.getCaMode() != null ? server.getCaMode().getProfile() : DEFAULT_PROFILE;
        LOG.info(
                "Validate before creating Certificate Request for CA :{} in Mode {} ", caName, profile);

        CmpUtil.notNull(csrModel, "CsrModel Instance");
        CmpUtil.notNull(csrModel.getSubjectData(), "Subject DN");
        CmpUtil.notNull(csrModel.getPrivateKey(), "Subject private key");
        CmpUtil.notNull(csrModel.getPublicKey(), "Subject public key");
        CmpUtil.notNull(server.getIssuerDN(), "Issuer DN");
        CmpUtil.notNull(server.getUrl(), "External CA URL");
        CmpUtil.notNull(server.getAuthentication().getIak(), "IAK/RV Password");
        CmpUtil.notNull(httpClient, "Closeable Http Client");

        if (notBefore != null && notAfter != null && notBefore.compareTo(notAfter) > 0) {
            throw new IllegalArgumentException("Before Date is set after the After Date");
        }
    }

    private Cmpv2CertificationModel retrieveCertificates(
            CsrModel csrModel, Cmpv2Server server, PKIMessage pkiMessage, Cmpv2HttpClient cmpv2HttpClient)
            throws CmpClientException {
        final byte[] respBytes = cmpv2HttpClient.postRequest(pkiMessage, server.getUrl(), server.getCaName());
        try {
            final PKIMessage respPkiMessage = PKIMessage.getInstance(respBytes);
            LOG.info("Received response from Server");
            checkIfCmpResponseContainsError(respPkiMessage);
            checkCmpResponse(respPkiMessage, csrModel.getPublicKey(), server.getAuthentication().getIak());
            return checkCmpCertRepMessage(respPkiMessage);
        } catch (IllegalArgumentException iae) {
            CmpClientException cmpClientException =
                    new CmpClientException(
                            "Error encountered while processing response from CA server ", iae);
            LOG.error("Error encountered while processing response from CA server ", iae);
            throw cmpClientException;
        }
    }
}