Compare commits

..

5 Commits

9 changed files with 258 additions and 29 deletions

View File

@ -1,5 +1,155 @@
//import 'package:omemo_dart/omemo_dart.dart'; import 'dart:convert';
import 'package:omemo_dart/omemo_dart.dart';
void main() { /// This example aims to demonstrate how omemo_dart is used. Since omemo_dart is not
// TODO(PapaTutuWawa): Currently NOOP /// dependent on any XMPP library, you need to convert stanzas to the appropriate
/// intermediary format and back.
void main() async {
const aliceJid = 'alice@some.server';
const bobJid = 'bob@other.serve';
// You are Alice and want to begin using OMEMO, so you first create a SessionManager
final aliceSession = await OmemoSessionManager.generateNewIdentity(
// The bare Jid of Alice as a String
aliceJid,
// 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
// no persistent data and can thus use the MemoryBTBVTrustManager. If we wanted to keep
// the state, we would have to override BlindTrustBeforeVerificationTrustManager.
MemoryBTBVTrustManager(),
// Here we specify how many Onetime Prekeys we want to have. XEP-0384 recommends around
// 100 OPKs, so let's generate 100. The parameter defaults to 100.
//opkAmount: 100,
);
// 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
// request it using PEP and then convert the device bundle into a OmemoBundle object.
final bobSession = await OmemoSessionManager.generateNewIdentity(
bobJid,
MemoryBTBVTrustManager(),
// Just for illustrative purposes
opkAmount: 1,
);
// Alice prepares to send the message to Bob, so she builds the message stanza and
// collects all the children of the stanza that should be encrypted into a string.
const aliceMessageStanzaBody = '''
<body>Hello Bob, it's me, Alice!</body>
<super-secret-element xmlns='super-secret-element' />
''';
// Since OMEMO 0.8.3 mandates usage of XEP-0420: Stanza Content Encryption, we have to
// wrap our acual payload - aliceMessageStanzaBody - into an SCE envelope. Note that
// the rpad element must contain a random string. See XEP-0420 for recommendations.
// OMEMO makes the <time /> element optional, but let's use for this example.
const envelope = '''
<envelope xmlns='urn:xmpp:sce:1'>
<content>
$aliceMessageStanzaBody
</content>
<rpad>s0m3-r4nd0m-b9t3s</rpad>
<from jid='$aliceJid' />
<time stamp='1969-07-20T21:56:15-05:00' />
</envelope>
''';
// Since Alice has no open session with Bob, we need to tell the session manager to build
// it when sending the message.
final message = await aliceSession.encryptToJid(
// The bare receiver Jid
bobJid,
// The envelope we want to encrypt
envelope,
// Since this is the first time Alice contacts Bob from this device, we need to create
// 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 (await bobSession.getDevice()).toBundle(),
],
);
// Alice now builds the actual message stanza for Bob
final payload = base64.encode(message.ciphertext!);
final aliceDevice = await aliceSession.getDevice();
// ignore: unused_local_variable
final bobDevice = await bobSession.getDevice();
// Since we know we have just one key for Bob, we take a shortcut. However, in the real
// world, we have to serialise every EncryptedKey to a <key /> element and group them
// per Jid.
final key = message.encryptedKeys[0];
// Note that the key's "kex" attribute refers to key.kex. It just means that the
// encrypted key also contains the required data for Bob to build a session with Alice.
// ignore: unused_local_variable
final aliceStanza = '''
<message from='$aliceJid/device1' to='$bobJid/device2'>
<encrypted xmlns='urn:xmpp:omemo:2'>
<header sid='${aliceDevice.id}'>
<keys jid='$bobJid'>
<key rid='${key.rid} kex='true'>
${key.value}
</key>
</keys>
</header>
<payload>
$payload
</payload>
</encrypted>
</message>
''';
// Alice can now send this message to Bob using our preferred XMPP library.
// ...
// Bob now receives an OMEMO encrypted message from Alice and wants to decrypt it.
// Since we have just one key, let's just deserialise the one key by hand.
final keys = [
EncryptedKey(bobJid, key.rid, key.value, true),
];
// Bob extracts the payload and attempts to decrypt it.
// ignore: unused_local_variable
final bobMessage = await bobSession.decryptMessage(
// base64 decode the payload
base64.decode(payload),
// Specify the Jid of the sender
aliceJid,
// Specify the device identifier of the sender (the "sid" attribute of <header />)
aliceDevice.id,
// The deserialised keys
keys,
);
// 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
// of the envelope we just decrypted.
// Bob now has a session with Alice and can send encrypted message to her.
// Since they both used the BlindTrustBeforeVerificationTrustManager, they currently
// use blind trust, meaning that both Alice and Bob accept new devices without any
// hesitation. If Alice, however, decides to verify one of Bob's devices and sets
// it as verified using
// ```
// await aliceSession.trustManager.setDeviceTrust(bobJid, bobDevice.id, BTBVTrustState.verified)
// ```
// then Alice's OmemoSessionManager won't encrypt to new devices unless they are also
// verified. To prevent user confusion, you should check if every device is trusted
// before sending the message and ask the user for a trust decision.
// If you want to make the BlindTrustBeforeVerificationTrustManager persistent, then
// you need to subclass it and override the `Future<void> commitState()` and
// `Future<void> loadState()` functions. commitState is called everytime the internal
// state gets changed. loadState never gets automatically called but is more of a
// function for the user to restore the trust manager. In those functions you have
// access to `ratchetMap`, which maps a `RatchetMapKey` - essentially a tuple consisting
// of a bare Jid and the device identifier - to the trust state, and `devices` which
// maps a bare Jid to its device identifiers.
// To make the entire OmemoSessionManager persistent, you have two options:
// - use the provided `toJson()` and `fromJson()` functions. They, however, serialise
// and deserialise *ALL* known sessions, so it might be slow.
// - subscribe to the session manager's `eventStream`. There, events get triggered
// everytime a ratchet changes, our own device changes or the internal ratchet map
// gets changed. This give finer control over the the serialisation. The session
// manager can then be restored using its constructor. For a list of events, see
// lib/src/omemo/events.dart.
} }

View File

@ -2,14 +2,15 @@ library omemo_dart;
export 'src/double_ratchet/double_ratchet.dart'; export 'src/double_ratchet/double_ratchet.dart';
export 'src/errors.dart'; export 'src/errors.dart';
export 'src/events.dart';
export 'src/helpers.dart'; export 'src/helpers.dart';
export 'src/keys.dart'; export 'src/keys.dart';
export 'src/omemo/bundle.dart'; export 'src/omemo/bundle.dart';
export 'src/omemo/device.dart'; export 'src/omemo/device.dart';
export 'src/omemo/encrypted_key.dart'; export 'src/omemo/encrypted_key.dart';
export 'src/omemo/encryption_result.dart'; export 'src/omemo/encryption_result.dart';
export 'src/omemo/events.dart';
export 'src/omemo/fingerprint.dart'; export 'src/omemo/fingerprint.dart';
export 'src/omemo/ratchet_map_key.dart';
export 'src/omemo/sessionmanager.dart'; export 'src/omemo/sessionmanager.dart';
export 'src/trust/base.dart'; export 'src/trust/base.dart';
export 'src/trust/btbv.dart'; export 'src/trust/btbv.dart';

View File

@ -1,6 +1,5 @@
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
@internal
@immutable @immutable
class RatchetMapKey { class RatchetMapKey {

View File

@ -7,13 +7,13 @@ import 'package:meta/meta.dart';
import 'package:omemo_dart/src/crypto.dart'; import 'package:omemo_dart/src/crypto.dart';
import 'package:omemo_dart/src/double_ratchet/double_ratchet.dart'; import 'package:omemo_dart/src/double_ratchet/double_ratchet.dart';
import 'package:omemo_dart/src/errors.dart'; import 'package:omemo_dart/src/errors.dart';
import 'package:omemo_dart/src/events.dart';
import 'package:omemo_dart/src/helpers.dart'; import 'package:omemo_dart/src/helpers.dart';
import 'package:omemo_dart/src/keys.dart'; import 'package:omemo_dart/src/keys.dart';
import 'package:omemo_dart/src/omemo/bundle.dart'; import 'package:omemo_dart/src/omemo/bundle.dart';
import 'package:omemo_dart/src/omemo/device.dart'; import 'package:omemo_dart/src/omemo/device.dart';
import 'package:omemo_dart/src/omemo/encrypted_key.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/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/fingerprint.dart';
import 'package:omemo_dart/src/omemo/ratchet_map_key.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_authenticated_message.dart';
@ -78,6 +78,7 @@ class OmemoSessionManager {
/// The trust manager /// The trust manager
final TrustManager _trustManager; final TrustManager _trustManager;
TrustManager get trustManager => _trustManager;
/// A stream that receives events regarding the session /// A stream that receives events regarding the session
Stream<OmemoEvent> get eventStream => _eventStreamController.stream; Stream<OmemoEvent> get eventStream => _eventStreamController.stream;
@ -224,8 +225,11 @@ class OmemoSessionManager {
// We assume that the user already checked if the session exists // We assume that the user already checked if the session exists
for (final jid in jids) { for (final jid in jids) {
for (final deviceId in _deviceMap[jid]!) { for (final deviceId in _deviceMap[jid]!) {
// Empty OMEMO messages are allowed to bypass trust
if (plaintext != null) {
// Only encrypt to devices that are trusted // Only encrypt to devices that are trusted
if (!(await _trustManager.isTrusted(jid, deviceId))) continue; if (!(await _trustManager.isTrusted(jid, deviceId))) continue;
}
final ratchetKey = RatchetMapKey(jid, deviceId); final ratchetKey = RatchetMapKey(jid, deviceId);
final ratchet = _ratchetMap[ratchetKey]!; final ratchet = _ratchetMap[ratchetKey]!;

View File

@ -13,29 +13,33 @@ enum BTBVTrustState {
verified, verified,
} }
class BlindTrustBeforeVerificationTrustManager extends TrustManager { /// A TrustManager that implements the idea of Blind Trust Before Verification.
/// See https://gultsch.de/trust.html for more details.
abstract class BlindTrustBeforeVerificationTrustManager extends TrustManager {
BlindTrustBeforeVerificationTrustManager() BlindTrustBeforeVerificationTrustManager()
: _trustCache = {}, : trustCache = {},
_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
final Map<RatchetMapKey, BTBVTrustState> _trustCache; @protected
final Map<RatchetMapKey, BTBVTrustState> trustCache;
/// Mapping of Jids to their device identifiers /// Mapping of Jids to their device identifiers
final Map<String, List<int>> _devices; @protected
final Map<String, List<int>> devices;
/// The lock for _devices and _trustCache /// The lock for devices and trustCache
final Lock _lock; final Lock _lock;
/// Returns true if [jid] has at least one device that is verified. If not, returns false. /// Returns true if [jid] has at least one device that is verified. If not, returns false.
/// Note that this function accesses _devices and _trustCache, which requires that the /// Note that this function accesses devices and trustCache, which requires that the
/// lock for those two maps (_lock) has been aquired before calling. /// lock for those two maps (_lock) has been aquired before calling.
bool _hasAtLeastOneVerifiedDevice(String jid) { bool _hasAtLeastOneVerifiedDevice(String jid) {
if (!_devices.containsKey(jid)) return false; if (!devices.containsKey(jid)) return false;
return _devices[jid]!.any((id) { return devices[jid]!.any((id) {
return _trustCache[RatchetMapKey(jid, id)]! == BTBVTrustState.verified; return trustCache[RatchetMapKey(jid, id)]! == BTBVTrustState.verified;
}); });
} }
@ -43,7 +47,7 @@ class BlindTrustBeforeVerificationTrustManager extends TrustManager {
Future<bool> isTrusted(String jid, int deviceId) async { Future<bool> isTrusted(String jid, int deviceId) async {
var returnValue = false; var returnValue = false;
await _lock.synchronized(() async { await _lock.synchronized(() async {
final trustCacheValue = _trustCache[RatchetMapKey(jid, deviceId)]; final trustCacheValue = trustCache[RatchetMapKey(jid, deviceId)];
if (trustCacheValue == BTBVTrustState.notTrusted) { if (trustCacheValue == BTBVTrustState.notTrusted) {
returnValue = false; returnValue = false;
return; return;
@ -71,16 +75,19 @@ class BlindTrustBeforeVerificationTrustManager extends TrustManager {
Future<void> onNewSession(String jid, int deviceId) async { Future<void> onNewSession(String jid, int deviceId) async {
await _lock.synchronized(() async { await _lock.synchronized(() async {
if (_hasAtLeastOneVerifiedDevice(jid)) { if (_hasAtLeastOneVerifiedDevice(jid)) {
_trustCache[RatchetMapKey(jid, deviceId)] = BTBVTrustState.notTrusted; trustCache[RatchetMapKey(jid, deviceId)] = BTBVTrustState.notTrusted;
} else { } else {
_trustCache[RatchetMapKey(jid, deviceId)] = BTBVTrustState.blindTrust; trustCache[RatchetMapKey(jid, deviceId)] = BTBVTrustState.blindTrust;
} }
if (_devices.containsKey(jid)) { if (devices.containsKey(jid)) {
_devices[jid]!.add(deviceId); devices[jid]!.add(deviceId);
} else { } else {
_devices[jid] = List<int>.from([deviceId]); devices[jid] = List<int>.from([deviceId]);
} }
// Commit the state
await commitState();
}); });
} }
@ -89,8 +96,8 @@ class BlindTrustBeforeVerificationTrustManager extends TrustManager {
final map = <int, BTBVTrustState>{}; final map = <int, BTBVTrustState>{};
await _lock.synchronized(() async { await _lock.synchronized(() async {
for (final deviceId in _devices[jid]!) { for (final deviceId in devices[jid]!) {
map[deviceId] = _trustCache[RatchetMapKey(jid, deviceId)]!; map[deviceId] = trustCache[RatchetMapKey(jid, deviceId)]!;
} }
}); });
@ -100,10 +107,33 @@ 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(String jid, int deviceId, BTBVTrustState state) async { Future<void> setDeviceTrust(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;
// Commit the state
await commitState();
}); });
} }
/// Called when the state of the trust manager has been changed. Allows the user to
/// commit the trust state to persistent storage.
@visibleForOverriding
Future<void> commitState();
/// Called when the user wants to restore the state of the trust manager. The format
/// and actual storage mechanism is left to the user.
@visibleForOverriding
Future<void> loadState();
@visibleForTesting @visibleForTesting
BTBVTrustState getDeviceTrust(String jid, int deviceId) => _trustCache[RatchetMapKey(jid, deviceId)]!; BTBVTrustState getDeviceTrust(String jid, int deviceId) => trustCache[RatchetMapKey(jid, deviceId)]!;
}
/// A BTBV TrustManager that does not commit its state to persistent storage. Well suited
/// for testing.
class MemoryBTBVTrustManager extends BlindTrustBeforeVerificationTrustManager {
@override
Future<void> commitState() async {}
@override
Future<void> loadState() async {}
} }

14
lib/src/trust/never.dart Normal file
View File

@ -0,0 +1,14 @@
import 'package:meta/meta.dart';
import 'package:omemo_dart/src/trust/base.dart';
/// Only use for testing!
/// An implementation of TrustManager that never trusts any device and thus
/// has no internal state.
@visibleForTesting
class NeverTrustingTrustManager extends TrustManager {
@override
Future<bool> isTrusted(String jid, int deviceId) async => false;
@override
Future<void> onNewSession(String jid, int deviceId) async {}
}

View File

@ -1,5 +1,6 @@
import 'package:omemo_dart/omemo_dart.dart'; import 'package:omemo_dart/omemo_dart.dart';
import 'package:omemo_dart/src/trust/always.dart'; import 'package:omemo_dart/src/trust/always.dart';
import 'package:omemo_dart/src/trust/never.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
void main() { void main() {
@ -336,4 +337,34 @@ void main() {
); );
expect(messagePlaintext, bobMessage); expect(messagePlaintext, bobMessage);
}); });
test('Test trust bypassing with empty OMEMO messages', () async {
const aliceJid = 'alice@server.example';
const bobJid = 'bob@other.server.example';
// Alice and Bob generate their sessions
final aliceSession = await OmemoSessionManager.generateNewIdentity(
aliceJid,
NeverTrustingTrustManager(),
opkAmount: 1,
);
final bobSession = await OmemoSessionManager.generateNewIdentity(
bobJid,
NeverTrustingTrustManager(),
opkAmount: 1,
);
// Alice encrypts an empty message for Bob
final aliceMessage = await aliceSession.encryptToJid(
bobJid,
null,
newSessions: [
await (await bobSession.getDevice()).toBundle(),
],
);
// Despite Alice not trusting Bob's device, we should have encrypted it for his
// untrusted device.
expect(aliceMessage.encryptedKeys.length, 1);
});
} }

View File

@ -4,7 +4,7 @@ import 'package:test/test.dart';
void main() { void main() {
test('Test the Blind Trust Before Verification TrustManager', () async { test('Test the Blind Trust Before Verification TrustManager', () async {
// Caroline's BTBV manager // Caroline's BTBV manager
final btbv = BlindTrustBeforeVerificationTrustManager(); 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';