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