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