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