-
Notifications
You must be signed in to change notification settings - Fork 976
Expand file tree
/
Copy pathfoldermetadata.cpp
More file actions
1235 lines (1047 loc) · 52 KB
/
Copy pathfoldermetadata.cpp
File metadata and controls
1235 lines (1047 loc) · 52 KB
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
/*
* SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "account.h"
#include "encryptedfoldermetadatahandler.h"
#include "foldermetadata.h"
#include "clientsideencryption.h"
#include "clientsideencryptionjobs.h"
#include <common/checksums.h>
#include <QDir>
#include <QJsonArray>
#include <QJsonDocument>
#include <QSslCertificate>
namespace OCC
{
Q_LOGGING_CATEGORY(lcCseMetadata, "nextcloud.sync.clientsideencryption.metadata", QtInfoMsg)
namespace
{
constexpr auto authenticationTagKey = "authenticationTag";
constexpr auto cipherTextKey = "ciphertext";
constexpr auto counterKey = "counter";
constexpr auto filesKey = "files";
constexpr auto filedropKey = "filedrop";
constexpr auto foldersKey = "folders";
constexpr auto initializationVectorKey = "initializationVector";
constexpr auto keyChecksumsKey = "keyChecksums";
constexpr auto metadataJsonKey = "metadata";
constexpr auto metadataKeyKey = "metadataKey";
constexpr auto nonceKey = "nonce";
constexpr auto usersKey = "users";
constexpr auto usersUserIdKey = "userId";
constexpr auto usersCertificateKey = "certificate";
constexpr auto usersEncryptedMetadataKey = "encryptedMetadataKey";
constexpr auto usersEncryptedFiledropKey = "encryptedFiledropKey";
constexpr auto versionKey = "version";
constexpr auto encryptedKey = "encrypted";
const auto metadataKeySize = 16;
QString metadataStringFromOCsDocument(const QJsonDocument &ocsDoc)
{
const auto &ocsDocObj = ocsDoc.object();
const auto &ocsObj = ocsDocObj["ocs"].toObject();
const auto &dataObj = ocsObj["data"].toObject();
return dataObj["meta-data"].toString();
}
}
bool FolderMetadata::isOriginalFilenameValid(const QString &originalFilename)
{
if (originalFilename.isEmpty()) {
return false;
}
if (originalFilename == QStringLiteral(".")
|| originalFilename == QStringLiteral("..")) {
return false;
}
if (originalFilename.contains(QLatin1Char('/'))
|| originalFilename.contains(QLatin1Char('\\'))
|| originalFilename.contains(QChar(0))) {
return false;
}
const auto slashPrefixedName = QStringLiteral("/") + originalFilename;
return QDir::cleanPath(slashPrefixedName) == slashPrefixedName;
}
bool FolderMetadata::EncryptedFile::isDirectory() const
{
return mimetype.isEmpty() || mimetype == QByteArrayLiteral("inode/directory") || mimetype == QByteArrayLiteral("httpd/unix-directory");
}
FolderMetadata::FolderMetadata(AccountPtr account, const QString &remoteFolderRoot, FolderType folderType) :
_account(account),
_remoteFolderRoot(Utility::noLeadingSlashPath(Utility::noTrailingSlashPath(remoteFolderRoot))),
_isRootEncryptedFolder(folderType == FolderType::Root)
{
Q_ASSERT(!_remoteFolderRoot.isEmpty());
initEmptyMetadata();
}
FolderMetadata::FolderMetadata(AccountPtr account,
const QString &remoteFolderRoot,
const QByteArray &metadata,
const RootEncryptedFolderInfo &rootEncryptedFolderInfo,
const QByteArray &signature,
QObject *parent)
: QObject(parent)
, _account(account)
, _remoteFolderRoot(Utility::noLeadingSlashPath(Utility::noTrailingSlashPath(remoteFolderRoot)))
, _initialMetadata(metadata)
, _isRootEncryptedFolder(rootEncryptedFolderInfo.path == QStringLiteral("/"))
, _binaryMetadataKeyForEncryption(rootEncryptedFolderInfo.binaryKeyForEncryption)
, _binaryMetadataKeyForDecryption(rootEncryptedFolderInfo.binaryKeyForDecryption)
, _keyChecksums(rootEncryptedFolderInfo.keyChecksums)
, _initialSignature(signature)
{
Q_ASSERT(!_remoteFolderRoot.isEmpty());
_existingMetadataVersion = setupVersionFromExistingMetadata(metadata);
const auto doc = QJsonDocument::fromJson(metadata);
qCDebug(lcCseMetadata()) << doc.toJson(QJsonDocument::Compact);
if (!_isRootEncryptedFolder
&& !rootEncryptedFolderInfo.keysSet()
&& !rootEncryptedFolderInfo.path.isEmpty()) {
startFetchRootE2eeFolderMetadata(rootEncryptedFolderInfo.path);
} else {
initMetadata();
}
}
void FolderMetadata::initMetadata()
{
if (_initialMetadata.isEmpty()) {
initEmptyMetadata();
return;
}
qCDebug(lcCseMetadata()) << "Setting up existing metadata";
setupExistingMetadata(_initialMetadata);
if (binaryMetadataKeyForDecryption().isEmpty() || binaryMetadataKeyForEncryption().isEmpty()) {
qCWarning(lcCseMetadata()) << "Failed to setup FolderMetadata. Could not parse/create metadataKey!";
}
emitSetupComplete();
}
void FolderMetadata::setupExistingMetadata(const QByteArray &metadata)
{
const auto doc = QJsonDocument::fromJson(metadata);
qCDebug(lcCseMetadata()) << "Got existing metadata:" << doc.toJson(QJsonDocument::Compact);
if (_existingMetadataVersion < MetadataVersion::Version1) {
qCWarning(lcCseMetadata()) << "Could not setup metadata. Incorrect version" << _existingMetadataVersion;
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return;
}
if (_existingMetadataVersion < MetadataVersion::Version2_0 && !_initialSignature.isEmpty()) {
qCWarning(lcCseMetadata()) << "Could not setup legacy metadata with a V2 signature.";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return;
}
if (_existingMetadataVersion < MetadataVersion::Version2_0) {
setupExistingMetadataLegacy(metadata);
return;
}
qCDebug(lcCseMetadata()) << "Setting up latest metadata version" << _existingMetadataVersion;
const auto metaDataStr = metadataStringFromOCsDocument(doc);
const auto metaDataDoc = QJsonDocument::fromJson(metaDataStr.toLocal8Bit());
const auto folderUsers = metaDataDoc[usersKey].toArray();
const auto isUsersArrayValid = (!_isRootEncryptedFolder && folderUsers.isEmpty()) || (_isRootEncryptedFolder && !folderUsers.isEmpty());
Q_ASSERT(isUsersArrayValid);
if (!isUsersArrayValid) {
qCWarning(lcCseMetadata()) << "Could not decrypt metadata key. Users array is invalid!";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return;
}
if (_isRootEncryptedFolder) {
QJsonDocument debugHelper;
debugHelper.setArray(folderUsers);
qCDebug(lcCseMetadata()) << "users: " << debugHelper.toJson(QJsonDocument::Compact);
}
for (auto it = folderUsers.constBegin(); it != folderUsers.constEnd(); ++it) {
const auto folderUserObject = it->toObject();
const auto userId = folderUserObject.value(usersUserIdKey).toString();
UserWithFolderAccess folderUser;
folderUser.userId = userId;
/* TODO: does it make sense to store each certificatePem that has been successfuly verified? Is this secure?
/ Can the attacker use outdated certificate as an attack vector?*/
folderUser.certificatePem = folderUserObject.value(usersCertificateKey).toString().toUtf8();
folderUser.encryptedMetadataKey = folderUserObject.value(usersEncryptedMetadataKey).toString().toUtf8();
_folderUsers[userId] = folderUser;
}
if (_isRootEncryptedFolder && !_initialSignature.isEmpty()) {
const auto metadataForSignature = prepareMetadataForSignature(metaDataDoc);
QVector<QByteArray> certificatePems;
certificatePems.reserve(_folderUsers.size());
for (const auto &folderUser : std::as_const(_folderUsers)) {
certificatePems.push_back(folderUser.certificatePem);
}
if (!_account->e2e()->verifySignatureCryptographicMessageSyntax(QByteArray::fromBase64(_initialSignature), metadataForSignature.toBase64(), certificatePems)) {
qCWarning(lcCseMetadata()) << "Could not parse encrypred folder metadata. Failed to verify signature!";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return;
}
}
if (_initialSignature.isEmpty()) {
qCWarning(lcCseMetadata()) << "Signature is empty";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return;
}
if (_folderUsers.contains(_account->davUser())) {
const auto currentFolderUser = _folderUsers.value(_account->davUser());
const auto currentUserCertificate = QSslCertificate{currentFolderUser.certificatePem};
_binaryMetadataKeyForEncryption = QByteArray::fromBase64(decryptDataWithPrivateKey(currentFolderUser.encryptedMetadataKey, currentUserCertificate.digest(QCryptographicHash::Sha256).toBase64()));
_binaryMetadataKeyForDecryption = _binaryMetadataKeyForEncryption;
}
if (!parseFileDropPart(metaDataDoc)) {
qCWarning(lcCseMetadata()) << "Could not parse filedrop part";
return;
}
if (binaryMetadataKeyForDecryption().isEmpty() || binaryMetadataKeyForEncryption().isEmpty()) {
qCWarning(lcCseMetadata()) << "Could not setup metadata key!";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return;
}
const auto &metaDataObj = metaDataDoc.object();
const auto &metadataObj = metaDataObj[metadataJsonKey].toObject();
_metadataNonce = QByteArray::fromBase64(metadataObj[nonceKey].toString().toLocal8Bit());
const auto &cipherTextEncrypted = metadataObj[cipherTextKey].toString().toLocal8Bit();
// for compatibility, the format is "cipheredpart|initializationVector", so we need to extract the "cipheredpart"
const auto cipherTextPartExtracted = cipherTextEncrypted.split('|').at(0);
const auto cipherTextDecrypted = EncryptionHelper::decryptThenUnGzipData(binaryMetadataKeyForDecryption(), QByteArray::fromBase64(cipherTextPartExtracted), _metadataNonce);
if (cipherTextDecrypted.isEmpty()) {
qCWarning(lcCseMetadata()) << "Could not decrypt cipher text!";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return;
}
const auto cipherTextDocument = QJsonDocument::fromJson(cipherTextDecrypted);
const auto keyCheckSums = cipherTextDocument[keyChecksumsKey].toArray();
if (!keyCheckSums.isEmpty()) {
_keyChecksums.clear();
}
for (auto it = keyCheckSums.constBegin(); it != keyCheckSums.constEnd(); ++it) {
const auto keyChecksum = it->toVariant().toString().toUtf8();
if (!keyChecksum.isEmpty()) {
//TODO: check that no hash has been removed from the keyChecksums
// How do we check that?
_keyChecksums.insert(keyChecksum);
}
}
if (!verifyMetadataKey(binaryMetadataKeyForDecryption())) {
qCWarning(lcCseMetadata()) << "Could not verify metadataKey!";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return;
}
const auto &cipherTextObj = cipherTextDocument.object();
const auto &files = cipherTextObj[filesKey].toObject();
const auto &folders = cipherTextObj[foldersKey].toObject();
const auto counterVariantFromJson = cipherTextObj.value(counterKey).toVariant();
if (counterVariantFromJson.isValid() && counterVariantFromJson.canConvert<quint64>()) {
// TODO: We need to check counter: new counter must be greater than locally stored counter
// What does that mean? We store the counter in metadata, should we now store it in local database as we do for all file records in SyncJournal?
// What if metadata was not updated for a while? The counter will then not be greater than locally stored (in SyncJournal DB?)
_counter = counterVariantFromJson.value<quint64>();
}
for (auto it = files.constBegin(), end = files.constEnd(); it != end; ++it) {
const auto parsedEncryptedFile = parseEncryptedFileFromJson(it.key(), it.value());
if (!parsedEncryptedFile.originalFilename.isEmpty()) {
_files.push_back(parsedEncryptedFile);
}
}
for (auto it = folders.constBegin(); it != folders.constEnd(); ++it) {
const auto folderName = it.value().toString();
if (folderName.isEmpty()) {
continue;
}
if (!isOriginalFilenameValid(folderName)) {
qCWarning(lcCseMetadata()) << "skipping encrypted folder" << it.key() << "metadata has an invalid file name";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
continue;
}
EncryptedFile file;
file.encryptedFilename = it.key();
file.originalFilename = folderName;
_files.push_back(file);
}
_isMetadataValid = true;
}
void FolderMetadata::setupExistingMetadataLegacy(const QByteArray &metadata)
{
const auto doc = QJsonDocument::fromJson(metadata);
qCDebug(lcCseMetadata()) << "Setting up legacy existing metadata version" << _existingMetadataVersion << doc.toJson(QJsonDocument::Compact);
const auto &metaDataStr = metadataStringFromOCsDocument(doc);
const auto &metaDataDoc = QJsonDocument::fromJson(metaDataStr.toLocal8Bit());
const auto &metaDataObj = metaDataDoc.object();
const auto &fullMetaDataObj = metaDataObj[metadataJsonKey].toObject();
// we will use metadata key from metadata to decrypt legacy metadata, so let's clear the decryption key if any provided by top-level folder
_binaryMetadataKeyForDecryption.clear();
const auto metadataKeyFromJson = fullMetaDataObj[metadataKeyKey].toString().toLocal8Bit();
if (!metadataKeyFromJson.isEmpty()) {
// parse version 1.1 and 1.2 (both must have a single "metadataKey"), not "metadataKeys" as 1.0
const auto decryptedMetadataKeyBase64 = decryptDataWithPrivateKey(metadataKeyFromJson, _account->e2e()->certificateSha256Fingerprint());
if (!decryptedMetadataKeyBase64.isEmpty()) {
// fromBase64() multiple times just to stick with the old wrong way
_binaryMetadataKeyForDecryption = QByteArray::fromBase64(QByteArray::fromBase64(QByteArray::fromBase64(decryptedMetadataKeyBase64)));
}
}
if (binaryMetadataKeyForDecryption().isEmpty() && _existingMetadataVersion < MetadataVersion::Version1_2) {
// parse version 1.0 (before security-vulnerability fix for metadata keys was released
qCDebug(lcCseMetadata()) << "Migrating from" << _existingMetadataVersion << "to"
<< latestSupportedMetadataVersion();
const auto metadataKeys = fullMetaDataObj["metadataKeys"].toObject();
if (metadataKeys.isEmpty()) {
qCWarning(lcCseMetadata()) << "Could not migrate. No metadata keys found!";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return;
}
const auto &allKeys = metadataKeys.keys();
const auto &lastMetadataKeyFromJson = allKeys.last().toLocal8Bit();
if (!lastMetadataKeyFromJson.isEmpty()) {
const auto lastMetadataKeyValueFromJson = metadataKeys.value(lastMetadataKeyFromJson).toString().toLocal8Bit();
if (!lastMetadataKeyValueFromJson.isEmpty()) {
const auto lastMetadataKeyValueFromJsonBase64 = decryptDataWithPrivateKey(lastMetadataKeyValueFromJson, _account->e2e()->certificateSha256Fingerprint());
if (!lastMetadataKeyValueFromJsonBase64.isEmpty()) {
_binaryMetadataKeyForDecryption = QByteArray::fromBase64(QByteArray::fromBase64(lastMetadataKeyValueFromJsonBase64));
}
}
}
}
if (binaryMetadataKeyForDecryption().isEmpty()) {
qCWarning(lcCseMetadata()) << "Could not setup existing metadata with missing metadataKeys!";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return;
}
if (binaryMetadataKeyForEncryption().isEmpty()) {
_binaryMetadataKeyForEncryption = binaryMetadataKeyForDecryption();
}
const auto &files = metaDataObj[filesKey].toObject();
const auto &metadataKey = metaDataObj[metadataJsonKey].toObject()[metadataKeyKey].toString().toUtf8();
const auto &metadataKeyChecksum = metaDataObj[metadataJsonKey].toObject()["checksum"].toString().toUtf8();
setFileDrop(metaDataObj.value("filedrop").toObject());
// for unit tests
_fileDropFromServer = _fileDrop;
for (auto it = files.constBegin(); it != files.constEnd(); ++it) {
EncryptedFile file;
file.encryptedFilename = it.key();
const auto fileObj = it.value().toObject();
file.authenticationTag = QByteArray::fromBase64(fileObj[authenticationTagKey].toString().toLocal8Bit());
file.initializationVector = QByteArray::fromBase64(fileObj[initializationVectorKey].toString().toLocal8Bit());
// Decrypt encrypted part
const auto encryptedFile = fileObj[encryptedKey].toString().toLocal8Bit();
const auto decryptedFile = decryptJsonObject(encryptedFile, binaryMetadataKeyForDecryption());
const auto decryptedFileDoc = QJsonDocument::fromJson(decryptedFile);
const auto decryptedFileObj = decryptedFileDoc.object();
const auto originalFilename = decryptedFileObj["filename"].toString();
if (originalFilename.isEmpty()) {
qCWarning(lcCseMetadata) << "decrypted metadata" << decryptedFileDoc.toJson(QJsonDocument::Compact) << "skipping encrypted file" << file.encryptedFilename << "metadata has an empty file name";
continue;
}
if (!isOriginalFilenameValid(originalFilename)) {
qCWarning(lcCseMetadata) << "skipping encrypted file" << file.encryptedFilename << "metadata has an invalid file name";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
continue;
}
file.originalFilename = originalFilename;
file.encryptionKey = QByteArray::fromBase64(decryptedFileObj["key"].toString().toLocal8Bit());
file.mimetype = decryptedFileObj["mimetype"].toString().toLocal8Bit();
// In case we wrongly stored "inode/directory" we try to recover from it
if (file.mimetype == QByteArrayLiteral("inode/directory")) {
file.mimetype = QByteArrayLiteral("httpd/unix-directory");
}
qCDebug(lcCseMetadata) << "encrypted file" << decryptedFileObj["filename"].toString() << decryptedFileObj["key"].toString() << it.key();
_files.push_back(file);
}
if (!checkMetadataKeyChecksum(metadataKey, metadataKeyChecksum) && _existingMetadataVersion >= MetadataVersion::Version1_2) {
if (!_account->shouldSkipE2eeMetadataChecksumValidation()) {
qCWarning(lcCseMetadata) << "Failed to validate checksum for legacy metadata!"
<< "checksum comparison failed"
<< "server value" << metadataKeyChecksum << "client value" << computeMetadataKeyChecksum(metadataKey);
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return;
} else {
qCWarning(lcCseMetadata) << "Failed to validate checksum for legacy metadata!"
<< "shouldSkipE2eeMetadataChecksumValidation is set. Allowing invalid checksum until next sync.";
}
}
_isMetadataValid = true;
}
FolderMetadata::MetadataVersion FolderMetadata::setupVersionFromExistingMetadata(const QByteArray &metadata)
{
auto resultVersion = FolderMetadata::MetadataVersion{};
const auto &doc = QJsonDocument::fromJson(metadata);
const auto &metaDataStr = metadataStringFromOCsDocument(doc);
const auto &metaDataDoc = QJsonDocument::fromJson(metaDataStr.toLocal8Bit()).object();
const auto &metadataObj = metaDataDoc[metadataJsonKey].toObject();
QString versionStringFromMetadata;
if (metadataObj.contains(versionKey)) {
const auto metadataVersionValue = metadataObj.value(versionKey);
if (metadataVersionValue.type() == QJsonValue::Type::String) {
versionStringFromMetadata = metadataObj[versionKey].toString();
} else if (metadataVersionValue.type() == QJsonValue::Type::Double) {
versionStringFromMetadata = QString::number(metadataVersionValue.toDouble(), 'f', 1);
}
}
else if (metaDataDoc.contains(versionKey)) {
const auto metadataVersionValue = metaDataDoc[versionKey].toVariant();
if (metadataVersionValue.metaType() == QMetaType(QMetaType::QString)) {
versionStringFromMetadata = metadataVersionValue.toString();
} else if (metadataVersionValue.metaType() == QMetaType(QMetaType::Double)) {
versionStringFromMetadata = QString::number(metadataVersionValue.toDouble(), 'f', 1);
} else if (metadataVersionValue.metaType() == QMetaType(QMetaType::Int)) {
versionStringFromMetadata = QString::number(metadataVersionValue.toInt()) + QStringLiteral(".0");
}
}
if (versionStringFromMetadata == QStringLiteral("1.2")) {
resultVersion = MetadataVersion::Version1_2;
} else if (versionStringFromMetadata == QStringLiteral("2.0") || versionStringFromMetadata == QStringLiteral("2")) {
resultVersion = MetadataVersion::Version2_0;
} else if (versionStringFromMetadata == QStringLiteral("2.1")) {
resultVersion = MetadataVersion::Version2_1;
} else if (versionStringFromMetadata == QStringLiteral("1.0")
|| versionStringFromMetadata == QStringLiteral("1.1")) {
// We used to have an intermediate 1.1 after applying a security-vulnerability fix for metadata keys.
// It should be treated as MetadataVersion::Version1, as we don't want to change logic related to 1.2, since 1.1 is an edge case.
resultVersion = MetadataVersion::Version1;
}
return resultVersion;
}
void FolderMetadata::emitSetupComplete()
{
QTimer::singleShot(0, this, [this]() {
emit setupComplete();
});
}
// RSA/ECB/OAEPWithSHA-256AndMGF1Padding using private / public key.
QByteArray FolderMetadata::encryptDataWithPublicKey(const QByteArray &binaryData,
const CertificateInformation &shareUserCertificate) const
{
const auto encryptBase64Result = EncryptionHelper::encryptStringAsymmetric(shareUserCertificate, _account->e2e()->paddingMode(), *_account->e2e(), binaryData);
if (encryptBase64Result) {
return *encryptBase64Result;
} else {
qCWarning(lcCseMetadata()) << "fail to encryptDataWithPublicKey";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return {};
}
return {};
}
QByteArray FolderMetadata::decryptDataWithPrivateKey(const QByteArray &base64Data,
const QByteArray &base64CertificateSha256Hash) const
{
const auto decryptBase64Result = EncryptionHelper::decryptStringAsymmetric(_account->e2e()->getCertificateInformationByFingerprint(base64CertificateSha256Hash), _account->e2e()->paddingMode(), *_account->e2e(), base64Data);
if (!decryptBase64Result) {
qCWarning(lcCseMetadata()) << "ERROR. Could not decrypt the metadata key";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return {};
}
return *decryptBase64Result;
}
// AES/GCM/NoPadding (128 bit key size)
QByteArray FolderMetadata::encryptJsonObject(const QByteArray& obj, const QByteArray pass) const
{
return EncryptionHelper::encryptStringSymmetric(pass, obj);
}
QByteArray FolderMetadata::decryptJsonObject(const QByteArray& encryptedMetadata, const QByteArray& pass) const
{
return EncryptionHelper::decryptStringSymmetric(pass, encryptedMetadata);
}
bool FolderMetadata::checkMetadataKeyChecksum(const QByteArray &metadataKey, const QByteArray &metadataKeyChecksum) const
{
const auto referenceMetadataKeyValue = computeMetadataKeyChecksum(metadataKey);
return referenceMetadataKeyValue == metadataKeyChecksum;
}
QByteArray FolderMetadata::computeMetadataKeyChecksum(const QByteArray &metadataKey) const
{
auto hashAlgorithm = QCryptographicHash{QCryptographicHash::Sha256};
auto mnemonic = _account->e2e()->getMnemonic();
hashAlgorithm.addData(mnemonic.remove(' ').toUtf8());
auto sortedFiles = _files;
std::sort(sortedFiles.begin(), sortedFiles.end(), [](const auto &first, const auto &second) {
return first.encryptedFilename < second.encryptedFilename;
});
for (const auto &singleFile : sortedFiles) {
hashAlgorithm.addData(singleFile.encryptedFilename.toUtf8());
}
hashAlgorithm.addData(metadataKey);
return hashAlgorithm.result().toHex();
}
bool FolderMetadata::isValid() const
{
return _isMetadataValid;
}
FolderMetadata::EncryptedFile FolderMetadata::parseEncryptedFileFromJson(const QString &encryptedFilename, const QJsonValue &fileJSON) const
{
const auto fileObj = fileJSON.toObject();
const auto originalFilename = fileObj["filename"].toString();
if (originalFilename.isEmpty()) {
qCWarning(lcCseMetadata()) << "skipping encrypted file" << encryptedFilename << "metadata has an empty file name";
return {};
}
if (!isOriginalFilenameValid(originalFilename)) {
qCWarning(lcCseMetadata()) << "skipping encrypted file" << encryptedFilename << "metadata has an invalid file name";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return {};
}
EncryptedFile file;
file.encryptedFilename = encryptedFilename;
file.authenticationTag = QByteArray::fromBase64(fileObj[authenticationTagKey].toString().toLocal8Bit());
auto nonce = QByteArray::fromBase64(fileObj[initializationVectorKey].toString().toLocal8Bit());
if (nonce.isEmpty()) {
nonce = QByteArray::fromBase64(fileObj[nonceKey].toString().toLocal8Bit());
}
file.initializationVector = nonce;
file.originalFilename = originalFilename;
file.encryptionKey = QByteArray::fromBase64(fileObj["key"].toString().toLocal8Bit());
file.mimetype = fileObj["mimetype"].toString().toLocal8Bit();
// In case we wrongly stored "inode/directory" we try to recover from it
if (file.mimetype == QByteArrayLiteral("inode/directory")) {
file.mimetype = QByteArrayLiteral("httpd/unix-directory");
}
return file;
}
QJsonObject FolderMetadata::convertFileToJsonObject(const EncryptedFile *encryptedFile) const
{
if (!encryptedFile || !isOriginalFilenameValid(encryptedFile->originalFilename)) {
qCWarning(lcCseMetadata()) << "Metadata generation failed. Invalid original file name.";
return {};
}
QJsonObject file;
file.insert("key", QString(encryptedFile->encryptionKey.toBase64()));
file.insert("filename", encryptedFile->originalFilename);
file.insert("mimetype", QString(encryptedFile->mimetype));
const auto nonceFinalKey = latestSupportedMetadataVersion() < MetadataVersion::Version2_0
? initializationVectorKey
: nonceKey;
file.insert(nonceFinalKey, QString(encryptedFile->initializationVector.toBase64()));
file.insert(authenticationTagKey, QString(encryptedFile->authenticationTag.toBase64()));
return file;
}
const QByteArray FolderMetadata::binaryMetadataKeyForEncryption() const
{
return _binaryMetadataKeyForEncryption;
}
const QSet<QByteArray>& FolderMetadata::keyChecksums() const
{
return _keyChecksums;
}
void FolderMetadata::initEmptyMetadata()
{
if (_account->capabilities().clientSideEncryptionVersion() < 2.0) {
return initEmptyMetadataLegacy();
}
const auto certificateType = _account->e2e()->useTokenBasedEncryption() ?
FolderMetadata::CertificateType::HardwareCertificate : FolderMetadata::CertificateType::SoftwareNextcloudCertificate;
if (_isRootEncryptedFolder) {
if (!addUser(_account->davUser(), _account->e2e()->getCertificate(), certificateType)) {
qCWarning(lcCseMetadata) << "Empty metadata setup failed. Could not add first user.";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return;
}
_binaryMetadataKeyForDecryption = _binaryMetadataKeyForEncryption;
}
_isMetadataValid = true;
emitSetupComplete();
}
void FolderMetadata::initEmptyMetadataLegacy()
{
_binaryMetadataKeyForEncryption = EncryptionHelper::generateRandom(metadataKeySize);
_binaryMetadataKeyForDecryption = _binaryMetadataKeyForEncryption;
_isMetadataValid = true;
emitSetupComplete();
}
QByteArray FolderMetadata::encryptedMetadata()
{
Q_ASSERT(_isMetadataValid);
if (!_isMetadataValid) {
qCWarning(lcCseMetadata()) << "Could not encrypt non-initialized metadata!";
return {};
}
if (latestSupportedMetadataVersion() < MetadataVersion::Version2_0) {
return encryptedMetadataLegacy();
}
if (_isRootEncryptedFolder && _folderUsers.isEmpty() && _existingMetadataVersion < MetadataVersion::Version2_0) {
// migrated from legacy version, create metadata key and setup folderUsrs array
createNewMetadataKeyForEncryption();
}
if (binaryMetadataKeyForEncryption().isEmpty()) {
qCWarning(lcCseMetadata()) << "Encrypting metadata failed! Empty metadata key!";
return {};
}
if (_isRootEncryptedFolder) {
for (auto &folderUser : _folderUsers) {
if (folderUser.userId == _account->davUser()) {
folderUser.certificatePem = _account->e2e()->getCertificate().toPem();
}
}
updateUsersEncryptedMetadataKey();
}
QJsonObject files, folders;
for (auto it = _files.constBegin(), end = _files.constEnd(); it != end; ++it) {
const auto file = convertFileToJsonObject(&(*it));
if (file.isEmpty()) {
qCWarning(lcCseMetadata) << "Metadata generation failed for file" << it->encryptedFilename;
return {};
}
const auto isDirectory =
it->mimetype.isEmpty() || it->mimetype == QByteArrayLiteral("inode/directory") || it->mimetype == QByteArrayLiteral("httpd/unix-directory");
if (isDirectory) {
folders.insert(it->encryptedFilename, it->originalFilename);
} else {
files.insert(it->encryptedFilename, file);
}
}
QJsonArray keyChecksums;
if (_isRootEncryptedFolder) {
for (auto it = _keyChecksums.constBegin(), end = _keyChecksums.constEnd(); it != end; ++it) {
keyChecksums.push_back(QJsonValue::fromVariant(*it));
}
}
QJsonObject cipherText = {{counterKey, QJsonValue::fromVariant(newCounter())}, {filesKey, files}, {foldersKey, folders}};
const auto isChecksumsArrayValid = (!_isRootEncryptedFolder && keyChecksums.isEmpty()) || (_isRootEncryptedFolder && !keyChecksums.isEmpty());
Q_ASSERT(isChecksumsArrayValid);
if (!isChecksumsArrayValid) {
qCWarning(lcCseMetadata) << "Empty keyChecksums while shouldn't be empty!";
return {};
}
if (!keyChecksums.isEmpty()) {
cipherText.insert(keyChecksumsKey, keyChecksums);
}
const QJsonDocument cipherTextDoc(cipherText);
QByteArray authenticationTag;
const auto initializationVector = EncryptionHelper::generateRandom(metadataKeySize);
const auto initializationVectorBase64 = initializationVector.toBase64();
const auto gzippedThenEncryptData = EncryptionHelper::gzipThenEncryptData(binaryMetadataKeyForEncryption(), cipherTextDoc.toJson(QJsonDocument::Compact), initializationVector, authenticationTag).toBase64();
// backwards compatible with old versions ("ciphertext|initializationVector")
const auto encryptedCipherText = QByteArray(gzippedThenEncryptData + QByteArrayLiteral("|") + initializationVectorBase64);
const QJsonObject metadata{{cipherTextKey, QJsonValue::fromVariant(encryptedCipherText)},
{nonceKey, QJsonValue::fromVariant(initializationVectorBase64)},
{authenticationTagKey, QJsonValue::fromVariant(authenticationTag.toBase64())}};
QJsonObject metaObject = {{metadataJsonKey, metadata}, {versionKey, QString::number(_account->capabilities().clientSideEncryptionVersion(), 'f', 1)}};
QJsonArray folderUsers;
if (_isRootEncryptedFolder) {
for (const auto &folderUser : _folderUsers) {
const QJsonObject folderUserJson{{usersUserIdKey, folderUser.userId},
{usersCertificateKey, QJsonValue::fromVariant(folderUser.certificatePem)},
{usersEncryptedMetadataKey, QJsonValue::fromVariant(folderUser.encryptedMetadataKey)}};
folderUsers.push_back(folderUserJson);
}
}
const auto isFolderUsersArrayValid = (!_isRootEncryptedFolder && folderUsers.isEmpty()) || (_isRootEncryptedFolder && !folderUsers.isEmpty());
Q_ASSERT(isFolderUsersArrayValid);
if (!isFolderUsersArrayValid) {
qCWarning(lcCseMetadata) << "Empty folderUsers while shouldn't be empty!";
return {};
}
if (!folderUsers.isEmpty()) {
metaObject.insert(usersKey, folderUsers);
}
Q_ASSERT(!_isRootEncryptedFolder || !folderUsers.isEmpty());
if (!_fileDrop.isEmpty()) {
// if we did not consume _fileDrop, we must keep it where it was, on the server
metaObject.insert(filedropKey, _fileDrop);
}
QJsonDocument internalMetadata;
internalMetadata.setObject(metaObject);
const auto jsonString = internalMetadata.toJson();
const auto metadataForSignature = prepareMetadataForSignature(internalMetadata);
_metadataSignature = _account->e2e()->generateSignatureCryptographicMessageSyntax(metadataForSignature.toBase64()).toBase64();
_encryptedMetadataVersion = latestSupportedMetadataVersion();
return jsonString;
}
QByteArray FolderMetadata::encryptedMetadataLegacy()
{
if (_binaryMetadataKeyForEncryption.isEmpty()) {
qCWarning(lcCseMetadata) << "Metadata generation failed! Empty metadata key!";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return {};
}
const auto version = _account->capabilities().clientSideEncryptionVersion();
// multiple toBase64() just to keep with the old (wrong way)
const auto encryptedMetadataKey = encryptDataWithPublicKey(binaryMetadataKeyForEncryption(), _account->e2e()->getCertificateInformation()).toBase64();
const QJsonObject metadata{
{versionKey, version},
{metadataKeyKey, QJsonValue::fromVariant(encryptedMetadataKey)},
{"checksum", QJsonValue::fromVariant(computeMetadataKeyChecksum(encryptedMetadataKey))},
};
QJsonObject files;
for (auto it = _files.constBegin(), end = _files.constEnd(); it != end; ++it) {
if (!isOriginalFilenameValid(it->originalFilename)) {
qCWarning(lcCseMetadata) << "Metadata generation failed. Invalid original file name for encrypted file" << it->encryptedFilename;
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return {};
}
QJsonObject encrypted;
encrypted.insert("key", QString(it->encryptionKey.toBase64()));
encrypted.insert("filename", it->originalFilename);
encrypted.insert("mimetype", QString(it->mimetype));
QJsonDocument encryptedDoc;
encryptedDoc.setObject(encrypted);
QString encryptedEncrypted = encryptJsonObject(encryptedDoc.toJson(QJsonDocument::Compact), binaryMetadataKeyForEncryption());
if (encryptedEncrypted.isEmpty()) {
qCWarning(lcCseMetadata) << "Metadata generation failed!";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
}
QJsonObject file;
file.insert(encryptedKey, encryptedEncrypted);
file.insert(initializationVectorKey, QString(it->initializationVector.toBase64()));
file.insert(authenticationTagKey, QString(it->authenticationTag.toBase64()));
files.insert(it->encryptedFilename, file);
}
QJsonObject filedrop;
for (auto fileDropIt = _fileDrop.constBegin(), end = _fileDrop.constEnd(); fileDropIt != end; ++fileDropIt) {
filedrop.insert(fileDropIt.key(), fileDropIt.value());
}
auto metaObject = QJsonObject{
{metadataJsonKey, metadata},
};
if (files.count()) {
metaObject.insert(filesKey, files);
}
if (filedrop.count()) {
metaObject.insert(filedropKey, filedrop);
}
_encryptedMetadataVersion = fromItemEncryptionStatusToMedataVersion(EncryptionStatusEnums::fromEndToEndEncryptionApiVersion(version));
QJsonDocument internalMetadata;
internalMetadata.setObject(metaObject);
return internalMetadata.toJson();
}
EncryptionStatusEnums::ItemEncryptionStatus FolderMetadata::existingMetadataEncryptionStatus() const
{
return FolderMetadata::fromMedataVersionToItemEncryptionStatus(_existingMetadataVersion);
}
EncryptionStatusEnums::ItemEncryptionStatus FolderMetadata::encryptedMetadataEncryptionStatus() const
{
return FolderMetadata::fromMedataVersionToItemEncryptionStatus(_encryptedMetadataVersion);
}
bool FolderMetadata::isVersion2AndUp() const
{
return _existingMetadataVersion >= MetadataVersion::Version2_0;
}
FolderMetadata::MetadataVersion FolderMetadata::latestSupportedMetadataVersion() const
{
const auto itemEncryptionStatusFromApiVersion = EncryptionStatusEnums::fromEndToEndEncryptionApiVersion(_account->capabilities().clientSideEncryptionVersion());
return fromItemEncryptionStatusToMedataVersion(itemEncryptionStatusFromApiVersion);
}
bool FolderMetadata::parseFileDropPart(const QJsonDocument &doc)
{
const auto &fileDropObject = doc.object().value(filedropKey).toObject();
const auto &fileDropMap = fileDropObject.toVariantMap();
for (auto it = std::cbegin(fileDropMap); it != std::cend(fileDropMap); ++it) {
const auto fileDropEntryParsed = it.value().toMap();
FileDropEntry fileDropEntry{it.key(),
fileDropEntryParsed.value(cipherTextKey).toByteArray(),
QByteArray::fromBase64(fileDropEntryParsed.value(nonceKey).toByteArray()),
QByteArray::fromBase64(fileDropEntryParsed.value(authenticationTagKey).toByteArray()),
{}};
const auto usersRaw = fileDropEntryParsed.value(usersKey).toList();
for (const auto &userRaw : usersRaw) {
const auto userParsed = userRaw.toMap();
const auto userParsedId = userParsed.value(usersUserIdKey).toByteArray();
if (userParsedId == _account->davUser()) {
const auto fileDropEntryUser = UserWithFileDropEntryAccess{
userParsedId,
QByteArray::fromBase64(decryptDataWithPrivateKey(userParsed.value(usersEncryptedFiledropKey).toByteArray(), _account->e2e()->certificateSha256Fingerprint()))
};
if (!fileDropEntryUser.isValid()) {
qCWarning(lcCseMetadata()) << "Could not parse filedrop data. encryptedFiledropKey decryption failed";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return false;
}
fileDropEntry.currentUser = fileDropEntryUser;
break;
}
}
if (!fileDropEntry.isValid()) {
qCWarning(lcCseMetadata()) << "Could not parse filedrop data. fileDropEntry is invalid for userId" << fileDropEntry.currentUser.userId;
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return false;
}
if (fileDropEntry.currentUser.isValid()) {
_fileDropEntries.push_back(fileDropEntry);
}
}
return true;
}
void FolderMetadata::setFileDrop(const QJsonObject &fileDrop)
{
_fileDrop = fileDrop;
}
QByteArray FolderMetadata::metadataSignature() const
{
return _metadataSignature;
}
QByteArray FolderMetadata::initialMetadata() const
{
return _initialMetadata;
}
void FolderMetadata::updateSelfCertificate()
{
for (auto &oneFolderUser : _folderUsers) {
if (oneFolderUser.userId == _account->davUser()) {
oneFolderUser.certificatePem = _account->e2e()->getCertificate().toPem();
}
}
}
quint64 FolderMetadata::newCounter() const
{
return _counter + 1;
}
EncryptionStatusEnums::ItemEncryptionStatus FolderMetadata::fromMedataVersionToItemEncryptionStatus(const MetadataVersion metadataVersion)
{
switch (metadataVersion) {
case FolderMetadata::MetadataVersion::Version2_1:
case FolderMetadata::MetadataVersion::Version2_0:
return SyncFileItem::EncryptionStatus::EncryptedMigratedV2_0;
case FolderMetadata::MetadataVersion::Version1_2:
return SyncFileItem::EncryptionStatus::EncryptedMigratedV1_2;
case FolderMetadata::MetadataVersion::Version1:
return SyncFileItem::EncryptionStatus::Encrypted;
case FolderMetadata::MetadataVersion::VersionUndefined:
return SyncFileItem::EncryptionStatus::NotEncrypted;
}
return SyncFileItem::EncryptionStatus::NotEncrypted;
}
FolderMetadata::MetadataVersion FolderMetadata::fromItemEncryptionStatusToMedataVersion(const EncryptionStatusEnums::ItemEncryptionStatus encryptionStatus)
{
switch (encryptionStatus) {
case EncryptionStatusEnums::ItemEncryptionStatus::Encrypted:
return MetadataVersion::Version1;
case EncryptionStatusEnums::ItemEncryptionStatus::EncryptedMigratedV1_2:
return MetadataVersion::Version1_2;
case EncryptionStatusEnums::ItemEncryptionStatus::EncryptedMigratedV2_0:
return MetadataVersion::Version2_0;
case EncryptionStatusEnums::ItemEncryptionStatus::NotEncrypted:
return MetadataVersion::VersionUndefined;
}
return MetadataVersion::VersionUndefined;
}
QByteArray FolderMetadata::prepareMetadataForSignature(const QJsonDocument &fullMetadata)
{
auto metdataModified = fullMetadata;
auto modifiedObject = metdataModified.object();
modifiedObject.remove(filedropKey);
if (modifiedObject.contains(usersKey)) {
const auto folderUsers = modifiedObject[usersKey].toArray();
QJsonArray modofiedFolderUsers;
for (auto it = folderUsers.constBegin(); it != folderUsers.constEnd(); ++it) {
auto folderUserObject = it->toObject();
folderUserObject.remove(usersEncryptedFiledropKey);
modofiedFolderUsers.push_back(folderUserObject);
}
modifiedObject.insert(usersKey, modofiedFolderUsers);
}
metdataModified.setObject(modifiedObject);
return metdataModified.toJson(QJsonDocument::Compact);
}
bool FolderMetadata::addEncryptedFile(const EncryptedFile &f) {
Q_ASSERT(_isMetadataValid);
if (!_isMetadataValid) {
qCWarning(lcCseMetadata()) << "Could not add encrypted file to non-initialized metadata!";
return false;
}
if (!isOriginalFilenameValid(f.originalFilename)) {
qCWarning(lcCseMetadata()) << "Could not add encrypted file with invalid original file name.";
_account->reportClientStatus(OCC::ClientStatusReportingStatus::E2EeError_GeneralError);
return false;
}
for (int i = 0; i < _files.size(); ++i) {
if (_files.at(i).originalFilename == f.originalFilename) {
_files.removeAt(i);
break;
}
}
_files.append(f);
return true;
}