001/*
002 * acme4j - Java ACME client
003 *
004 * Copyright (C) 2016 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;
015
016import static java.util.Collections.unmodifiableList;
017import static java.util.Objects.requireNonNull;
018import static java.util.stream.Collectors.toList;
019import static java.util.stream.Collectors.toUnmodifiableList;
020import static org.shredzone.acme4j.toolbox.AcmeUtils.getRenewalUniqueIdentifier;
021
022import java.io.IOException;
023import java.io.Serial;
024import java.io.Writer;
025import java.net.MalformedURLException;
026import java.net.URI;
027import java.net.URL;
028import java.security.KeyPair;
029import java.security.Principal;
030import java.security.cert.CertificateEncodingException;
031import java.security.cert.X509Certificate;
032import java.util.Collection;
033import java.util.List;
034import java.util.Optional;
035
036import edu.umd.cs.findbugs.annotations.Nullable;
037import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
038import org.shredzone.acme4j.connector.Resource;
039import org.shredzone.acme4j.exception.AcmeException;
040import org.shredzone.acme4j.exception.AcmeLazyLoadingException;
041import org.shredzone.acme4j.exception.AcmeNotSupportedException;
042import org.shredzone.acme4j.exception.AcmeProtocolException;
043import org.shredzone.acme4j.toolbox.AcmeUtils;
044import org.shredzone.acme4j.toolbox.JSONBuilder;
045import org.slf4j.Logger;
046import org.slf4j.LoggerFactory;
047
048/**
049 * Represents an issued certificate and its certificate chain.
050 * <p>
051 * A certificate is immutable once it is issued. For renewal, a new certificate must be
052 * ordered.
053 */
054public class Certificate extends AcmeResource {
055    @Serial
056    private static final long serialVersionUID = 7381527770159084201L;
057    private static final Logger LOG = LoggerFactory.getLogger(Certificate.class);
058
059    private @Nullable List<X509Certificate> certChain;
060    private @Nullable Collection<URL> alternates;
061    private transient @Nullable RenewalInfo renewalInfo = null;
062    private transient @Nullable List<Certificate> alternateCerts = null;
063
064    protected Certificate(Login login, URL certUrl) {
065        super(login, certUrl);
066    }
067
068    /**
069     * Downloads the certificate chain.
070     * <p>
071     * The certificate is downloaded lazily by the other methods. Usually there is no need
072     * to invoke this method, unless the download is to be enforced. If the certificate
073     * has been downloaded already, nothing will happen.
074     *
075     * @throws AcmeException
076     *         if the certificate could not be downloaded
077     */
078    public void download() throws AcmeException {
079        if (certChain == null) {
080            LOG.debug("download");
081            try (var conn = getSession().connect()) {
082                conn.sendCertificateRequest(getLocation(), getLogin());
083                alternates = conn.getLinks("alternate");
084                certChain = conn.readCertificates();
085            }
086        }
087    }
088
089    /**
090     * Returns the created certificate.
091     *
092     * @return The created end-entity {@link X509Certificate} without issuer chain.
093     */
094    public X509Certificate getCertificate() {
095        lazyDownload();
096        return requireNonNull(certChain).get(0);
097    }
098
099    /**
100     * Returns the created certificate and issuer chain.
101     *
102     * @return The created end-entity {@link X509Certificate} and issuer chain. The first
103     *         certificate is always the end-entity certificate, followed by the
104     *         intermediate certificates required to build a path to a trusted root.
105     */
106    public List<X509Certificate> getCertificateChain() {
107        lazyDownload();
108        return unmodifiableList(requireNonNull(certChain));
109    }
110
111    /**
112     * Returns URLs to alternate certificate chains.
113     *
114     * @return Alternate certificate chains, or empty if there are none.
115     */
116    public List<URL> getAlternates() {
117        lazyDownload();
118        return requireNonNull(alternates).stream().collect(toUnmodifiableList());
119    }
120
121    /**
122     * Returns alternate certificate chains, if available.
123     *
124     * @return Alternate certificate chains, or empty if there are none.
125     * @since 2.11
126     */
127    public List<Certificate> getAlternateCertificates() {
128        if (alternateCerts == null) {
129            var login = getLogin();
130            alternateCerts = getAlternates().stream()
131                    .map(login::bindCertificate)
132                    .collect(toList());
133        }
134        return unmodifiableList(alternateCerts);
135    }
136
137    /**
138     * Checks if this certificate was issued by the given issuer name.
139     *
140     * @param issuer
141     *         Issuer name to check against, case-sensitive
142     * @return {@code true} if this issuer name was found in the certificate chain as
143     * issuer, {@code false} otherwise.
144     * @since 3.0.0
145     */
146    public boolean isIssuedBy(String issuer) {
147        var issuerCn = "CN=" + issuer;
148        return getCertificateChain().stream()
149                .map(X509Certificate::getIssuerX500Principal)
150                .map(Principal::getName)
151                .anyMatch(issuerCn::equals);
152    }
153
154    /**
155     * Finds a {@link Certificate} that was issued by the given issuer name.
156     *
157     * @param issuer
158     *         Issuer name to check against, case-sensitive
159     * @return Certificate that was issued by that issuer, or {@code empty} if there was
160     * none. The returned {@link Certificate} may be this instance, or one of the
161     * {@link #getAlternateCertificates()} instances. If multiple certificates are issued
162     * by that issuer, the first one that was found is returned.
163     * @since 3.0.0
164     */
165    public Optional<Certificate> findCertificate(String issuer) {
166        if (isIssuedBy(issuer)) {
167            return Optional.of(this);
168        }
169        return getAlternateCertificates().stream()
170                .filter(c -> c.isIssuedBy(issuer))
171                .findFirst();
172    }
173
174    /**
175     * Writes the certificate to the given writer. It is written in PEM format, with the
176     * end-entity cert coming first, followed by the intermediate certificates.
177     *
178     * @param out
179     *            {@link Writer} to write to. The writer is not closed after use.
180     */
181    public void writeCertificate(Writer out) throws IOException {
182        try {
183            for (var cert : getCertificateChain()) {
184                AcmeUtils.writeToPem(cert.getEncoded(), AcmeUtils.PemLabel.CERTIFICATE, out);
185            }
186        } catch (CertificateEncodingException ex) {
187            throw new IOException("Encoding error", ex);
188        }
189    }
190
191    /**
192     * Returns the location of the certificate's RenewalInfo. Empty if the CA does not
193     * provide this information.
194     *
195     * @since 3.0.0
196     */
197    public Optional<URL> getRenewalInfoLocation() {
198        try {
199            return getSession().resourceUrlOptional(Resource.RENEWAL_INFO)
200                    .map(baseUrl -> {
201                        try {
202                            var url = baseUrl.toExternalForm();
203                            if (!url.endsWith("/")) {
204                                url += '/';
205                            }
206                            url += getRenewalUniqueIdentifier(getCertificate());
207                            return URI.create(url).toURL();
208                        } catch (MalformedURLException ex) {
209                            throw new AcmeProtocolException("Invalid RenewalInfo URL", ex);
210                        }
211                    });
212        } catch (AcmeException ex) {
213            throw new AcmeLazyLoadingException(this, ex);
214        }
215    }
216
217    /**
218     * Returns {@code true} if the CA provides renewal information.
219     *
220     * @since 3.0.0
221     */
222    public boolean hasRenewalInfo() {
223        return getRenewalInfoLocation().isPresent();
224    }
225
226    /**
227     * Reads the RenewalInfo for this certificate.
228     *
229     * @return The {@link RenewalInfo} of this certificate.
230     * @throws AcmeNotSupportedException if the CA does not support renewal information.
231     * @since 3.0.0
232     */
233    @SuppressFBWarnings("EI_EXPOSE_REP")   // behavior is intended
234    public RenewalInfo getRenewalInfo() {
235        if (renewalInfo == null) {
236            renewalInfo = getRenewalInfoLocation()
237                    .map(getLogin()::bindRenewalInfo)
238                    .orElseThrow(() -> new AcmeNotSupportedException("renewal-info"));
239        }
240        return renewalInfo;
241    }
242
243    /**
244     * Revokes this certificate.
245     */
246    public void revoke() throws AcmeException {
247        revoke(null);
248    }
249
250    /**
251     * Revokes this certificate.
252     *
253     * @param reason
254     *            {@link RevocationReason} stating the reason of the revocation that is
255     *            used when generating OCSP responses and CRLs. {@code null} to give no
256     *            reason.
257     * @see #revoke(Login, X509Certificate, RevocationReason)
258     * @see #revoke(Session, KeyPair, X509Certificate, RevocationReason)
259     */
260    public void revoke(@Nullable RevocationReason reason) throws AcmeException {
261        revoke(getLogin(), getCertificate(), reason);
262    }
263
264    /**
265     * Revoke a certificate.
266     * <p>
267     * Use this method if the certificate's location is unknown, so you cannot regenerate
268     * a {@link Certificate} instance. This method requires a {@link Login} to your
269     * account and the issued certificate.
270     *
271     * @param login
272     *         {@link Login} to the account
273     * @param cert
274     *         The {@link X509Certificate} to be revoked
275     * @param reason
276     *         {@link RevocationReason} stating the reason of the revocation that is used
277     *         when generating OCSP responses and CRLs. {@code null} to give no reason.
278     * @see #revoke(Session, KeyPair, X509Certificate, RevocationReason)
279     * @since 2.6
280     */
281    public static void revoke(Login login, X509Certificate cert, @Nullable RevocationReason reason)
282                throws AcmeException {
283        LOG.debug("revoke");
284
285        var session = login.getSession();
286
287        var resUrl = session.resourceUrl(Resource.REVOKE_CERT);
288
289        try (var conn = session.connect()) {
290            var claims = new JSONBuilder();
291            claims.putBase64("certificate", cert.getEncoded());
292            if (reason != null) {
293                claims.put("reason", reason.getReasonCode());
294            }
295
296            conn.sendSignedRequest(resUrl, claims, login);
297        } catch (CertificateEncodingException ex) {
298            throw new AcmeProtocolException("Invalid certificate", ex);
299        }
300    }
301
302    /**
303     * Revoke a certificate.
304     * <p>
305     * Use this method if the key pair of your account was lost (so you are unable to
306     * login into your account), but you still have the key pair of the affected domain
307     * and the issued certificate.
308     *
309     * @param session
310     *         {@link Session} connected to the ACME server
311     * @param domainKeyPair
312     *         Key pair the CSR was signed with
313     * @param cert
314     *         The {@link X509Certificate} to be revoked
315     * @param reason
316     *         {@link RevocationReason} stating the reason of the revocation that is used
317     *         when generating OCSP responses and CRLs. {@code null} to give no reason.
318     * @see #revoke(Login, X509Certificate, RevocationReason)
319     */
320    public static void revoke(Session session, KeyPair domainKeyPair, X509Certificate cert,
321            @Nullable RevocationReason reason) throws AcmeException {
322        LOG.debug("revoke using the domain key pair");
323
324        var resUrl = session.resourceUrl(Resource.REVOKE_CERT);
325
326        try (var conn = session.connect()) {
327            var claims = new JSONBuilder();
328            claims.putBase64("certificate", cert.getEncoded());
329            if (reason != null) {
330                claims.put("reason", reason.getReasonCode());
331            }
332
333            conn.sendSignedRequest(resUrl, claims, session, domainKeyPair);
334        } catch (CertificateEncodingException ex) {
335            throw new AcmeProtocolException("Invalid certificate", ex);
336        }
337    }
338
339    /**
340     * Lazily downloads the certificate. Throws a runtime {@link AcmeLazyLoadingException}
341     * if the download failed.
342     */
343    private void lazyDownload() {
344        try {
345            download();
346        } catch (AcmeException ex) {
347            throw new AcmeLazyLoadingException(this, ex);
348        }
349    }
350
351}