The issue you're encountering arises from the way the group key is derived and managed when there are more than two users in the chat. When additional peers join or leave the room, the group key derivation process doesn't produce consistent results among all peers, leading to decryption failures.
Understanding the Problem
In your code, the group key is derived by combining pairwise ECDH shared secrets between the local peer and all other peers. Specifically, you:
-
Collect peer IDs and public keys: You gather all peer IDs (including your own) and sort them to ensure consistent ordering.
-
Derive pairwise shared secrets: For each peer (excluding yourself), you use ECDH to derive a shared secret.
-
Concatenate and hash shared secrets: You concatenate all the shared secrets and hash them to obtain the group key.
The problem arises because:
-
Dynamic Membership: When peers join or leave, not all peers might have the same set of peer IDs at the exact moment they derive the group key.
-
Asynchronous Updates: There's no synchronization mechanism to ensure all peers have updated their peerPublicKeys and derived the new group key before messages are sent using it.
-
Inconsistent Ordering: Even with sorting, if the set of peers differs among peers (due to timing issues), the concatenated shared secrets will differ, leading to different group keys.
Solution
To fix this issue, you need to implement proper group key management that handles dynamic group membership and ensures consistent key derivation among all peers. Here's how you can do it:
1. Implement a Group Key Agreement Protocol
Using pairwise ECDH is suitable for two parties but doesn't scale safely for groups. Instead, consider implementing a group key agreement protocol designed for dynamic groups, such as:
- Tree-based Group Diffie-Hellman (TGDH)
- Group Domain of Interpretation (GDOI)
- Instruction-tree-based methods (e.g., Burmester-Desmedt protocol)
These protocols are designed to securely manage group keys in the presence of dynamic membership changes.
2. Synchronize Group Key Updates
Ensure that all peers only start using a new group key after:
- All peers have derived the new key.
- There's confirmation that every peer has updated their key material.
Implement Synchronization Steps:
- When a peer joins or leaves, broadcast a
group-key-update message.
- Peers set a flag indicating a pending key update and pause message sending.
- After deriving the new group key, each peer sends an acknowledgment.
- Once all acknowledgments are received, peers set the new key as active and resume sending messages.
3. Handle Key Versioning and Consistency
Modify how the groupKeyVersion is managed:
- Use a monotonically increasing counter or include a timestamp to represent the key version.
- Ensure that all peers agree on the
groupKeyVersion before using the new key.
Example Modification:
// In deriveGroupKey, after computing the new key:
groupKeyVersion = previousGroupKeyVersion + 1;
// Or use a timestamp
groupKeyVersion = Date.now();
// Broadcast the new version to all peers
broadcastGroupKeyVersion(groupKeyVersion);
4. Buffer Messages During Key Updates
Modify your message handling to buffer incoming messages that are:
- Encrypted with a future
groupKeyVersion until the new key is active.
- Encrypted with an old
groupKeyVersion for a short grace period to handle in-transit messages.
Example Adjustment:
channel.onmessage = async (event) => {
let encryptedMessage = JSON.parse(event.data);
if (encryptedMessage.version > groupKeyVersion) {
// Buffer message until group key is updated
bufferMessage(encryptedMessage);
return;
} else if (encryptedMessage.version < groupKeyVersion) {
// Discard old messages or handle as needed
return;
}
// Proceed to decrypt the message
};
5. Ensure Consistent Ordering and Complete Peer List
Before deriving the group key:
- Confirm that you have the complete and identical list of peers that other peers have.
- Use a reliable method to synchronize peer lists, such as having a designated group manager or using the server to distribute a consistent peer list.
Example Adjustment:
- When a new peer joins, the server sends an updated peer list to all peers.
- Peers wait until they receive the updated list before deriving the new group key.
6. Avoid Immediate Rekeying on Membership Changes
Alternatively, consider not rekeying immediately when peers join or leave, particularly if real-time synchronization is challenging.
- Set intervals or specific events that trigger rekeying.
- Use a separate mechanism to securely share the group key with new peers without disrupting the current key for existing peers.
Rewriting Critical Code Sections
Implementing Synchronization on Group Key Update:
async function deriveGroupKey() {
// ... existing code to derive the group key ...
// Notify peers that the group key has been updated
sendGroupKeyUpdateNotification(groupKeyVersion);
// Wait for acknowledgments from all peers
await waitForAllPeersToConfirmKeyUpdate();
// Now the group key is ready to be used
isGroupKeyReady = true;
}
function sendGroupKeyUpdateNotification(version) {
sendMessageToPeers(JSON.stringify({
type: 'group-key-update',
version: version
}));
}
function waitForAllPeersToConfirmKeyUpdate() {
return new Promise((resolve) => {
let confirmedPeers = new Set();
// Listen for acknowledgments
function onAck(peerId) {
confirmedPeers.add(peerId);
if (confirmedPeers.size === Object.keys(peerPublicKeys).length) {
// All peers have confirmed
resolve();
}
}
// Set up listener for acknowledgments
// You need to implement the mechanism to receive acknowledgments
});
}
Handling Incoming Group Key Update Notifications:
channel.onmessage = async (event) => {
let data = JSON.parse(event.data);
if (data.type === 'group-key-update') {
// Update the groupKeyVersion and derive the new key
groupKeyVersion = data.version;
await deriveGroupKey();
// Send acknowledgment back to the sender
sendGroupKeyUpdateAck();
return;
}
// ... existing message handling code ...
};
Conclusion
Implementing secure group key management with dynamic membership is non-trivial. The current approach of concatenating pairwise ECDH shared secrets and hashing them doesn't suffice for scenarios where peers can join or leave at any time.
By incorporating proper synchronization mechanisms, group key agreement protocols, and careful handling of key updates, you can ensure that all peers derive and use the same group key, preventing decryption failures when more than two users are in the chat.
Recommendations:
- Study existing group key management protocols to choose one that fits your needs.
- Consider the security implications of the chosen method, especially regarding forward and backward secrecy.
- Test your implementation extensively with edge cases, such as simultaneous joins/leaves, network delays, and message ordering issues.
Implementing these changes will make your encrypted group chat more robust and capable of handling multiple users without decryption errors.