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 HostnameVerifier wrapHostnameVerifier(final HostnameVerifier defaultVerifier) {
296 if (defaultVerifier == null)
297 throw new IllegalArgumentException("The default verifier may not be null");
298
299 return new MemorizingHostnameVerifier(defaultVerifier);
300 }
301
302 public HostnameVerifier wrapHostnameVerifierNonInteractive(final HostnameVerifier defaultVerifier) {
303 if (defaultVerifier == null)
304 throw new IllegalArgumentException("The default verifier may not be null");
305
306 return new NonInteractiveMemorizingHostnameVerifier(defaultVerifier);
307 }
308
309 X509TrustManager getTrustManager(KeyStore ks) {
310 try {
311 TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
312 tmf.init(ks);
313 for (TrustManager t : tmf.getTrustManagers()) {
314 if (t instanceof X509TrustManager) {
315 return (X509TrustManager)t;
316 }
317 }
318 } catch (Exception e) {
319 // Here, we are covering up errors. It might be more useful
320 // however to throw them out of the constructor so the
321 // embedding app knows something went wrong.
322 LOGGER.log(Level.SEVERE, "getTrustManager(" + ks + ")", e);
323 }
324 return null;
325 }
326
327 KeyStore loadAppKeyStore() {
328 KeyStore ks;
329 try {
330 ks = KeyStore.getInstance(KeyStore.getDefaultType());
331 } catch (KeyStoreException e) {
332 LOGGER.log(Level.SEVERE, "getAppKeyStore()", e);
333 return null;
334 }
335 try {
336 ks.load(null, null);
337 ks.load(new java.io.FileInputStream(keyStoreFile), "MTM".toCharArray());
338 } catch (java.io.FileNotFoundException e) {
339 LOGGER.log(Level.INFO, "getAppKeyStore(" + keyStoreFile + ") - file does not exist");
340 } catch (Exception e) {
341 LOGGER.log(Level.SEVERE, "getAppKeyStore(" + keyStoreFile + ")", e);
342 }
343 return ks;
344 }
345
346 void storeCert(String alias, Certificate cert) {
347 try {
348 appKeyStore.setCertificateEntry(alias, cert);
349 } catch (KeyStoreException e) {
350 LOGGER.log(Level.SEVERE, "storeCert(" + cert + ")", e);
351 return;
352 }
353 keyStoreUpdated();
354 }
355
356 void storeCert(X509Certificate cert) {
357 storeCert(cert.getSubjectDN().toString(), cert);
358 }
359
360 void keyStoreUpdated() {
361 // reload appTrustManager
362 appTrustManager = getTrustManager(appKeyStore);
363
364 // store KeyStore to file
365 java.io.FileOutputStream fos = null;
366 try {
367 fos = new java.io.FileOutputStream(keyStoreFile);
368 appKeyStore.store(fos, "MTM".toCharArray());
369 } catch (Exception e) {
370 LOGGER.log(Level.SEVERE, "storeCert(" + keyStoreFile + ")", e);
371 } finally {
372 if (fos != null) {
373 try {
374 fos.close();
375 } catch (IOException e) {
376 LOGGER.log(Level.SEVERE, "storeCert(" + keyStoreFile + ")", e);
377 }
378 }
379 }
380 }
381
382 // if the certificate is stored in the app key store, it is considered "known"
383 private boolean isCertKnown(X509Certificate cert) {
384 try {
385 return appKeyStore.getCertificateAlias(cert) != null;
386 } catch (KeyStoreException e) {
387 return false;
388 }
389 }
390
391 private boolean isExpiredException(Throwable e) {
392 do {
393 if (e instanceof CertificateExpiredException)
394 return true;
395 e = e.getCause();
396 } while (e != null);
397 return false;
398 }
399
400 public void checkCertTrusted(X509Certificate[] chain, String authType, String domain, boolean isServer, boolean interactive)
401 throws CertificateException
402 {
403 LOGGER.log(Level.FINE, "checkCertTrusted(" + chain + ", " + authType + ", " + isServer + ")");
404 try {
405 LOGGER.log(Level.FINE, "checkCertTrusted: trying appTrustManager");
406 if (isServer)
407 appTrustManager.checkServerTrusted(chain, authType);
408 else
409 appTrustManager.checkClientTrusted(chain, authType);
410 } catch (CertificateException ae) {
411 LOGGER.log(Level.FINER, "checkCertTrusted: appTrustManager failed", ae);
412 // if the cert is stored in our appTrustManager, we ignore expiredness
413 if (isExpiredException(ae)) {
414 LOGGER.log(Level.INFO, "checkCertTrusted: accepting expired certificate from keystore");
415 return;
416 }
417 if (isCertKnown(chain[0])) {
418 LOGGER.log(Level.INFO, "checkCertTrusted: accepting cert already stored in keystore");
419 return;
420 }
421 try {
422 if (defaultTrustManager == null)
423 throw ae;
424 LOGGER.log(Level.FINE, "checkCertTrusted: trying defaultTrustManager");
425 if (isServer)
426 defaultTrustManager.checkServerTrusted(chain, authType);
427 else
428 defaultTrustManager.checkClientTrusted(chain, authType);
429 } catch (CertificateException e) {
430 boolean trustSystemCAs = !PreferenceManager.getDefaultSharedPreferences(master).getBoolean("dont_trust_system_cas", false);
431 if (domain != null && isServer && trustSystemCAs && !isIp(domain)) {
432 String hash = getBase64Hash(chain[0],"SHA-256");
433 List<String> fingerprints = getPoshFingerprints(domain);
434 if (hash != null && fingerprints.contains(hash)) {
435 Log.d("mtm","trusted cert fingerprint of "+domain+" via posh");
436 return;
437 }
438 }
439 e.printStackTrace();
440 if (interactive) {
441 interactCert(chain, authType, e);
442 } else {
443 throw e;
444 }
445 }
446 }
447 }
448
449 private List<String> getPoshFingerprints(String domain) {
450 List<String> cached = getPoshFingerprintsFromCache(domain);
451 if (cached == null) {
452 return getPoshFingerprintsFromServer(domain);
453 } else {
454 return cached;
455 }
456 }
457
458 private List<String> getPoshFingerprintsFromServer(String domain) {
459 return getPoshFingerprintsFromServer(domain, "https://"+domain+"/.well-known/posh/xmpp-client.json",-1,true);
460 }
461
462 private List<String> getPoshFingerprintsFromServer(String domain, String url, int maxTtl, boolean followUrl) {
463 Log.d("mtm","downloading json for "+domain+" from "+url);
464 try {
465 List<String> results = new ArrayList<>();
466 HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
467 connection.setConnectTimeout(5000);
468 connection.setReadTimeout(5000);
469 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
470 String inputLine;
471 StringBuilder builder = new StringBuilder();
472 while ((inputLine = in.readLine()) != null) {
473 builder.append(inputLine);
474 }
475 JSONObject jsonObject = new JSONObject(builder.toString());
476 in.close();
477 int expires = jsonObject.getInt("expires");
478 if (expires <= 0) {
479 return new ArrayList<>();
480 }
481 if (maxTtl >= 0) {
482 expires = Math.min(maxTtl,expires);
483 }
484 String redirect;
485 try {
486 redirect = jsonObject.getString("url");
487 } catch (JSONException e) {
488 redirect = null;
489 }
490 if (followUrl && redirect != null && redirect.toLowerCase().startsWith("https")) {
491 return getPoshFingerprintsFromServer(domain, redirect, expires, false);
492 }
493 JSONArray fingerprints = jsonObject.getJSONArray("fingerprints");
494 for(int i = 0; i < fingerprints.length(); i++) {
495 JSONObject fingerprint = fingerprints.getJSONObject(i);
496 String sha256 = fingerprint.getString("sha-256");
497 if (sha256 != null) {
498 results.add(sha256);
499 }
500 }
501 writeFingerprintsToCache(domain, results,1000L * expires+System.currentTimeMillis());
502 return results;
503 } catch (Exception e) {
504 Log.d("mtm","error fetching posh "+e.getMessage());
505 return new ArrayList<>();
506 }
507 }
508
509 private File getPoshCacheFile(String domain) {
510 return new File(poshCacheDir+domain+".json");
511 }
512
513 private void writeFingerprintsToCache(String domain, List<String> results, long expires) {
514 File file = getPoshCacheFile(domain);
515 file.getParentFile().mkdirs();
516 try {
517 file.createNewFile();
518 JSONObject jsonObject = new JSONObject();
519 jsonObject.put("expires",expires);
520 jsonObject.put("fingerprints",new JSONArray(results));
521 FileOutputStream outputStream = new FileOutputStream(file);
522 outputStream.write(jsonObject.toString().getBytes());
523 outputStream.flush();
524 outputStream.close();
525 } catch (Exception e) {
526 e.printStackTrace();
527 }
528 }
529
530 private List<String> getPoshFingerprintsFromCache(String domain) {
531 File file = getPoshCacheFile(domain);
532 try {
533 InputStream is = new FileInputStream(file);
534 BufferedReader buf = new BufferedReader(new InputStreamReader(is));
535
536 String line = buf.readLine();
537 StringBuilder sb = new StringBuilder();
538
539 while(line != null){
540 sb.append(line).append("\n");
541 line = buf.readLine();
542 }
543 JSONObject jsonObject = new JSONObject(sb.toString());
544 is.close();
545 long expires = jsonObject.getLong("expires");
546 long expiresIn = expires - System.currentTimeMillis();
547 if (expiresIn < 0) {
548 file.delete();
549 return null;
550 } else {
551 Log.d("mtm","posh fingerprints expire in "+(expiresIn/1000)+"s");
552 }
553 List<String> result = new ArrayList<>();
554 JSONArray jsonArray = jsonObject.getJSONArray("fingerprints");
555 for(int i = 0; i < jsonArray.length(); ++i) {
556 result.add(jsonArray.getString(i));
557 }
558 return result;
559 } catch (FileNotFoundException e) {
560 return null;
561 } catch (IOException e) {
562 return null;
563 } catch (JSONException e) {
564 file.delete();
565 return null;
566 }
567 }
568
569 private static boolean isIp(final String server) {
570 return server != null && (
571 PATTERN_IPV4.matcher(server).matches()
572 || PATTERN_IPV6.matcher(server).matches()
573 || PATTERN_IPV6_6HEX4DEC.matcher(server).matches()
574 || PATTERN_IPV6_HEX4DECCOMPRESSED.matcher(server).matches()
575 || PATTERN_IPV6_HEXCOMPRESSED.matcher(server).matches());
576 }
577
578 private static String getBase64Hash(X509Certificate certificate, String digest) throws CertificateEncodingException {
579 MessageDigest md;
580 try {
581 md = MessageDigest.getInstance(digest);
582 } catch (NoSuchAlgorithmException e) {
583 return null;
584 }
585 md.update(certificate.getEncoded());
586 return Base64.encodeToString(md.digest(),Base64.NO_WRAP);
587 }
588
589 private X509Certificate[] getAcceptedIssuers() {
590 LOGGER.log(Level.FINE, "getAcceptedIssuers()");
591 return defaultTrustManager.getAcceptedIssuers();
592 }
593
594 private int createDecisionId(MTMDecision d) {
595 int myId;
596 synchronized(openDecisions) {
597 myId = decisionId;
598 openDecisions.put(myId, d);
599 decisionId += 1;
600 }
601 return myId;
602 }
603
604 private static String hexString(byte[] data) {
605 StringBuffer si = new StringBuffer();
606 for (int i = 0; i < data.length; i++) {
607 si.append(String.format("%02x", data[i]));
608 if (i < data.length - 1)
609 si.append(":");
610 }
611 return si.toString();
612 }
613
614 private static String certHash(final X509Certificate cert, String digest) {
615 try {
616 MessageDigest md = MessageDigest.getInstance(digest);
617 md.update(cert.getEncoded());
618 return hexString(md.digest());
619 } catch (java.security.cert.CertificateEncodingException e) {
620 return e.getMessage();
621 } catch (java.security.NoSuchAlgorithmException e) {
622 return e.getMessage();
623 }
624 }
625
626 private void certDetails(StringBuffer si, X509Certificate c) {
627 SimpleDateFormat validityDateFormater = new SimpleDateFormat("yyyy-MM-dd");
628 si.append("\n");
629 si.append(c.getSubjectDN().toString());
630 si.append("\n");
631 si.append(validityDateFormater.format(c.getNotBefore()));
632 si.append(" - ");
633 si.append(validityDateFormater.format(c.getNotAfter()));
634 si.append("\nSHA-256: ");
635 si.append(certHash(c, "SHA-256"));
636 si.append("\nSHA-1: ");
637 si.append(certHash(c, "SHA-1"));
638 si.append("\nSigned by: ");
639 si.append(c.getIssuerDN().toString());
640 si.append("\n");
641 }
642
643 private String certChainMessage(final X509Certificate[] chain, CertificateException cause) {
644 Throwable e = cause;
645 LOGGER.log(Level.FINE, "certChainMessage for " + e);
646 StringBuffer si = new StringBuffer();
647 if (e.getCause() != null) {
648 e = e.getCause();
649 // HACK: there is no sane way to check if the error is a "trust anchor
650 // not found", so we use string comparison.
651 if (NO_TRUST_ANCHOR.equals(e.getMessage())) {
652 si.append(master.getString(R.string.mtm_trust_anchor));
653 } else
654 si.append(e.getLocalizedMessage());
655 si.append("\n");
656 }
657 si.append("\n");
658 si.append(master.getString(R.string.mtm_connect_anyway));
659 si.append("\n\n");
660 si.append(master.getString(R.string.mtm_cert_details));
661 for (X509Certificate c : chain) {
662 certDetails(si, c);
663 }
664 return si.toString();
665 }
666
667 private String hostNameMessage(X509Certificate cert, String hostname) {
668 StringBuffer si = new StringBuffer();
669
670 si.append(master.getString(R.string.mtm_hostname_mismatch, hostname));
671 si.append("\n\n");
672 try {
673 Collection<List<?>> sans = cert.getSubjectAlternativeNames();
674 if (sans == null) {
675 si.append(cert.getSubjectDN());
676 si.append("\n");
677 } else for (List<?> altName : sans) {
678 Object name = altName.get(1);
679 if (name instanceof String) {
680 si.append("[");
681 si.append((Integer)altName.get(0));
682 si.append("] ");
683 si.append(name);
684 si.append("\n");
685 }
686 }
687 } catch (CertificateParsingException e) {
688 e.printStackTrace();
689 si.append("<Parsing error: ");
690 si.append(e.getLocalizedMessage());
691 si.append(">\n");
692 }
693 si.append("\n");
694 si.append(master.getString(R.string.mtm_connect_anyway));
695 si.append("\n\n");
696 si.append(master.getString(R.string.mtm_cert_details));
697 certDetails(si, cert);
698 return si.toString();
699 }
700 /**
701 * Returns the top-most entry of the activity stack.
702 *
703 * @return the Context of the currently bound UI or the master context if none is bound
704 */
705 Context getUI() {
706 return (foregroundAct != null) ? foregroundAct : master;
707 }
708
709 int interact(final String message, final int titleId) {
710 /* prepare the MTMDecision blocker object */
711 MTMDecision choice = new MTMDecision();
712 final int myId = createDecisionId(choice);
713
714 masterHandler.post(new Runnable() {
715 public void run() {
716 Intent ni = new Intent(master, MemorizingActivity.class);
717 ni.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
718 ni.setData(Uri.parse(MemorizingTrustManager.class.getName() + "/" + myId));
719 ni.putExtra(DECISION_INTENT_ID, myId);
720 ni.putExtra(DECISION_INTENT_CERT, message);
721 ni.putExtra(DECISION_TITLE_ID, titleId);
722
723 // we try to directly start the activity and fall back to
724 // making a notification
725 try {
726 getUI().startActivity(ni);
727 } catch (Exception e) {
728 LOGGER.log(Level.FINE, "startActivity(MemorizingActivity)", e);
729 }
730 }
731 });
732
733 LOGGER.log(Level.FINE, "openDecisions: " + openDecisions + ", waiting on " + myId);
734 try {
735 synchronized(choice) { choice.wait(); }
736 } catch (InterruptedException e) {
737 LOGGER.log(Level.FINER, "InterruptedException", e);
738 }
739 LOGGER.log(Level.FINE, "finished wait on " + myId + ": " + choice.state);
740 return choice.state;
741 }
742
743 void interactCert(final X509Certificate[] chain, String authType, CertificateException cause)
744 throws CertificateException
745 {
746 switch (interact(certChainMessage(chain, cause), R.string.mtm_accept_cert)) {
747 case MTMDecision.DECISION_ALWAYS:
748 storeCert(chain[0]); // only store the server cert, not the whole chain
749 case MTMDecision.DECISION_ONCE:
750 break;
751 default:
752 throw (cause);
753 }
754 }
755
756 boolean interactHostname(X509Certificate cert, String hostname)
757 {
758 switch (interact(hostNameMessage(cert, hostname), R.string.mtm_accept_servername)) {
759 case MTMDecision.DECISION_ALWAYS:
760 storeCert(hostname, cert);
761 case MTMDecision.DECISION_ONCE:
762 return true;
763 default:
764 return false;
765 }
766 }
767
768 protected static void interactResult(int decisionId, int choice) {
769 MTMDecision d;
770 synchronized(openDecisions) {
771 d = openDecisions.get(decisionId);
772 openDecisions.remove(decisionId);
773 }
774 if (d == null) {
775 LOGGER.log(Level.SEVERE, "interactResult: aborting due to stale decision reference!");
776 return;
777 }
778 synchronized(d) {
779 d.state = choice;
780 d.notify();
781 }
782 }
783
784 class MemorizingHostnameVerifier implements HostnameVerifier {
785 private HostnameVerifier defaultVerifier;
786
787 public MemorizingHostnameVerifier(HostnameVerifier wrapped) {
788 defaultVerifier = wrapped;
789 }
790
791 protected boolean verify(String hostname, SSLSession session, boolean interactive) {
792 LOGGER.log(Level.FINE, "hostname verifier for " + hostname + ", trying default verifier first");
793 // if the default verifier accepts the hostname, we are done
794 if (defaultVerifier.verify(hostname, session)) {
795 LOGGER.log(Level.FINE, "default verifier accepted " + hostname);
796 return true;
797 }
798 // otherwise, we check if the hostname is an alias for this cert in our keystore
799 try {
800 X509Certificate cert = (X509Certificate)session.getPeerCertificates()[0];
801 //Log.d(TAG, "cert: " + cert);
802 if (cert.equals(appKeyStore.getCertificate(hostname.toLowerCase(Locale.US)))) {
803 LOGGER.log(Level.FINE, "certificate for " + hostname + " is in our keystore. accepting.");
804 return true;
805 } else {
806 LOGGER.log(Level.FINE, "server " + hostname + " provided wrong certificate, asking user.");
807 if (interactive) {
808 return interactHostname(cert, hostname);
809 } else {
810 return false;
811 }
812 }
813 } catch (Exception e) {
814 e.printStackTrace();
815 return false;
816 }
817 }
818
819 @Override
820 public boolean verify(String hostname, SSLSession session) {
821 return verify(hostname, session, true);
822 }
823 }
824
825 class NonInteractiveMemorizingHostnameVerifier extends MemorizingHostnameVerifier {
826
827 public NonInteractiveMemorizingHostnameVerifier(HostnameVerifier wrapped) {
828 super(wrapped);
829 }
830 @Override
831 public boolean verify(String hostname, SSLSession session) {
832 return verify(hostname, session, false);
833 }
834
835
836 }
837
838 public X509TrustManager getNonInteractive(String domain) {
839 return new NonInteractiveMemorizingTrustManager(domain);
840 }
841
842 public X509TrustManager getInteractive(String domain) {
843 return new InteractiveMemorizingTrustManager(domain);
844 }
845
846 public X509TrustManager getNonInteractive() {
847 return new NonInteractiveMemorizingTrustManager(null);
848 }
849
850 public X509TrustManager getInteractive() {
851 return new InteractiveMemorizingTrustManager(null);
852 }
853
854 private class NonInteractiveMemorizingTrustManager implements X509TrustManager {
855
856 private final String domain;
857
858 public NonInteractiveMemorizingTrustManager(String domain) {
859 this.domain = domain;
860 }
861
862 @Override
863 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
864 MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, false, false);
865 }
866
867 @Override
868 public void checkServerTrusted(X509Certificate[] chain, String authType)
869 throws CertificateException {
870 MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, true, false);
871 }
872
873 @Override
874 public X509Certificate[] getAcceptedIssuers() {
875 return MemorizingTrustManager.this.getAcceptedIssuers();
876 }
877
878 }
879
880 private class InteractiveMemorizingTrustManager implements X509TrustManager {
881 private final String domain;
882
883 public InteractiveMemorizingTrustManager(String domain) {
884 this.domain = domain;
885 }
886
887 @Override
888 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
889 MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, false, true);
890 }
891
892 @Override
893 public void checkServerTrusted(X509Certificate[] chain, String authType)
894 throws CertificateException {
895 MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, true, true);
896 }
897
898 @Override
899 public X509Certificate[] getAcceptedIssuers() {
900 return MemorizingTrustManager.this.getAcceptedIssuers();
901 }
902 }
903}