use of co.krypt.krypton.pgp.asciiarmor.AsciiArmor in project krypton-android by kryptco.
the class Silo method respondToRequest.
public void respondToRequest(Pairing pairing, Request request, boolean requestAllowed) throws Unrecoverable {
// Fine-grained locking allows performing signatures in parallel
synchronized ((Silo.class.getName() + request.requestID).intern()) {
synchronized (Silo.class) {
if (sendCachedResponseIfPresent(pairing, request)) {
return;
}
}
Response response = Response.with(request);
Analytics analytics = new Analytics(context);
if (analytics.isDisabled()) {
response.trackingID = "disabled";
} else {
response.trackingID = analytics.getClientID();
}
request.body.visit(new RequestBody.Visitor<Void, Unrecoverable>() {
@Override
public Void visit(MeRequest meRequest) throws CryptoException {
response.meResponse = new MeResponse(meStorage.loadWithUserID(meRequest.userID()));
return null;
}
@Override
public Void visit(SignRequest signRequest) throws Unrecoverable {
signRequest.validate();
response.signResponse = new SignResponse();
if (requestAllowed) {
try {
SSHKeyPairI key = MeStorage.getOrLoadKeyPair(context);
if (MessageDigest.isEqual(signRequest.publicKeyFingerprint, key.publicKeyFingerprint())) {
if (signRequest.verifyHostName()) {
String hostName = signRequest.hostAuth.hostNames[0];
String hostKey = Base64.encodeAsString(signRequest.hostAuth.hostKey);
synchronized (databaseLock) {
List<KnownHost> matchingKnownHosts = dbHelper.getKnownHostDao().queryForEq("host_name", hostName);
try {
Sigchain.NativeResult<List<Sigchain.PinnedHost>> teamPinnedHosts = TeamDataProvider.getPinnedKeysByHost(context, hostName);
if (teamPinnedHosts.success != null) {
for (Sigchain.PinnedHost pinnedHost : teamPinnedHosts.success) {
matchingKnownHosts.add(new KnownHost(pinnedHost.host, co.krypt.krypton.crypto.Base64.encode(pinnedHost.publicKey), 0));
}
}
} catch (Native.NotLinked e) {
e.printStackTrace();
}
if (matchingKnownHosts.size() == 0) {
dbHelper.getKnownHostDao().create(new KnownHost(hostName, hostKey, System.currentTimeMillis() / 1000));
broadcastKnownHostsChanged();
} else {
boolean foundKnownHost = false;
List<String> pinnedPublicKeys = new ArrayList<>();
for (KnownHost pinnedHost : matchingKnownHosts) {
pinnedPublicKeys.add(pinnedHost.publicKey);
if (pinnedHost.publicKey.equals(hostKey)) {
foundKnownHost = true;
break;
}
}
if (!foundKnownHost) {
throw new MismatchedHostKeyException(pinnedPublicKeys, "Expected " + pinnedPublicKeys.toString() + " received " + hostKey);
}
}
}
}
String algo = signRequest.algo();
if ((key instanceof RSASSHKeyPair) && request.semVer().lessThan(Versions.KR_SUPPORTS_RSA_SHA256_512)) {
algo = "ssh-rsa";
}
response.signResponse.signature = key.signDigestAppendingPubkey(signRequest.data, algo);
SSHSignatureLog log = new SSHSignatureLog(signRequest.data, true, signRequest.command, signRequest.user(), signRequest.firstHostnameIfExists(), System.currentTimeMillis() / 1000, signRequest.verifyHostName(), JSON.toJson(signRequest.hostAuth), pairing.getUUIDString(), pairing.workstationName);
co.krypt.krypton.team.log.Log teamLog = co.krypt.krypton.team.log.Log.fromSSHRequest(pairing, request, signRequest, co.krypt.krypton.team.log.Log.Body.SSH.Result.signature(response.signResponse.signature));
EventBus.getDefault().post(new TeamService.EncryptLog(C.background(context), teamLog));
pairingStorage.appendToSSHLog(log);
Notifications.notifySuccess(context, pairing, request, log);
if (signRequest.verifiedHostNameOrDefault("unknown host").equals("me.krypt.co")) {
Intent sshMeIntent = new Intent(TestSSHFragment.SSH_ME_ACTION);
LocalBroadcastManager.getInstance(context).sendBroadcast(sshMeIntent);
}
if (signRequest.hostAuth == null) {
new Analytics(context).postEvent("host", "unknown", null, null, false);
} else if (!signRequest.verifyHostName()) {
new Analytics(context).postEvent("host", "unverified", null, null, false);
}
} else {
Log.e(TAG, Base64.encodeAsString(signRequest.publicKeyFingerprint) + " != " + Base64.encodeAsString(key.publicKeyFingerprint()));
response.signResponse.error = "unknown key fingerprint";
}
} catch (SQLException e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
response.signResponse.error = "SQL error: " + e.getMessage() + "\n" + sw.toString();
e.printStackTrace();
} catch (MismatchedHostKeyException e) {
response.signResponse.error = "host public key mismatched";
if (signRequest.hostAuth.hostKey != null) {
co.krypt.krypton.team.log.Log teamLog = co.krypt.krypton.team.log.Log.fromSSHRequest(pairing, request, signRequest, co.krypt.krypton.team.log.Log.Body.SSH.Result.hostMismatch(e.pinnedPublicKeys.toArray(new String[] {})));
EventBus.getDefault().post(new TeamService.EncryptLog(C.background(context), teamLog));
}
Notifications.notifyReject(context, pairing, request, "Host public key mismatched.");
e.printStackTrace();
}
} else {
response.signResponse.error = "rejected";
co.krypt.krypton.team.log.Log teamLog = co.krypt.krypton.team.log.Log.fromSSHRequest(pairing, request, signRequest, co.krypt.krypton.team.log.Log.Body.SSH.Result.userRejected());
EventBus.getDefault().post(new TeamService.EncryptLog(C.background(context), teamLog));
pairingStorage.appendToSSHLog(new SSHSignatureLog(signRequest.data, false, signRequest.command, signRequest.user(), signRequest.firstHostnameIfExists(), System.currentTimeMillis() / 1000, signRequest.verifyHostName(), JSON.toJson(signRequest.hostAuth), pairing.getUUIDString(), pairing.workstationName));
}
return null;
}
@Override
public Void visit(GitSignRequest gitSignRequest) throws Unrecoverable {
if (requestAllowed) {
try {
SSHKeyPairI key = MeStorage.getOrLoadKeyPair(context);
new MeStorage(context).loadWithUserID(UserID.parse(gitSignRequest.userID));
co.krypt.krypton.team.log.Log.Body.GitSignatureResult gitSignatureResult = new co.krypt.krypton.team.log.Log.Body.GitSignatureResult();
co.krypt.krypton.log.Log log = gitSignRequest.body.visit(new GitSignRequestBody.Visitor<co.krypt.krypton.log.Log, Exception>() {
@Override
public co.krypt.krypton.log.Log visit(CommitInfo commit) throws Unrecoverable {
byte[] signature = SignableUtils.signBinaryDocument(commit, key, HashAlgorithm.SHA512);
response.gitSignResponse = new GitSignResponse(signature, null);
gitSignatureResult.signature = signature;
GitCommitSignatureLog commitLog = new GitCommitSignatureLog(pairing, commit, new AsciiArmor(AsciiArmor.HeaderLine.SIGNATURE, AsciiArmor.backwardsCompatibleHeaders(request.semVer()), signature).toString());
pairings().appendToCommitLogs(commitLog);
return commitLog;
}
@Override
public co.krypt.krypton.log.Log visit(TagInfo tag) throws Unrecoverable {
byte[] signature = SignableUtils.signBinaryDocument(tag, key, HashAlgorithm.SHA512);
response.gitSignResponse = new GitSignResponse(signature, null);
gitSignatureResult.signature = signature;
GitTagSignatureLog tagLog = new GitTagSignatureLog(pairing, tag, new AsciiArmor(AsciiArmor.HeaderLine.SIGNATURE, AsciiArmor.backwardsCompatibleHeaders(request.semVer()), signature).toString());
pairings().appendToTagLogs(tagLog);
return tagLog;
}
});
co.krypt.krypton.team.log.Log teamLog = co.krypt.krypton.team.log.Log.fromGitRequest(pairing, request, gitSignRequest, gitSignatureResult);
EventBus.getDefault().post(new TeamService.EncryptLog(C.background(context), teamLog));
Notifications.notifySuccess(context, pairing, request, log);
} catch (Exception e) {
e.printStackTrace();
response.gitSignResponse = new GitSignResponse(null, "unknown error");
}
} else {
response.gitSignResponse = new GitSignResponse(null, "rejected");
gitSignRequest.body.visit(new GitSignRequestBody.Visitor<Void, RuntimeException>() {
@Override
public Void visit(CommitInfo commit) throws RuntimeException {
pairings().appendToCommitLogs(new GitCommitSignatureLog(pairing, commit, null));
return null;
}
@Override
public Void visit(TagInfo tag) throws RuntimeException {
pairings().appendToTagLogs(new GitTagSignatureLog(pairing, tag, null));
return null;
}
});
co.krypt.krypton.team.log.Log teamLog = co.krypt.krypton.team.log.Log.fromGitRequest(pairing, request, gitSignRequest, co.krypt.krypton.team.log.Log.Body.GitSignatureResult.userRejected());
EventBus.getDefault().post(new TeamService.EncryptLog(C.background(context), teamLog));
}
return null;
}
@Override
public Void visit(UnpairRequest unpairRequest) throws Unrecoverable {
// Processed in handle()
return null;
}
@Override
public Void visit(HostsRequest hostsRequest) throws Unrecoverable {
HostsResponse hostsResponse = new HostsResponse();
synchronized (databaseLock) {
try {
List<SSHSignatureLog> sshLogs = dbHelper.getSSHSignatureLogDao().queryBuilder().groupByRaw("user, host_name").query();
List<UserAndHost> userAndHosts = new LinkedList<>();
for (SSHSignatureLog log : sshLogs) {
UserAndHost userAndHost = new UserAndHost();
userAndHost.user = log.user;
userAndHost.host = log.hostName;
userAndHosts.add(userAndHost);
}
HostInfo hostInfo = new HostInfo();
UserAndHost[] userAndHostsArray = new UserAndHost[userAndHosts.size()];
userAndHosts.toArray(userAndHostsArray);
hostInfo.hosts = userAndHostsArray;
List<UserID> userIDs = meStorage.getUserIDs();
List<String> userIDStrings = new LinkedList<>();
for (UserID userID : userIDs) {
userIDStrings.add(userID.toString());
}
String[] userIDArray = new String[userIDs.size()];
userIDStrings.toArray(userIDArray);
hostInfo.pgpUserIDs = userIDArray;
hostsResponse.hostInfo = hostInfo;
} catch (SQLException e1) {
hostsResponse.error = "sql exception";
}
}
response.hostsResponse = hostsResponse;
return null;
}
@Override
public Void visit(ReadTeamRequest readTeamRequest) throws Unrecoverable {
SuccessOrTaggedErrorResult<JsonObject> result = new SuccessOrTaggedErrorResult<>();
response.readTeamResponse = result;
if (requestAllowed) {
try {
Sigchain.NativeResult<JsonObject> readToken = TeamDataProvider.signReadToken(context, readTeamRequest.publicKey);
if (readToken.success != null) {
result.success = readToken.success;
} else {
result.error = readToken.error;
}
} catch (Native.NotLinked e) {
e.printStackTrace();
result.error = e.getMessage();
}
} else {
response.readTeamResponse.error = "rejected";
}
return null;
}
@Override
public Void visit(LogDecryptionRequest logDecryptionRequest) throws Unrecoverable {
SuccessOrTaggedErrorResult<JsonObject> result = new SuccessOrTaggedErrorResult<>();
response.logDecryptionResponse = result;
if (requestAllowed) {
try {
Sigchain.NativeResult<JsonObject> unwrappedKey = TeamDataProvider.unwrapKey(context, logDecryptionRequest.wrappedKey);
if (unwrappedKey.success != null) {
result.success = unwrappedKey.success;
} else {
result.error = unwrappedKey.error;
}
} catch (Native.NotLinked e) {
e.printStackTrace();
result.error = e.getMessage();
}
} else {
response.logDecryptionResponse.error = "rejected";
}
return null;
}
@Override
public Void visit(TeamOperationRequest teamOperationRequest) throws Unrecoverable {
SuccessOrTaggedErrorResult<Sigchain.TeamOperationResponse> result = new SuccessOrTaggedErrorResult<>();
response.teamOperationResponse = result;
if (requestAllowed) {
try {
Sigchain.NativeResult<Sigchain.TeamOperationResponse> nativeResult = TeamDataProvider.requestTeamOperation(context, teamOperationRequest.operation);
if (nativeResult.success != null) {
response.teamOperationResponse.success = nativeResult.success;
} else {
response.teamOperationResponse.error = nativeResult.error;
}
} catch (Native.NotLinked e) {
e.printStackTrace();
result.error = e.getMessage();
}
} else {
response.teamOperationResponse.error = "rejected";
}
return null;
}
});
response.snsEndpointARN = SNSTransport.getInstance(context).getEndpointARN();
synchronized (Silo.class) {
try {
if (responseDiskCacheByRequestID != null && !responseDiskCacheByRequestID.isClosed()) {
DiskLruCache.Editor cacheEditor = responseDiskCacheByRequestID.edit(request.requestIDCacheKey(pairing));
cacheEditor.set(0, JSON.toJson(response));
cacheEditor.commit();
responseDiskCacheByRequestID.flush();
}
} catch (IOException e) {
e.printStackTrace();
throw new Unrecoverable(e);
}
responseMemCacheByRequestID.put(request.requestIDCacheKey(pairing), response);
}
send(pairing, response);
}
}
use of co.krypt.krypton.pgp.asciiarmor.AsciiArmor in project krypton-android by kryptco.
the class MemberDetailFragment method updateUI.
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void updateUI(TeamService.GetTeamHomeDataResult result) {
if (result.r.success == null) {
return;
}
boolean i_am_admin = result.r.success.is_admin;
Sigchain.Member selected = null;
for (Sigchain.Member member : result.r.success.members) {
if (Arrays.equals(publicKey, member.identity.publicKey)) {
selected = member;
}
}
if (selected == null) {
getFragmentManager().popBackStack();
return;
}
final Sigchain.Member member = selected;
if (selected.is_removed) {
roleLabel.setText("Removed");
} else {
if (selected.is_admin) {
roleLabel.setText("Admin");
} else {
roleLabel.setText("Member");
}
}
email.setText(selected.identity.email);
if (i_am_admin) {
if (selected.is_removed) {
removeButton.animate().alpha(0f).setDuration(500).start();
removeButton.setEnabled(false);
promoteDemoteButton.animate().alpha(0f).setDuration(500).start();
promoteDemoteButton.setEnabled(false);
} else {
removeButton.animate().alpha(1f).setDuration(500).start();
removeButton.setEnabled(true);
removeButton.setOnClickListener(v -> requestOp(Sigchain.RequestableTeamOperation.remove(publicKey)));
promoteDemoteButton.setEnabled(true);
promoteDemoteButton.animate().alpha(1f).setDuration(500).start();
if (selected.is_admin) {
promoteDemoteButton.setText("Demote");
promoteDemoteButton.setOnClickListener(v -> requestOp(Sigchain.RequestableTeamOperation.demote(publicKey)));
} else {
promoteDemoteButton.setText("Promote");
promoteDemoteButton.setOnClickListener(v -> requestOp(Sigchain.RequestableTeamOperation.promote(publicKey)));
}
}
} else {
promoteDemoteButton.setEnabled(false);
promoteDemoteButton.animate().alpha(0f).setDuration(500).start();
removeButton.setEnabled(false);
removeButton.animate().alpha(0f).setDuration(500).start();
}
sshButton.setOnClickListener(v -> {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
try {
sharingIntent.putExtra(Intent.EXTRA_TEXT, Wire.publicKeyBytesToAuthorizedKeysFormat(member.identity.sshPublicKey));
startActivity(Intent.createChooser(sharingIntent, "Share " + member.identity.email + "'s SSH public key"));
} catch (IOException e) {
Error.shortToast(getContext(), "Failed to export public key");
e.printStackTrace();
}
});
pgpButton.setOnClickListener(v -> {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, new AsciiArmor(AsciiArmor.HeaderLine.PUBLIC_KEY, AsciiArmor.KRYPTON_DEFAULT_HEADERS, member.identity.pgpPublicKey).toString());
startActivity(Intent.createChooser(sharingIntent, "Share " + member.identity.email + "'s PGP public key"));
});
}
use of co.krypt.krypton.pgp.asciiarmor.AsciiArmor in project krypton-android by kryptco.
the class AsciiArmorTest method publicKey_parses.
@Test
public void publicKey_parses() throws Exception {
AsciiArmor aa = AsciiArmor.parse(PGPPublicKeyTest.testPubKey1);
Assert.assertTrue(aa.headerLine.equals(AsciiArmor.HeaderLine.PUBLIC_KEY));
Assert.assertTrue(aa.headers.size() == 1);
Assert.assertTrue(aa.headers.get(0).first.equals("Comment"));
Assert.assertTrue(aa.headers.get(0).second.equals("Some test hello"));
String reserialized = aa.toString();
Assert.assertTrue(reserialized.equals(PGPPublicKeyTest.testPubKey1));
}
use of co.krypt.krypton.pgp.asciiarmor.AsciiArmor in project krypton-android by kryptco.
the class GitTest method testCommitHash.
@Test
public void testCommitHash() throws Exception {
byte[] sigMessage = Base64.decode("iF4EABYKAAYFAlkkmD8ACgkQ4eT0x9ceFp1gNQD+LWiJFax8iQqgr0yJ1P7JFGvMwuZc8r05h6U+X+lyKYEBAK939lEX1rvBmcetftVbRlOMX5oQZwBLt/NJh+nQ3ssC");
CommitInfo commit = new CommitInfo("2c4df4a89ac5b0b8b21fd2aad4d9b19cd91e7049", "1cd97d0545a25c578e3f4da5283106606276eadf", null, "Alex Grinman <alex@krypt.co> 1495570495 -0400", "Alex Grinman <alex@krypt.co> 1495570495 -0400", "\ntest1234\n".getBytes("UTF-8"));
AsciiArmor aa = new AsciiArmor(AsciiArmor.HeaderLine.SIGNATURE, Collections.singletonList(new Pair<String, String>("Comment", "Created With Kryptonite")), sigMessage);
Assert.assertTrue(Arrays.equals(commit.commitHash(aa.toString()), Base16.decode("84e09dac58d81b1f3fc4806b1b4cb18af3cca0ea")));
}
Aggregations