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