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:<ul>
154     * <li><a href="https://ccadb-public.secure.force.com/mozilla/IncludedCACertificateReport">Mozilla List</a></li>
155     * <li><a href="https://ccadb-public.secure.force.com/microsoft/IncludedCACertificateReportForMSFT">Microsoft List</a></li>
156     * <li><a href="https://support.apple.com/en-us/HT210770">Apple List</a></li>
157     * </ul>
158     */
159    private static final NativeCertAmend[] PLATFORM_CERT_AMEND = {
160        // Let's Encrypt - should be included in JDK, but problems with Ubuntu 18.04, see #15851
161        new NativeCertAmend(Collections.singleton("DST Root CA X3"),
162                "DST_Root_CA_X3.pem",
163                "0687260331a72403d909f105e69bcf0d32e1bd2493ffc6d9206d11bcd6770739",
164                "https://acme-v02.api.letsencrypt.org"),
165        // #19872 - Government of Netherlands - for PDOK aerial imagery at ​https://geodata.nationaalgeoregister.nl
166        new NativeCertAmend(Collections.singleton("Staat der Nederlanden EV Root CA"),
167                "Staat_der_Nederlanden_EV_Root_CA.crt",
168                "4d2491414cfe956746ec4cefa6cf6f72e28a1329432f9d8a907ac4cb5dadc15a",
169                "https://roottest-ev.pkioverheid.nl"),
170        // #14649 - Government of Netherlands - for PDOK aerial imagery at ​https://geodata.nationaalgeoregister.nl
171        new NativeCertAmend(Arrays.asList("Government of Netherlands G3", "Staat der Nederlanden Root CA - G3"),
172                "Staat_der_Nederlanden_Root_CA_-_G3.crt",
173                "3c4fb0b95ab8b30032f432b86f535fe172c185d0fd39865837cf36187fa6f428",
174                "https://roottest-g3.pkioverheid.nl"),
175        // #15178 - Trusted and used by French Government - for cadastre - https://www.certigna.fr/autorites/index.xhtml?ac=Racine#lracine
176        new NativeCertAmend(Collections.singleton("Certigna"),
177                "Certigna.crt",
178                "e3b6a2db2ed7ce48842f7ac53241c7b71d54144bfb40c11f3f1d0b42f5eea12d",
179                "https://www.certigna.fr"),
180        // #16307 - Trusted and used by Slovakian Government - https://eidas.disig.sk/en/cacert/
181        new NativeCertAmend(Collections.singleton("CA Disig Root R2"),
182                "CA_Disig_Root_R2.pem",
183                "e23d4a036d7b70e9f595b1422079d2b91edfbb1fb651a0633eaa8a9dc5f80703",
184                "https://eidas.disig.sk"),
185        // #17062 - Government of Taiwan - for https://data.gov.tw/license - https://grca.nat.gov.tw/GRCAeng/index.html
186        new NativeCertAmend(Arrays.asList("TW Government Root Certification Authority", "Government Root Certification Authority"),
187                "Taiwan_GRCA.pem",
188                "7600295eefe85b9e1fd624db76062aaaae59818a54d2774cd4c0b2c01131e1b3",
189                "https://grca.nat.gov.tw"),
190        // #17668 - used by city of Budapest - for https://terinfo.ujbuda.hu - https://e-szigno.hu/
191        new NativeCertAmend(Collections.singleton("MicroSec e-Szigno Root CA 2009"),
192                "Microsec_e-Szigno_Root_CA_2009.pem",
193                "3c5f81fea5fab82c64bfa2eaecafcde8e077fc8620a7cae537163df36edbf378",
194                "https://e-szigno.hu"),
195        // #18920 - Spanish Government - https://www.sede.fnmt.gob.es/descargas/certificados-raiz-de-la-fnmt
196        new NativeCertAmend(Collections.singleton("AC RAIZ FNMT-RCM"),
197                "AC_RAIZ_FNMT-RCM.pem",
198                "ebc5570c29018c4d67b1aa127baf12f703b4611ebc17b7dab5573894179b93fa",
199                "https://www.sede.fnmt.gob.es"),
200    };
201
202    private CertificateAmendment() {
203        // Hide default constructor for utility classes
204    }
205
206    /**
207     * Add missing root certificates to the list of trusted certificates for TLS connections.
208     * @throws IOException if an I/O error occurs
209     * @throws GeneralSecurityException if a security error occurs
210     */
211    public static void addMissingCertificates() throws IOException, GeneralSecurityException {
212        if (!Config.getPref().getBoolean("tls.add-missing-certificates", true))
213            return;
214        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
215        Path cacertsPath = Paths.get(Utils.getSystemProperty("java.home"), "lib", "security", "cacerts");
216        try (InputStream is = Files.newInputStream(cacertsPath)) {
217            keyStore.load(is, "changeit".toCharArray());
218        } catch (SecurityException e) {
219            Logging.log(Logging.LEVEL_ERROR, "Unable to load keystore", e);
220            return;
221        }
222
223        MessageDigest md = MessageDigest.getInstance("SHA-256");
224        CertificateFactory cf = CertificateFactory.getInstance("X.509");
225        boolean certificateAdded = false;
226        // Add embedded certificates. Exit in case of error
227        for (EmbeddedCertAmend certAmend : CERT_AMEND) {
228            try (CachedFile certCF = new CachedFile(certAmend.url)) {
229                X509Certificate cert = (X509Certificate) cf.generateCertificate(
230                        new ByteArrayInputStream(certCF.getByteContent()));
231                if (checkAndAddCertificate(md, cert, certAmend, keyStore)) {
232                    certificateAdded = true;
233                }
234            }
235        }
236
237        try {
238            // Try to add platform certificates. Do not exit in case of error (embedded certificates may be OK)
239            for (NativeCertAmend certAmend : PLATFORM_CERT_AMEND) {
240                X509Certificate cert = PlatformManager.getPlatform().getX509Certificate(certAmend);
241                if (checkAndAddCertificate(md, cert, certAmend, keyStore)) {
242                    certificateAdded = true;
243                }
244            }
245        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException | IllegalStateException e) {
246            Logging.error(e);
247        }
248
249        if (certificateAdded) {
250            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
251            tmf.init(keyStore);
252            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
253            sslContext.init(null, tmf.getTrustManagers(), null);
254            SSLContext.setDefault(sslContext);
255        }
256    }
257
258    private static boolean checkAndAddCertificate(MessageDigest md, X509Certificate cert, CertAmend certAmend, KeyStore keyStore)
259            throws CertificateEncodingException, KeyStoreException, InvalidAlgorithmParameterException {
260        if (cert != null) {
261            String sha256 = Utils.toHexString(md.digest(cert.getEncoded()));
262            if (!certAmend.sha256.equals(sha256)) {
263                throw new IllegalStateException(
264                        tr("Error adding certificate {0} - certificate fingerprint mismatch. Expected {1}, was {2}",
265                            certAmend, certAmend.sha256, sha256));
266            }
267            if (certificateIsMissing(keyStore, cert)) {
268                if (Logging.isDebugEnabled()) {
269                    Logging.debug("Adding certificate for TLS connections: " + cert.getSubjectX500Principal().getName());
270                }
271                String alias = "josm:" + certAmend.filename;
272                keyStore.setCertificateEntry(alias, cert);
273                return true;
274            }
275        }
276        return false;
277    }
278
279    /**
280     * Check if the certificate is missing and needs to be added to the keystore.
281     * @param keyStore the keystore
282     * @param crt the certificate
283     * @return true, if the certificate is not contained in the keystore
284     * @throws InvalidAlgorithmParameterException if the keystore does not contain at least one trusted certificate entry
285     * @throws KeyStoreException if the keystore has not been initialized
286     */
287    private static boolean certificateIsMissing(KeyStore keyStore, X509Certificate crt)
288            throws KeyStoreException, InvalidAlgorithmParameterException {
289        PKIXParameters params = new PKIXParameters(keyStore);
290        return params.getTrustAnchors().stream()
291                .map(TrustAnchor::getTrustedCert)
292                .noneMatch(c -> Objects.equals(crt.getSubjectX500Principal().getName(), c.getSubjectX500Principal().getName()));
293    }
294}