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.Collection;
025import java.util.Collections;
026import java.util.Objects;
027
028import javax.net.ssl.SSLContext;
029import javax.net.ssl.TrustManagerFactory;
030
031import org.openstreetmap.josm.spi.preferences.Config;
032import org.openstreetmap.josm.tools.Logging;
033import org.openstreetmap.josm.tools.PlatformManager;
034import org.openstreetmap.josm.tools.Utils;
035
036/**
037 * Class to add missing root certificates to the list of trusted certificates
038 * for TLS connections.
039 *
040 * The added certificates are deemed trustworthy by the main web browsers and
041 * operating systems, but not included in some distributions of Java.
042 *
043 * The certificates are added in-memory at each start, nothing is written to disk.
044 * @since 9995
045 */
046public final class CertificateAmendment {
047
048    /**
049     * A certificate amendment.
050     * @since 11943
051     */
052    public static class CertAmend {
053        private final String filename;
054        private final String sha256;
055
056        protected CertAmend(String filename, String sha256) {
057            this.filename = Objects.requireNonNull(filename);
058            this.sha256 = Objects.requireNonNull(sha256);
059        }
060
061        /**
062         * Returns the certificate filename.
063         * @return filename for both JOSM embedded certificate and Unix platform certificate
064         * @since 12241
065         */
066        public final String getFilename() {
067            return filename;
068        }
069
070        /**
071         * Returns the SHA-256 hash.
072         * @return the SHA-256 hash, in hexadecimal
073         */
074        public final String getSha256() {
075            return sha256;
076        }
077    }
078
079    /**
080     * An embedded certificate amendment.
081     * @since 13450
082     */
083    public static class EmbeddedCertAmend extends CertAmend {
084        private final String url;
085
086        EmbeddedCertAmend(String url, String filename, String sha256) {
087            super(filename, sha256);
088            this.url = Objects.requireNonNull(url);
089        }
090
091        /**
092         * Returns the embedded URL in JOSM jar.
093         * @return path for JOSM embedded certificate
094         */
095        public final String getUrl() {
096            return url;
097        }
098
099        @Override
100        public String toString() {
101            return url;
102        }
103    }
104
105    /**
106     * A certificate amendment relying on native platform certificate store.
107     * @since 13450
108     */
109    public static class NativeCertAmend extends CertAmend {
110        private final Collection<String> aliases;
111        private final String httpsWebSite;
112
113        NativeCertAmend(Collection<String> aliases, String filename, String sha256, String httpsWebSite) {
114            super(filename, sha256);
115            this.aliases = Objects.requireNonNull(aliases);
116            this.httpsWebSite = Objects.requireNonNull(httpsWebSite);
117        }
118
119        /**
120         * Returns the native aliases in System Root Certificates keystore/keychain.
121         * @return the native aliases in System Root Certificates keystore/keychain
122         * @since 15006
123         */
124        public final Collection<String> getNativeAliases() {
125            return aliases;
126        }
127
128        /**
129         * Returns the https website we need to call to notify Windows we need its root certificate.
130         * @return the https website signed with this root CA
131         * @since 13451
132         */
133        public String getWebSite() {
134            return httpsWebSite;
135        }
136
137        @Override
138        public String toString() {
139            return String.join(" / ", aliases);
140        }
141    }
142
143    /**
144     * Certificates embedded in JOSM
145     */
146    private static final EmbeddedCertAmend[] CERT_AMEND = {
147    };
148
149    /**
150     * Certificates looked into platform native keystore and not embedded in JOSM.
151     * Identifiers must match Windows/macOS keystore aliases and Unix filenames for efficient search.
152     * To find correct values, see:<ul>
153     * <li><a href="https://ccadb.my.salesforce-sites.com/mozilla/includedcacertificatereport">Mozilla List</a></li>
154     * <li><a href="https://ccadb.my.salesforce-sites.com/microsoft/includedcacertificatereportformsft">Microsoft List</a></li>
155     * <li><a href="https://support.apple.com/en-us/HT210770">Apple List</a></li>
156     * </ul>
157     */
158    private static final NativeCertAmend[] PLATFORM_CERT_AMEND = {
159        // #15178 - Trusted and used by French Government - for cadastre - https://www.certigna.fr/autorites/index.xhtml?ac=Racine#lracine
160        // (expires 2027, should be in Java 21)
161        new NativeCertAmend(Collections.singleton("Certigna"),
162                "Certigna.crt",
163                "e3b6a2db2ed7ce48842f7ac53241c7b71d54144bfb40c11f3f1d0b42f5eea12d",
164                "https://www.certigna.fr"),
165        // #16307 - Trusted and used by Slovakian Government - https://eidas.disig.sk/en/cacert/ (expires 2042)
166        new NativeCertAmend(Collections.singleton("CA Disig Root R2"),
167                "CA_Disig_Root_R2.pem",
168                "e23d4a036d7b70e9f595b1422079d2b91edfbb1fb651a0633eaa8a9dc5f80703",
169                "https://eidas.disig.sk"),
170        // #17668 - used by city of Budapest - for https://terinfo.ujbuda.hu - https://e-szigno.hu/ (expires 2029)
171        new NativeCertAmend(Collections.singleton("MicroSec e-Szigno Root CA 2009"),
172                "Microsec_e-Szigno_Root_CA_2009.pem",
173                "3c5f81fea5fab82c64bfa2eaecafcde8e077fc8620a7cae537163df36edbf378",
174                "https://e-szigno.hu"),
175        // #18920 - Spanish Government - https://www.sede.fnmt.gob.es/descargas/certificados-raiz-de-la-fnmt (expires 2030)
176        new NativeCertAmend(Collections.singleton("AC RAIZ FNMT-RCM"),
177                "AC_RAIZ_FNMT-RCM.pem",
178                "ebc5570c29018c4d67b1aa127baf12f703b4611ebc17b7dab5573894179b93fa",
179                "https://www.sede.fnmt.gob.es"),
180        // #24580 - Greek Research - https://repo.harica.gr (expires 2029)
181        new NativeCertAmend(Collections.singleton("HARICA TLS RSA Root CA 2021"),
182                "HARICA_TLS_RSA_Root_CA_2021.pem",
183                "d95d0e8eda79525bf9beb11b14d2100d3294985f0c62d9fabd9cd999eccb7b1d",
184                "https://www.harica.gr"),
185    };
186
187    private CertificateAmendment() {
188        // Hide default constructor for utility classes
189    }
190
191    /**
192     * Add missing root certificates to the list of trusted certificates for TLS connections.
193     * @throws IOException if an I/O error occurs
194     * @throws GeneralSecurityException if a security error occurs
195     */
196    public static void addMissingCertificates() throws IOException, GeneralSecurityException {
197        if (!Config.getPref().getBoolean("tls.add-missing-certificates", true))
198            return;
199        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
200        Path cacertsPath = Paths.get(Utils.getSystemProperty("java.home"), "lib", "security", "cacerts");
201        try (InputStream is = Files.newInputStream(cacertsPath)) {
202            keyStore.load(is, "changeit".toCharArray());
203        } catch (SecurityException e) {
204            Logging.log(Logging.LEVEL_ERROR, "Unable to load keystore", e);
205            return;
206        }
207
208        MessageDigest md = MessageDigest.getInstance("SHA-256");
209        CertificateFactory cf = CertificateFactory.getInstance("X.509");
210        boolean certificateAdded = false;
211        // Add embedded certificates. Exit in case of error
212        for (EmbeddedCertAmend certAmend : CERT_AMEND) {
213            try (CachedFile certCF = new CachedFile(certAmend.url)) {
214                X509Certificate cert = (X509Certificate) cf.generateCertificate(
215                        new ByteArrayInputStream(certCF.getByteContent()));
216                if (checkAndAddCertificate(md, cert, certAmend, keyStore)) {
217                    certificateAdded = true;
218                }
219            }
220        }
221
222        try {
223            // Try to add platform certificates. Do not exit in case of error (embedded certificates may be OK)
224            for (NativeCertAmend certAmend : PLATFORM_CERT_AMEND) {
225                X509Certificate cert = PlatformManager.getPlatform().getX509Certificate(certAmend);
226                if (checkAndAddCertificate(md, cert, certAmend, keyStore)) {
227                    certificateAdded = true;
228                }
229            }
230        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException | IllegalStateException e) {
231            Logging.error(e);
232        }
233
234        if (certificateAdded) {
235            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
236            tmf.init(keyStore);
237            SSLContext sslContext = SSLContext.getInstance("TLSv1.3");
238            sslContext.init(null, tmf.getTrustManagers(), null);
239            SSLContext.setDefault(sslContext);
240        }
241    }
242
243    private static boolean checkAndAddCertificate(MessageDigest md, X509Certificate cert, CertAmend certAmend, KeyStore keyStore)
244            throws CertificateEncodingException, KeyStoreException, InvalidAlgorithmParameterException {
245        if (cert != null) {
246            String sha256 = Utils.toHexString(md.digest(cert.getEncoded()));
247            if (!certAmend.sha256.equals(sha256)) {
248                throw new IllegalStateException(
249                        tr("Error adding certificate {0} - certificate fingerprint mismatch. Expected {1}, was {2}",
250                            certAmend, certAmend.sha256, sha256));
251            }
252            if (certificateIsMissing(keyStore, cert)) {
253                if (Logging.isDebugEnabled()) {
254                    Logging.debug("Adding certificate for TLS connections: " + cert.getSubjectX500Principal().getName());
255                }
256                String alias = "josm:" + certAmend.filename;
257                keyStore.setCertificateEntry(alias, cert);
258                return true;
259            }
260        }
261        return false;
262    }
263
264    /**
265     * Check if the certificate is missing and needs to be added to the keystore.
266     * @param keyStore the keystore
267     * @param crt the certificate
268     * @return true, if the certificate is not contained in the keystore
269     * @throws InvalidAlgorithmParameterException if the keystore does not contain at least one trusted certificate entry
270     * @throws KeyStoreException if the keystore has not been initialized
271     */
272    private static boolean certificateIsMissing(KeyStore keyStore, X509Certificate crt)
273            throws KeyStoreException, InvalidAlgorithmParameterException {
274        PKIXParameters params = new PKIXParameters(keyStore);
275        return params.getTrustAnchors().stream()
276                .map(TrustAnchor::getTrustedCert)
277                .noneMatch(c -> Objects.equals(crt.getSubjectX500Principal().getName(), c.getSubjectX500Principal().getName()));
278    }
279}