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