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.content.SharedPreferences;
 35import android.net.Uri;
 36import android.os.Build;
 37import android.os.Handler;
 38import android.preference.PreferenceManager;
 39import android.util.Base64;
 40import android.util.Log;
 41import android.util.SparseArray;
 42
 43import androidx.appcompat.app.AppCompatActivity;
 44
 45import com.google.common.base.Charsets;
 46import com.google.common.base.Joiner;
 47import com.google.common.base.Preconditions;
 48import com.google.common.io.ByteStreams;
 49import com.google.common.io.CharStreams;
 50
 51import eu.siacs.conversations.Config;
 52import eu.siacs.conversations.R;
 53import eu.siacs.conversations.crypto.BundledTrustManager;
 54import eu.siacs.conversations.crypto.CombiningTrustManager;
 55import eu.siacs.conversations.crypto.TrustManagers;
 56import eu.siacs.conversations.crypto.XmppDomainVerifier;
 57import eu.siacs.conversations.entities.MTMDecision;
 58import eu.siacs.conversations.http.HttpConnectionManager;
 59import eu.siacs.conversations.persistance.FileBackend;
 60import eu.siacs.conversations.ui.MemorizingActivity;
 61
 62import org.json.JSONArray;
 63import org.json.JSONException;
 64import org.json.JSONObject;
 65
 66import java.io.File;
 67import java.io.FileInputStream;
 68import java.io.FileOutputStream;
 69import java.io.IOException;
 70import java.io.InputStream;
 71import java.io.InputStreamReader;
 72import java.security.KeyStore;
 73import java.security.KeyStoreException;
 74import java.security.MessageDigest;
 75import java.security.NoSuchAlgorithmException;
 76import java.security.cert.Certificate;
 77import java.security.cert.CertificateEncodingException;
 78import java.security.cert.CertificateException;
 79import java.security.cert.CertificateParsingException;
 80import java.security.cert.X509Certificate;
 81import java.text.SimpleDateFormat;
 82import java.util.ArrayList;
 83import java.util.Enumeration;
 84import java.util.List;
 85import java.util.Locale;
 86import java.util.logging.Level;
 87import java.util.logging.Logger;
 88import java.util.regex.Pattern;
 89
 90import javax.net.ssl.TrustManager;
 91import javax.net.ssl.TrustManagerFactory;
 92import javax.net.ssl.X509TrustManager;
 93
 94/**
 95 * A X509 trust manager implementation which asks the user about invalid certificates and memorizes
 96 * their decision.
 97 *
 98 * <p>The certificate validity is checked using the system default X509 TrustManager, creating a
 99 * query Dialog if the check fails.
100 *
101 * <p><b>WARNING:</b> This only works if a dedicated thread is used for opening sockets!
102 */
103public class MemorizingTrustManager {
104
105    private static final SimpleDateFormat DATE_FORMAT =
106            new SimpleDateFormat("yyyy-MM-dd", Locale.US);
107
108    static final String DECISION_INTENT = "de.duenndns.ssl.DECISION";
109    public static final String DECISION_INTENT_ID = DECISION_INTENT + ".decisionId";
110    public static final String DECISION_INTENT_CERT = DECISION_INTENT + ".cert";
111    public static final String DECISION_TITLE_ID = DECISION_INTENT + ".titleId";
112    static final String NO_TRUST_ANCHOR = "Trust anchor for certification path not found.";
113    private static final Pattern PATTERN_IPV4 =
114            Pattern.compile(
115                    "\\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");
116    private static final Pattern PATTERN_IPV6_HEX4DECCOMPRESSED =
117            Pattern.compile(
118                    "\\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");
119    private static final Pattern PATTERN_IPV6_6HEX4DEC =
120            Pattern.compile(
121                    "\\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");
122    private static final Pattern PATTERN_IPV6_HEXCOMPRESSED =
123            Pattern.compile(
124                    "\\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");
125    private static final Pattern PATTERN_IPV6 =
126            Pattern.compile("\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z");
127    private static final Logger LOGGER = Logger.getLogger(MemorizingTrustManager.class.getName());
128    static String KEYSTORE_DIR = "KeyStore";
129    static String KEYSTORE_FILE = "KeyStore.bks";
130    private static int decisionId = 0;
131    private static final SparseArray<MTMDecision> openDecisions = new SparseArray<MTMDecision>();
132    Context master;
133    AppCompatActivity foregroundAct;
134    NotificationManager notificationManager;
135    Handler masterHandler;
136    private File keyStoreFile;
137    private KeyStore appKeyStore;
138    private final X509TrustManager defaultTrustManager;
139    private X509TrustManager appTrustManager;
140    private String poshCacheDir;
141
142    /**
143     * Creates an instance of the MemorizingTrustManager class that falls back to a custom
144     * TrustManager.
145     *
146     * <p>You need to supply the application context. This has to be one of: - Application -
147     * Activity - Service
148     *
149     * <p>The context is used for file management, to display the dialog / notification and for
150     * obtaining translated strings.
151     *
152     * @param context Context for the application.
153     * @param defaultTrustManager Delegate trust management to this TM. If null, the user must
154     *     accept every certificate.
155     */
156    public MemorizingTrustManager(
157            final Context context, final X509TrustManager defaultTrustManager) {
158        init(context);
159        this.appTrustManager = getTrustManager(appKeyStore);
160        this.defaultTrustManager = defaultTrustManager;
161    }
162
163    /**
164     * Creates an instance of the MemorizingTrustManager class using the system X509TrustManager.
165     *
166     * <p>You need to supply the application context. This has to be one of: - Application -
167     * Activity - Service
168     *
169     * <p>The context is used for file management, to display the dialog / notification and for
170     * obtaining translated strings.
171     *
172     * @param context Context for the application.
173     */
174    public MemorizingTrustManager(final Context context) {
175        init(context);
176        this.appTrustManager = getTrustManager(appKeyStore);
177        try {
178            if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.N) {
179                this.defaultTrustManager = defaultWithBundledLetsEncrypt(context);
180            } else {
181                this.defaultTrustManager = TrustManagers.createDefaultTrustManager();
182            }
183        } catch (final NoSuchAlgorithmException
184                | KeyStoreException
185                | CertificateException
186                | IOException e) {
187            throw new RuntimeException(e);
188        }
189    }
190
191    private static X509TrustManager defaultWithBundledLetsEncrypt(final Context context)
192            throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
193        final BundledTrustManager bundleTrustManager =
194                BundledTrustManager.builder()
195                        .loadKeyStore(
196                                context.getResources().openRawResource(R.raw.letsencrypt),
197                                "letsencrypt")
198                        .build();
199        return CombiningTrustManager.combineWithDefault(bundleTrustManager);
200    }
201
202    private static boolean isIp(final String server) {
203        return server != null
204                && (PATTERN_IPV4.matcher(server).matches()
205                        || PATTERN_IPV6.matcher(server).matches()
206                        || PATTERN_IPV6_6HEX4DEC.matcher(server).matches()
207                        || PATTERN_IPV6_HEX4DECCOMPRESSED.matcher(server).matches()
208                        || PATTERN_IPV6_HEXCOMPRESSED.matcher(server).matches());
209    }
210
211    private static String getBase64Hash(X509Certificate certificate, String digest)
212            throws CertificateEncodingException {
213        MessageDigest md;
214        try {
215            md = MessageDigest.getInstance(digest);
216        } catch (NoSuchAlgorithmException e) {
217            return null;
218        }
219        md.update(certificate.getEncoded());
220        return Base64.encodeToString(md.digest(), Base64.NO_WRAP);
221    }
222
223    private static String hexString(byte[] data) {
224        StringBuffer si = new StringBuffer();
225        for (int i = 0; i < data.length; i++) {
226            si.append(String.format("%02x", data[i]));
227            if (i < data.length - 1) si.append(":");
228        }
229        return si.toString();
230    }
231
232    private static String certHash(final X509Certificate cert, String digest) {
233        try {
234            MessageDigest md = MessageDigest.getInstance(digest);
235            md.update(cert.getEncoded());
236            return hexString(md.digest());
237        } catch (CertificateEncodingException | NoSuchAlgorithmException e) {
238            return e.getMessage();
239        }
240    }
241
242    public static void interactResult(int decisionId, int choice) {
243        MTMDecision d;
244        synchronized (openDecisions) {
245            d = openDecisions.get(decisionId);
246            openDecisions.remove(decisionId);
247        }
248        if (d == null) {
249            LOGGER.log(Level.SEVERE, "interactResult: aborting due to stale decision reference!");
250            return;
251        }
252        synchronized (d) {
253            d.state = choice;
254            d.notify();
255        }
256    }
257
258    void init(final Context context) {
259        master = context;
260        masterHandler = new Handler(context.getMainLooper());
261        notificationManager =
262                (NotificationManager) master.getSystemService(Context.NOTIFICATION_SERVICE);
263
264        Application app;
265        if (context instanceof Application) {
266            app = (Application) context;
267        } else if (context instanceof Service) {
268            app = ((Service) context).getApplication();
269        } else if (context instanceof AppCompatActivity) {
270            app = ((AppCompatActivity) context).getApplication();
271        } else
272            throw new ClassCastException(
273                    "MemorizingTrustManager context must be either Activity or Service!");
274
275        File dir = app.getDir(KEYSTORE_DIR, Context.MODE_PRIVATE);
276        keyStoreFile = new File(dir + File.separator + KEYSTORE_FILE);
277
278        poshCacheDir = app.getCacheDir().getAbsolutePath() + "/posh_cache/";
279
280        appKeyStore = loadAppKeyStore();
281    }
282
283    /**
284     * Get a list of all certificate aliases stored in MTM.
285     *
286     * @return an {@link Enumeration} of all certificates
287     */
288    public Enumeration<String> getCertificates() {
289        try {
290            return appKeyStore.aliases();
291        } catch (KeyStoreException e) {
292            // this should never happen, however...
293            throw new RuntimeException(e);
294        }
295    }
296
297    /**
298     * Removes the given certificate from MTMs key store.
299     *
300     * <p><b>WARNING</b>: this does not immediately invalidate the certificate. It is well possible
301     * that (a) data is transmitted over still existing connections or (b) new connections are
302     * created using TLS renegotiation, without a new cert check.
303     *
304     * @param alias the certificate's alias as returned by {@link #getCertificates()}.
305     * @throws KeyStoreException if the certificate could not be deleted.
306     */
307    public void deleteCertificate(String alias) throws KeyStoreException {
308        appKeyStore.deleteEntry(alias);
309        keyStoreUpdated();
310    }
311
312    private X509TrustManager getTrustManager(final KeyStore keyStore) {
313        Preconditions.checkNotNull(keyStore);
314        try {
315            TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
316            tmf.init(keyStore);
317            for (TrustManager t : tmf.getTrustManagers()) {
318                if (t instanceof X509TrustManager) {
319                    return (X509TrustManager) t;
320                }
321            }
322        } catch (final Exception e) {
323            // Here, we are covering up errors. It might be more useful
324            // however to throw them out of the constructor so the
325            // embedding app knows something went wrong.
326            LOGGER.log(Level.SEVERE, "getTrustManager(" + keyStore + ")", e);
327        }
328        return null;
329    }
330
331    KeyStore loadAppKeyStore() {
332        KeyStore ks;
333        try {
334            ks = KeyStore.getInstance(KeyStore.getDefaultType());
335        } catch (KeyStoreException e) {
336            LOGGER.log(Level.SEVERE, "getAppKeyStore()", e);
337            return null;
338        }
339        FileInputStream fileInputStream = null;
340        try {
341            ks.load(null, null);
342            fileInputStream = new FileInputStream(keyStoreFile);
343            ks.load(fileInputStream, "MTM".toCharArray());
344        } catch (java.io.FileNotFoundException e) {
345            LOGGER.log(Level.INFO, "getAppKeyStore(" + keyStoreFile + ") - file does not exist");
346        } catch (Exception e) {
347            LOGGER.log(Level.SEVERE, "getAppKeyStore(" + keyStoreFile + ")", e);
348        } finally {
349            FileBackend.close(fileInputStream);
350        }
351        return ks;
352    }
353
354    void storeCert(String alias, Certificate cert) {
355        try {
356            appKeyStore.setCertificateEntry(alias, cert);
357        } catch (KeyStoreException e) {
358            LOGGER.log(Level.SEVERE, "storeCert(" + cert + ")", e);
359            return;
360        }
361        keyStoreUpdated();
362    }
363
364    void storeCert(X509Certificate cert) {
365        storeCert(cert.getSubjectDN().toString(), cert);
366    }
367
368    void keyStoreUpdated() {
369        // reload appTrustManager
370        appTrustManager = getTrustManager(appKeyStore);
371
372        // store KeyStore to file
373        java.io.FileOutputStream fos = null;
374        try {
375            fos = new java.io.FileOutputStream(keyStoreFile);
376            appKeyStore.store(fos, "MTM".toCharArray());
377        } catch (Exception e) {
378            LOGGER.log(Level.SEVERE, "storeCert(" + keyStoreFile + ")", e);
379        } finally {
380            if (fos != null) {
381                try {
382                    fos.close();
383                } catch (IOException e) {
384                    LOGGER.log(Level.SEVERE, "storeCert(" + keyStoreFile + ")", e);
385                }
386            }
387        }
388    }
389
390    // if the certificate is stored in the app key store, it is considered "known"
391    private boolean isCertKnown(X509Certificate cert) {
392        try {
393            return appKeyStore.getCertificateAlias(cert) != null;
394        } catch (KeyStoreException e) {
395            return false;
396        }
397    }
398
399    private void checkCertTrusted(
400            X509Certificate[] chain,
401            String authType,
402            String domain,
403            boolean isServer,
404            boolean interactive)
405            throws CertificateException {
406        LOGGER.log(
407                Level.FINE, "checkCertTrusted(" + chain + ", " + authType + ", " + isServer + ")");
408        try {
409            LOGGER.log(Level.FINE, "checkCertTrusted: trying appTrustManager");
410            if (isServer) appTrustManager.checkServerTrusted(chain, authType);
411            else appTrustManager.checkClientTrusted(chain, authType);
412        } catch (final CertificateException ae) {
413            LOGGER.log(Level.FINER, "checkCertTrusted: appTrustManager failed", ae);
414            if (isCertKnown(chain[0])) {
415                LOGGER.log(
416                        Level.INFO, "checkCertTrusted: accepting cert already stored in keystore");
417                return;
418            }
419            try {
420                if (defaultTrustManager == null) throw ae;
421                LOGGER.log(Level.FINE, "checkCertTrusted: trying defaultTrustManager");
422                if (isServer) defaultTrustManager.checkServerTrusted(chain, authType);
423                else defaultTrustManager.checkClientTrusted(chain, authType);
424            } catch (final CertificateException e) {
425                final SharedPreferences preferences =
426                        PreferenceManager.getDefaultSharedPreferences(master);
427                final boolean trustSystemCAs =
428                        !preferences.getBoolean("dont_trust_system_cas", false);
429                if (domain != null
430                        && isServer
431                        && trustSystemCAs
432                        && !isIp(domain)
433                        && !domain.endsWith(".onion")) {
434                    final String hash = getBase64Hash(chain[0], "SHA-256");
435                    final List<String> fingerprints = getPoshFingerprints(domain);
436                    if (hash != null && fingerprints.size() > 0) {
437                        if (fingerprints.contains(hash)) {
438                            Log.d(
439                                    Config.LOGTAG,
440                                    "trusted cert fingerprint of " + domain + " via posh");
441                            return;
442                        } else {
443                            Log.d(
444                                    Config.LOGTAG,
445                                    "fingerprint " + hash + " not found in " + fingerprints);
446                        }
447                        if (getPoshCacheFile(domain).delete()) {
448                            Log.d(
449                                    Config.LOGTAG,
450                                    "deleted posh file for "
451                                            + domain
452                                            + " after not being able to verify");
453                        }
454                    }
455                }
456                if (interactive) {
457                    interactCert(chain, authType, e);
458                } else {
459                    throw e;
460                }
461            }
462        }
463    }
464
465    private List<String> getPoshFingerprints(final String domain) {
466        final List<String> cached = getPoshFingerprintsFromCache(domain);
467        if (cached == null) {
468            return getPoshFingerprintsFromServer(domain);
469        } else {
470            return cached;
471        }
472    }
473
474    private List<String> getPoshFingerprintsFromServer(String domain) {
475        return getPoshFingerprintsFromServer(
476                domain, "https://" + domain + "/.well-known/posh/xmpp-client.json", -1, true);
477    }
478
479    private List<String> getPoshFingerprintsFromServer(
480            String domain, String url, int maxTtl, boolean followUrl) {
481        Log.d(Config.LOGTAG, "downloading json for " + domain + " from " + url);
482        final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(master);
483        final boolean useTor =
484                QuickConversationsService.isConversations()
485                        && preferences.getBoolean(
486                                "use_tor", master.getResources().getBoolean(R.bool.use_tor));
487        try {
488            final List<String> results = new ArrayList<>();
489            final InputStream inputStream = HttpConnectionManager.open(url, useTor);
490            final String body =
491                    CharStreams.toString(
492                            new InputStreamReader(
493                                    ByteStreams.limit(inputStream, 10_000), Charsets.UTF_8));
494            final JSONObject jsonObject = new JSONObject(body);
495            int expires = jsonObject.getInt("expires");
496            if (expires <= 0) {
497                return new ArrayList<>();
498            }
499            if (maxTtl >= 0) {
500                expires = Math.min(maxTtl, expires);
501            }
502            String redirect;
503            try {
504                redirect = jsonObject.getString("url");
505            } catch (JSONException e) {
506                redirect = null;
507            }
508            if (followUrl && redirect != null && redirect.toLowerCase().startsWith("https")) {
509                return getPoshFingerprintsFromServer(domain, redirect, expires, false);
510            }
511            final JSONArray fingerprints = jsonObject.getJSONArray("fingerprints");
512            for (int i = 0; i < fingerprints.length(); i++) {
513                final JSONObject fingerprint = fingerprints.getJSONObject(i);
514                final String sha256 = fingerprint.getString("sha-256");
515                results.add(sha256);
516            }
517            writeFingerprintsToCache(domain, results, 1000L * expires + System.currentTimeMillis());
518            return results;
519        } catch (final Exception e) {
520            Log.d(Config.LOGTAG, "error fetching posh", e);
521            return new ArrayList<>();
522        }
523    }
524
525    private File getPoshCacheFile(String domain) {
526        return new File(poshCacheDir + domain + ".json");
527    }
528
529    private void writeFingerprintsToCache(String domain, List<String> results, long expires) {
530        final File file = getPoshCacheFile(domain);
531        file.getParentFile().mkdirs();
532        try {
533            file.createNewFile();
534            JSONObject jsonObject = new JSONObject();
535            jsonObject.put("expires", expires);
536            jsonObject.put("fingerprints", new JSONArray(results));
537            FileOutputStream outputStream = new FileOutputStream(file);
538            outputStream.write(jsonObject.toString().getBytes());
539            outputStream.flush();
540            outputStream.close();
541        } catch (Exception e) {
542            e.printStackTrace();
543        }
544    }
545
546    private List<String> getPoshFingerprintsFromCache(String domain) {
547        final File file = getPoshCacheFile(domain);
548        try {
549            final InputStream inputStream = new FileInputStream(file);
550            final String json =
551                    CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
552            final JSONObject jsonObject = new JSONObject(json);
553            long expires = jsonObject.getLong("expires");
554            long expiresIn = expires - System.currentTimeMillis();
555            if (expiresIn < 0) {
556                file.delete();
557                return null;
558            } else {
559                Log.d(Config.LOGTAG, "posh fingerprints expire in " + (expiresIn / 1000) + "s");
560            }
561            final List<String> result = new ArrayList<>();
562            final JSONArray jsonArray = jsonObject.getJSONArray("fingerprints");
563            for (int i = 0; i < jsonArray.length(); ++i) {
564                result.add(jsonArray.getString(i));
565            }
566            return result;
567        } catch (final IOException e) {
568            return null;
569        } catch (JSONException e) {
570            file.delete();
571            return null;
572        }
573    }
574
575    private X509Certificate[] getAcceptedIssuers() {
576        return defaultTrustManager == null
577                ? new X509Certificate[0]
578                : defaultTrustManager.getAcceptedIssuers();
579    }
580
581    private int createDecisionId(MTMDecision d) {
582        int myId;
583        synchronized (openDecisions) {
584            myId = decisionId;
585            openDecisions.put(myId, d);
586            decisionId += 1;
587        }
588        return myId;
589    }
590
591    private void certDetails(
592            final StringBuffer si, final X509Certificate c, final boolean showValidFor) {
593
594        si.append("\n");
595        if (showValidFor) {
596            try {
597                si.append("Valid for: ");
598                si.append(Joiner.on(", ").join(XmppDomainVerifier.parseValidDomains(c).all()));
599            } catch (final CertificateParsingException e) {
600                si.append("Unable to parse Certificate");
601            }
602            si.append("\n");
603        } else {
604            si.append(c.getSubjectDN());
605        }
606        si.append("\n");
607        si.append(DATE_FORMAT.format(c.getNotBefore()));
608        si.append(" - ");
609        si.append(DATE_FORMAT.format(c.getNotAfter()));
610        si.append("\nSHA-256: ");
611        si.append(certHash(c, "SHA-256"));
612        si.append("\nSHA-1: ");
613        si.append(certHash(c, "SHA-1"));
614        si.append("\nSigned by: ");
615        si.append(c.getIssuerDN().toString());
616        si.append("\n");
617    }
618
619    private String certChainMessage(final X509Certificate[] chain, CertificateException cause) {
620        Throwable e = cause;
621        LOGGER.log(Level.FINE, "certChainMessage for " + e);
622        final StringBuffer si = new StringBuffer();
623        if (e.getCause() != null) {
624            e = e.getCause();
625            // HACK: there is no sane way to check if the error is a "trust anchor
626            // not found", so we use string comparison.
627            if (NO_TRUST_ANCHOR.equals(e.getMessage())) {
628                si.append(master.getString(R.string.mtm_trust_anchor));
629            } else si.append(e.getLocalizedMessage());
630            si.append("\n");
631        }
632        si.append("\n");
633        si.append(master.getString(R.string.mtm_connect_anyway));
634        si.append("\n\n");
635        si.append(master.getString(R.string.mtm_cert_details));
636        si.append('\n');
637        for (int i = 0; i < chain.length; ++i) {
638            certDetails(si, chain[i], i == 0);
639        }
640        return si.toString();
641    }
642
643    /**
644     * Returns the top-most entry of the activity stack.
645     *
646     * @return the Context of the currently bound UI or the master context if none is bound
647     */
648    Context getUI() {
649        return (foregroundAct != null) ? foregroundAct : master;
650    }
651
652    int interact(final String message, final int titleId) {
653        /* prepare the MTMDecision blocker object */
654        MTMDecision choice = new MTMDecision();
655        final int myId = createDecisionId(choice);
656
657        masterHandler.post(
658                new Runnable() {
659                    public void run() {
660                        Intent ni = new Intent(master, MemorizingActivity.class);
661                        ni.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
662                        ni.setData(Uri.parse(MemorizingTrustManager.class.getName() + "/" + myId));
663                        ni.putExtra(DECISION_INTENT_ID, myId);
664                        ni.putExtra(DECISION_INTENT_CERT, message);
665                        ni.putExtra(DECISION_TITLE_ID, titleId);
666
667                        // we try to directly start the activity and fall back to
668                        // making a notification
669                        try {
670                            getUI().startActivity(ni);
671                        } catch (Exception e) {
672                            LOGGER.log(Level.FINE, "startActivity(MemorizingActivity)", e);
673                        }
674                    }
675                });
676
677        LOGGER.log(Level.FINE, "openDecisions: " + openDecisions + ", waiting on " + myId);
678        try {
679            synchronized (choice) {
680                choice.wait();
681            }
682        } catch (InterruptedException e) {
683            LOGGER.log(Level.FINER, "InterruptedException", e);
684        }
685        LOGGER.log(Level.FINE, "finished wait on " + myId + ": " + choice.state);
686        return choice.state;
687    }
688
689    void interactCert(final X509Certificate[] chain, String authType, CertificateException cause)
690            throws CertificateException {
691        switch (interact(certChainMessage(chain, cause), R.string.mtm_accept_cert)) {
692            case MTMDecision.DECISION_ALWAYS:
693                storeCert(chain[0]); // only store the server cert, not the whole chain
694            case MTMDecision.DECISION_ONCE:
695                break;
696            default:
697                throw (cause);
698        }
699    }
700
701    public X509TrustManager getNonInteractive(String domain) {
702        return new NonInteractiveMemorizingTrustManager(domain);
703    }
704
705    public X509TrustManager getInteractive(String domain) {
706        return new InteractiveMemorizingTrustManager(domain);
707    }
708
709    public X509TrustManager getNonInteractive() {
710        return new NonInteractiveMemorizingTrustManager(null);
711    }
712
713    public X509TrustManager getInteractive() {
714        return new InteractiveMemorizingTrustManager(null);
715    }
716
717    private class NonInteractiveMemorizingTrustManager implements X509TrustManager {
718
719        private final String domain;
720
721        public NonInteractiveMemorizingTrustManager(String domain) {
722            this.domain = domain;
723        }
724
725        @Override
726        public void checkClientTrusted(X509Certificate[] chain, String authType)
727                throws CertificateException {
728            MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, false, false);
729        }
730
731        @Override
732        public void checkServerTrusted(X509Certificate[] chain, String authType)
733                throws CertificateException {
734            MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, true, false);
735        }
736
737        @Override
738        public X509Certificate[] getAcceptedIssuers() {
739            return MemorizingTrustManager.this.getAcceptedIssuers();
740        }
741    }
742
743    private class InteractiveMemorizingTrustManager implements X509TrustManager {
744        private final String domain;
745
746        public InteractiveMemorizingTrustManager(String domain) {
747            this.domain = domain;
748        }
749
750        @Override
751        public void checkClientTrusted(X509Certificate[] chain, String authType)
752                throws CertificateException {
753            MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, false, true);
754        }
755
756        @Override
757        public void checkServerTrusted(X509Certificate[] chain, String authType)
758                throws CertificateException {
759            MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, true, true);
760        }
761
762        @Override
763        public X509Certificate[] getAcceptedIssuers() {
764            return MemorizingTrustManager.this.getAcceptedIssuers();
765        }
766    }
767}