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