Add sshauthentication-api v1 support
This commit is contained in:
parent
83ab483fc7
commit
2619cb1db3
57 changed files with 3954 additions and 79 deletions
|
@ -55,6 +55,7 @@ dependencies {
|
|||
// libs as submodules
|
||||
compile project(':libkeychain')
|
||||
compile project(':openpgp-api-lib')
|
||||
compile project(':sshauthentication-api')
|
||||
compile project(':extern:bouncycastle:core')
|
||||
compile project(':extern:bouncycastle:pg')
|
||||
compile project(':extern:bouncycastle:prov')
|
||||
|
|
|
@ -767,7 +767,6 @@
|
|||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
|
||||
<activity
|
||||
android:name=".ui.LogDisplayActivity"
|
||||
android:configChanges="orientation|screenSize|keyboardHidden|keyboard"
|
||||
|
@ -883,6 +882,11 @@
|
|||
android:name=".remote.ui.SelectSignKeyIdActivity"
|
||||
android:exported="false"
|
||||
android:label="@string/app_name" />
|
||||
<activity
|
||||
android:name=".remote.ui.dialog.RemoteSelectAuthenticationKeyActivity"
|
||||
android:exported="false"
|
||||
android:theme="@style/Theme.Keychain.Transparent"
|
||||
android:label="@string/app_name" />
|
||||
<activity
|
||||
android:name=".remote.ui.RequestKeyPermissionActivity"
|
||||
android:exported="false"
|
||||
|
@ -961,6 +965,19 @@
|
|||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<!-- SSHAuthentication Remote API, this service has explicitly no permission requirements
|
||||
because we are using our own package based allow/disallow system -->
|
||||
<service
|
||||
android:name=".remote.SshAuthenticationService"
|
||||
android:enabled="true"
|
||||
android:exported="true"
|
||||
android:process=":remote_ssh_api"
|
||||
tools:ignore="ExportedService">
|
||||
<intent-filter>
|
||||
<action android:name="org.openintents.ssh.authentication.ISshAuthenticationService" />
|
||||
</intent-filter>
|
||||
</service>
|
||||
|
||||
<!-- Contact Sync services -->
|
||||
<service
|
||||
android:name=".service.DummyAccountService"
|
||||
|
|
|
@ -720,6 +720,19 @@ public abstract class OperationResult implements Parcelable {
|
|||
MSG_PSE_SIGCRYPTING (LogLevel.DEBUG, R.string.msg_pse_sigcrypting),
|
||||
MSG_PSE_SYMMETRIC (LogLevel.INFO, R.string.msg_pse_symmetric),
|
||||
|
||||
MSG_AUTH (LogLevel.DEBUG, R.string.msg_auth),
|
||||
MSG_AUTH_ERROR_KEY_AUTH (LogLevel.ERROR, R.string.msg_auth_error_key_auth),
|
||||
MSG_AUTH_ERROR_KEY_NOT_ALLOWED(LogLevel.ERROR, R.string.msg_auth_error_key_not_allowed),
|
||||
MSG_AUTH_ERROR_REVOKED_OR_EXPIRED (LogLevel.ERROR, R.string.msg_auth_error_revoked_or_expired),
|
||||
MSG_AUTH_ERROR_UNLOCK (LogLevel.ERROR, R.string.msg_auth_error_unlock),
|
||||
MSG_AUTH_PENDING_NFC (LogLevel.INFO, R.string.msg_auth_pending_nfc),
|
||||
MSG_AUTH_PENDING_PASSPHRASE (LogLevel.INFO, R.string.msg_auth_pending_passphrase),
|
||||
MSG_AUTH_ERROR_BAD_PASSPHRASE (LogLevel.ERROR, R.string.msg_auth_error_bad_passphrase),
|
||||
MSG_AUTH_ERROR_NFC (LogLevel.ERROR, R.string.msg_auth_error_nfc),
|
||||
MSG_AUTH_ERROR_SIG (LogLevel.ERROR, R.string.msg_auth_error_sig),
|
||||
MSG_AUTH_OK (LogLevel.OK, R.string.msg_auth_ok),
|
||||
|
||||
|
||||
MSG_CRT_CERTIFYING (LogLevel.DEBUG, R.string.msg_crt_certifying),
|
||||
MSG_CRT_CERTIFY_UIDS (LogLevel.DEBUG, R.plurals.msg_crt_certify_uids),
|
||||
MSG_CRT_CERTIFY_UATS (LogLevel.DEBUG, R.plurals.msg_crt_certify_uats),
|
||||
|
|
|
@ -19,14 +19,6 @@
|
|||
package org.sufficientlysecure.keychain.pgp;
|
||||
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.PublicKey;
|
||||
import java.security.interfaces.ECPublicKey;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.Iterator;
|
||||
|
||||
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
|
||||
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
|
||||
import org.bouncycastle.bcpg.ECDHPublicBCPGKey;
|
||||
|
@ -45,6 +37,14 @@ import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
|
|||
import org.sufficientlysecure.keychain.util.IterableIterator;
|
||||
import org.sufficientlysecure.keychain.util.Log;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.security.PublicKey;
|
||||
import java.security.interfaces.ECPublicKey;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.GregorianCalendar;
|
||||
import java.util.Iterator;
|
||||
|
||||
/** Wrapper for a PGPPublicKey.
|
||||
*
|
||||
* The methods implemented in this class are a thin layer over
|
||||
|
@ -211,18 +211,22 @@ public class CanonicalizedPublicKey extends UncachedPublicKey {
|
|||
return !isRevoked() && !isExpired();
|
||||
}
|
||||
|
||||
// For use only in card export; returns the public key.
|
||||
// For use in key export only; returns the public key in a JCA compatible format.
|
||||
public PublicKey getJcaPublicKey() throws PgpGeneralException {
|
||||
JcaPGPKeyConverter keyConverter = new JcaPGPKeyConverter();
|
||||
PublicKey publicKey;
|
||||
try {
|
||||
publicKey = keyConverter.getPublicKey(mPublicKey);
|
||||
} catch (PGPException e) {
|
||||
throw new PgpGeneralException("Error converting public key: "+ e.getMessage(), e);
|
||||
}
|
||||
return publicKey;
|
||||
}
|
||||
|
||||
// For use in card export only; returns the public key in a JCA compatible format.
|
||||
public ECPublicKey getSecurityTokenECPublicKey()
|
||||
throws PgpGeneralException {
|
||||
JcaPGPKeyConverter keyConverter = new JcaPGPKeyConverter();
|
||||
PublicKey retVal;
|
||||
try {
|
||||
retVal = keyConverter.getPublicKey(mPublicKey);
|
||||
} catch (PGPException e) {
|
||||
throw new PgpGeneralException("Error converting public key!", e);
|
||||
}
|
||||
|
||||
return (ECPublicKey) retVal;
|
||||
return (ECPublicKey) getJcaPublicKey();
|
||||
}
|
||||
|
||||
public ASN1ObjectIdentifier getSecurityTokenHashAlgorithm()
|
||||
|
|
|
@ -28,6 +28,7 @@ import java.util.Map;
|
|||
|
||||
import org.bouncycastle.bcpg.S2K;
|
||||
import org.bouncycastle.bcpg.SymmetricKeyAlgorithmTags;
|
||||
import org.bouncycastle.openpgp.PGPAuthenticationSignatureGenerator;
|
||||
import org.bouncycastle.openpgp.PGPException;
|
||||
import org.bouncycastle.openpgp.PGPPrivateKey;
|
||||
import org.bouncycastle.openpgp.PGPSecretKey;
|
||||
|
@ -252,6 +253,26 @@ public class CanonicalizedSecretKey extends CanonicalizedPublicKey {
|
|||
}
|
||||
}
|
||||
|
||||
public PGPAuthenticationSignatureGenerator getAuthenticationSignatureGenerator(int hashAlgorithm,
|
||||
Map<ByteBuffer, byte[]> signedHashes)
|
||||
throws PgpGeneralException {
|
||||
if (mPrivateKeyState == PRIVATE_KEY_STATE_LOCKED) {
|
||||
throw new PrivateKeyNotUnlockedException();
|
||||
}
|
||||
|
||||
PGPContentSignerBuilder contentSignerBuilder = getContentSignerBuilder(hashAlgorithm, signedHashes);
|
||||
|
||||
try {
|
||||
PGPAuthenticationSignatureGenerator signatureGenerator = new PGPAuthenticationSignatureGenerator(contentSignerBuilder);
|
||||
signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, mPrivateKey);
|
||||
|
||||
return signatureGenerator;
|
||||
} catch (PGPException e) {
|
||||
// TODO: simply throw PGPException!
|
||||
throw new PgpGeneralException("Error initializing signature!", e);
|
||||
}
|
||||
}
|
||||
|
||||
public PGPSignatureGenerator getDataSignatureGenerator(int hashAlgo, boolean cleartext,
|
||||
Map<ByteBuffer, byte[]> signedHashes, Date creationTimestamp)
|
||||
throws PgpGeneralException {
|
||||
|
|
|
@ -0,0 +1,130 @@
|
|||
/*
|
||||
* Copyright (C) 2017 Christian Hagau <ach@hagau.se>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.sufficientlysecure.keychain.pgp;
|
||||
|
||||
import org.bouncycastle.bcpg.DSAPublicBCPGKey;
|
||||
import org.bouncycastle.bcpg.ECPublicBCPGKey;
|
||||
import org.bouncycastle.bcpg.EdDSAPublicBCPGKey;
|
||||
import org.bouncycastle.bcpg.RSAPublicBCPGKey;
|
||||
import org.bouncycastle.openpgp.PGPPublicKey;
|
||||
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
|
||||
import org.sufficientlysecure.keychain.ssh.key.SshDSAPublicKey;
|
||||
import org.sufficientlysecure.keychain.ssh.key.SshECDSAPublicKey;
|
||||
import org.sufficientlysecure.keychain.ssh.key.SshEd25519PublicKey;
|
||||
import org.sufficientlysecure.keychain.ssh.key.SshRSAPublicKey;
|
||||
|
||||
public class SshPublicKey {
|
||||
private final static String TAG = "SshPublicKey";
|
||||
|
||||
private CanonicalizedPublicKey mPublicKey;
|
||||
|
||||
public SshPublicKey(CanonicalizedPublicKey publicKey) {
|
||||
mPublicKey = publicKey;
|
||||
}
|
||||
|
||||
public String getEncodedKey() throws PgpGeneralException {
|
||||
PGPPublicKey key = mPublicKey.getPublicKey();
|
||||
|
||||
switch (key.getAlgorithm()) {
|
||||
case PGPPublicKey.RSA_GENERAL:
|
||||
return encodeRSAKey(key);
|
||||
case PGPPublicKey.ECDSA:
|
||||
return encodeECKey(key);
|
||||
case PGPPublicKey.EDDSA:
|
||||
return encodeEdDSAKey(key);
|
||||
case PGPPublicKey.DSA:
|
||||
return encodeDSAKey(key);
|
||||
default:
|
||||
break;
|
||||
}
|
||||
throw new PgpGeneralException("Unknown algorithm");
|
||||
}
|
||||
|
||||
private String encodeRSAKey(PGPPublicKey publicKey) {
|
||||
RSAPublicBCPGKey publicBCPGKey = (RSAPublicBCPGKey) publicKey.getPublicKeyPacket().getKey();
|
||||
|
||||
SshRSAPublicKey pubkey = new SshRSAPublicKey(publicBCPGKey.getPublicExponent(), publicBCPGKey.getModulus());
|
||||
|
||||
return pubkey.getPublicKeyBlob();
|
||||
}
|
||||
|
||||
private String encodeECKey(PGPPublicKey publicKey) {
|
||||
ECPublicBCPGKey publicBCPGKey = (ECPublicBCPGKey) publicKey.getPublicKeyPacket().getKey();
|
||||
|
||||
String curveName = getCurveName(publicBCPGKey);
|
||||
SshECDSAPublicKey sshECDSAPublicKey = new SshECDSAPublicKey(curveName, publicBCPGKey.getEncodedPoint());
|
||||
|
||||
return sshECDSAPublicKey.getPublicKeyBlob();
|
||||
}
|
||||
|
||||
private String getCurveName(ECPublicBCPGKey publicBCPGKey) {
|
||||
String curveOid = publicBCPGKey.getCurveOID().getId();
|
||||
// see RFC5656 section 10.{1,2}
|
||||
switch (curveOid) {
|
||||
// REQUIRED curves
|
||||
case "1.2.840.10045.3.1.7":
|
||||
return "nistp256";
|
||||
case "1.3.132.0.34":
|
||||
return "nistp384";
|
||||
case "1.3.132.0.35":
|
||||
return "nistp521";
|
||||
|
||||
// RECOMMENDED curves
|
||||
case "1.3.132.0.1":
|
||||
return "1.3.132.0.1";
|
||||
case "1.2.840.10045.3.1.1":
|
||||
return "1.2.840.10045.3.1.1";
|
||||
case "1.3.132.0.33":
|
||||
return "1.3.132.0.33";
|
||||
case "1.3.132.0.26":
|
||||
return "1.3.132.0.26";
|
||||
case "1.3.132.0.27":
|
||||
return "1.3.132.0.27";
|
||||
case "1.3.132.0.16":
|
||||
return "1.3.132.0.16";
|
||||
case "1.3.132.0.36":
|
||||
return "1.3.132.0.36";
|
||||
case "1.3.132.0.37":
|
||||
return "1.3.132.0.37";
|
||||
case "1.3.132.0.38":
|
||||
return "1.3.132.0.38";
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String encodeEdDSAKey(PGPPublicKey publicKey) {
|
||||
EdDSAPublicBCPGKey publicBCPGKey = (EdDSAPublicBCPGKey) publicKey.getPublicKeyPacket().getKey();
|
||||
|
||||
SshEd25519PublicKey pubkey = new SshEd25519PublicKey(publicBCPGKey.getEdDSAEncodedPoint());
|
||||
|
||||
return pubkey.getPublicKeyBlob();
|
||||
}
|
||||
|
||||
private String encodeDSAKey(PGPPublicKey publicKey) {
|
||||
DSAPublicBCPGKey publicBCPGKey = (DSAPublicBCPGKey) publicKey.getPublicKeyPacket().getKey();
|
||||
|
||||
SshDSAPublicKey sshDSAPublicKey = new SshDSAPublicKey(publicBCPGKey.getP(),
|
||||
publicBCPGKey.getQ(),
|
||||
publicBCPGKey.getG(),
|
||||
publicBCPGKey.getY());
|
||||
|
||||
return sshDSAPublicKey.getPublicKeyBlob();
|
||||
}
|
||||
}
|
|
@ -201,6 +201,27 @@ public class CachedPublicKeyRing extends KeyRing {
|
|||
}
|
||||
}
|
||||
|
||||
/** Returns the key id which should be used for authentication.
|
||||
*
|
||||
* This method returns keys which are actually available (ie. secret available, and not stripped,
|
||||
* revoked, or expired), hence only works on keyrings where a secret key is available!
|
||||
*
|
||||
*/
|
||||
public long getSecretAuthenticationId() throws PgpKeyNotFoundException {
|
||||
try {
|
||||
Object data = mKeyRepository.getGenericData(mUri,
|
||||
KeyRings.HAS_AUTHENTICATE,
|
||||
KeyRepository.FIELD_TYPE_INTEGER);
|
||||
return (Long) data;
|
||||
} catch(KeyWritableRepository.NotFoundException e) {
|
||||
throw new PgpKeyNotFoundException(e);
|
||||
}
|
||||
}
|
||||
|
||||
public boolean hasAuthentication() throws PgpKeyNotFoundException {
|
||||
return getSecretAuthenticationId() != 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getVerified() throws PgpKeyNotFoundException {
|
||||
try {
|
||||
|
|
|
@ -355,6 +355,8 @@ public class KeychainProvider extends ContentProvider {
|
|||
"kE." + Keys.KEY_ID + " AS " + KeyRings.HAS_ENCRYPT);
|
||||
projectionMap.put(KeyRings.HAS_SIGN,
|
||||
"kS." + Keys.KEY_ID + " AS " + KeyRings.HAS_SIGN);
|
||||
projectionMap.put(KeyRings.HAS_AUTHENTICATE,
|
||||
"kA." + Keys.KEY_ID + " AS " + KeyRings.HAS_AUTHENTICATE);
|
||||
projectionMap.put(KeyRings.HAS_CERTIFY,
|
||||
"kC." + Keys.KEY_ID + " AS " + KeyRings.HAS_CERTIFY);
|
||||
projectionMap.put(KeyRings.IS_EXPIRED,
|
||||
|
|
|
@ -17,7 +17,6 @@
|
|||
|
||||
package org.sufficientlysecure.keychain.remote;
|
||||
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
import android.app.PendingIntent;
|
||||
|
@ -28,7 +27,6 @@ import android.os.Build;
|
|||
import org.sufficientlysecure.keychain.pgp.DecryptVerifySecurityProblem;
|
||||
import org.sufficientlysecure.keychain.provider.KeychainContract;
|
||||
import org.sufficientlysecure.keychain.remote.ui.RemoteBackupActivity;
|
||||
import org.sufficientlysecure.keychain.remote.ui.dialog.RemoteDeduplicateActivity;
|
||||
import org.sufficientlysecure.keychain.remote.ui.RemoteErrorActivity;
|
||||
import org.sufficientlysecure.keychain.remote.ui.RemoteImportKeysActivity;
|
||||
import org.sufficientlysecure.keychain.remote.ui.RemotePassphraseDialogActivity;
|
||||
|
@ -38,6 +36,8 @@ import org.sufficientlysecure.keychain.remote.ui.RemoteSecurityTokenOperationAct
|
|||
import org.sufficientlysecure.keychain.remote.ui.RemoteSelectPubKeyActivity;
|
||||
import org.sufficientlysecure.keychain.remote.ui.RequestKeyPermissionActivity;
|
||||
import org.sufficientlysecure.keychain.remote.ui.SelectSignKeyIdActivity;
|
||||
import org.sufficientlysecure.keychain.remote.ui.dialog.RemoteDeduplicateActivity;
|
||||
import org.sufficientlysecure.keychain.remote.ui.dialog.RemoteSelectAuthenticationKeyActivity;
|
||||
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
|
||||
import org.sufficientlysecure.keychain.service.input.RequiredInputParcel;
|
||||
import org.sufficientlysecure.keychain.ui.keyview.ViewKeyActivity;
|
||||
|
@ -56,10 +56,12 @@ public class ApiPendingIntentFactory {
|
|||
switch (requiredInput.mType) {
|
||||
case SECURITY_TOKEN_MOVE_KEY_TO_CARD:
|
||||
case SECURITY_TOKEN_DECRYPT:
|
||||
case SECURITY_TOKEN_AUTH:
|
||||
case SECURITY_TOKEN_SIGN: {
|
||||
return createSecurityTokenOperationPendingIntent(data, requiredInput, cryptoInput);
|
||||
}
|
||||
|
||||
case PASSPHRASE_AUTH:
|
||||
case PASSPHRASE: {
|
||||
return createPassphrasePendingIntent(data, requiredInput, cryptoInput);
|
||||
}
|
||||
|
@ -139,6 +141,14 @@ public class ApiPendingIntentFactory {
|
|||
return createInternal(data, intent);
|
||||
}
|
||||
|
||||
PendingIntent createSelectAuthenticationKeyIdPendingIntent(Intent data, String packageName) {
|
||||
Intent intent = new Intent(mContext, RemoteSelectAuthenticationKeyActivity.class);
|
||||
intent.setData(KeychainContract.ApiApps.buildByPackageNameUri(packageName));
|
||||
intent.putExtra(RemoteSelectAuthenticationKeyActivity.EXTRA_PACKAGE_NAME, packageName);
|
||||
|
||||
return createInternal(data, intent);
|
||||
}
|
||||
|
||||
PendingIntent createBackupPendingIntent(Intent data, long[] masterKeyIds, boolean backupSecret) {
|
||||
Intent intent = new Intent(mContext, RemoteBackupActivity.class);
|
||||
intent.putExtra(RemoteBackupActivity.EXTRA_MASTER_KEY_IDS, masterKeyIds);
|
||||
|
|
|
@ -0,0 +1,400 @@
|
|||
/*
|
||||
* Copyright (C) 2017 Christian Hagau <ach@hagau.se>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.sufficientlysecure.keychain.remote;
|
||||
|
||||
import android.app.PendingIntent;
|
||||
import android.app.Service;
|
||||
import android.content.Intent;
|
||||
import android.os.IBinder;
|
||||
import android.util.Log;
|
||||
import org.bouncycastle.bcpg.HashAlgorithmTags;
|
||||
import org.openintents.ssh.authentication.ISshAuthenticationService;
|
||||
import org.openintents.ssh.authentication.SshAuthenticationApi;
|
||||
import org.openintents.ssh.authentication.SshAuthenticationApiError;
|
||||
import org.openintents.ssh.authentication.response.KeySelectionResponse;
|
||||
import org.openintents.ssh.authentication.response.PublicKeyResponse;
|
||||
import org.openintents.ssh.authentication.response.SigningResponse;
|
||||
import org.openintents.ssh.authentication.response.SshPublicKeyResponse;
|
||||
import org.sufficientlysecure.keychain.Constants;
|
||||
import org.sufficientlysecure.keychain.operations.results.OperationResult.LogEntryParcel;
|
||||
import org.sufficientlysecure.keychain.pgp.CanonicalizedPublicKey;
|
||||
import org.sufficientlysecure.keychain.pgp.SshPublicKey;
|
||||
import org.sufficientlysecure.keychain.pgp.exception.PgpGeneralException;
|
||||
import org.sufficientlysecure.keychain.pgp.exception.PgpKeyNotFoundException;
|
||||
import org.sufficientlysecure.keychain.provider.ApiDataAccessObject;
|
||||
import org.sufficientlysecure.keychain.provider.CachedPublicKeyRing;
|
||||
import org.sufficientlysecure.keychain.provider.KeyRepository;
|
||||
import org.sufficientlysecure.keychain.provider.KeychainContract;
|
||||
import org.sufficientlysecure.keychain.service.input.CryptoInputParcel;
|
||||
import org.sufficientlysecure.keychain.service.input.RequiredInputParcel;
|
||||
import org.sufficientlysecure.keychain.ssh.AuthenticationData;
|
||||
import org.sufficientlysecure.keychain.ssh.AuthenticationOperation;
|
||||
import org.sufficientlysecure.keychain.ssh.AuthenticationParcel;
|
||||
import org.sufficientlysecure.keychain.ssh.AuthenticationResult;
|
||||
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.PublicKey;
|
||||
import java.util.*;
|
||||
|
||||
|
||||
public class SshAuthenticationService extends Service {
|
||||
private static final String TAG = "SshAuthService";
|
||||
|
||||
private ApiPermissionHelper mApiPermissionHelper;
|
||||
private KeyRepository mKeyRepository;
|
||||
private ApiDataAccessObject mApiDao;
|
||||
private ApiPendingIntentFactory mApiPendingIntentFactory;
|
||||
|
||||
private static final List<Integer> SUPPORTED_VERSIONS = Collections.unmodifiableList(Collections.singletonList(1));
|
||||
private static final int INVALID_API_VERSION = -1;
|
||||
|
||||
private static final int HASHALGORITHM_NONE = SshAuthenticationApiError.INVALID_HASH_ALGORITHM;
|
||||
|
||||
@Override
|
||||
public void onCreate() {
|
||||
super.onCreate();
|
||||
mApiPermissionHelper = new ApiPermissionHelper(this, new ApiDataAccessObject(this));
|
||||
mKeyRepository = KeyRepository.create(this);
|
||||
mApiDao = new ApiDataAccessObject(this);
|
||||
|
||||
mApiPendingIntentFactory = new ApiPendingIntentFactory(getBaseContext());
|
||||
}
|
||||
|
||||
private final ISshAuthenticationService.Stub mSSHAgent = new ISshAuthenticationService.Stub() {
|
||||
@Override
|
||||
public Intent execute(Intent intent) {
|
||||
return checkIntent(intent);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
@Override
|
||||
public IBinder onBind(Intent intent) {
|
||||
return mSSHAgent;
|
||||
}
|
||||
|
||||
private Intent checkIntent(Intent intent) {
|
||||
Intent errorResult = checkRequirements(intent);
|
||||
if (errorResult == null) {
|
||||
return executeInternal(intent);
|
||||
} else {
|
||||
return errorResult;
|
||||
}
|
||||
}
|
||||
|
||||
private Intent executeInternal(Intent intent) {
|
||||
switch (intent.getAction()) {
|
||||
case SshAuthenticationApi.ACTION_SIGN:
|
||||
return authenticate(intent);
|
||||
case SshAuthenticationApi.ACTION_SELECT_KEY:
|
||||
return getAuthenticationKey(intent);
|
||||
case SshAuthenticationApi.ACTION_GET_PUBLIC_KEY:
|
||||
return getAuthenticationPublicKey(intent, false);
|
||||
case SshAuthenticationApi.ACTION_GET_SSH_PUBLIC_KEY:
|
||||
return getAuthenticationPublicKey(intent, true);
|
||||
default:
|
||||
return createErrorResult(SshAuthenticationApiError.UNKNOWN_ACTION, "Unknown action");
|
||||
}
|
||||
}
|
||||
|
||||
private Intent authenticate(Intent data) {
|
||||
Intent errorIntent = checkForKeyId(data);
|
||||
if (errorIntent != null) {
|
||||
return errorIntent;
|
||||
}
|
||||
|
||||
// keyid == masterkeyid -> authkeyid
|
||||
// keyId is the pgp master keyId, the keyId used will be the first authentication
|
||||
// key in the keyring designated by the master keyId
|
||||
String keyIdString = data.getStringExtra(SshAuthenticationApi.EXTRA_KEY_ID);
|
||||
long masterKeyId = Long.valueOf(keyIdString);
|
||||
|
||||
int hashAlgorithmTag = getHashAlgorithm(data);
|
||||
if (hashAlgorithmTag == HASHALGORITHM_NONE) {
|
||||
return createErrorResult(SshAuthenticationApiError.GENERIC_ERROR, "No valid hash algorithm!");
|
||||
}
|
||||
|
||||
byte[] challenge = data.getByteArrayExtra(SshAuthenticationApi.EXTRA_CHALLENGE);
|
||||
if (challenge == null || challenge.length == 0) {
|
||||
return createErrorResult(SshAuthenticationApiError.GENERIC_ERROR, "No challenge given");
|
||||
}
|
||||
|
||||
// carries the metadata necessary for authentication
|
||||
AuthenticationData.Builder authData = AuthenticationData.builder();
|
||||
authData.setAuthenticationMasterKeyId(masterKeyId);
|
||||
|
||||
CachedPublicKeyRing cachedPublicKeyRing = mKeyRepository.getCachedPublicKeyRing(masterKeyId);
|
||||
|
||||
long authSubKeyId;
|
||||
try {
|
||||
// get first usable subkey capable of authentication
|
||||
authSubKeyId = cachedPublicKeyRing.getSecretAuthenticationId();
|
||||
} catch (PgpKeyNotFoundException e) {
|
||||
return createExceptionErrorResult(SshAuthenticationApiError.NO_AUTH_KEY,
|
||||
"authentication key for master key id not found in keychain", e);
|
||||
}
|
||||
|
||||
authData.setAuthenticationSubKeyId(authSubKeyId);
|
||||
|
||||
authData.setAllowedAuthenticationKeyIds(getAllowedKeyIds());
|
||||
|
||||
authData.setHashAlgorithm(hashAlgorithmTag);
|
||||
|
||||
CryptoInputParcel inputParcel = CryptoInputParcelCacheService.getCryptoInputParcel(this, data);
|
||||
if (inputParcel == null) {
|
||||
// fresh request, assign UUID
|
||||
inputParcel = CryptoInputParcel.createCryptoInputParcel(new Date());
|
||||
}
|
||||
|
||||
AuthenticationParcel authParcel = AuthenticationParcel
|
||||
.createAuthenticationParcel(authData.build(), challenge);
|
||||
|
||||
// execute authentication operation!
|
||||
AuthenticationOperation authOperation = new AuthenticationOperation(this, mKeyRepository);
|
||||
AuthenticationResult authResult = authOperation.execute(authData.build(), inputParcel, authParcel);
|
||||
|
||||
if (authResult.isPending()) {
|
||||
RequiredInputParcel requiredInput = authResult.getRequiredInputParcel();
|
||||
PendingIntent pi = mApiPendingIntentFactory.requiredInputPi(data, requiredInput,
|
||||
authResult.mCryptoInputParcel);
|
||||
// return PendingIntent to be executed by client
|
||||
return packagePendingIntent(pi);
|
||||
} else if (authResult.success()) {
|
||||
return new SigningResponse(authResult.getSignature()).toIntent();
|
||||
} else {
|
||||
LogEntryParcel errorMsg = authResult.getLog().getLast();
|
||||
return createErrorResult(SshAuthenticationApiError.INTERNAL_ERROR, getString(errorMsg.mType.getMsgId()));
|
||||
}
|
||||
}
|
||||
|
||||
private Intent checkForKeyId(Intent data) {
|
||||
long authMasterKeyId = getKeyId(data);
|
||||
if (authMasterKeyId == Constants.key.none) {
|
||||
return createErrorResult(SshAuthenticationApiError.NO_KEY_ID,
|
||||
"No key id in request");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private long getKeyId(Intent data) {
|
||||
String keyIdString = data.getStringExtra(SshAuthenticationApi.EXTRA_KEY_ID);
|
||||
long authMasterKeyId = Constants.key.none;
|
||||
if (keyIdString != null) {
|
||||
try {
|
||||
authMasterKeyId = Long.valueOf(keyIdString);
|
||||
} catch (NumberFormatException e) {
|
||||
return Constants.key.none;
|
||||
}
|
||||
}
|
||||
return authMasterKeyId;
|
||||
}
|
||||
|
||||
private int getHashAlgorithm(Intent data) {
|
||||
int hashAlgorithm = data.getIntExtra(SshAuthenticationApi.EXTRA_HASH_ALGORITHM, HASHALGORITHM_NONE);
|
||||
|
||||
switch (hashAlgorithm) {
|
||||
case SshAuthenticationApi.SHA1:
|
||||
return HashAlgorithmTags.SHA1;
|
||||
case SshAuthenticationApi.RIPEMD160:
|
||||
return HashAlgorithmTags.RIPEMD160;
|
||||
case SshAuthenticationApi.SHA224:
|
||||
return HashAlgorithmTags.SHA224;
|
||||
case SshAuthenticationApi.SHA256:
|
||||
return HashAlgorithmTags.SHA256;
|
||||
case SshAuthenticationApi.SHA384:
|
||||
return HashAlgorithmTags.SHA384;
|
||||
case SshAuthenticationApi.SHA512:
|
||||
return HashAlgorithmTags.SHA512;
|
||||
default:
|
||||
return HASHALGORITHM_NONE;
|
||||
}
|
||||
}
|
||||
|
||||
private Intent getAuthenticationKey(Intent data) {
|
||||
long masterKeyId = getKeyId(data);
|
||||
if (masterKeyId != Constants.key.none) {
|
||||
String description;
|
||||
|
||||
try {
|
||||
description = getDescription(masterKeyId);
|
||||
} catch (PgpKeyNotFoundException e) {
|
||||
return createExceptionErrorResult(SshAuthenticationApiError.NO_SUCH_KEY,
|
||||
"Could not create description", e);
|
||||
}
|
||||
|
||||
return new KeySelectionResponse(String.valueOf(masterKeyId), description).toIntent();
|
||||
} else {
|
||||
return redirectToKeySelection(data);
|
||||
}
|
||||
}
|
||||
|
||||
private Intent redirectToKeySelection(Intent data) {
|
||||
String currentPkg = mApiPermissionHelper.getCurrentCallingPackage();
|
||||
PendingIntent pi = mApiPendingIntentFactory.createSelectAuthenticationKeyIdPendingIntent(data, currentPkg);
|
||||
return packagePendingIntent(pi);
|
||||
}
|
||||
|
||||
private Intent packagePendingIntent(PendingIntent pi) {
|
||||
Intent result = new Intent();
|
||||
result.putExtra(SshAuthenticationApi.EXTRA_RESULT_CODE,
|
||||
SshAuthenticationApi.RESULT_CODE_USER_INTERACTION_REQUIRED);
|
||||
result.putExtra(SshAuthenticationApi.EXTRA_PENDING_INTENT, pi);
|
||||
return result;
|
||||
}
|
||||
|
||||
private Intent getAuthenticationPublicKey(Intent data, boolean asSshKey) {
|
||||
long masterKeyId = getKeyId(data);
|
||||
if (masterKeyId != Constants.key.none) {
|
||||
try {
|
||||
if (asSshKey) {
|
||||
return getSSHPublicKey(masterKeyId);
|
||||
} else {
|
||||
return getX509PublicKey(masterKeyId);
|
||||
}
|
||||
} catch (KeyRepository.NotFoundException e) {
|
||||
return createExceptionErrorResult(SshAuthenticationApiError.NO_SUCH_KEY,
|
||||
"Key for master key id not found", e);
|
||||
} catch (PgpKeyNotFoundException e) {
|
||||
return createExceptionErrorResult(SshAuthenticationApiError.NO_AUTH_KEY,
|
||||
"Authentication key for master key id not found in keychain", e);
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
return createExceptionErrorResult(SshAuthenticationApi.RESULT_CODE_ERROR,
|
||||
"", e);
|
||||
}
|
||||
} else {
|
||||
return createErrorResult(SshAuthenticationApiError.NO_KEY_ID,
|
||||
"No key id in request");
|
||||
}
|
||||
}
|
||||
|
||||
private Intent getX509PublicKey(long masterKeyId) throws KeyRepository.NotFoundException, PgpKeyNotFoundException, NoSuchAlgorithmException {
|
||||
byte[] encodedPublicKey;
|
||||
int algorithm;
|
||||
|
||||
PublicKey publicKey;
|
||||
try {
|
||||
publicKey = getPublicKey(masterKeyId).getJcaPublicKey();
|
||||
} catch (PgpGeneralException e) { // this should probably never happen
|
||||
return createExceptionErrorResult(SshAuthenticationApiError.GENERIC_ERROR,
|
||||
"Error converting public key", e);
|
||||
}
|
||||
|
||||
encodedPublicKey = publicKey.getEncoded();
|
||||
algorithm = translateAlgorithm(publicKey.getAlgorithm());
|
||||
|
||||
return new PublicKeyResponse(encodedPublicKey, algorithm).toIntent();
|
||||
}
|
||||
|
||||
private int translateAlgorithm(String algorithm) throws NoSuchAlgorithmException {
|
||||
switch (algorithm) {
|
||||
case "RSA":
|
||||
return SshAuthenticationApi.RSA;
|
||||
case "ECDSA":
|
||||
return SshAuthenticationApi.ECDSA;
|
||||
case "EdDSA":
|
||||
return SshAuthenticationApi.EDDSA;
|
||||
case "DSA":
|
||||
return SshAuthenticationApi.DSA;
|
||||
default:
|
||||
throw new NoSuchAlgorithmException("Error matching key algorithm to API supported algorithm: "
|
||||
+ algorithm);
|
||||
}
|
||||
}
|
||||
|
||||
private Intent getSSHPublicKey(long masterKeyId) throws KeyRepository.NotFoundException, PgpKeyNotFoundException {
|
||||
String sshPublicKeyBlob;
|
||||
|
||||
CanonicalizedPublicKey publicKey = getPublicKey(masterKeyId);
|
||||
|
||||
SshPublicKey sshPublicKey = new SshPublicKey(publicKey);
|
||||
try {
|
||||
sshPublicKeyBlob = sshPublicKey.getEncodedKey();
|
||||
} catch (PgpGeneralException e) {
|
||||
return createExceptionErrorResult(SshAuthenticationApiError.GENERIC_ERROR,
|
||||
"Error converting public key to SSH format", e);
|
||||
}
|
||||
|
||||
return new SshPublicKeyResponse(sshPublicKeyBlob).toIntent();
|
||||
}
|
||||
|
||||
private CanonicalizedPublicKey getPublicKey(long masterKeyId)
|
||||
throws PgpKeyNotFoundException, KeyRepository.NotFoundException {
|
||||
KeyRepository keyRepository = KeyRepository.create(getApplicationContext());
|
||||
long authSubKeyId = keyRepository.getCachedPublicKeyRing(masterKeyId)
|
||||
.getSecretAuthenticationId();
|
||||
return keyRepository.getCanonicalizedPublicKeyRing(masterKeyId)
|
||||
.getPublicKey(authSubKeyId);
|
||||
}
|
||||
|
||||
private String getDescription(long masterKeyId) throws PgpKeyNotFoundException {
|
||||
CachedPublicKeyRing cachedPublicKeyRing = mKeyRepository.getCachedPublicKeyRing(masterKeyId);
|
||||
|
||||
String description = "";
|
||||
long authSubKeyId = cachedPublicKeyRing.getSecretAuthenticationId();
|
||||
description += cachedPublicKeyRing.getPrimaryUserId();
|
||||
description += " (" + Long.toHexString(authSubKeyId) + ")";
|
||||
|
||||
return description;
|
||||
}
|
||||
|
||||
private HashSet<Long> getAllowedKeyIds() {
|
||||
String currentPkg = mApiPermissionHelper.getCurrentCallingPackage();
|
||||
return mApiDao.getAllowedKeyIdsForApp(KeychainContract.ApiAllowedKeys.buildBaseUri(currentPkg));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return null if basic requirements are met
|
||||
*/
|
||||
private Intent checkRequirements(Intent data) {
|
||||
if (data == null) {
|
||||
return createErrorResult(SshAuthenticationApiError.GENERIC_ERROR, "No parameter bundle");
|
||||
}
|
||||
|
||||
// check version
|
||||
int apiVersion = data.getIntExtra(SshAuthenticationApi.EXTRA_API_VERSION, INVALID_API_VERSION);
|
||||
if (!SUPPORTED_VERSIONS.contains(apiVersion)) {
|
||||
String errorMsg = "Incompatible API versions:\n"
|
||||
+ "used : " + data.getIntExtra(SshAuthenticationApi.EXTRA_API_VERSION, INVALID_API_VERSION) + "\n"
|
||||
+ "supported : " + SUPPORTED_VERSIONS;
|
||||
|
||||
return createErrorResult(SshAuthenticationApiError.INCOMPATIBLE_API_VERSIONS, errorMsg);
|
||||
}
|
||||
|
||||
// check if caller is allowed to access OpenKeychain
|
||||
Intent result = mApiPermissionHelper.isAllowedOrReturnIntent(data);
|
||||
if (result != null) {
|
||||
return result; // disallowed, redirect to registration
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private Intent createErrorResult(int errorCode, String errorMessage) {
|
||||
Log.e(TAG, errorMessage);
|
||||
Intent result = new Intent();
|
||||
result.putExtra(SshAuthenticationApi.EXTRA_ERROR, new SshAuthenticationApiError(errorCode, errorMessage));
|
||||
result.putExtra(SshAuthenticationApi.EXTRA_RESULT_CODE, SshAuthenticationApi.RESULT_CODE_ERROR);
|
||||
return result;
|
||||
}
|
||||
|
||||
private Intent createExceptionErrorResult(int errorCode, String errorMessage, Exception e) {
|
||||
String message = errorMessage + " : " + e.getMessage();
|
||||
return createErrorResult(errorCode, message);
|
||||
}
|
||||
|
||||
}
|
|
@ -25,6 +25,7 @@ import java.util.List;
|
|||
import android.content.ContentResolver;
|
||||
import android.content.Context;
|
||||
import android.database.Cursor;
|
||||
import android.net.Uri;
|
||||
import android.support.annotation.Nullable;
|
||||
import android.support.v4.content.AsyncTaskLoader;
|
||||
|
||||
|
@ -41,6 +42,8 @@ public class KeyLoader extends AsyncTaskLoader<List<KeyInfo>> {
|
|||
KeyRings.MASTER_KEY_ID,
|
||||
KeyRings.CREATION,
|
||||
KeyRings.HAS_ENCRYPT,
|
||||
KeyRings.HAS_AUTHENTICATE,
|
||||
KeyRings.HAS_ANY_SECRET,
|
||||
KeyRings.VERIFIED,
|
||||
KeyRings.NAME,
|
||||
KeyRings.EMAIL,
|
||||
|
@ -51,34 +54,37 @@ public class KeyLoader extends AsyncTaskLoader<List<KeyInfo>> {
|
|||
private static final int INDEX_MASTER_KEY_ID = 1;
|
||||
private static final int INDEX_CREATION = 2;
|
||||
private static final int INDEX_HAS_ENCRYPT = 3;
|
||||
private static final int INDEX_VERIFIED = 4;
|
||||
private static final int INDEX_NAME = 5;
|
||||
private static final int INDEX_EMAIL = 6;
|
||||
private static final int INDEX_COMMENT = 7;
|
||||
private static final int INDEX_HAS_AUTHENTICATE = 4;
|
||||
private static final int INDEX_HAS_ANY_SECRET = 5;
|
||||
private static final int INDEX_VERIFIED = 6;
|
||||
private static final int INDEX_NAME = 7;
|
||||
private static final int INDEX_EMAIL = 8;
|
||||
private static final int INDEX_COMMENT = 9;
|
||||
|
||||
private static final String QUERY_WHERE = Tables.KEYS + "." + KeyRings.IS_REVOKED +
|
||||
" = 0 AND " + KeyRings.IS_EXPIRED + " = 0";
|
||||
private static final String QUERY_ORDER = Tables.KEYS + "." + KeyRings.CREATION + " DESC";
|
||||
|
||||
private final ContentResolver contentResolver;
|
||||
private final String emailAddress;
|
||||
private final KeySelector keySelector;
|
||||
|
||||
private List<KeyInfo> cachedResult;
|
||||
|
||||
|
||||
KeyLoader(Context context, ContentResolver contentResolver, String emailAddress) {
|
||||
KeyLoader(Context context, ContentResolver contentResolver, KeySelector keySelector) {
|
||||
super(context);
|
||||
|
||||
this.contentResolver = contentResolver;
|
||||
this.emailAddress = emailAddress;
|
||||
this.keySelector = keySelector;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<KeyInfo> loadInBackground() {
|
||||
ArrayList<KeyInfo> keyInfos = new ArrayList<>();
|
||||
Cursor cursor;
|
||||
|
||||
String selection = QUERY_WHERE + " AND " + keySelector.getSelection();
|
||||
cursor = contentResolver.query(keySelector.getKeyRingUri(), QUERY_PROJECTION, selection, null, QUERY_ORDER);
|
||||
|
||||
Cursor cursor = contentResolver.query(KeyRings.buildUnifiedKeyRingsFindByEmailUri(emailAddress),
|
||||
QUERY_PROJECTION, QUERY_WHERE, null, QUERY_ORDER);
|
||||
if (cursor == null) {
|
||||
return null;
|
||||
}
|
||||
|
@ -123,6 +129,8 @@ public class KeyLoader extends AsyncTaskLoader<List<KeyInfo>> {
|
|||
public abstract long getMasterKeyId();
|
||||
public abstract long getCreationDate();
|
||||
public abstract boolean getHasEncrypt();
|
||||
public abstract boolean getHasAuthenticate();
|
||||
public abstract boolean getHasAnySecret();
|
||||
public abstract boolean getIsVerified();
|
||||
|
||||
@Nullable
|
||||
|
@ -136,6 +144,8 @@ public class KeyLoader extends AsyncTaskLoader<List<KeyInfo>> {
|
|||
long masterKeyId = cursor.getLong(INDEX_MASTER_KEY_ID);
|
||||
long creationDate = cursor.getLong(INDEX_CREATION) * 1000L;
|
||||
boolean hasEncrypt = cursor.getInt(INDEX_HAS_ENCRYPT) != 0;
|
||||
boolean hasAuthenticate = cursor.getInt(INDEX_HAS_AUTHENTICATE) != 0;
|
||||
boolean hasAnySecret = cursor.getInt(INDEX_HAS_ANY_SECRET) != 0;
|
||||
boolean isVerified = cursor.getInt(INDEX_VERIFIED) == 2;
|
||||
|
||||
String name = cursor.getString(INDEX_NAME);
|
||||
|
@ -143,7 +153,17 @@ public class KeyLoader extends AsyncTaskLoader<List<KeyInfo>> {
|
|||
String comment = cursor.getString(INDEX_COMMENT);
|
||||
|
||||
return new AutoValue_KeyLoader_KeyInfo(
|
||||
masterKeyId, creationDate, hasEncrypt, isVerified, name, email, comment);
|
||||
masterKeyId, creationDate, hasEncrypt, hasAuthenticate, hasAnySecret, isVerified, name, email, comment);
|
||||
}
|
||||
}
|
||||
|
||||
@AutoValue
|
||||
public abstract static class KeySelector {
|
||||
public abstract Uri getKeyRingUri();
|
||||
public abstract String getSelection();
|
||||
|
||||
static KeySelector create(Uri keyRingUri, String selection) {
|
||||
return new AutoValue_KeyLoader_KeySelector(keyRingUri, selection);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -32,7 +32,9 @@ import android.support.v4.content.Loader;
|
|||
|
||||
import org.sufficientlysecure.keychain.Constants;
|
||||
import org.sufficientlysecure.keychain.provider.AutocryptPeerDataAccessObject;
|
||||
import org.sufficientlysecure.keychain.provider.KeychainContract.KeyRings;
|
||||
import org.sufficientlysecure.keychain.remote.ui.dialog.KeyLoader.KeyInfo;
|
||||
import org.sufficientlysecure.keychain.remote.ui.dialog.KeyLoader.KeySelector;
|
||||
import org.sufficientlysecure.keychain.util.Log;
|
||||
|
||||
|
||||
|
@ -90,7 +92,10 @@ class RemoteDeduplicatePresenter implements LoaderCallbacks<List<KeyInfo>> {
|
|||
|
||||
@Override
|
||||
public Loader<List<KeyInfo>> onCreateLoader(int id, Bundle args) {
|
||||
return new KeyLoader(context, context.getContentResolver(), duplicateAddress);
|
||||
KeySelector keySelector = KeySelector.create(
|
||||
KeyRings.buildUnifiedKeyRingsFindByEmailUri(duplicateAddress), null);
|
||||
|
||||
return new KeyLoader(context, context.getContentResolver(), keySelector);
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
|
@ -0,0 +1,349 @@
|
|||
/*
|
||||
* Copyright (C) 2017 Vincent Breitmoser <v.breitmoser@mugenguild.com>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package org.sufficientlysecure.keychain.remote.ui.dialog;
|
||||
|
||||
|
||||
import android.annotation.SuppressLint;
|
||||
import android.app.Activity;
|
||||
import android.app.Dialog;
|
||||
import android.content.Context;
|
||||
import android.content.DialogInterface;
|
||||
import android.content.Intent;
|
||||
import android.content.res.Resources;
|
||||
import android.graphics.drawable.Drawable;
|
||||
import android.graphics.drawable.Drawable.ConstantState;
|
||||
import android.net.Uri;
|
||||
import android.os.Bundle;
|
||||
import android.support.annotation.NonNull;
|
||||
import android.support.v4.app.DialogFragment;
|
||||
import android.support.v4.app.FragmentActivity;
|
||||
import android.support.v4.content.res.ResourcesCompat;
|
||||
import android.support.v4.graphics.drawable.DrawableCompat;
|
||||
import android.support.v7.widget.LinearLayoutManager;
|
||||
import android.support.v7.widget.RecyclerView;
|
||||
import android.support.v7.widget.RecyclerView.Adapter;
|
||||
import android.text.format.DateUtils;
|
||||
import android.view.ContextThemeWrapper;
|
||||
import android.view.LayoutInflater;
|
||||
import android.view.View;
|
||||
import android.view.View.OnClickListener;
|
||||
import android.view.ViewGroup;
|
||||
import android.widget.Button;
|
||||
import android.widget.ImageView;
|
||||
import android.widget.TextView;
|
||||
|
||||
import com.mikepenz.materialdrawer.util.KeyboardUtil;
|
||||
|
||||
import org.openintents.ssh.authentication.SshAuthenticationApi;
|
||||
import org.sufficientlysecure.keychain.R;
|
||||
import org.sufficientlysecure.keychain.provider.ApiDataAccessObject;
|
||||
import org.sufficientlysecure.keychain.provider.KeychainContract;
|
||||
import org.sufficientlysecure.keychain.remote.ui.RemoteSecurityTokenOperationActivity;
|
||||
import org.sufficientlysecure.keychain.remote.ui.dialog.KeyLoader.KeyInfo;
|
||||
import org.sufficientlysecure.keychain.remote.ui.dialog.RemoteSelectAuthenticationKeyPresenter.RemoteSelectAuthenticationKeyView;
|
||||
import org.sufficientlysecure.keychain.ui.dialog.CustomAlertDialogBuilder;
|
||||
import org.sufficientlysecure.keychain.ui.util.ThemeChanger;
|
||||
import org.sufficientlysecure.keychain.ui.util.recyclerview.DividerItemDecoration;
|
||||
import org.sufficientlysecure.keychain.ui.util.recyclerview.RecyclerItemClickListener;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
public class RemoteSelectAuthenticationKeyActivity extends FragmentActivity {
|
||||
public static final String EXTRA_PACKAGE_NAME = "package_name";
|
||||
|
||||
public static final int LOADER_ID_KEYS = 0;
|
||||
|
||||
|
||||
private RemoteSelectAuthenticationKeyPresenter presenter;
|
||||
|
||||
|
||||
@Override
|
||||
protected void onCreate(Bundle savedInstanceState) {
|
||||
super.onCreate(savedInstanceState);
|
||||
|
||||
presenter = new RemoteSelectAuthenticationKeyPresenter(getBaseContext(), LOADER_ID_KEYS);
|
||||
|
||||
KeyboardUtil.hideKeyboard(this);
|
||||
|
||||
if (savedInstanceState == null) {
|
||||
RemoteSelectAuthenticationKeyDialogFragment frag = new RemoteSelectAuthenticationKeyDialogFragment();
|
||||
frag.show(getSupportFragmentManager(), "selectAuthenticationKeyDialog");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onStart() {
|
||||
super.onStart();
|
||||
|
||||
Intent intent = getIntent();
|
||||
String packageName = intent.getStringExtra(EXTRA_PACKAGE_NAME);
|
||||
|
||||
|
||||
presenter.setupFromIntentData(packageName);
|
||||
presenter.startLoaders(getSupportLoaderManager());
|
||||
}
|
||||
|
||||
private void onKeySelected(long masterKeyId) {
|
||||
Intent callingIntent = getIntent();
|
||||
Intent originalIntent = callingIntent.getParcelableExtra(
|
||||
RemoteSecurityTokenOperationActivity.EXTRA_DATA);
|
||||
|
||||
Uri appUri = callingIntent.getData();
|
||||
|
||||
Uri allowedKeysUri = appUri.buildUpon()
|
||||
.appendPath(KeychainContract.PATH_ALLOWED_KEYS)
|
||||
.build();
|
||||
|
||||
ApiDataAccessObject apiDao = new ApiDataAccessObject(getBaseContext());
|
||||
apiDao.addAllowedKeyIdForApp(allowedKeysUri, masterKeyId);
|
||||
|
||||
originalIntent.putExtra(SshAuthenticationApi.EXTRA_KEY_ID, String.valueOf(masterKeyId));
|
||||
|
||||
setResult(RESULT_OK, originalIntent);
|
||||
finish();
|
||||
}
|
||||
|
||||
public static class RemoteSelectAuthenticationKeyDialogFragment extends DialogFragment {
|
||||
private RemoteSelectAuthenticationKeyPresenter presenter;
|
||||
private RemoteSelectAuthenticationKeyView mvpView;
|
||||
|
||||
private Button buttonSelect;
|
||||
private Button buttonCancel;
|
||||
private RecyclerView keyChoiceList;
|
||||
|
||||
@NonNull
|
||||
@Override
|
||||
public Dialog onCreateDialog(Bundle savedInstanceState) {
|
||||
final Activity activity = getActivity();
|
||||
|
||||
ContextThemeWrapper theme = ThemeChanger.getDialogThemeWrapper(activity);
|
||||
CustomAlertDialogBuilder alert = new CustomAlertDialogBuilder(theme);
|
||||
|
||||
LayoutInflater layoutInflater = LayoutInflater.from(theme);
|
||||
@SuppressLint("InflateParams")
|
||||
View view = layoutInflater.inflate(R.layout.api_remote_select_authentication_key, null, false);
|
||||
alert.setView(view);
|
||||
|
||||
buttonSelect = (Button) view.findViewById(R.id.button_select);
|
||||
buttonCancel = (Button) view.findViewById(R.id.button_cancel);
|
||||
|
||||
keyChoiceList = (RecyclerView) view.findViewById(R.id.authentication_key_list);
|
||||
keyChoiceList.setLayoutManager(new LinearLayoutManager(activity));
|
||||
keyChoiceList.addItemDecoration(
|
||||
new DividerItemDecoration(activity, DividerItemDecoration.VERTICAL_LIST, true));
|
||||
|
||||
setupListenersForPresenter();
|
||||
mvpView = createMvpView(view, layoutInflater);
|
||||
|
||||
return alert.create();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onActivityCreated(Bundle savedInstanceState) {
|
||||
super.onActivityCreated(savedInstanceState);
|
||||
|
||||
presenter = ((RemoteSelectAuthenticationKeyActivity) getActivity()).presenter;
|
||||
presenter.setView(mvpView);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCancel(DialogInterface dialog) {
|
||||
super.onCancel(dialog);
|
||||
|
||||
if (presenter != null) {
|
||||
presenter.onCancel();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onDismiss(DialogInterface dialog) {
|
||||
super.onDismiss(dialog);
|
||||
|
||||
if (presenter != null) {
|
||||
presenter.setView(null);
|
||||
presenter = null;
|
||||
}
|
||||
}
|
||||
|
||||
@NonNull
|
||||
private RemoteSelectAuthenticationKeyView createMvpView(View view, LayoutInflater layoutInflater) {
|
||||
final ImageView iconClientApp = (ImageView) view.findViewById(R.id.icon_client_app);
|
||||
final KeyChoiceAdapter keyChoiceAdapter = new KeyChoiceAdapter(layoutInflater, getResources());
|
||||
keyChoiceList.setAdapter(keyChoiceAdapter);
|
||||
|
||||
return new RemoteSelectAuthenticationKeyView() {
|
||||
@Override
|
||||
public void finish(long masterKeyId) {
|
||||
FragmentActivity activity = getActivity();
|
||||
if (activity == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
((RemoteSelectAuthenticationKeyActivity)activity).onKeySelected(masterKeyId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void finishAsCancelled() {
|
||||
FragmentActivity activity = getActivity();
|
||||
if (activity == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
activity.setResult(RESULT_CANCELED);
|
||||
activity.finish();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setTitleClientIcon(Drawable drawable) {
|
||||
iconClientApp.setImageDrawable(drawable);
|
||||
keyChoiceAdapter.setSelectionDrawable(drawable);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setKeyListData(List<KeyInfo> data) {
|
||||
keyChoiceAdapter.setData(data);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setActiveItem(Integer position) {
|
||||
keyChoiceAdapter.setActiveItem(position);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setEnableSelectButton(boolean enabled) {
|
||||
buttonSelect.setEnabled(enabled);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private void setupListenersForPresenter() {
|
||||
buttonSelect.setOnClickListener(new OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
presenter.onClickSelect();
|
||||
}
|
||||
});
|
||||
|
||||
buttonCancel.setOnClickListener(new OnClickListener() {
|
||||
@Override
|
||||
public void onClick(View view) {
|
||||
presenter.onClickCancel();
|
||||
}
|
||||
});
|
||||
|
||||
keyChoiceList.addOnItemTouchListener(new RecyclerItemClickListener(getContext(),
|
||||
new RecyclerItemClickListener.OnItemClickListener() {
|
||||
@Override
|
||||
public void onItemClick(View view, int position) {
|
||||
presenter.onKeyItemClick(position);
|
||||
}
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
private static class KeyChoiceAdapter extends Adapter<KeyChoiceViewHolder> {
|
||||
private final LayoutInflater layoutInflater;
|
||||
private final Resources resources;
|
||||
private List<KeyInfo> data;
|
||||
private Drawable iconUnselected;
|
||||
private Drawable iconSelected;
|
||||
private Integer activeItem;
|
||||
|
||||
KeyChoiceAdapter(LayoutInflater layoutInflater, Resources resources) {
|
||||
this.layoutInflater = layoutInflater;
|
||||
this.resources = resources;
|
||||
}
|
||||
|
||||
@Override
|
||||
public KeyChoiceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
|
||||
View keyChoiceItemView = layoutInflater.inflate(R.layout.authentication_key_item, parent, false);
|
||||
return new KeyChoiceViewHolder(keyChoiceItemView);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onBindViewHolder(KeyChoiceViewHolder holder, int position) {
|
||||
KeyInfo keyInfo = data.get(position);
|
||||
Drawable icon = (activeItem != null && position == activeItem) ? iconSelected : iconUnselected;
|
||||
holder.bind(keyInfo, icon);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getItemCount() {
|
||||
return data != null ? data.size() : 0;
|
||||
}
|
||||
|
||||
public void setData(List<KeyInfo> data) {
|
||||
this.data = data;
|
||||
notifyDataSetChanged();
|
||||
}
|
||||
|
||||
void setSelectionDrawable(Drawable drawable) {
|
||||
ConstantState constantState = drawable.getConstantState();
|
||||
if (constantState == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
iconSelected = constantState.newDrawable(resources);
|
||||
|
||||
iconUnselected = constantState.newDrawable(resources);
|
||||
DrawableCompat.setTint(iconUnselected.mutate(), ResourcesCompat.getColor(resources, R.color.md_grey_300, null));
|
||||
|
||||
notifyDataSetChanged();
|
||||
}
|
||||
|
||||
void setActiveItem(Integer newActiveItem) {
|
||||
Integer prevActiveItem = this.activeItem;
|
||||
this.activeItem = newActiveItem;
|
||||
|
||||
if (prevActiveItem != null) {
|
||||
notifyItemChanged(prevActiveItem);
|
||||
}
|
||||
if (newActiveItem != null) {
|
||||
notifyItemChanged(newActiveItem);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class KeyChoiceViewHolder extends RecyclerView.ViewHolder {
|
||||
private final TextView vName;
|
||||
private final TextView vCreation;
|
||||
private final ImageView vIcon;
|
||||
|
||||
KeyChoiceViewHolder(View itemView) {
|
||||
super(itemView);
|
||||
|
||||
vName = (TextView) itemView.findViewById(R.id.key_list_item_name);
|
||||
vCreation = (TextView) itemView.findViewById(R.id.key_list_item_creation);
|
||||
vIcon = (ImageView) itemView.findViewById(R.id.key_list_item_icon);
|
||||
}
|
||||
|
||||
void bind(KeyInfo keyInfo, Drawable selectionIcon) {
|
||||
vName.setText(keyInfo.getName());
|
||||
|
||||
Context context = vCreation.getContext();
|
||||
String dateTime = DateUtils.formatDateTime(context, keyInfo.getCreationDate(),
|
||||
DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME |
|
||||