refactor magic creates password gen to CryptoHelper

This commit is contained in:
Daniel Gultsch 2018-10-20 00:05:10 +02:00
parent 157ebbac52
commit f9cafc144b
2 changed files with 243 additions and 247 deletions

View file

@ -16,16 +16,13 @@ import java.security.SecureRandom;
import eu.siacs.conversations.Config; import eu.siacs.conversations.Config;
import eu.siacs.conversations.R; import eu.siacs.conversations.R;
import eu.siacs.conversations.entities.Account; import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.utils.CryptoHelper;
import rocks.xmpp.addr.Jid; import rocks.xmpp.addr.Jid;
public class MagicCreateActivity extends XmppActivity implements TextWatcher { public class MagicCreateActivity extends XmppActivity implements TextWatcher {
private TextView mFullJidDisplay; private TextView mFullJidDisplay;
private EditText mUsername; private EditText mUsername;
private SecureRandom mRandom;
private static final String CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456780+-/#$!?";
private static final int PW_LENGTH = 10;
@Override @Override
protected void refreshUiReal() { protected void refreshUiReal() {
@ -57,7 +54,6 @@ public class MagicCreateActivity extends XmppActivity implements TextWatcher {
configureActionBar(getSupportActionBar()); configureActionBar(getSupportActionBar());
mFullJidDisplay = findViewById(R.id.full_jid); mFullJidDisplay = findViewById(R.id.full_jid);
mUsername = findViewById(R.id.username); mUsername = findViewById(R.id.username);
mRandom = new SecureRandom();
Button next = findViewById(R.id.create_account); Button next = findViewById(R.id.create_account);
next.setOnClickListener(v -> { next.setOnClickListener(v -> {
try { try {
@ -70,7 +66,7 @@ public class MagicCreateActivity extends XmppActivity implements TextWatcher {
mUsername.setError(null); mUsername.setError(null);
Account account = xmppConnectionService.findAccountByJid(jid); Account account = xmppConnectionService.findAccountByJid(jid);
if (account == null) { if (account == null) {
account = new Account(jid, createPassword()); account = new Account(jid, CryptoHelper.createPassword(new SecureRandom()));
account.setOption(Account.OPTION_REGISTER, true); account.setOption(Account.OPTION_REGISTER, true);
account.setOption(Account.OPTION_DISABLED, true); account.setOption(Account.OPTION_DISABLED, true);
account.setOption(Account.OPTION_MAGIC_CREATE, true); account.setOption(Account.OPTION_MAGIC_CREATE, true);
@ -92,14 +88,6 @@ public class MagicCreateActivity extends XmppActivity implements TextWatcher {
mUsername.addTextChangedListener(this); mUsername.addTextChangedListener(this);
} }
private String createPassword() {
StringBuilder builder = new StringBuilder(PW_LENGTH);
for (int i = 0; i < PW_LENGTH; ++i) {
builder.append(CHARS.charAt(mRandom.nextInt(CHARS.length() - 1)));
}
return builder.toString();
}
@Override @Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { public void beforeTextChanged(CharSequence s, int start, int count, int after) {

View file

@ -36,261 +36,269 @@ import rocks.xmpp.addr.Jid;
public final class CryptoHelper { public final class CryptoHelper {
private static final char[] VOWELS = "aeiou".toCharArray(); public static final Pattern UUID_PATTERN = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}");
private static final char[] CONSONANTS = "bcfghjklmnpqrstvwxyz".toCharArray(); final public static byte[] ONE = new byte[]{0, 0, 0, 1};
private static final char[] CHARS = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz123456789+-/#$!?".toCharArray();
private static final int PW_LENGTH = 10;
private static final char[] VOWELS = "aeiou".toCharArray();
private static final char[] CONSONANTS = "bcfghjklmnpqrstvwxyz".toCharArray();
private final static char[] hexArray = "0123456789abcdef".toCharArray();
private final static char[] hexArray = "0123456789abcdef".toCharArray(); public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public static final Pattern UUID_PATTERN = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"); public static String createPassword(SecureRandom random) {
final public static byte[] ONE = new byte[] { 0, 0, 0, 1 }; StringBuilder builder = new StringBuilder(PW_LENGTH);
for (int i = 0; i < PW_LENGTH; ++i) {
builder.append(CHARS[random.nextInt(CHARS.length - 1)]);
}
return builder.toString();
}
public static String bytesToHex(byte[] bytes) { public static String pronounceable(SecureRandom random) {
char[] hexChars = new char[bytes.length * 2]; char[] output = new char[random.nextInt(4) * 2 + 5];
for (int j = 0; j < bytes.length; j++) { boolean vowel = random.nextBoolean();
int v = bytes[j] & 0xFF; for (int i = 0; i < output.length; ++i) {
hexChars[j * 2] = hexArray[v >>> 4]; output[i] = vowel ? VOWELS[random.nextInt(VOWELS.length)] : CONSONANTS[random.nextInt(CONSONANTS.length)];
hexChars[j * 2 + 1] = hexArray[v & 0x0F]; vowel = !vowel;
} }
return new String(hexChars); return String.valueOf(output);
} }
public static String pronounceable(SecureRandom random) { public static byte[] hexToBytes(String hexString) {
char[] output = new char[random.nextInt(4) * 2 + 5]; int len = hexString.length();
boolean vowel = random.nextBoolean(); byte[] array = new byte[len / 2];
for(int i = 0; i < output.length; ++i) { for (int i = 0; i < len; i += 2) {
output[i] = vowel ? VOWELS[random.nextInt(VOWELS.length)] : CONSONANTS[random.nextInt(CONSONANTS.length)]; array[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
vowel = !vowel; .digit(hexString.charAt(i + 1), 16));
} }
return String.valueOf(output); return array;
} }
public static byte[] hexToBytes(String hexString) { public static String hexToString(final String hexString) {
int len = hexString.length(); return new String(hexToBytes(hexString));
byte[] array = new byte[len / 2]; }
for (int i = 0; i < len; i += 2) {
array[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character
.digit(hexString.charAt(i + 1), 16));
}
return array;
}
public static String hexToString(final String hexString) { public static byte[] concatenateByteArrays(byte[] a, byte[] b) {
return new String(hexToBytes(hexString)); byte[] result = new byte[a.length + b.length];
} System.arraycopy(a, 0, result, 0, a.length);
System.arraycopy(b, 0, result, a.length, b.length);
return result;
}
public static byte[] concatenateByteArrays(byte[] a, byte[] b) { /**
byte[] result = new byte[a.length + b.length]; * Escapes usernames or passwords for SASL.
System.arraycopy(a, 0, result, 0, a.length); */
System.arraycopy(b, 0, result, a.length, b.length); public static String saslEscape(final String s) {
return result; final StringBuilder sb = new StringBuilder((int) (s.length() * 1.1));
} for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case ',':
sb.append("=2C");
break;
case '=':
sb.append("=3D");
break;
default:
sb.append(c);
break;
}
}
return sb.toString();
}
/** public static String saslPrep(final String s) {
* Escapes usernames or passwords for SASL. return Normalizer.normalize(s, Normalizer.Form.NFKC);
*/ }
public static String saslEscape(final String s) {
final StringBuilder sb = new StringBuilder((int) (s.length() * 1.1));
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case ',':
sb.append("=2C");
break;
case '=':
sb.append("=3D");
break;
default:
sb.append(c);
break;
}
}
return sb.toString();
}
public static String saslPrep(final String s) { public static String random(int length, SecureRandom random) {
return Normalizer.normalize(s, Normalizer.Form.NFKC); final byte[] bytes = new byte[length];
} random.nextBytes(bytes);
return Base64.encodeToString(bytes, Base64.NO_PADDING | Base64.NO_WRAP | Base64.URL_SAFE);
}
public static String random(int length, SecureRandom random) { public static String prettifyFingerprint(String fingerprint) {
final byte[] bytes = new byte[length]; if (fingerprint == null) {
random.nextBytes(bytes); return "";
return Base64.encodeToString(bytes,Base64.NO_PADDING|Base64.NO_WRAP|Base64.URL_SAFE); } else if (fingerprint.length() < 40) {
} return fingerprint;
}
StringBuilder builder = new StringBuilder(fingerprint);
for (int i = 8; i < builder.length(); i += 9) {
builder.insert(i, ' ');
}
return builder.toString();
}
public static String prettifyFingerprint(String fingerprint) { public static String prettifyFingerprintCert(String fingerprint) {
if (fingerprint==null) { StringBuilder builder = new StringBuilder(fingerprint);
return ""; for (int i = 2; i < builder.length(); i += 3) {
} else if (fingerprint.length() < 40) { builder.insert(i, ':');
return fingerprint; }
} return builder.toString();
StringBuilder builder = new StringBuilder(fingerprint); }
for(int i=8;i<builder.length();i+=9) {
builder.insert(i, ' ');
}
return builder.toString();
}
public static String prettifyFingerprintCert(String fingerprint) { public static String[] getOrderedCipherSuites(final String[] platformSupportedCipherSuites) {
StringBuilder builder = new StringBuilder(fingerprint); final Collection<String> cipherSuites = new LinkedHashSet<>(Arrays.asList(Config.ENABLED_CIPHERS));
for(int i=2;i < builder.length(); i+=3) { final List<String> platformCiphers = Arrays.asList(platformSupportedCipherSuites);
builder.insert(i,':'); cipherSuites.retainAll(platformCiphers);
} cipherSuites.addAll(platformCiphers);
return builder.toString(); filterWeakCipherSuites(cipherSuites);
} cipherSuites.remove("TLS_FALLBACK_SCSV");
return cipherSuites.toArray(new String[cipherSuites.size()]);
}
public static String[] getOrderedCipherSuites(final String[] platformSupportedCipherSuites) { private static void filterWeakCipherSuites(final Collection<String> cipherSuites) {
final Collection<String> cipherSuites = new LinkedHashSet<>(Arrays.asList(Config.ENABLED_CIPHERS)); final Iterator<String> it = cipherSuites.iterator();
final List<String> platformCiphers = Arrays.asList(platformSupportedCipherSuites); while (it.hasNext()) {
cipherSuites.retainAll(platformCiphers); String cipherName = it.next();
cipherSuites.addAll(platformCiphers); // remove all ciphers with no or very weak encryption or no authentication
filterWeakCipherSuites(cipherSuites); for (String weakCipherPattern : Config.WEAK_CIPHER_PATTERNS) {
cipherSuites.remove("TLS_FALLBACK_SCSV"); if (cipherName.contains(weakCipherPattern)) {
return cipherSuites.toArray(new String[cipherSuites.size()]); it.remove();
} break;
}
}
}
}
private static void filterWeakCipherSuites(final Collection<String> cipherSuites) { public static Pair<Jid, String> extractJidAndName(X509Certificate certificate) throws CertificateEncodingException, IllegalArgumentException, CertificateParsingException {
final Iterator<String> it = cipherSuites.iterator(); Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames();
while (it.hasNext()) { List<String> emails = new ArrayList<>();
String cipherName = it.next(); if (alternativeNames != null) {
// remove all ciphers with no or very weak encryption or no authentication for (List<?> san : alternativeNames) {
for (String weakCipherPattern : Config.WEAK_CIPHER_PATTERNS) { Integer type = (Integer) san.get(0);
if (cipherName.contains(weakCipherPattern)) { if (type == 1) {
it.remove(); emails.add((String) san.get(1));
break; }
} }
} }
} X500Name x500name = new JcaX509CertificateHolder(certificate).getSubject();
} if (emails.size() == 0 && x500name.getRDNs(BCStyle.EmailAddress).length > 0) {
emails.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.EmailAddress)[0].getFirst().getValue()));
}
String name = x500name.getRDNs(BCStyle.CN).length > 0 ? IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[0].getFirst().getValue()) : null;
if (emails.size() >= 1) {
return new Pair<>(Jid.of(emails.get(0)), name);
} else if (name != null) {
try {
Jid jid = Jid.of(name);
if (jid.isBareJid() && jid.getLocal() != null) {
return new Pair<>(jid, null);
}
} catch (IllegalArgumentException e) {
return null;
}
}
return null;
}
public static Pair<Jid,String> extractJidAndName(X509Certificate certificate) throws CertificateEncodingException, IllegalArgumentException, CertificateParsingException { public static Bundle extractCertificateInformation(X509Certificate certificate) {
Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames(); Bundle information = new Bundle();
List<String> emails = new ArrayList<>(); try {
if (alternativeNames != null) { JcaX509CertificateHolder holder = new JcaX509CertificateHolder(certificate);
for(List<?> san : alternativeNames) { X500Name subject = holder.getSubject();
Integer type = (Integer) san.get(0); try {
if (type == 1) { information.putString("subject_cn", subject.getRDNs(BCStyle.CN)[0].getFirst().getValue().toString());
emails.add((String) san.get(1)); } catch (Exception e) {
} //ignored
} }
} try {
X500Name x500name = new JcaX509CertificateHolder(certificate).getSubject(); information.putString("subject_o", subject.getRDNs(BCStyle.O)[0].getFirst().getValue().toString());
if (emails.size() == 0 && x500name.getRDNs(BCStyle.EmailAddress).length > 0) { } catch (Exception e) {
emails.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.EmailAddress)[0].getFirst().getValue())); //ignored
} }
String name = x500name.getRDNs(BCStyle.CN).length > 0 ? IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[0].getFirst().getValue()) : null;
if (emails.size() >= 1) {
return new Pair<>(Jid.of(emails.get(0)), name);
} else if (name != null){
try {
Jid jid = Jid.of(name);
if (jid.isBareJid() && jid.getLocal() != null) {
return new Pair<>(jid,null);
}
} catch (IllegalArgumentException e) {
return null;
}
}
return null;
}
public static Bundle extractCertificateInformation(X509Certificate certificate) { X500Name issuer = holder.getIssuer();
Bundle information = new Bundle(); try {
try { information.putString("issuer_cn", issuer.getRDNs(BCStyle.CN)[0].getFirst().getValue().toString());
JcaX509CertificateHolder holder = new JcaX509CertificateHolder(certificate); } catch (Exception e) {
X500Name subject = holder.getSubject(); //ignored
try { }
information.putString("subject_cn", subject.getRDNs(BCStyle.CN)[0].getFirst().getValue().toString()); try {
} catch (Exception e) { information.putString("issuer_o", issuer.getRDNs(BCStyle.O)[0].getFirst().getValue().toString());
//ignored } catch (Exception e) {
} //ignored
try { }
information.putString("subject_o",subject.getRDNs(BCStyle.O)[0].getFirst().getValue().toString()); try {
} catch (Exception e) { information.putString("sha1", getFingerprintCert(certificate.getEncoded()));
//ignored } catch (Exception e) {
}
X500Name issuer = holder.getIssuer(); }
try { return information;
information.putString("issuer_cn", issuer.getRDNs(BCStyle.CN)[0].getFirst().getValue().toString()); } catch (CertificateEncodingException e) {
} catch (Exception e) { return information;
//ignored }
} }
try {
information.putString("issuer_o", issuer.getRDNs(BCStyle.O)[0].getFirst().getValue().toString());
} catch (Exception e) {
//ignored
}
try {
information.putString("sha1", getFingerprintCert(certificate.getEncoded()));
} catch (Exception e) {
} public static String getFingerprintCert(byte[] input) throws NoSuchAlgorithmException {
return information; MessageDigest md = MessageDigest.getInstance("SHA-1");
} catch (CertificateEncodingException e) { byte[] fingerprint = md.digest(input);
return information; return prettifyFingerprintCert(bytesToHex(fingerprint));
} }
}
public static String getFingerprintCert(byte[] input) throws NoSuchAlgorithmException { public static String getAccountFingerprint(Account account, String androidId) {
MessageDigest md = MessageDigest.getInstance("SHA-1"); return getFingerprint(account.getJid().asBareJid().toEscapedString() + "\00" + androidId);
byte[] fingerprint = md.digest(input); }
return prettifyFingerprintCert(bytesToHex(fingerprint));
}
public static String getAccountFingerprint(Account account, String androidId) { public static String getFingerprint(String value) {
return getFingerprint(account.getJid().asBareJid().toEscapedString()+"\00"+androidId); try {
} MessageDigest md = MessageDigest.getInstance("SHA-1");
return bytesToHex(md.digest(value.getBytes("UTF-8")));
} catch (Exception e) {
return "";
}
}
public static String getFingerprint(String value) { public static int encryptionTypeToText(int encryption) {
try { switch (encryption) {
MessageDigest md = MessageDigest.getInstance("SHA-1"); case Message.ENCRYPTION_OTR:
return bytesToHex(md.digest(value.getBytes("UTF-8"))); return R.string.encryption_choice_otr;
} catch (Exception e) { case Message.ENCRYPTION_AXOLOTL:
return ""; case Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE:
} return R.string.encryption_choice_omemo;
} case Message.ENCRYPTION_NONE:
return R.string.encryption_choice_unencrypted;
default:
return R.string.encryption_choice_pgp;
}
}
public static int encryptionTypeToText(int encryption) { public static URL toAesGcmUrl(URL url) {
switch (encryption) { if (!url.getProtocol().equalsIgnoreCase("https")) {
case Message.ENCRYPTION_OTR: return url;
return R.string.encryption_choice_otr; }
case Message.ENCRYPTION_AXOLOTL: try {
case Message.ENCRYPTION_AXOLOTL_NOT_FOR_THIS_DEVICE: return new URL(AesGcmURLStreamHandler.PROTOCOL_NAME + url.toString().substring(url.getProtocol().length()));
return R.string.encryption_choice_omemo; } catch (MalformedURLException e) {
case Message.ENCRYPTION_NONE: return url;
return R.string.encryption_choice_unencrypted; }
default: }
return R.string.encryption_choice_pgp;
}
}
public static URL toAesGcmUrl(URL url) { public static URL toHttpsUrl(URL url) {
if (!url.getProtocol().equalsIgnoreCase("https")) { if (!url.getProtocol().equalsIgnoreCase(AesGcmURLStreamHandler.PROTOCOL_NAME)) {
return url; return url;
} }
try { try {
return new URL(AesGcmURLStreamHandler.PROTOCOL_NAME+url.toString().substring(url.getProtocol().length())); return new URL("https" + url.toString().substring(url.getProtocol().length()));
} catch (MalformedURLException e) { } catch (MalformedURLException e) {
return url; return url;
} }
} }
public static URL toHttpsUrl(URL url) { public static boolean isPgpEncryptedUrl(String url) {
if (!url.getProtocol().equalsIgnoreCase(AesGcmURLStreamHandler.PROTOCOL_NAME)) { if (url == null) {
return url; return false;
} }
try { final String u = url.toLowerCase();
return new URL("https"+url.toString().substring(url.getProtocol().length())); return !u.contains(" ") && (u.startsWith("https://") || u.startsWith("http://") || u.startsWith("p1s3://")) && u.endsWith(".pgp");
} catch (MalformedURLException e) { }
return url;
}
}
public static boolean isPgpEncryptedUrl(String url) {
if (url == null) {
return false;
}
final String u = url.toLowerCase();
return !u.contains(" ") && (u.startsWith("https://") || u.startsWith("http://") || u.startsWith("p1s3://")) && u.endsWith(".pgp");
}
} }