MemorizingTrustManager.java

  1/* MemorizingTrustManager - a TrustManager which asks the user about invalid
  2 *  certificates and memorizes their decision.
  3 *
  4 * Copyright (c) 2010 Georg Lukas <georg@op-co.de>
  5 *
  6 * MemorizingTrustManager.java contains the actual trust manager and interface
  7 * code to create a MemorizingActivity and obtain the results.
  8 *
  9 * Permission is hereby granted, free of charge, to any person obtaining a copy
 10 * of this software and associated documentation files (the "Software"), to deal
 11 * in the Software without restriction, including without limitation the rights
 12 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 13 * copies of the Software, and to permit persons to whom the Software is
 14 * furnished to do so, subject to the following conditions:
 15 *
 16 * The above copyright notice and this permission notice shall be included in
 17 * all copies or substantial portions of the Software.
 18 *
 19 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 20 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 21 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 22 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 23 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 24 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 25 * THE SOFTWARE.
 26 */
 27package eu.siacs.conversations.services;
 28
 29import android.app.Application;
 30import android.app.NotificationManager;
 31import android.app.Service;
 32import android.content.Context;
 33import android.content.Intent;
 34import android.net.Uri;
 35import android.os.Handler;
 36import android.preference.PreferenceManager;
 37import android.util.Base64;
 38import android.util.Log;
 39import android.util.SparseArray;
 40
 41import androidx.appcompat.app.AppCompatActivity;
 42
 43import org.json.JSONArray;
 44import org.json.JSONException;
 45import org.json.JSONObject;
 46
 47import java.io.BufferedReader;
 48import java.io.File;
 49import java.io.FileInputStream;
 50import java.io.FileNotFoundException;
 51import java.io.FileOutputStream;
 52import java.io.IOException;
 53import java.io.InputStream;
 54import java.io.InputStreamReader;
 55import java.net.URL;
 56import java.security.KeyStore;
 57import java.security.KeyStoreException;
 58import java.security.MessageDigest;
 59import java.security.NoSuchAlgorithmException;
 60import java.security.cert.Certificate;
 61import java.security.cert.CertificateEncodingException;
 62import java.security.cert.CertificateException;
 63import java.security.cert.CertificateExpiredException;
 64import java.security.cert.CertificateParsingException;
 65import java.security.cert.X509Certificate;
 66import java.text.SimpleDateFormat;
 67import java.util.ArrayList;
 68import java.util.Collection;
 69import java.util.Enumeration;
 70import java.util.List;
 71import java.util.Locale;
 72import java.util.logging.Level;
 73import java.util.logging.Logger;
 74import java.util.regex.Pattern;
 75
 76import javax.net.ssl.HostnameVerifier;
 77import javax.net.ssl.HttpsURLConnection;
 78import javax.net.ssl.SSLSession;
 79import javax.net.ssl.TrustManager;
 80import javax.net.ssl.TrustManagerFactory;
 81import javax.net.ssl.X509TrustManager;
 82
 83import eu.siacs.conversations.R;
 84import eu.siacs.conversations.crypto.DomainHostnameVerifier;
 85import eu.siacs.conversations.entities.MTMDecision;
 86import eu.siacs.conversations.persistance.FileBackend;
 87import eu.siacs.conversations.ui.MemorizingActivity;
 88
 89/**
 90 * A X509 trust manager implementation which asks the user about invalid
 91 * certificates and memorizes their decision.
 92 * <p>
 93 * The certificate validity is checked using the system default X509
 94 * TrustManager, creating a query Dialog if the check fails.
 95 * <p>
 96 * <b>WARNING:</b> This only works if a dedicated thread is used for
 97 * opening sockets!
 98 */
 99public class MemorizingTrustManager {
100
101
102    final static String DECISION_INTENT = "de.duenndns.ssl.DECISION";
103    public final static String DECISION_INTENT_ID = DECISION_INTENT + ".decisionId";
104    public final static String DECISION_INTENT_CERT = DECISION_INTENT + ".cert";
105    public final static String DECISION_TITLE_ID = DECISION_INTENT + ".titleId";
106    final static String DECISION_INTENT_CHOICE = DECISION_INTENT + ".decisionChoice";
107    final static String NO_TRUST_ANCHOR = "Trust anchor for certification path not found.";
108    private static final Pattern PATTERN_IPV4 = Pattern.compile("\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
109    private static final Pattern PATTERN_IPV6_HEX4DECCOMPRESSED = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?) ::((?:[0-9A-Fa-f]{1,4}:)*)(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
110    private static final Pattern PATTERN_IPV6_6HEX4DEC = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}:){6,6})(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z");
111    private static final Pattern PATTERN_IPV6_HEXCOMPRESSED = Pattern.compile("\\A((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)::((?:[0-9A-Fa-f]{1,4}(?::[0-9A-Fa-f]{1,4})*)?)\\z");
112    private static final Pattern PATTERN_IPV6 = Pattern.compile("\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z");
113    private final static Logger LOGGER = Logger.getLogger(MemorizingTrustManager.class.getName());
114    private final static int NOTIFICATION_ID = 100509;
115    static String KEYSTORE_DIR = "KeyStore";
116    static String KEYSTORE_FILE = "KeyStore.bks";
117    private static int decisionId = 0;
118    private static final SparseArray<MTMDecision> openDecisions = new SparseArray<MTMDecision>();
119    Context master;
120    AppCompatActivity foregroundAct;
121    NotificationManager notificationManager;
122    Handler masterHandler;
123    private File keyStoreFile;
124    private KeyStore appKeyStore;
125    private final X509TrustManager defaultTrustManager;
126    private X509TrustManager appTrustManager;
127    private String poshCacheDir;
128
129    /**
130     * Creates an instance of the MemorizingTrustManager class that falls back to a custom TrustManager.
131     * <p>
132     * You need to supply the application context. This has to be one of:
133     * - Application
134     * - Activity
135     * - Service
136     * <p>
137     * The context is used for file management, to display the dialog /
138     * notification and for obtaining translated strings.
139     *
140     * @param m                   Context for the application.
141     * @param defaultTrustManager Delegate trust management to this TM. If null, the user must accept every certificate.
142     */
143    public MemorizingTrustManager(Context m, X509TrustManager defaultTrustManager) {
144        init(m);
145        this.appTrustManager = getTrustManager(appKeyStore);
146        this.defaultTrustManager = defaultTrustManager;
147    }
148
149    /**
150     * Creates an instance of the MemorizingTrustManager class using the system X509TrustManager.
151     * <p>
152     * You need to supply the application context. This has to be one of:
153     * - Application
154     * - Activity
155     * - Service
156     * <p>
157     * The context is used for file management, to display the dialog /
158     * notification and for obtaining translated strings.
159     *
160     * @param m Context for the application.
161     */
162    public MemorizingTrustManager(Context m) {
163        init(m);
164        this.appTrustManager = getTrustManager(appKeyStore);
165        this.defaultTrustManager = getTrustManager(null);
166    }
167
168    /**
169     * Changes the path for the KeyStore file.
170     * <p>
171     * The actual filename relative to the app's directory will be
172     * <code>app_<i>dirname</i>/<i>filename</i></code>.
173     *
174     * @param dirname  directory to store the KeyStore.
175     * @param filename file name for the KeyStore.
176     */
177    public static void setKeyStoreFile(String dirname, String filename) {
178        KEYSTORE_DIR = dirname;
179        KEYSTORE_FILE = filename;
180    }
181
182    private static boolean isIp(final String server) {
183        return server != null && (
184                PATTERN_IPV4.matcher(server).matches()
185                        || PATTERN_IPV6.matcher(server).matches()
186                        || PATTERN_IPV6_6HEX4DEC.matcher(server).matches()
187                        || PATTERN_IPV6_HEX4DECCOMPRESSED.matcher(server).matches()
188                        || PATTERN_IPV6_HEXCOMPRESSED.matcher(server).matches());
189    }
190
191    private static String getBase64Hash(X509Certificate certificate, String digest) throws CertificateEncodingException {
192        MessageDigest md;
193        try {
194            md = MessageDigest.getInstance(digest);
195        } catch (NoSuchAlgorithmException e) {
196            return null;
197        }
198        md.update(certificate.getEncoded());
199        return Base64.encodeToString(md.digest(), Base64.NO_WRAP);
200    }
201
202    private static String hexString(byte[] data) {
203        StringBuffer si = new StringBuffer();
204        for (int i = 0; i < data.length; i++) {
205            si.append(String.format("%02x", data[i]));
206            if (i < data.length - 1)
207                si.append(":");
208        }
209        return si.toString();
210    }
211
212    private static String certHash(final X509Certificate cert, String digest) {
213        try {
214            MessageDigest md = MessageDigest.getInstance(digest);
215            md.update(cert.getEncoded());
216            return hexString(md.digest());
217        } catch (java.security.cert.CertificateEncodingException e) {
218            return e.getMessage();
219        } catch (java.security.NoSuchAlgorithmException e) {
220            return e.getMessage();
221        }
222    }
223
224    public static void interactResult(int decisionId, int choice) {
225        MTMDecision d;
226        synchronized (openDecisions) {
227            d = openDecisions.get(decisionId);
228            openDecisions.remove(decisionId);
229        }
230        if (d == null) {
231            LOGGER.log(Level.SEVERE, "interactResult: aborting due to stale decision reference!");
232            return;
233        }
234        synchronized (d) {
235            d.state = choice;
236            d.notify();
237        }
238    }
239
240    void init(Context m) {
241        master = m;
242        masterHandler = new Handler(m.getMainLooper());
243        notificationManager = (NotificationManager) master.getSystemService(Context.NOTIFICATION_SERVICE);
244
245        Application app;
246        if (m instanceof Application) {
247            app = (Application) m;
248        } else if (m instanceof Service) {
249            app = ((Service) m).getApplication();
250        } else if (m instanceof AppCompatActivity) {
251            app = ((AppCompatActivity) m).getApplication();
252        } else
253            throw new ClassCastException("MemorizingTrustManager context must be either Activity or Service!");
254
255        File dir = app.getDir(KEYSTORE_DIR, Context.MODE_PRIVATE);
256        keyStoreFile = new File(dir + File.separator + KEYSTORE_FILE);
257
258        poshCacheDir = app.getCacheDir().getAbsolutePath() + "/posh_cache/";
259
260        appKeyStore = loadAppKeyStore();
261    }
262
263    /**
264     * Binds an Activity to the MTM for displaying the query dialog.
265     * <p>
266     * This is useful if your connection is run from a service that is
267     * triggered by user interaction -- in such cases the activity is
268     * visible and the user tends to ignore the service notification.
269     * <p>
270     * You should never have a hidden activity bound to MTM! Use this
271     * function in onResume() and @see unbindDisplayActivity in onPause().
272     *
273     * @param act Activity to be bound
274     */
275    public void bindDisplayActivity(AppCompatActivity act) {
276        foregroundAct = act;
277    }
278
279    /**
280     * Removes an Activity from the MTM display stack.
281     * <p>
282     * Always call this function when the Activity added with
283     * {@link #bindDisplayActivity(AppCompatActivity)} is hidden.
284     *
285     * @param act Activity to be unbound
286     */
287    public void unbindDisplayActivity(AppCompatActivity act) {
288        // do not remove if it was overridden by a different activity
289        if (foregroundAct == act)
290            foregroundAct = null;
291    }
292
293    /**
294     * Get a list of all certificate aliases stored in MTM.
295     *
296     * @return an {@link Enumeration} of all certificates
297     */
298    public Enumeration<String> getCertificates() {
299        try {
300            return appKeyStore.aliases();
301        } catch (KeyStoreException e) {
302            // this should never happen, however...
303            throw new RuntimeException(e);
304        }
305    }
306
307    /**
308     * Get a certificate for a given alias.
309     *
310     * @param alias the certificate's alias as returned by {@link #getCertificates()}.
311     * @return the certificate associated with the alias or <tt>null</tt> if none found.
312     */
313    public Certificate getCertificate(String alias) {
314        try {
315            return appKeyStore.getCertificate(alias);
316        } catch (KeyStoreException e) {
317            // this should never happen, however...
318            throw new RuntimeException(e);
319        }
320    }
321
322    /**
323     * Removes the given certificate from MTMs key store.
324     *
325     * <p>
326     * <b>WARNING</b>: this does not immediately invalidate the certificate. It is
327     * well possible that (a) data is transmitted over still existing connections or
328     * (b) new connections are created using TLS renegotiation, without a new cert
329     * check.
330     * </p>
331     *
332     * @param alias the certificate's alias as returned by {@link #getCertificates()}.
333     * @throws KeyStoreException if the certificate could not be deleted.
334     */
335    public void deleteCertificate(String alias) throws KeyStoreException {
336        appKeyStore.deleteEntry(alias);
337        keyStoreUpdated();
338    }
339
340    /**
341     * Creates a new hostname verifier supporting user interaction.
342     *
343     * <p>This method creates a new {@link HostnameVerifier} that is bound to
344     * the given instance of {@link MemorizingTrustManager}, and leverages an
345     * existing {@link HostnameVerifier}. The returned verifier performs the
346     * following steps, returning as soon as one of them succeeds:
347     * /p>
348     * <ol>
349     * <li>Success, if the wrapped defaultVerifier accepts the certificate.</li>
350     * <li>Success, if the server certificate is stored in the keystore under the given hostname.</li>
351     * <li>Ask the user and return accordingly.</li>
352     * <li>Failure on exception.</li>
353     * </ol>
354     *
355     * @param defaultVerifier the {@link HostnameVerifier} that should perform the actual check
356     * @return a new hostname verifier using the MTM's key store
357     * @throws IllegalArgumentException if the defaultVerifier parameter is null
358     */
359    public DomainHostnameVerifier wrapHostnameVerifier(final HostnameVerifier defaultVerifier, final boolean interactive) {
360        if (defaultVerifier == null)
361            throw new IllegalArgumentException("The default verifier may not be null");
362
363        return new MemorizingHostnameVerifier(defaultVerifier, interactive);
364    }
365
366    X509TrustManager getTrustManager(KeyStore ks) {
367        try {
368            TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
369            tmf.init(ks);
370            for (TrustManager t : tmf.getTrustManagers()) {
371                if (t instanceof X509TrustManager) {
372                    return (X509TrustManager) t;
373                }
374            }
375        } catch (Exception e) {
376            // Here, we are covering up errors. It might be more useful
377            // however to throw them out of the constructor so the
378            // embedding app knows something went wrong.
379            LOGGER.log(Level.SEVERE, "getTrustManager(" + ks + ")", e);
380        }
381        return null;
382    }
383
384    KeyStore loadAppKeyStore() {
385        KeyStore ks;
386        try {
387            ks = KeyStore.getInstance(KeyStore.getDefaultType());
388        } catch (KeyStoreException e) {
389            LOGGER.log(Level.SEVERE, "getAppKeyStore()", e);
390            return null;
391        }
392        FileInputStream fileInputStream = null;
393        try {
394            ks.load(null, null);
395            fileInputStream = new FileInputStream(keyStoreFile);
396            ks.load(fileInputStream, "MTM".toCharArray());
397        } catch (java.io.FileNotFoundException e) {
398            LOGGER.log(Level.INFO, "getAppKeyStore(" + keyStoreFile + ") - file does not exist");
399        } catch (Exception e) {
400            LOGGER.log(Level.SEVERE, "getAppKeyStore(" + keyStoreFile + ")", e);
401        } finally {
402            FileBackend.close(fileInputStream);
403        }
404        return ks;
405    }
406
407    void storeCert(String alias, Certificate cert) {
408        try {
409            appKeyStore.setCertificateEntry(alias, cert);
410        } catch (KeyStoreException e) {
411            LOGGER.log(Level.SEVERE, "storeCert(" + cert + ")", e);
412            return;
413        }
414        keyStoreUpdated();
415    }
416
417    void storeCert(X509Certificate cert) {
418        storeCert(cert.getSubjectDN().toString(), cert);
419    }
420
421    void keyStoreUpdated() {
422        // reload appTrustManager
423        appTrustManager = getTrustManager(appKeyStore);
424
425        // store KeyStore to file
426        java.io.FileOutputStream fos = null;
427        try {
428            fos = new java.io.FileOutputStream(keyStoreFile);
429            appKeyStore.store(fos, "MTM".toCharArray());
430        } catch (Exception e) {
431            LOGGER.log(Level.SEVERE, "storeCert(" + keyStoreFile + ")", e);
432        } finally {
433            if (fos != null) {
434                try {
435                    fos.close();
436                } catch (IOException e) {
437                    LOGGER.log(Level.SEVERE, "storeCert(" + keyStoreFile + ")", e);
438                }
439            }
440        }
441    }
442
443    // if the certificate is stored in the app key store, it is considered "known"
444    private boolean isCertKnown(X509Certificate cert) {
445        try {
446            return appKeyStore.getCertificateAlias(cert) != null;
447        } catch (KeyStoreException e) {
448            return false;
449        }
450    }
451
452    private boolean isExpiredException(Throwable e) {
453        do {
454            if (e instanceof CertificateExpiredException)
455                return true;
456            e = e.getCause();
457        } while (e != null);
458        return false;
459    }
460
461    public void checkCertTrusted(X509Certificate[] chain, String authType, String domain, boolean isServer, boolean interactive)
462            throws CertificateException {
463        LOGGER.log(Level.FINE, "checkCertTrusted(" + chain + ", " + authType + ", " + isServer + ")");
464        try {
465            LOGGER.log(Level.FINE, "checkCertTrusted: trying appTrustManager");
466            if (isServer)
467                appTrustManager.checkServerTrusted(chain, authType);
468            else
469                appTrustManager.checkClientTrusted(chain, authType);
470        } catch (CertificateException ae) {
471            LOGGER.log(Level.FINER, "checkCertTrusted: appTrustManager failed", ae);
472            // if the cert is stored in our appTrustManager, we ignore expiredness
473            if (isExpiredException(ae)) {
474                LOGGER.log(Level.INFO, "checkCertTrusted: accepting expired certificate from keystore");
475                return;
476            }
477            if (isCertKnown(chain[0])) {
478                LOGGER.log(Level.INFO, "checkCertTrusted: accepting cert already stored in keystore");
479                return;
480            }
481            try {
482                if (defaultTrustManager == null)
483                    throw ae;
484                LOGGER.log(Level.FINE, "checkCertTrusted: trying defaultTrustManager");
485                if (isServer)
486                    defaultTrustManager.checkServerTrusted(chain, authType);
487                else
488                    defaultTrustManager.checkClientTrusted(chain, authType);
489            } catch (CertificateException e) {
490                boolean trustSystemCAs = !PreferenceManager.getDefaultSharedPreferences(master).getBoolean("dont_trust_system_cas", false);
491                if (domain != null && isServer && trustSystemCAs && !isIp(domain)) {
492                    final String hash = getBase64Hash(chain[0], "SHA-256");
493                    final List<String> fingerprints = getPoshFingerprints(domain);
494                    if (hash != null && fingerprints.size() > 0) {
495                        if (fingerprints.contains(hash)) {
496                            Log.d("mtm", "trusted cert fingerprint of " + domain + " via posh");
497                            return;
498                        }
499                        if (getPoshCacheFile(domain).delete()) {
500                            Log.d("mtm", "deleted posh file for " + domain + " after not being able to verify");
501                        }
502                    }
503                }
504                if (interactive) {
505                    interactCert(chain, authType, e);
506                } else {
507                    throw e;
508                }
509            }
510        }
511    }
512
513    private List<String> getPoshFingerprints(String domain) {
514        List<String> cached = getPoshFingerprintsFromCache(domain);
515        if (cached == null) {
516            return getPoshFingerprintsFromServer(domain);
517        } else {
518            return cached;
519        }
520    }
521
522    private List<String> getPoshFingerprintsFromServer(String domain) {
523        return getPoshFingerprintsFromServer(domain, "https://" + domain + "/.well-known/posh/xmpp-client.json", -1, true);
524    }
525
526    private List<String> getPoshFingerprintsFromServer(String domain, String url, int maxTtl, boolean followUrl) {
527        Log.d("mtm", "downloading json for " + domain + " from " + url);
528        try {
529            List<String> results = new ArrayList<>();
530            HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
531            connection.setConnectTimeout(5000);
532            connection.setReadTimeout(5000);
533            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
534            String inputLine;
535            StringBuilder builder = new StringBuilder();
536            while ((inputLine = in.readLine()) != null) {
537                builder.append(inputLine);
538            }
539            JSONObject jsonObject = new JSONObject(builder.toString());
540            in.close();
541            int expires = jsonObject.getInt("expires");
542            if (expires <= 0) {
543                return new ArrayList<>();
544            }
545            if (maxTtl >= 0) {
546                expires = Math.min(maxTtl, expires);
547            }
548            String redirect;
549            try {
550                redirect = jsonObject.getString("url");
551            } catch (JSONException e) {
552                redirect = null;
553            }
554            if (followUrl && redirect != null && redirect.toLowerCase().startsWith("https")) {
555                return getPoshFingerprintsFromServer(domain, redirect, expires, false);
556            }
557            JSONArray fingerprints = jsonObject.getJSONArray("fingerprints");
558            for (int i = 0; i < fingerprints.length(); i++) {
559                JSONObject fingerprint = fingerprints.getJSONObject(i);
560                String sha256 = fingerprint.getString("sha-256");
561                if (sha256 != null) {
562                    results.add(sha256);
563                }
564            }
565            writeFingerprintsToCache(domain, results, 1000L * expires + System.currentTimeMillis());
566            return results;
567        } catch (Exception e) {
568            Log.d("mtm", "error fetching posh " + e.getMessage());
569            return new ArrayList<>();
570        }
571    }
572
573    private File getPoshCacheFile(String domain) {
574        return new File(poshCacheDir + domain + ".json");
575    }
576
577    private void writeFingerprintsToCache(String domain, List<String> results, long expires) {
578        File file = getPoshCacheFile(domain);
579        file.getParentFile().mkdirs();
580        try {
581            file.createNewFile();
582            JSONObject jsonObject = new JSONObject();
583            jsonObject.put("expires", expires);
584            jsonObject.put("fingerprints", new JSONArray(results));
585            FileOutputStream outputStream = new FileOutputStream(file);
586            outputStream.write(jsonObject.toString().getBytes());
587            outputStream.flush();
588            outputStream.close();
589        } catch (Exception e) {
590            e.printStackTrace();
591        }
592    }
593
594    private List<String> getPoshFingerprintsFromCache(String domain) {
595        File file = getPoshCacheFile(domain);
596        try {
597            InputStream is = new FileInputStream(file);
598            BufferedReader buf = new BufferedReader(new InputStreamReader(is));
599
600            String line = buf.readLine();
601            StringBuilder sb = new StringBuilder();
602
603            while (line != null) {
604                sb.append(line).append("\n");
605                line = buf.readLine();
606            }
607            JSONObject jsonObject = new JSONObject(sb.toString());
608            is.close();
609            long expires = jsonObject.getLong("expires");
610            long expiresIn = expires - System.currentTimeMillis();
611            if (expiresIn < 0) {
612                file.delete();
613                return null;
614            } else {
615                Log.d("mtm", "posh fingerprints expire in " + (expiresIn / 1000) + "s");
616            }
617            List<String> result = new ArrayList<>();
618            JSONArray jsonArray = jsonObject.getJSONArray("fingerprints");
619            for (int i = 0; i < jsonArray.length(); ++i) {
620                result.add(jsonArray.getString(i));
621            }
622            return result;
623        } catch (FileNotFoundException e) {
624            return null;
625        } catch (IOException e) {
626            return null;
627        } catch (JSONException e) {
628            file.delete();
629            return null;
630        }
631    }
632
633    private X509Certificate[] getAcceptedIssuers() {
634        LOGGER.log(Level.FINE, "getAcceptedIssuers()");
635        return defaultTrustManager.getAcceptedIssuers();
636    }
637
638    private int createDecisionId(MTMDecision d) {
639        int myId;
640        synchronized (openDecisions) {
641            myId = decisionId;
642            openDecisions.put(myId, d);
643            decisionId += 1;
644        }
645        return myId;
646    }
647
648    private void certDetails(StringBuffer si, X509Certificate c) {
649        SimpleDateFormat validityDateFormater = new SimpleDateFormat("yyyy-MM-dd");
650        si.append("\n");
651        si.append(c.getSubjectDN().toString());
652        si.append("\n");
653        si.append(validityDateFormater.format(c.getNotBefore()));
654        si.append(" - ");
655        si.append(validityDateFormater.format(c.getNotAfter()));
656        si.append("\nSHA-256: ");
657        si.append(certHash(c, "SHA-256"));
658        si.append("\nSHA-1: ");
659        si.append(certHash(c, "SHA-1"));
660        si.append("\nSigned by: ");
661        si.append(c.getIssuerDN().toString());
662        si.append("\n");
663    }
664
665    private String certChainMessage(final X509Certificate[] chain, CertificateException cause) {
666        Throwable e = cause;
667        LOGGER.log(Level.FINE, "certChainMessage for " + e);
668        StringBuffer si = new StringBuffer();
669        if (e.getCause() != null) {
670            e = e.getCause();
671            // HACK: there is no sane way to check if the error is a "trust anchor
672            // not found", so we use string comparison.
673            if (NO_TRUST_ANCHOR.equals(e.getMessage())) {
674                si.append(master.getString(R.string.mtm_trust_anchor));
675            } else
676                si.append(e.getLocalizedMessage());
677            si.append("\n");
678        }
679        si.append("\n");
680        si.append(master.getString(R.string.mtm_connect_anyway));
681        si.append("\n\n");
682        si.append(master.getString(R.string.mtm_cert_details));
683        for (X509Certificate c : chain) {
684            certDetails(si, c);
685        }
686        return si.toString();
687    }
688
689    private String hostNameMessage(X509Certificate cert, String hostname) {
690        StringBuffer si = new StringBuffer();
691
692        si.append(master.getString(R.string.mtm_hostname_mismatch, hostname));
693        si.append("\n\n");
694        try {
695            Collection<List<?>> sans = cert.getSubjectAlternativeNames();
696            if (sans == null) {
697                si.append(cert.getSubjectDN());
698                si.append("\n");
699            } else for (List<?> altName : sans) {
700                Object name = altName.get(1);
701                if (name instanceof String) {
702                    si.append("[");
703                    si.append(altName.get(0));
704                    si.append("] ");
705                    si.append(name);
706                    si.append("\n");
707                }
708            }
709        } catch (CertificateParsingException e) {
710            e.printStackTrace();
711            si.append("<Parsing error: ");
712            si.append(e.getLocalizedMessage());
713            si.append(">\n");
714        }
715        si.append("\n");
716        si.append(master.getString(R.string.mtm_connect_anyway));
717        si.append("\n\n");
718        si.append(master.getString(R.string.mtm_cert_details));
719        certDetails(si, cert);
720        return si.toString();
721    }
722
723    /**
724     * Returns the top-most entry of the activity stack.
725     *
726     * @return the Context of the currently bound UI or the master context if none is bound
727     */
728    Context getUI() {
729        return (foregroundAct != null) ? foregroundAct : master;
730    }
731
732    int interact(final String message, final int titleId) {
733        /* prepare the MTMDecision blocker object */
734        MTMDecision choice = new MTMDecision();
735        final int myId = createDecisionId(choice);
736
737        masterHandler.post(new Runnable() {
738            public void run() {
739                Intent ni = new Intent(master, MemorizingActivity.class);
740                ni.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
741                ni.setData(Uri.parse(MemorizingTrustManager.class.getName() + "/" + myId));
742                ni.putExtra(DECISION_INTENT_ID, myId);
743                ni.putExtra(DECISION_INTENT_CERT, message);
744                ni.putExtra(DECISION_TITLE_ID, titleId);
745
746                // we try to directly start the activity and fall back to
747                // making a notification
748                try {
749                    getUI().startActivity(ni);
750                } catch (Exception e) {
751                    LOGGER.log(Level.FINE, "startActivity(MemorizingActivity)", e);
752                }
753            }
754        });
755
756        LOGGER.log(Level.FINE, "openDecisions: " + openDecisions + ", waiting on " + myId);
757        try {
758            synchronized (choice) {
759                choice.wait();
760            }
761        } catch (InterruptedException e) {
762            LOGGER.log(Level.FINER, "InterruptedException", e);
763        }
764        LOGGER.log(Level.FINE, "finished wait on " + myId + ": " + choice.state);
765        return choice.state;
766    }
767
768    void interactCert(final X509Certificate[] chain, String authType, CertificateException cause)
769            throws CertificateException {
770        switch (interact(certChainMessage(chain, cause), R.string.mtm_accept_cert)) {
771            case MTMDecision.DECISION_ALWAYS:
772                storeCert(chain[0]); // only store the server cert, not the whole chain
773            case MTMDecision.DECISION_ONCE:
774                break;
775            default:
776                throw (cause);
777        }
778    }
779
780    boolean interactHostname(X509Certificate cert, String hostname) {
781        switch (interact(hostNameMessage(cert, hostname), R.string.mtm_accept_servername)) {
782            case MTMDecision.DECISION_ALWAYS:
783                storeCert(hostname, cert);
784            case MTMDecision.DECISION_ONCE:
785                return true;
786            default:
787                return false;
788        }
789    }
790
791    public X509TrustManager getNonInteractive(String domain) {
792        return new NonInteractiveMemorizingTrustManager(domain);
793    }
794
795    public X509TrustManager getInteractive(String domain) {
796        return new InteractiveMemorizingTrustManager(domain);
797    }
798
799    public X509TrustManager getNonInteractive() {
800        return new NonInteractiveMemorizingTrustManager(null);
801    }
802
803    public X509TrustManager getInteractive() {
804        return new InteractiveMemorizingTrustManager(null);
805    }
806
807    class MemorizingHostnameVerifier implements DomainHostnameVerifier {
808        private final HostnameVerifier defaultVerifier;
809        private final boolean interactive;
810
811        public MemorizingHostnameVerifier(HostnameVerifier wrapped, boolean interactive) {
812            this.defaultVerifier = wrapped;
813            this.interactive = interactive;
814        }
815
816        @Override
817        public boolean verify(String domain, String hostname, SSLSession session) {
818            LOGGER.log(Level.FINE, "hostname verifier for " + domain + ", trying default verifier first");
819            // if the default verifier accepts the hostname, we are done
820            if (defaultVerifier instanceof DomainHostnameVerifier) {
821                if (((DomainHostnameVerifier) defaultVerifier).verify(domain, hostname, session)) {
822                    return true;
823                }
824            } else {
825                if (defaultVerifier.verify(domain, session)) {
826                    return true;
827                }
828            }
829
830
831            // otherwise, we check if the hostname is an alias for this cert in our keystore
832            try {
833                X509Certificate cert = (X509Certificate) session.getPeerCertificates()[0];
834                //Log.d(TAG, "cert: " + cert);
835                if (cert.equals(appKeyStore.getCertificate(domain.toLowerCase(Locale.US)))) {
836                    LOGGER.log(Level.FINE, "certificate for " + domain + " is in our keystore. accepting.");
837                    return true;
838                } else {
839                    LOGGER.log(Level.FINE, "server " + domain + " provided wrong certificate, asking user.");
840                    if (interactive) {
841                        return interactHostname(cert, domain);
842                    } else {
843                        return false;
844                    }
845                }
846            } catch (Exception e) {
847                e.printStackTrace();
848                return false;
849            }
850        }
851
852        @Override
853        public boolean verify(String domain, SSLSession sslSession) {
854            return verify(domain, null, sslSession);
855        }
856    }
857
858    private class NonInteractiveMemorizingTrustManager implements X509TrustManager {
859
860        private final String domain;
861
862        public NonInteractiveMemorizingTrustManager(String domain) {
863            this.domain = domain;
864        }
865
866        @Override
867        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
868            MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, false, false);
869        }
870
871        @Override
872        public void checkServerTrusted(X509Certificate[] chain, String authType)
873                throws CertificateException {
874            MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, true, false);
875        }
876
877        @Override
878        public X509Certificate[] getAcceptedIssuers() {
879            return MemorizingTrustManager.this.getAcceptedIssuers();
880        }
881
882    }
883
884    private class InteractiveMemorizingTrustManager implements X509TrustManager {
885        private final String domain;
886
887        public InteractiveMemorizingTrustManager(String domain) {
888            this.domain = domain;
889        }
890
891        @Override
892        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
893            MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, false, true);
894        }
895
896        @Override
897        public void checkServerTrusted(X509Certificate[] chain, String authType)
898                throws CertificateException {
899            MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, true, true);
900        }
901
902        @Override
903        public X509Certificate[] getAcceptedIssuers() {
904            return MemorizingTrustManager.this.getAcceptedIssuers();
905        }
906    }
907}