Compare commits

..

No commits in common. "0ffc0b067a8996a0e3f35c3ef567ef75b7ce940e" and "04bb70d6572a1ae98e351e09fe5e53a18ea51ead" have entirely different histories.

36 changed files with 1173 additions and 964 deletions

View File

@ -8,45 +8,28 @@ void main() async {
const aliceJid = 'alice@some.server'; const aliceJid = 'alice@some.server';
const bobJid = 'bob@other.serve'; const bobJid = 'bob@other.serve';
// You are Alice and want to begin using OMEMO, so you first create an OmemoManager. // You are Alice and want to begin using OMEMO, so you first create a SessionManager
final aliceManager = OmemoManager( final aliceSession = await OmemoSessionManager.generateNewIdentity(
// Generate Alice's OMEMO device bundle. We can specify how many One-time Prekeys we want, but // The bare Jid of Alice as a String
// per default, omemo_dart generates 100 (recommended by XEP-0384). aliceJid,
await OmemoDevice.generateNewDevice(aliceJid),
// The trust manager we want to use. In this case, we use the provided one that // The trust manager we want to use. In this case, we use the provided one that
// implements "Blind Trust Before Verification". To make things simpler, we keep // implements "Blind Trust Before Verification". To make things simpler, we keep
// no persistent data and can thus use the MemoryBTBVTrustManager. If we wanted to keep // no persistent data and can thus use the MemoryBTBVTrustManager. If we wanted to keep
// the state, we would have to override BlindTrustBeforeVerificationTrustManager. // the state, we would have to override BlindTrustBeforeVerificationTrustManager.
MemoryBTBVTrustManager(), MemoryBTBVTrustManager(),
// This function is called whenever we need to send an OMEMO heartbeat to [recipient]. // Here we specify how many Onetime Prekeys we want to have. XEP-0384 recommends around
// [result] is the encryted data to include. This needs to be wired into your XMPP library's // 100 OPKs, so let's generate 100. The parameter defaults to 100.
// OMEMO implementation. //opkAmount: 100,
// For simplicity, we use an empty function and imagine it works.
(result, recipient) async => {},
// This function is called whenever we need to fetch the device list for [jid].
// This needs to be wired into your XMPP library's OMEMO implementation.
// For simplicity, we use an empty function and imagine it works.
(jid) async => [],
// This function is called whenever we need to fetch the device bundle with id [id] from [jid].
// This needs to be wired into your XMPP library's OMEMO implementation.
// For simplicity, we use an empty function and imagine it works.
(jid, id) async => null,
// This function is called whenever we need to subscribe to [jid]'s device list PubSub node.
// This needs to be wired into your XMPP library's OMEMO implementation.
// For simplicity, we use an empty function and imagine it works.
(jid) async {},
); );
// Alice now wants to chat with Bob at his bare Jid "bob@other.server". To make things // Alice now wants to chat with Bob at his bare Jid "bob@other.server". To make things
// simple, we just generate the identity bundle ourselves. In the real world, we would // simple, we just generate the identity bundle ourselves. In the real world, we would
// request it using PEP and then convert the device bundle into a OmemoBundle object. // request it using PEP and then convert the device bundle into a OmemoBundle object.
final bobManager = OmemoManager( final bobSession = await OmemoSessionManager.generateNewIdentity(
await OmemoDevice.generateNewDevice(bobJid), bobJid,
MemoryBTBVTrustManager(), MemoryBTBVTrustManager(),
(result, recipient) async => {}, // Just for illustrative purposes
(jid) async => [], opkAmount: 1,
(jid, id) async => null,
(jid) async {},
); );
// Alice prepares to send the message to Bob, so she builds the message stanza and // Alice prepares to send the message to Bob, so she builds the message stanza and
@ -70,21 +53,22 @@ void main() async {
<time stamp='1969-07-20T21:56:15-05:00' /> <time stamp='1969-07-20T21:56:15-05:00' />
</envelope> </envelope>
'''; ''';
// Since Alice has no open session with Bob, we need to tell the session manager to build // Since Alice has no open session with Bob, we need to tell the session manager to build
// it when sending the message. // it when sending the message.
final message = await aliceSession.onOutgoingStanza( final message = await aliceSession.encryptToJid(
OmemoOutgoingStanza( // The bare receiver Jid
// The bare receiver Jid bobJid,
[bobJid], // The envelope we want to encrypt
envelope,
// The payload we want to encrypt, i.e. the envelope. // Since this is the first time Alice contacts Bob from this device, we need to create
envelope, // a new session. Let's also assume that Bob only has one device. We may, however,
), // add more bundles to newSessions, if we know of more.
newSessions: [
await bobSession.getDeviceBundle(),
],
); );
// In a proper implementation, we should also do some error checking here.
// Alice now builds the actual message stanza for Bob // Alice now builds the actual message stanza for Bob
final payload = base64.encode(message.ciphertext!); final payload = base64.encode(message.ciphertext!);
final aliceDevice = await aliceSession.getDevice(); final aliceDevice = await aliceSession.getDevice();
@ -126,29 +110,20 @@ void main() async {
// Bob extracts the payload and attempts to decrypt it. // Bob extracts the payload and attempts to decrypt it.
// ignore: unused_local_variable // ignore: unused_local_variable
final bobMessage = await bobManager.onIncomingStanza( final bobMessage = await bobSession.decryptMessage(
OmemoIncomingStanza( // base64 decode the payload
// The bare sender JID of the message. In this case, it's Alice's. base64.decode(payload),
aliceJid, // Specify the Jid of the sender
aliceJid,
// The 'sid' attribute of the <header /> element. Here, we know that Alice only has one device. // Specify the device identifier of the sender (the "sid" attribute of <header />)
aliceDevice.id, aliceDevice.id,
// The deserialised keys
// Time the message was sent. Since the message was not delayed, we use the keys,
// current time. // Since the message was not delayed, we use the current time
DateTime.now().millisecondsSinceEpoch, DateTime.now().millisecondsSinceEpoch,
/// The decoded <key /> elements. from the header. Note that we only include the ones
/// relevant for Bob, so all children of <keys jid='$bobJid' />.
keys,
/// The text of the <payload /> element, if it exists. If not, then the message might be
/// a hearbeat, where no payload is sent. In that case, use null.
payload,
),
); );
// All Bob has to do now is replace the OMEMO wrapper element // All Bob has to do now is replace the OMEMO wrapper element
// <encrypted xmlns='urn:xmpp:omemo:2' />) with the content of the <content /> element // <encrypted xmlns='urn:xmpp:omemo:2' />) with the content of the <content /> element
// of the envelope we just decrypted. // of the envelope we just decrypted.

View File

@ -12,6 +12,7 @@ export 'src/omemo/events.dart';
export 'src/omemo/fingerprint.dart'; export 'src/omemo/fingerprint.dart';
export 'src/omemo/omemomanager.dart'; export 'src/omemo/omemomanager.dart';
export 'src/omemo/ratchet_map_key.dart'; export 'src/omemo/ratchet_map_key.dart';
export 'src/omemo/sessionmanager.dart';
export 'src/omemo/stanza.dart'; export 'src/omemo/stanza.dart';
export 'src/trust/base.dart'; export 'src/trust/base.dart';
export 'src/trust/btbv.dart'; export 'src/trust/btbv.dart';

View File

@ -10,35 +10,12 @@ import 'dart:core' as $core;
import 'package:protobuf/protobuf.dart' as $pb; import 'package:protobuf/protobuf.dart' as $pb;
class OMEMOMessage extends $pb.GeneratedMessage { class OMEMOMessage extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo( static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'OMEMOMessage', createEmptyInstance: create)
const $core.bool.fromEnvironment('protobuf.omit_message_names') ..a<$core.int>(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'n', $pb.PbFieldType.QU3)
? '' ..a<$core.int>(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'pn', $pb.PbFieldType.QU3)
: 'OMEMOMessage', ..a<$core.List<$core.int>>(3, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'dhPub', $pb.PbFieldType.QY)
createEmptyInstance: create) ..a<$core.List<$core.int>>(4, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'ciphertext', $pb.PbFieldType.OY)
..a<$core.int>( ;
1,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'n',
$pb.PbFieldType.QU3)
..a<$core.int>(
2,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'pn',
$pb.PbFieldType.QU3)
..a<$core.List<$core.int>>(
3,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'dhPub',
$pb.PbFieldType.QY)
..a<$core.List<$core.int>>(
4,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'ciphertext',
$pb.PbFieldType.OY);
OMEMOMessage._() : super(); OMEMOMessage._() : super();
factory OMEMOMessage({ factory OMEMOMessage({
@ -62,40 +39,31 @@ class OMEMOMessage extends $pb.GeneratedMessage {
} }
return _result; return _result;
} }
factory OMEMOMessage.fromBuffer($core.List<$core.int> i, factory OMEMOMessage.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r);
[$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => factory OMEMOMessage.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r);
create()..mergeFromBuffer(i, r); @$core.Deprecated(
factory OMEMOMessage.fromJson($core.String i, 'Using this can add significant overhead to your binary. '
[$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
create()..mergeFromJson(i, r); 'Will be removed in next major version')
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
'Will be removed in next major version')
OMEMOMessage clone() => OMEMOMessage()..mergeFromMessage(this); OMEMOMessage clone() => OMEMOMessage()..mergeFromMessage(this);
@$core.Deprecated('Using this can add significant overhead to your binary. ' @$core.Deprecated(
'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' 'Using this can add significant overhead to your binary. '
'Will be removed in next major version') 'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
OMEMOMessage copyWith(void Function(OMEMOMessage) updates) => 'Will be removed in next major version')
super.copyWith((message) => updates(message as OMEMOMessage)) OMEMOMessage copyWith(void Function(OMEMOMessage) updates) => super.copyWith((message) => updates(message as OMEMOMessage)) as OMEMOMessage; // ignore: deprecated_member_use
as OMEMOMessage; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i; $pb.BuilderInfo get info_ => _i;
@$core.pragma('dart2js:noInline') @$core.pragma('dart2js:noInline')
static OMEMOMessage create() => OMEMOMessage._(); static OMEMOMessage create() => OMEMOMessage._();
OMEMOMessage createEmptyInstance() => create(); OMEMOMessage createEmptyInstance() => create();
static $pb.PbList<OMEMOMessage> createRepeated() => static $pb.PbList<OMEMOMessage> createRepeated() => $pb.PbList<OMEMOMessage>();
$pb.PbList<OMEMOMessage>();
@$core.pragma('dart2js:noInline') @$core.pragma('dart2js:noInline')
static OMEMOMessage getDefault() => _defaultInstance ??= static OMEMOMessage getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<OMEMOMessage>(create);
$pb.GeneratedMessage.$_defaultFor<OMEMOMessage>(create);
static OMEMOMessage? _defaultInstance; static OMEMOMessage? _defaultInstance;
@$pb.TagNumber(1) @$pb.TagNumber(1)
$core.int get n => $_getIZ(0); $core.int get n => $_getIZ(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
set n($core.int v) { set n($core.int v) { $_setUnsignedInt32(0, v); }
$_setUnsignedInt32(0, v);
}
@$pb.TagNumber(1) @$pb.TagNumber(1)
$core.bool hasN() => $_has(0); $core.bool hasN() => $_has(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
@ -104,10 +72,7 @@ class OMEMOMessage extends $pb.GeneratedMessage {
@$pb.TagNumber(2) @$pb.TagNumber(2)
$core.int get pn => $_getIZ(1); $core.int get pn => $_getIZ(1);
@$pb.TagNumber(2) @$pb.TagNumber(2)
set pn($core.int v) { set pn($core.int v) { $_setUnsignedInt32(1, v); }
$_setUnsignedInt32(1, v);
}
@$pb.TagNumber(2) @$pb.TagNumber(2)
$core.bool hasPn() => $_has(1); $core.bool hasPn() => $_has(1);
@$pb.TagNumber(2) @$pb.TagNumber(2)
@ -116,10 +81,7 @@ class OMEMOMessage extends $pb.GeneratedMessage {
@$pb.TagNumber(3) @$pb.TagNumber(3)
$core.List<$core.int> get dhPub => $_getN(2); $core.List<$core.int> get dhPub => $_getN(2);
@$pb.TagNumber(3) @$pb.TagNumber(3)
set dhPub($core.List<$core.int> v) { set dhPub($core.List<$core.int> v) { $_setBytes(2, v); }
$_setBytes(2, v);
}
@$pb.TagNumber(3) @$pb.TagNumber(3)
$core.bool hasDhPub() => $_has(2); $core.bool hasDhPub() => $_has(2);
@$pb.TagNumber(3) @$pb.TagNumber(3)
@ -128,10 +90,7 @@ class OMEMOMessage extends $pb.GeneratedMessage {
@$pb.TagNumber(4) @$pb.TagNumber(4)
$core.List<$core.int> get ciphertext => $_getN(3); $core.List<$core.int> get ciphertext => $_getN(3);
@$pb.TagNumber(4) @$pb.TagNumber(4)
set ciphertext($core.List<$core.int> v) { set ciphertext($core.List<$core.int> v) { $_setBytes(3, v); }
$_setBytes(3, v);
}
@$pb.TagNumber(4) @$pb.TagNumber(4)
$core.bool hasCiphertext() => $_has(3); $core.bool hasCiphertext() => $_has(3);
@$pb.TagNumber(4) @$pb.TagNumber(4)
@ -139,23 +98,10 @@ class OMEMOMessage extends $pb.GeneratedMessage {
} }
class OMEMOAuthenticatedMessage extends $pb.GeneratedMessage { class OMEMOAuthenticatedMessage extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo( static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'OMEMOAuthenticatedMessage', createEmptyInstance: create)
const $core.bool.fromEnvironment('protobuf.omit_message_names') ..a<$core.List<$core.int>>(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'mac', $pb.PbFieldType.QY)
? '' ..a<$core.List<$core.int>>(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'message', $pb.PbFieldType.QY)
: 'OMEMOAuthenticatedMessage', ;
createEmptyInstance: create)
..a<$core.List<$core.int>>(
1,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'mac',
$pb.PbFieldType.QY)
..a<$core.List<$core.int>>(
2,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'message',
$pb.PbFieldType.QY);
OMEMOAuthenticatedMessage._() : super(); OMEMOAuthenticatedMessage._() : super();
factory OMEMOAuthenticatedMessage({ factory OMEMOAuthenticatedMessage({
@ -171,42 +117,31 @@ class OMEMOAuthenticatedMessage extends $pb.GeneratedMessage {
} }
return _result; return _result;
} }
factory OMEMOAuthenticatedMessage.fromBuffer($core.List<$core.int> i, factory OMEMOAuthenticatedMessage.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r);
[$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => factory OMEMOAuthenticatedMessage.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r);
create()..mergeFromBuffer(i, r); @$core.Deprecated(
factory OMEMOAuthenticatedMessage.fromJson($core.String i, 'Using this can add significant overhead to your binary. '
[$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
create()..mergeFromJson(i, r); 'Will be removed in next major version')
@$core.Deprecated('Using this can add significant overhead to your binary. ' OMEMOAuthenticatedMessage clone() => OMEMOAuthenticatedMessage()..mergeFromMessage(this);
'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' @$core.Deprecated(
'Will be removed in next major version') 'Using this can add significant overhead to your binary. '
OMEMOAuthenticatedMessage clone() => 'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
OMEMOAuthenticatedMessage()..mergeFromMessage(this); 'Will be removed in next major version')
@$core.Deprecated('Using this can add significant overhead to your binary. ' OMEMOAuthenticatedMessage copyWith(void Function(OMEMOAuthenticatedMessage) updates) => super.copyWith((message) => updates(message as OMEMOAuthenticatedMessage)) as OMEMOAuthenticatedMessage; // ignore: deprecated_member_use
'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
'Will be removed in next major version')
OMEMOAuthenticatedMessage copyWith(
void Function(OMEMOAuthenticatedMessage) updates) =>
super.copyWith((message) => updates(message as OMEMOAuthenticatedMessage))
as OMEMOAuthenticatedMessage; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i; $pb.BuilderInfo get info_ => _i;
@$core.pragma('dart2js:noInline') @$core.pragma('dart2js:noInline')
static OMEMOAuthenticatedMessage create() => OMEMOAuthenticatedMessage._(); static OMEMOAuthenticatedMessage create() => OMEMOAuthenticatedMessage._();
OMEMOAuthenticatedMessage createEmptyInstance() => create(); OMEMOAuthenticatedMessage createEmptyInstance() => create();
static $pb.PbList<OMEMOAuthenticatedMessage> createRepeated() => static $pb.PbList<OMEMOAuthenticatedMessage> createRepeated() => $pb.PbList<OMEMOAuthenticatedMessage>();
$pb.PbList<OMEMOAuthenticatedMessage>();
@$core.pragma('dart2js:noInline') @$core.pragma('dart2js:noInline')
static OMEMOAuthenticatedMessage getDefault() => _defaultInstance ??= static OMEMOAuthenticatedMessage getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<OMEMOAuthenticatedMessage>(create);
$pb.GeneratedMessage.$_defaultFor<OMEMOAuthenticatedMessage>(create);
static OMEMOAuthenticatedMessage? _defaultInstance; static OMEMOAuthenticatedMessage? _defaultInstance;
@$pb.TagNumber(1) @$pb.TagNumber(1)
$core.List<$core.int> get mac => $_getN(0); $core.List<$core.int> get mac => $_getN(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
set mac($core.List<$core.int> v) { set mac($core.List<$core.int> v) { $_setBytes(0, v); }
$_setBytes(0, v);
}
@$pb.TagNumber(1) @$pb.TagNumber(1)
$core.bool hasMac() => $_has(0); $core.bool hasMac() => $_has(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
@ -215,10 +150,7 @@ class OMEMOAuthenticatedMessage extends $pb.GeneratedMessage {
@$pb.TagNumber(2) @$pb.TagNumber(2)
$core.List<$core.int> get message => $_getN(1); $core.List<$core.int> get message => $_getN(1);
@$pb.TagNumber(2) @$pb.TagNumber(2)
set message($core.List<$core.int> v) { set message($core.List<$core.int> v) { $_setBytes(1, v); }
$_setBytes(1, v);
}
@$pb.TagNumber(2) @$pb.TagNumber(2)
$core.bool hasMessage() => $_has(1); $core.bool hasMessage() => $_has(1);
@$pb.TagNumber(2) @$pb.TagNumber(2)
@ -226,41 +158,13 @@ class OMEMOAuthenticatedMessage extends $pb.GeneratedMessage {
} }
class OMEMOKeyExchange extends $pb.GeneratedMessage { class OMEMOKeyExchange extends $pb.GeneratedMessage {
static final $pb.BuilderInfo _i = $pb.BuilderInfo( static final $pb.BuilderInfo _i = $pb.BuilderInfo(const $core.bool.fromEnvironment('protobuf.omit_message_names') ? '' : 'OMEMOKeyExchange', createEmptyInstance: create)
const $core.bool.fromEnvironment('protobuf.omit_message_names') ..a<$core.int>(1, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'pkId', $pb.PbFieldType.QU3)
? '' ..a<$core.int>(2, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'spkId', $pb.PbFieldType.QU3)
: 'OMEMOKeyExchange', ..a<$core.List<$core.int>>(3, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'ik', $pb.PbFieldType.QY)
createEmptyInstance: create) ..a<$core.List<$core.int>>(4, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'ek', $pb.PbFieldType.QY)
..a<$core.int>( ..aQM<OMEMOAuthenticatedMessage>(5, const $core.bool.fromEnvironment('protobuf.omit_field_names') ? '' : 'message', subBuilder: OMEMOAuthenticatedMessage.create)
1, ;
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'pkId',
$pb.PbFieldType.QU3)
..a<$core.int>(
2,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'spkId',
$pb.PbFieldType.QU3)
..a<$core.List<$core.int>>(
3,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'ik',
$pb.PbFieldType.QY)
..a<$core.List<$core.int>>(
4,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'ek',
$pb.PbFieldType.QY)
..aQM<OMEMOAuthenticatedMessage>(
5,
const $core.bool.fromEnvironment('protobuf.omit_field_names')
? ''
: 'message',
subBuilder: OMEMOAuthenticatedMessage.create);
OMEMOKeyExchange._() : super(); OMEMOKeyExchange._() : super();
factory OMEMOKeyExchange({ factory OMEMOKeyExchange({
@ -288,40 +192,31 @@ class OMEMOKeyExchange extends $pb.GeneratedMessage {
} }
return _result; return _result;
} }
factory OMEMOKeyExchange.fromBuffer($core.List<$core.int> i, factory OMEMOKeyExchange.fromBuffer($core.List<$core.int> i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromBuffer(i, r);
[$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => factory OMEMOKeyExchange.fromJson($core.String i, [$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => create()..mergeFromJson(i, r);
create()..mergeFromBuffer(i, r); @$core.Deprecated(
factory OMEMOKeyExchange.fromJson($core.String i, 'Using this can add significant overhead to your binary. '
[$pb.ExtensionRegistry r = $pb.ExtensionRegistry.EMPTY]) => 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
create()..mergeFromJson(i, r); 'Will be removed in next major version')
@$core.Deprecated('Using this can add significant overhead to your binary. '
'Use [GeneratedMessageGenericExtensions.deepCopy] instead. '
'Will be removed in next major version')
OMEMOKeyExchange clone() => OMEMOKeyExchange()..mergeFromMessage(this); OMEMOKeyExchange clone() => OMEMOKeyExchange()..mergeFromMessage(this);
@$core.Deprecated('Using this can add significant overhead to your binary. ' @$core.Deprecated(
'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' 'Using this can add significant overhead to your binary. '
'Will be removed in next major version') 'Use [GeneratedMessageGenericExtensions.rebuild] instead. '
OMEMOKeyExchange copyWith(void Function(OMEMOKeyExchange) updates) => 'Will be removed in next major version')
super.copyWith((message) => updates(message as OMEMOKeyExchange)) OMEMOKeyExchange copyWith(void Function(OMEMOKeyExchange) updates) => super.copyWith((message) => updates(message as OMEMOKeyExchange)) as OMEMOKeyExchange; // ignore: deprecated_member_use
as OMEMOKeyExchange; // ignore: deprecated_member_use
$pb.BuilderInfo get info_ => _i; $pb.BuilderInfo get info_ => _i;
@$core.pragma('dart2js:noInline') @$core.pragma('dart2js:noInline')
static OMEMOKeyExchange create() => OMEMOKeyExchange._(); static OMEMOKeyExchange create() => OMEMOKeyExchange._();
OMEMOKeyExchange createEmptyInstance() => create(); OMEMOKeyExchange createEmptyInstance() => create();
static $pb.PbList<OMEMOKeyExchange> createRepeated() => static $pb.PbList<OMEMOKeyExchange> createRepeated() => $pb.PbList<OMEMOKeyExchange>();
$pb.PbList<OMEMOKeyExchange>();
@$core.pragma('dart2js:noInline') @$core.pragma('dart2js:noInline')
static OMEMOKeyExchange getDefault() => _defaultInstance ??= static OMEMOKeyExchange getDefault() => _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<OMEMOKeyExchange>(create);
$pb.GeneratedMessage.$_defaultFor<OMEMOKeyExchange>(create);
static OMEMOKeyExchange? _defaultInstance; static OMEMOKeyExchange? _defaultInstance;
@$pb.TagNumber(1) @$pb.TagNumber(1)
$core.int get pkId => $_getIZ(0); $core.int get pkId => $_getIZ(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
set pkId($core.int v) { set pkId($core.int v) { $_setUnsignedInt32(0, v); }
$_setUnsignedInt32(0, v);
}
@$pb.TagNumber(1) @$pb.TagNumber(1)
$core.bool hasPkId() => $_has(0); $core.bool hasPkId() => $_has(0);
@$pb.TagNumber(1) @$pb.TagNumber(1)
@ -330,10 +225,7 @@ class OMEMOKeyExchange extends $pb.GeneratedMessage {
@$pb.TagNumber(2) @$pb.TagNumber(2)
$core.int get spkId => $_getIZ(1); $core.int get spkId => $_getIZ(1);
@$pb.TagNumber(2) @$pb.TagNumber(2)
set spkId($core.int v) { set spkId($core.int v) { $_setUnsignedInt32(1, v); }
$_setUnsignedInt32(1, v);
}
@$pb.TagNumber(2) @$pb.TagNumber(2)
$core.bool hasSpkId() => $_has(1); $core.bool hasSpkId() => $_has(1);
@$pb.TagNumber(2) @$pb.TagNumber(2)
@ -342,10 +234,7 @@ class OMEMOKeyExchange extends $pb.GeneratedMessage {
@$pb.TagNumber(3) @$pb.TagNumber(3)
$core.List<$core.int> get ik => $_getN(2); $core.List<$core.int> get ik => $_getN(2);
@$pb.TagNumber(3) @$pb.TagNumber(3)
set ik($core.List<$core.int> v) { set ik($core.List<$core.int> v) { $_setBytes(2, v); }
$_setBytes(2, v);
}
@$pb.TagNumber(3) @$pb.TagNumber(3)
$core.bool hasIk() => $_has(2); $core.bool hasIk() => $_has(2);
@$pb.TagNumber(3) @$pb.TagNumber(3)
@ -354,10 +243,7 @@ class OMEMOKeyExchange extends $pb.GeneratedMessage {
@$pb.TagNumber(4) @$pb.TagNumber(4)
$core.List<$core.int> get ek => $_getN(3); $core.List<$core.int> get ek => $_getN(3);
@$pb.TagNumber(4) @$pb.TagNumber(4)
set ek($core.List<$core.int> v) { set ek($core.List<$core.int> v) { $_setBytes(3, v); }
$_setBytes(3, v);
}
@$pb.TagNumber(4) @$pb.TagNumber(4)
$core.bool hasEk() => $_has(3); $core.bool hasEk() => $_has(3);
@$pb.TagNumber(4) @$pb.TagNumber(4)
@ -366,10 +252,7 @@ class OMEMOKeyExchange extends $pb.GeneratedMessage {
@$pb.TagNumber(5) @$pb.TagNumber(5)
OMEMOAuthenticatedMessage get message => $_getN(4); OMEMOAuthenticatedMessage get message => $_getN(4);
@$pb.TagNumber(5) @$pb.TagNumber(5)
set message(OMEMOAuthenticatedMessage v) { set message(OMEMOAuthenticatedMessage v) { setField(5, v); }
setField(5, v);
}
@$pb.TagNumber(5) @$pb.TagNumber(5)
$core.bool hasMessage() => $_has(4); $core.bool hasMessage() => $_has(4);
@$pb.TagNumber(5) @$pb.TagNumber(5)
@ -377,3 +260,4 @@ class OMEMOKeyExchange extends $pb.GeneratedMessage {
@$pb.TagNumber(5) @$pb.TagNumber(5)
OMEMOAuthenticatedMessage ensureMessage() => $_ensure(4); OMEMOAuthenticatedMessage ensureMessage() => $_ensure(4);
} }

View File

@ -4,3 +4,4 @@
// //
// @dart = 2.12 // @dart = 2.12
// ignore_for_file: annotate_overrides,camel_case_types,constant_identifier_names,directives_ordering,library_prefixes,non_constant_identifier_names,prefer_final_fields,return_of_invalid_type,unnecessary_const,unnecessary_import,unnecessary_this,unused_import,unused_shown_name // ignore_for_file: annotate_overrides,camel_case_types,constant_identifier_names,directives_ordering,library_prefixes,non_constant_identifier_names,prefer_final_fields,return_of_invalid_type,unnecessary_const,unnecessary_import,unnecessary_this,unused_import,unused_shown_name

View File

@ -8,53 +8,41 @@
import 'dart:core' as $core; import 'dart:core' as $core;
import 'dart:convert' as $convert; import 'dart:convert' as $convert;
import 'dart:typed_data' as $typed_data; import 'dart:typed_data' as $typed_data;
@$core.Deprecated('Use oMEMOMessageDescriptor instead') @$core.Deprecated('Use oMEMOMessageDescriptor instead')
const OMEMOMessage$json = { const OMEMOMessage$json = const {
'1': 'OMEMOMessage', '1': 'OMEMOMessage',
'2': [ '2': const [
{'1': 'n', '3': 1, '4': 2, '5': 13, '10': 'n'}, const {'1': 'n', '3': 1, '4': 2, '5': 13, '10': 'n'},
{'1': 'pn', '3': 2, '4': 2, '5': 13, '10': 'pn'}, const {'1': 'pn', '3': 2, '4': 2, '5': 13, '10': 'pn'},
{'1': 'dh_pub', '3': 3, '4': 2, '5': 12, '10': 'dhPub'}, const {'1': 'dh_pub', '3': 3, '4': 2, '5': 12, '10': 'dhPub'},
{'1': 'ciphertext', '3': 4, '4': 1, '5': 12, '10': 'ciphertext'}, const {'1': 'ciphertext', '3': 4, '4': 1, '5': 12, '10': 'ciphertext'},
], ],
}; };
/// Descriptor for `OMEMOMessage`. Decode as a `google.protobuf.DescriptorProto`. /// Descriptor for `OMEMOMessage`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List oMEMOMessageDescriptor = $convert.base64Decode( final $typed_data.Uint8List oMEMOMessageDescriptor = $convert.base64Decode('CgxPTUVNT01lc3NhZ2USDAoBbhgBIAIoDVIBbhIOCgJwbhgCIAIoDVICcG4SFQoGZGhfcHViGAMgAigMUgVkaFB1YhIeCgpjaXBoZXJ0ZXh0GAQgASgMUgpjaXBoZXJ0ZXh0');
'CgxPTUVNT01lc3NhZ2USDAoBbhgBIAIoDVIBbhIOCgJwbhgCIAIoDVICcG4SFQoGZGhfcHViGAMgAigMUgVkaFB1YhIeCgpjaXBoZXJ0ZXh0GAQgASgMUgpjaXBoZXJ0ZXh0');
@$core.Deprecated('Use oMEMOAuthenticatedMessageDescriptor instead') @$core.Deprecated('Use oMEMOAuthenticatedMessageDescriptor instead')
const OMEMOAuthenticatedMessage$json = { const OMEMOAuthenticatedMessage$json = const {
'1': 'OMEMOAuthenticatedMessage', '1': 'OMEMOAuthenticatedMessage',
'2': [ '2': const [
{'1': 'mac', '3': 1, '4': 2, '5': 12, '10': 'mac'}, const {'1': 'mac', '3': 1, '4': 2, '5': 12, '10': 'mac'},
{'1': 'message', '3': 2, '4': 2, '5': 12, '10': 'message'}, const {'1': 'message', '3': 2, '4': 2, '5': 12, '10': 'message'},
], ],
}; };
/// Descriptor for `OMEMOAuthenticatedMessage`. Decode as a `google.protobuf.DescriptorProto`. /// Descriptor for `OMEMOAuthenticatedMessage`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List oMEMOAuthenticatedMessageDescriptor = final $typed_data.Uint8List oMEMOAuthenticatedMessageDescriptor = $convert.base64Decode('ChlPTUVNT0F1dGhlbnRpY2F0ZWRNZXNzYWdlEhAKA21hYxgBIAIoDFIDbWFjEhgKB21lc3NhZ2UYAiACKAxSB21lc3NhZ2U=');
$convert.base64Decode(
'ChlPTUVNT0F1dGhlbnRpY2F0ZWRNZXNzYWdlEhAKA21hYxgBIAIoDFIDbWFjEhgKB21lc3NhZ2UYAiACKAxSB21lc3NhZ2U=');
@$core.Deprecated('Use oMEMOKeyExchangeDescriptor instead') @$core.Deprecated('Use oMEMOKeyExchangeDescriptor instead')
const OMEMOKeyExchange$json = { const OMEMOKeyExchange$json = const {
'1': 'OMEMOKeyExchange', '1': 'OMEMOKeyExchange',
'2': [ '2': const [
{'1': 'pk_id', '3': 1, '4': 2, '5': 13, '10': 'pkId'}, const {'1': 'pk_id', '3': 1, '4': 2, '5': 13, '10': 'pkId'},
{'1': 'spk_id', '3': 2, '4': 2, '5': 13, '10': 'spkId'}, const {'1': 'spk_id', '3': 2, '4': 2, '5': 13, '10': 'spkId'},
{'1': 'ik', '3': 3, '4': 2, '5': 12, '10': 'ik'}, const {'1': 'ik', '3': 3, '4': 2, '5': 12, '10': 'ik'},
{'1': 'ek', '3': 4, '4': 2, '5': 12, '10': 'ek'}, const {'1': 'ek', '3': 4, '4': 2, '5': 12, '10': 'ek'},
{ const {'1': 'message', '3': 5, '4': 2, '5': 11, '6': '.OMEMOAuthenticatedMessage', '10': 'message'},
'1': 'message',
'3': 5,
'4': 2,
'5': 11,
'6': '.OMEMOAuthenticatedMessage',
'10': 'message'
},
], ],
}; };
/// Descriptor for `OMEMOKeyExchange`. Decode as a `google.protobuf.DescriptorProto`. /// Descriptor for `OMEMOKeyExchange`. Decode as a `google.protobuf.DescriptorProto`.
final $typed_data.Uint8List oMEMOKeyExchangeDescriptor = $convert.base64Decode( final $typed_data.Uint8List oMEMOKeyExchangeDescriptor = $convert.base64Decode('ChBPTUVNT0tleUV4Y2hhbmdlEhMKBXBrX2lkGAEgAigNUgRwa0lkEhUKBnNwa19pZBgCIAIoDVIFc3BrSWQSDgoCaWsYAyACKAxSAmlrEg4KAmVrGAQgAigMUgJlaxI0CgdtZXNzYWdlGAUgAigLMhouT01FTU9BdXRoZW50aWNhdGVkTWVzc2FnZVIHbWVzc2FnZQ==');
'ChBPTUVNT0tleUV4Y2hhbmdlEhMKBXBrX2lkGAEgAigNUgRwa0lkEhUKBnNwa19pZBgCIAIoDVIFc3BrSWQSDgoCaWsYAyACKAxSAmlrEg4KAmVrGAQgAigMUgJlaxI0CgdtZXNzYWdlGAUgAigLMhouT01FTU9BdXRoZW50aWNhdGVkTWVzc2FnZVIHbWVzc2FnZQ==');

View File

@ -6,3 +6,4 @@
// ignore_for_file: annotate_overrides,camel_case_types,constant_identifier_names,deprecated_member_use_from_same_package,directives_ordering,library_prefixes,non_constant_identifier_names,prefer_final_fields,return_of_invalid_type,unnecessary_const,unnecessary_import,unnecessary_this,unused_import,unused_shown_name // ignore_for_file: annotate_overrides,camel_case_types,constant_identifier_names,deprecated_member_use_from_same_package,directives_ordering,library_prefixes,non_constant_identifier_names,prefer_final_fields,return_of_invalid_type,unnecessary_const,unnecessary_import,unnecessary_this,unused_import,unused_shown_name
export 'schema.pb.dart'; export 'schema.pb.dart';

View File

@ -6,11 +6,7 @@ import 'package:omemo_dart/src/keys.dart';
/// it indicates which of [kp] ([identityKey] == 1) or [pk] ([identityKey] == 2) /// it indicates which of [kp] ([identityKey] == 1) or [pk] ([identityKey] == 2)
/// is the identity key. This is needed since the identity key pair/public key is /// is the identity key. This is needed since the identity key pair/public key is
/// an Ed25519 key, but we need them as X25519 keys for DH. /// an Ed25519 key, but we need them as X25519 keys for DH.
Future<List<int>> omemoDH( Future<List<int>> omemoDH(OmemoKeyPair kp, OmemoPublicKey pk, int identityKey) async {
OmemoKeyPair kp,
OmemoPublicKey pk,
int identityKey,
) async {
var ckp = kp; var ckp = kp;
var cpk = pk; var cpk = pk;
@ -21,14 +17,15 @@ Future<List<int>> omemoDH(
} }
final shared = await Cryptography.instance.x25519().sharedSecretKey( final shared = await Cryptography.instance.x25519().sharedSecretKey(
keyPair: await ckp.asKeyPair(), keyPair: await ckp.asKeyPair(),
remotePublicKey: cpk.asPublicKey(), remotePublicKey: cpk.asPublicKey(),
); );
return shared.extractBytes(); return shared.extractBytes();
} }
class HkdfKeyResult { class HkdfKeyResult {
const HkdfKeyResult(this.encryptionKey, this.authenticationKey, this.iv); const HkdfKeyResult(this.encryptionKey, this.authenticationKey, this.iv);
final List<int> encryptionKey; final List<int> encryptionKey;
final List<int> authenticationKey; final List<int> authenticationKey;
@ -38,8 +35,7 @@ class HkdfKeyResult {
/// cryptography _really_ wants to check the MAC output from AES-256-CBC. Since /// cryptography _really_ wants to check the MAC output from AES-256-CBC. Since
/// we don't have it, we need the MAC check to always "pass". /// we don't have it, we need the MAC check to always "pass".
class NoMacSecretBox extends SecretBox { class NoMacSecretBox extends SecretBox {
NoMacSecretBox(super.cipherText, {required super.nonce}) NoMacSecretBox(super.cipherText, { required super.nonce }) : super(mac: Mac.empty);
: super(mac: Mac.empty);
@override @override
Future<void> checkMac({ Future<void> checkMac({
@ -63,21 +59,13 @@ Future<HkdfKeyResult> deriveEncryptionKeys(List<int> input, String info) async {
info: utf8.encode(info), info: utf8.encode(info),
); );
final bytes = await result.extractBytes(); final bytes = await result.extractBytes();
return HkdfKeyResult( return HkdfKeyResult(bytes.sublist(0, 32), bytes.sublist(32, 64), bytes.sublist(64, 80));
bytes.sublist(0, 32),
bytes.sublist(32, 64),
bytes.sublist(64, 80),
);
} }
/// A small helper function to make AES-256-CBC easier. Encrypt [plaintext] using [key] as /// A small helper function to make AES-256-CBC easier. Encrypt [plaintext] using [key] as
/// the encryption key and [iv] as the IV. Returns the ciphertext. /// the encryption key and [iv] as the IV. Returns the ciphertext.
Future<List<int>> aes256CbcEncrypt( Future<List<int>> aes256CbcEncrypt(List<int> plaintext, List<int> key, List<int> iv) async {
List<int> plaintext,
List<int> key,
List<int> iv,
) async {
final algorithm = AesCbc.with256bits( final algorithm = AesCbc.with256bits(
macAlgorithm: MacAlgorithm.empty, macAlgorithm: MacAlgorithm.empty,
); );
@ -92,11 +80,7 @@ Future<List<int>> aes256CbcEncrypt(
/// A small helper function to make AES-256-CBC easier. Decrypt [ciphertext] using [key] as /// A small helper function to make AES-256-CBC easier. Decrypt [ciphertext] using [key] as
/// the encryption key and [iv] as the IV. Returns the ciphertext. /// the encryption key and [iv] as the IV. Returns the ciphertext.
Future<List<int>> aes256CbcDecrypt( Future<List<int>> aes256CbcDecrypt(List<int> ciphertext, List<int> key, List<int> iv) async {
List<int> ciphertext,
List<int> key,
List<int> iv,
) async {
final algorithm = AesCbc.with256bits( final algorithm = AesCbc.with256bits(
macAlgorithm: MacAlgorithm.empty, macAlgorithm: MacAlgorithm.empty,
); );

View File

@ -10,20 +10,13 @@ const encryptHkdfInfoString = 'OMEMO Message Key Material';
/// Signals ENCRYPT function as specified by OMEMO 0.8.3. /// Signals ENCRYPT function as specified by OMEMO 0.8.3.
/// Encrypt [plaintext] using the message key [mk], given associated_data [associatedData] /// Encrypt [plaintext] using the message key [mk], given associated_data [associatedData]
/// and the AD output from the X3DH [sessionAd]. /// and the AD output from the X3DH [sessionAd].
Future<List<int>> encrypt( Future<List<int>> encrypt(List<int> mk, List<int> plaintext, List<int> associatedData, List<int> sessionAd) async {
List<int> mk,
List<int> plaintext,
List<int> associatedData,
List<int> sessionAd,
) async {
// Generate encryption, authentication key and IV // Generate encryption, authentication key and IV
final keys = await deriveEncryptionKeys(mk, encryptHkdfInfoString); final keys = await deriveEncryptionKeys(mk, encryptHkdfInfoString);
final ciphertext = final ciphertext = await aes256CbcEncrypt(plaintext, keys.encryptionKey, keys.iv);
await aes256CbcEncrypt(plaintext, keys.encryptionKey, keys.iv);
final header = OmemoMessage.fromBuffer(associatedData.sublist(sessionAd.length))
final header = ..ciphertext = ciphertext;
OmemoMessage.fromBuffer(associatedData.sublist(sessionAd.length))
..ciphertext = ciphertext;
final headerBytes = header.writeToBuffer(); final headerBytes = header.writeToBuffer();
final hmacInput = concat([sessionAd, headerBytes]); final hmacInput = concat([sessionAd, headerBytes]);
final hmacResult = await truncatedHmac(hmacInput, keys.authenticationKey); final hmacResult = await truncatedHmac(hmacInput, keys.authenticationKey);
@ -36,15 +29,10 @@ Future<List<int>> encrypt(
/// Signals DECRYPT function as specified by OMEMO 0.8.3. /// Signals DECRYPT function as specified by OMEMO 0.8.3.
/// Decrypt [ciphertext] with the message key [mk], given the associated_data [associatedData] /// Decrypt [ciphertext] with the message key [mk], given the associated_data [associatedData]
/// and the AD output from the X3DH. /// and the AD output from the X3DH.
Future<List<int>> decrypt( Future<List<int>> decrypt(List<int> mk, List<int> ciphertext, List<int> associatedData, List<int> sessionAd) async {
List<int> mk,
List<int> ciphertext,
List<int> associatedData,
List<int> sessionAd,
) async {
// Generate encryption, authentication key and IV // Generate encryption, authentication key and IV
final keys = await deriveEncryptionKeys(mk, encryptHkdfInfoString); final keys = await deriveEncryptionKeys(mk, encryptHkdfInfoString);
// Assumption ciphertext is a OMEMOAuthenticatedMessage // Assumption ciphertext is a OMEMOAuthenticatedMessage
final message = OmemoAuthenticatedMessage.fromBuffer(ciphertext); final message = OmemoAuthenticatedMessage.fromBuffer(ciphertext);
final header = OmemoMessage.fromBuffer(message.message!); final header = OmemoMessage.fromBuffer(message.message!);

View File

@ -42,7 +42,7 @@ class SkippedKey {
'n': n, 'n': n,
}; };
} }
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
return other is SkippedKey && other.dh == dh && other.n == n; return other is SkippedKey && other.dh == dh && other.n == n;
@ -56,12 +56,12 @@ class OmemoDoubleRatchet {
OmemoDoubleRatchet( OmemoDoubleRatchet(
this.dhs, // DHs this.dhs, // DHs
this.dhr, // DHr this.dhr, // DHr
this.rk, // RK this.rk, // RK
this.cks, // CKs this.cks, // CKs
this.ckr, // CKr this.ckr, // CKr
this.ns, // Ns this.ns, // Ns
this.nr, // Nr this.nr, // Nr
this.pn, // Pn this.pn, // Pn
this.ik, this.ik,
this.sessionAd, this.sessionAd,
this.mkSkipped, // MKSKIPPED this.mkSkipped, // MKSKIPPED
@ -69,7 +69,7 @@ class OmemoDoubleRatchet {
this.kexTimestamp, this.kexTimestamp,
this.kex, this.kex,
); );
factory OmemoDoubleRatchet.fromJson(Map<String, dynamic> data) { factory OmemoDoubleRatchet.fromJson(Map<String, dynamic> data) {
/* /*
{ {
@ -99,8 +99,7 @@ class OmemoDoubleRatchet {
// NOTE: Dart has some issues with just casting a List<dynamic> to List<Map<...>>, as // NOTE: Dart has some issues with just casting a List<dynamic> to List<Map<...>>, as
// such we need to convert the items by hand. // such we need to convert the items by hand.
final mkSkipped = Map<SkippedKey, List<int>>.fromEntries( final mkSkipped = Map<SkippedKey, List<int>>.fromEntries(
(data['mkskipped']! as List<dynamic>) (data['mkskipped']! as List<dynamic>).map<MapEntry<SkippedKey, List<int>>>(
.map<MapEntry<SkippedKey, List<int>>>(
(entry) { (entry) {
final map = entry as Map<String, dynamic>; final map = entry as Map<String, dynamic>;
final key = SkippedKey.fromJson(map); final key = SkippedKey.fromJson(map);
@ -111,7 +110,7 @@ class OmemoDoubleRatchet {
}, },
), ),
); );
return OmemoDoubleRatchet( return OmemoDoubleRatchet(
OmemoKeyPair.fromBytes( OmemoKeyPair.fromBytes(
base64.decode(data['dhs_pub']! as String), base64.decode(data['dhs_pub']! as String),
@ -136,7 +135,7 @@ class OmemoDoubleRatchet {
data['kex'] as String?, data['kex'] as String?,
); );
} }
/// Sending DH keypair /// Sending DH keypair
OmemoKeyPair dhs; OmemoKeyPair dhs;
@ -160,7 +159,7 @@ class OmemoDoubleRatchet {
/// The IK public key from the chat partner. Not used for the actual encryption but /// The IK public key from the chat partner. Not used for the actual encryption but
/// for verification purposes /// for verification purposes
final OmemoPublicKey ik; final OmemoPublicKey ik;
final List<int> sessionAd; final List<int> sessionAd;
final Map<SkippedKey, List<int>> mkSkipped; final Map<SkippedKey, List<int>> mkSkipped;
@ -171,24 +170,18 @@ class OmemoDoubleRatchet {
/// The key exchange that was used for initiating the session. /// The key exchange that was used for initiating the session.
final String? kex; final String? kex;
/// Indicates whether we received an empty OMEMO message after building a session with /// Indicates whether we received an empty OMEMO message after building a session with
/// the device. /// the device.
bool acknowledged; bool acknowledged;
/// Create an OMEMO session using the Signed Pre Key [spk], the shared secret [sk] that /// Create an OMEMO session using the Signed Pre Key [spk], the shared secret [sk] that
/// was obtained using a X3DH and the associated data [ad] that was also obtained through /// was obtained using a X3DH and the associated data [ad] that was also obtained through
/// a X3DH. [ik] refers to Bob's (the receiver's) IK public key. /// a X3DH. [ik] refers to Bob's (the receiver's) IK public key.
static Future<OmemoDoubleRatchet> initiateNewSession( static Future<OmemoDoubleRatchet> initiateNewSession(OmemoPublicKey spk, OmemoPublicKey ik, List<int> sk, List<int> ad, int timestamp) async {
OmemoPublicKey spk,
OmemoPublicKey ik,
List<int> sk,
List<int> ad,
int timestamp,
) async {
final dhs = await OmemoKeyPair.generateNewPair(KeyPairType.x25519); final dhs = await OmemoKeyPair.generateNewPair(KeyPairType.x25519);
final dhr = spk; final dhr = spk;
final rk = await kdfRk(sk, await omemoDH(dhs, dhr, 0)); final rk = await kdfRk(sk, await omemoDH(dhs, dhr, 0));
final cks = rk; final cks = rk;
return OmemoDoubleRatchet( return OmemoDoubleRatchet(
@ -213,13 +206,7 @@ class OmemoDoubleRatchet {
/// Pre Key keypair [spk], the shared secret [sk] that was obtained through a X3DH and /// Pre Key keypair [spk], the shared secret [sk] that was obtained through a X3DH and
/// the associated data [ad] that was also obtained through a X3DH. [ik] refers to /// the associated data [ad] that was also obtained through a X3DH. [ik] refers to
/// Alice's (the initiator's) IK public key. /// Alice's (the initiator's) IK public key.
static Future<OmemoDoubleRatchet> acceptNewSession( static Future<OmemoDoubleRatchet> acceptNewSession(OmemoKeyPair spk, OmemoPublicKey ik, List<int> sk, List<int> ad, int kexTimestamp) async {
OmemoKeyPair spk,
OmemoPublicKey ik,
List<int> sk,
List<int> ad,
int kexTimestamp,
) async {
return OmemoDoubleRatchet( return OmemoDoubleRatchet(
spk, spk,
null, null,
@ -239,15 +226,14 @@ class OmemoDoubleRatchet {
} }
Future<Map<String, dynamic>> toJson() async { Future<Map<String, dynamic>> toJson() async {
final mkSkippedSerialised = final mkSkippedSerialised = List<Map<String, dynamic>>.empty(growable: true);
List<Map<String, dynamic>>.empty(growable: true);
for (final entry in mkSkipped.entries) { for (final entry in mkSkipped.entries) {
final result = await entry.key.toJson(); final result = await entry.key.toJson();
result['key'] = base64.encode(entry.value); result['key'] = base64.encode(entry.value);
mkSkippedSerialised.add(result); mkSkippedSerialised.add(result);
} }
return { return {
'dhs': base64.encode(await dhs.sk.getBytes()), 'dhs': base64.encode(await dhs.sk.getBytes()),
'dhs_pub': base64.encode(await dhs.pk.getBytes()), 'dhs_pub': base64.encode(await dhs.pk.getBytes()),
@ -272,11 +258,8 @@ class OmemoDoubleRatchet {
final curveKey = await ik.toCurve25519(); final curveKey = await ik.toCurve25519();
return HEX.encode(await curveKey.getBytes()); return HEX.encode(await curveKey.getBytes());
} }
Future<List<int>?> _trySkippedMessageKeys( Future<List<int>?> _trySkippedMessageKeys(OmemoMessage header, List<int> ciphertext) async {
OmemoMessage header,
List<int> ciphertext,
) async {
final key = SkippedKey( final key = SkippedKey(
OmemoPublicKey.fromBytes(header.dhPub!, KeyPairType.x25519), OmemoPublicKey.fromBytes(header.dhPub!, KeyPairType.x25519),
header.n!, header.n!,
@ -285,12 +268,7 @@ class OmemoDoubleRatchet {
final mk = mkSkipped[key]!; final mk = mkSkipped[key]!;
mkSkipped.remove(key); mkSkipped.remove(key);
return decrypt( return decrypt(mk, ciphertext, concat([sessionAd, header.writeToBuffer()]), sessionAd);
mk,
ciphertext,
concat([sessionAd, header.writeToBuffer()]),
sessionAd,
);
} }
return null; return null;
@ -342,12 +320,7 @@ class OmemoDoubleRatchet {
return RatchetStep( return RatchetStep(
header, header,
await encrypt( await encrypt(mk, plaintext, concat([sessionAd, header.writeToBuffer()]), sessionAd),
mk,
plaintext,
concat([sessionAd, header.writeToBuffer()]),
sessionAd,
),
); );
} }
@ -355,10 +328,7 @@ class OmemoDoubleRatchet {
/// Ratchet. Returns the decrypted (raw) plaintext. /// Ratchet. Returns the decrypted (raw) plaintext.
/// ///
/// Throws an SkippingTooManyMessagesException if too many messages were to be skipped. /// Throws an SkippingTooManyMessagesException if too many messages were to be skipped.
Future<List<int>> ratchetDecrypt( Future<List<int>> ratchetDecrypt(OmemoMessage header, List<int> ciphertext) async {
OmemoMessage header,
List<int> ciphertext,
) async {
// Check if we skipped too many messages // Check if we skipped too many messages
final plaintext = await _trySkippedMessageKeys(header, ciphertext); final plaintext = await _trySkippedMessageKeys(header, ciphertext);
if (plaintext != null) { if (plaintext != null) {
@ -373,19 +343,14 @@ class OmemoDoubleRatchet {
await _skipMessageKeys(header.pn!); await _skipMessageKeys(header.pn!);
await _dhRatchet(header); await _dhRatchet(header);
} }
await _skipMessageKeys(header.n!); await _skipMessageKeys(header.n!);
final newCkr = await kdfCk(ckr!, kdfCkNextChainKey); final newCkr = await kdfCk(ckr!, kdfCkNextChainKey);
final mk = await kdfCk(ckr!, kdfCkNextMessageKey); final mk = await kdfCk(ckr!, kdfCkNextMessageKey);
ckr = newCkr; ckr = newCkr;
nr++; nr++;
return decrypt( return decrypt(mk, ciphertext, concat([sessionAd, header.writeToBuffer()]), sessionAd);
mk,
ciphertext,
concat([sessionAd, header.writeToBuffer()]),
sessionAd,
);
} }
OmemoDoubleRatchet clone() { OmemoDoubleRatchet clone() {
@ -393,8 +358,12 @@ class OmemoDoubleRatchet {
dhs, dhs,
dhr, dhr,
rk, rk,
cks != null ? List<int>.from(cks!) : null, cks != null ?
ckr != null ? List<int>.from(ckr!) : null, List<int>.from(cks!) :
null,
ckr != null ?
List<int>.from(ckr!) :
null,
ns, ns,
nr, nr,
pn, pn,
@ -412,8 +381,12 @@ class OmemoDoubleRatchet {
dhs, dhs,
dhr, dhr,
rk, rk,
cks != null ? List<int>.from(cks!) : null, cks != null ?
ckr != null ? List<int>.from(ckr!) : null, List<int>.from(cks!) :
null,
ckr != null ?
List<int>.from(ckr!) :
null,
ns, ns,
nr, nr,
pn, pn,
@ -425,36 +398,35 @@ class OmemoDoubleRatchet {
kex, kex,
); );
} }
@visibleForTesting @visibleForTesting
Future<bool> equals(OmemoDoubleRatchet other) async { Future<bool> equals(OmemoDoubleRatchet other) async {
final dhrMatch = dhr == null final dhrMatch = dhr == null ?
? other.dhr == null other.dhr == null :
: // ignore: invalid_use_of_visible_for_testing_member
// ignore: invalid_use_of_visible_for_testing_member other.dhr != null && await dhr!.equals(other.dhr!);
other.dhr != null && await dhr!.equals(other.dhr!); final ckrMatch = ckr == null ?
final ckrMatch = ckr == null other.ckr == null :
? other.ckr == null other.ckr != null && listsEqual(ckr!, other.ckr!);
: other.ckr != null && listsEqual(ckr!, other.ckr!); final cksMatch = cks == null ?
final cksMatch = cks == null other.cks == null :
? other.cks == null other.cks != null && listsEqual(cks!, other.cks!);
: other.cks != null && listsEqual(cks!, other.cks!);
// ignore: invalid_use_of_visible_for_testing_member // ignore: invalid_use_of_visible_for_testing_member
final dhsMatch = await dhs.equals(other.dhs); final dhsMatch = await dhs.equals(other.dhs);
// ignore: invalid_use_of_visible_for_testing_member // ignore: invalid_use_of_visible_for_testing_member
final ikMatch = await ik.equals(other.ik); final ikMatch = await ik.equals(other.ik);
return dhsMatch && return dhsMatch &&
ikMatch && ikMatch &&
dhrMatch && dhrMatch &&
listsEqual(rk, other.rk) && listsEqual(rk, other.rk) &&
cksMatch && cksMatch &&
ckrMatch && ckrMatch &&
ns == other.ns && ns == other.ns &&
nr == other.nr && nr == other.nr &&
pn == other.pn && pn == other.pn &&
listsEqual(sessionAd, other.sessionAd) && listsEqual(sessionAd, other.sessionAd) &&
kexTimestamp == other.kexTimestamp; kexTimestamp == other.kexTimestamp;
} }
} }

View File

@ -2,10 +2,8 @@ abstract class OmemoException {}
/// Triggered during X3DH if the signature if the SPK does verify to the actual SPK. /// Triggered during X3DH if the signature if the SPK does verify to the actual SPK.
class InvalidSignatureException extends OmemoException implements Exception { class InvalidSignatureException extends OmemoException implements Exception {
String errMsg() => String errMsg() => 'The signature of the SPK does not match the provided signature';
'The signature of the SPK does not match the provided signature';
} }
/// Triggered by the Double Ratchet if the computed HMAC does not match the attached HMAC. /// Triggered by the Double Ratchet if the computed HMAC does not match the attached HMAC.
/// Triggered by the Session Manager if the computed HMAC does not match the attached HMAC. /// Triggered by the Session Manager if the computed HMAC does not match the attached HMAC.
class InvalidMessageHMACException extends OmemoException implements Exception { class InvalidMessageHMACException extends OmemoException implements Exception {
@ -14,14 +12,12 @@ class InvalidMessageHMACException extends OmemoException implements Exception {
/// Triggered by the Double Ratchet if skipping messages would cause skipping more than /// Triggered by the Double Ratchet if skipping messages would cause skipping more than
/// MAXSKIP messages /// MAXSKIP messages
class SkippingTooManyMessagesException extends OmemoException class SkippingTooManyMessagesException extends OmemoException implements Exception {
implements Exception {
String errMsg() => 'Skipping messages would cause a skip bigger than MAXSKIP'; String errMsg() => 'Skipping messages would cause a skip bigger than MAXSKIP';
} }
/// Triggered by the Session Manager if the message key is not encrypted for the device. /// Triggered by the Session Manager if the message key is not encrypted for the device.
class NotEncryptedForDeviceException extends OmemoException class NotEncryptedForDeviceException extends OmemoException implements Exception {
implements Exception {
String errMsg() => 'Not encrypted for this device'; String errMsg() => 'Not encrypted for this device';
} }
@ -45,8 +41,7 @@ class InvalidKeyExchangeException extends OmemoException implements Exception {
/// Triggered by the Session Manager when a message's sequence number is smaller than we /// Triggered by the Session Manager when a message's sequence number is smaller than we
/// expect it to be. /// expect it to be.
class MessageAlreadyDecryptedException extends OmemoException class MessageAlreadyDecryptedException extends OmemoException implements Exception {
implements Exception {
String errMsg() => 'The message has already been decrypted'; String errMsg() => 'The message has already been decrypted';
} }
@ -54,8 +49,6 @@ class MessageAlreadyDecryptedException extends OmemoException
/// no key material available. That happens, for example, when we want to create a /// no key material available. That happens, for example, when we want to create a
/// ratchet session with a JID we had no session with but fetching the device bundle /// ratchet session with a JID we had no session with but fetching the device bundle
/// failed. /// failed.
class NoKeyMaterialAvailableException extends OmemoException class NoKeyMaterialAvailableException extends OmemoException implements Exception {
implements Exception { String errMsg() => 'No key material available to create a ratchet session with';
String errMsg() =>
'No key material available to create a ratchet session with';
} }

View File

@ -43,11 +43,7 @@ int generateRandom32BitNumber() {
return Random.secure().nextInt(4294967295 /*pow(2, 32) - 1*/); return Random.secure().nextInt(4294967295 /*pow(2, 32) - 1*/);
} }
OmemoPublicKey? decodeKeyIfNotNull( OmemoPublicKey? decodeKeyIfNotNull(Map<String, dynamic> map, String key, KeyPairType type) {
Map<String, dynamic> map,
String key,
KeyPairType type,
) {
if (map[key] == null) return null; if (map[key] == null) return null;
return OmemoPublicKey.fromBytes( return OmemoPublicKey.fromBytes(

View File

@ -21,7 +21,7 @@ class OmemoPublicKey {
} }
final SimplePublicKey _pubkey; final SimplePublicKey _pubkey;
KeyPairType get type => _pubkey.type; KeyPairType get type => _pubkey.type;
/// Return the bytes that comprise the public key. /// Return the bytes that comprise the public key.
@ -31,10 +31,7 @@ class OmemoPublicKey {
Future<String> asBase64() async => base64Encode(_pubkey.bytes); Future<String> asBase64() async => base64Encode(_pubkey.bytes);
Future<OmemoPublicKey> toCurve25519() async { Future<OmemoPublicKey> toCurve25519() async {
assert( assert(type == KeyPairType.ed25519, 'Cannot convert non-Ed25519 public key to X25519');
type == KeyPairType.ed25519,
'Cannot convert non-Ed25519 public key to X25519',
);
final pkc = Uint8List(publicKeyLength); final pkc = Uint8List(publicKeyLength);
TweetNaClExt.crypto_sign_ed25519_pk_to_x25519_pk( TweetNaClExt.crypto_sign_ed25519_pk_to_x25519_pk(
@ -42,20 +39,17 @@ class OmemoPublicKey {
Uint8List.fromList(await getBytes()), Uint8List.fromList(await getBytes()),
); );
return OmemoPublicKey( return OmemoPublicKey(SimplePublicKey(List<int>.from(pkc), type: KeyPairType.x25519));
SimplePublicKey(List<int>.from(pkc), type: KeyPairType.x25519),
);
} }
SimplePublicKey asPublicKey() => _pubkey; SimplePublicKey asPublicKey() => _pubkey;
@visibleForTesting @visibleForTesting
Future<bool> equals(OmemoPublicKey key) async { Future<bool> equals(OmemoPublicKey key) async {
return type == key.type && return type == key.type && listsEqual(
listsEqual( await getBytes(),
await getBytes(), await key.getBytes(),
await key.getBytes(), );
);
} }
} }
@ -65,12 +59,9 @@ class OmemoPrivateKey {
final KeyPairType type; final KeyPairType type;
Future<List<int>> getBytes() async => _privkey; Future<List<int>> getBytes() async => _privkey;
Future<OmemoPrivateKey> toCurve25519() async { Future<OmemoPrivateKey> toCurve25519() async {
assert( assert(type == KeyPairType.ed25519, 'Cannot convert non-Ed25519 private key to X25519');
type == KeyPairType.ed25519,
'Cannot convert non-Ed25519 private key to X25519',
);
final skc = Uint8List(privateKeyLength); final skc = Uint8List(privateKeyLength);
TweetNaClExt.crypto_sign_ed25519_sk_to_x25519_sk( TweetNaClExt.crypto_sign_ed25519_sk_to_x25519_sk(
@ -83,11 +74,10 @@ class OmemoPrivateKey {
@visibleForTesting @visibleForTesting
Future<bool> equals(OmemoPrivateKey key) async { Future<bool> equals(OmemoPrivateKey key) async {
return type == key.type && return type == key.type && listsEqual(
listsEqual( await getBytes(),
await getBytes(), await key.getBytes(),
await key.getBytes(), );
);
} }
} }
@ -97,11 +87,7 @@ class OmemoKeyPair {
/// Create an OmemoKeyPair just from a [type] and the bytes of the private and public /// Create an OmemoKeyPair just from a [type] and the bytes of the private and public
/// key. /// key.
factory OmemoKeyPair.fromBytes( factory OmemoKeyPair.fromBytes(List<int> publicKey, List<int> privateKey, KeyPairType type) {
List<int> publicKey,
List<int> privateKey,
KeyPairType type,
) {
return OmemoKeyPair( return OmemoKeyPair(
OmemoPublicKey.fromBytes( OmemoPublicKey.fromBytes(
publicKey, publicKey,
@ -118,10 +104,7 @@ class OmemoKeyPair {
/// Generate a completely new random OmemoKeyPair of type [type]. [type] must be either /// Generate a completely new random OmemoKeyPair of type [type]. [type] must be either
/// KeyPairType.ed25519 or KeyPairType.x25519. /// KeyPairType.ed25519 or KeyPairType.x25519.
static Future<OmemoKeyPair> generateNewPair(KeyPairType type) async { static Future<OmemoKeyPair> generateNewPair(KeyPairType type) async {
assert( assert(type == KeyPairType.ed25519 || type == KeyPairType.x25519, 'Keypair must be either Ed25519 or X25519');
type == KeyPairType.ed25519 || type == KeyPairType.x25519,
'Keypair must be either Ed25519 or X25519',
);
SimpleKeyPair kp; SimpleKeyPair kp;
if (type == KeyPairType.ed25519) { if (type == KeyPairType.ed25519) {
@ -136,7 +119,7 @@ class OmemoKeyPair {
} }
final kpd = await kp.extract(); final kpd = await kp.extract();
return OmemoKeyPair( return OmemoKeyPair(
OmemoPublicKey(await kp.extractPublicKey()), OmemoPublicKey(await kp.extractPublicKey()),
OmemoPrivateKey(await kpd.extractPrivateKeyBytes(), type), OmemoPrivateKey(await kpd.extractPrivateKeyBytes(), type),
@ -147,13 +130,10 @@ class OmemoKeyPair {
final KeyPairType type; final KeyPairType type;
final OmemoPublicKey pk; final OmemoPublicKey pk;
final OmemoPrivateKey sk; final OmemoPrivateKey sk;
/// Return the bytes that comprise the public key. /// Return the bytes that comprise the public key.
Future<OmemoKeyPair> toCurve25519() async { Future<OmemoKeyPair> toCurve25519() async {
assert( assert(type == KeyPairType.ed25519, 'Cannot convert non-Ed25519 keypair to X25519');
type == KeyPairType.ed25519,
'Cannot convert non-Ed25519 keypair to X25519',
);
return OmemoKeyPair( return OmemoKeyPair(
await pk.toCurve25519(), await pk.toCurve25519(),
@ -173,7 +153,7 @@ class OmemoKeyPair {
@visibleForTesting @visibleForTesting
Future<bool> equals(OmemoKeyPair pair) async { Future<bool> equals(OmemoKeyPair pair) async {
return type == pair.type && return type == pair.type &&
await pk.equals(pair.pk) && await pk.equals(pair.pk) &&
await sk.equals(pair.sk); await sk.equals(pair.sk);
} }
} }

View File

@ -4,6 +4,7 @@ import 'package:hex/hex.dart';
import 'package:omemo_dart/src/keys.dart'; import 'package:omemo_dart/src/keys.dart';
class OmemoBundle { class OmemoBundle {
const OmemoBundle( const OmemoBundle(
this.jid, this.jid,
this.id, this.id,
@ -13,23 +14,17 @@ class OmemoBundle {
this.ikEncoded, this.ikEncoded,
this.opksEncoded, this.opksEncoded,
); );
/// The bare Jid the Bundle belongs to /// The bare Jid the Bundle belongs to
final String jid; final String jid;
/// The device Id /// The device Id
final int id; final int id;
/// The SPK but base64 encoded /// The SPK but base64 encoded
final String spkEncoded; final String spkEncoded;
final int spkId; final int spkId;
/// The SPK signature but base64 encoded /// The SPK signature but base64 encoded
final String spkSignatureEncoded; final String spkSignatureEncoded;
/// The IK but base64 encoded /// The IK but base64 encoded
final String ikEncoded; final String ikEncoded;
/// The mapping of a OPK's id to the base64 encoded data /// The mapping of a OPK's id to the base64 encoded data
final Map<int, String> opksEncoded; final Map<int, String> opksEncoded;

View File

@ -91,12 +91,9 @@ class OmemoDevice {
opks, opks,
); );
} }
/// Generate a completely new device, i.e. cryptographic identity. /// Generate a completely new device, i.e. cryptographic identity.
static Future<OmemoDevice> generateNewDevice( static Future<OmemoDevice> generateNewDevice(String jid, { int opkAmount = 100 }) async {
String jid, {
int opkAmount = 100,
}) async {
final id = generateRandom32BitNumber(); final id = generateRandom32BitNumber();
final ik = await OmemoKeyPair.generateNewPair(KeyPairType.ed25519); final ik = await OmemoKeyPair.generateNewPair(KeyPairType.ed25519);
final spk = await OmemoKeyPair.generateNewPair(KeyPairType.x25519); final spk = await OmemoKeyPair.generateNewPair(KeyPairType.x25519);
@ -113,7 +110,7 @@ class OmemoDevice {
/// Our bare Jid /// Our bare Jid
final String jid; final String jid;
/// The device Id /// The device Id
final int id; final int id;
@ -122,16 +119,13 @@ class OmemoDevice {
/// The signed prekey... /// The signed prekey...
final OmemoKeyPair spk; final OmemoKeyPair spk;
/// ...its Id, ... /// ...its Id, ...
final int spkId; final int spkId;
/// ...and its signature /// ...and its signature
final List<int> spkSignature; final List<int> spkSignature;
/// The old Signed Prekey... /// The old Signed Prekey...
final OmemoKeyPair? oldSpk; final OmemoKeyPair? oldSpk;
/// ...and its Id /// ...and its Id
final int? oldSpkId; final int? oldSpkId;
@ -143,7 +137,7 @@ class OmemoDevice {
@internal @internal
Future<OmemoDevice> replaceOnetimePrekey(int id) async { Future<OmemoDevice> replaceOnetimePrekey(int id) async {
opks[id] = await OmemoKeyPair.generateNewPair(KeyPairType.x25519); opks[id] = await OmemoKeyPair.generateNewPair(KeyPairType.x25519);
return OmemoDevice( return OmemoDevice(
jid, jid,
this.id, this.id,
@ -194,7 +188,7 @@ class OmemoDevice {
opks, opks,
); );
} }
/// Converts this device into an OmemoBundle that could be used for publishing. /// Converts this device into an OmemoBundle that could be used for publishing.
Future<OmemoBundle> toBundle() async { Future<OmemoBundle> toBundle() async {
final encodedOpks = <int, String>{}; final encodedOpks = <int, String>{};
@ -220,7 +214,7 @@ class OmemoDevice {
final curveKey = await ik.pk.toCurve25519(); final curveKey = await ik.pk.toCurve25519();
return HEX.encode(await curveKey.getBytes()); return HEX.encode(await curveKey.getBytes());
} }
/// Serialise the device information. /// Serialise the device information.
Future<Map<String, dynamic>> toJson() async { Future<Map<String, dynamic>> toJson() async {
/// Serialise the OPKs /// Serialise the OPKs
@ -232,7 +226,7 @@ class OmemoDevice {
'private': base64.encode(await entry.value.sk.getBytes()), 'private': base64.encode(await entry.value.sk.getBytes()),
}); });
} }
return { return {
'jid': jid, 'jid': jid,
'id': id, 'id': id,
@ -257,9 +251,7 @@ class OmemoDevice {
} else { } else {
for (final entry in opks.entries) { for (final entry in opks.entries) {
// ignore: invalid_use_of_visible_for_testing_member // ignore: invalid_use_of_visible_for_testing_member
final matches = final matches = await other.opks[entry.key]?.equals(entry.value) ?? false;
// ignore: invalid_use_of_visible_for_testing_member
await other.opks[entry.key]?.equals(entry.value) ?? false;
if (!matches) { if (!matches) {
opksMatch = false; opksMatch = false;
} }
@ -271,18 +263,15 @@ class OmemoDevice {
// ignore: invalid_use_of_visible_for_testing_member // ignore: invalid_use_of_visible_for_testing_member
final spkMatch = await spk.equals(other.spk); final spkMatch = await spk.equals(other.spk);
// ignore: invalid_use_of_visible_for_testing_member // ignore: invalid_use_of_visible_for_testing_member
final oldSpkMatch = oldSpk != null final oldSpkMatch = oldSpk != null ? await oldSpk!.equals(other.oldSpk!) : other.oldSpk == null;
// ignore: invalid_use_of_visible_for_testing_member
? await oldSpk!.equals(other.oldSpk!)
: other.oldSpk == null;
return id == other.id && return id == other.id &&
ikMatch && ikMatch &&
spkMatch && spkMatch &&
oldSpkMatch && oldSpkMatch &&
jid == other.jid && jid == other.jid &&
listsEqual(spkSignature, other.spkSignature) && listsEqual(spkSignature, other.spkSignature) &&
spkId == other.spkId && spkId == other.spkId &&
oldSpkId == other.oldSpkId && oldSpkId == other.oldSpkId &&
opksMatch; opksMatch;
} }
} }

View File

@ -4,6 +4,7 @@ import 'package:meta/meta.dart';
/// <keys /> header. /// <keys /> header.
@immutable @immutable
class EncryptedKey { class EncryptedKey {
const EncryptedKey(this.jid, this.rid, this.value, this.kex); const EncryptedKey(this.jid, this.rid, this.value, this.kex);
final String jid; final String jid;
final int rid; final int rid;

View File

@ -5,16 +5,11 @@ import 'package:omemo_dart/src/omemo/ratchet_map_key.dart';
@immutable @immutable
class EncryptionResult { class EncryptionResult {
const EncryptionResult( const EncryptionResult(this.ciphertext, this.encryptedKeys, this.deviceEncryptionErrors, this.jidEncryptionErrors);
this.ciphertext,
this.encryptedKeys,
this.deviceEncryptionErrors,
this.jidEncryptionErrors,
);
/// The actual message that was encrypted. /// The actual message that was encrypted.
final List<int>? ciphertext; final List<int>? ciphertext;
/// Mapping of the device Id to the key for decrypting ciphertext, encrypted /// Mapping of the device Id to the key for decrypting ciphertext, encrypted
/// for the ratchet with said device Id. /// for the ratchet with said device Id.
final List<EncryptedKey> encryptedKeys; final List<EncryptedKey> encryptedKeys;
@ -27,7 +22,5 @@ class EncryptionResult {
/// True if the encryption was a success. This means that we could encrypt for /// True if the encryption was a success. This means that we could encrypt for
/// at least one ratchet. /// at least one ratchet.
bool isSuccess(int numberOfRecipients) => bool isSuccess(int numberOfRecipients) => encryptedKeys.isNotEmpty && jidEncryptionErrors.length < numberOfRecipients;
encryptedKeys.isNotEmpty &&
jidEncryptionErrors.length < numberOfRecipients;
} }

View File

@ -5,13 +5,7 @@ abstract class OmemoEvent {}
/// Triggered when a ratchet has been modified /// Triggered when a ratchet has been modified
class RatchetModifiedEvent extends OmemoEvent { class RatchetModifiedEvent extends OmemoEvent {
RatchetModifiedEvent( RatchetModifiedEvent(this.jid, this.deviceId, this.ratchet, this.added, this.replaced);
this.jid,
this.deviceId,
this.ratchet,
this.added,
this.replaced,
);
final String jid; final String jid;
final int deviceId; final int deviceId;
final OmemoDoubleRatchet ratchet; final OmemoDoubleRatchet ratchet;

View File

@ -9,8 +9,8 @@ class DeviceFingerprint {
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
return other is DeviceFingerprint && return other is DeviceFingerprint &&
fingerprint == other.fingerprint && fingerprint == other.fingerprint &&
deviceId == other.deviceId; deviceId == other.deviceId;
} }
@override @override

View File

@ -33,10 +33,7 @@ class _InternalDecryptionResult {
this.ratchetCreated, this.ratchetCreated,
this.ratchetReplaced, this.ratchetReplaced,
this.payload, this.payload,
) : assert( ) : assert(!ratchetCreated || !ratchetReplaced, 'Ratchet must be either replaced or created');
!ratchetCreated || !ratchetReplaced,
'Ratchet must be either replaced or created',
);
final bool ratchetCreated; final bool ratchetCreated;
final bool ratchetReplaced; final bool ratchetReplaced;
final String? payload; final String? payload;
@ -58,8 +55,7 @@ class OmemoManager {
/// Send an empty OMEMO:2 message using the encrypted payload @result to /// Send an empty OMEMO:2 message using the encrypted payload @result to
/// @recipientJid. /// @recipientJid.
final Future<void> Function(EncryptionResult result, String recipientJid) final Future<void> Function(EncryptionResult result, String recipientJid) sendEmptyOmemoMessageImpl;
sendEmptyOmemoMessageImpl;
/// Fetch the list of device ids associated with @jid. If the device list cannot be /// Fetch the list of device ids associated with @jid. If the device list cannot be
/// fetched, return null. /// fetched, return null.
@ -70,20 +66,16 @@ class OmemoManager {
/// Subscribe to the device list PEP node of @jid. /// Subscribe to the device list PEP node of @jid.
final Future<void> Function(String jid) subscribeToDeviceListNodeImpl; final Future<void> Function(String jid) subscribeToDeviceListNodeImpl;
/// Map bare JID to its known devices /// Map bare JID to its known devices
Map<String, List<int>> _deviceList = {}; Map<String, List<int>> _deviceList = {};
/// Map bare JIDs to whether we already requested the device list once /// Map bare JIDs to whether we already requested the device list once
final Map<String, bool> _deviceListRequested = {}; final Map<String, bool> _deviceListRequested = {};
/// Map bare a ratchet key to its ratchet. Note that this is also locked by /// Map bare a ratchet key to its ratchet. Note that this is also locked by
/// _ratchetCriticalSectionLock. /// _ratchetCriticalSectionLock.
Map<RatchetMapKey, OmemoDoubleRatchet> _ratchetMap = {}; Map<RatchetMapKey, OmemoDoubleRatchet> _ratchetMap = {};
/// Map bare JID to whether we already tried to subscribe to the device list node. /// Map bare JID to whether we already tried to subscribe to the device list node.
final Map<String, bool> _subscriptionMap = {}; final Map<String, bool> _subscriptionMap = {};
/// For preventing a race condition in encryption/decryption /// For preventing a race condition in encryption/decryption
final Map<String, Queue<Completer<void>>> _ratchetCriticalSectionQueue = {}; final Map<String, Queue<Completer<void>>> _ratchetCriticalSectionQueue = {};
final Lock _ratchetCriticalSectionLock = Lock(); final Lock _ratchetCriticalSectionLock = Lock();
@ -91,15 +83,14 @@ class OmemoManager {
/// The OmemoManager's trust management /// The OmemoManager's trust management
final TrustManager _trustManager; final TrustManager _trustManager;
TrustManager get trustManager => _trustManager; TrustManager get trustManager => _trustManager;
/// Our own keys... /// Our own keys...
final Lock _deviceLock = Lock(); final Lock _deviceLock = Lock();
// ignore: prefer_final_fields // ignore: prefer_final_fields
OmemoDevice _device; OmemoDevice _device;
/// The event bus of the session manager /// The event bus of the session manager
final StreamController<OmemoEvent> _eventStreamController = final StreamController<OmemoEvent> _eventStreamController = StreamController<OmemoEvent>.broadcast();
StreamController<OmemoEvent>.broadcast();
Stream<OmemoEvent> get eventStream => _eventStreamController.stream; Stream<OmemoEvent> get eventStream => _eventStreamController.stream;
/// Enter the critical section for performing cryptographic operations on the ratchets /// Enter the critical section for performing cryptographic operations on the ratchets
@ -119,7 +110,7 @@ class OmemoManager {
await completer.future; await completer.future;
} }
} }
/// Leave the critical section for the ratchets. /// Leave the critical section for the ratchets.
Future<void> _leaveRatchetCriticalSection(String jid) async { Future<void> _leaveRatchetCriticalSection(String jid) async {
await _ratchetCriticalSectionLock.synchronized(() { await _ratchetCriticalSectionLock.synchronized(() {
@ -133,30 +124,22 @@ class OmemoManager {
}); });
} }
Future<String?> _decryptAndVerifyHmac( Future<String?> _decryptAndVerifyHmac(List<int>? ciphertext, List<int> keyAndHmac) async {
List<int>? ciphertext,
List<int> keyAndHmac,
) async {
// Empty OMEMO messages should just have the key decrypted and/or session set up. // Empty OMEMO messages should just have the key decrypted and/or session set up.
if (ciphertext == null) { if (ciphertext == null) {
return null; return null;
} }
final key = keyAndHmac.sublist(0, 32); final key = keyAndHmac.sublist(0, 32);
final hmac = keyAndHmac.sublist(32, 48); final hmac = keyAndHmac.sublist(32, 48);
final derivedKeys = await deriveEncryptionKeys(key, omemoPayloadInfoString); final derivedKeys = await deriveEncryptionKeys(key, omemoPayloadInfoString);
final computedHmac = final computedHmac = await truncatedHmac(ciphertext, derivedKeys.authenticationKey);
await truncatedHmac(ciphertext, derivedKeys.authenticationKey);
if (!listsEqual(hmac, computedHmac)) { if (!listsEqual(hmac, computedHmac)) {
throw InvalidMessageHMACException(); throw InvalidMessageHMACException();
} }
return utf8.decode( return utf8.decode(
await aes256CbcDecrypt( await aes256CbcDecrypt(ciphertext, derivedKeys.encryptionKey, derivedKeys.iv),
ciphertext,
derivedKeys.encryptionKey,
derivedKeys.iv,
),
); );
} }
@ -184,18 +167,13 @@ class OmemoManager {
_ratchetMap[key] = ratchet; _ratchetMap[key] = ratchet;
// Commit the ratchet // Commit the ratchet
_eventStreamController _eventStreamController.add(RatchetModifiedEvent(jid, deviceId, ratchet, true, false));
.add(RatchetModifiedEvent(jid, deviceId, ratchet, true, false));
} }
/// Build a new session with the user at [jid] with the device [deviceId] using data /// Build a new session with the user at [jid] with the device [deviceId] using data
/// from the key exchange [kex]. In case [kex] contains an unknown Signed Prekey /// from the key exchange [kex]. In case [kex] contains an unknown Signed Prekey
/// identifier an UnknownSignedPrekeyException will be thrown. /// identifier an UnknownSignedPrekeyException will be thrown.
Future<OmemoDoubleRatchet> _addSessionFromKeyExchange( Future<OmemoDoubleRatchet> _addSessionFromKeyExchange(String jid, int deviceId, OmemoKeyExchange kex) async {
String jid,
int deviceId,
OmemoKeyExchange kex,
) async {
// Pick the correct SPK // Pick the correct SPK
final device = await getDevice(); final device = await getDevice();
OmemoKeyPair spk; OmemoKeyPair spk;
@ -225,20 +203,13 @@ class OmemoManager {
getTimestamp(), getTimestamp(),
); );
// Notify the trust manager
await trustManager.onNewSession(jid, deviceId);
return ratchet; return ratchet;
} }
/// Create a ratchet session initiated by Alice to the user with Jid [jid] and the device /// Create a ratchet session initiated by Alice to the user with Jid [jid] and the device
/// [deviceId] from the bundle [bundle]. /// [deviceId] from the bundle [bundle].
@visibleForTesting @visibleForTesting
Future<OmemoKeyExchange> addSessionFromBundle( Future<OmemoKeyExchange> addSessionFromBundle(String jid, int deviceId, OmemoBundle bundle) async {
String jid,
int deviceId,
OmemoBundle bundle,
) async {
final device = await getDevice(); final device = await getDevice();
final kexResult = await x3dhFromBundle( final kexResult = await x3dhFromBundle(
bundle, bundle,
@ -261,15 +232,13 @@ class OmemoManager {
..ik = await device.ik.pk.getBytes() ..ik = await device.ik.pk.getBytes()
..ek = await kexResult.ek.pk.getBytes(); ..ek = await kexResult.ek.pk.getBytes();
} }
/// In case a decryption error occurs, the Double Ratchet spec says to just restore /// In case a decryption error occurs, the Double Ratchet spec says to just restore
/// the ratchet to its old state. As such, this function restores the ratchet at /// the ratchet to its old state. As such, this function restores the ratchet at
/// [mapKey] with [oldRatchet]. /// [mapKey] with [oldRatchet].
/// NOTE: Must be called from within the ratchet critical section /// NOTE: Must be called from within the ratchet critical section
void _restoreRatchet(RatchetMapKey mapKey, OmemoDoubleRatchet oldRatchet) { void _restoreRatchet(RatchetMapKey mapKey, OmemoDoubleRatchet oldRatchet) {
_log.finest( _log.finest('Restoring ratchet ${mapKey.jid}:${mapKey.deviceId} to ${oldRatchet.nr}');
'Restoring ratchet ${mapKey.jid}:${mapKey.deviceId} to ${oldRatchet.nr}',
);
_ratchetMap[mapKey] = oldRatchet; _ratchetMap[mapKey] = oldRatchet;
// Commit the ratchet // Commit the ratchet
@ -283,7 +252,7 @@ class OmemoManager {
), ),
); );
} }
/// Attempt to decrypt [ciphertext]. [keys] refers to the <key /> elements inside the /// Attempt to decrypt [ciphertext]. [keys] refers to the <key /> elements inside the
/// <keys /> element with a "jid" attribute matching our own. [senderJid] refers to the /// <keys /> element with a "jid" attribute matching our own. [senderJid] refers to the
/// bare Jid of the sender. [senderDeviceId] refers to the "sid" attribute of the /// bare Jid of the sender. [senderDeviceId] refers to the "sid" attribute of the
@ -296,20 +265,14 @@ class OmemoManager {
/// element, then [ciphertext] must be set to null. In this case, this function /// element, then [ciphertext] must be set to null. In this case, this function
/// will return null as there is no message to be decrypted. This, however, is used /// will return null as there is no message to be decrypted. This, however, is used
/// to set up sessions or advance the ratchets. /// to set up sessions or advance the ratchets.
Future<_InternalDecryptionResult> _decryptMessage( Future<_InternalDecryptionResult> _decryptMessage(List<int>? ciphertext, String senderJid, int senderDeviceId, List<EncryptedKey> keys, int timestamp) async {
List<int>? ciphertext,
String senderJid,
int senderDeviceId,
List<EncryptedKey> keys,
int timestamp,
) async {
// Try to find a session we can decrypt with. // Try to find a session we can decrypt with.
var device = await getDevice(); var device = await getDevice();
final rawKey = keys.firstWhereOrNull((key) => key.rid == device.id); final rawKey = keys.firstWhereOrNull((key) => key.rid == device.id);
if (rawKey == null) { if (rawKey == null) {
throw NotEncryptedForDeviceException(); throw NotEncryptedForDeviceException();
} }
final decodedRawKey = base64.decode(rawKey.value); final decodedRawKey = base64.decode(rawKey.value);
List<int>? keyAndHmac; List<int>? keyAndHmac;
OmemoAuthenticatedMessage authMessage; OmemoAuthenticatedMessage authMessage;
@ -326,21 +289,17 @@ class OmemoManager {
// Guard against old key exchanges // Guard against old key exchanges
if (oldRatchet != null) { if (oldRatchet != null) {
_log.finest( _log.finest('KEX for existent ratchet ${ratchetKey.toJsonKey()}. ${oldRatchet.kexTimestamp} > $timestamp: ${oldRatchet.kexTimestamp > timestamp}');
'KEX for existent ratchet ${ratchetKey.toJsonKey()}. ${oldRatchet.kexTimestamp} > $timestamp: ${oldRatchet.kexTimestamp > timestamp}',
);
if (oldRatchet.kexTimestamp > timestamp) { if (oldRatchet.kexTimestamp > timestamp) {
throw InvalidKeyExchangeException(); throw InvalidKeyExchangeException();
} }
} }
final r = final r = await _addSessionFromKeyExchange(senderJid, senderDeviceId, kex);
await _addSessionFromKeyExchange(senderJid, senderDeviceId, kex);
// Try to decrypt with the new ratchet r // Try to decrypt with the new ratchet r
try { try {
keyAndHmac = keyAndHmac = await r.ratchetDecrypt(message, authMessage.writeToBuffer());
await r.ratchetDecrypt(message, authMessage.writeToBuffer());
final result = await _decryptAndVerifyHmac(ciphertext, keyAndHmac); final result = await _decryptAndVerifyHmac(ciphertext, keyAndHmac);
// Add the new ratchet // Add the new ratchet
@ -377,21 +336,20 @@ class OmemoManager {
authMessage = OmemoAuthenticatedMessage.fromBuffer(decodedRawKey); authMessage = OmemoAuthenticatedMessage.fromBuffer(decodedRawKey);
message = OmemoMessage.fromBuffer(authMessage.message!); message = OmemoMessage.fromBuffer(authMessage.message!);
} }
final devices = _deviceList[senderJid]; final devices = _deviceList[senderJid];
if (devices?.contains(senderDeviceId) != true) { if (devices?.contains(senderDeviceId) != true) {
throw NoDecryptionKeyException(); throw NoDecryptionKeyException();
} }
// TODO(PapaTutuWawa): When receiving a message that is not an OMEMOKeyExchange from a device there is no session with, clients SHOULD create a session with that device and notify it about the new session by responding with an empty OMEMO message as per Sending a message. // TODO(PapaTutuWawa): When receiving a message that is not an OMEMOKeyExchange from a device there is no session with, clients SHOULD create a session with that device and notify it about the new session by responding with an empty OMEMO message as per Sending a message.
// We can guarantee that the ratchet exists at this point in time // We can guarantee that the ratchet exists at this point in time
final ratchet = getRatchet(ratchetKey)!; final ratchet = getRatchet(ratchetKey)!;
try { try {
if (rawKey.kex) { if (rawKey.kex) {
keyAndHmac = keyAndHmac = await ratchet.ratchetDecrypt(message, authMessage.writeToBuffer());
await ratchet.ratchetDecrypt(message, authMessage.writeToBuffer());
} else { } else {
keyAndHmac = await ratchet.ratchetDecrypt(message, decodedRawKey); keyAndHmac = await ratchet.ratchetDecrypt(message, decodedRawKey);
} }
@ -417,7 +375,7 @@ class OmemoManager {
false, false,
await _decryptAndVerifyHmac(ciphertext, keyAndHmac), await _decryptAndVerifyHmac(ciphertext, keyAndHmac),
); );
} catch (_) { } catch (_) {
_restoreRatchet(ratchetKey, oldRatchet!); _restoreRatchet(ratchetKey, oldRatchet!);
rethrow; rethrow;
} }
@ -432,25 +390,25 @@ class OmemoManager {
Future<List<OmemoBundle>> _fetchNewBundles(String jid) async { Future<List<OmemoBundle>> _fetchNewBundles(String jid) async {
// Check if we already requested the device list for [jid] // Check if we already requested the device list for [jid]
List<int> bundlesToFetch; List<int> bundlesToFetch;
if (!_deviceListRequested.containsKey(jid) || if (!_deviceListRequested.containsKey(jid) || !_deviceList.containsKey(jid)) {
!_deviceList.containsKey(jid)) {
// We don't have an up-to-date version of the device list // We don't have an up-to-date version of the device list
final newDeviceList = await fetchDeviceListImpl(jid); final newDeviceList = await fetchDeviceListImpl(jid);
if (newDeviceList == null) return []; if (newDeviceList == null) return [];
_deviceList[jid] = newDeviceList; _deviceList[jid] = newDeviceList;
bundlesToFetch = newDeviceList.where((id) { bundlesToFetch = newDeviceList
return !_ratchetMap.containsKey(RatchetMapKey(jid, id)) || .where((id) {
_deviceList[jid]?.contains(id) == false; return !_ratchetMap.containsKey(RatchetMapKey(jid, id)) ||
}).toList(); _deviceList[jid]?.contains(id) == false;
}).toList();
// Trigger an event with the new device list // Trigger an event with the new device list
_eventStreamController.add(DeviceListModifiedEvent(_deviceList)); _eventStreamController.add(DeviceListModifiedEvent(_deviceList));
} else { } else {
// We already have an up-to-date version of the device list // We already have an up-to-date version of the device list
bundlesToFetch = _deviceList[jid]! bundlesToFetch = _deviceList[jid]!
.where((id) => !_ratchetMap.containsKey(RatchetMapKey(jid, id))) .where((id) => !_ratchetMap.containsKey(RatchetMapKey(jid, id)))
.toList(); .toList();
} }
if (bundlesToFetch.isNotEmpty) { if (bundlesToFetch.isNotEmpty) {
@ -468,7 +426,7 @@ class OmemoManager {
return newBundles; return newBundles;
} }
/// Encrypt the key [plaintext] for all known bundles of the Jids in [jids]. Returns a /// Encrypt the key [plaintext] for all known bundles of the Jids in [jids]. Returns a
/// map that maps the device Id to the ciphertext of [plaintext]. /// map that maps the device Id to the ciphertext of [plaintext].
/// ///
@ -476,10 +434,7 @@ class OmemoManager {
/// does not contain a <payload /> element. This means that the ciphertext attribute of /// does not contain a <payload /> element. This means that the ciphertext attribute of
/// the result will be null as well. /// the result will be null as well.
/// NOTE: Must be called within the ratchet critical section /// NOTE: Must be called within the ratchet critical section
Future<EncryptionResult> _encryptToJids( Future<EncryptionResult> _encryptToJids(List<String> jids, String? plaintext) async {
List<String> jids,
String? plaintext,
) async {
final encryptedKeys = List<EncryptedKey>.empty(growable: true); final encryptedKeys = List<EncryptedKey>.empty(growable: true);
var ciphertext = const <int>[]; var ciphertext = const <int>[];
@ -540,14 +495,12 @@ class OmemoManager {
var ratchet = _ratchetMap[ratchetKey]; var ratchet = _ratchetMap[ratchetKey];
if (ratchet == null) { if (ratchet == null) {
_log.severe('Ratchet ${ratchetKey.toJsonKey()} does not exist.'); _log.severe('Ratchet ${ratchetKey.toJsonKey()} does not exist.');
deviceEncryptionErrors[ratchetKey] = deviceEncryptionErrors[ratchetKey] = NoKeyMaterialAvailableException();
NoKeyMaterialAvailableException();
continue; continue;
} }
final ciphertext = final ciphertext = (await ratchet.ratchetEncrypt(keyPayload)).ciphertext;
(await ratchet.ratchetEncrypt(keyPayload)).ciphertext;
if (kex.containsKey(ratchetKey)) { if (kex.containsKey(ratchetKey)) {
// The ratchet did not exist // The ratchet did not exist
final k = kex[ratchetKey]! final k = kex[ratchetKey]!
@ -567,10 +520,9 @@ class OmemoManager {
} else if (!ratchet.acknowledged) { } else if (!ratchet.acknowledged) {
// The ratchet exists but is not acked // The ratchet exists but is not acked
if (ratchet.kex != null) { if (ratchet.kex != null) {
final oldKex = final oldKex = OmemoKeyExchange.fromBuffer(base64.decode(ratchet.kex!))
OmemoKeyExchange.fromBuffer(base64.decode(ratchet.kex!)) ..message = OmemoAuthenticatedMessage.fromBuffer(ciphertext);
..message = OmemoAuthenticatedMessage.fromBuffer(ciphertext);
encryptedKeys.add( encryptedKeys.add(
EncryptedKey( EncryptedKey(
jid, jid,
@ -581,9 +533,7 @@ class OmemoManager {
); );
} else { } else {
// The ratchet is not acked but we don't have the old key exchange // The ratchet is not acked but we don't have the old key exchange
_log.warning( _log.warning('Ratchet for $jid:$deviceId is not acked but the kex attribute is null');
'Ratchet for $jid:$deviceId is not acked but the kex attribute is null',
);
encryptedKeys.add( encryptedKeys.add(
EncryptedKey( EncryptedKey(
jid, jid,
@ -606,13 +556,13 @@ class OmemoManager {
} }
// Commit the ratchet // Commit the ratchet
_eventStreamController _eventStreamController.add(RatchetModifiedEvent(jid, deviceId, ratchet, false, false));
.add(RatchetModifiedEvent(jid, deviceId, ratchet, false, false));
} }
} }
return EncryptionResult( return EncryptionResult(
plaintext != null ? ciphertext : null, plaintext != null ?
ciphertext : null,
encryptedKeys, encryptedKeys,
deviceEncryptionErrors, deviceEncryptionErrors,
jidEncryptionErrors, jidEncryptionErrors,
@ -628,13 +578,14 @@ class OmemoManager {
unawaited(subscribeToDeviceListNodeImpl(stanza.bareSenderJid)); unawaited(subscribeToDeviceListNodeImpl(stanza.bareSenderJid));
_subscriptionMap[stanza.bareSenderJid] = true; _subscriptionMap[stanza.bareSenderJid] = true;
} }
final ratchetKey = final ratchetKey = RatchetMapKey(stanza.bareSenderJid, stanza.senderDeviceId);
RatchetMapKey(stanza.bareSenderJid, stanza.senderDeviceId);
final _InternalDecryptionResult result; final _InternalDecryptionResult result;
try { try {
result = await _decryptMessage( result = await _decryptMessage(
stanza.payload != null ? base64.decode(stanza.payload!) : null, stanza.payload != null ?
base64.decode(stanza.payload!) :
null,
stanza.bareSenderJid, stanza.bareSenderJid,
stanza.senderDeviceId, stanza.senderDeviceId,
stanza.keys, stanza.keys,
@ -650,10 +601,7 @@ class OmemoManager {
// Check if the ratchet is acked // Check if the ratchet is acked
final ratchet = getRatchet(ratchetKey); final ratchet = getRatchet(ratchetKey);
assert( assert(ratchet != null, 'We decrypted the message, so the ratchet must exist');
ratchet != null,
'We decrypted the message, so the ratchet must exist',
);
if (ratchet!.acknowledged) { if (ratchet!.acknowledged) {
// Ratchet is acknowledged // Ratchet is acknowledged
@ -723,26 +671,20 @@ class OmemoManager {
); );
await sendEmptyOmemoMessageImpl(result, jid); await sendEmptyOmemoMessageImpl(result, jid);
} }
/// Mark the ratchet for device [deviceId] from [jid] as acked. /// Mark the ratchet for device [deviceId] from [jid] as acked.
Future<void> ratchetAcknowledged( Future<void> ratchetAcknowledged(String jid, int deviceId, { bool enterCriticalSection = true }) async {
String jid,
int deviceId, {
bool enterCriticalSection = true,
}) async {
if (enterCriticalSection) await _enterRatchetCriticalSection(jid); if (enterCriticalSection) await _enterRatchetCriticalSection(jid);
final key = RatchetMapKey(jid, deviceId); final key = RatchetMapKey(jid, deviceId);
if (_ratchetMap.containsKey(key)) { if (_ratchetMap.containsKey(key)) {
final ratchet = _ratchetMap[key]!..acknowledged = true; final ratchet = _ratchetMap[key]!
..acknowledged = true;
// Commit it // Commit it
_eventStreamController _eventStreamController.add(RatchetModifiedEvent(jid, deviceId, ratchet, false, false));
.add(RatchetModifiedEvent(jid, deviceId, ratchet, false, false));
} else { } else {
_log.severe( _log.severe('Attempted to acknowledge ratchet ${key.toJsonKey()}, even though it does not exist');
'Attempted to acknowledge ratchet ${key.toJsonKey()}, even though it does not exist',
);
} }
if (enterCriticalSection) await _leaveRatchetCriticalSection(jid); if (enterCriticalSection) await _leaveRatchetCriticalSection(jid);
@ -758,7 +700,7 @@ class OmemoManager {
_eventStreamController.add(DeviceModifiedEvent(_device)); _eventStreamController.add(DeviceModifiedEvent(_device));
}); });
} }
/// Returns the device used for encryption and decryption. /// Returns the device used for encryption and decryption.
Future<OmemoDevice> getDevice() => _deviceLock.synchronized(() => _device); Future<OmemoDevice> getDevice() => _deviceLock.synchronized(() => _device);
@ -769,19 +711,18 @@ class OmemoManager {
Future<OmemoBundle> getDeviceBundle() async => (await getDevice()).toBundle(); Future<OmemoBundle> getDeviceBundle() async => (await getDevice()).toBundle();
/// Directly aquire the current device's fingerprint. /// Directly aquire the current device's fingerprint.
Future<String> getDeviceFingerprint() async => Future<String> getDeviceFingerprint() async => (await getDevice()).getFingerprint();
(await getDevice()).getFingerprint();
/// Returns the fingerprints for all devices of [jid] that we have a session with. /// Returns the fingerprints for all devices of [jid] that we have a session with.
/// If there are not sessions with [jid], then returns null. /// If there are not sessions with [jid], then returns null.
Future<List<DeviceFingerprint>?> getFingerprintsForJid(String jid) async { Future<List<DeviceFingerprint>?> getFingerprintsForJid(String jid) async {
if (!_deviceList.containsKey(jid)) return null; if (!_deviceList.containsKey(jid)) return null;
await _enterRatchetCriticalSection(jid); await _enterRatchetCriticalSection(jid);
final fingerprintKeys = _deviceList[jid]! final fingerprintKeys = _deviceList[jid]!
.map((id) => RatchetMapKey(jid, id)) .map((id) => RatchetMapKey(jid, id))
.where((key) => _ratchetMap.containsKey(key)); .where((key) => _ratchetMap.containsKey(key));
final fingerprints = List<DeviceFingerprint>.empty(growable: true); final fingerprints = List<DeviceFingerprint>.empty(growable: true);
for (final key in fingerprintKeys) { for (final key in fingerprintKeys) {
@ -797,7 +738,7 @@ class OmemoManager {
await _leaveRatchetCriticalSection(jid); await _leaveRatchetCriticalSection(jid);
return fingerprints; return fingerprints;
} }
/// Ensures that the device list is fetched again on the next message sending. /// Ensures that the device list is fetched again on the next message sending.
void onNewConnection() { void onNewConnection() {
_deviceListRequested.clear(); _deviceListRequested.clear();
@ -813,10 +754,7 @@ class OmemoManager {
_eventStreamController.add(DeviceListModifiedEvent(_deviceList)); _eventStreamController.add(DeviceListModifiedEvent(_deviceList));
} }
void initialize( void initialize(Map<RatchetMapKey, OmemoDoubleRatchet> ratchetMap, Map<String, List<int>> deviceList) {
Map<RatchetMapKey, OmemoDoubleRatchet> ratchetMap,
Map<String, List<int>> deviceList,
) {
_deviceList = deviceList; _deviceList = deviceList;
_ratchetMap = ratchetMap; _ratchetMap = ratchetMap;
} }
@ -841,7 +779,7 @@ class OmemoManager {
// Remove trust decisions // Remove trust decisions
await _trustManager.removeTrustDecisionsForJid(jid); await _trustManager.removeTrustDecisionsForJid(jid);
await _leaveRatchetCriticalSection(jid); await _leaveRatchetCriticalSection(jid);
} }

View File

@ -20,12 +20,10 @@ class RatchetMapKey {
String toJsonKey() { String toJsonKey() {
return '$deviceId:$jid'; return '$deviceId:$jid';
} }
@override @override
bool operator ==(Object other) { bool operator ==(Object other) {
return other is RatchetMapKey && return other is RatchetMapKey && jid == other.jid && deviceId == other.deviceId;
jid == other.jid &&
deviceId == other.deviceId;
} }
@override @override

View File

@ -0,0 +1,679 @@
import 'dart:async';
import 'dart:convert';
import 'package:collection/collection.dart';
import 'package:cryptography/cryptography.dart';
import 'package:hex/hex.dart';
import 'package:logging/logging.dart';
import 'package:meta/meta.dart';
import 'package:omemo_dart/src/crypto.dart';
import 'package:omemo_dart/src/double_ratchet/double_ratchet.dart';
import 'package:omemo_dart/src/errors.dart';
import 'package:omemo_dart/src/helpers.dart';
import 'package:omemo_dart/src/keys.dart';
import 'package:omemo_dart/src/omemo/bundle.dart';
import 'package:omemo_dart/src/omemo/constants.dart';
import 'package:omemo_dart/src/omemo/device.dart';
import 'package:omemo_dart/src/omemo/encrypted_key.dart';
import 'package:omemo_dart/src/omemo/encryption_result.dart';
import 'package:omemo_dart/src/omemo/events.dart';
import 'package:omemo_dart/src/omemo/fingerprint.dart';
import 'package:omemo_dart/src/omemo/ratchet_map_key.dart';
import 'package:omemo_dart/src/protobuf/omemo_authenticated_message.dart';
import 'package:omemo_dart/src/protobuf/omemo_key_exchange.dart';
import 'package:omemo_dart/src/protobuf/omemo_message.dart';
import 'package:omemo_dart/src/trust/base.dart';
import 'package:omemo_dart/src/x3dh/x3dh.dart';
import 'package:synchronized/synchronized.dart';
@Deprecated('Use OmemoManager instead')
class OmemoSessionManager {
@Deprecated('Use OmemoManager instead')
OmemoSessionManager(this._device, this._deviceMap, this._ratchetMap, this._trustManager)
: _lock = Lock(),
_deviceLock = Lock(),
_eventStreamController = StreamController<OmemoEvent>.broadcast(),
_log = Logger('OmemoSessionManager');
/// Deserialise the OmemoSessionManager from JSON data [data] that does not contain
/// the ratchet sessions.
@Deprecated('Use OmemoManager instead')
factory OmemoSessionManager.fromJsonWithoutSessions(
Map<String, dynamic> data,
Map<RatchetMapKey, OmemoDoubleRatchet> ratchetMap,
TrustManager trustManager,
) {
// NOTE: Dart has some issues with just casting a List<dynamic> to List<Map<...>>, as
// such we need to convert the items by hand.
return OmemoSessionManager(
OmemoDevice.fromJson(data['device']! as Map<String, dynamic>),
(data['devices']! as Map<String, dynamic>).map<String, List<int>>(
(key, value) {
return MapEntry(
key,
(value as List<dynamic>).map<int>((i) => i as int).toList(),
);
}
),
ratchetMap,
trustManager,
);
}
/// Generate a new cryptographic identity.
static Future<OmemoSessionManager> generateNewIdentity(String jid, TrustManager trustManager, { int opkAmount = 100 }) async {
assert(opkAmount > 0, 'opkAmount must be bigger than 0.');
final device = await OmemoDevice.generateNewDevice(jid, opkAmount: opkAmount);
return OmemoSessionManager(device, {}, {}, trustManager);
}
/// Logging
Logger _log;
/// Lock for _ratchetMap and _bundleMap
final Lock _lock;
/// Mapping of the Device Id to its OMEMO session
final Map<RatchetMapKey, OmemoDoubleRatchet> _ratchetMap;
/// Mapping of a bare Jid to its Device Ids
final Map<String, List<int>> _deviceMap;
/// The event bus of the session manager
final StreamController<OmemoEvent> _eventStreamController;
/// Our own keys...
// ignore: prefer_final_fields
OmemoDevice _device;
/// and its lock
final Lock _deviceLock;
/// The trust manager
final TrustManager _trustManager;
TrustManager get trustManager => _trustManager;
/// A stream that receives events regarding the session
Stream<OmemoEvent> get eventStream => _eventStreamController.stream;
/// Returns our own device.
Future<OmemoDevice> getDevice() async {
return _deviceLock.synchronized(() => _device);
}
/// Returns the id attribute of our own device. This is just a short-hand for
/// ```await (session.getDevice()).id```.
Future<int> getDeviceId() async {
return _deviceLock.synchronized(() => _device.id);
}
/// Returns the device as an OmemoBundle. This is just a short-hand for
/// ```await (await session.getDevice()).toBundle()```.
Future<OmemoBundle> getDeviceBundle() async {
return _deviceLock.synchronized(() async => _device.toBundle());
}
/// Add a session [ratchet] with the [deviceId] to the internal tracking state.
Future<void> _addSession(String jid, int deviceId, OmemoDoubleRatchet ratchet) async {
await _lock.synchronized(() async {
// Add the bundle Id
if (!_deviceMap.containsKey(jid)) {
_deviceMap[jid] = [deviceId];
// Commit the device map
_eventStreamController.add(DeviceListModifiedEvent(_deviceMap));
} else {
// Prevent having the same device multiple times in the list
if (!_deviceMap[jid]!.contains(deviceId)) {
_deviceMap[jid]!.add(deviceId);
// Commit the device map
_eventStreamController.add(DeviceListModifiedEvent(_deviceMap));
}
}
// Add the ratchet session
final key = RatchetMapKey(jid, deviceId);
_ratchetMap[key] = ratchet;
// Commit the ratchet
_eventStreamController.add(RatchetModifiedEvent(jid, deviceId, ratchet, true, false));
});
}
/// Create a ratchet session initiated by Alice to the user with Jid [jid] and the device
/// [deviceId] from the bundle [bundle].
@visibleForTesting
Future<OmemoKeyExchange> addSessionFromBundle(String jid, int deviceId, OmemoBundle bundle) async {
final device = await getDevice();
final kexResult = await x3dhFromBundle(
bundle,
device.ik,
);
final ratchet = await OmemoDoubleRatchet.initiateNewSession(
bundle.spk,
bundle.ik,
kexResult.sk,
kexResult.ad,
getTimestamp(),
);
await _trustManager.onNewSession(jid, deviceId);
await _addSession(jid, deviceId, ratchet);
return OmemoKeyExchange()
..pkId = kexResult.opkId
..spkId = bundle.spkId
..ik = await device.ik.pk.getBytes()
..ek = await kexResult.ek.pk.getBytes();
}
/// Build a new session with the user at [jid] with the device [deviceId] using data
/// from the key exchange [kex]. In case [kex] contains an unknown Signed Prekey
/// identifier an UnknownSignedPrekeyException will be thrown.
Future<OmemoDoubleRatchet> _addSessionFromKeyExchange(String jid, int deviceId, OmemoKeyExchange kex) async {
// Pick the correct SPK
final device = await getDevice();
final spk = await _lock.synchronized(() async {
if (kex.spkId == _device.spkId) {
return _device.spk;
} else if (kex.spkId == _device.oldSpkId) {
return _device.oldSpk;
}
return null;
});
if (spk == null) {
throw UnknownSignedPrekeyException();
}
final kexResult = await x3dhFromInitialMessage(
X3DHMessage(
OmemoPublicKey.fromBytes(kex.ik!, KeyPairType.ed25519),
OmemoPublicKey.fromBytes(kex.ek!, KeyPairType.x25519),
kex.pkId!,
),
spk,
device.opks.values.elementAt(kex.pkId!),
device.ik,
);
final ratchet = await OmemoDoubleRatchet.acceptNewSession(
spk,
OmemoPublicKey.fromBytes(kex.ik!, KeyPairType.ed25519),
kexResult.sk,
kexResult.ad,
getTimestamp(),
);
return ratchet;
}
/// Like [encryptToJids] but only for one Jid [jid].
Future<EncryptionResult> encryptToJid(String jid, String? plaintext, { List<OmemoBundle>? newSessions }) {
return encryptToJids([jid], plaintext, newSessions: newSessions);
}
/// Encrypt the key [plaintext] for all known bundles of the Jids in [jids]. Returns a
/// map that maps the device Id to the ciphertext of [plaintext].
///
/// If [plaintext] is null, then the result will be an empty OMEMO message, i.e. one that
/// does not contain a <payload /> element. This means that the ciphertext attribute of
/// the result will be null as well.
Future<EncryptionResult> encryptToJids(List<String> jids, String? plaintext, { List<OmemoBundle>? newSessions }) async {
final encryptedKeys = List<EncryptedKey>.empty(growable: true);
var ciphertext = const <int>[];
var keyPayload = const <int>[];
if (plaintext != null) {
// Generate the key and encrypt the plaintext
final key = generateRandomBytes(32);
final keys = await deriveEncryptionKeys(key, omemoPayloadInfoString);
ciphertext = await aes256CbcEncrypt(
utf8.encode(plaintext),
keys.encryptionKey,
keys.iv,
);
final hmac = await truncatedHmac(ciphertext, keys.authenticationKey);
keyPayload = concat([key, hmac]);
} else {
keyPayload = List<int>.filled(32, 0x0);
}
final kex = <int, OmemoKeyExchange>{};
if (newSessions != null) {
for (final newSession in newSessions) {
kex[newSession.id] = await addSessionFromBundle(
newSession.jid,
newSession.id,
newSession,
);
}
}
await _lock.synchronized(() async {
// We assume that the user already checked if the session exists
for (final jid in jids) {
for (final deviceId in _deviceMap[jid]!) {
// Empty OMEMO messages are allowed to bypass trust
if (plaintext != null) {
// Only encrypt to devices that are trusted
if (!(await _trustManager.isTrusted(jid, deviceId))) continue;
// Onyl encrypt to devices that are enabled
if (!(await _trustManager.isEnabled(jid, deviceId))) continue;
}
final ratchetKey = RatchetMapKey(jid, deviceId);
var ratchet = _ratchetMap[ratchetKey]!;
final ciphertext = (await ratchet.ratchetEncrypt(keyPayload)).ciphertext;
if (kex.isNotEmpty && kex.containsKey(deviceId)) {
// The ratchet did not exist
final k = kex[deviceId]!
..message = OmemoAuthenticatedMessage.fromBuffer(ciphertext);
final buffer = base64.encode(k.writeToBuffer());
encryptedKeys.add(
EncryptedKey(
jid,
deviceId,
buffer,
true,
),
);
ratchet = ratchet.cloneWithKex(buffer);
_ratchetMap[ratchetKey] = ratchet;
} else if (!ratchet.acknowledged) {
// The ratchet exists but is not acked
if (ratchet.kex != null) {
final oldKex = OmemoKeyExchange.fromBuffer(base64.decode(ratchet.kex!))
..message = OmemoAuthenticatedMessage.fromBuffer(ciphertext);
encryptedKeys.add(
EncryptedKey(
jid,
deviceId,
base64.encode(oldKex.writeToBuffer()),
true,
),
);
} else {
// The ratchet is not acked but we don't have the old key exchange
_log.warning('Ratchet for $jid:$deviceId is not acked but the kex attribute is null');
encryptedKeys.add(
EncryptedKey(
jid,
deviceId,
base64.encode(ciphertext),
false,
),
);
}
} else {
// The ratchet exists and is acked
encryptedKeys.add(
EncryptedKey(
jid,
deviceId,
base64.encode(ciphertext),
false,
),
);
}
// Commit the ratchet
_eventStreamController.add(RatchetModifiedEvent(jid, deviceId, ratchet, false, false));
}
}
});
return EncryptionResult(
plaintext != null ? ciphertext : null,
encryptedKeys,
const <RatchetMapKey, OmemoException>{},
const <String, OmemoException>{},
);
}
/// In case a decryption error occurs, the Double Ratchet spec says to just restore
/// the ratchet to its old state. As such, this function restores the ratchet at
/// [mapKey] with [oldRatchet].
Future<void> _restoreRatchet(RatchetMapKey mapKey, OmemoDoubleRatchet oldRatchet) async {
await _lock.synchronized(() {
_log.finest('Restoring ratchet ${mapKey.jid}:${mapKey.deviceId} to ${oldRatchet.nr}');
_ratchetMap[mapKey] = oldRatchet;
// Commit the ratchet
_eventStreamController.add(
RatchetModifiedEvent(
mapKey.jid,
mapKey.deviceId,
oldRatchet,
false,
false,
),
);
});
}
Future<String?> _decryptAndVerifyHmac(List<int>? ciphertext, List<int> keyAndHmac) async {
// Empty OMEMO messages should just have the key decrypted and/or session set up.
if (ciphertext == null) {
return null;
}
final key = keyAndHmac.sublist(0, 32);
final hmac = keyAndHmac.sublist(32, 48);
final derivedKeys = await deriveEncryptionKeys(key, omemoPayloadInfoString);
final computedHmac = await truncatedHmac(ciphertext, derivedKeys.authenticationKey);
if (!listsEqual(hmac, computedHmac)) {
throw InvalidMessageHMACException();
}
return utf8.decode(
await aes256CbcDecrypt(ciphertext, derivedKeys.encryptionKey, derivedKeys.iv),
);
}
/// Attempt to decrypt [ciphertext]. [keys] refers to the <key /> elements inside the
/// <keys /> element with a "jid" attribute matching our own. [senderJid] refers to the
/// bare Jid of the sender. [senderDeviceId] refers to the "sid" attribute of the
/// <encrypted /> element.
/// [timestamp] refers to the time the message was sent. This might be either what the
/// server tells you via "XEP-0203: Delayed Delivery" or the point in time at which
/// you received the stanza, if no Delayed Delivery element was found.
///
/// If the received message is an empty OMEMO message, i.e. there is no <payload />
/// element, then [ciphertext] must be set to null. In this case, this function
/// will return null as there is no message to be decrypted. This, however, is used
/// to set up sessions or advance the ratchets.
Future<String?> decryptMessage(List<int>? ciphertext, String senderJid, int senderDeviceId, List<EncryptedKey> keys, int timestamp) async {
// Try to find a session we can decrypt with.
var device = await getDevice();
final rawKey = keys.firstWhereOrNull((key) => key.rid == device.id);
if (rawKey == null) {
throw NotEncryptedForDeviceException();
}
final ratchetKey = RatchetMapKey(senderJid, senderDeviceId);
final decodedRawKey = base64.decode(rawKey.value);
List<int>? keyAndHmac;
OmemoAuthenticatedMessage authMessage;
OmemoDoubleRatchet? oldRatchet;
OmemoMessage? message;
if (rawKey.kex) {
// If the ratchet already existed, we store it. If it didn't, oldRatchet will stay
// null.
final oldRatchet = (await _getRatchet(ratchetKey))?.clone();
final kex = OmemoKeyExchange.fromBuffer(decodedRawKey);
authMessage = kex.message!;
message = OmemoMessage.fromBuffer(authMessage.message!);
// Guard against old key exchanges
if (oldRatchet != null) {
_log.finest('KEX for existent ratchet. ${oldRatchet.pn}');
if (oldRatchet.kexTimestamp > timestamp) {
throw InvalidKeyExchangeException();
}
// Try to decrypt it
try {
final decrypted = await oldRatchet.ratchetDecrypt(message, authMessage.writeToBuffer());
// Commit the ratchet
_eventStreamController.add(
RatchetModifiedEvent(
senderJid,
senderDeviceId,
oldRatchet,
false,
false,
),
);
final plaintext = await _decryptAndVerifyHmac(
ciphertext,
decrypted,
);
await _addSession(senderJid, senderDeviceId, oldRatchet);
return plaintext;
} catch (_) {
_log.finest('Failed to use old ratchet with KEX for existing ratchet');
}
}
final r = await _addSessionFromKeyExchange(senderJid, senderDeviceId, kex);
await _trustManager.onNewSession(senderJid, senderDeviceId);
await _addSession(senderJid, senderDeviceId, r);
// Replace the OPK
// TODO(PapaTutuWawa): Replace the OPK when we know that the KEX worked
await _deviceLock.synchronized(() async {
device = await device.replaceOnetimePrekey(kex.pkId!);
// Commit the device
_eventStreamController.add(DeviceModifiedEvent(device));
});
} else {
authMessage = OmemoAuthenticatedMessage.fromBuffer(decodedRawKey);
message = OmemoMessage.fromBuffer(authMessage.message!);
}
final devices = _deviceMap[senderJid];
if (devices == null) {
throw NoDecryptionKeyException();
}
if (!devices.contains(senderDeviceId)) {
throw NoDecryptionKeyException();
}
// We can guarantee that the ratchet exists at this point in time
final ratchet = (await _getRatchet(ratchetKey))!;
oldRatchet ??= ratchet.clone();
try {
if (rawKey.kex) {
keyAndHmac = await ratchet.ratchetDecrypt(message, authMessage.writeToBuffer());
} else {
keyAndHmac = await ratchet.ratchetDecrypt(message, decodedRawKey);
}
} catch (_) {
await _restoreRatchet(ratchetKey, oldRatchet);
rethrow;
}
// Commit the ratchet
_eventStreamController.add(
RatchetModifiedEvent(
senderJid,
senderDeviceId,
ratchet,
false,
false,
),
);
try {
return _decryptAndVerifyHmac(ciphertext, keyAndHmac);
} catch (_) {
await _restoreRatchet(ratchetKey, oldRatchet);
rethrow;
}
}
/// Returns the list of hex-encoded fingerprints we have for sessions with [jid].
Future<List<DeviceFingerprint>> getHexFingerprintsForJid(String jid) async {
final fingerprints = List<DeviceFingerprint>.empty(growable: true);
await _lock.synchronized(() async {
// Get devices for jid
final devices = _deviceMap[jid] ?? [];
for (final deviceId in devices) {
final ratchet = _ratchetMap[RatchetMapKey(jid, deviceId)]!;
fingerprints.add(
DeviceFingerprint(
deviceId,
HEX.encode(await ratchet.ik.getBytes()),
),
);
}
});
return fingerprints;
}
/// Returns the hex-encoded fingerprint of the current device.
Future<DeviceFingerprint> getHexFingerprintForDevice() async {
final device = await getDevice();
return DeviceFingerprint(
device.id,
HEX.encode(await device.ik.pk.getBytes()),
);
}
/// Replaces the Signed Prekey and its signature in our own device bundle. Triggers
/// a DeviceModifiedEvent when done.
/// See https://xmpp.org/extensions/xep-0384.html#protocol-key_exchange under the point
/// "signed PreKey rotation period" for recommendations.
Future<void> rotateSignedPrekey() async {
await _deviceLock.synchronized(() async {
_device = await _device.replaceSignedPrekey();
// Commit the new device
_eventStreamController.add(DeviceModifiedEvent(_device));
});
}
/// Returns the device map, i.e. the mapping of bare Jid to its device identifiers
/// we have built sessions with.
Future<Map<String, List<int>>> getDeviceMap() async {
return _lock.synchronized(() => _deviceMap);
}
/// Removes the ratchet identified by [jid] and [deviceId] from the session manager.
/// Also triggers events for commiting the new device map to storage and removing
/// the old ratchet.
Future<void> removeRatchet(String jid, int deviceId) async {
await _lock.synchronized(() async {
// Remove the ratchet
_ratchetMap.remove(RatchetMapKey(jid, deviceId));
// Commit it
_eventStreamController.add(RatchetRemovedEvent(jid, deviceId));
// Remove the device from jid
_deviceMap[jid]!.remove(deviceId);
if (_deviceMap[jid]!.isEmpty) {
_deviceMap.remove(jid);
}
// Commit it
_eventStreamController.add(DeviceListModifiedEvent(_deviceMap));
});
}
/// Removes all ratchets for Jid [jid]. Triggers a DeviceMapModified event at the end and an
/// RatchetRemovedEvent for each ratchet.
Future<void> removeAllRatchets(String jid) async {
await _lock.synchronized(() async {
for (final deviceId in _deviceMap[jid]!) {
// Remove the ratchet
_ratchetMap.remove(RatchetMapKey(jid, deviceId));
// Commit it
_eventStreamController.add(RatchetRemovedEvent(jid, deviceId));
}
// Remove the device from jid
_deviceMap.remove(jid);
// Commit it
_eventStreamController.add(DeviceListModifiedEvent(_deviceMap));
});
}
/// Returns the list of device identifiers belonging to [jid] that are yet unacked, i.e.
/// we have not yet received an empty OMEMO message from.
Future<List<int>?> getUnacknowledgedRatchets(String jid) async {
return _lock.synchronized(() async {
final ret = List<int>.empty(growable: true);
final devices = _deviceMap[jid];
if (devices == null) return null;
for (final device in devices) {
final ratchet = _ratchetMap[RatchetMapKey(jid, device)]!;
if (!ratchet.acknowledged) ret.add(device);
}
return ret;
});
}
/// Returns true if the ratchet for [jid] with device identifier [deviceId] is
/// acknowledged. Returns false if not.
Future<bool> isRatchetAcknowledged(String jid, int deviceId) async {
return _lock.synchronized(() => _ratchetMap[RatchetMapKey(jid, deviceId)]!.acknowledged);
}
/// Mark the ratchet for device [deviceId] from [jid] as acked.
Future<void> ratchetAcknowledged(String jid, int deviceId) async {
await _lock.synchronized(() async {
final ratchet = _ratchetMap[RatchetMapKey(jid, deviceId)]!
..acknowledged = true;
// Commit it
_eventStreamController.add(RatchetModifiedEvent(jid, deviceId, ratchet, false, false));
});
}
/// Generates an entirely new device. May be useful when the user wants to reset their cryptographic
/// identity. Triggers an event to commit it to storage.
Future<void> regenerateDevice({ int opkAmount = 100 }) async {
await _deviceLock.synchronized(() async {
_device = await OmemoDevice.generateNewDevice(_device.jid, opkAmount: opkAmount);
// Commit it
_eventStreamController.add(DeviceModifiedEvent(_device));
});
}
/// Make our device have a new identifier. Only useful before publishing it as a bundle
/// to make sure that our device has a id that is account unique.
Future<void> regenerateDeviceId() async {
await _deviceLock.synchronized(() async {
_device = _device.withNewId();
// Commit it
_eventStreamController.add(DeviceModifiedEvent(_device));
});
}
Future<OmemoDoubleRatchet?> _getRatchet(RatchetMapKey key) async {
return _lock.synchronized(() async {
return _ratchetMap[key];
});
}
@visibleForTesting
OmemoDoubleRatchet getRatchet(String jid, int deviceId) => _ratchetMap[RatchetMapKey(jid, deviceId)]!;
@visibleForTesting
Map<RatchetMapKey, OmemoDoubleRatchet> getRatchetMap() => _ratchetMap;
/// Serialise the entire session manager into a JSON object.
Future<Map<String, dynamic>> toJsonWithoutSessions() async {
/*
{
'devices': {
'alice@...': [1, 2, ...],
'bob@...': [1],
...
},
'device': { ... },
}
*/
return {
'devices': _deviceMap,
'device': await (await getDevice()).toJson(),
};
}
}

View File

@ -2,11 +2,12 @@ import 'package:omemo_dart/src/helpers.dart';
import 'package:omemo_dart/src/protobuf/protobuf.dart'; import 'package:omemo_dart/src/protobuf/protobuf.dart';
class OmemoAuthenticatedMessage { class OmemoAuthenticatedMessage {
OmemoAuthenticatedMessage(); OmemoAuthenticatedMessage();
factory OmemoAuthenticatedMessage.fromBuffer(List<int> data) { factory OmemoAuthenticatedMessage.fromBuffer(List<int> data) {
var i = 0; var i = 0;
// required bytes mac = 1; // required bytes mac = 1;
if (data[0] != fieldId(1, fieldTypeByteArray)) { if (data[0] != fieldId(1, fieldTypeByteArray)) {
throw Exception(); throw Exception();
@ -23,7 +24,7 @@ class OmemoAuthenticatedMessage {
..mac = mac ..mac = mac
..message = message; ..message = message;
} }
List<int>? mac; List<int>? mac;
List<int>? message; List<int>? message;

View File

@ -46,7 +46,7 @@ class OmemoKeyExchange {
..ek = ek ..ek = ek
..message = message; ..message = message;
} }
int? pkId; int? pkId;
int? spkId; int? spkId;
List<int>? ik; List<int>? ik;

View File

@ -2,11 +2,12 @@ import 'package:omemo_dart/src/helpers.dart';
import 'package:omemo_dart/src/protobuf/protobuf.dart'; import 'package:omemo_dart/src/protobuf/protobuf.dart';
class OmemoMessage { class OmemoMessage {
OmemoMessage(); OmemoMessage();
factory OmemoMessage.fromBuffer(List<int> data) { factory OmemoMessage.fromBuffer(List<int> data) {
var i = 0; var i = 0;
// required uint32 n = 1; // required uint32 n = 1;
if (data[0] != fieldId(1, fieldTypeUint32)) { if (data[0] != fieldId(1, fieldTypeUint32)) {
throw Exception(); throw Exception();

View File

@ -13,6 +13,7 @@ int fieldId(int number, int type) {
} }
class VarintDecode { class VarintDecode {
const VarintDecode(this.n, this.length); const VarintDecode(this.n, this.length);
final int n; final int n;
final int length; final int length;

View File

@ -18,9 +18,9 @@ class AlwaysTrustingTrustManager extends TrustManager {
@override @override
Future<void> setEnabled(String jid, int deviceId, bool enabled) async {} Future<void> setEnabled(String jid, int deviceId, bool enabled) async {}
@override @override
Future<void> removeTrustDecisionsForJid(String jid) async {} Future<void> removeTrustDecisionsForJid(String jid) async {}
@override @override
Future<Map<String, dynamic>> toJson() async => <String, dynamic>{}; Future<Map<String, dynamic>> toJson() async => <String, dynamic>{};
} }

View File

@ -10,30 +10,23 @@ import 'package:synchronized/synchronized.dart';
enum BTBVTrustState { enum BTBVTrustState {
notTrusted, // = 1 notTrusted, // = 1
blindTrust, // = 2 blindTrust, // = 2
verified, // = 3 verified, // = 3
} }
int _trustToInt(BTBVTrustState state) { int _trustToInt(BTBVTrustState state) {
switch (state) { switch (state) {
case BTBVTrustState.notTrusted: case BTBVTrustState.notTrusted: return 1;
return 1; case BTBVTrustState.blindTrust: return 2;
case BTBVTrustState.blindTrust: case BTBVTrustState.verified: return 3;
return 2;
case BTBVTrustState.verified:
return 3;
} }
} }
BTBVTrustState _trustFromInt(int i) { BTBVTrustState _trustFromInt(int i) {
switch (i) { switch (i) {
case 1: case 1: return BTBVTrustState.notTrusted;
return BTBVTrustState.notTrusted; case 2: return BTBVTrustState.blindTrust;
case 2: case 3: return BTBVTrustState.verified;
return BTBVTrustState.blindTrust; default: return BTBVTrustState.notTrusted;
case 3:
return BTBVTrustState.verified;
default:
return BTBVTrustState.notTrusted;
} }
} }
@ -44,10 +37,10 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
Map<RatchetMapKey, BTBVTrustState>? trustCache, Map<RatchetMapKey, BTBVTrustState>? trustCache,
Map<RatchetMapKey, bool>? enablementCache, Map<RatchetMapKey, bool>? enablementCache,
Map<String, List<int>>? devices, Map<String, List<int>>? devices,
}) : trustCache = trustCache ?? {}, }) : trustCache = trustCache ?? {},
enablementCache = enablementCache ?? {}, enablementCache = enablementCache ?? {},
devices = devices ?? {}, devices = devices ?? {},
_lock = Lock(); _lock = Lock();
/// The cache for mapping a RatchetMapKey to its trust state /// The cache for mapping a RatchetMapKey to its trust state
@visibleForTesting @visibleForTesting
@ -58,7 +51,7 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
@visibleForTesting @visibleForTesting
@protected @protected
final Map<RatchetMapKey, bool> enablementCache; final Map<RatchetMapKey, bool> enablementCache;
/// Mapping of Jids to their device identifiers /// Mapping of Jids to their device identifiers
@visibleForTesting @visibleForTesting
@protected @protected
@ -77,7 +70,7 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
return trustCache[RatchetMapKey(jid, id)]! == BTBVTrustState.verified; return trustCache[RatchetMapKey(jid, id)]! == BTBVTrustState.verified;
}); });
} }
@override @override
Future<bool> isTrusted(String jid, int deviceId) async { Future<bool> isTrusted(String jid, int deviceId) async {
var returnValue = false; var returnValue = false;
@ -123,12 +116,12 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
} else { } else {
devices[jid] = List<int>.from([deviceId]); devices[jid] = List<int>.from([deviceId]);
} }
// Commit the state // Commit the state
await commitState(); await commitState();
}); });
} }
/// Returns a mapping from the device identifiers of [jid] to their trust state. If /// Returns a mapping from the device identifiers of [jid] to their trust state. If
/// there are no devices known for [jid], then an empty map is returned. /// there are no devices known for [jid], then an empty map is returned.
Future<Map<int, BTBVTrustState>> getDevicesTrust(String jid) async { Future<Map<int, BTBVTrustState>> getDevicesTrust(String jid) async {
@ -136,7 +129,7 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
final map = <int, BTBVTrustState>{}; final map = <int, BTBVTrustState>{};
if (!devices.containsKey(jid)) return map; if (!devices.containsKey(jid)) return map;
for (final deviceId in devices[jid]!) { for (final deviceId in devices[jid]!) {
map[deviceId] = trustCache[RatchetMapKey(jid, deviceId)]!; map[deviceId] = trustCache[RatchetMapKey(jid, deviceId)]!;
} }
@ -146,11 +139,7 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
} }
/// Sets the trust of [jid]'s device with identifier [deviceId] to [state]. /// Sets the trust of [jid]'s device with identifier [deviceId] to [state].
Future<void> setDeviceTrust( Future<void> setDeviceTrust(String jid, int deviceId, BTBVTrustState state) async {
String jid,
int deviceId,
BTBVTrustState state,
) async {
await _lock.synchronized(() async { await _lock.synchronized(() async {
trustCache[RatchetMapKey(jid, deviceId)] = state; trustCache[RatchetMapKey(jid, deviceId)] = state;
@ -183,14 +172,10 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
Future<Map<String, dynamic>> toJson() async { Future<Map<String, dynamic>> toJson() async {
return { return {
'devices': devices, 'devices': devices,
'trust': trustCache.map( 'trust': trustCache.map((key, value) => MapEntry(
(key, value) => MapEntry( key.toJsonKey(), _trustToInt(value),
key.toJsonKey(), ),),
_trustToInt(value), 'enable': enablementCache.map((key, value) => MapEntry(key.toJsonKey(), value)),
),
),
'enable':
enablementCache.map((key, value) => MapEntry(key.toJsonKey(), value)),
}; };
} }
@ -207,11 +192,8 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
/// From a serialized version of a BTBV trust manager, extract the trust cache. /// From a serialized version of a BTBV trust manager, extract the trust cache.
/// NOTE: This is needed as Dart cannot just cast a List<dynamic> to List<int> and so on. /// NOTE: This is needed as Dart cannot just cast a List<dynamic> to List<int> and so on.
static Map<RatchetMapKey, BTBVTrustState> trustCacheFromJson( static Map<RatchetMapKey, BTBVTrustState> trustCacheFromJson(Map<String, dynamic> json) {
Map<String, dynamic> json, return (json['trust']! as Map<String, dynamic>).map<RatchetMapKey, BTBVTrustState>(
) {
return (json['trust']! as Map<String, dynamic>)
.map<RatchetMapKey, BTBVTrustState>(
(key, value) => MapEntry( (key, value) => MapEntry(
RatchetMapKey.fromJsonKey(key), RatchetMapKey.fromJsonKey(key),
_trustFromInt(value as int), _trustFromInt(value as int),
@ -221,9 +203,7 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
/// From a serialized version of a BTBV trust manager, extract the enable cache. /// From a serialized version of a BTBV trust manager, extract the enable cache.
/// NOTE: This is needed as Dart cannot just cast a List<dynamic> to List<int> and so on. /// NOTE: This is needed as Dart cannot just cast a List<dynamic> to List<int> and so on.
static Map<RatchetMapKey, bool> enableCacheFromJson( static Map<RatchetMapKey, bool> enableCacheFromJson(Map<String, dynamic> json) {
Map<String, dynamic> json,
) {
return (json['enable']! as Map<String, dynamic>).map<RatchetMapKey, bool>( return (json['enable']! as Map<String, dynamic>).map<RatchetMapKey, bool>(
(key, value) => MapEntry( (key, value) => MapEntry(
RatchetMapKey.fromJsonKey(key), RatchetMapKey.fromJsonKey(key),
@ -232,22 +212,21 @@ abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
); );
} }
@override @override
Future<void> removeTrustDecisionsForJid(String jid) async { Future<void> removeTrustDecisionsForJid(String jid) async {
await _lock.synchronized(() async { await _lock.synchronized(() async {
devices.remove(jid); devices.remove(jid);
await commitState(); await commitState();
}); });
} }
/// Called when the state of the trust manager has been changed. Allows the user to /// Called when the state of the trust manager has been changed. Allows the user to
/// commit the trust state to persistent storage. /// commit the trust state to persistent storage.
@visibleForOverriding @visibleForOverriding
Future<void> commitState(); Future<void> commitState();
@visibleForTesting @visibleForTesting
BTBVTrustState getDeviceTrust(String jid, int deviceId) => BTBVTrustState getDeviceTrust(String jid, int deviceId) => trustCache[RatchetMapKey(jid, deviceId)]!;
trustCache[RatchetMapKey(jid, deviceId)]!;
} }
/// A BTBV TrustManager that does not commit its state to persistent storage. Well suited /// A BTBV TrustManager that does not commit its state to persistent storage. Well suited

View File

@ -18,7 +18,7 @@ class NeverTrustingTrustManager extends TrustManager {
@override @override
Future<void> setEnabled(String jid, int deviceId, bool enabled) async {} Future<void> setEnabled(String jid, int deviceId, bool enabled) async {}
@override @override
Future<void> removeTrustDecisionsForJid(String jid) async {} Future<void> removeTrustDecisionsForJid(String jid) async {}
@override @override

View File

@ -12,6 +12,7 @@ const omemoX3DHInfoString = 'OMEMO X3DH';
/// Performed by Alice /// Performed by Alice
class X3DHAliceResult { class X3DHAliceResult {
const X3DHAliceResult(this.ek, this.sk, this.opkId, this.ad); const X3DHAliceResult(this.ek, this.sk, this.opkId, this.ad);
final OmemoKeyPair ek; final OmemoKeyPair ek;
final List<int> sk; final List<int> sk;
@ -21,6 +22,7 @@ class X3DHAliceResult {
/// Received by Bob /// Received by Bob
class X3DHMessage { class X3DHMessage {
const X3DHMessage(this.ik, this.ek, this.opkId); const X3DHMessage(this.ik, this.ek, this.opkId);
final OmemoPublicKey ik; final OmemoPublicKey ik;
final OmemoPublicKey ek; final OmemoPublicKey ek;
@ -28,6 +30,7 @@ class X3DHMessage {
} }
class X3DHBobResult { class X3DHBobResult {
const X3DHBobResult(this.sk, this.ad); const X3DHBobResult(this.sk, this.ad);
final List<int> sk; final List<int> sk;
final List<int> ad; final List<int> ad;
@ -36,10 +39,7 @@ class X3DHBobResult {
/// Sign [message] using the keypair [keyPair]. Note that [keyPair] must be /// Sign [message] using the keypair [keyPair]. Note that [keyPair] must be
/// a Ed25519 keypair. /// a Ed25519 keypair.
Future<List<int>> sig(OmemoKeyPair keyPair, List<int> message) async { Future<List<int>> sig(OmemoKeyPair keyPair, List<int> message) async {
assert( assert(keyPair.type == KeyPairType.ed25519, 'Signature keypair must be Ed25519');
keyPair.type == KeyPairType.ed25519,
'Signature keypair must be Ed25519',
);
final signature = await Ed25519().sign( final signature = await Ed25519().sign(
message, message,
keyPair: await keyPair.asKeyPair(), keyPair: await keyPair.asKeyPair(),
@ -70,10 +70,7 @@ Future<List<int>> kdf(List<int> km) async {
/// Alice builds a session with Bob using his bundle [bundle] and Alice's identity key /// Alice builds a session with Bob using his bundle [bundle] and Alice's identity key
/// pair [ik]. /// pair [ik].
Future<X3DHAliceResult> x3dhFromBundle( Future<X3DHAliceResult> x3dhFromBundle(OmemoBundle bundle, OmemoKeyPair ik) async {
OmemoBundle bundle,
OmemoKeyPair ik,
) async {
// Check the signature first // Check the signature first
final signatureValue = await Ed25519().verify( final signatureValue = await Ed25519().verify(
await bundle.spk.getBytes(), await bundle.spk.getBytes(),
@ -94,9 +91,9 @@ Future<X3DHAliceResult> x3dhFromBundle(
final opkIndex = random.nextInt(bundle.opksEncoded.length); final opkIndex = random.nextInt(bundle.opksEncoded.length);
final opkId = bundle.opksEncoded.keys.elementAt(opkIndex); final opkId = bundle.opksEncoded.keys.elementAt(opkIndex);
final opk = bundle.getOpk(opkId); final opk = bundle.getOpk(opkId);
final dh1 = await omemoDH(ik, bundle.spk, 1); final dh1 = await omemoDH(ik, bundle.spk, 1);
final dh2 = await omemoDH(ek, bundle.ik, 2); final dh2 = await omemoDH(ek, bundle.ik, 2);
final dh3 = await omemoDH(ek, bundle.spk, 0); final dh3 = await omemoDH(ek, bundle.spk, 0);
final dh4 = await omemoDH(ek, opk, 0); final dh4 = await omemoDH(ek, opk, 0);
@ -111,14 +108,9 @@ Future<X3DHAliceResult> x3dhFromBundle(
/// Bob builds the X3DH shared secret from the inital message [msg], the SPK [spk], the /// Bob builds the X3DH shared secret from the inital message [msg], the SPK [spk], the
/// OPK [opk] that was selected by Alice and our IK [ik]. Returns the shared secret. /// OPK [opk] that was selected by Alice and our IK [ik]. Returns the shared secret.
Future<X3DHBobResult> x3dhFromInitialMessage( Future<X3DHBobResult> x3dhFromInitialMessage(X3DHMessage msg, OmemoKeyPair spk, OmemoKeyPair opk, OmemoKeyPair ik) async {
X3DHMessage msg,
OmemoKeyPair spk,
OmemoKeyPair opk,
OmemoKeyPair ik,
) async {
final dh1 = await omemoDH(spk, msg.ik, 2); final dh1 = await omemoDH(spk, msg.ik, 2);
final dh2 = await omemoDH(ik, msg.ek, 1); final dh2 = await omemoDH(ik, msg.ek, 1);
final dh3 = await omemoDH(spk, msg.ek, 0); final dh3 = await omemoDH(spk, msg.ek, 0);
final dh4 = await omemoDH(opk, msg.ek, 0); final dh4 = await omemoDH(opk, msg.ek, 0);

View File

@ -16,7 +16,7 @@ void main() {
..pn = 0 ..pn = 0
..dhPub = List<int>.empty(); ..dhPub = List<int>.empty();
final asd = concat([sessionAd, header.writeToBuffer()]); final asd = concat([sessionAd, header.writeToBuffer()]);
final ciphertext = await encrypt( final ciphertext = await encrypt(
mk, mk,
plaintext, plaintext,
@ -55,13 +55,13 @@ void main() {
2: await opkBob.pk.asBase64(), 2: await opkBob.pk.asBase64(),
}, },
); );
// Alice does X3DH // Alice does X3DH
final resultAlice = await x3dhFromBundle(bundleBob, ikAlice); final resultAlice = await x3dhFromBundle(bundleBob, ikAlice);
// Alice sends the inital message to Bob // Alice sends the inital message to Bob
// ... // ...
// Bob does X3DH // Bob does X3DH
final resultBob = await x3dhFromInitialMessage( final resultBob = await x3dhFromInitialMessage(
X3DHMessage( X3DHMessage(
@ -76,6 +76,7 @@ void main() {
print('X3DH key exchange done'); print('X3DH key exchange done');
// Alice and Bob now share sk as a common secret and ad // Alice and Bob now share sk as a common secret and ad
// Build a session // Build a session
final alicesRatchet = await OmemoDoubleRatchet.initiateNewSession( final alicesRatchet = await OmemoDoubleRatchet.initiateNewSession(
@ -97,11 +98,10 @@ void main() {
for (var i = 0; i < 100; i++) { for (var i = 0; i < 100; i++) {
final messageText = 'Hello, dear $i'; final messageText = 'Hello, dear $i';
if (i.isEven) { if (i.isEven) {
// Alice encrypts a message // Alice encrypts a message
final aliceRatchetResult = final aliceRatchetResult = await alicesRatchet.ratchetEncrypt(utf8.encode(messageText));
await alicesRatchet.ratchetEncrypt(utf8.encode(messageText));
print('Alice sent the message'); print('Alice sent the message');
// Alice sends it to Bob // Alice sends it to Bob
@ -117,8 +117,7 @@ void main() {
expect(utf8.encode(messageText), bobRatchetResult); expect(utf8.encode(messageText), bobRatchetResult);
} else { } else {
// Bob sends a message to Alice // Bob sends a message to Alice
final bobRatchetResult = final bobRatchetResult = await bobsRatchet.ratchetEncrypt(utf8.encode(messageText));
await bobsRatchet.ratchetEncrypt(utf8.encode(messageText));
print('Bob sent the message'); print('Bob sent the message');
// Bobs sends it to Alice // Bobs sends it to Alice

View File

@ -30,18 +30,18 @@ void main() {
if (!m) opksMatch = false; if (!m) opksMatch = false;
} }
} }
expect(opksMatch, true); expect(opksMatch, true);
expect(await device.ik.equals(newDevice.ik), true); expect(await device.ik.equals(newDevice.ik), true);
expect(await device.spk.equals(newDevice.spk), true); expect(await device.spk.equals(newDevice.spk), true);
final oldSpkMatch = device.oldSpk != null final oldSpkMatch = device.oldSpk != null ?
? await device.oldSpk!.equals(newDevice.oldSpk!) await device.oldSpk!.equals(newDevice.oldSpk!) :
: newDevice.oldSpk == null; newDevice.oldSpk == null;
expect(oldSpkMatch, true); expect(oldSpkMatch, true);
expect(listsEqual(device.spkSignature, newDevice.spkSignature), true); expect(listsEqual(device.spkSignature, newDevice.spkSignature), true);
}); });
test('Test using OMEMO sessions with only one device per user', () async { test('Test using OMEMO sessions with only one device per user', () async {
const aliceJid = 'alice@server.example'; const aliceJid = 'alice@server.example';
const bobJid = 'bob@other.server.example'; const bobJid = 'bob@other.server.example';
@ -80,7 +80,7 @@ void main() {
], ],
); );
expect(aliceMessage.encryptedKeys.length, 1); expect(aliceMessage.encryptedKeys.length, 1);
// Alice sends the message to Bob // Alice sends the message to Bob
// ... // ...
@ -107,11 +107,9 @@ void main() {
); );
// Ratchets are acked // Ratchets are acked
await aliceSession.ratchetAcknowledged( await aliceSession.ratchetAcknowledged(bobJid, await bobSession.getDeviceId());
bobJid, await bobSession.getDeviceId()); await bobSession.ratchetAcknowledged(aliceJid, await aliceSession.getDeviceId());
await bobSession.ratchetAcknowledged(
aliceJid, await aliceSession.getDeviceId());
// Bob responds to Alice // Bob responds to Alice
const bobResponseText = 'Oh, hello Alice!'; const bobResponseText = 'Oh, hello Alice!';
final bobResponseMessage = await bobSession.encryptToJid( final bobResponseMessage = await bobSession.encryptToJid(
@ -133,11 +131,10 @@ void main() {
expect(bobResponseText, aliceReceivedMessage); expect(bobResponseText, aliceReceivedMessage);
}); });
test('Test using OMEMO sessions with only two devices for the receiver', test('Test using OMEMO sessions with only two devices for the receiver', () async {
() async {
const aliceJid = 'alice@server.example'; const aliceJid = 'alice@server.example';
const bobJid = 'bob@other.server.example'; const bobJid = 'bob@other.server.example';
// Alice and Bob generate their sessions // Alice and Bob generate their sessions
final aliceSession = await OmemoSessionManager.generateNewIdentity( final aliceSession = await OmemoSessionManager.generateNewIdentity(
aliceJid, aliceJid,
@ -184,11 +181,9 @@ void main() {
expect(messagePlaintext, bobMessage); expect(messagePlaintext, bobMessage);
// Ratchets are acked // Ratchets are acked
await aliceSession.ratchetAcknowledged( await aliceSession.ratchetAcknowledged(bobJid, await bobSession.getDeviceId());
bobJid, await bobSession.getDeviceId()); await bobSession.ratchetAcknowledged(aliceJid, await aliceSession.getDeviceId());
await bobSession.ratchetAcknowledged(
aliceJid, await aliceSession.getDeviceId());
// Bob responds to Alice // Bob responds to Alice
const bobResponseText = 'Oh, hello Alice!'; const bobResponseText = 'Oh, hello Alice!';
final bobResponseMessage = await bobSession.encryptToJid( final bobResponseMessage = await bobSession.encryptToJid(
@ -223,7 +218,7 @@ void main() {
test('Test using OMEMO sessions with encrypt to self', () async { test('Test using OMEMO sessions with encrypt to self', () async {
const aliceJid = 'alice@server.example'; const aliceJid = 'alice@server.example';
const bobJid = 'bob@other.server.example'; const bobJid = 'bob@other.server.example';
// Alice and Bob generate their sessions // Alice and Bob generate their sessions
final aliceSession1 = await OmemoSessionManager.generateNewIdentity( final aliceSession1 = await OmemoSessionManager.generateNewIdentity(
aliceJid, aliceJid,
@ -280,7 +275,7 @@ void main() {
test('Test sending empty OMEMO messages', () async { test('Test sending empty OMEMO messages', () async {
const aliceJid = 'alice@server.example'; const aliceJid = 'alice@server.example';
const bobJid = 'bob@other.server.example'; const bobJid = 'bob@other.server.example';
// Alice and Bob generate their sessions // Alice and Bob generate their sessions
final aliceSession = await OmemoSessionManager.generateNewIdentity( final aliceSession = await OmemoSessionManager.generateNewIdentity(
aliceJid, aliceJid,
@ -355,7 +350,7 @@ void main() {
test('Test accepting a session with an old SPK', () async { test('Test accepting a session with an old SPK', () async {
const aliceJid = 'alice@server.example'; const aliceJid = 'alice@server.example';
const bobJid = 'bob@other.server.example'; const bobJid = 'bob@other.server.example';
// Alice and Bob generate their sessions // Alice and Bob generate their sessions
final aliceSession = await OmemoSessionManager.generateNewIdentity( final aliceSession = await OmemoSessionManager.generateNewIdentity(
aliceJid, aliceJid,
@ -381,7 +376,7 @@ void main() {
// Alice loses her Internet connection. Bob rotates his SPK. // Alice loses her Internet connection. Bob rotates his SPK.
await bobSession.rotateSignedPrekey(); await bobSession.rotateSignedPrekey();
// Alice regains her Internet connection and sends the message to Bob // Alice regains her Internet connection and sends the message to Bob
// ... // ...
@ -399,7 +394,7 @@ void main() {
test('Test trust bypassing with empty OMEMO messages', () async { test('Test trust bypassing with empty OMEMO messages', () async {
const aliceJid = 'alice@server.example'; const aliceJid = 'alice@server.example';
const bobJid = 'bob@other.server.example'; const bobJid = 'bob@other.server.example';
// Alice and Bob generate their sessions // Alice and Bob generate their sessions
final aliceSession = await OmemoSessionManager.generateNewIdentity( final aliceSession = await OmemoSessionManager.generateNewIdentity(
aliceJid, aliceJid,
@ -462,11 +457,9 @@ void main() {
); );
// Ratchets are acked // Ratchets are acked
await aliceSession.ratchetAcknowledged( await aliceSession.ratchetAcknowledged(bobJid, await bobSession.getDeviceId());
bobJid, await bobSession.getDeviceId()); await bobSession.ratchetAcknowledged(aliceJid, await aliceSession.getDeviceId());
await bobSession.ratchetAcknowledged(
aliceJid, await aliceSession.getDeviceId());
for (var i = 0; i < 100; i++) { for (var i = 0; i < 100; i++) {
final messageText = 'Test Message #$i'; final messageText = 'Test Message #$i';
// Bob responds to Alice // Bob responds to Alice
@ -604,8 +597,7 @@ void main() {
// ... // ...
// Alice marks the ratchet as acknowledged // Alice marks the ratchet as acknowledged
await aliceSession.ratchetAcknowledged( await aliceSession.ratchetAcknowledged(bobJid, await bobSession.getDeviceId());
bobJid, await bobSession.getDeviceId());
expect( expect(
(await aliceSession.getUnacknowledgedRatchets(bobJid))!.isEmpty, (await aliceSession.getUnacknowledgedRatchets(bobJid))!.isEmpty,
true, true,
@ -679,7 +671,7 @@ void main() {
// Both should only have one ratchet // Both should only have one ratchet
expect(aliceSession.getRatchetMap().length, 1); expect(aliceSession.getRatchetMap().length, 1);
expect(bobSession.getRatchetMap().length, 1); expect(bobSession.getRatchetMap().length, 1);
// The ratchets should both be different // The ratchets should both be different
expect(await aliceRatchet1.equals(aliceRatchet2), false); expect(await aliceRatchet1.equals(aliceRatchet2), false);
expect(await bobRatchet1.equals(bobRatchet2), false); expect(await bobRatchet1.equals(bobRatchet2), false);
@ -734,8 +726,9 @@ void main() {
msg2.encryptedKeys, msg2.encryptedKeys,
getTimestamp(), getTimestamp(),
); );
});
});
test('Test receiving old messages including a KEX', () async { test('Test receiving old messages including a KEX', () async {
const aliceJid = 'alice@server.example'; const aliceJid = 'alice@server.example';
const bobJid = 'bob@other.server.example'; const bobJid = 'bob@other.server.example';
@ -753,7 +746,7 @@ void main() {
final bobsReceivedMessages = List<EncryptionResult>.empty(growable: true); final bobsReceivedMessages = List<EncryptionResult>.empty(growable: true);
final bobsReceivedMessagesTimestamps = List<int>.empty(growable: true); final bobsReceivedMessagesTimestamps = List<int>.empty(growable: true);
// Alice sends Bob a message // Alice sends Bob a message
final msg1 = await aliceSession.encryptToJid( final msg1 = await aliceSession.encryptToJid(
bobJid, bobJid,
@ -775,11 +768,9 @@ void main() {
); );
// Ratchets are acked // Ratchets are acked
await aliceSession.ratchetAcknowledged( await aliceSession.ratchetAcknowledged(bobJid, await bobSession.getDeviceId());
bobJid, await bobSession.getDeviceId()); await bobSession.ratchetAcknowledged(aliceJid, await aliceSession.getDeviceId());
await bobSession.ratchetAcknowledged(
aliceJid, await aliceSession.getDeviceId());
// Bob responds // Bob responds
final msg2 = await bobSession.encryptToJid( final msg2 = await bobSession.encryptToJid(
aliceJid, aliceJid,
@ -793,7 +784,7 @@ void main() {
msg2.encryptedKeys, msg2.encryptedKeys,
getTimestamp(), getTimestamp(),
); );
// Send some messages between the two // Send some messages between the two
for (var i = 0; i < 100; i++) { for (var i = 0; i < 100; i++) {
final msg = await aliceSession.encryptToJid( final msg = await aliceSession.encryptToJid(
@ -817,8 +808,8 @@ void main() {
// Due to some issue with the transport protocol, the messages to Bob are received // Due to some issue with the transport protocol, the messages to Bob are received
// again. // again.
final ratchetPreError = bobSession final ratchetPreError = bobSession
.getRatchet(aliceJid, await aliceSession.getDeviceId()) .getRatchet(aliceJid, await aliceSession.getDeviceId())
.clone(); .clone();
var invalidKex = 0; var invalidKex = 0;
var errorCounter = 0; var errorCounter = 0;
for (var i = 0; i < bobsReceivedMessages.length; i++) { for (var i = 0; i < bobsReceivedMessages.length; i++) {
@ -839,14 +830,15 @@ void main() {
} }
} }
final ratchetPostError = bobSession final ratchetPostError = bobSession
.getRatchet(aliceJid, await aliceSession.getDeviceId()) .getRatchet(aliceJid, await aliceSession.getDeviceId())
.clone(); .clone();
// The 100 messages including the initial KEX message // The 100 messages including the initial KEX message
expect(invalidKex, 1); expect(invalidKex, 1);
expect(errorCounter, 100); expect(errorCounter, 100);
expect(await ratchetPreError.equals(ratchetPostError), true); expect(await ratchetPreError.equals(ratchetPostError), true);
final msg3 = await aliceSession.encryptToJid( final msg3 = await aliceSession.encryptToJid(
bobJid, bobJid,
'Are you okay?', 'Are you okay?',
@ -911,10 +903,8 @@ void main() {
); );
// Now the acks reach us // Now the acks reach us
await aliceSession.ratchetAcknowledged( await aliceSession.ratchetAcknowledged(bobJid, await bobSession.getDeviceId());
bobJid, await bobSession.getDeviceId()); await bobSession.ratchetAcknowledged(aliceJid, await aliceSession.getDeviceId());
await bobSession.ratchetAcknowledged(
aliceJid, await aliceSession.getDeviceId());
// Alice sends another message // Alice sends another message
final msg3 = await aliceSession.encryptToJid( final msg3 = await aliceSession.encryptToJid(

View File

@ -5,15 +5,6 @@ import 'package:omemo_dart/src/protobuf/omemo_key_exchange.dart';
import 'package:omemo_dart/src/trust/always.dart'; import 'package:omemo_dart/src/trust/always.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
class TestingTrustManager extends AlwaysTrustingTrustManager {
final Map<String, int> devices = {};
@override
Future<void> onNewSession(String jid, int deviceId) async {
devices[jid] = deviceId;
}
}
void main() { void main() {
Logger.root Logger.root
..level = Level.ALL ..level = Level.ALL
@ -28,8 +19,7 @@ void main() {
var aliceEmptyMessageSent = 0; var aliceEmptyMessageSent = 0;
var bobEmptyMessageSent = 0; var bobEmptyMessageSent = 0;
final aliceDevice = final aliceDevice = await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1); final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
final aliceManager = OmemoManager( final aliceManager = OmemoManager(
@ -40,7 +30,7 @@ void main() {
}, },
(jid) async { (jid) async {
expect(jid, bobJid); expect(jid, bobJid);
return [bobDevice.id]; return [ bobDevice.id ];
}, },
(jid, id) async { (jid, id) async {
expect(jid, bobJid); expect(jid, bobJid);
@ -94,7 +84,7 @@ void main() {
bobJid, bobJid,
bobDevice.id, bobDevice.id,
); );
// Bob now responds // Bob now responds
final bobResult2 = await bobManager.onOutgoingStanza( final bobResult2 = await bobManager.onOutgoingStanza(
const OmemoOutgoingStanza( const OmemoOutgoingStanza(
@ -124,8 +114,7 @@ void main() {
var aliceEmptyMessageSent = 0; var aliceEmptyMessageSent = 0;
var bobEmptyMessageSent = 0; var bobEmptyMessageSent = 0;
final aliceDevice = final aliceDevice = await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1); final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
final aliceManager = OmemoManager( final aliceManager = OmemoManager(
@ -136,7 +125,7 @@ void main() {
}, },
(jid) async { (jid) async {
expect(jid, bobJid); expect(jid, bobJid);
return [bobDevice.id]; return [ bobDevice.id ];
}, },
(jid, id) async { (jid, id) async {
expect(jid, bobJid); expect(jid, bobJid);
@ -186,7 +175,7 @@ void main() {
// Bob acknowledges the message // Bob acknowledges the message
await aliceManager.ratchetAcknowledged(bobJid, bobDevice.id); await aliceManager.ratchetAcknowledged(bobJid, bobDevice.id);
// Alice now sends 52 messages that Bob decrypts // Alice now sends 52 messages that Bob decrypts
for (var i = 0; i <= 51; i++) { for (var i = 0; i <= 51; i++) {
final aliceResultLoop = await aliceManager.onOutgoingStanza( final aliceResultLoop = await aliceManager.onOutgoingStanza(
@ -237,8 +226,7 @@ void main() {
test('Test accessing data without it existing', () async { test('Test accessing data without it existing', () async {
const aliceJid = 'alice@server1'; const aliceJid = 'alice@server1';
const bobJid = 'bob@server2'; const bobJid = 'bob@server2';
final aliceDevice = final aliceDevice = await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
final aliceManager = OmemoManager( final aliceManager = OmemoManager(
aliceDevice, aliceDevice,
@ -267,12 +255,9 @@ void main() {
const bobJid = 'bob@server2'; const bobJid = 'bob@server2';
var oldDevice = true; var oldDevice = true;
final aliceDevice = final aliceDevice = await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1); final bobOldDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
final bobOldDevice = final bobCurrentDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
final bobCurrentDevice =
await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
final aliceManager = OmemoManager( final aliceManager = OmemoManager(
aliceDevice, aliceDevice,
@ -281,13 +266,15 @@ void main() {
(jid) async { (jid) async {
expect(jid, bobJid); expect(jid, bobJid);
return oldDevice ? [bobOldDevice.id] : [bobCurrentDevice.id]; return oldDevice ?
[ bobOldDevice.id ] :
[ bobCurrentDevice.id ];
}, },
(jid, id) async { (jid, id) async {
expect(jid, bobJid); expect(jid, bobJid);
return oldDevice return oldDevice ?
? bobOldDevice.toBundle() bobOldDevice.toBundle() :
: bobCurrentDevice.toBundle(); bobCurrentDevice.toBundle();
}, },
(jid) async {}, (jid) async {},
); );
@ -352,12 +339,9 @@ void main() {
const bobJid = 'bob@server2'; const bobJid = 'bob@server2';
var bothDevices = false; var bothDevices = false;
final aliceDevice = final aliceDevice = await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1); final bobDevice1 = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
final bobDevice1 = final bobDevice2 = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
final bobDevice2 =
await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
final aliceManager = OmemoManager( final aliceManager = OmemoManager(
aliceDevice, aliceDevice,
@ -368,7 +352,9 @@ void main() {
return [ return [
bobDevice1.id, bobDevice1.id,
if (bothDevices) bobDevice2.id,
if (bothDevices)
bobDevice2.id,
]; ];
}, },
(jid, id) async { (jid, id) async {
@ -461,12 +447,9 @@ void main() {
const bobJid = 'bob@server2'; const bobJid = 'bob@server2';
var bothDevices = false; var bothDevices = false;
final aliceDevice = final aliceDevice = await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1); final bobDevice1 = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
final bobDevice1 = final bobDevice2 = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
final bobDevice2 =
await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
final aliceManager = OmemoManager( final aliceManager = OmemoManager(
aliceDevice, aliceDevice,
@ -477,7 +460,9 @@ void main() {
return [ return [
bobDevice1.id, bobDevice1.id,
if (bothDevices) bobDevice2.id,
if (bothDevices)
bobDevice2.id,
]; ];
}, },
(jid, id) async { (jid, id) async {
@ -538,7 +523,7 @@ void main() {
// Bob acks the ratchet session // Bob acks the ratchet session
await aliceManager.ratchetAcknowledged(bobJid, bobDevice1.id); await aliceManager.ratchetAcknowledged(bobJid, bobDevice1.id);
// Bob now publishes a new device // Bob now publishes a new device
bothDevices = true; bothDevices = true;
aliceManager.onDeviceListUpdate( aliceManager.onDeviceListUpdate(
@ -548,7 +533,7 @@ void main() {
bobDevice2.id, bobDevice2.id,
], ],
); );
// Now Alice encrypts another message // Now Alice encrypts another message
final aliceResult2 = await aliceManager.onOutgoingStanza( final aliceResult2 = await aliceManager.onOutgoingStanza(
const OmemoOutgoingStanza( const OmemoOutgoingStanza(
@ -609,11 +594,9 @@ void main() {
const bobJid = 'bob@server2'; const bobJid = 'bob@server2';
const cocoJid = 'coco@server3'; const cocoJid = 'coco@server3';
final aliceDevice = final aliceDevice = await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1); final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
final cocoDevice = final cocoDevice = await OmemoDevice.generateNewDevice(cocoJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(cocoJid, opkAmount: 1);
final aliceManager = OmemoManager( final aliceManager = OmemoManager(
aliceDevice, aliceDevice,
@ -695,8 +678,7 @@ void main() {
const bobJid = 'bob@server2'; const bobJid = 'bob@server2';
var failure = false; var failure = false;
final aliceDevice = final aliceDevice = await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1); final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
final aliceManager = OmemoManager( final aliceManager = OmemoManager(
@ -706,12 +688,16 @@ void main() {
(jid) async { (jid) async {
expect(jid, bobJid); expect(jid, bobJid);
return failure ? null : [bobDevice.id]; return failure ?
null :
[bobDevice.id];
}, },
(jid, id) async { (jid, id) async {
expect(jid, bobJid); expect(jid, bobJid);
return failure ? null : bobDevice.toBundle(); return failure ?
null :
bobDevice.toBundle();
}, },
(jid) async {}, (jid) async {},
); );
@ -783,8 +769,7 @@ void main() {
const aliceJid = 'alice@server1'; const aliceJid = 'alice@server1';
const bobJid = 'bob@server2'; const bobJid = 'bob@server2';
final aliceDevice = final aliceDevice = await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
final aliceManager = OmemoManager( final aliceManager = OmemoManager(
aliceDevice, aliceDevice,
@ -812,11 +797,7 @@ void main() {
); );
expect(aliceResult.isSuccess(1), false); expect(aliceResult.isSuccess(1), false);
expect( expect(aliceResult.jidEncryptionErrors[bobJid] is NoKeyMaterialAvailableException, true);
aliceResult.jidEncryptionErrors[bobJid]
is NoKeyMaterialAvailableException,
true,
);
}); });
test('Test sending a message two two JIDs with failed lookups', () async { test('Test sending a message two two JIDs with failed lookups', () async {
@ -824,8 +805,7 @@ void main() {
const bobJid = 'bob@server2'; const bobJid = 'bob@server2';
const cocoJid = 'coco@server3'; const cocoJid = 'coco@server3';
final aliceDevice = final aliceDevice = await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1); final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
final aliceManager = OmemoManager( final aliceManager = OmemoManager(
@ -866,11 +846,7 @@ void main() {
); );
expect(aliceResult.isSuccess(2), true); expect(aliceResult.isSuccess(2), true);
expect( expect(aliceResult.jidEncryptionErrors[cocoJid] is NoKeyMaterialAvailableException, true);
aliceResult.jidEncryptionErrors[cocoJid]
is NoKeyMaterialAvailableException,
true,
);
// Bob decrypts it // Bob decrypts it
final bobResult = await bobManager.onIncomingStanza( final bobResult = await bobManager.onIncomingStanza(
@ -890,8 +866,7 @@ void main() {
const aliceJid = 'alice@server1'; const aliceJid = 'alice@server1';
const bobJid = 'bob@server2'; const bobJid = 'bob@server2';
final aliceDevice = final aliceDevice = await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1); final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
final aliceManager = OmemoManager( final aliceManager = OmemoManager(
@ -936,6 +911,7 @@ void main() {
aliceMessage.encryptedKeys, aliceMessage.encryptedKeys,
base64.encode(aliceMessage.ciphertext!), base64.encode(aliceMessage.ciphertext!),
), ),
); );
// Ratchets are acked // Ratchets are acked
@ -943,7 +919,7 @@ void main() {
bobJid, bobJid,
bobDevice.id, bobDevice.id,
); );
for (var i = 0; i < 100; i++) { for (var i = 0; i < 100; i++) {
final messageText = 'Test Message #$i'; final messageText = 'Test Message #$i';
// Bob responds to Alice // Bob responds to Alice
@ -954,7 +930,7 @@ void main() {
), ),
); );
expect(bobResponseMessage.isSuccess(1), true); expect(bobResponseMessage.isSuccess(1), true);
final aliceReceivedMessage = await aliceManager.onIncomingStanza( final aliceReceivedMessage = await aliceManager.onIncomingStanza(
OmemoIncomingStanza( OmemoIncomingStanza(
bobJid, bobJid,
@ -969,11 +945,10 @@ void main() {
}); });
test('Test removing all ratchets and sending a message', () async { test('Test removing all ratchets and sending a message', () async {
const aliceJid = 'alice@server1'; const aliceJid = 'alice@server1';
const bobJid = 'bob@server2'; const bobJid = 'bob@server2';
final aliceDevice = final aliceDevice = await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1); final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
EncryptionResult? aliceEmptyMessage; EncryptionResult? aliceEmptyMessage;
@ -1054,7 +1029,7 @@ void main() {
bobJid, bobJid,
await bobManager.getDeviceId(), await bobManager.getDeviceId(),
); );
// Alice sends another message // Alice sends another message
final aliceResult3 = await aliceManager.onOutgoingStanza( final aliceResult3 = await aliceManager.onOutgoingStanza(
const OmemoOutgoingStanza( const OmemoOutgoingStanza(
@ -1100,17 +1075,14 @@ void main() {
expect(aliceResult4.payload, "That's okay."); expect(aliceResult4.payload, "That's okay.");
}); });
test( test('Test removing all ratchets and sending a message without post-heartbeat ack', () async {
'Test removing all ratchets and sending a message without post-heartbeat ack',
() async {
// This test is the same as "Test removing all ratchets and sending a message" except // This test is the same as "Test removing all ratchets and sending a message" except
// that bob does not ack the ratchet after Alice's heartbeat after she recreated // that bob does not ack the ratchet after Alice's heartbeat after she recreated
// all ratchets. // all ratchets.
const aliceJid = 'alice@server1'; const aliceJid = 'alice@server1';
const bobJid = 'bob@server2'; const bobJid = 'bob@server2';
final aliceDevice = final aliceDevice = await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1); final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
EncryptionResult? aliceEmptyMessage; EncryptionResult? aliceEmptyMessage;
@ -1235,8 +1207,7 @@ void main() {
const aliceJid = 'alice@server1'; const aliceJid = 'alice@server1';
const bobJid = 'bob@server2'; const bobJid = 'bob@server2';
final aliceDevice = final aliceDevice = await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1); final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
final aliceManager = OmemoManager( final aliceManager = OmemoManager(
@ -1245,7 +1216,7 @@ void main() {
(result, recipientJid) async {}, (result, recipientJid) async {},
(jid) async { (jid) async {
expect(jid, bobJid); expect(jid, bobJid);
return [bobDevice.id]; return [ bobDevice.id ];
}, },
(jid, id) async { (jid, id) async {
expect(jid, bobJid); expect(jid, bobJid);
@ -1267,7 +1238,7 @@ void main() {
}, },
(jid) async {}, (jid) async {},
); );
// Alice sends Bob a message // Alice sends Bob a message
final aliceResult1 = await aliceManager.onOutgoingStanza( final aliceResult1 = await aliceManager.onOutgoingStanza(
const OmemoOutgoingStanza( const OmemoOutgoingStanza(
@ -1292,7 +1263,7 @@ void main() {
expect(bobResult1.error, null); expect(bobResult1.error, null);
expect(bobResult1.payload, 'Hello World!'); expect(bobResult1.payload, 'Hello World!');
// Alice immediately sends another message // Alice immediately sends another message
final aliceResult2 = await aliceManager.onOutgoingStanza( final aliceResult2 = await aliceManager.onOutgoingStanza(
const OmemoOutgoingStanza( const OmemoOutgoingStanza(
[bobJid], [bobJid],
@ -1347,8 +1318,8 @@ void main() {
), ),
); );
expect(aliceResult3.error, null); expect(aliceResult3.error, null);
expect(aliceResult3.payload, 'Hello Alice!'); expect(aliceResult3.payload, 'Hello Alice!');
// Bob now acks the ratchet // Bob now acks the ratchet
await aliceManager.ratchetAcknowledged( await aliceManager.ratchetAcknowledged(
bobJid, bobJid,
@ -1379,68 +1350,4 @@ void main() {
expect(bobResult4.error, null); expect(bobResult4.error, null);
expect(bobResult4.payload, 'Hi Bob'); expect(bobResult4.payload, 'Hi Bob');
}); });
test('Test correct trust behaviour on receiving', () async {
const aliceJid = 'alice@server1';
const bobJid = 'bob@server2';
final aliceDevice =
await OmemoDevice.generateNewDevice(aliceJid, opkAmount: 1);
final bobDevice = await OmemoDevice.generateNewDevice(bobJid, opkAmount: 1);
final aliceManager = OmemoManager(
aliceDevice,
AlwaysTrustingTrustManager(),
(result, recipientJid) async {},
(jid) async {
expect(jid, bobJid);
return [bobDevice.id];
},
(jid, id) async {
expect(jid, bobJid);
return bobDevice.toBundle();
},
(jid) async {},
);
final bobManager = OmemoManager(
bobDevice,
TestingTrustManager(),
(result, recipientJid) async {},
(jid) async {
expect(jid, aliceJid);
return [aliceDevice.id];
},
(jid, id) async {
expect(jid, aliceJid);
return aliceDevice.toBundle();
},
(jid) async {},
);
// Alice sends Bob a message
final aliceResult1 = await aliceManager.onOutgoingStanza(
const OmemoOutgoingStanza(
[bobJid],
'Hello World!',
),
);
// Bob decrypts Alice's message
final bobResult1 = await bobManager.onIncomingStanza(
OmemoIncomingStanza(
aliceJid,
aliceDevice.id,
DateTime.now().millisecondsSinceEpoch,
aliceResult1.encryptedKeys,
base64.encode(aliceResult1.ciphertext!),
),
);
expect(bobResult1.error, null);
// Bob should have some trust state
expect(
(bobManager.trustManager as TestingTrustManager).devices[aliceJid],
await aliceManager.getDeviceId(),
);
});
} }

View File

@ -76,7 +76,7 @@ void main() {
..dhPub = <int>[1, 2, 3]; ..dhPub = <int>[1, 2, 3];
final serial = pbMessage.writeToBuffer(); final serial = pbMessage.writeToBuffer();
final msg = OmemoMessage.fromBuffer(serial); final msg = OmemoMessage.fromBuffer(serial);
expect(msg.n, 1); expect(msg.n, 1);
expect(msg.pn, 5); expect(msg.pn, 5);
expect(msg.dhPub, <int>[1, 2, 3]); expect(msg.dhPub, <int>[1, 2, 3]);
@ -90,7 +90,7 @@ void main() {
..ciphertext = <int>[4, 5, 6]; ..ciphertext = <int>[4, 5, 6];
final serial = m.writeToBuffer(); final serial = m.writeToBuffer();
final msg = OMEMOMessage.fromBuffer(serial); final msg = OMEMOMessage.fromBuffer(serial);
expect(msg.n, 1); expect(msg.n, 1);
expect(msg.pn, 5); expect(msg.pn, 5);
expect(msg.dhPub, <int>[1, 2, 3]); expect(msg.dhPub, <int>[1, 2, 3]);
@ -169,7 +169,7 @@ void main() {
expect(decoded.pkId, 698); expect(decoded.pkId, 698);
expect(decoded.spkId, 245); expect(decoded.spkId, 245);
expect(decoded.ik, <int>[1, 4, 6]); expect(decoded.ik, <int>[1, 4, 6]);
expect(decoded.ek, <int>[4, 6, 7, 80]); expect(decoded.ek, <int>[4 ,6 ,7 , 80]);
expect(decoded.message!.mac, <int>[5, 6, 8, 0]); expect(decoded.message!.mac, <int>[5, 6, 8, 0]);
expect(decoded.message!.message, <int>[4, 5, 7, 3, 2]); expect(decoded.message!.message, <int>[4, 5, 7, 3, 2]);

View File

@ -22,22 +22,20 @@ void main() {
expect(await oldDevice.equals(newDevice), true); expect(await oldDevice.equals(newDevice), true);
}); });
test('Test serialising and deserialising the Device after rotating the SPK', test('Test serialising and deserialising the Device after rotating the SPK', () async {
() async {
// Generate a random session // Generate a random session
final oldSession = await OmemoSessionManager.generateNewIdentity( final oldSession = await OmemoSessionManager.generateNewIdentity(
'user@test.server', 'user@test.server',
AlwaysTrustingTrustManager(), AlwaysTrustingTrustManager(),
opkAmount: 1, opkAmount: 1,
); );
final oldDevice = final oldDevice = await (await oldSession.getDevice()).replaceSignedPrekey();
await (await oldSession.getDevice()).replaceSignedPrekey();
final serialised = jsonify(await oldDevice.toJson()); final serialised = jsonify(await oldDevice.toJson());
final newDevice = OmemoDevice.fromJson(serialised); final newDevice = OmemoDevice.fromJson(serialised);
expect(await oldDevice.equals(newDevice), true); expect(await oldDevice.equals(newDevice), true);
}); });
test('Test serialising and deserialising the OmemoDoubleRatchet', () async { test('Test serialising and deserialising the OmemoDoubleRatchet', () async {
// Generate a random ratchet // Generate a random ratchet
const aliceJid = 'alice@server.example'; const aliceJid = 'alice@server.example';
@ -66,8 +64,7 @@ void main() {
aliceMessage.encryptedKeys, aliceMessage.encryptedKeys,
getTimestamp(), getTimestamp(),
); );
final aliceOld = final aliceOld = aliceSession.getRatchet(bobJid, await bobSession.getDeviceId());
aliceSession.getRatchet(bobJid, await bobSession.getDeviceId());
final aliceSerialised = jsonify(await aliceOld.toJson()); final aliceSerialised = jsonify(await aliceOld.toJson());
final aliceNew = OmemoDoubleRatchet.fromJson(aliceSerialised); final aliceNew = OmemoDoubleRatchet.fromJson(aliceSerialised);
@ -119,14 +116,13 @@ void main() {
expect(result2.deviceId, test2.deviceId); expect(result2.deviceId, test2.deviceId);
}); });
test('Test serializing and deserializing the components of the BTBV manager', test('Test serializing and deserializing the components of the BTBV manager', () async {
() async {
// Caroline's BTBV manager // Caroline's BTBV manager
final btbv = MemoryBTBVTrustManager(); final btbv = MemoryBTBVTrustManager();
// Example data // Example data
const aliceJid = 'alice@some.server'; const aliceJid = 'alice@some.server';
const bobJid = 'bob@other.server'; const bobJid = 'bob@other.server';
await btbv.onNewSession(aliceJid, 1); await btbv.onNewSession(aliceJid, 1);
await btbv.setDeviceTrust(aliceJid, 1, BTBVTrustState.verified); await btbv.setDeviceTrust(aliceJid, 1, BTBVTrustState.verified);
await btbv.onNewSession(aliceJid, 2); await btbv.onNewSession(aliceJid, 2);
@ -134,20 +130,17 @@ void main() {
await btbv.onNewSession(bobJid, 4); await btbv.onNewSession(bobJid, 4);
final serialized = jsonify(await btbv.toJson()); final serialized = jsonify(await btbv.toJson());
final deviceList = final deviceList = BlindTrustBeforeVerificationTrustManager.deviceListFromJson(
BlindTrustBeforeVerificationTrustManager.deviceListFromJson(
serialized, serialized,
); );
expect(btbv.devices, deviceList); expect(btbv.devices, deviceList);
final trustCache = final trustCache = BlindTrustBeforeVerificationTrustManager.trustCacheFromJson(
BlindTrustBeforeVerificationTrustManager.trustCacheFromJson(
serialized, serialized,
); );
expect(btbv.trustCache, trustCache); expect(btbv.trustCache, trustCache);
final enableCache = final enableCache = BlindTrustBeforeVerificationTrustManager.enableCacheFromJson(
BlindTrustBeforeVerificationTrustManager.enableCacheFromJson(
serialized, serialized,
); );
expect(btbv.enablementCache, enableCache); expect(btbv.enablementCache, enableCache);

View File

@ -8,7 +8,7 @@ void main() {
// Example data // Example data
const aliceJid = 'alice@some.server'; const aliceJid = 'alice@some.server';
const bobJid = 'bob@other.server'; const bobJid = 'bob@other.server';
// Caroline starts a chat a device from Alice // Caroline starts a chat a device from Alice
await btbv.onNewSession(aliceJid, 1); await btbv.onNewSession(aliceJid, 1);
expect(await btbv.isTrusted(aliceJid, 1), true); expect(await btbv.isTrusted(aliceJid, 1), true);

View File

@ -24,13 +24,13 @@ void main() {
2: await opkBob.pk.asBase64(), 2: await opkBob.pk.asBase64(),
}, },
); );
// Alice does X3DH // Alice does X3DH
final resultAlice = await x3dhFromBundle(bundleBob, ikAlice); final resultAlice = await x3dhFromBundle(bundleBob, ikAlice);
// Alice sends the inital message to Bob // Alice sends the inital message to Bob
// ... // ...
// Bob does X3DH // Bob does X3DH
final resultBob = await x3dhFromInitialMessage( final resultBob = await x3dhFromInitialMessage(
X3DHMessage( X3DHMessage(
@ -42,7 +42,7 @@ void main() {
opkBob, opkBob,
ikBob, ikBob,
); );
expect(resultAlice.sk, resultBob.sk); expect(resultAlice.sk, resultBob.sk);
expect(resultAlice.ad, resultBob.ad); expect(resultAlice.ad, resultBob.ad);
}); });
@ -66,18 +66,14 @@ void main() {
2: await opkBob.pk.asBase64(), 2: await opkBob.pk.asBase64(),
}, },
); );
// Alice does X3DH // Alice does X3DH
var exception = false; var exception = false;
try { try {
await x3dhFromBundle(bundleBob, ikAlice); await x3dhFromBundle(bundleBob, ikAlice);
} catch (e) { } catch(e) {
exception = true; exception = true;
expect( expect(e is InvalidSignatureException, true, reason: 'Expected InvalidSignatureException, but got $e');
e is InvalidSignatureException,
true,
reason: 'Expected InvalidSignatureException, but got $e',
);
} }
expect(exception, true, reason: 'Expected test failure'); expect(exception, true, reason: 'Expected test failure');