close FileInputStream in MTM. fixes #1150

This commit is contained in:
Daniel Gultsch 2020-03-26 08:25:22 +01:00
parent 3cf469a43b
commit 4e33ebb308
1 changed files with 818 additions and 815 deletions

View File

@ -26,18 +26,18 @@
*/ */
package eu.siacs.conversations.services; package eu.siacs.conversations.services;
import android.support.v7.app.AppCompatActivity ;
import android.app.Application; import android.app.Application;
import android.app.NotificationManager; import android.app.NotificationManager;
import android.app.Service; import android.app.Service;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.net.Uri; import android.net.Uri;
import android.os.Handler;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64; import android.util.Base64;
import android.util.Log; import android.util.Log;
import android.util.SparseArray; import android.util.SparseArray;
import android.os.Handler;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
@ -52,19 +52,24 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.URL; import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.security.cert.*;
import java.security.KeyStore; import java.security.KeyStore;
import java.security.KeyStoreException; import java.security.KeyStoreException;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.util.ArrayList; import java.security.NoSuchAlgorithmException;
import java.util.logging.Level; import java.security.cert.Certificate;
import java.util.logging.Logger; import java.security.cert.CertificateEncodingException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateParsingException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HostnameVerifier;
@ -77,6 +82,7 @@ import javax.net.ssl.X509TrustManager;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.crypto.DomainHostnameVerifier; import eu.siacs.conversations.crypto.DomainHostnameVerifier;
import eu.siacs.conversations.entities.MTMDecision; import eu.siacs.conversations.entities.MTMDecision;
import eu.siacs.conversations.persistance.FileBackend;
import eu.siacs.conversations.ui.MemorizingActivity; import eu.siacs.conversations.ui.MemorizingActivity;
/** /**
@ -92,32 +98,26 @@ import eu.siacs.conversations.ui.MemorizingActivity;
public class MemorizingTrustManager { public class MemorizingTrustManager {
final static String DECISION_INTENT = "de.duenndns.ssl.DECISION";
public final static String DECISION_INTENT_ID = DECISION_INTENT + ".decisionId";
public final static String DECISION_INTENT_CERT = DECISION_INTENT + ".cert";
public final static String DECISION_TITLE_ID = DECISION_INTENT + ".titleId";
final static String DECISION_INTENT_CHOICE = DECISION_INTENT + ".decisionChoice";
final static String NO_TRUST_ANCHOR = "Trust anchor for certification path not found.";
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"); 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");
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"); 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");
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"); 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");
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"); 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");
private static final Pattern PATTERN_IPV6 = Pattern.compile("\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z"); private static final Pattern PATTERN_IPV6 = Pattern.compile("\\A(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\\z");
final static String DECISION_INTENT = "de.duenndns.ssl.DECISION";
public final static String DECISION_INTENT_ID = DECISION_INTENT + ".decisionId";
public final static String DECISION_INTENT_CERT = DECISION_INTENT + ".cert";
final static String DECISION_INTENT_CHOICE = DECISION_INTENT + ".decisionChoice";
private final static Logger LOGGER = Logger.getLogger(MemorizingTrustManager.class.getName()); private final static Logger LOGGER = Logger.getLogger(MemorizingTrustManager.class.getName());
public final static String DECISION_TITLE_ID = DECISION_INTENT + ".titleId";
private final static int NOTIFICATION_ID = 100509; private final static int NOTIFICATION_ID = 100509;
final static String NO_TRUST_ANCHOR = "Trust anchor for certification path not found.";
static String KEYSTORE_DIR = "KeyStore"; static String KEYSTORE_DIR = "KeyStore";
static String KEYSTORE_FILE = "KeyStore.bks"; static String KEYSTORE_FILE = "KeyStore.bks";
private static int decisionId = 0;
private static SparseArray<MTMDecision> openDecisions = new SparseArray<MTMDecision>();
Context master; Context master;
AppCompatActivity foregroundAct; AppCompatActivity foregroundAct;
NotificationManager notificationManager; NotificationManager notificationManager;
private static int decisionId = 0;
private static SparseArray<MTMDecision> openDecisions = new SparseArray<MTMDecision>();
Handler masterHandler; Handler masterHandler;
private File keyStoreFile; private File keyStoreFile;
private KeyStore appKeyStore; private KeyStore appKeyStore;
@ -125,13 +125,14 @@ public class MemorizingTrustManager {
private X509TrustManager appTrustManager; private X509TrustManager appTrustManager;
private String poshCacheDir; private String poshCacheDir;
/** Creates an instance of the MemorizingTrustManager class that falls back to a custom TrustManager. /**
* * Creates an instance of the MemorizingTrustManager class that falls back to a custom TrustManager.
* <p>
* You need to supply the application context. This has to be one of: * You need to supply the application context. This has to be one of:
* - Application * - Application
* - Activity * - Activity
* - Service * - Service
* * <p>
* The context is used for file management, to display the dialog / * The context is used for file management, to display the dialog /
* notification and for obtaining translated strings. * notification and for obtaining translated strings.
* *
@ -144,13 +145,14 @@ public class MemorizingTrustManager {
this.defaultTrustManager = defaultTrustManager; this.defaultTrustManager = defaultTrustManager;
} }
/** Creates an instance of the MemorizingTrustManager class using the system X509TrustManager. /**
* * Creates an instance of the MemorizingTrustManager class using the system X509TrustManager.
* <p>
* You need to supply the application context. This has to be one of: * You need to supply the application context. This has to be one of:
* - Application * - Application
* - Activity * - Activity
* - Service * - Service
* * <p>
* The context is used for file management, to display the dialog / * The context is used for file management, to display the dialog /
* notification and for obtaining translated strings. * notification and for obtaining translated strings.
* *
@ -162,36 +164,108 @@ public class MemorizingTrustManager {
this.defaultTrustManager = getTrustManager(null); this.defaultTrustManager = getTrustManager(null);
} }
/**
* Changes the path for the KeyStore file.
* <p>
* The actual filename relative to the app's directory will be
* <code>app_<i>dirname</i>/<i>filename</i></code>.
*
* @param dirname directory to store the KeyStore.
* @param filename file name for the KeyStore.
*/
public static void setKeyStoreFile(String dirname, String filename) {
KEYSTORE_DIR = dirname;
KEYSTORE_FILE = filename;
}
private static boolean isIp(final String server) {
return server != null && (
PATTERN_IPV4.matcher(server).matches()
|| PATTERN_IPV6.matcher(server).matches()
|| PATTERN_IPV6_6HEX4DEC.matcher(server).matches()
|| PATTERN_IPV6_HEX4DECCOMPRESSED.matcher(server).matches()
|| PATTERN_IPV6_HEXCOMPRESSED.matcher(server).matches());
}
private static String getBase64Hash(X509Certificate certificate, String digest) throws CertificateEncodingException {
MessageDigest md;
try {
md = MessageDigest.getInstance(digest);
} catch (NoSuchAlgorithmException e) {
return null;
}
md.update(certificate.getEncoded());
return Base64.encodeToString(md.digest(), Base64.NO_WRAP);
}
private static String hexString(byte[] data) {
StringBuffer si = new StringBuffer();
for (int i = 0; i < data.length; i++) {
si.append(String.format("%02x", data[i]));
if (i < data.length - 1)
si.append(":");
}
return si.toString();
}
private static String certHash(final X509Certificate cert, String digest) {
try {
MessageDigest md = MessageDigest.getInstance(digest);
md.update(cert.getEncoded());
return hexString(md.digest());
} catch (java.security.cert.CertificateEncodingException e) {
return e.getMessage();
} catch (java.security.NoSuchAlgorithmException e) {
return e.getMessage();
}
}
public static void interactResult(int decisionId, int choice) {
MTMDecision d;
synchronized (openDecisions) {
d = openDecisions.get(decisionId);
openDecisions.remove(decisionId);
}
if (d == null) {
LOGGER.log(Level.SEVERE, "interactResult: aborting due to stale decision reference!");
return;
}
synchronized (d) {
d.state = choice;
d.notify();
}
}
void init(Context m) { void init(Context m) {
master = m; master = m;
masterHandler = new Handler(m.getMainLooper()); masterHandler = new Handler(m.getMainLooper());
notificationManager = (NotificationManager)master.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager = (NotificationManager) master.getSystemService(Context.NOTIFICATION_SERVICE);
Application app; Application app;
if (m instanceof Application) { if (m instanceof Application) {
app = (Application)m; app = (Application) m;
} else if (m instanceof Service) { } else if (m instanceof Service) {
app = ((Service)m).getApplication(); app = ((Service) m).getApplication();
} else if (m instanceof AppCompatActivity) { } else if (m instanceof AppCompatActivity) {
app = ((AppCompatActivity)m).getApplication(); app = ((AppCompatActivity) m).getApplication();
} else throw new ClassCastException("MemorizingTrustManager context must be either Activity or Service!"); } else
throw new ClassCastException("MemorizingTrustManager context must be either Activity or Service!");
File dir = app.getDir(KEYSTORE_DIR, Context.MODE_PRIVATE); File dir = app.getDir(KEYSTORE_DIR, Context.MODE_PRIVATE);
keyStoreFile = new File(dir + File.separator + KEYSTORE_FILE); keyStoreFile = new File(dir + File.separator + KEYSTORE_FILE);
poshCacheDir = app.getCacheDir().getAbsolutePath()+"/posh_cache/"; poshCacheDir = app.getCacheDir().getAbsolutePath() + "/posh_cache/";
appKeyStore = loadAppKeyStore(); appKeyStore = loadAppKeyStore();
} }
/** /**
* Binds an Activity to the MTM for displaying the query dialog. * Binds an Activity to the MTM for displaying the query dialog.
* * <p>
* This is useful if your connection is run from a service that is * This is useful if your connection is run from a service that is
* triggered by user interaction -- in such cases the activity is * triggered by user interaction -- in such cases the activity is
* visible and the user tends to ignore the service notification. * visible and the user tends to ignore the service notification.
* * <p>
* You should never have a hidden activity bound to MTM! Use this * You should never have a hidden activity bound to MTM! Use this
* function in onResume() and @see unbindDisplayActivity in onPause(). * function in onResume() and @see unbindDisplayActivity in onPause().
* *
@ -203,7 +277,7 @@ public class MemorizingTrustManager {
/** /**
* Removes an Activity from the MTM display stack. * Removes an Activity from the MTM display stack.
* * <p>
* Always call this function when the Activity added with * Always call this function when the Activity added with
* {@link #bindDisplayActivity(AppCompatActivity)} is hidden. * {@link #bindDisplayActivity(AppCompatActivity)} is hidden.
* *
@ -215,20 +289,6 @@ public class MemorizingTrustManager {
foregroundAct = null; foregroundAct = null;
} }
/**
* Changes the path for the KeyStore file.
*
* The actual filename relative to the app's directory will be
* <code>app_<i>dirname</i>/<i>filename</i></code>.
*
* @param dirname directory to store the KeyStore.
* @param filename file name for the KeyStore.
*/
public static void setKeyStoreFile(String dirname, String filename) {
KEYSTORE_DIR = dirname;
KEYSTORE_FILE = filename;
}
/** /**
* Get a list of all certificate aliases stored in MTM. * Get a list of all certificate aliases stored in MTM.
* *
@ -247,7 +307,6 @@ public class MemorizingTrustManager {
* Get a certificate for a given alias. * Get a certificate for a given alias.
* *
* @param alias the certificate's alias as returned by {@link #getCertificates()}. * @param alias the certificate's alias as returned by {@link #getCertificates()}.
*
* @return the certificate associated with the alias or <tt>null</tt> if none found. * @return the certificate associated with the alias or <tt>null</tt> if none found.
*/ */
public Certificate getCertificate(String alias) { public Certificate getCertificate(String alias) {
@ -268,8 +327,8 @@ public class MemorizingTrustManager {
* (b) new connections are created using TLS renegotiation, without a new cert * (b) new connections are created using TLS renegotiation, without a new cert
* check. * check.
* </p> * </p>
* @param alias the certificate's alias as returned by {@link #getCertificates()}.
* *
* @param alias the certificate's alias as returned by {@link #getCertificates()}.
* @throws KeyStoreException if the certificate could not be deleted. * @throws KeyStoreException if the certificate could not be deleted.
*/ */
public void deleteCertificate(String alias) throws KeyStoreException { public void deleteCertificate(String alias) throws KeyStoreException {
@ -284,7 +343,7 @@ public class MemorizingTrustManager {
* the given instance of {@link MemorizingTrustManager}, and leverages an * the given instance of {@link MemorizingTrustManager}, and leverages an
* existing {@link HostnameVerifier}. The returned verifier performs the * existing {@link HostnameVerifier}. The returned verifier performs the
* following steps, returning as soon as one of them succeeds: * following steps, returning as soon as one of them succeeds:
* </p> * /p>
* <ol> * <ol>
* <li>Success, if the wrapped defaultVerifier accepts the certificate.</li> * <li>Success, if the wrapped defaultVerifier accepts the certificate.</li>
* <li>Success, if the server certificate is stored in the keystore under the given hostname.</li> * <li>Success, if the server certificate is stored in the keystore under the given hostname.</li>
@ -294,7 +353,6 @@ public class MemorizingTrustManager {
* *
* @param defaultVerifier the {@link HostnameVerifier} that should perform the actual check * @param defaultVerifier the {@link HostnameVerifier} that should perform the actual check
* @return a new hostname verifier using the MTM's key store * @return a new hostname verifier using the MTM's key store
*
* @throws IllegalArgumentException if the defaultVerifier parameter is null * @throws IllegalArgumentException if the defaultVerifier parameter is null
*/ */
public DomainHostnameVerifier wrapHostnameVerifier(final HostnameVerifier defaultVerifier, final boolean interactive) { public DomainHostnameVerifier wrapHostnameVerifier(final HostnameVerifier defaultVerifier, final boolean interactive) {
@ -310,7 +368,7 @@ public class MemorizingTrustManager {
tmf.init(ks); tmf.init(ks);
for (TrustManager t : tmf.getTrustManagers()) { for (TrustManager t : tmf.getTrustManagers()) {
if (t instanceof X509TrustManager) { if (t instanceof X509TrustManager) {
return (X509TrustManager)t; return (X509TrustManager) t;
} }
} }
} catch (Exception e) { } catch (Exception e) {
@ -330,13 +388,17 @@ public class MemorizingTrustManager {
LOGGER.log(Level.SEVERE, "getAppKeyStore()", e); LOGGER.log(Level.SEVERE, "getAppKeyStore()", e);
return null; return null;
} }
FileInputStream fileInputStream = null;
try { try {
ks.load(null, null); ks.load(null, null);
ks.load(new java.io.FileInputStream(keyStoreFile), "MTM".toCharArray()); fileInputStream = new FileInputStream(keyStoreFile);
ks.load(fileInputStream, "MTM".toCharArray());
} catch (java.io.FileNotFoundException e) { } catch (java.io.FileNotFoundException e) {
LOGGER.log(Level.INFO, "getAppKeyStore(" + keyStoreFile + ") - file does not exist"); LOGGER.log(Level.INFO, "getAppKeyStore(" + keyStoreFile + ") - file does not exist");
} catch (Exception e) { } catch (Exception e) {
LOGGER.log(Level.SEVERE, "getAppKeyStore(" + keyStoreFile + ")", e); LOGGER.log(Level.SEVERE, "getAppKeyStore(" + keyStoreFile + ")", e);
} finally {
FileBackend.close(fileInputStream);
} }
return ks; return ks;
} }
@ -396,8 +458,7 @@ public class MemorizingTrustManager {
} }
public void checkCertTrusted(X509Certificate[] chain, String authType, String domain, boolean isServer, boolean interactive) public void checkCertTrusted(X509Certificate[] chain, String authType, String domain, boolean isServer, boolean interactive)
throws CertificateException throws CertificateException {
{
LOGGER.log(Level.FINE, "checkCertTrusted(" + chain + ", " + authType + ", " + isServer + ")"); LOGGER.log(Level.FINE, "checkCertTrusted(" + chain + ", " + authType + ", " + isServer + ")");
try { try {
LOGGER.log(Level.FINE, "checkCertTrusted: trying appTrustManager"); LOGGER.log(Level.FINE, "checkCertTrusted: trying appTrustManager");
@ -427,15 +488,15 @@ public class MemorizingTrustManager {
} catch (CertificateException e) { } catch (CertificateException e) {
boolean trustSystemCAs = !PreferenceManager.getDefaultSharedPreferences(master).getBoolean("dont_trust_system_cas", false); boolean trustSystemCAs = !PreferenceManager.getDefaultSharedPreferences(master).getBoolean("dont_trust_system_cas", false);
if (domain != null && isServer && trustSystemCAs && !isIp(domain)) { if (domain != null && isServer && trustSystemCAs && !isIp(domain)) {
final String hash = getBase64Hash(chain[0],"SHA-256"); final String hash = getBase64Hash(chain[0], "SHA-256");
final List<String> fingerprints = getPoshFingerprints(domain); final List<String> fingerprints = getPoshFingerprints(domain);
if (hash != null && fingerprints.size() > 0) { if (hash != null && fingerprints.size() > 0) {
if (fingerprints.contains(hash)) { if (fingerprints.contains(hash)) {
Log.d("mtm","trusted cert fingerprint of "+domain+" via posh"); Log.d("mtm", "trusted cert fingerprint of " + domain + " via posh");
return; return;
} }
if (getPoshCacheFile(domain).delete()) { if (getPoshCacheFile(domain).delete()) {
Log.d("mtm", "deleted posh file for "+domain+" after not being able to verify"); Log.d("mtm", "deleted posh file for " + domain + " after not being able to verify");
} }
} }
} }
@ -458,11 +519,11 @@ public class MemorizingTrustManager {
} }
private List<String> getPoshFingerprintsFromServer(String domain) { private List<String> getPoshFingerprintsFromServer(String domain) {
return getPoshFingerprintsFromServer(domain, "https://"+domain+"/.well-known/posh/xmpp-client.json",-1,true); return getPoshFingerprintsFromServer(domain, "https://" + domain + "/.well-known/posh/xmpp-client.json", -1, true);
} }
private List<String> getPoshFingerprintsFromServer(String domain, String url, int maxTtl, boolean followUrl) { private List<String> getPoshFingerprintsFromServer(String domain, String url, int maxTtl, boolean followUrl) {
Log.d("mtm","downloading json for "+domain+" from "+url); Log.d("mtm", "downloading json for " + domain + " from " + url);
try { try {
List<String> results = new ArrayList<>(); List<String> results = new ArrayList<>();
HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection(); HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
@ -481,7 +542,7 @@ public class MemorizingTrustManager {
return new ArrayList<>(); return new ArrayList<>();
} }
if (maxTtl >= 0) { if (maxTtl >= 0) {
expires = Math.min(maxTtl,expires); expires = Math.min(maxTtl, expires);
} }
String redirect; String redirect;
try { try {
@ -493,23 +554,23 @@ public class MemorizingTrustManager {
return getPoshFingerprintsFromServer(domain, redirect, expires, false); return getPoshFingerprintsFromServer(domain, redirect, expires, false);
} }
JSONArray fingerprints = jsonObject.getJSONArray("fingerprints"); JSONArray fingerprints = jsonObject.getJSONArray("fingerprints");
for(int i = 0; i < fingerprints.length(); i++) { for (int i = 0; i < fingerprints.length(); i++) {
JSONObject fingerprint = fingerprints.getJSONObject(i); JSONObject fingerprint = fingerprints.getJSONObject(i);
String sha256 = fingerprint.getString("sha-256"); String sha256 = fingerprint.getString("sha-256");
if (sha256 != null) { if (sha256 != null) {
results.add(sha256); results.add(sha256);
} }
} }
writeFingerprintsToCache(domain, results,1000L * expires+System.currentTimeMillis()); writeFingerprintsToCache(domain, results, 1000L * expires + System.currentTimeMillis());
return results; return results;
} catch (Exception e) { } catch (Exception e) {
Log.d("mtm","error fetching posh "+e.getMessage()); Log.d("mtm", "error fetching posh " + e.getMessage());
return new ArrayList<>(); return new ArrayList<>();
} }
} }
private File getPoshCacheFile(String domain) { private File getPoshCacheFile(String domain) {
return new File(poshCacheDir+domain+".json"); return new File(poshCacheDir + domain + ".json");
} }
private void writeFingerprintsToCache(String domain, List<String> results, long expires) { private void writeFingerprintsToCache(String domain, List<String> results, long expires) {
@ -518,8 +579,8 @@ public class MemorizingTrustManager {
try { try {
file.createNewFile(); file.createNewFile();
JSONObject jsonObject = new JSONObject(); JSONObject jsonObject = new JSONObject();
jsonObject.put("expires",expires); jsonObject.put("expires", expires);
jsonObject.put("fingerprints",new JSONArray(results)); jsonObject.put("fingerprints", new JSONArray(results));
FileOutputStream outputStream = new FileOutputStream(file); FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(jsonObject.toString().getBytes()); outputStream.write(jsonObject.toString().getBytes());
outputStream.flush(); outputStream.flush();
@ -538,7 +599,7 @@ public class MemorizingTrustManager {
String line = buf.readLine(); String line = buf.readLine();
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
while(line != null){ while (line != null) {
sb.append(line).append("\n"); sb.append(line).append("\n");
line = buf.readLine(); line = buf.readLine();
} }
@ -550,11 +611,11 @@ public class MemorizingTrustManager {
file.delete(); file.delete();
return null; return null;
} else { } else {
Log.d("mtm","posh fingerprints expire in "+(expiresIn/1000)+"s"); Log.d("mtm", "posh fingerprints expire in " + (expiresIn / 1000) + "s");
} }
List<String> result = new ArrayList<>(); List<String> result = new ArrayList<>();
JSONArray jsonArray = jsonObject.getJSONArray("fingerprints"); JSONArray jsonArray = jsonObject.getJSONArray("fingerprints");
for(int i = 0; i < jsonArray.length(); ++i) { for (int i = 0; i < jsonArray.length(); ++i) {
result.add(jsonArray.getString(i)); result.add(jsonArray.getString(i));
} }
return result; return result;
@ -568,26 +629,6 @@ public class MemorizingTrustManager {
} }
} }
private static boolean isIp(final String server) {
return server != null && (
PATTERN_IPV4.matcher(server).matches()
|| PATTERN_IPV6.matcher(server).matches()
|| PATTERN_IPV6_6HEX4DEC.matcher(server).matches()
|| PATTERN_IPV6_HEX4DECCOMPRESSED.matcher(server).matches()
|| PATTERN_IPV6_HEXCOMPRESSED.matcher(server).matches());
}
private static String getBase64Hash(X509Certificate certificate, String digest) throws CertificateEncodingException {
MessageDigest md;
try {
md = MessageDigest.getInstance(digest);
} catch (NoSuchAlgorithmException e) {
return null;
}
md.update(certificate.getEncoded());
return Base64.encodeToString(md.digest(),Base64.NO_WRAP);
}
private X509Certificate[] getAcceptedIssuers() { private X509Certificate[] getAcceptedIssuers() {
LOGGER.log(Level.FINE, "getAcceptedIssuers()"); LOGGER.log(Level.FINE, "getAcceptedIssuers()");
return defaultTrustManager.getAcceptedIssuers(); return defaultTrustManager.getAcceptedIssuers();
@ -595,7 +636,7 @@ public class MemorizingTrustManager {
private int createDecisionId(MTMDecision d) { private int createDecisionId(MTMDecision d) {
int myId; int myId;
synchronized(openDecisions) { synchronized (openDecisions) {
myId = decisionId; myId = decisionId;
openDecisions.put(myId, d); openDecisions.put(myId, d);
decisionId += 1; decisionId += 1;
@ -603,28 +644,6 @@ public class MemorizingTrustManager {
return myId; return myId;
} }
private static String hexString(byte[] data) {
StringBuffer si = new StringBuffer();
for (int i = 0; i < data.length; i++) {
si.append(String.format("%02x", data[i]));
if (i < data.length - 1)
si.append(":");
}
return si.toString();
}
private static String certHash(final X509Certificate cert, String digest) {
try {
MessageDigest md = MessageDigest.getInstance(digest);
md.update(cert.getEncoded());
return hexString(md.digest());
} catch (java.security.cert.CertificateEncodingException e) {
return e.getMessage();
} catch (java.security.NoSuchAlgorithmException e) {
return e.getMessage();
}
}
private void certDetails(StringBuffer si, X509Certificate c) { private void certDetails(StringBuffer si, X509Certificate c) {
SimpleDateFormat validityDateFormater = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat validityDateFormater = new SimpleDateFormat("yyyy-MM-dd");
si.append("\n"); si.append("\n");
@ -680,7 +699,7 @@ public class MemorizingTrustManager {
Object name = altName.get(1); Object name = altName.get(1);
if (name instanceof String) { if (name instanceof String) {
si.append("["); si.append("[");
si.append((Integer)altName.get(0)); si.append((Integer) altName.get(0));
si.append("] "); si.append("] ");
si.append(name); si.append(name);
si.append("\n"); si.append("\n");
@ -699,6 +718,7 @@ public class MemorizingTrustManager {
certDetails(si, cert); certDetails(si, cert);
return si.toString(); return si.toString();
} }
/** /**
* Returns the top-most entry of the activity stack. * Returns the top-most entry of the activity stack.
* *
@ -734,7 +754,9 @@ public class MemorizingTrustManager {
LOGGER.log(Level.FINE, "openDecisions: " + openDecisions + ", waiting on " + myId); LOGGER.log(Level.FINE, "openDecisions: " + openDecisions + ", waiting on " + myId);
try { try {
synchronized(choice) { choice.wait(); } synchronized (choice) {
choice.wait();
}
} catch (InterruptedException e) { } catch (InterruptedException e) {
LOGGER.log(Level.FINER, "InterruptedException", e); LOGGER.log(Level.FINER, "InterruptedException", e);
} }
@ -743,8 +765,7 @@ public class MemorizingTrustManager {
} }
void interactCert(final X509Certificate[] chain, String authType, CertificateException cause) void interactCert(final X509Certificate[] chain, String authType, CertificateException cause)
throws CertificateException throws CertificateException {
{
switch (interact(certChainMessage(chain, cause), R.string.mtm_accept_cert)) { switch (interact(certChainMessage(chain, cause), R.string.mtm_accept_cert)) {
case MTMDecision.DECISION_ALWAYS: case MTMDecision.DECISION_ALWAYS:
storeCert(chain[0]); // only store the server cert, not the whole chain storeCert(chain[0]); // only store the server cert, not the whole chain
@ -755,8 +776,7 @@ public class MemorizingTrustManager {
} }
} }
boolean interactHostname(X509Certificate cert, String hostname) boolean interactHostname(X509Certificate cert, String hostname) {
{
switch (interact(hostNameMessage(cert, hostname), R.string.mtm_accept_servername)) { switch (interact(hostNameMessage(cert, hostname), R.string.mtm_accept_servername)) {
case MTMDecision.DECISION_ALWAYS: case MTMDecision.DECISION_ALWAYS:
storeCert(hostname, cert); storeCert(hostname, cert);
@ -767,20 +787,20 @@ public class MemorizingTrustManager {
} }
} }
public static void interactResult(int decisionId, int choice) { public X509TrustManager getNonInteractive(String domain) {
MTMDecision d; return new NonInteractiveMemorizingTrustManager(domain);
synchronized(openDecisions) {
d = openDecisions.get(decisionId);
openDecisions.remove(decisionId);
} }
if (d == null) {
LOGGER.log(Level.SEVERE, "interactResult: aborting due to stale decision reference!"); public X509TrustManager getInteractive(String domain) {
return; return new InteractiveMemorizingTrustManager(domain);
} }
synchronized(d) {
d.state = choice; public X509TrustManager getNonInteractive() {
d.notify(); return new NonInteractiveMemorizingTrustManager(null);
} }
public X509TrustManager getInteractive() {
return new InteractiveMemorizingTrustManager(null);
} }
class MemorizingHostnameVerifier implements DomainHostnameVerifier { class MemorizingHostnameVerifier implements DomainHostnameVerifier {
@ -797,7 +817,7 @@ public class MemorizingTrustManager {
LOGGER.log(Level.FINE, "hostname verifier for " + domain + ", trying default verifier first"); LOGGER.log(Level.FINE, "hostname verifier for " + domain + ", trying default verifier first");
// if the default verifier accepts the hostname, we are done // if the default verifier accepts the hostname, we are done
if (defaultVerifier instanceof DomainHostnameVerifier) { if (defaultVerifier instanceof DomainHostnameVerifier) {
if (((DomainHostnameVerifier) defaultVerifier).verify(domain,hostname, session)) { if (((DomainHostnameVerifier) defaultVerifier).verify(domain, hostname, session)) {
return true; return true;
} }
} else { } else {
@ -809,7 +829,7 @@ public class MemorizingTrustManager {
// otherwise, we check if the hostname is an alias for this cert in our keystore // otherwise, we check if the hostname is an alias for this cert in our keystore
try { try {
X509Certificate cert = (X509Certificate)session.getPeerCertificates()[0]; X509Certificate cert = (X509Certificate) session.getPeerCertificates()[0];
//Log.d(TAG, "cert: " + cert); //Log.d(TAG, "cert: " + cert);
if (cert.equals(appKeyStore.getCertificate(domain.toLowerCase(Locale.US)))) { if (cert.equals(appKeyStore.getCertificate(domain.toLowerCase(Locale.US)))) {
LOGGER.log(Level.FINE, "certificate for " + domain + " is in our keystore. accepting."); LOGGER.log(Level.FINE, "certificate for " + domain + " is in our keystore. accepting.");
@ -830,27 +850,10 @@ public class MemorizingTrustManager {
@Override @Override
public boolean verify(String domain, SSLSession sslSession) { public boolean verify(String domain, SSLSession sslSession) {
return verify(domain,null,sslSession); return verify(domain, null, sslSession);
} }
} }
public X509TrustManager getNonInteractive(String domain) {
return new NonInteractiveMemorizingTrustManager(domain);
}
public X509TrustManager getInteractive(String domain) {
return new InteractiveMemorizingTrustManager(domain);
}
public X509TrustManager getNonInteractive() {
return new NonInteractiveMemorizingTrustManager(null);
}
public X509TrustManager getInteractive() {
return new InteractiveMemorizingTrustManager(null);
}
private class NonInteractiveMemorizingTrustManager implements X509TrustManager { private class NonInteractiveMemorizingTrustManager implements X509TrustManager {
private final String domain; private final String domain;