basic pgp encrypted file transfer

This commit is contained in:
Daniel Gultsch 2014-05-06 21:34:30 +02:00
parent f7033cb7e0
commit 461f2ffb16
7 changed files with 259 additions and 98 deletions

View file

@ -2,6 +2,10 @@ package eu.siacs.conversations.crypto;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@ -11,25 +15,31 @@ import org.openintents.openpgp.util.OpenPgpApi;
import org.openintents.openpgp.util.OpenPgpApi.IOpenPgpCallback;
import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Contact;
import eu.siacs.conversations.entities.Message;
import eu.siacs.conversations.services.XmppConnectionService;
import eu.siacs.conversations.xmpp.jingle.JingleFile;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.util.Log;
public class PgpEngine {
private OpenPgpApi api;
private XmppConnectionService mXmppConnectionService;
public PgpEngine(OpenPgpApi api) {
public PgpEngine(OpenPgpApi api, XmppConnectionService service) {
this.api = api;
this.mXmppConnectionService = service;
}
public void decrypt(final Message message, final OnPgpEngineResult callback) {
Log.d("xmppService","decrypting message "+message.getUuid());
Intent params = new Intent();
params.setAction(OpenPgpApi.ACTION_DECRYPT_VERIFY);
params.putExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME, message
.getConversation().getAccount().getJid());
if (message.getType() == Message.TYPE_TEXT) {
InputStream is = new ByteArrayInputStream(message.getBody().getBytes());
final OutputStream os = new ByteArrayOutputStream();
api.executeApiAsync(params, is, os, new IOpenPgpCallback() {
@ -56,30 +66,29 @@ public class PgpEngine {
}
}
});
}
} else if (message.getType() == Message.TYPE_IMAGE) {
try {
final JingleFile inputFile = this.mXmppConnectionService.getFileBackend().getJingleFile(message, false);
final JingleFile outputFile = this.mXmppConnectionService.getFileBackend().getJingleFile(message,true);
outputFile.createNewFile();
InputStream is = new FileInputStream(inputFile);
OutputStream os = new FileOutputStream(outputFile);
api.executeApiAsync(params, is, os, new IOpenPgpCallback() {
public void encrypt(Account account, long keyId, Message message,
final OnPgpEngineResult callback) {
Log.d("xmppService", "called to pgpengine::encrypt");
long[] keys = { keyId };
Intent params = new Intent();
params.setAction(OpenPgpApi.ACTION_ENCRYPT);
params.putExtra(OpenPgpApi.EXTRA_KEY_IDS, keys);
params.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true);
params.putExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME, account.getJid());
InputStream is = new ByteArrayInputStream(message.getBody().getBytes());
ByteArrayOutputStream os = new ByteArrayOutputStream();
Intent result = api.executeApi(params, is, os);
@Override
public void onReturn(Intent result) {
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE,
OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS:
StringBuilder encryptedMessageBody = new StringBuilder();
String[] lines = os.toString().split("\n");
for (int i = 3; i < lines.length - 1; ++i) {
encryptedMessageBody.append(lines[i].trim());
}
message.setEncryptedBody(encryptedMessageBody.toString());
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(outputFile.getAbsolutePath(),options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
message.setBody(""+outputFile.getSize()+","+imageWidth+","+imageHeight);
message.setEncryption(Message.ENCRYPTION_DECRYPTED);
PgpEngine.this.mXmppConnectionService.updateMessage(message);
PgpEngine.this.mXmppConnectionService.updateUi(message.getConversation(), false);
callback.success();
return;
case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
@ -90,6 +99,97 @@ public class PgpEngine {
callback.error((OpenPgpError) result
.getParcelableExtra(OpenPgpApi.RESULT_ERROR));
return;
default:
return;
}
}
});
} catch (FileNotFoundException e) {
callback.error(new OpenPgpError(0, "file not found: "+e.getMessage()));
} catch (IOException e) {
callback.error(new OpenPgpError(0, "io exception: "+e.getMessage()));
}
}
}
public void encrypt(Account account, final Message message,
final OnPgpEngineResult callback) {
long[] keys = { message.getConversation().getContact().getPgpKeyId() };
Intent params = new Intent();
params.setAction(OpenPgpApi.ACTION_ENCRYPT);
params.putExtra(OpenPgpApi.EXTRA_KEY_IDS, keys);
params.putExtra(OpenPgpApi.EXTRA_REQUEST_ASCII_ARMOR, true);
params.putExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME, account.getJid());
InputStream is = new ByteArrayInputStream(message.getBody().getBytes());
final OutputStream os = new ByteArrayOutputStream();
api.executeApiAsync(params, is, os, new IOpenPgpCallback() {
@Override
public void onReturn(Intent result) {
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE,
OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS:
StringBuilder encryptedMessageBody = new StringBuilder();
String[] lines = os.toString().split("\n");
for (int i = 3; i < lines.length - 1; ++i) {
encryptedMessageBody.append(lines[i].trim());
}
message.setEncryptedBody(encryptedMessageBody.toString());
callback.success();
break;
case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
callback.userInputRequried((PendingIntent) result
.getParcelableExtra(OpenPgpApi.RESULT_INTENT));
break;
case OpenPgpApi.RESULT_CODE_ERROR:
callback.error((OpenPgpError) result
.getParcelableExtra(OpenPgpApi.RESULT_ERROR));
break;
}
}
});
}
public void encrypt(final Message message, final OnPgpEngineResult callback) {
try {
Log.d("xmppService","calling to encrypt file");
JingleFile inputFile = this.mXmppConnectionService.getFileBackend().getJingleFile(message, true);
JingleFile outputFile = this.mXmppConnectionService.getFileBackend().getJingleFile(message, false);
outputFile.createNewFile();
long[] keys = { message.getConversation().getContact().getPgpKeyId() };
Intent params = new Intent();
params.setAction(OpenPgpApi.ACTION_ENCRYPT);
params.putExtra(OpenPgpApi.EXTRA_KEY_IDS, keys);
params.putExtra(OpenPgpApi.EXTRA_ACCOUNT_NAME, message.getConversation().getAccount().getJid());
InputStream is = new FileInputStream(inputFile);
OutputStream os = new FileOutputStream(outputFile);
api.executeApiAsync(params, is, os, new IOpenPgpCallback() {
@Override
public void onReturn(Intent result) {
switch (result.getIntExtra(OpenPgpApi.RESULT_CODE,
OpenPgpApi.RESULT_CODE_ERROR)) {
case OpenPgpApi.RESULT_CODE_SUCCESS:
callback.success();
break;
case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
callback.userInputRequried((PendingIntent) result
.getParcelableExtra(OpenPgpApi.RESULT_INTENT));
break;
case OpenPgpApi.RESULT_CODE_ERROR:
callback.error((OpenPgpError) result
.getParcelableExtra(OpenPgpApi.RESULT_ERROR));
break;
}
}
});
} catch (FileNotFoundException e) {
Log.d("xmppService","file not found: "+e.getMessage());
} catch (IOException e) {
Log.d("xmppService","io exception during file encrypt");
}
}
@ -130,10 +230,8 @@ public class PgpEngine {
return 0;
}
case OpenPgpApi.RESULT_CODE_USER_INTERACTION_REQUIRED:
Log.d("xmppService","user interaction required");
return 0;
case OpenPgpApi.RESULT_CODE_ERROR:
Log.d("xmppService","pgp error");
return 0;
}
return 0;

View file

@ -49,11 +49,20 @@ public class FileBackend {
}
public JingleFile getJingleFile(Message message) {
return getJingleFile(message, true);
}
public JingleFile getJingleFile(Message message, boolean decrypted) {
Conversation conversation = message.getConversation();
String prefix = context.getFilesDir().getAbsolutePath();
String path = prefix + "/" + conversation.getAccount().getJid() + "/"
+ conversation.getContactJid();
String filename = message.getUuid() + ".webp";
String filename;
if ((decrypted)||(message.getEncryption() == Message.ENCRYPTION_NONE)) {
filename = message.getUuid() + ".webp";
} else {
filename = message.getUuid() + ".webp.pgp";
}
return new JingleFile(path + "/" + filename);
}

View file

@ -47,6 +47,7 @@ import eu.siacs.conversations.xmpp.OnStatusChanged;
import eu.siacs.conversations.xmpp.OnTLSExceptionReceived;
import eu.siacs.conversations.xmpp.XmppConnection;
import eu.siacs.conversations.xmpp.jingle.JingleConnectionManager;
import eu.siacs.conversations.xmpp.jingle.JingleFile;
import eu.siacs.conversations.xmpp.jingle.OnJinglePacketReceived;
import eu.siacs.conversations.xmpp.jingle.stanzas.JinglePacket;
import eu.siacs.conversations.xmpp.stanzas.IqPacket;
@ -92,7 +93,7 @@ public class XmppConnectionService extends Service {
private JingleConnectionManager mJingleConnectionManager = new JingleConnectionManager(
this);
public OnConversationListChangedListener convChangedListener = null;
private OnConversationListChangedListener convChangedListener = null;
private int convChangedListenerCount = 0;
private OnAccountListChangedListener accountChangedListener = null;
private OnTLSExceptionReceived tlsException = null;
@ -432,7 +433,7 @@ public class XmppConnectionService extends Service {
if (this.mPgpEngine == null) {
this.mPgpEngine = new PgpEngine(new OpenPgpApi(
getApplicationContext(),
pgpServiceConnection.getService()));
pgpServiceConnection.getService()),this);
}
return mPgpEngine;
} else {
@ -445,14 +446,9 @@ public class XmppConnectionService extends Service {
return this.fileBackend;
}
public void attachImageToConversation(final Conversation conversation,
public Message attachImageToConversation(final Conversation conversation,
final String presence, final Uri uri) {
new Thread(new Runnable() {
@Override
public void run() {
Message message = new Message(conversation, "",
Message.ENCRYPTION_NONE);
final Message message = new Message(conversation, "",Message.ENCRYPTION_NONE);
message.setPresence(presence);
message.setType(Message.TYPE_IMAGE);
message.setStatus(Message.STATUS_PREPARING);
@ -460,6 +456,10 @@ public class XmppConnectionService extends Service {
if (convChangedListener != null) {
convChangedListener.onConversationListChanged();
}
new Thread(new Runnable() {
@Override
public void run() {
getFileBackend().copyImageToPrivateStorage(message, uri);
message.setStatus(Message.STATUS_OFFERED);
databaseBackend.createMessage(message);
@ -469,6 +469,25 @@ public class XmppConnectionService extends Service {
sendMessage(message, null);
}
}).start();
return message;
}
public Message attachEncryptedImageToConversation(final Conversation conversation, final String presence, final Uri uri, final OnPgpEngineResult callback) {
Log.d(LOGTAG,"attach encrypted image");
final Message message = new Message(conversation, "",Message.ENCRYPTION_DECRYPTED);
message.setPresence(presence);
message.setType(Message.TYPE_IMAGE);
message.setStatus(Message.STATUS_PREPARING);
new Thread(new Runnable() {
@Override
public void run() {
getFileBackend().copyImageToPrivateStorage(message, uri);
getPgpEngine().encrypt(message, callback);
message.setStatus(Message.STATUS_OFFERED);
}
}).start();
return message;
}
protected Conversation findMuc(String name, Account account) {
@ -754,8 +773,6 @@ public class XmppConnectionService extends Service {
addToConversation = true;
} else if (message.getEncryption() == Message.ENCRYPTION_PGP) {
message.getConversation().endOtrIfNeeded();
long keyId = message.getConversation().getContact()
.getPgpKeyId();
packet = new MessagePacket();
packet.setType(MessagePacket.TYPE_CHAT);
packet.setFrom(message.getConversation().getAccount()
@ -1409,12 +1426,6 @@ public class XmppConnectionService extends Service {
}).start();
}
public void updateConversationInGui() {
if (convChangedListener != null) {
convChangedListener.onConversationListChanged();
}
}
public void sendConversationSubject(Conversation conversation,
String subject) {
MessagePacket packet = new MessagePacket();
@ -1480,4 +1491,12 @@ public class XmppConnectionService extends Service {
return PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
}
public void updateUi(Conversation conversation, boolean notify) {
if (convChangedListener != null) {
convChangedListener.onConversationListChanged();
} else {
UIHelper.updateNotification(getApplicationContext(), getConversations(), conversation, notify);
}
}
}

View file

@ -6,7 +6,10 @@ import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import org.openintents.openpgp.OpenPgpError;
import eu.siacs.conversations.R;
import eu.siacs.conversations.crypto.OnPgpEngineResult;
import eu.siacs.conversations.entities.Account;
import eu.siacs.conversations.entities.Contact;
import eu.siacs.conversations.entities.Conversation;
@ -18,9 +21,11 @@ import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.IntentSender.SendIntentException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
@ -59,6 +64,7 @@ public class ConversationActivity extends XmppActivity {
public static final int REQUEST_SEND_MESSAGE = 0x75441;
public static final int REQUEST_DECRYPT_PGP = 0x76783;
private static final int ATTACH_FILE = 0x48502;
private static final int REQUEST_SEND_PGP_IMAGE = 0x53883;
protected SlidingPaneLayout spl;
@ -70,6 +76,8 @@ public class ConversationActivity extends XmppActivity {
private boolean useSubject = true;
private ArrayAdapter<Conversation> listAdapter;
public Message pendingMessage = null;
private OnConversationListChangedListener onConvChanged = new OnConversationListChangedListener() {
@Override
@ -581,10 +589,42 @@ public class ConversationActivity extends XmppActivity {
selectedFragment.hidePgpPassphraseBox();
}
} else if (requestCode == ATTACH_FILE) {
Conversation conversation = getSelectedConversation();
final Conversation conversation = getSelectedConversation();
String presence = conversation.getNextPresence();
if (conversation.nextMessageEncryption == Message.ENCRYPTION_NONE) {
xmppConnectionService.attachImageToConversation(conversation, presence, data.getData());
} else if (conversation.nextMessageEncryption == Message.ENCRYPTION_PGP) {
pendingMessage = xmppConnectionService.attachEncryptedImageToConversation(conversation, presence, data.getData(), new OnPgpEngineResult() {
@Override
public void userInputRequried(PendingIntent pi) {
Log.d(LOGTAG,"user input requried");
try {
startIntentSenderForResult(pi.getIntentSender(),
ConversationActivity.REQUEST_SEND_PGP_IMAGE, null, 0,
0, 0);
} catch (SendIntentException e1) {
Log.d("xmppService","failed to start intent to send message");
}
}
@Override
public void success() {
conversation.getMessages().add(pendingMessage);
pendingMessage.setStatus(Message.STATUS_OFFERED);
xmppConnectionService.databaseBackend.createMessage(pendingMessage);
xmppConnectionService.sendMessage(pendingMessage, null);
xmppConnectionService.updateUi(conversation, false);
}
@Override
public void error(OpenPgpError openPgpError) {
Log.d(LOGTAG,"pgp error"+openPgpError.getMessage());
}
});
} else {
Log.d(LOGTAG,"unknown next message encryption: "+conversation.nextMessageEncryption);
}
}
}
}

View file

@ -269,7 +269,7 @@ public class ConversationFragment extends Fragment {
String filesize = "";
if (item.getType() == Message.TYPE_IMAGE) {
if ((item.getType() == Message.TYPE_IMAGE)&&((item.getEncryption() == Message.ENCRYPTION_DECRYPTED)||(item.getEncryption() == Message.ENCRYPTION_NONE))) {
String[] fileParams = item.getBody().split(",");
if ((fileParams.length>=1)&&(item.getStatus() != Message.STATUS_PREPARING)) {
long size = Long.parseLong(fileParams[0]);
@ -510,7 +510,7 @@ public class ConversationFragment extends Fragment {
ConversationActivity activity = (ConversationActivity) getActivity();
if (this.conversation != null) {
for (Message message : this.conversation.getMessages()) {
if (message.getEncryption() == Message.ENCRYPTION_PGP) {
if ((message.getEncryption() == Message.ENCRYPTION_PGP)&&(message.getStatus() == Message.STATUS_RECIEVED)) {
decryptMessage(message);
break;
}
@ -594,7 +594,7 @@ public class ConversationFragment extends Fragment {
}
protected void sendPgpMessage(final Message message) {
ConversationActivity activity = (ConversationActivity) getActivity();
final ConversationActivity activity = (ConversationActivity) getActivity();
final XmppConnectionService xmppService = activity.xmppConnectionService;
final Contact contact = message.getConversation().getContact();
final Account account = message.getConversation().getAccount();
@ -604,7 +604,6 @@ public class ConversationFragment extends Fragment {
@Override
public void userInputRequried(PendingIntent pi) {
Log.d("xmppService","hasKey returned user input required");
try {
getActivity().startIntentSenderForResult(pi.getIntentSender(),
ConversationActivity.REQUEST_SEND_MESSAGE, null, 0,
@ -616,13 +615,12 @@ public class ConversationFragment extends Fragment {
@Override
public void success() {
Log.d("xmppService","hasKey returned success");
xmppService.getPgpEngine().encrypt(account, contact.getPgpKeyId(), message,new OnPgpEngineResult() {
xmppService.getPgpEngine().encrypt(account, message,new OnPgpEngineResult() {
@Override
public void userInputRequried(PendingIntent pi) {
try {
getActivity().startIntentSenderForResult(pi.getIntentSender(),
activity.startIntentSenderForResult(pi.getIntentSender(),
ConversationActivity.REQUEST_SEND_MESSAGE, null, 0,
0, 0);
} catch (SendIntentException e1) {

View file

@ -77,9 +77,7 @@ public class MessageParser {
.sendMessagePacket(outPacket);
}
}
if (service.convChangedListener!=null) {
service.convChangedListener.onConversationListChanged();
}
service.updateUi(conversation, false);
} else if ((before != after) && (after == SessionStatus.FINISHED)) {
conversation.resetOtrSession();
Log.d(LOGTAG,"otr session stoped");
@ -101,7 +99,7 @@ public class MessageParser {
Conversation conversation = service.findOrCreateConversation(account, fromParts[0],true);
if (packet.hasChild("subject")) {
conversation.getMucOptions().setSubject(packet.findChild("subject").getContent());
service.updateConversationInGui();
service.updateUi(conversation, false);
return null;
}
if ((fromParts.length == 1)) {
@ -118,7 +116,6 @@ public class MessageParser {
public static Message parseCarbonMessage(MessagePacket packet,
Account account, XmppConnectionService service) {
// TODO Auto-generated method stub
int status;
String fullJid;
Element forwarded;

View file

@ -81,6 +81,7 @@ public class JingleConnection {
sendSuccess();
if (acceptedAutomatically) {
message.markUnread();
JingleConnection.this.mXmppConnectionService.updateUi(message.getConversation(), true);
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
@ -91,7 +92,7 @@ public class JingleConnection {
mXmppConnectionService.databaseBackend.createMessage(message);
mXmppConnectionService.markMessage(message, Message.STATUS_RECIEVED);
}
Log.d("xmppService","sucessfully transmitted file. sha1:"+file.getSha1Sum()+" "+message.getBody());
Log.d("xmppService","sucessfully transmitted file:"+file.getName()+" encryption:"+message.getEncryption());
}
};
@ -226,7 +227,6 @@ public class JingleConnection {
this.mergeCandidates(JingleCandidate.parse(content.socks5transport().getChildren()));
this.fileOffer = packet.getJingleContent().getFileOffer();
if (fileOffer!=null) {
this.file = this.mXmppConnectionService.getFileBackend().getJingleFile(message);
Element fileSize = fileOffer.findChild("size");
Element fileNameElement = fileOffer.findChild("name");
if (fileNameElement!=null) {
@ -243,20 +243,20 @@ public class JingleConnection {
}
}
if (supportedFile) {
this.file.setExpectedSize(Long.parseLong(fileSize.getContent()));
message.setBody(""+this.file.getExpectedSize());
long size = Long.parseLong(fileSize.getContent());
message.setBody(""+size);
conversation.getMessages().add(message);
if (this.file.getExpectedSize()<=this.mJingleConnectionManager.getAutoAcceptFileSize()) {
if (size<=this.mJingleConnectionManager.getAutoAcceptFileSize()) {
Log.d("xmppService","auto accepting file from "+packet.getFrom());
this.acceptedAutomatically = true;
this.sendAccept();
} else {
message.markUnread();
Log.d("xmppService","not auto accepting new file offer with size: "+this.file.getExpectedSize()+" allowed size:"+this.mJingleConnectionManager.getAutoAcceptFileSize());
if (this.mXmppConnectionService.convChangedListener!=null) {
this.mXmppConnectionService.convChangedListener.onConversationListChanged();
}
Log.d("xmppService","not auto accepting new file offer with size: "+size+" allowed size:"+this.mJingleConnectionManager.getAutoAcceptFileSize());
this.mXmppConnectionService.updateUi(conversation, true);
}
this.file = this.mXmppConnectionService.getFileBackend().getJingleFile(message,false);
this.file.setExpectedSize(size);
} else {
this.sendCancel();
}
@ -273,7 +273,7 @@ public class JingleConnection {
Content content = new Content(this.contentCreator,this.contentName);
if (message.getType() == Message.TYPE_IMAGE) {
content.setTransportId(this.transportId);
this.file = this.mXmppConnectionService.getFileBackend().getJingleFile(message);
this.file = this.mXmppConnectionService.getFileBackend().getJingleFile(message,false);
content.setFileOffer(this.file);
this.transportId = this.mJingleConnectionManager.nextRandomId();
content.setTransportId(this.transportId);