forked from matrix-org/purple-matrix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matrix-e2e.c
1951 lines (1763 loc) · 70 KB
/
matrix-e2e.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Matrix end-to-end encryption support
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111-1301 USA
*/
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <string.h>
#include <sqlite3.h>
#include "libmatrix.h"
#include "matrix-api.h"
#include "matrix-e2e.h"
#include "matrix-json.h"
#include "debug.h"
/* json-glib */
#include <json-glib/json-glib.h>
#include "connection.h"
#ifndef MATRIX_NO_E2E
#include "olm/olm.h"
#include <gcrypt.h>
#ifdef _WIN32
#include <Wincrypt.h>
#endif
struct _MatrixOlmSession;
struct _MatrixE2EData {
OlmAccount *oa;
gchar *device_id;
gchar *curve25519_pubkey;
gchar *ed25519_pubkey;
sqlite3 *db;
/* Mapping from MatrixHashKeyOlm to MatrixOlmSession */
GHashTable *olm_session_hash;
};
#define PURPLE_CONV_E2E_STATE "e2e"
/* Hung off the Purple conversation with the PURPLE_CONV_E2E_STATE */
typedef struct _MatrixE2ERoomData {
/* Mapping from _MatrixHashKeyInBoundMegOlm to OlmInboundGroupSession */
GHashTable *megolm_sessions_inbound;
} MatrixE2ERoomData;
typedef struct _MatrixHashKeyOlm {
gchar *sender_key;
gchar *sender_id;
} MatrixHashKeyOlm;
typedef struct _MatrixOlmSession {
gchar *sender_key;
gchar *sender_id;
OlmSession *session;
sqlite3_int64 unique;
struct _MatrixOlmSession *next;
} MatrixOlmSession;
typedef struct _MatrixHashKeyInBoundMegOlm {
gchar *sender_key;
gchar *sender_id;
gchar *session_id;
gchar *device_id;
} MatrixHashKeyInBoundMegOlm;
struct _MatrixMediaCryptInfo {
guchar sha256[32];
guchar aes_k[32];
guchar aes_iv[16];
};
static void key_upload_callback(MatrixConnectionData *conn,
gpointer user_data,
struct _JsonNode *json_root,
const char *body,
size_t body_len, const char *content_type);
/* Really clear an area of memory */
static void clear_mem(volatile char *data, size_t len)
{
#ifdef __STDC_LIB_EXT1__
/* Untested! */
memset_s(data, len, '\0', len);
#else
size_t index;
for(index = 0;index < len; index ++)
{
data[index] = '\0';
}
#endif
}
/* Returns a pointer to a freshly allocated buffer of 'n' bytes of random data.
* If it fails it returns NULL.
* TODO: There must be some portable function we can call to do this.
*/
static void *get_random(size_t n)
{
#ifndef _WIN32
FILE *urandom = fopen("/dev/urandom", "rb");
if (!urandom) {
return NULL;
}
void *buffer = g_malloc(n);
if (fread(buffer, 1, n, urandom) != n) {
g_free(buffer);
buffer = NULL;
}
fclose(urandom);
#else
static HCRYPTPROV hCryptoServiceProvider = 0;
if (hCryptoServiceProvider == 0) {
/* Crypto init */
CryptAcquireContextA(&hCryptoServiceProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT);
}
unsigned char *buffer = g_new(unsigned char, n);
if (!CryptGenRandom(hCryptoServiceProvider, n, buffer)) {
g_free(buffer);
buffer = NULL;
}
#endif
return buffer;
}
/* GHashFunc for two MatrixHasKeyOlm */
static gboolean olm_inbound_equality(gconstpointer a, gconstpointer b)
{
const MatrixHashKeyOlm *hk_a;
const MatrixHashKeyOlm *hk_b;
hk_a = (const MatrixHashKeyOlm *)a;
hk_b = (const MatrixHashKeyOlm *)b;
return !strcmp(hk_a->sender_key, hk_b->sender_key) &&
!strcmp(hk_a->sender_id, hk_b->sender_id);
}
/* GHashFunc for a _MatrixHashKeyOlm */
static guint olm_inbound_hash(gconstpointer a)
{
const MatrixHashKeyOlm *hk;
hk = (const MatrixHashKeyOlm *)a;
return g_str_hash(hk->sender_key) +
g_str_hash(hk->sender_id);
}
static void olm_hash_key_destroy(gpointer k)
{
MatrixHashKeyOlm *ok = k;
clear_mem(ok->sender_key, strlen(ok->sender_key));
g_free(ok->sender_key);
g_free(ok->sender_id);
g_free(ok);
}
static void free_matrix_olm_session(MatrixOlmSession *msession,
gboolean free_session)
{
g_free(msession->sender_id);
g_free(msession->sender_key);
if (free_session) {
olm_clear_session(msession->session);
g_free(msession->session);
}
}
static void olm_hash_value_destroy(gpointer v)
{
MatrixOlmSession *os = v;
while (os) {
MatrixOlmSession *next = os->next;
free_matrix_olm_session(os, TRUE);
os = next;
}
}
/* GEqualFunc for two MatrixHashKeyInBoundMegOlm */
static gboolean megolm_inbound_equality(gconstpointer a, gconstpointer b)
{
const MatrixHashKeyInBoundMegOlm *hk_a;
const MatrixHashKeyInBoundMegOlm *hk_b;
hk_a = (const MatrixHashKeyInBoundMegOlm *)a;
hk_b = (const MatrixHashKeyInBoundMegOlm *)b;
return !strcmp(hk_a->sender_key, hk_b->sender_key) &&
!strcmp(hk_a->sender_id, hk_b->sender_id) &&
!strcmp(hk_a->session_id, hk_b->session_id) &&
!strcmp(hk_a->device_id, hk_b->device_id);
}
/* GHashFunc for a _MatrixHashKeyInBoundMegOlm */
static guint megolm_inbound_hash(gconstpointer a)
{
const MatrixHashKeyInBoundMegOlm *hk;
hk = (const MatrixHashKeyInBoundMegOlm *)a;
return g_str_hash(hk->sender_key) +
g_str_hash(hk->session_id) +
g_str_hash(hk->sender_id) +
g_str_hash(hk->device_id);
}
static void megolm_inbound_key_destroy(gpointer v)
{
MatrixHashKeyInBoundMegOlm *key = v;
g_free(key->sender_key);
g_free(key->session_id);
g_free(key->sender_id);
g_free(key->device_id);
}
static void megolm_inbound_value_destroy(gpointer v)
{
OlmInboundGroupSession *oigs = v;
olm_clear_inbound_group_session(oigs);
g_free(oigs);
}
static MatrixE2ERoomData *get_e2e_room_data(PurpleConversation *conv)
{
MatrixE2ERoomData *result;
result = purple_conversation_get_data(conv, PURPLE_CONV_E2E_STATE);
if (!result) {
result = g_new0(MatrixE2ERoomData, 1);
purple_conversation_set_data(conv, PURPLE_CONV_E2E_STATE, result);
}
return result;
}
static GHashTable *get_e2e_inbound_megolm_hash(PurpleConversation *conv)
{
MatrixE2ERoomData *rd = get_e2e_room_data(conv);
if (!rd->megolm_sessions_inbound) {
rd->megolm_sessions_inbound = g_hash_table_new_full(megolm_inbound_hash,
megolm_inbound_equality,
megolm_inbound_key_destroy,
megolm_inbound_value_destroy);
}
return rd->megolm_sessions_inbound;
}
static OlmInboundGroupSession *get_inbound_megolm_session(
PurpleConversation *conv,
const gchar *sender_key, const gchar *sender_id,
const gchar *session_id, const gchar *device_id)
{
MatrixHashKeyInBoundMegOlm match;
match.sender_key = (gchar *)sender_key;
match.sender_id = (gchar *)sender_id;
match.session_id = (gchar *)session_id;
match.device_id = (gchar *)device_id;
OlmInboundGroupSession *result =
(OlmInboundGroupSession *)g_hash_table_lookup(
get_e2e_inbound_megolm_hash(conv), &match);
purple_debug_info("matrixprpl", "%s: %s/%s/%s/%s: %p\n",
__func__, device_id, sender_id, sender_key, session_id,
result);
return result;
}
static void store_inbound_megolm_session(PurpleConversation *conv,
const gchar *sender_key, const gchar *sender_id,
const gchar *session_id, const gchar *device_id,
OlmInboundGroupSession *igs) {
MatrixHashKeyInBoundMegOlm *key = g_new0(MatrixHashKeyInBoundMegOlm, 1);
key->sender_key = g_strdup(sender_key);
key->sender_id = g_strdup(sender_id);
key->session_id = g_strdup(session_id);
key->device_id = g_strdup(device_id);
purple_debug_info("matrixprpl", "%s: %s/%s/%s/%s\n",
__func__, device_id, sender_id, sender_key, session_id);
g_hash_table_insert(get_e2e_inbound_megolm_hash(conv), key, igs);
}
/* Find if we already have an OlmSession for this sender/sender_key somewhere
* that this body matches.
*/
static MatrixOlmSession *find_olm_session(MatrixConnectionData *conn,
const char *sender_id, const char *sender_key,
const char *body)
{
gboolean have_sender = FALSE;
MatrixOlmSession *cur_entry, *list_head, *hash_result;
MatrixOlmSession *result = NULL;
MatrixHashKeyOlm match;
purple_debug_info("matrixprpl", "find_olm_session for %s/%s\n",
sender_id, sender_key);
match.sender_key = (gchar *)sender_key;
match.sender_id = (gchar *)sender_id;
hash_result = (MatrixOlmSession *)g_hash_table_lookup(
conn->e2e->olm_session_hash, &match);
cur_entry = hash_result;
list_head = hash_result;
while (cur_entry) {
if (!strcmp(sender_id, cur_entry->sender_id) &&
!strcmp(sender_key, cur_entry->sender_key)) {
size_t ret;
char *body_double = g_strdup(body);
have_sender = TRUE;
ret = olm_matches_inbound_session(cur_entry->session, body_double,
strlen(body));
g_free(body_double);
if (ret == 1) {
purple_debug_info("matrixprpl",
"%s: Found matching session for %s/%s\n",
__func__, sender_id, sender_key);
return cur_entry;
}
if (ret == olm_error()) {
purple_debug_warning("matrixprpl",
"%s: Error while checking session %p for "
"match with %s/%s: %s\n", __func__, cur_entry->session,
sender_id, sender_key,
olm_session_last_error(cur_entry->session));
}
}
cur_entry = cur_entry->next;
}
if (!have_sender) {
MatrixOlmSession **chain = &list_head;
int ret;
/* We have no entries at all for the sender+key, lets load all the
* data from the db
*/
const char *query = "SELECT session_pickle, rowid "
"FROM olmsessions "
"WHERE sender_name = ? AND "
"sender_key = ?";
sqlite3_stmt *dbstmt = NULL;
ret = sqlite3_prepare_v2(conn->e2e->db, query, -1, &dbstmt, NULL);
if (ret != SQLITE_OK || !dbstmt) {
purple_debug_warning("matrixprpl",
"%s: Failed to prep select %d '%s'\n",
__func__, ret, query);
goto bad_sql;
}
ret = sqlite3_bind_text(dbstmt, 1, sender_id, -1, NULL);
if (ret == SQLITE_OK) {
ret = sqlite3_bind_text(dbstmt, 2, sender_key, -1, NULL);
}
if (ret != SQLITE_OK) {
purple_debug_warning("matrixprpl", "%s: Failed to bind %d\n",
__func__, ret);
goto bad_sql;
}
/* Find the end of the chain to get the pointer to update */
for (cur_entry = list_head; cur_entry; cur_entry=cur_entry->next) {
chain = &(cur_entry->next);
}
while (ret = sqlite3_step(dbstmt), ret == SQLITE_ROW) {
const gchar *pickle = (gchar *)sqlite3_column_text(dbstmt, 0);
gchar *dupe_pickle;
if (!pickle) {
purple_debug_warning("matrixprpl",
"%s: Empty pickle for %s/%s\n", __func__,
sender_id, sender_key);
continue;
};
dupe_pickle = g_strdup(pickle);
OlmSession *session = olm_session(g_malloc0(olm_session_size()));
if (olm_unpickle_session(session, "!", 1, dupe_pickle,
strlen(dupe_pickle)) == olm_error()) {
purple_debug_warning("matrixprpl",
"%s: Failed to unpickle %s for %s/%s\n",
__func__, pickle, sender_id, sender_key);
g_free(dupe_pickle);
g_free(session);
continue;
}
g_free(dupe_pickle);
cur_entry = g_new0(MatrixOlmSession, 1);
cur_entry->sender_id = g_strdup(sender_id);
cur_entry->sender_key = g_strdup(sender_key);
cur_entry->session = session;
cur_entry->unique = sqlite3_column_int64(dbstmt, 1);
*chain = cur_entry;
if (!result) {
char *body_double = g_strdup(body);
/* But is this the session we're after ? */
ret = olm_matches_inbound_session(session,
body_double, strlen(body));
g_free(body_double);
if (ret == 1) {
purple_debug_info("matrixprpl",
"%s: Found (loaded) session for %s/%s\n",
__func__, sender_id, sender_key);
result = cur_entry;
/* Carry on loading any other sessions */
}
if (ret == olm_error()) {
purple_debug_warning("matrixprpl",
"%s: Error while checking loaded session %p for "
"match with %s/%s: %s\n", __func__, session,
sender_id, sender_key,
olm_session_last_error(session));
}
if (!ret) {
purple_debug_warning("matrixprpl",
"%s: Loaded session (%" PRIx64
") is not a match for %s/%s\n",
__func__, (int64_t)cur_entry->unique, sender_id,
sender_key);
}
}
}
if (ret != SQLITE_DONE) {
purple_debug_warning("matrixprpl", "%s: db step failed %d\n",
__func__, ret);
goto bad_sql;
}
bad_sql:
sqlite3_finalize(dbstmt);
}
if (list_head && !hash_result) {
MatrixHashKeyOlm *key = g_new0(MatrixHashKeyOlm, 1);
key->sender_key = g_strdup(sender_key);
key->sender_id = g_strdup(sender_id);
/* We loaded entries where there were none before, set the hash */
g_hash_table_insert(conn->e2e->olm_session_hash, key, list_head);
}
return result;
}
/* Save a new olm session into the database */
static MatrixOlmSession *store_olm_session(MatrixConnectionData *conn,
OlmSession *session,
const char *sender_id,
const char *sender_key)
{
MatrixOlmSession *cur_entry = g_new0(MatrixOlmSession, 1);
size_t pickle_len = olm_pickle_session_length(session);
gchar *pickle = g_malloc(pickle_len+1);
sqlite3_stmt *dbstmt = NULL;
pickle_len = olm_pickle_session(session, "!", 1, pickle, pickle_len);
if (pickle_len == olm_error()) {
purple_debug_warning("matrixprpl",
"%s: Failed to pickle session for %s/%s: %s\n",
__func__, sender_id, sender_key,
olm_session_last_error(session));
goto err;
}
pickle[pickle_len] = '\0';
cur_entry->sender_id = g_strdup(sender_id);
cur_entry->sender_key = g_strdup(sender_key);
cur_entry->session = session;
const char *query = "INSERT into olmsessions "
"(sender_name, sender_key, session_pickle) "
"VALUES (?, ?, ?)";
int ret = sqlite3_prepare_v2(conn->e2e->db, query, -1, &dbstmt, NULL);
if (ret != SQLITE_OK || !dbstmt) {
purple_debug_warning("matrixprpl",
"%s: Failed to prep insert %d '%s'\n",
__func__, ret, query);
goto err;
}
ret = sqlite3_bind_text(dbstmt, 1, sender_id, -1, NULL);
if (ret == SQLITE_OK) {
ret = sqlite3_bind_text(dbstmt, 2, sender_key, -1, NULL);
}
if (ret == SQLITE_OK) {
ret = sqlite3_bind_text(dbstmt, 3, pickle, -1, NULL);
}
if (ret != SQLITE_OK) {
purple_debug_warning("matrixprpl",
"%s: Failed to bind %d\n", __func__, ret);
goto err;
}
ret = sqlite3_step(dbstmt);
if (ret != SQLITE_DONE) {
purple_debug_warning("matrixprpl",
"%s: Insert failed %d (%s)\n", __func__,
ret, query);
goto err;
}
sqlite3_finalize(dbstmt);
cur_entry->unique = sqlite3_last_insert_rowid(conn->e2e->db);
MatrixHashKeyOlm match;
match.sender_key = (gchar *)sender_key;
match.sender_id = (gchar *)sender_id;
MatrixOlmSession *hash_result = (MatrixOlmSession *)g_hash_table_lookup(
conn->e2e->olm_session_hash, &match);
if (hash_result) {
/* If there's already an entry, insert it after the head */
cur_entry->next = hash_result->next;
hash_result->next = cur_entry;
} else {
/* No entry, we need to stuff it into the hash table */
MatrixHashKeyOlm *key = g_new0(MatrixHashKeyOlm, 1);
key->sender_key = g_strdup(sender_key);
key->sender_id = g_strdup(sender_id);
/* We loaded entries where there were none before, set the hash */
g_hash_table_insert(conn->e2e->olm_session_hash, key, cur_entry);
}
return cur_entry;
err:
g_free(pickle);
free_matrix_olm_session(cur_entry, FALSE);
return NULL;
}
/* Update an existing OLM session in the database */
static int update_olm_session(MatrixConnectionData *conn,
MatrixOlmSession *mos)
{
size_t pickle_len = olm_pickle_session_length(mos->session);
gchar *pickle = g_malloc(pickle_len+1);
sqlite3_stmt *dbstmt = NULL;
int ret = -1;
pickle_len = olm_pickle_session(mos->session, "!", 1, pickle, pickle_len);
if (pickle_len == olm_error()) {
purple_debug_warning("matrixprpl",
"%s: Failed to pickle session for %s/%s: %s\n",
__func__, mos->sender_id, mos->sender_key,
olm_session_last_error(mos->session));
goto err;
}
pickle[pickle_len] = '\0';
const char *query ="UPDATE olmsessions SET session_pickle=? "
"WHERE sender_name = ? AND sender_key = ? AND "
"ROWID = ?";
ret = sqlite3_prepare_v2(conn->e2e->db, query, -1, &dbstmt, NULL);
if (ret != SQLITE_OK || !dbstmt) {
purple_debug_warning("matrixprpl",
"%s: Failed to prep update %d '%s'\n",
__func__, ret, query);
ret = -1;
goto err;
}
ret = sqlite3_bind_text(dbstmt, 1, pickle, -1, NULL);
if (ret == SQLITE_OK) {
ret = sqlite3_bind_text(dbstmt, 2, mos->sender_id, -1, NULL);
}
if (ret == SQLITE_OK) {
ret = sqlite3_bind_text(dbstmt, 3, mos->sender_key, -1, NULL);
}
if (ret == SQLITE_OK) {
ret = sqlite3_bind_int64(dbstmt, 4, mos->unique);
}
if (ret != SQLITE_OK) {
purple_debug_warning("matrixprpl",
"%s: Failed to bind %d\n", __func__, ret);
ret = -1;
goto err;
}
ret = sqlite3_step(dbstmt);
if (ret != SQLITE_DONE) {
purple_debug_warning("matrixprpl",
"%s: Update failed %d (%s)\n", __func__,
ret, query);
ret = -1;
goto err;
}
ret = 0;
err:
sqlite3_finalize(dbstmt);
g_free(pickle);
return ret;
}
/* Sign the JsonObject with olm_account_sign and add it to the object
* as a 'signatures' member of the top level object.
* 0 on success
*/
int matrix_sign_json(MatrixConnectionData *conn, JsonObject *tosign)
{
int ret = -1;
OlmAccount *account = conn->e2e->oa;
const gchar *device_id = conn->e2e->device_id;
PurpleConnection *pc = conn->pc;
GString *can_json = matrix_canonical_json(tosign);
gchar *can_json_c = g_string_free(can_json, FALSE);
size_t sig_length = olm_account_signature_length(account);
gchar *sig = g_malloc0(sig_length+1);
if (olm_account_sign(account, can_json_c, strlen(can_json_c),
sig, sig_length)==olm_error()) {
purple_connection_error_reason(pc,
PURPLE_CONNECTION_ERROR_OTHER_ERROR,
olm_account_last_error(account));
goto out;
}
/* We need to add a "signatures" member which is an object, with
* a "user_id" member that is itself an object which has an "ed25519:$DEVICEID" member
* that is the signature.
*/
GString *alg_dev = g_string_new(NULL);
g_string_printf(alg_dev, "ed25519:%s", device_id);
gchar *alg_dev_c = g_string_free(alg_dev, FALSE);
JsonObject *sig_dev = json_object_new();
json_object_set_string_member(sig_dev, alg_dev_c, sig);
JsonObject *sig_obj = json_object_new();
json_object_set_object_member(sig_obj, conn->user_id, sig_dev);
json_object_set_object_member(tosign, "signatures", sig_obj);
g_free(alg_dev_c);
ret = 0;
out:
g_free(can_json_c);
g_free(sig);
return ret;
}
/* Store the current Olm account data into the Purple account data
*/
static int matrix_store_e2e_account(MatrixConnectionData *conn)
{
PurpleConnection *pc = conn->pc;
size_t pickle_len = olm_pickle_account_length(conn->e2e->oa);
char *pickled_account = g_malloc0(pickle_len+1);
/* TODO: Wth to use as the key? We've not got anything in purple to protect
* it with? We could do with stuffing something into the system key ring
*/
if (olm_pickle_account(conn->e2e->oa, "!", 1, pickled_account, pickle_len) ==
olm_error()) {
purple_connection_error_reason(pc,
PURPLE_CONNECTION_ERROR_OTHER_ERROR,
olm_account_last_error(conn->e2e->oa));
g_free(pickled_account);
return -1;
}
/* Create a JSON string to store in our account data, we include
* our device and server as sanity checks.
* TODO: Should we defer this until we've sent it to the server?
*/
JsonObject *settings_body = json_object_new();
json_object_set_string_member(settings_body, "device_id", conn->e2e->device_id);
json_object_set_string_member(settings_body, "server", conn->homeserver);
json_object_set_string_member(settings_body, "pickle", pickled_account);
g_free(pickled_account);
JsonNode *settings_node = json_node_new(JSON_NODE_OBJECT);
json_node_set_object(settings_node, settings_body);
json_object_unref(settings_body);
JsonGenerator *settings_generator = json_generator_new();
json_generator_set_root(settings_generator, settings_node);
gchar *settings_string = json_generator_to_data(settings_generator, NULL);
g_object_unref(G_OBJECT(settings_generator));
json_node_free(settings_node);
purple_account_set_string(pc->account,
PRPL_ACCOUNT_OPT_OLM_ACCOUNT_KEYS, settings_string);
g_free(settings_string);
return 0;
}
/* Retrieve an Olm account from the Purple account data
* Returns: 1 on success
* 0 on no stored account
* -1 on error
*/
static int matrix_restore_e2e_account(MatrixConnectionData *conn)
{
PurpleConnection *pc = conn->pc;
gchar *pickled_account = NULL;
const char *account_string = purple_account_get_string(pc->account,
PRPL_ACCOUNT_OPT_OLM_ACCOUNT_KEYS, NULL);
int ret = -1;
if (!account_string || !*account_string) {
return 0;
}
/* Deal with existing account string */
JsonParser *json_parser = json_parser_new();
const gchar *retrieved_device_id, *retrieved_hs, *retrieved_pickle;
GError *err = NULL;
if (!json_parser_load_from_data(json_parser,
account_string, strlen(account_string),
&err)) {
purple_connection_error_reason(pc,
PURPLE_CONNECTION_ERROR_OTHER_ERROR,
"Failed to parse stored account key");
purple_debug_info("matrixprpl",
"unable to parse account JSON: %s",
err->message);
g_error_free(err);
g_object_unref(json_parser);
ret = -1;
goto out;
}
JsonNode *settings_node = json_parser_get_root(json_parser);
JsonObject *settings_body = matrix_json_node_get_object(settings_node);
retrieved_device_id = matrix_json_object_get_string_member(settings_body, "device_id");
retrieved_hs = matrix_json_object_get_string_member(settings_body, "server");
retrieved_pickle = matrix_json_object_get_string_member(settings_body, "pickle");
if (!retrieved_device_id || !retrieved_hs || !retrieved_pickle) {
purple_connection_error_reason(pc,
PURPLE_CONNECTION_ERROR_OTHER_ERROR,
"Unable to retrieve part of the stored account key");
g_object_unref(json_parser);
ret = -1;
goto out;
}
if (strcmp(retrieved_device_id, conn->e2e->device_id) ||
strcmp(retrieved_hs, conn->homeserver)) {
purple_connection_error_reason(pc,
PURPLE_CONNECTION_ERROR_OTHER_ERROR,
"Device ID/HS doesn't matched for stored account key");
g_object_unref(json_parser);
ret = -1;
goto out;
}
pickled_account = g_strdup(retrieved_pickle);
if (olm_unpickle_account(conn->e2e->oa, "!", 1, pickled_account, strlen(retrieved_pickle)) ==
olm_error()) {
purple_connection_error_reason(pc,
PURPLE_CONNECTION_ERROR_OTHER_ERROR,
olm_account_last_error(conn->e2e->oa));
g_object_unref(json_parser);
ret = -1;
goto out;
}
g_object_unref(json_parser);
purple_debug_info("matrixprpl", "Succesfully unpickled account\n");
ret = 1;
out:
g_free(pickled_account);
return ret;
}
/* Returns the list of algorithms and our keys for those algorithms on the current account */
static int get_id_keys(PurpleConnection *pc, OlmAccount *account, gchar ***algorithms, gchar ***keys)
{
/* There has to be an easier way than this.... */
size_t id_key_len = olm_account_identity_keys_length(account);
gchar *id_keys = g_malloc0(id_key_len+1);
if (olm_account_identity_keys(account, id_keys, id_key_len) ==
olm_error()) {
purple_connection_error_reason(pc,
PURPLE_CONNECTION_ERROR_OTHER_ERROR,
olm_account_last_error(account));
g_free(id_keys);
return -1;
}
/* We get back a json string, something like:
* {"curve25519":"encodedkey...","ed25519":"encodedkey...."}'
*/
JsonParser *json_parser = json_parser_new();
GError *err = NULL;
if (!json_parser_load_from_data(json_parser,
id_keys, strlen(id_keys), &err)) {
purple_connection_error_reason(pc,
PURPLE_CONNECTION_ERROR_OTHER_ERROR,
"Failed to parse olm account ID keys");
purple_debug_info("matrixprpl",
"unable to parse olm account ID keys: %s",
err->message);
g_error_free(err);
g_free(id_keys);
g_object_unref(json_parser);
return -1;
}
/* We have one object with a series of string members where
* each member is named after the algorithm.
*/
JsonNode *id_node = json_parser_get_root(json_parser);
JsonObject *id_body = matrix_json_node_get_object(id_node);
guint n_keys = json_object_get_size(id_body);
*algorithms = g_new(gchar *, n_keys);
*keys = g_new(gchar *, n_keys);
GList *iter, *iter_start;
const gchar *key_algo;
guint i = 0;
iter_start = json_object_get_members(id_body);
for (iter = iter_start; iter != NULL; iter = iter->next)
{
key_algo = iter->data;
(*algorithms)[i] = g_strdup(key_algo);
(*keys)[i] = g_strdup(matrix_json_object_get_string_member(id_body, key_algo));
i++;
}
g_list_free(iter_start);
g_free(id_keys);
g_object_unref(json_parser);
return n_keys;
}
/* See: https://matrix.org/docs/guides/e2e_implementation.html#creating-and-registering-one-time-keys */
static int send_one_time_keys(MatrixConnectionData *conn, size_t n_keys)
{
PurpleConnection *pc = conn->pc;
int ret;
size_t random_needed;
void *random_buffer;
void *olm_1t_keys_json = NULL;
JsonParser *json_parser = NULL;
size_t olm_keys_buffer_size;
JsonObject *otk_json = NULL;
random_needed = olm_account_generate_one_time_keys_random_length(
conn->e2e->oa, n_keys);
random_buffer = get_random(random_needed);
if (!random_buffer) {
return -1;
}
if (olm_account_generate_one_time_keys(conn->e2e->oa, n_keys, random_buffer,
random_needed) == olm_error()) {
purple_connection_error_reason(pc,
PURPLE_CONNECTION_ERROR_OTHER_ERROR,
olm_account_last_error(conn->e2e->oa));
ret = -1;
goto out;
}
olm_keys_buffer_size = olm_account_one_time_keys_length(conn->e2e->oa);
olm_1t_keys_json = g_malloc0(olm_keys_buffer_size+1);
if (olm_account_one_time_keys(conn->e2e->oa, olm_1t_keys_json,
olm_keys_buffer_size) == olm_error()) {
purple_connection_error_reason(pc,
PURPLE_CONNECTION_ERROR_OTHER_ERROR,
olm_account_last_error(conn->e2e->oa));
ret = -1;
goto out;
}
/* olm_1t_keys_json has json like:
* {
* curve25519: {
* "keyid1": "base64encodedcurve25519key1",
* "keyid2": "base64encodedcurve25519key2"
* }
* }
* I think in practice this is just curve25519 but I'll avoid hard coding
* We need to produce an object with a set of signed objects each having
* one key
*/
json_parser = json_parser_new();
GError *err = NULL;
if (!json_parser_load_from_data(json_parser,
olm_1t_keys_json, strlen(olm_1t_keys_json), &err)) {
purple_connection_error_reason(pc,
PURPLE_CONNECTION_ERROR_OTHER_ERROR,
"Failed to parse generated 1-time json");
g_error_free(err);
ret = -1;
goto out;
}
/* The output JSON we're generating */
otk_json = json_object_new();
JsonNode *olm_1tk_root = json_parser_get_root(json_parser);
JsonObject *olm_1tk_obj = matrix_json_node_get_object(olm_1tk_root);
GList *algo_iter, *algo_iter_start;
const gchar *keys_algo;
algo_iter_start = json_object_get_members(olm_1tk_obj);
for (algo_iter = algo_iter_start; algo_iter != NULL; algo_iter = algo_iter->next)
{
keys_algo = algo_iter->data;
/* We're expecting keys_algo to be "curve25519" and keys_obj to be an
* object with a set of keys.
*/
GList *keys_iter, *keys_iter_start;
JsonObject *keys_obj = matrix_json_object_get_object_member(olm_1tk_obj, keys_algo);
const gchar *key_id;
keys_iter_start = json_object_get_members(keys_obj);
for (keys_iter = keys_iter_start; keys_iter != NULL; keys_iter = keys_iter->next)
{
key_id = keys_iter->data;
const gchar *key_string = matrix_json_object_get_string_member(keys_obj, key_id);
JsonObject *signed_key = json_object_new();
json_object_set_string_member(signed_key, "key", key_string);
ret = matrix_sign_json(conn, signed_key);
if (ret) {
g_object_unref(signed_key);
goto out;
}
gchar *signed_key_name = g_strdup_printf("signed_%s:%s", keys_algo,
key_id);
json_object_set_object_member(otk_json,
signed_key_name, signed_key);
g_free(signed_key_name);
}
g_list_free(keys_iter_start);
}
g_list_free(algo_iter_start);
matrix_api_upload_keys(conn, NULL, otk_json,
key_upload_callback,
matrix_api_error, matrix_api_bad_response, (void *)1);
otk_json = NULL; /* matrix_api_upload_keys frees with its json */
ret = 0;
out:
g_object_unref(json_parser);
if (otk_json)
g_object_unref(otk_json);
g_free(random_buffer);
g_free(olm_1t_keys_json);
return ret;
}
/* Called from sync with an object of the form:
* "device_one_time_keys_count" : {
* "signed_curve25519" : 100
* },
*/
void matrix_e2e_handle_sync_key_counts(PurpleConnection *pc, JsonObject *count_object,
gboolean force_send)
{
gboolean need_to_send = force_send;
gboolean valid_counts = FALSE;
MatrixConnectionData *conn = purple_connection_get_protocol_data(pc);
size_t max_keys = olm_account_max_number_of_one_time_keys(conn->e2e->oa);
size_t to_create = max_keys;
if (!force_send) {
GList *iter, *iter_start;
const gchar *key_algo;
iter_start = json_object_get_members(count_object);
for (iter = iter_start; iter != NULL; iter = iter->next)
{
key_algo = iter->data;
valid_counts = TRUE;
gint64 count = matrix_json_object_get_int_member(count_object, key_algo);
if (count < max_keys / 2) {
to_create = (max_keys / 2) - count;
need_to_send = TRUE;
}
purple_debug_info("matrixprpl", "%s: %s: %" G_GINT64_FORMAT "\n",
__func__, key_algo, count);
}
g_list_free(iter_start);
}
need_to_send |= !valid_counts;
if (need_to_send) {
purple_debug_info("matrixprpl", "%s: need to send\n",__func__);
send_one_time_keys(conn, to_create);
}
}
/* Called back when we've successfully uploaded the device keys
* we use 'user_data' = 1 to indicate we did an upload of one time
* keys.
*/
static void key_upload_callback(MatrixConnectionData *conn,
gpointer user_data,
struct _JsonNode *json_root,
const char *body,
size_t body_len, const char *content_type)