001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.io;
003
004import static org.openstreetmap.josm.tools.I18n.tr;
005
006import java.io.ByteArrayInputStream;
007import java.io.IOException;
008import java.io.InputStream;
009import java.nio.file.Files;
010import java.nio.file.Path;
011import java.nio.file.Paths;
012import java.security.GeneralSecurityException;
013import java.security.InvalidAlgorithmParameterException;
014import java.security.KeyStore;
015import java.security.KeyStoreException;
016import java.security.MessageDigest;
017import java.security.NoSuchAlgorithmException;
018import java.security.cert.CertificateEncodingException;
019import java.security.cert.CertificateException;
020import java.security.cert.CertificateFactory;
021import java.security.cert.PKIXParameters;
022import java.security.cert.TrustAnchor;
023import java.security.cert.X509Certificate;
024import java.util.Arrays;
025import java.util.Collection;
026import java.util.Collections;
027import java.util.Objects;
028
029import javax.net.ssl.SSLContext;
030import javax.net.ssl.TrustManagerFactory;
031
032import org.openstreetmap.josm.spi.preferences.Config;
033import org.openstreetmap.josm.tools.Logging;
034import org.openstreetmap.josm.tools.PlatformManager;
035import org.openstreetmap.josm.tools.Utils;
036
037/**
038 * Class to add missing root certificates to the list of trusted certificates
039 * for TLS connections.
040 *
041 * The added certificates are deemed trustworthy by the main web browsers and
042 * operating systems, but not included in some distributions of Java.
043 *
044 * The certificates are added in-memory at each start, nothing is written to disk.
045 * @since 9995
046 */
047public final class CertificateAmendment {
048
049    /**
050     * A certificate amendment.
051     * @since 11943
052     */
053    public static class CertAmend {
054        private final String filename;
055        private final String sha256;
056
057        protected CertAmend(String filename, String sha256) {
058            this.filename = Objects.requireNonNull(filename);
059            this.sha256 = Objects.requireNonNull(sha256);
060        }
061
062        /**
063         * Returns the certificate filename.
064         * @return filename for both JOSM embedded certificate and Unix platform certificate
065         * @since 12241
066         */
067        public final String getFilename() {
068            return filename;
069        }
070
071        /**
072         * Returns the SHA-256 hash.
073         * @return the SHA-256 hash, in hexadecimal
074         */
075        public final String getSha256() {
076            return sha256;
077        }
078    }
079
080    /**
081     * An embedded certificate amendment.
082     * @since 13450
083     */
084    public static class EmbeddedCertAmend extends CertAmend {
085        private final String url;
086
087        EmbeddedCertAmend(String url, String filename, String sha256) {
088            super(filename, sha256);
089            this.url = Objects.requireNonNull(url);
090        }
091
092        /**
093         * Returns the embedded URL in JOSM jar.
094         * @return path for JOSM embedded certificate
095         */
096        public final String getUrl() {
097            return url;
098        }
099
100        @Override
101        public String toString() {
102            return url;
103        }
104    }
105
106    /**
107     * A certificate amendment relying on native platform certificate store.
108     * @since 13450
109     */
110    public static class NativeCertAmend extends CertAmend {
111        private final Collection<String> aliases;
112        private final String httpsWebSite;
113
114        NativeCertAmend(Collection<String> aliases, String filename, String sha256, String httpsWebSite) {
115            super(filename, sha256);
116            this.aliases = Objects.requireNonNull(aliases);
117            this.httpsWebSite = Objects.requireNonNull(httpsWebSite);
118        }
119
120        /**
121         * Returns the native aliases in System Root Certificates keystore/keychain.
122         * @return the native aliases in System Root Certificates keystore/keychain
123         * @since 15006
124         */
125        public final Collection<String> getNativeAliases() {
126            return aliases;
127        }
128
129        /**
130         * Returns the https website we need to call to notify Windows we need its root certificate.
131         * @return the https website signed with this root CA
132         * @since 13451
133         */
134        public String getWebSite() {
135            return httpsWebSite;
136        }
137
138        @Override
139        public String toString() {
140            return String.join(" / ", aliases);
141        }
142    }
143
144    /**
145     * Certificates embedded in JOSM
146     */
147    private static final EmbeddedCertAmend[] CERT_AMEND = {
148    };
149
150    /**
151     * Certificates looked into platform native keystore and not embedded in JOSM.
152     * Identifiers must match Windows/macOS keystore aliases and Unix filenames for efficient search.
153     * To find correct values, see https://ccadb-public.secure.force.com/mozilla/IncludedCACertificateReport
154     * and https://support.apple.com/en-us/HT208127
155     */
156    private static final NativeCertAmend[] PLATFORM_CERT_AMEND = {
157        // Let's Encrypt - should be included in JDK, but problems with Ubuntu 18.04, see #15851
158        new NativeCertAmend(Collections.singleton("DST Root CA X3"),
159                "DST_Root_CA_X3.pem",
160                "0687260331a72403d909f105e69bcf0d32e1bd2493ffc6d9206d11bcd6770739",
161                "https://acme-v02.api.letsencrypt.org"),
162        // Government of Netherlands
163        new NativeCertAmend(Collections.singleton("Staat der Nederlanden Root CA - G2"),
164                "Staat_der_Nederlanden_Root_CA_-_G2.crt",
165                "668c83947da63b724bece1743c31a0e6aed0db8ec5b31be377bb784f91b6716f",
166                "https://roottest-g2.pkioverheid.nl"),
167        // Government of Netherlands
168        new NativeCertAmend(Arrays.asList("Government of Netherlands G3", "Staat der Nederlanden Root CA - G3"),
169                "Staat_der_Nederlanden_Root_CA_-_G3.crt",
170                "3c4fb0b95ab8b30032f432b86f535fe172c185d0fd39865837cf36187fa6f428",
171                "https://roottest-g3.pkioverheid.nl"),
172        // Trusted and used by French Government - https://www.certigna.fr/autorites/index.xhtml?ac=Racine#lracine
173        new NativeCertAmend(Collections.singleton("Certigna"),
174                "Certigna.crt",
175                "e3b6a2db2ed7ce48842f7ac53241c7b71d54144bfb40c11f3f1d0b42f5eea12d",
176                "https://www.certigna.fr"),
177        // Trusted and used by Slovakian Government - https://eidas.disig.sk/en/cacert/
178        new NativeCertAmend(Collections.singleton("CA Disig Root R2"),
179                "CA_Disig_Root_R2.pem",
180                "e23d4a036d7b70e9f595b1422079d2b91edfbb1fb651a0633eaa8a9dc5f80703",
181                "https://eidas.disig.sk"),
182        // Government of Taiwan - https://grca.nat.gov.tw/GRCAeng/index.html
183        new NativeCertAmend(Arrays.asList("TW Government Root Certification Authority", "Government Root Certification Authority"),
184                "Taiwan_GRCA.pem",
185                "7600295eefe85b9e1fd624db76062aaaae59818a54d2774cd4c0b2c01131e1b3",
186                "https://grca.nat.gov.tw")
187    };
188
189    private CertificateAmendment() {
190        // Hide default constructor for utility classes
191    }
192
193    /**
194     * Add missing root certificates to the list of trusted certificates for TLS connections.
195     * @throws IOException if an I/O error occurs
196     * @throws GeneralSecurityException if a security error occurs
197     */
198    public static void addMissingCertificates() throws IOException, GeneralSecurityException {
199        if (!Config.getPref().getBoolean("tls.add-missing-certificates", true))
200            return;
201        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
202        Path cacertsPath = Paths.get(Utils.getSystemProperty("java.home"), "lib", "security", "cacerts");
203        try (InputStream is = Files.newInputStream(cacertsPath)) {
204            keyStore.load(is, "changeit".toCharArray());
205        } catch (SecurityException e) {
206            Logging.log(Logging.LEVEL_ERROR, "Unable to load keystore", e);
207            return;
208        }
209
210        MessageDigest md = MessageDigest.getInstance("SHA-256");
211        CertificateFactory cf = CertificateFactory.getInstance("X.509");
212        boolean certificateAdded = false;
213        // Add embedded certificates. Exit in case of error
214        for (EmbeddedCertAmend certAmend : CERT_AMEND) {
215            try (CachedFile certCF = new CachedFile(certAmend.url)) {
216                X509Certificate cert = (X509Certificate) cf.generateCertificate(
217                        new ByteArrayInputStream(certCF.getByteContent()));
218                if (checkAndAddCertificate(md, cert, certAmend, keyStore)) {
219                    certificateAdded = true;
220                }
221            }
222        }
223
224        try {
225            // Try to add platform certificates. Do not exit in case of error (embedded certificates may be OK)
226            for (NativeCertAmend certAmend : PLATFORM_CERT_AMEND) {
227                X509Certificate cert = PlatformManager.getPlatform().getX509Certificate(certAmend);
228                if (checkAndAddCertificate(md, cert, certAmend, keyStore)) {
229                    certificateAdded = true;
230                }
231            }
232        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException | IllegalStateException e) {
233            Logging.error(e);
234        }
235
236        if (certificateAdded) {
237            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
238            tmf.init(keyStore);
239            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
240            sslContext.init(null, tmf.getTrustManagers(), null);
241            SSLContext.setDefault(sslContext);
242        }
243    }
244
245    private static boolean checkAndAddCertificate(MessageDigest md, X509Certificate cert, CertAmend certAmend, KeyStore keyStore)
246            throws CertificateEncodingException, KeyStoreException, InvalidAlgorithmParameterException {
247        if (cert != null) {
248            String sha256 = Utils.toHexString(md.digest(cert.getEncoded()));
249            if (!certAmend.sha256.equals(sha256)) {
250                throw new IllegalStateException(
251                        tr("Error adding certificate {0} - certificate fingerprint mismatch. Expected {1}, was {2}",
252                            certAmend, certAmend.sha256, sha256));
253            }
254            if (certificateIsMissing(keyStore, cert)) {
255                if (Logging.isDebugEnabled()) {
256                    Logging.debug(tr("Adding certificate for TLS connections: {0}", cert.getSubjectX500Principal().getName()));
257                }
258                String alias = "josm:" + certAmend.filename;
259                keyStore.setCertificateEntry(alias, cert);
260                return true;
261            }
262        }
263        return false;
264    }
265
266    /**
267     * Check if the certificate is missing and needs to be added to the keystore.
268     * @param keyStore the keystore
269     * @param crt the certificate
270     * @return true, if the certificate is not contained in the keystore
271     * @throws InvalidAlgorithmParameterException if the keystore does not contain at least one trusted certificate entry
272     * @throws KeyStoreException if the keystore has not been initialized
273     */
274    private static boolean certificateIsMissing(KeyStore keyStore, X509Certificate crt)
275            throws KeyStoreException, InvalidAlgorithmParameterException {
276        PKIXParameters params = new PKIXParameters(keyStore);
277        String id = crt.getSubjectX500Principal().getName();
278        for (TrustAnchor ta : params.getTrustAnchors()) {
279            X509Certificate cert = ta.getTrustedCert();
280            if (Objects.equals(id, cert.getSubjectX500Principal().getName()))
281                return false;
282        }
283        return true;
284    }
285}