001/*
002 * acme4j - Java ACME client
003 *
004 * Copyright (C) 2015 Richard "Shred" Körber
005 *   http://acme4j.shredzone.org
006 *
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
013 */
014package org.shredzone.acme4j.util;
015
016import java.io.ByteArrayInputStream;
017import java.io.IOException;
018import java.io.InputStream;
019import java.io.InputStreamReader;
020import java.math.BigInteger;
021import java.nio.charset.StandardCharsets;
022import java.security.InvalidKeyException;
023import java.security.KeyPair;
024import java.security.NoSuchAlgorithmException;
025import java.security.PrivateKey;
026import java.security.PublicKey;
027import java.security.cert.CertificateException;
028import java.security.cert.CertificateFactory;
029import java.security.cert.X509Certificate;
030import java.time.Duration;
031import java.time.Instant;
032import java.util.Date;
033import java.util.Objects;
034import java.util.function.Function;
035
036import org.bouncycastle.asn1.ASN1ObjectIdentifier;
037import org.bouncycastle.asn1.DEROctetString;
038import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
039import org.bouncycastle.asn1.x500.X500Name;
040import org.bouncycastle.asn1.x509.Extension;
041import org.bouncycastle.asn1.x509.Extensions;
042import org.bouncycastle.asn1.x509.GeneralName;
043import org.bouncycastle.asn1.x509.GeneralNames;
044import org.bouncycastle.cert.CertIOException;
045import org.bouncycastle.cert.X509CertificateHolder;
046import org.bouncycastle.cert.jcajce.JcaX509v1CertificateBuilder;
047import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
048import org.bouncycastle.openssl.PEMParser;
049import org.bouncycastle.operator.ContentSigner;
050import org.bouncycastle.operator.OperatorCreationException;
051import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
052import org.bouncycastle.pkcs.PKCS10CertificationRequest;
053import org.bouncycastle.pkcs.jcajce.JcaPKCS10CertificationRequest;
054import org.shredzone.acme4j.Identifier;
055import org.shredzone.acme4j.challenge.TlsAlpn01Challenge;
056
057/**
058 * Utility class offering convenience methods for certificates.
059 * <p>
060 * Requires {@code Bouncy Castle}.
061 */
062public final class CertificateUtils {
063
064    /**
065     * The {@code acmeValidation} object identifier.
066     *
067     * @since 2.1
068     */
069    public static final ASN1ObjectIdentifier ACME_VALIDATION =
070                    new ASN1ObjectIdentifier(TlsAlpn01Challenge.ACME_VALIDATION_OID).intern();
071
072    private CertificateUtils() {
073        // utility class without constructor
074    }
075
076    /**
077     * Reads a CSR PEM file.
078     *
079     * @param in
080     *            {@link InputStream} to read the CSR from. The {@link InputStream} is
081     *            closed after use.
082     * @return CSR that was read
083     */
084    public static PKCS10CertificationRequest readCSR(InputStream in) throws IOException {
085        try (var pemParser = new PEMParser(new InputStreamReader(in, StandardCharsets.US_ASCII))) {
086            var parsedObj = pemParser.readObject();
087            if (!(parsedObj instanceof PKCS10CertificationRequest)) {
088                throw new IOException("Not a PKCS10 CSR");
089            }
090            return (PKCS10CertificationRequest) parsedObj;
091        }
092    }
093
094    /**
095     * Creates a self-signed {@link X509Certificate} that can be used for the
096     * {@link TlsAlpn01Challenge}. The certificate is valid for 7 days.
097     *
098     * @param keypair
099     *            A domain {@link KeyPair} to be used for the challenge
100     * @param id
101     *            The {@link Identifier} that is to be validated
102     * @param acmeValidation
103     *            The value that is returned by
104     *            {@link TlsAlpn01Challenge#getAcmeValidation()}
105     * @return Created certificate
106     * @since 2.6
107     */
108    public static X509Certificate createTlsAlpn01Certificate(KeyPair keypair, Identifier id, byte[] acmeValidation)
109                throws IOException {
110        Objects.requireNonNull(keypair, "keypair");
111        Objects.requireNonNull(id, "id");
112        if (acmeValidation == null || acmeValidation.length != 32) {
113            throw new IllegalArgumentException("Bad acmeValidation parameter");
114        }
115
116        var now = System.currentTimeMillis();
117
118        var issuer = new X500Name("CN=acme.invalid");
119        var serial = BigInteger.valueOf(now);
120        var notBefore = Instant.ofEpochMilli(now);
121        var notAfter = notBefore.plus(Duration.ofDays(7));
122
123        var certBuilder = new JcaX509v3CertificateBuilder(
124                    issuer, serial, Date.from(notBefore), Date.from(notAfter),
125                    issuer, keypair.getPublic());
126
127        var gns = new GeneralName[1];
128
129        gns[0] = switch (id.getType()) {
130            case Identifier.TYPE_DNS -> new GeneralName(GeneralName.dNSName, id.getDomain());
131            case Identifier.TYPE_IP -> new GeneralName(GeneralName.iPAddress, id.getIP().getHostAddress());
132            default -> throw new IllegalArgumentException("Unsupported Identifier type " + id.getType());
133        };
134        certBuilder.addExtension(Extension.subjectAlternativeName, false, new GeneralNames(gns));
135        certBuilder.addExtension(ACME_VALIDATION, true, new DEROctetString(acmeValidation));
136
137        return buildCertificate(certBuilder::build, keypair.getPrivate());
138    }
139
140    /**
141     * Creates a self-signed root certificate.
142     * <p>
143     * The generated certificate is only meant for testing purposes!
144     *
145     * @param subject
146     *         This certificate's subject X.500 name.
147     * @param notBefore
148     *         {@link Instant} before which the certificate is not valid.
149     * @param notAfter
150     *         {@link Instant} after which the certificate is not valid.
151     * @param keypair
152     *         {@link KeyPair} that is to be used for this certificate.
153     * @return Generated {@link X509Certificate}
154     * @since 2.8
155     */
156    public static X509Certificate createTestRootCertificate(String subject,
157            Instant notBefore, Instant notAfter, KeyPair keypair) {
158        Objects.requireNonNull(subject, "subject");
159        Objects.requireNonNull(notBefore, "notBefore");
160        Objects.requireNonNull(notAfter, "notAfter");
161        Objects.requireNonNull(keypair, "keypair");
162
163        var certBuilder = new JcaX509v1CertificateBuilder(
164                new X500Name(subject),
165                BigInteger.valueOf(System.currentTimeMillis()),
166                Date.from(notBefore),
167                Date.from(notAfter),
168                new X500Name(subject),
169                keypair.getPublic()
170        );
171
172        return buildCertificate(certBuilder::build, keypair.getPrivate());
173    }
174
175    /**
176     * Creates an intermediate certificate that is signed by an issuer.
177     * <p>
178     * The generated certificate is only meant for testing purposes!
179     *
180     * @param subject
181     *         This certificate's subject X.500 name.
182     * @param notBefore
183     *         {@link Instant} before which the certificate is not valid.
184     * @param notAfter
185     *         {@link Instant} after which the certificate is not valid.
186     * @param intermediatePublicKey
187     *         {@link PublicKey} of this certificate
188     * @param issuer
189     *         The issuer's {@link X509Certificate}.
190     * @param issuerPrivateKey
191     *         {@link PrivateKey} of the issuer. This is not the private key of this
192     *         intermediate certificate.
193     * @return Generated {@link X509Certificate}
194     * @since 2.8
195     */
196    public static X509Certificate createTestIntermediateCertificate(String subject,
197            Instant notBefore, Instant notAfter, PublicKey intermediatePublicKey,
198            X509Certificate issuer, PrivateKey issuerPrivateKey) {
199        Objects.requireNonNull(subject, "subject");
200        Objects.requireNonNull(notBefore, "notBefore");
201        Objects.requireNonNull(notAfter, "notAfter");
202        Objects.requireNonNull(intermediatePublicKey, "intermediatePublicKey");
203        Objects.requireNonNull(issuer, "issuer");
204        Objects.requireNonNull(issuerPrivateKey, "issuerPrivateKey");
205
206        var certBuilder = new JcaX509v1CertificateBuilder(
207                new X500Name(issuer.getIssuerX500Principal().getName()),
208                BigInteger.valueOf(System.currentTimeMillis()),
209                Date.from(notBefore),
210                Date.from(notAfter),
211                new X500Name(subject),
212                intermediatePublicKey
213        );
214
215        return buildCertificate(certBuilder::build, issuerPrivateKey);
216    }
217
218    /**
219     * Creates a signed end entity certificate from the given CSR.
220     * <p>
221     * This method is only meant for testing purposes! Do not use it in a real-world CA
222     * implementation.
223     * <p>
224     * Do not assume that real-world certificates have a similar structure. It's up to the
225     * discretion of the CA which distinguished names, validity dates, extensions and
226     * other parameters are transferred from the CSR to the generated certificate.
227     *
228     * @param csr
229     *         CSR to create the certificate from
230     * @param notBefore
231     *         {@link Instant} before which the certificate is not valid.
232     * @param notAfter
233     *         {@link Instant} after which the certificate is not valid.
234     * @param issuer
235     *         The issuer's {@link X509Certificate}.
236     * @param issuerPrivateKey
237     *         {@link PrivateKey} of the issuer. This is not the private key the CSR was
238     *         signed with.
239     * @return Generated {@link X509Certificate}
240     * @since 2.8
241     */
242    public static X509Certificate createTestCertificate(PKCS10CertificationRequest csr,
243            Instant notBefore, Instant notAfter, X509Certificate issuer, PrivateKey issuerPrivateKey) {
244        Objects.requireNonNull(csr, "csr");
245        Objects.requireNonNull(notBefore, "notBefore");
246        Objects.requireNonNull(notAfter, "notAfter");
247        Objects.requireNonNull(issuer, "issuer");
248        Objects.requireNonNull(issuerPrivateKey, "issuerPrivateKey");
249
250        try {
251            var jcaCsr = new JcaPKCS10CertificationRequest(csr);
252
253            var certBuilder = new JcaX509v3CertificateBuilder(
254                    new X500Name(issuer.getIssuerX500Principal().getName()),
255                    BigInteger.valueOf(System.currentTimeMillis()),
256                    Date.from(notBefore),
257                    Date.from(notAfter),
258                    csr.getSubject(),
259                    jcaCsr.getPublicKey());
260
261            var attr = csr.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
262            if (attr.length > 0) {
263                var extensions = attr[0].getAttrValues().toArray();
264                if (extensions.length > 0 && extensions[0] instanceof Extensions extension0) {
265                    var san = GeneralNames.fromExtensions(extension0, Extension.subjectAlternativeName);
266                    var critical = csr.getSubject().getRDNs().length == 0;
267                    certBuilder.addExtension(Extension.subjectAlternativeName, critical, san);
268                }
269            }
270
271            return buildCertificate(certBuilder::build, issuerPrivateKey);
272        } catch (NoSuchAlgorithmException | InvalidKeyException | CertIOException ex) {
273            throw new IllegalArgumentException("Invalid CSR", ex);
274        }
275    }
276
277    /**
278     * Build a {@link X509Certificate} from a builder.
279     *
280     * @param builder
281     *         Builder method that receives a {@link ContentSigner} and returns a {@link
282     *         X509CertificateHolder}.
283     * @param privateKey
284     *         {@link PrivateKey} to sign the certificate with
285     * @return The generated {@link X509Certificate}
286     */
287    private static X509Certificate buildCertificate(Function<ContentSigner, X509CertificateHolder> builder, PrivateKey privateKey) {
288        try {
289            var signerBuilder = new JcaContentSignerBuilder("SHA256withRSA");
290            var cert = builder.apply(signerBuilder.build(privateKey)).getEncoded();
291            var certificateFactory = CertificateFactory.getInstance("X.509");
292            return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(cert));
293        } catch (CertificateException | OperatorCreationException | IOException ex) {
294            throw new IllegalArgumentException("Could not build certificate", ex);
295        }
296    }
297
298}