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 File file = getPoshCacheFile(domain);
594 try {
595 InputStream is = new FileInputStream(file);
596 BufferedReader buf = new BufferedReader(new InputStreamReader(is));
597
598 String line = buf.readLine();
599 StringBuilder sb = new StringBuilder();
600
601 while (line != null) {
602 sb.append(line).append("\n");
603 line = buf.readLine();
604 }
605 JSONObject jsonObject = new JSONObject(sb.toString());
606 is.close();
607 long expires = jsonObject.getLong("expires");
608 long expiresIn = expires - System.currentTimeMillis();
609 if (expiresIn < 0) {
610 file.delete();
611 return null;
612 } else {
613 Log.d("mtm", "posh fingerprints expire in " + (expiresIn / 1000) + "s");
614 }
615 List<String> result = new ArrayList<>();
616 JSONArray jsonArray = jsonObject.getJSONArray("fingerprints");
617 for (int i = 0; i < jsonArray.length(); ++i) {
618 result.add(jsonArray.getString(i));
619 }
620 return result;
621 } catch (FileNotFoundException e) {
622 return null;
623 } catch (IOException e) {
624 return null;
625 } catch (JSONException e) {
626 file.delete();
627 return null;
628 }
629 }
630
631 private X509Certificate[] getAcceptedIssuers() {
632 LOGGER.log(Level.FINE, "getAcceptedIssuers()");
633 return defaultTrustManager.getAcceptedIssuers();
634 }
635
636 private int createDecisionId(MTMDecision d) {
637 int myId;
638 synchronized (openDecisions) {
639 myId = decisionId;
640 openDecisions.put(myId, d);
641 decisionId += 1;
642 }
643 return myId;
644 }
645
646 private void certDetails(StringBuffer si, X509Certificate c) {
647 SimpleDateFormat validityDateFormater = new SimpleDateFormat("yyyy-MM-dd");
648 si.append("\n");
649 si.append(c.getSubjectDN().toString());
650 si.append("\n");
651 si.append(validityDateFormater.format(c.getNotBefore()));
652 si.append(" - ");
653 si.append(validityDateFormater.format(c.getNotAfter()));
654 si.append("\nSHA-256: ");
655 si.append(certHash(c, "SHA-256"));
656 si.append("\nSHA-1: ");
657 si.append(certHash(c, "SHA-1"));
658 si.append("\nSigned by: ");
659 si.append(c.getIssuerDN().toString());
660 si.append("\n");
661 }
662
663 private String certChainMessage(final X509Certificate[] chain, CertificateException cause) {
664 Throwable e = cause;
665 LOGGER.log(Level.FINE, "certChainMessage for " + e);
666 StringBuffer si = new StringBuffer();
667 if (e.getCause() != null) {
668 e = e.getCause();
669 // HACK: there is no sane way to check if the error is a "trust anchor
670 // not found", so we use string comparison.
671 if (NO_TRUST_ANCHOR.equals(e.getMessage())) {
672 si.append(master.getString(R.string.mtm_trust_anchor));
673 } else
674 si.append(e.getLocalizedMessage());
675 si.append("\n");
676 }
677 si.append("\n");
678 si.append(master.getString(R.string.mtm_connect_anyway));
679 si.append("\n\n");
680 si.append(master.getString(R.string.mtm_cert_details));
681 for (X509Certificate c : chain) {
682 certDetails(si, c);
683 }
684 return si.toString();
685 }
686
687 private String hostNameMessage(X509Certificate cert, String hostname) {
688 StringBuffer si = new StringBuffer();
689
690 si.append(master.getString(R.string.mtm_hostname_mismatch, hostname));
691 si.append("\n\n");
692 try {
693 Collection<List<?>> sans = cert.getSubjectAlternativeNames();
694 if (sans == null) {
695 si.append(cert.getSubjectDN());
696 si.append("\n");
697 } else for (List<?> altName : sans) {
698 Object name = altName.get(1);
699 if (name instanceof String) {
700 si.append("[");
701 si.append(altName.get(0));
702 si.append("] ");
703 si.append(name);
704 si.append("\n");
705 }
706 }
707 } catch (CertificateParsingException e) {
708 e.printStackTrace();
709 si.append("<Parsing error: ");
710 si.append(e.getLocalizedMessage());
711 si.append(">\n");
712 }
713 si.append("\n");
714 si.append(master.getString(R.string.mtm_connect_anyway));
715 si.append("\n\n");
716 si.append(master.getString(R.string.mtm_cert_details));
717 certDetails(si, cert);
718 return si.toString();
719 }
720
721 /**
722 * Returns the top-most entry of the activity stack.
723 *
724 * @return the Context of the currently bound UI or the master context if none is bound
725 */
726 Context getUI() {
727 return (foregroundAct != null) ? foregroundAct : master;
728 }
729
730 int interact(final String message, final int titleId) {
731 /* prepare the MTMDecision blocker object */
732 MTMDecision choice = new MTMDecision();
733 final int myId = createDecisionId(choice);
734
735 masterHandler.post(new Runnable() {
736 public void run() {
737 Intent ni = new Intent(master, MemorizingActivity.class);
738 ni.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
739 ni.setData(Uri.parse(MemorizingTrustManager.class.getName() + "/" + myId));
740 ni.putExtra(DECISION_INTENT_ID, myId);
741 ni.putExtra(DECISION_INTENT_CERT, message);
742 ni.putExtra(DECISION_TITLE_ID, titleId);
743
744 // we try to directly start the activity and fall back to
745 // making a notification
746 try {
747 getUI().startActivity(ni);
748 } catch (Exception e) {
749 LOGGER.log(Level.FINE, "startActivity(MemorizingActivity)", e);
750 }
751 }
752 });
753
754 LOGGER.log(Level.FINE, "openDecisions: " + openDecisions + ", waiting on " + myId);
755 try {
756 synchronized (choice) {
757 choice.wait();
758 }
759 } catch (InterruptedException e) {
760 LOGGER.log(Level.FINER, "InterruptedException", e);
761 }
762 LOGGER.log(Level.FINE, "finished wait on " + myId + ": " + choice.state);
763 return choice.state;
764 }
765
766 void interactCert(final X509Certificate[] chain, String authType, CertificateException cause)
767 throws CertificateException {
768 switch (interact(certChainMessage(chain, cause), R.string.mtm_accept_cert)) {
769 case MTMDecision.DECISION_ALWAYS:
770 storeCert(chain[0]); // only store the server cert, not the whole chain
771 case MTMDecision.DECISION_ONCE:
772 break;
773 default:
774 throw (cause);
775 }
776 }
777
778 boolean interactHostname(X509Certificate cert, String hostname) {
779 switch (interact(hostNameMessage(cert, hostname), R.string.mtm_accept_servername)) {
780 case MTMDecision.DECISION_ALWAYS:
781 storeCert(hostname, cert);
782 case MTMDecision.DECISION_ONCE:
783 return true;
784 default:
785 return false;
786 }
787 }
788
789 public X509TrustManager getNonInteractive(String domain) {
790 return new NonInteractiveMemorizingTrustManager(domain);
791 }
792
793 public X509TrustManager getInteractive(String domain) {
794 return new InteractiveMemorizingTrustManager(domain);
795 }
796
797 public X509TrustManager getNonInteractive() {
798 return new NonInteractiveMemorizingTrustManager(null);
799 }
800
801 public X509TrustManager getInteractive() {
802 return new InteractiveMemorizingTrustManager(null);
803 }
804
805 class MemorizingHostnameVerifier implements DomainHostnameVerifier {
806 private final HostnameVerifier defaultVerifier;
807 private final boolean interactive;
808
809 public MemorizingHostnameVerifier(HostnameVerifier wrapped, boolean interactive) {
810 this.defaultVerifier = wrapped;
811 this.interactive = interactive;
812 }
813
814 @Override
815 public boolean verify(String domain, String hostname, SSLSession session) {
816 LOGGER.log(Level.FINE, "hostname verifier for " + domain + ", trying default verifier first");
817 // if the default verifier accepts the hostname, we are done
818 if (defaultVerifier instanceof DomainHostnameVerifier) {
819 if (((DomainHostnameVerifier) defaultVerifier).verify(domain, hostname, session)) {
820 return true;
821 }
822 } else {
823 if (defaultVerifier.verify(domain, session)) {
824 return true;
825 }
826 }
827
828
829 // otherwise, we check if the hostname is an alias for this cert in our keystore
830 try {
831 X509Certificate cert = (X509Certificate) session.getPeerCertificates()[0];
832 //Log.d(TAG, "cert: " + cert);
833 if (cert.equals(appKeyStore.getCertificate(domain.toLowerCase(Locale.US)))) {
834 LOGGER.log(Level.FINE, "certificate for " + domain + " is in our keystore. accepting.");
835 return true;
836 } else {
837 LOGGER.log(Level.FINE, "server " + domain + " provided wrong certificate, asking user.");
838 if (interactive) {
839 return interactHostname(cert, domain);
840 } else {
841 return false;
842 }
843 }
844 } catch (Exception e) {
845 e.printStackTrace();
846 return false;
847 }
848 }
849
850 @Override
851 public boolean verify(String domain, SSLSession sslSession) {
852 return verify(domain, null, sslSession);
853 }
854 }
855
856 private class NonInteractiveMemorizingTrustManager implements X509TrustManager {
857
858 private final String domain;
859
860 public NonInteractiveMemorizingTrustManager(String domain) {
861 this.domain = domain;
862 }
863
864 @Override
865 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
866 MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, false, false);
867 }
868
869 @Override
870 public void checkServerTrusted(X509Certificate[] chain, String authType)
871 throws CertificateException {
872 MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, true, false);
873 }
874
875 @Override
876 public X509Certificate[] getAcceptedIssuers() {
877 return MemorizingTrustManager.this.getAcceptedIssuers();
878 }
879
880 }
881
882 private class InteractiveMemorizingTrustManager implements X509TrustManager {
883 private final String domain;
884
885 public InteractiveMemorizingTrustManager(String domain) {
886 this.domain = domain;
887 }
888
889 @Override
890 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
891 MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, false, true);
892 }
893
894 @Override
895 public void checkServerTrusted(X509Certificate[] chain, String authType)
896 throws CertificateException {
897 MemorizingTrustManager.this.checkCertTrusted(chain, authType, domain, true, true);
898 }
899
900 @Override
901 public X509Certificate[] getAcceptedIssuers() {
902 return MemorizingTrustManager.this.getAcceptedIssuers();
903 }
904 }
905}