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        // #14649 - Government of Netherlands - for PDOK aerial imagery at ​https://geodata.nationaalgeoregister.nl
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        // #14649 - Government of Netherlands - for PDOK aerial imagery at ​https://geodata.nationaalgeoregister.nl
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        // #15178 - Trusted and used by French Government - for cadastre - 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        // #16307 - 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        // #17062 - Government of Taiwan - for https://data.gov.tw/license - 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        // #17668 - used by city of Budapest - for https://terinfo.ujbuda.hu - https://e-szigno.hu/
188        new NativeCertAmend(Collections.singleton("MicroSec e-Szigno Root CA 2009"),
189                "Microsec_e-Szigno_Root_CA_2009.pem",
190                "3c5f81fea5fab82c64bfa2eaecafcde8e077fc8620a7cae537163df36edbf378",
191                "https://e-szigno.hu"),
192    };
193
194    private CertificateAmendment() {
195        // Hide default constructor for utility classes
196    }
197
198    /**
199     * Add missing root certificates to the list of trusted certificates for TLS connections.
200     * @throws IOException if an I/O error occurs
201     * @throws GeneralSecurityException if a security error occurs
202     */
203    public static void addMissingCertificates() throws IOException, GeneralSecurityException {
204        if (!Config.getPref().getBoolean("tls.add-missing-certificates", true))
205            return;
206        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
207        Path cacertsPath = Paths.get(Utils.getSystemProperty("java.home"), "lib", "security", "cacerts");
208        try (InputStream is = Files.newInputStream(cacertsPath)) {
209            keyStore.load(is, "changeit".toCharArray());
210        } catch (SecurityException e) {
211            Logging.log(Logging.LEVEL_ERROR, "Unable to load keystore", e);
212            return;
213        }
214
215        MessageDigest md = MessageDigest.getInstance("SHA-256");
216        CertificateFactory cf = CertificateFactory.getInstance("X.509");
217        boolean certificateAdded = false;
218        // Add embedded certificates. Exit in case of error
219        for (EmbeddedCertAmend certAmend : CERT_AMEND) {
220            try (CachedFile certCF = new CachedFile(certAmend.url)) {
221                X509Certificate cert = (X509Certificate) cf.generateCertificate(
222                        new ByteArrayInputStream(certCF.getByteContent()));
223                if (checkAndAddCertificate(md, cert, certAmend, keyStore)) {
224                    certificateAdded = true;
225                }
226            }
227        }
228
229        try {
230            // Try to add platform certificates. Do not exit in case of error (embedded certificates may be OK)
231            for (NativeCertAmend certAmend : PLATFORM_CERT_AMEND) {
232                X509Certificate cert = PlatformManager.getPlatform().getX509Certificate(certAmend);
233                if (checkAndAddCertificate(md, cert, certAmend, keyStore)) {
234                    certificateAdded = true;
235                }
236            }
237        } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException | IllegalStateException e) {
238            Logging.error(e);
239        }
240
241        if (certificateAdded) {
242            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
243            tmf.init(keyStore);
244            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
245            sslContext.init(null, tmf.getTrustManagers(), null);
246            SSLContext.setDefault(sslContext);
247        }
248    }
249
250    private static boolean checkAndAddCertificate(MessageDigest md, X509Certificate cert, CertAmend certAmend, KeyStore keyStore)
251            throws CertificateEncodingException, KeyStoreException, InvalidAlgorithmParameterException {
252        if (cert != null) {
253            String sha256 = Utils.toHexString(md.digest(cert.getEncoded()));
254            if (!certAmend.sha256.equals(sha256)) {
255                throw new IllegalStateException(
256                        tr("Error adding certificate {0} - certificate fingerprint mismatch. Expected {1}, was {2}",
257                            certAmend, certAmend.sha256, sha256));
258            }
259            if (certificateIsMissing(keyStore, cert)) {
260                if (Logging.isDebugEnabled()) {
261                    Logging.debug(tr("Adding certificate for TLS connections: {0}", cert.getSubjectX500Principal().getName()));
262                }
263                String alias = "josm:" + certAmend.filename;
264                keyStore.setCertificateEntry(alias, cert);
265                return true;
266            }
267        }
268        return false;
269    }
270
271    /**
272     * Check if the certificate is missing and needs to be added to the keystore.
273     * @param keyStore the keystore
274     * @param crt the certificate
275     * @return true, if the certificate is not contained in the keystore
276     * @throws InvalidAlgorithmParameterException if the keystore does not contain at least one trusted certificate entry
277     * @throws KeyStoreException if the keystore has not been initialized
278     */
279    private static boolean certificateIsMissing(KeyStore keyStore, X509Certificate crt)
280            throws KeyStoreException, InvalidAlgorithmParameterException {
281        PKIXParameters params = new PKIXParameters(keyStore);
282        String id = crt.getSubjectX500Principal().getName();
283        for (TrustAnchor ta : params.getTrustAnchors()) {
284            X509Certificate cert = ta.getTrustedCert();
285            if (Objects.equals(id, cert.getSubjectX500Principal().getName()))
286                return false;
287        }
288        return true;
289    }
290}