Refactor relationship between SessionCipher and Message.

This commit is contained in:
Moxie Marlinspike
2013-08-19 17:31:34 -07:00
parent d1969412fb
commit 1cc2762656
14 changed files with 420 additions and 537 deletions

View File

@@ -37,6 +37,7 @@ import org.thoughtcrime.securesms.sms.SmsTransportDetails;
import org.whispersystems.textsecure.crypto.InvalidKeyException;
import org.whispersystems.textsecure.crypto.InvalidMessageException;
import org.whispersystems.textsecure.crypto.SessionCipher;
import org.whispersystems.textsecure.crypto.protocol.EncryptedMessage;
import org.whispersystems.textsecure.util.Hex;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.WorkerThread;
@@ -194,9 +195,10 @@ public class DecryptingQueue {
synchronized (SessionCipher.CIPHER_LOCK) {
Log.w("DecryptingQueue", "Decrypting: " + Hex.toString(ciphertextPduBytes));
SessionCipher cipher = new SessionCipher(context, masterSecret, recipient, new TextTransport());
EncryptedMessage message = new EncryptedMessage(context, masterSecret, new TextTransport());
try {
plaintextPduBytes = cipher.decryptMessage(ciphertextPduBytes);
plaintextPduBytes = message.decrypt(recipient, ciphertextPduBytes);
} catch (InvalidMessageException ime) {
// XXX - For some reason, Sprint seems to append a single character to the
// end of message text segments. I don't know why, so here we just try
@@ -205,7 +207,7 @@ public class DecryptingQueue {
Log.w("DecryptingQueue", "Attempting truncated decrypt...");
byte[] truncated = new byte[ciphertextPduBytes.length - 1];
System.arraycopy(ciphertextPduBytes, 0, truncated, 0, truncated.length);
plaintextPduBytes = cipher.decryptMessage(truncated);
plaintextPduBytes = message.decrypt(recipient, truncated);
} else {
throw ime;
}
@@ -273,8 +275,8 @@ public class DecryptingQueue {
return;
}
SessionCipher cipher = new SessionCipher(context, masterSecret, recipient, new SmsTransportDetails());
plaintextBody = new String(cipher.decryptMessage(body.getBytes()));
EncryptedMessage message = new EncryptedMessage(context, masterSecret, new SmsTransportDetails());
plaintextBody = new String(message.decrypt(recipient, body.getBytes()));
} catch (InvalidMessageException e) {
Log.w("DecryptionQueue", e);
database.markAsDecryptFailed(messageId);

View File

@@ -26,11 +26,11 @@ import org.whispersystems.textsecure.crypto.IdentityKey;
import org.whispersystems.textsecure.crypto.KeyUtil;
import org.whispersystems.textsecure.crypto.MasterSecret;
import org.whispersystems.textsecure.crypto.PublicKey;
import org.whispersystems.textsecure.crypto.protocol.EncryptedMessage;
import org.whispersystems.textsecure.push.PreKeyEntity;
import org.whispersystems.textsecure.storage.LocalKeyRecord;
import org.whispersystems.textsecure.storage.RemoteKeyRecord;
import org.whispersystems.textsecure.storage.SessionRecord;
import org.whispersystems.textsecure.crypto.protocol.Message;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.service.KeyCachingService;
import org.thoughtcrime.securesms.sms.MessageSender;
@@ -105,7 +105,7 @@ public class KeyExchangeProcessor {
sessionRecord.setSessionId(localKeyRecord.getCurrentKeyPair().getPublicKey().getFingerprintBytes(),
remoteKeyRecord.getCurrentRemoteKey().getFingerprintBytes());
sessionRecord.setIdentityKey(message.getIdentityKey());
sessionRecord.setSessionVersion(Message.SUPPORTED_VERSION);
sessionRecord.setSessionVersion(EncryptedMessage.SUPPORTED_VERSION);
sessionRecord.save();
DatabaseFactory.getIdentityDatabase(context)
@@ -118,7 +118,7 @@ public class KeyExchangeProcessor {
if (needsResponseFromUs()) {
localKeyRecord = KeyUtil.initializeRecordFor(recipient, context, masterSecret);
KeyExchangeMessage ourMessage = new KeyExchangeMessage(context, masterSecret, Math.min(Message.SUPPORTED_VERSION, message.getMaxVersion()), localKeyRecord, initiateKeyId);
KeyExchangeMessage ourMessage = new KeyExchangeMessage(context, masterSecret, Math.min(EncryptedMessage.SUPPORTED_VERSION, message.getMaxVersion()), localKeyRecord, initiateKeyId);
OutgoingKeyExchangeMessage textMessage = new OutgoingKeyExchangeMessage(recipient, ourMessage.serialize());
Log.w("KeyExchangeProcessor", "Responding with key exchange message fingerprint: " + ourMessage.getPublicKey().getFingerprint());
Log.w("KeyExchangeProcessor", "Which has a local key record fingerprint: " + localKeyRecord.getCurrentKeyPair().getPublicKey().getFingerprint());
@@ -132,9 +132,9 @@ public class KeyExchangeProcessor {
sessionRecord.setSessionId(localKeyRecord.getCurrentKeyPair().getPublicKey().getFingerprintBytes(),
remoteKeyRecord.getCurrentRemoteKey().getFingerprintBytes());
sessionRecord.setIdentityKey(message.getIdentityKey());
sessionRecord.setSessionVersion(Math.min(Message.SUPPORTED_VERSION, message.getMaxVersion()));
sessionRecord.setSessionVersion(Math.min(EncryptedMessage.SUPPORTED_VERSION, message.getMaxVersion()));
Log.w("KeyExchangeUtil", "Setting session version: " + Math.min(Message.SUPPORTED_VERSION, message.getMaxVersion()));
Log.w("KeyExchangeUtil", "Setting session version: " + Math.min(EncryptedMessage.SUPPORTED_VERSION, message.getMaxVersion()));
sessionRecord.save();

View File

@@ -25,8 +25,8 @@ import org.whispersystems.textsecure.crypto.IdentityKey;
import org.whispersystems.textsecure.crypto.InvalidKeyException;
import org.whispersystems.textsecure.crypto.MasterSecret;
import org.whispersystems.textsecure.crypto.PublicKey;
import org.whispersystems.textsecure.crypto.protocol.EncryptedMessage;
import org.whispersystems.textsecure.storage.LocalKeyRecord;
import org.whispersystems.textsecure.crypto.protocol.Message;
import org.whispersystems.textsecure.util.Base64;
import org.whispersystems.textsecure.util.Conversions;
@@ -67,7 +67,7 @@ public class KeyExchangeMessage {
public KeyExchangeMessage(Context context, MasterSecret masterSecret, int messageVersion, LocalKeyRecord record, int highIdBits) {
this.publicKey = new PublicKey(record.getCurrentKeyPair().getPublicKey());
this.messageVersion = messageVersion;
this.supportedVersion = Message.SUPPORTED_VERSION;
this.supportedVersion = EncryptedMessage.SUPPORTED_VERSION;
publicKey.setId(publicKey.getId() | (highIdBits << 12));
@@ -93,9 +93,9 @@ public class KeyExchangeMessage {
this.supportedVersion = Conversions.lowBitsToInt(keyBytes[0]);
this.serialized = messageBody;
if (messageVersion > Message.SUPPORTED_VERSION)
if (messageVersion > EncryptedMessage.SUPPORTED_VERSION)
throw new InvalidVersionException("Key exchange with version: " + messageVersion +
" but we only support: " + Message.SUPPORTED_VERSION);
" but we only support: " + EncryptedMessage.SUPPORTED_VERSION);
if (messageVersion >= 1)
keyBytes = Base64.decodeWithoutPadding(messageBody);

View File

@@ -1,207 +0,0 @@
/**
* Copyright (C) 2011 Whisper Systems
*
* 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.thoughtcrime.securesms.mms;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.CRC32;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
import org.whispersystems.textsecure.crypto.SessionCipher;
import org.whispersystems.textsecure.crypto.TransportDetails;
import org.whispersystems.textsecure.util.Conversions;
import android.util.Log;
public class PngTransport implements TransportDetails {
private static final int CRC_LENGTH = 4;
private static final int IHDR_WIDTH_OFFSET = 8;
private static final int IHDR_HEIGHT_OFFSET = 12;
private static final int IDAT_HEADER_LENGTH = 8;
private static final byte[] PNG_HEADER = {(byte)0x89, (byte)0x50, (byte)0x4E, (byte)0x47, (byte)0x0D, (byte)0x0A, (byte)0x1A, (byte)0x0A};
private static final byte[] IHDR_CHUNK = {(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x0D, (byte)0x49, (byte)0x48, (byte)0x44, (byte)0x52,
(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00,
(byte)0x10, (byte)0x06, (byte)0x00, (byte)0x00, (byte)0x00};
private static final byte[] IEND_CHUNK = {(byte)0x00, (byte)0x00, (byte)0x00, (byte)0x00, (byte)0x49, (byte)0x45, (byte)0x4E, (byte)0x44};
private static final byte[] IDAT_TAG = {(byte)0x49, (byte)0x44, (byte)0x41, (byte)0x54};
private static final int BYTES_PER_ROW = 640 * 8;
private static final int IDAT_LENGTH_OFFSET = 33;
private void readFully(InputStream in, byte[] buffer) throws IOException {
int totalRead = 0;
int read = 0;
while (totalRead < buffer.length) {
read = in.read(buffer, totalRead, buffer.length-totalRead);
Log.w("PngTransport", "Read: " + read);
if (read == -1)
throw new IOException("Could not fill buffer!");
totalRead+=read;
}
}
private int getImageHeight(byte[] data) {
int rows = (data.length / BYTES_PER_ROW);
assert(data.length % BYTES_PER_ROW == 0);
return rows;
}
private byte[] getIhdr(int width, int height) {
byte[] ihdr = new byte[IHDR_CHUNK.length];
System.arraycopy(IHDR_CHUNK, 0, ihdr, 0, ihdr.length);
Conversions.intToByteArray(ihdr, IHDR_WIDTH_OFFSET, width);
Conversions.intToByteArray(ihdr, IHDR_HEIGHT_OFFSET, height);
return ihdr;
}
private byte[] calculateChunkCrc(byte[] header, byte[] chunk) {
byte[] crcBytes = new byte[4];
CRC32 crc = new CRC32();
crc.update(header, 4, header.length - 4);
if (chunk != null)
crc.update(chunk, 0, chunk.length);
long crcValue = crc.getValue();
Conversions.longTo4ByteArray(crcBytes, 0, crcValue);
return crcBytes;
}
private int readIhdr(ByteArrayInputStream bais) throws IOException {
byte[] ihdr = new byte[IHDR_CHUNK.length];
bais.read(ihdr);
return Conversions.byteArrayToInt(ihdr, IHDR_HEIGHT_OFFSET);
}
private byte[] readIdatChunk(ByteArrayInputStream bais, int rows) throws IOException {
InflaterInputStream iis = new InflaterInputStream(bais);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[BYTES_PER_ROW + 1];
Log.w("PngTransport", "Total image height: " + rows);
for (int i=0;i<rows;i++) {
readFully(iis, buffer);
Log.w("PngTransport", "Read row: " + i);
baos.write(buffer, 1, buffer.length-1);
}
return baos.toByteArray();
}
private byte[] getIdatChunkHeader(byte[] chunk) {
byte[] headerBytes = new byte[8];
Conversions.intToByteArray(headerBytes, 0, chunk.length);
System.arraycopy(IDAT_TAG, 0, headerBytes, 4, IDAT_TAG.length);
return headerBytes;
}
private byte[] getIdatChunk(byte[] data) {
try {
int rows = (data.length / BYTES_PER_ROW);
assert(data.length % BYTES_PER_ROW == 0);
Log.w("PngTransport", "data % bytes_per_row: " + (data.length % BYTES_PER_ROW));
ByteArrayOutputStream baos = new ByteArrayOutputStream((rows * BYTES_PER_ROW) + rows);
DeflaterOutputStream dos = new DeflaterOutputStream(baos);
for (int i=0;i<rows;i++) {
dos.write((byte)0x00);
dos.write(data, (i*BYTES_PER_ROW), BYTES_PER_ROW);
}
dos.close();
return baos.toByteArray();
} catch (IOException ioe) {
throw new AssertionError(ioe);
}
}
public byte[] encodeMessage(byte[] data) {
try {
int height = getImageHeight(data);
byte[] idatChunk = getIdatChunk(data);
byte[] idatChunkHeader = getIdatChunkHeader(idatChunk);
byte[] ihdrChunk = getIhdr(640, height);
ByteArrayOutputStream baos = new ByteArrayOutputStream(PNG_HEADER.length + IHDR_CHUNK.length + CRC_LENGTH +
idatChunkHeader.length + idatChunk.length + CRC_LENGTH +
IEND_CHUNK.length + CRC_LENGTH);
baos.write(PNG_HEADER);
baos.write(ihdrChunk);
baos.write(calculateChunkCrc(ihdrChunk, null));
baos.write(idatChunkHeader);
baos.write(idatChunk);
baos.write(calculateChunkCrc(idatChunkHeader, idatChunk));
baos.write(IEND_CHUNK);
baos.write(calculateChunkCrc(IEND_CHUNK, null));
return baos.toByteArray();
} catch (IOException ioe) {
throw new AssertionError(ioe);
}
}
public byte[] decodeMessage(byte[] encodedMessageBytes) throws IOException {
if (encodedMessageBytes.length < IDAT_LENGTH_OFFSET + 5)
throw new IOException("Encoded bytes too short!");
ByteArrayInputStream bais = new ByteArrayInputStream(encodedMessageBytes);
bais.skip(PNG_HEADER.length);
int rows = readIhdr(bais);
bais.skip(CRC_LENGTH);
bais.skip(IDAT_HEADER_LENGTH);
return readIdatChunk(bais, rows);
}
public byte[] getPaddedMessageBody(byte[] messageBody) {
int rows = ((SessionCipher.ENCRYPTED_MESSAGE_OVERHEAD + messageBody.length) / BYTES_PER_ROW) + 1;
byte[] paddedMessage = new byte[(rows * BYTES_PER_ROW) - SessionCipher.ENCRYPTED_MESSAGE_OVERHEAD];
System.arraycopy(messageBody, 0, paddedMessage, 0, messageBody.length);
paddedMessage[messageBody.length] = (byte)0x01;
return paddedMessage;
}
public byte[] stripPaddedMessage(byte[] messageWithPadding) {
int i;
for (i=messageWithPadding.length-1;i>=0;i--) {
if (messageWithPadding[i] == (byte)0x01)
break;
else if (i == 0)
throw new AssertionError("No padding!");
}
int paddingLength = messageWithPadding.length - i;
byte[] message = new byte[messageWithPadding.length - paddingLength];
System.arraycopy(messageWithPadding, 0, message, 0, message.length);
return message;
}
}

View File

@@ -23,19 +23,23 @@ import org.whispersystems.textsecure.util.Base64;
public class TextTransport implements TransportDetails {
public byte[] decodeMessage(byte[] encodedMessageBytes) throws IOException {
@Override
public byte[] getDecodedMessage(byte[] encodedMessageBytes) throws IOException {
return Base64.decode(encodedMessageBytes);
}
public byte[] encodeMessage(byte[] messageWithMac) {
@Override
public byte[] getEncodedMessage(byte[] messageWithMac) {
return Base64.encodeBytes(messageWithMac).getBytes();
}
@Override
public byte[] getPaddedMessageBody(byte[] messageBody) {
return messageBody;
}
public byte[] stripPaddedMessage(byte[] messageWithPadding) {
@Override
public byte[] getStrippedPaddingMessageBody(byte[] messageWithPadding) {
return messageWithPadding;
}

View File

@@ -38,20 +38,20 @@ public class SmsTransportDetails implements TransportDetails {
public static final int ENCRYPTED_SINGLE_MESSAGE_BODY_MAX_SIZE = SINGLE_MESSAGE_MAX_BYTES - SessionCipher.ENCRYPTED_MESSAGE_OVERHEAD;
@Override
public byte[] encodeMessage(byte[] messageWithMac) {
public byte[] getEncodedMessage(byte[] messageWithMac) {
String encodedMessage = Base64.encodeBytesWithoutPadding(messageWithMac);
Log.w("SmsTransportDetails", "Encoded Message Length: " + encodedMessage.length());
return encodedMessage.getBytes();
}
@Override
public byte[] decodeMessage(byte[] encodedMessageBytes) throws IOException {
public byte[] getDecodedMessage(byte[] encodedMessageBytes) throws IOException {
String encodedMessage = new String(encodedMessageBytes);
return Base64.decodeWithoutPadding(encodedMessage);
}
@Override
public byte[] stripPaddedMessage(byte[] messageWithPadding) {
public byte[] getStrippedPaddingMessageBody(byte[] messageWithPadding) {
int paddingBeginsIndex = 0;
for (int i=1;i<messageWithPadding.length;i++) {

View File

@@ -1,44 +0,0 @@
package org.thoughtcrime.securesms.transport;
import org.whispersystems.textsecure.crypto.TransportDetails;
import org.whispersystems.textsecure.util.Base64;
import java.io.IOException;
public class BaseTransportDetails implements TransportDetails {
@Override
public byte[] stripPaddedMessage(byte[] messageWithPadding) {
int paddingBeginsIndex = 0;
for (int i=1;i<messageWithPadding.length;i++) {
if (messageWithPadding[i] == (byte)0x00) {
paddingBeginsIndex = i;
break;
}
}
if (paddingBeginsIndex == 0)
return messageWithPadding;
byte[] message = new byte[paddingBeginsIndex];
System.arraycopy(messageWithPadding, 0, message, 0, message.length);
return message;
}
@Override
public byte[] getPaddedMessageBody(byte[] messageBody) {
return messageBody;
}
@Override
public byte[] encodeMessage(byte[] messageWithMac) {
return Base64.encodeBytesWithoutPadding(messageWithMac).getBytes();
}
@Override
public byte[] decodeMessage(byte[] encodedMessageBytes) throws IOException {
return Base64.decodeWithoutPadding(new String(encodedMessageBytes));
}
}

View File

@@ -14,6 +14,7 @@ import org.thoughtcrime.securesms.mms.MmsSendHelper;
import org.thoughtcrime.securesms.mms.TextTransport;
import org.thoughtcrime.securesms.protocol.WirePrefix;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.whispersystems.textsecure.crypto.protocol.EncryptedMessage;
import org.whispersystems.textsecure.util.Hex;
import java.io.IOException;
@@ -133,13 +134,8 @@ public class MmsTransport {
}
private byte[] getEncryptedPdu(MasterSecret masterSecret, String recipient, byte[] pduBytes) {
synchronized (SessionCipher.CIPHER_LOCK) {
SessionCipher cipher = new SessionCipher(context, masterSecret,
new Recipient(null, recipient, null, null),
new TextTransport());
return cipher.encryptMessage(pduBytes);
}
EncryptedMessage message = new EncryptedMessage(context, masterSecret, new TextTransport());
return message.encrypt(new Recipient(null, recipient, null, null), pduBytes);
}
private boolean isInconsistentResponse(SendReq message, SendConf response) {

View File

@@ -4,6 +4,7 @@ import android.content.Context;
import android.util.Log;
import org.thoughtcrime.securesms.crypto.KeyExchangeProcessor;
import org.thoughtcrime.securesms.mms.TextTransport;
import org.thoughtcrime.securesms.recipients.Recipient;
import org.thoughtcrime.securesms.sms.SmsTransportDetails;
import org.whispersystems.textsecure.crypto.MasterSecret;
@@ -12,6 +13,7 @@ import org.thoughtcrime.securesms.mms.PartParser;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.thoughtcrime.securesms.util.Util;
import org.whispersystems.textsecure.crypto.SessionCipher;
import org.whispersystems.textsecure.crypto.protocol.EncryptedMessage;
import org.whispersystems.textsecure.push.PreKeyEntity;
import org.whispersystems.textsecure.push.PushAttachmentData;
import org.whispersystems.textsecure.push.PushServiceSocket;
@@ -106,17 +108,16 @@ public class PushTransport extends BaseTransport {
KeyExchangeProcessor processor = new KeyExchangeProcessor(context, masterSecret, recipient);
processor.processKeyExchangeMessage(preKey);
synchronized (SessionCipher.CIPHER_LOCK) {
SessionCipher sessionCipher = new SessionCipher(context, masterSecret, recipient, new SmsTransportDetails());
return sessionCipher.encryptMessage(plaintext.getBytes());
}
return plaintext.getBytes();
// synchronized (SessionCipher.CIPHER_LOCK) {
// SessionCipher sessionCipher = new SessionCipher(context, masterSecret, recipient, new SmsTransportDetails());
// return sessionCipher.encryptMessage(plaintext.getBytes());
// }
}
private byte[] getEncryptedMessageForExistingSession(Recipient recipient, String plaintext) {
synchronized (SessionCipher.CIPHER_LOCK) {
SessionCipher sessionCipher = new SessionCipher(context, masterSecret, recipient, new SmsTransportDetails());
return sessionCipher.encryptMessage(plaintext.getBytes());
}
EncryptedMessage message = new EncryptedMessage(context, masterSecret, new TextTransport());
return message.encrypt(recipient, plaintext.getBytes());
}
}

View File

@@ -15,6 +15,7 @@ import org.thoughtcrime.securesms.sms.MultipartSmsMessageHandler;
import org.thoughtcrime.securesms.sms.OutgoingTextMessage;
import org.thoughtcrime.securesms.sms.SmsTransportDetails;
import org.thoughtcrime.securesms.util.TextSecurePreferences;
import org.whispersystems.textsecure.crypto.protocol.EncryptedMessage;
import java.util.ArrayList;
@@ -138,9 +139,7 @@ public class SmsTransport extends BaseTransport {
}
private String getAsymmetricEncrypt(MasterSecret masterSecret, String body, Recipient recipient) {
synchronized (SessionCipher.CIPHER_LOCK) {
SessionCipher cipher = new SessionCipher(context, masterSecret, recipient, new SmsTransportDetails());
return new String(cipher.encryptMessage(body.getBytes()));
}
EncryptedMessage message = new EncryptedMessage(context, masterSecret, new SmsTransportDetails());
return new String(message.encrypt(recipient, body.getBytes()));
}
}