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