[OOM CERT-SERVICE-API] Add support for URI, IP, E-mail in SANs
[oom/platform/cert-service.git] / certService / src / main / java / org / onap / oom / certservice / cmpv2client / impl / CmpMessageHelper.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2020 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.oom.certservice.cmpv2client.impl;
22
23 import static org.onap.oom.certservice.cmpv2client.impl.CmpUtil.generateProtectedBytes;
24
25 import java.io.ByteArrayOutputStream;
26 import java.io.IOException;
27 import java.security.InvalidKeyException;
28 import java.security.KeyPair;
29 import java.security.MessageDigest;
30 import java.security.NoSuchAlgorithmException;
31 import java.security.NoSuchProviderException;
32 import java.security.Signature;
33 import java.security.SignatureException;
34 import java.util.Date;
35 import javax.crypto.Mac;
36 import javax.crypto.SecretKey;
37 import javax.crypto.spec.SecretKeySpec;
38
39 import org.bouncycastle.asn1.ASN1EncodableVector;
40 import org.bouncycastle.asn1.ASN1Integer;
41 import org.bouncycastle.asn1.ASN1ObjectIdentifier;
42 import org.bouncycastle.asn1.DERBitString;
43 import org.bouncycastle.asn1.DEROctetString;
44 import org.bouncycastle.asn1.DEROutputStream;
45 import org.bouncycastle.asn1.DERSequence;
46 import org.bouncycastle.asn1.DERTaggedObject;
47 import org.bouncycastle.asn1.cmp.PBMParameter;
48 import org.bouncycastle.asn1.cmp.PKIBody;
49 import org.bouncycastle.asn1.cmp.PKIHeader;
50 import org.bouncycastle.asn1.cmp.PKIMessage;
51 import org.bouncycastle.asn1.crmf.CertRequest;
52 import org.bouncycastle.asn1.crmf.OptionalValidity;
53 import org.bouncycastle.asn1.crmf.POPOSigningKey;
54 import org.bouncycastle.asn1.crmf.ProofOfPossession;
55 import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
56 import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
57 import org.bouncycastle.asn1.x509.Extension;
58 import org.bouncycastle.asn1.x509.Extensions;
59 import org.bouncycastle.asn1.x509.ExtensionsGenerator;
60 import org.bouncycastle.asn1.x509.GeneralName;
61 import org.bouncycastle.asn1.x509.GeneralNames;
62 import org.bouncycastle.asn1.x509.KeyUsage;
63 import org.bouncycastle.asn1.x509.Time;
64 import org.bouncycastle.jce.provider.BouncyCastleProvider;
65 import org.onap.oom.certservice.cmpv2client.exceptions.CmpClientException;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68
69 public final class CmpMessageHelper {
70
71     private static final Logger LOG = LoggerFactory.getLogger(CmpMessageHelper.class);
72     private static final AlgorithmIdentifier OWF_ALGORITHM =
73             new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.3.14.3.2.26"));
74     private static final AlgorithmIdentifier MAC_ALGORITHM =
75             new AlgorithmIdentifier(new ASN1ObjectIdentifier("1.2.840.113549.2.9"));
76     private static final ASN1ObjectIdentifier PASSWORD_BASED_MAC =
77             new ASN1ObjectIdentifier("1.2.840.113533.7.66.13");
78
79     private CmpMessageHelper() {
80     }
81
82     /**
83      * Creates an Optional Validity, which is used to specify how long the returned cert should be
84      * valid for.
85      *
86      * @param notBefore Date specifying certificate is not valid before this date.
87      * @param notAfter  Date specifying certificate is not valid after this date.
88      * @return {@link OptionalValidity} that can be set for certificate on external CA.
89      */
90     public static OptionalValidity generateOptionalValidity(
91             final Date notBefore, final Date notAfter) {
92         LOG.info("Generating Optional Validity from Date objects");
93         ASN1EncodableVector optionalValidityV = new ASN1EncodableVector();
94         if (notBefore != null) {
95             Time nb = new Time(notBefore);
96             optionalValidityV.add(new DERTaggedObject(true, 0, nb));
97         }
98         if (notAfter != null) {
99             Time na = new Time(notAfter);
100             optionalValidityV.add(new DERTaggedObject(true, 1, na));
101         }
102         return OptionalValidity.getInstance(new DERSequence(optionalValidityV));
103     }
104
105     /**
106      * Create Extensions from Subject Alternative Names.
107      *
108      * @return {@link Extensions}.
109      */
110     public static Extensions generateExtension(final GeneralName[] sansArray)
111             throws CmpClientException {
112         LOG.info("Generating Extensions from Subject Alternative Names");
113         final ExtensionsGenerator extGenerator = new ExtensionsGenerator();
114         // KeyUsage
115         try {
116             final KeyUsage keyUsage =
117                     new KeyUsage(
118                             KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation);
119             extGenerator.addExtension(Extension.keyUsage, false, new DERBitString(keyUsage));
120             extGenerator.addExtension(
121                     Extension.subjectAlternativeName, false, new GeneralNames(sansArray));
122         } catch (IOException ioe) {
123             CmpClientException cmpClientException =
124                     new CmpClientException(
125                             "Exception occurred while creating extensions for PKIMessage", ioe);
126             LOG.error("Exception occurred while creating extensions for PKIMessage");
127             throw cmpClientException;
128         }
129         return extGenerator.generate();
130     }
131
132     /**
133      * Method generates Proof-of-Possession (POP) of Private Key. To allow a CA/RA to properly
134      * validity binding between an End Entity and a Key Pair, the PKI Operations specified here make
135      * it possible for an End Entity to prove that it has possession of the Private Key corresponding
136      * to the Public Key for which a Certificate is requested.
137      *
138      * @param certRequest Certificate request that requires proof of possession
139      * @param keypair     keypair associated with the subject sending the certificate request
140      * @return {@link ProofOfPossession}.
141      * @throws CmpClientException A general-purpose Cmp client exception.
142      */
143     public static ProofOfPossession generateProofOfPossession(
144             final CertRequest certRequest, final KeyPair keypair) throws CmpClientException {
145         ProofOfPossession proofOfPossession;
146         try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
147             final DEROutputStream derOutputStream = new DEROutputStream(byteArrayOutputStream);
148             derOutputStream.writeObject(certRequest);
149
150             byte[] popoProtectionBytes = byteArrayOutputStream.toByteArray();
151             final String sigalg = PKCSObjectIdentifiers.sha256WithRSAEncryption.getId();
152             final Signature signature = Signature.getInstance(sigalg, BouncyCastleProvider.PROVIDER_NAME);
153             signature.initSign(keypair.getPrivate());
154             signature.update(popoProtectionBytes);
155             DERBitString bs = new DERBitString(signature.sign());
156
157             proofOfPossession =
158                     new ProofOfPossession(
159                             new POPOSigningKey(
160                                     null, new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs));
161         } catch (IOException
162                 | NoSuchProviderException
163                 | NoSuchAlgorithmException
164                 | InvalidKeyException
165                 | SignatureException ex) {
166             CmpClientException cmpClientException =
167                     new CmpClientException(
168                             "Exception occurred while creating proof of possession for PKIMessage", ex);
169             LOG.error("Exception occurred while creating proof of possession for PKIMessage");
170             throw cmpClientException;
171         }
172         return proofOfPossession;
173     }
174
175     /**
176      * Generic code to create Algorithm Identifier for protection of PKIMessage.
177      *
178      * @return Algorithm Identifier
179      */
180     public static AlgorithmIdentifier protectionAlgoIdentifier(int iterations, byte[] salt) {
181         ASN1Integer iteration = new ASN1Integer(iterations);
182         DEROctetString derSalt = new DEROctetString(salt);
183
184         PBMParameter pp = new PBMParameter(derSalt, OWF_ALGORITHM, iteration, MAC_ALGORITHM);
185         return new AlgorithmIdentifier(PASSWORD_BASED_MAC, pp);
186     }
187
188     /**
189      * Adds protection to the PKIMessage via a specified protection algorithm.
190      *
191      * @param password  password used to authenticate PkiMessage with external CA
192      * @param pkiHeader Header of PKIMessage containing generic details for any PKIMessage
193      * @param pkiBody   Body of PKIMessage containing specific details for certificate request
194      * @return Protected Pki Message
195      * @throws CmpClientException Wraps several exceptions into one general-purpose exception.
196      */
197     public static PKIMessage protectPkiMessage(
198             PKIHeader pkiHeader, PKIBody pkiBody, String password, int iterations, byte[] salt)
199             throws CmpClientException {
200
201         byte[] raSecret = password.getBytes();
202         byte[] basekey = new byte[raSecret.length + salt.length];
203         System.arraycopy(raSecret, 0, basekey, 0, raSecret.length);
204         System.arraycopy(salt, 0, basekey, raSecret.length, salt.length);
205         byte[] out;
206         try {
207             MessageDigest dig =
208                     MessageDigest.getInstance(
209                             OWF_ALGORITHM.getAlgorithm().getId(), BouncyCastleProvider.PROVIDER_NAME);
210             for (int i = 0; i < iterations; i++) {
211                 basekey = dig.digest(basekey);
212                 dig.reset();
213             }
214             byte[] protectedBytes = generateProtectedBytes(pkiHeader, pkiBody);
215             Mac mac =
216                     Mac.getInstance(MAC_ALGORITHM.getAlgorithm().getId(), BouncyCastleProvider.PROVIDER_NAME);
217             SecretKey key = new SecretKeySpec(basekey, MAC_ALGORITHM.getAlgorithm().getId());
218             mac.init(key);
219             mac.reset();
220             mac.update(protectedBytes, 0, protectedBytes.length);
221             out = mac.doFinal();
222         } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException ex) {
223             CmpClientException cmpClientException =
224                     new CmpClientException(
225                             "Exception occurred while generating proof of possession for PKIMessage", ex);
226             LOG.error("Exception occured while generating the proof of possession for PKIMessage");
227             throw cmpClientException;
228         }
229         DERBitString bs = new DERBitString(out);
230
231         return new PKIMessage(pkiHeader, pkiBody, bs);
232     }
233 }