Matrix protocol notes

analysis of matrix-js-sdk protocol implementation

Documentation

Basic example on how to use the Client Server API

latest version of the client-server API

Basic tutorial about implementation of End-to-End encryption

Reference implementations

Some reference implementations I took a look:

Matrix JS SDK git repository

mautrix-go git repository

Notes on End-to-End Encryption

Matrix end-to-end implementation guide

Terminology:

Inbound session
the session started from another user/device: there is a lot of them and they are rotated frequently.
Outbound session
the session started from local user/device: there is zero or one of them per room.

In order to exchange keys with another device, first, we should have keys of devices we want to share our keys with. This is done for all devices that don't yet have an outbound session (TODO: is this correct?). This is done by calling the /keys/claim endpoint endpoint. Once we have the key for a given device, we need to create a m.room_key event like this:

{
    "content": {
        "algorithm": "m.megolm.v1.aes-sha2",
        "room_id": "!Cuyf34gef24t:localhost",
        "session_id": "X3lUlvLELLYxeTx4yOVu6UDpasGEVO0Jbu+QFnm0cKQ",
        "session_key": "AgAAAADxKHa9uFxcXzwYoNueL5Xqi69IkD4sni8LlfJL7qNBEY..."
    },
    "type": "m.room_key"
}

/keys/claim endpoint

m.room_key

This payload is itself is encrypted and inserted inside a type 0 m.room_encrypted event, like this (in this case it is set as the <encrypted_payload_base_64> field:

{
  "type": "m.room.encrypted",
  "content": {
    "algorithm": "m.olm.v1.curve25519-aes-sha2",
    "sender_key": "<sender_curve25519_key>",
    "ciphertext": {
      "<device_curve25519_key>": {
        "type": 0,
        "body": "<encrypted_payload_base_64>"
      }
    }
  }
}

m.room_encrypted

TODO: Will be continued...

Common errors

{"errcode":"M_UNRECOGNIZED","error":"Unrecognized request"}

Possible causes:

libolm troubleshooting

First, always use Sanitizers when developing something in C. That said, if the Address Sanitizer gives you this error:

    #0 0x7828bdc04036 in olm::Ratchet::initialise_as_alice(unsigned char const*, unsigned long, _olm_curve25519_key_pair const&) /path/opt/olm-3.2.4/src/ratchet.cpp:219

... it may mean that you may have forgotten to initialize your session with olm_session(session).

Address Sanitizer