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