]> gitweb.ps.run Git - matrix_esp_thesis/blobdiff - src/matrix.c
generate identity keys
[matrix_esp_thesis] / src / matrix.c
index 7cc4de9fe11d25a054d6e62a44563d3f97682b82..33988b4a12710c35419ce363513b4c4cad21fc94 100644 (file)
 #define LOGIN_RESPONSE_SIZE 1024\r
 #define LOGIN_URL "/_matrix/client/v3/login"\r
 \r
-#define ROOMEVENT_REQUEST_SIZE 1024\r
+#define ENCRYPTED_REQUEST_SIZE 512\r
+#define ENCRYPTED_EVENT_SIZE 1024\r
+#define ROOMEVENT_REQUEST_SIZE 256\r
 #define ROOMEVENT_RESPONSE_SIZE 1024\r
 #define ROOMEVENT_URL "/_matrix/client/v3/rooms/%s/send/%s/%d"\r
 \r
+#define TODEVICE_EVENT_SIZE 512\r
+#define TODEVICE_URL "/_matrix/client/v3/sendToDevice/%s/%d"\r
+\r
+#define KEYS_QUERY_URL "/_matrix/client/v3/keys/query"\r
+#define KEYS_QUERY_REQUEST_SIZE 256\r
+#define KEYS_QUERY_RESPONSE_SIZE 1024\r
+\r
+#define JSON_QUERY_SIZE 128\r
+\r
+\r
+\r
+void\r
+Randomize(uint8_t * random, int randomLen)\r
+{\r
+    static bool first = false;\r
+    if (first) { srand(time(0)); first = false; }\r
+\r
+    for (int i = 0; i < randomLen; i++)\r
+    {\r
+        random[i] = rand() % 256;\r
+    }\r
+}\r
+\r
+bool\r
+JsonEscape(\r
+    char * sIn, int sInLen,\r
+    char * sOut, int sOutCap)\r
+{\r
+    int sOutIndex = 0;\r
+\r
+    for (int i = 0; i < sInLen; i++)\r
+    {\r
+        if (i >= sOutCap)\r
+            return false;\r
+        \r
+        if (sIn[i] == '.' ||\r
+            sIn[i] == '[' ||\r
+            sIn[i] == ']'\r
+        ) {\r
+            sOut[sOutIndex++] = '\\';\r
+        }\r
+        sOut[sOutIndex++] = sIn[i];\r
+    }\r
+\r
+    if (sOutIndex < sOutCap)\r
+        sOut[sOutIndex] = '\0';\r
+\r
+    return true;\r
+}\r
+\r
+// TODO: in/outbound sessions\r
+bool\r
+MatrixOlmSessionInit(\r
+    MatrixOlmSession * session,\r
+    const char * deviceId)\r
+{\r
+    memset(session, 0, sizeof(MatrixOlmSession));\r
+\r
+    static uint8_t random[MEGOLM_INIT_RANDOM_SIZE];\r
+    Randomize(random, MEGOLM_INIT_RANDOM_SIZE);\r
+\r
+    session->deviceId = deviceId;\r
+\r
+    session->session =\r
+        olm_session(session->memory);\r
+\r
+    return session->session != NULL;\r
+}\r
+\r
+bool\r
+MatrixOlmSessionEncrypt(\r
+    MatrixOlmSession * session,\r
+    const char * plaintext,\r
+    char * outBuffer, int outBufferCap)\r
+{\r
+    static uint8_t random[OLM_ENCRYPT_RANDOM_SIZE];\r
+    Randomize(random, OLM_ENCRYPT_RANDOM_SIZE);\r
+\r
+    size_t res = olm_encrypt(session->session,\r
+        plaintext, strlen(plaintext),\r
+        random, OLM_ENCRYPT_RANDOM_SIZE,\r
+        outBuffer, outBufferCap);\r
+\r
+    return res != olm_error();\r
+}\r
+\r
+// https://matrix.org/docs/guides/end-to-end-encryption-implementation-guide#starting-a-megolm-session\r
+bool\r
+MatrixMegolmOutSessionInit(\r
+    MatrixMegolmOutSession * session,\r
+    const char * roomId)\r
+{\r
+    memset(session, 0, sizeof(MatrixMegolmOutSession));\r
+\r
+    static uint8_t random[MEGOLM_INIT_RANDOM_SIZE];\r
+    Randomize(random, MEGOLM_INIT_RANDOM_SIZE);\r
+\r
+    session->roomId = roomId;\r
+\r
+    session->session =\r
+        olm_outbound_group_session(session->memory);\r
+\r
+    olm_init_outbound_group_session(\r
+        session->session,\r
+        random,\r
+        MEGOLM_INIT_RANDOM_SIZE);\r
+\r
+    olm_outbound_group_session_id(session->session,\r
+        (uint8_t *)session->id,\r
+        MEGOLM_SESSION_ID_SIZE);\r
+        \r
+    olm_outbound_group_session_key(session->session,\r
+        (uint8_t *)session->key,\r
+        MEGOLM_SESSION_KEY_SIZE);\r
+    \r
+    return true;\r
+}\r
+\r
+bool\r
+MatrixMegolmOutSessionEncrypt(\r
+    MatrixMegolmOutSession * session,\r
+    const char * plaintext,\r
+    char * outBuffer, int outBufferCap)\r
+{\r
+    size_t res = olm_group_encrypt(session->session,\r
+        (uint8_t *)plaintext, strlen(plaintext),\r
+        (uint8_t *)outBuffer, outBufferCap);\r
+\r
+    return res != olm_error();\r
+}\r
+\r
+\r
 \r
 bool\r
 MatrixClientInit(\r
     MatrixClient * client,\r
     const char * server)\r
 {\r
-    strcpy_s(\r
-        client->server,\r
-        SERVER_SIZE,\r
-        server\r
-    );\r
+    memset(client, 0, sizeof(MatrixClient));\r
+\r
+    strcpy(client->server, server);\r
+\r
+    // init olm account\r
+    client->olmAccount = olm_account(client->olmAccountMemory);\r
+\r
+    static uint8_t random[OLM_ACCOUNT_RANDOM_SIZE];\r
+    Randomize(random, OLM_ACCOUNT_RANDOM_SIZE);\r
+\r
+    size_t res;\r
+    res = olm_create_account(\r
+        client->olmAccount,\r
+        random,\r
+        OLM_ACCOUNT_RANDOM_SIZE);\r
+\r
+    // set device key\r
+    static char deviceKeysJson[OLM_IDENTITY_KEYS_JSON_SIZE];\r
+    res =\r
+        olm_account_identity_keys(\r
+            client->olmAccount,\r
+            deviceKeysJson,\r
+            OLM_IDENTITY_KEYS_JSON_SIZE);\r
+\r
+    mjson_get_string(deviceKeysJson, res,\r
+        "$.curve25519",\r
+        client->deviceKey, DEVICE_KEY_SIZE);\r
+    mjson_get_string(deviceKeysJson, res,\r
+        "$.ed25519",\r
+        client->signingKey, SIGNING_KEY_SIZE);\r
 \r
     return true;\r
 }\r
@@ -35,11 +194,27 @@ MatrixClientSetAccessToken(
 {\r
     int accessTokenLen = strlen(accessToken);\r
 \r
-    if (accessTokenLen < ACCESS_TOKEN_SIZE - 1)\r
+    if (accessTokenLen > ACCESS_TOKEN_SIZE - 1)\r
         return false;\r
 \r
     for (int i = 0; i < accessTokenLen; i++)\r
-        client->accessTokenBuffer[i] = accessToken[i];\r
+        client->accessToken[i] = accessToken[i];\r
+\r
+    return true;\r
+}\r
+\r
+bool\r
+MatrixClientSetDeviceId(\r
+    MatrixClient * client,\r
+    const char * deviceId)\r
+{\r
+    int deviceIdLen = strlen(deviceId);\r
+\r
+    if (deviceIdLen > DEVICE_ID_SIZE - 1)\r
+        return false;\r
+\r
+    for (int i = 0; i < deviceIdLen; i++)\r
+        client->deviceId[i] = deviceId[i];\r
 \r
     return true;\r
 }\r
@@ -83,20 +258,21 @@ MatrixClientLoginPassword(
 \r
     mjson_get_string(responseBuffer, responseLen,\r
         "$.access_token",\r
-        client->accessTokenBuffer, ACCESS_TOKEN_SIZE);\r
+        client->accessToken, ACCESS_TOKEN_SIZE);\r
     mjson_get_string(responseBuffer, responseLen,\r
         "$.device_id",\r
-        client->deviceIdBuffer, DEVICE_ID_SIZE);\r
+        client->deviceId, DEVICE_ID_SIZE);\r
     mjson_get_string(responseBuffer, responseLen,\r
         "$.expires_in_ms",\r
-        client->expireMsBuffer, EXPIRE_MS_SIZE);\r
+        client->expireMs, EXPIRE_MS_SIZE);\r
     mjson_get_string(responseBuffer, responseLen,\r
         "$.refresh_token",\r
-        client->refreshTokenBuffer, REFRESH_TOKEN_SIZE);\r
+        client->refreshToken, REFRESH_TOKEN_SIZE);\r
 \r
     return true;\r
 }\r
-    \r
+\r
+// https://spec.matrix.org/v1.6/client-server-api/#put_matrixclientv3roomsroomidsendeventtypetxnid\r
 bool\r
 MatrixClientSendEvent(\r
     MatrixClient * client,\r
@@ -105,8 +281,8 @@ MatrixClientSendEvent(
     const char * msgBody)\r
 {    \r
     static char requestUrl[MAX_URL_LEN];\r
-    sprintf_s(requestUrl, MAX_URL_LEN,\r
-        ROOMEVENT_URL, roomId, msgType, time(NULL));\r
+    sprintf(requestUrl,\r
+        ROOMEVENT_URL, roomId, msgType, (int)time(NULL));\r
 \r
     static char responseBuffer[ROOMEVENT_RESPONSE_SIZE];\r
     bool result =\r
@@ -119,3 +295,408 @@ MatrixClientSendEvent(
     return result;\r
 }\r
 \r
+// https://spec.matrix.org/v1.6/client-server-api/#mroomencrypted\r
+// https://matrix.org/docs/guides/end-to-end-encryption-implementation-guide#sending-an-encrypted-message-event\r
+bool\r
+MatrixClientSendEventEncrypted(\r
+    MatrixClient * client,\r
+    const char * roomId,\r
+    const char * msgType,\r
+    const char * msgBody)\r
+{\r
+    // event json\r
+    static char requestBuffer[ROOMEVENT_REQUEST_SIZE];\r
+    sprintf(requestBuffer,\r
+        "{"\r
+        "\"type\":\"%s\","\r
+        "\"content\":%s,"\r
+        "\"room_id\":\"%s\""\r
+        "}",\r
+        msgType,\r
+        msgBody,\r
+        roomId);\r
+\r
+    // get megolm session\r
+    MatrixMegolmOutSession * outSession;\r
+    MatrixClientGetMegolmOutSession(client, roomId, &outSession);\r
+        \r
+    // encrypt\r
+    static char encryptedBuffer[ENCRYPTED_REQUEST_SIZE];\r
+    MatrixMegolmOutSessionEncrypt(outSession,\r
+        requestBuffer,\r
+        encryptedBuffer, ENCRYPTED_REQUEST_SIZE);\r
+\r
+    // encrypted event json\r
+    const char * senderKey = client->deviceKey;\r
+    const char * sessionId = outSession->id;\r
+    const char * deviceId = client->deviceId;\r
+\r
+    static char encryptedEventBuffer[ENCRYPTED_EVENT_SIZE];\r
+    sprintf(encryptedEventBuffer,\r
+        "{"\r
+        "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
+        "\"sender_key\":\"%s\","\r
+        "\"ciphertext\":\"%s\","\r
+        "\"session_id\":\"%s\","\r
+        "\"device_id\":\"%s\""\r
+        "}",\r
+        senderKey,\r
+        encryptedBuffer,\r
+        sessionId,\r
+        deviceId);\r
+\r
+    // send\r
+    return MatrixClientSendEvent(client,\r
+        roomId,\r
+        "m.room.encrypted",\r
+        encryptedEventBuffer);\r
+}\r
+\r
+// https://spec.matrix.org/v1.6/client-server-api/#get_matrixclientv3sync\r
+bool\r
+MatrixClientSync(\r
+    MatrixClient * client,\r
+    char * outSyncBuffer, int outSyncCap)\r
+{\r
+    return\r
+        MatrixHttpGet(client,\r
+            "/_matrix/client/v3/sync",\r
+            outSyncBuffer, outSyncCap,\r
+            true);\r
+}\r
+\r
+bool\r
+MatrixClientShareMegolmOutSession(\r
+    MatrixClient * client,\r
+    const char * deviceId,\r
+    MatrixMegolmOutSession * session)\r
+{\r
+    // generate room key event\r
+    char eventBuffer[KEY_SHARE_EVENT_LEN];\r
+    sprintf(eventBuffer,\r
+        "{"\r
+            "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
+            "\"room_id\":\"%s\","\r
+            "\"session_id\":\"%s\","\r
+            "\"session_key\":\"%s\""\r
+        "}",\r
+        session->roomId,\r
+        session->id,\r
+        session->key\r
+    );\r
+\r
+    // get olm session\r
+    MatrixOlmSession * olmSession;\r
+    MatrixClientGetOlmSession(client, deviceId, &olmSession);\r
+\r
+    // encrypt\r
+    char encryptedBuffer[KEY_SHARE_EVENT_LEN];\r
+    MatrixOlmSessionEncrypt(olmSession,\r
+        eventBuffer,\r
+        encryptedBuffer, KEY_SHARE_EVENT_LEN);\r
+\r
+    // send\r
+    MatrixClientSendToDeviceEncrypted(client,\r
+        client->userId,\r
+        deviceId,\r
+        encryptedBuffer,\r
+        "m.room_key");\r
+\r
+    return true;\r
+}\r
+\r
+// bool\r
+// MatrixClientSetMegolmOutSession(\r
+//     MatrixClient * client,\r
+//     const char * roomId,\r
+//     MatrixMegolmOutSession session)\r
+// {\r
+//     if (client->numMegolmOutSessions < 10)\r
+//     {\r
+//         session.roomId = roomId;\r
+//         client->megolmOutSessions[client->numMegolmOutSessions] = session;\r
+//         client->numMegolmOutSessions++;\r
+\r
+//         return true;\r
+//     }\r
+//     return false;\r
+// }\r
+\r
+bool\r
+MatrixClientGetMegolmOutSession(\r
+    MatrixClient * client,\r
+    const char * roomId,\r
+    MatrixMegolmOutSession ** outSession)\r
+{\r
+    for (int i = 0; i < client->numMegolmOutSessions; i++)\r
+    {\r
+        if (strcmp(client->megolmOutSessions[i].roomId, roomId) == 0)\r
+        {\r
+            *outSession = &client->megolmOutSessions[i];\r
+            return true;\r
+        }\r
+    }\r
+\r
+    if (client->numMegolmOutSessions < NUM_MEGOLM_SESSIONS)\r
+    {\r
+        MatrixMegolmOutSessionInit(\r
+            &client->megolmOutSessions[client->numMegolmOutSessions],\r
+            roomId);\r
+\r
+        *outSession = &client->megolmOutSessions[client->numMegolmOutSessions];\r
+        \r
+        client->numMegolmOutSessions++;\r
+\r
+        return true;\r
+    }\r
+\r
+    return false;\r
+}\r
+\r
+bool\r
+MatrixClientGetOlmSession(\r
+    MatrixClient * client,\r
+    const char * deviceId,\r
+    MatrixOlmSession ** outSession)\r
+{\r
+    for (int i = 0; i < client->numOlmSessions; i++)\r
+    {\r
+        if (strcmp(client->olmSessions[i].deviceId, deviceId) == 0)\r
+        {\r
+            *outSession = &client->olmSessions[i];\r
+            return true;\r
+        }\r
+    }\r
+\r
+    if (client->numOlmSessions < NUM_OLM_SESSIONS)\r
+    {\r
+        MatrixOlmSessionInit(\r
+            &client->olmSessions[client->numOlmSessions],\r
+            deviceId);\r
+\r
+        *outSession = &client->olmSessions[client->numOlmSessions];\r
+        \r
+        client->numOlmSessions++;\r
+\r
+        return true;\r
+    }\r
+\r
+    return false;\r
+}\r
+\r
+// https://spec.matrix.org/v1.6/client-server-api/#put_matrixclientv3sendtodeviceeventtypetxnid\r
+bool\r
+MatrixClientSendToDevice(\r
+    MatrixClient * client,\r
+    const char * userId,\r
+    const char * deviceId,\r
+    const char * message,\r
+    const char * msgType)\r
+{\r
+    static char requestUrl[MAX_URL_LEN];\r
+    sprintf(requestUrl,\r
+        TODEVICE_URL, msgType, (int)time(NULL));\r
+\r
+    static char eventBuffer[TODEVICE_EVENT_SIZE];\r
+    snprintf(eventBuffer, TODEVICE_EVENT_SIZE,\r
+        "{"\r
+            "\"messages\": {"\r
+                "\"%s\": {"\r
+                    "\"%s\":%s"\r
+                "}"\r
+            "}"\r
+        "}",\r
+        userId,\r
+        deviceId,\r
+        message);\r
+\r
+    static char responseBuffer[ROOMEVENT_RESPONSE_SIZE];\r
+    bool result =\r
+        MatrixHttpPut(client,\r
+            requestUrl,\r
+            eventBuffer,\r
+            responseBuffer, ROOMEVENT_RESPONSE_SIZE,\r
+            true);\r
+    \r
+    return result;\r
+}\r
+\r
+bool\r
+MatrixClientSendToDeviceEncrypted(\r
+    MatrixClient * client,\r
+    const char * userId,\r
+    const char * deviceId,\r
+    const char * message,\r
+    const char * msgType)\r
+{\r
+    // get olm session\r
+    MatrixOlmSession * olmSession;\r
+    MatrixClientGetOlmSession(client, deviceId, &olmSession);\r
+\r
+    // create event json\r
+    char deviceKey[DEVICE_KEY_SIZE];\r
+    MatrixClientGetDeviceKey(client, deviceId, deviceKey, DEVICE_KEY_SIZE);\r
+    const char * senderKey = client->deviceKey;\r
+    \r
+    static char eventBuffer[TODEVICE_EVENT_SIZE];\r
+    sprintf(eventBuffer,\r
+        "{"\r
+        "\"type\": \"%s\","\r
+        "\"content\": \"%s\","\r
+        "\"sender\": \"%s\","\r
+        "\"recipient\": \"%s\","\r
+        "\"recipient_keys\": {"\r
+          "\"ed25519\": \"%s\""\r
+        "},"\r
+        "\"keys\": {"\r
+          "\"ed25519\": \"%s\""\r
+        "}"\r
+        "}",\r
+        msgType,\r
+        message,\r
+        client->userId,\r
+        userId, // recipient user id\r
+        deviceKey, // recipient device key\r
+        client->deviceKey);\r
+\r
+    // encrypt\r
+    static char encryptedBuffer[ENCRYPTED_REQUEST_SIZE];\r
+    MatrixOlmSessionEncrypt(olmSession,\r
+        eventBuffer,\r
+        encryptedBuffer, ENCRYPTED_REQUEST_SIZE);\r
+\r
+    static char encryptedEventBuffer[ENCRYPTED_EVENT_SIZE];\r
+    sprintf(encryptedEventBuffer,\r
+        "{"\r
+        "\"algorithm\":\"m.megolm.v1.aes-sha2\","\r
+        "\"sender_key\":\"%s\","\r
+        "\"ciphertext\":{"\r
+          "\"%s\":{"\r
+            "\"body\":\"%s\","\r
+            "\"type\":\"%d\""\r
+          "}"\r
+        "}"\r
+        "}",\r
+        senderKey,\r
+        deviceKey,\r
+        encryptedBuffer,\r
+        olmSession->type);\r
+\r
+    // send\r
+    return MatrixClientSendToDevice(\r
+        client,\r
+        userId,\r
+        deviceId,\r
+        encryptedEventBuffer,\r
+        "m.room.encrypted");\r
+}\r
+\r
+bool\r
+MatrixClientFindDevice(\r
+    MatrixClient * client,\r
+    const char * deviceId,\r
+    MatrixDevice ** outDevice)\r
+{\r
+    MatrixClientRequestDeviceKeys(client);\r
+\r
+    for (int i = 0; i < client->numDevices; i++)\r
+    {\r
+        if (strcmp(client->devices[i].deviceId, deviceId) == 0)\r
+        {\r
+            *outDevice = &client->devices[i];\r
+            return true;\r
+        }\r
+    }\r
+\r
+    *outDevice = NULL;\r
+    return false;\r
+}\r
+\r
+bool\r
+MatrixClientGetDeviceKey(\r
+    MatrixClient * client,\r
+    const char * deviceId,\r
+    char * outDeviceKey, int outDeviceKeyCap)\r
+{\r
+    MatrixClientRequestDeviceKeys(client);\r
+    \r
+    MatrixDevice * device;\r
+    if (MatrixClientFindDevice(client, deviceId, &device))\r
+    {\r
+        strncpy(outDeviceKey, device->deviceKey, outDeviceKeyCap);\r
+        return true;\r
+    }\r
+\r
+    return false;\r
+}\r
+\r
+// https://spec.matrix.org/v1.6/client-server-api/#post_matrixclientv3keysquery\r
+bool\r
+MatrixClientRequestDeviceKeys(\r
+    MatrixClient * client)\r
+{\r
+    char userIdEscaped[USER_ID_SIZE];\r
+    JsonEscape(client->userId, strlen(client->userId),\r
+        userIdEscaped, USER_ID_SIZE);\r
+\r
+    char request[KEYS_QUERY_REQUEST_SIZE];\r
+    snprintf(request, KEYS_QUERY_REQUEST_SIZE,\r
+        "{\"device_keys\":{\"%s\":[]}}", userIdEscaped);\r
+\r
+    char responseBuffer[KEYS_QUERY_RESPONSE_SIZE];\r
+    bool requestResult = MatrixHttpPost(client,\r
+        KEYS_QUERY_URL,\r
+        request,\r
+        responseBuffer, KEYS_QUERY_RESPONSE_SIZE,\r
+        true);\r
+\r
+    if (requestResult)\r
+    {\r
+        // query for retrieving device keys for user id\r
+        char query[JSON_QUERY_SIZE];\r
+        snprintf(query, JSON_QUERY_SIZE,\r
+            "$.device_keys.%s", userIdEscaped);\r
+        \r
+        const char * s;\r
+        int slen;\r
+        mjson_find(responseBuffer, strlen(responseBuffer),\r
+            query, &s, &slen);\r
+\r
+        // loop over keys\r
+        \r
+        int koff, klen, voff, vlen, vtype, off;\r
+        for (off = 0; (off = mjson_next(s, slen, off, &koff, &klen,\r
+                                        &voff, &vlen, &vtype)) != 0; ) {\r
+            const char * key = s + koff;\r
+            const char * val = s + voff;\r
+\r
+            // set device id, "key" is the JSON key\r
+            MatrixDevice d;\r
+            strncpy(d.deviceId, key, klen);\r
+\r
+            // look for device key in value\r
+            char deviceKeyQuery[JSON_QUERY_SIZE];\r
+            snprintf(deviceKeyQuery, JSON_QUERY_SIZE,\r
+                "$.keys.curve25519:%.*s", klen, key);\r
+            mjson_get_string(val, vlen,\r
+                deviceKeyQuery, d.deviceKey, DEVICE_KEY_SIZE);\r
+\r
+            // add device\r
+            if (client->numDevices < NUM_DEVICES)\r
+            {\r
+                client->devices[client->numDevices] = d;\r
+                client->numDevices++;\r
+            }\r
+            else\r
+            {\r
+                return false;\r
+            }\r
+        }\r
+\r
+        return true;\r
+    }\r
+    else\r
+    {\r
+        return false;\r
+    }\r
+}\r