Add sshauthentication-api v1 support

This commit is contained in:
Christian Hagau
2017-10-05 00:00:00 +00:00
parent 83ab483fc7
commit 2619cb1db3
57 changed files with 3954 additions and 79 deletions

View File

@@ -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);

View File

@@ -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);
}
}

View File

@@ -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);
}
}
}

View File

@@ -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

View File

@@ -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 |
DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_ABBREV_MONTH);
vCreation.setText(context.getString(R.string.label_key_created, dateTime));
vIcon.setImageDrawable(selectionIcon);
}
}
}

View File

@@ -0,0 +1,146 @@
/*
* 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.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.LoaderManager;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import org.sufficientlysecure.keychain.Constants;
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;
import java.util.List;
class RemoteSelectAuthenticationKeyPresenter implements LoaderCallbacks<List<KeyInfo>> {
private final PackageManager packageManager;
private final Context context;
private final int loaderId;
private RemoteSelectAuthenticationKeyView view;
private Integer selectedItem;
private List<KeyInfo> keyInfoData;
RemoteSelectAuthenticationKeyPresenter(Context context, int loaderId) {
this.context = context;
packageManager = context.getPackageManager();
this.loaderId = loaderId;
}
public void setView(RemoteSelectAuthenticationKeyView view) {
this.view = view;
}
void setupFromIntentData(String packageName) {
try {
setPackageInfo(packageName);
} catch (NameNotFoundException e) {
Log.e(Constants.TAG, "Unable to find info of calling app!");
view.finishAsCancelled();
}
}
private void setPackageInfo(String packageName) throws NameNotFoundException {
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0);
Drawable appIcon = packageManager.getApplicationIcon(applicationInfo);
view.setTitleClientIcon(appIcon);
}
void startLoaders(LoaderManager loaderManager) {
loaderManager.restartLoader(loaderId, null, this);
}
@Override
public Loader<List<KeyInfo>> onCreateLoader(int id, Bundle args) {
String selection = KeyRings.HAS_ANY_SECRET + " != 0 AND " + KeyRings.HAS_AUTHENTICATE + " != 0";
KeySelector keySelector = KeySelector.create(
KeyRings.buildUnifiedKeyRingsUri(), selection);
return new KeyLoader(context, context.getContentResolver(), keySelector);
}
@Override
public void onLoadFinished(Loader<List<KeyInfo>> loader, List<KeyInfo> data) {
this.keyInfoData = data;
view.setKeyListData(data);
}
@Override
public void onLoaderReset(Loader loader) {
if (view != null) {
view.setKeyListData(null);
}
}
void onClickSelect() {
if (keyInfoData == null) {
Log.e(Constants.TAG, "got click on select with no data…?");
return;
}
if (selectedItem == null) {
Log.e(Constants.TAG, "got click on select with no selection…?");
return;
}
long masterKeyId = keyInfoData.get(selectedItem).getMasterKeyId();
view.finish(masterKeyId);
}
void onClickCancel() {
view.finishAsCancelled();
}
public void onCancel() {
view.finishAsCancelled();
}
void onKeyItemClick(int position) {
if (selectedItem != null && position == selectedItem) {
selectedItem = null;
} else {
selectedItem = position;
}
view.setActiveItem(selectedItem);
view.setEnableSelectButton(selectedItem != null);
}
interface RemoteSelectAuthenticationKeyView {
void finish(long masterKeyId);
void finishAsCancelled();
void setTitleClientIcon(Drawable drawable);
void setKeyListData(List<KeyInfo> data);
void setActiveItem(Integer position);
void setEnableSelectButton(boolean enabled);
}
}