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 try {
462 List<String> results = new ArrayList<>();
463 URL url = new URL("https://"+domain+"/.well-known/posh/xmpp-client.json");
464 HttpsURLConnection connection = (HttpsURLConnection) 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 JSONArray fingerprints = jsonObject.getJSONArray("fingerprints");
476 for(int i = 0; i < fingerprints.length(); i++) {
477 JSONObject fingerprint = fingerprints.getJSONObject(i);
478 String sha256 = fingerprint.getString("sha-256");
479 if (sha256 != null) {
480 results.add(sha256);
481 }
482 }
483 int expires = jsonObject.getInt("expires");
484 if (expires <= 0) {
485 return new ArrayList<>();
486 }
487 in.close();
488 writeFingerprintsToCache(domain, results,1000L * expires+System.currentTimeMillis());
489 return results;
490 } catch (Exception e) {
491 Log.d("mtm","error fetching posh "+e.getMessage());
492 return new ArrayList<>();
493 }
494 }
495
496 private File getPoshCacheFile(String domain) {
497 return new File(poshCacheDir+domain+".json");
498 }
499
500 private void writeFingerprintsToCache(String domain, List<String> results, long expires) {
501 File file = getPoshCacheFile(domain);
502 file.getParentFile().mkdirs();
503 try {
504 file.createNewFile();
505 JSONObject jsonObject = new JSONObject();
506 jsonObject.put("expires",expires);
507 jsonObject.put("fingerprints",new JSONArray(results));
508 FileOutputStream outputStream = new FileOutputStream(file);
509 outputStream.write(jsonObject.toString().getBytes());
510 outputStream.flush();
511 outputStream.close();
512 } catch (Exception e) {
513 e.printStackTrace();
514 }
515 }
516
517 private List<String> getPoshFingerprintsFromCache(String domain) {
518 File file = getPoshCacheFile(domain);
519 try {
520 InputStream is = new FileInputStream(file);
521 BufferedReader buf = new BufferedReader(new InputStreamReader(is));
522
523 String line = buf.readLine();
524 StringBuilder sb = new StringBuilder();
525
526 while(line != null){
527 sb.append(line).append("\n");
528 line = buf.readLine();
529 }
530 JSONObject jsonObject = new JSONObject(sb.toString());
531 is.close();
532 long expires = jsonObject.getLong("expires");
533 long expiresIn = expires - System.currentTimeMillis();
534 if (expiresIn < 0) {
535 file.delete();
536 return null;
537 } else {
538 Log.d("mtm","posh fingerprints expire in "+(expiresIn/1000)+"s");
539 }
540 List<String> result = new ArrayList<>();
541 JSONArray jsonArray = jsonObject.getJSONArray("fingerprints");
542 for(int i = 0; i < jsonArray.length(); ++i) {
543 result.add(jsonArray.getString(i));
544 }
545 return result;
546 } catch (FileNotFoundException e) {
547 return null;
548 } catch (IOException e) {
549 return null;
550 } catch (JSONException e) {
551 file.delete();
552 return null;
553 }
554 }
555
556 private static boolean isIp(final String server) {
557 return server != null && (
558 PATTERN_IPV4.matcher(server).matches()
559 || PATTERN_IPV6.matcher(server).matches()
560 || PATTERN_IPV6_6HEX4DEC.matcher(server).matches()
561 || PATTERN_IPV6_HEX4DECCOMPRESSED.matcher(server).matches()
562 || PATTERN_IPV6_HEXCOMPRESSED.matcher(server).matches());
563 }
564
565 private static String getBase64Hash(X509Certificate certificate, String digest) throws CertificateEncodingException {
566 MessageDigest md;
567 try {
568 md = MessageDigest.getInstance(digest);
569 } catch (NoSuchAlgorithmException e) {
570 return null;
571 }
572 md.update(certificate.getEncoded());
573 return Base64.encodeToString(md.digest(),Base64.NO_WRAP);
574 }
575
576 private X509Certificate[] getAcceptedIssuers() {
577 LOGGER.log(Level.FINE, "getAcceptedIssuers()");
578 return defaultTrustManager.getAcceptedIssuers();
579 }
580
581 private int createDecisionId(MTMDecision d) {
582 int myId;
583 synchronized(openDecisions) {
584 myId = decisionId;
585 openDecisions.put(myId, d);
586 decisionId += 1;
587 }
588 return myId;
589 }
590
591 private static String hexString(byte[] data) {
592 StringBuffer si = new StringBuffer();
593 for (int i = 0; i < data.length; i++) {
594 si.append(String.format("%02x", data[i]));
595 if (i < data.length - 1)
596 si.append(":");
597 }
598 return si.toString();
599 }
600
601 private static String certHash(final X509Certificate cert, String digest) {
602 try {
603 MessageDigest md = MessageDigest.getInstance(digest);
604 md.update(cert.getEncoded());
605 return hexString(md.digest());
606 } catch (java.security.cert.CertificateEncodingException e) {
607 return e.getMessage();
608 } catch (java.security.NoSuchAlgorithmException e) {
609 return e.getMessage();
610 }
611 }
612
613 private void certDetails(StringBuffer si, X509Certificate c) {
614 SimpleDateFormat validityDateFormater = new SimpleDateFormat("yyyy-MM-dd");
615 si.append("\n");
616 si.append(c.getSubjectDN().toString());
617 si.append("\n");
618 si.append(validityDateFormater.format(c.getNotBefore()));
619 si.append(" - ");
620 si.append(validityDateFormater.format(c.getNotAfter()));
621 si.append("\nSHA-256: ");
622 si.append(certHash(c, "SHA-256"));
623 si.append("\nSHA-1: ");
624 si.append(certHash(c, "SHA-1"));
625 si.append("\nSigned by: ");
626 si.append(c.getIssuerDN().toString());
627 si.append("\n");
628 }
629
630 private String certChainMessage(final X509Certificate[] chain, CertificateException cause) {
631 Throwable e = cause;
632 LOGGER.log(Level.FINE, "certChainMessage for " + e);
633 StringBuffer si = new StringBuffer();
634 if (e.getCause() != null) {
635 e = e.getCause();
636 // HACK: there is no sane way to check if the error is a "trust anchor
637 // not found", so we use string comparison.
638 if (NO_TRUST_ANCHOR.equals(e.getMessage())) {
639 si.append(master.getString(R.string.mtm_trust_anchor));
640 } else
641 si.append(e.getLocalizedMessage());
642 si.append("\n");
643 }
644 si.append("\n");
645 si.append(master.getString(R.string.mtm_connect_anyway));
646 si.append("\n\n");
647 si.append(master.getString(R.string.mtm_cert_details));
648 for (X509Certificate c : chain) {
649 certDetails(si, c);
650 }
651 return si.toString();
652 }
653
654 private String hostNameMessage(X509Certificate cert, String hostname) {
655 StringBuffer si = new StringBuffer();
656
657 si.append(master.getString(R.string.mtm_hostname_mismatch, hostname));
658 si.append("\n\n");
659 try {
660 Collection<List<?>> sans = cert.getSubjectAlternativeNames();
661 if (sans == null) {
662 si.append(cert.getSubjectDN());
663 si.append("\n");
664 } else for (List<?> altName : sans) {
665 Object name = altName.get(1);
666 if (name instanceof String) {
667 si.append("[");
668 si.append((Integer)altName.get(0));
669 si.append("] ");
670 si.append(name);
671 si.append("\n");
672 }
673 }
674 } catch (CertificateParsingException e) {
675 e.printStackTrace();
676 si.append("<Parsing error: ");
677 si.append(e.getLocalizedMessage());
678 si.append(">\n");
679 }
680 si.append("\n");
681 si.append(master.getString(R.string.mtm_connect_anyway));
682 si.append("\n\n");
683 si.append(master.getString(R.string.mtm_cert_details));
684 certDetails(si, cert);
685 return si.toString();
686 }
687 /**
688 * Returns the top-most entry of the activity stack.
689 *
690 * @return the Context of the currently bound UI or the master context if none is bound
691 */
692 Context getUI() {
693 return (foregroundAct != null) ? foregroundAct : master;
694 }
695
696 int interact(final String message, final int titleId) {
697 /* prepare the MTMDecision blocker object */
698 MTMDecision choice = new MTMDecision();
699 final int myId = createDecisionId(choice);
700
701 masterHandler.post(new Runnable() {
702 public void run() {
703 Intent ni = new Intent(master, MemorizingActivity.class);
704 ni.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
705 ni.setData(Uri.parse(MemorizingTrustManager.class.getName() + "/" + myId));
706 ni.putExtra(DECISION_INTENT_ID, myId);
707 ni.putExtra(DECISION_INTENT_CERT, message);
708 ni.putExtra(DECISION_TITLE_ID, titleId);
709
710 // we try to directly start the activity and fall back to
711 // making a notification
712 try {
713 getUI().startActivity(ni);
714 } catch (Exception e) {
715 LOGGER.log(Level.FINE, "startActivity(MemorizingActivity)", e);
716 }
717 }
718 });
719
720 LOGGER.log(Level.FINE, "openDecisions: " + openDecisions + ", waiting on " + myId);
721 try {
722 synchronized(choice) { choice.wait(); }
723 } catch (InterruptedException e) {
724 LOGGER.log(Level.FINER, "InterruptedException", e);
725 }
726 LOGGER.log(Level.FINE, "finished wait on " + myId + ": " + choice.state);
727 return choice.state;
728 }
729
730 void interactCert(final X509Certificate[] chain, String authType, CertificateException cause)
731 throws CertificateException
732 {
733 switch (interact(certChainMessage(chain, cause), R.string.mtm_accept_cert)) {
734 case MTMDecision.DECISION_ALWAYS:
735 storeCert(chain[0]); // only store the server cert, not the whole chain
736 case MTMDecision.DECISION_ONCE:
737 break;
738 default:
739 throw (cause);
740 }
741 }
742
743 boolean interactHostname(X509Certificate cert, String hostname)
744 {
745 switch (interact(hostNameMessage(cert, hostname), R.string.mtm_accept_servername)) {
746 case MTMDecision.DECISION_ALWAYS:
747 storeCert(hostname, cert);
748 case MTMDecision.DECISION_ONCE:
749 return true;
750 default:
751 return false;
752 }
753 }
754
755 protected static void interactResult(int decisionId, int choice) {
756 MTMDecision d;
757 synchronized(openDecisions) {
758 d = openDecisions.get(decisionId);
759 openDecisions.remove(decisionId);
760 }
761 if (d == null) {
762 LOGGER.log(Level.SEVERE, "interactResult: aborting due to stale decision reference!");
763 return;
764 }
765 synchronized(d) {
766 d.state = choice;
767 d.notify();
768 }
769 }
770
771 class MemorizingHostnameVerifier implements HostnameVerifier {
772 private HostnameVerifier defaultVerifier;
773
774 public MemorizingHostnameVerifier(HostnameVerifier wrapped) {
775 defaultVerifier = wrapped;
776 }
777
778 protected boolean verify(String hostname, SSLSession session, boolean interactive) {
779 LOGGER.log(Level.FINE, "hostname verifier for " + hostname + ", trying default verifier first");
780 // if the default verifier accepts the hostname, we are done
781 if (defaultVerifier.verify(hostname, session)) {
782 LOGGER.log(Level.FINE, "default verifier accepted " + hostname);
783 return true;
784 }
785 // otherwise, we check if the hostname is an alias for this cert in our keystore
786 try {
787 X509Certificate cert = (X509Certificate)session.getPeerCertificates()[0];
788 //Log.d(TAG, "cert: " + cert);
789 if (cert.equals(appKeyStore.getCertificate(hostname.toLowerCase(Locale.US)))) {
790 LOGGER.log(Level.FINE, "certificate for " + hostname + " is in our keystore. accepting.");
791 return true;
792 } else {
793 LOGGER.log(Level.FINE, "server " + hostname + " provided wrong certificate, asking user.");
794 if (interactive) {
795 return interactHostname(cert, hostname);
796 } else {
797 return false;
798 }
799 }
800 } catch (Exception e) {
801 e.printStackTrace();
802 return false;
803 }
804 }
805
806 @Override
807 public boolean verify(String hostname, SSLSession session) {
808 return verify(hostname, session, true);
809 }
810 }
811
812 class NonInteractiveMemorizingHostnameVerifier extends MemorizingHostnameVerifier {
813
814 public NonInteractiveMemorizingHostnameVerifier(HostnameVerifier wrapped) {
815 super(wrapped);
816 }
817 @Override
818 public boolean verify(String hostname, SSLSession session) {
819 return verify(hostname, session, false);
820 }
821
822
823 }
824
825 public X509TrustManager getNonInteractive(String domain) {
826 return new NonInteractiveMemorizingTrustManager(domain);
827 }
828
829 public X509TrustManager getInteractive(String domain) {
830 return new InteractiveMemorizingTrustManager(domain);
831 }
832
833 public X509TrustManager getNonInteractive() {
834 return new NonInteractiveMemorizingTrustManager(null);
835 }
836
837 public X509TrustManager getInteractive() {
838 return new InteractiveMemorizingTrustManager(null);
839 }
840
841 private class NonInteractiveMemorizingTrustManager implements X509TrustManager {
842
843 private final String domain;
844
845 public NonInteractiveMemorizingTrustManager(String domain) {
846 this.domain = domain;
847 }
848
849 @Override
850 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
851 MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, false, false);
852 }
853
854 @Override
855 public void checkServerTrusted(X509Certificate[] chain, String authType)
856 throws CertificateException {
857 MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, true, false);
858 }
859
860 @Override
861 public X509Certificate[] getAcceptedIssuers() {
862 return MemorizingTrustManager.this.getAcceptedIssuers();
863 }
864
865 }
866
867 private class InteractiveMemorizingTrustManager implements X509TrustManager {
868 private final String domain;
869
870 public InteractiveMemorizingTrustManager(String domain) {
871 this.domain = domain;
872 }
873
874 @Override
875 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
876 MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, false, true);
877 }
878
879 @Override
880 public void checkServerTrusted(X509Certificate[] chain, String authType)
881 throws CertificateException {
882 MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, true, true);
883 }
884
885 @Override
886 public X509Certificate[] getAcceptedIssuers() {
887 return MemorizingTrustManager.this.getAcceptedIssuers();
888 }
889 }
890}