forked from linuxdeepin/dde-file-manager-extensions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencryptutils.cpp
More file actions
501 lines (441 loc) · 17.6 KB
/
encryptutils.cpp
File metadata and controls
501 lines (441 loc) · 17.6 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
// SPDX-FileCopyrightText: 2023 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later
#include "encryptutils.h"
#include "dfmplugin_disk_encrypt_global.h"
#include <dfm-framework/event/event.h>
#include <dfm-mount/dmount.h>
#include <QLabel>
#include <QVBoxLayout>
#include <QSettings>
#include <QDBusInterface>
#include <QDBusReply>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDir>
#include <QApplication>
#include <QFutureWatcher>
#include <QtConcurrent>
#include <dconfig.h>
#include <DDialog>
#include <fstab.h>
Q_DECLARE_METATYPE(bool *)
Q_DECLARE_METATYPE(QString *)
using namespace dfmplugin_diskenc;
bool config_utils::exportKeyEnabled()
{
auto cfg = Dtk::Core::DConfig::create("org.deepin.dde.file-manager",
"org.deepin.dde.file-manager.diskencrypt");
cfg->deleteLater();
return cfg->value("allowExportEncKey", true).toBool();
}
QString config_utils::cipherType()
{
auto cfg = Dtk::Core::DConfig::create("org.deepin.dde.file-manager",
"org.deepin.dde.file-manager.diskencrypt");
cfg->deleteLater();
auto cipher = cfg->value("encryptAlgorithm", "aes").toString();
QStringList supportedCipher { "sm4", "aes" };
if (!supportedCipher.contains(cipher))
return "aes";
return cipher;
}
bool fstab_utils::isFstabItem(const QString &mpt)
{
if (mpt.isEmpty())
return false;
bool fstabed { false };
struct fstab *fs;
setfsent();
while ((fs = getfsent()) != nullptr) {
QString path = fs->fs_file;
if (mpt == path) {
fstabed = true;
break;
}
}
endfsent();
return fstabed;
}
int tpm_utils::checkTPM()
{
return dpfSlotChannel->push("dfmplugin_encrypt_manager", "slot_TPMIsAvailablePro").toInt();
}
int tpm_utils::getRandomByTPM(int size, QString *output)
{
return dpfSlotChannel->push("dfmplugin_encrypt_manager", "slot_GetRandomByTPMPro", size, output).toInt();
}
int tpm_utils::isSupportAlgoByTPM(const QString &algoName, bool *support)
{
return dpfSlotChannel->push("dfmplugin_encrypt_manager", "slot_IsTPMSupportAlgoPro", algoName, support).toInt();
}
int tpm_utils::encryptByTPM(const QVariantMap &map)
{
return dpfSlotChannel->push("dfmplugin_encrypt_manager", "slot_EncryptByTPMPro", map).toInt();
}
int tpm_utils::decryptByTPM(const QVariantMap &map, QString *psw)
{
return dpfSlotChannel->push("dfmplugin_encrypt_manager", "slot_DecryptByTPMPro", map, psw).toInt();
}
int tpm_utils::ownerAuthStatus()
{
return dpfSlotChannel->push("dfmplugin_encrypt_manager", "slot_OwnerAuthStatus").toInt();
}
int device_utils::encKeyType(const QString &dev)
{
QDBusInterface iface(kDaemonBusName,
kDaemonBusPath,
kDaemonBusIface,
QDBusConnection::systemBus());
if (iface.isValid()) {
QDBusReply<QString> reply = iface.call("QueryTPMToken", dev);
if (!reply.isValid()) return 0;
QString tokenJson = reply.value();
if (tokenJson.isEmpty()) return 0;
QJsonDocument doc = QJsonDocument::fromJson(tokenJson.toLocal8Bit());
QJsonObject obj = doc.object();
cacheToken(dev, obj.toVariantMap());
QString usePin = obj.value("pin").toString("");
if (usePin.isEmpty()) return 0;
if (usePin == "1") return 1;
if (usePin == "0") return 2;
}
return 0;
}
int tpm_passphrase_utils::genPassphraseFromTPM(const QString &dev, const QString &pin, QString *passphrase)
{
Q_ASSERT(passphrase);
if ((tpm_utils::getRandomByTPM(kPasswordSize, passphrase) != 0)
|| passphrase->isEmpty()) {
qCritical() << "TPM get random number failed!";
return kTPMNoRandomNumber;
}
const QString dirPath = kGlobalTPMConfigPath + dev;
QDir dir(dirPath);
if (!dir.exists())
dir.mkpath(dirPath);
QString sessionHashAlgo, sessionKeyAlgo, primaryHashAlgo, primaryKeyAlgo, minorHashAlgo, minorKeyAlgo;
if (!getAlgorithm(&sessionHashAlgo, &sessionKeyAlgo, &primaryHashAlgo, &primaryKeyAlgo, &minorHashAlgo, &minorKeyAlgo)) {
qCritical() << "TPM algo choice failed!";
return kTPMMissingAlog;
}
QVariantMap map {
{ "PropertyKey_SessionHashAlgo", sessionHashAlgo },
{ "PropertyKey_SessionKeyAlgo", sessionKeyAlgo },
{ "PropertyKey_PrimaryHashAlgo", primaryHashAlgo },
{ "PropertyKey_PrimaryKeyAlgo", primaryKeyAlgo },
{ "PropertyKey_MinorHashAlgo", minorHashAlgo },
{ "PropertyKey_MinorKeyAlgo", minorKeyAlgo },
{ "PropertyKey_DirPath", dirPath },
{ "PropertyKey_Plain", *passphrase },
};
if (pin.isEmpty()) {
map.insert("PropertyKey_EncryptType", kUseTpmAndPcr);
map.insert("PropertyKey_Pcr", "7");
map.insert("PropertyKey_PcrBank", primaryHashAlgo);
} else {
map.insert("PropertyKey_EncryptType", kUseTpmAndPrcAndPin);
map.insert("PropertyKey_Pcr", "7");
map.insert("PropertyKey_PcrBank", primaryHashAlgo);
map.insert("PropertyKey_PinCode", pin);
}
int err = tpm_utils::encryptByTPM(map);
if (err != 0) {
qCritical() << "save to TPM failed!!!";
return TPMError(err);
}
QSettings settings(dirPath + QDir::separator() + "algo.ini", QSettings::IniFormat);
settings.setValue(kConfigKeySessionHashAlgo, QVariant(sessionHashAlgo));
settings.setValue(kConfigKeyPriKeyAlgo, QVariant(sessionKeyAlgo));
settings.setValue(kConfigKeyPriHashAlgo, QVariant(primaryHashAlgo));
settings.setValue(kConfigKeyPriKeyAlgo, QVariant(primaryKeyAlgo));
return kTPMNoError;
}
QString tpm_passphrase_utils::getPassphraseFromTPM(const QString &dev, const QString &pin)
{
const QString dirPath = kGlobalTPMConfigPath + dev;
QSettings tpmSets(dirPath + QDir::separator() + "algo.ini", QSettings::IniFormat);
const QString sessionHashAlgo = tpmSets.value(kConfigKeySessionHashAlgo).toString();
const QString sessionKeyAlgo = tpmSets.value(kConfigKeySessionKeyAlgo).toString();
const QString primaryHashAlgo = tpmSets.value(kConfigKeyPriHashAlgo).toString();
const QString primaryKeyAlgo = tpmSets.value(kConfigKeyPriKeyAlgo).toString();
QVariantMap map {
{ "PropertyKey_EncryptType", (pin.isEmpty() ? kUseTpmAndPcr : kUseTpmAndPrcAndPin) },
{ "PropertyKey_SessionHashAlgo", (sessionHashAlgo.isEmpty() ? "sha256" : sessionHashAlgo) }, // TODO:gongheng need help by liangbo
{ "PropertyKey_SessionKeyAlgo", (sessionKeyAlgo.isEmpty() ? "aes" : sessionKeyAlgo) },
{ "PropertyKey_PrimaryHashAlgo", primaryHashAlgo },
{ "PropertyKey_PrimaryKeyAlgo", primaryKeyAlgo },
{ "PropertyKey_DirPath", dirPath }
};
QString tokenDocPath = dirPath + QDir::separator() + "token.json";
QFile file(tokenDocPath);
if (!file.open(QIODevice::ReadOnly)) {
qCritical() << "Failed to open token.json!";
return "";
}
QJsonDocument tokenDoc = QJsonDocument::fromJson(file.readAll());
file.close();
QJsonObject obj = tokenDoc.object();
if (!obj.contains("pcr") || !obj.contains("pcr-bank")) {
qCritical() << "Failed to get pcr or pcr-bank from token.json!";
return "";
}
const QString pcr = obj.value("pcr").toString();
const QString pcr_bank = obj.value("pcr-bank").toString();
if (!pin.isEmpty())
map.insert("PropertyKey_PinCode", pin);
map.insert("PropertyKey_Pcr", pcr);
map.insert("PropertyKey_PcrBank", pcr_bank);
QString passphrase;
int ok = tpm_utils::decryptByTPM(map, &passphrase);
if (ok != 0) {
qWarning() << "cannot acquire passphrase from TPM for device"
<< dev;
}
return passphrase;
}
bool tpm_passphrase_utils::getAlgorithm(QString *sessionHashAlgo, QString *sessionKeyAlgo,
QString *primaryHashAlgo, QString *primaryKeyAlgo,
QString *minorHashAlgo, QString *minorKeyAlgo)
{
bool re1 { false };
bool re2 { false };
bool re3 { false };
bool re4 { false };
bool re5 { false };
bool re6 { false };
tpm_utils::isSupportAlgoByTPM(kTPMSessionHashAlgo, &re1);
tpm_utils::isSupportAlgoByTPM(kTPMSessionKeyAlgo, &re2);
tpm_utils::isSupportAlgoByTPM(kTPMPrimaryHashAlgo, &re3);
tpm_utils::isSupportAlgoByTPM(kTPMPrimaryKeyAlgo, &re4);
tpm_utils::isSupportAlgoByTPM(kTPMMinorHashAlgo, &re5);
tpm_utils::isSupportAlgoByTPM(kTPMMinorKeyAlgo, &re6);
if (re1 && re2 && re3 && re4 && re5 && re6) {
(*sessionHashAlgo) = kTPMSessionHashAlgo;
(*sessionKeyAlgo) = kTPMSessionKeyAlgo;
(*primaryHashAlgo) = kTPMPrimaryHashAlgo;
(*primaryKeyAlgo) = kTPMPrimaryKeyAlgo;
(*minorHashAlgo) = kTPMMinorHashAlgo;
(*minorKeyAlgo) = kTPMMinorKeyAlgo;
return true;
}
re1 = false;
re2 = false;
re3 = false;
re4 = false;
re5 = false;
re6 = false;
tpm_utils::isSupportAlgoByTPM(kTCMSessionHashAlgo, &re1);
tpm_utils::isSupportAlgoByTPM(kTCMSessionKeyAlgo, &re2);
tpm_utils::isSupportAlgoByTPM(kTCMPrimaryHashAlgo, &re3);
tpm_utils::isSupportAlgoByTPM(kTCMPrimaryKeyAlgo, &re4);
tpm_utils::isSupportAlgoByTPM(kTCMMinorHashAlgo, &re5);
tpm_utils::isSupportAlgoByTPM(kTCMMinorKeyAlgo, &re6);
if (re1 && re2 && re3 && re4 && re5 && re6) {
(*sessionHashAlgo) = kTCMSessionHashAlgo;
(*sessionKeyAlgo) = kTCMSessionKeyAlgo;
(*primaryHashAlgo) = kTCMPrimaryHashAlgo;
(*primaryKeyAlgo) = kTCMPrimaryKeyAlgo;
(*minorHashAlgo) = kTCMMinorHashAlgo;
(*minorKeyAlgo) = kTCMMinorKeyAlgo;
return true;
}
return false;
}
QString recovery_key_utils::formatRecoveryKey(const QString &raw)
{
static const int kSectionLen = 6;
QString formatted = raw;
formatted.remove("-");
int len = formatted.length();
if (len > 24)
formatted = formatted.mid(0, 24);
len = formatted.length();
int dashCount = len / kSectionLen;
if (len % kSectionLen == 0)
dashCount -= 1;
for (; dashCount > 0; dashCount--)
formatted.insert(dashCount * kSectionLen, '-');
return formatted;
}
BlockDev device_utils::createBlockDevice(const QString &devObjPath)
{
using namespace dfmmount;
auto monitor = DDeviceManager::instance()->getRegisteredMonitor(DeviceType::kBlockDevice).objectCast<DBlockMonitor>();
Q_ASSERT(monitor);
return monitor->createDeviceById(devObjPath).objectCast<DBlockDevice>();
}
int dialog_utils::showDialog(const QString &title, const QString &msg, DialogType type)
{
QString icon;
switch (type) {
case kInfo:
icon = "dialog-information";
break;
case kWarning:
icon = "dialog-warning";
break;
case kError:
icon = "dialog-error";
break;
}
Dtk::Widget::DDialog d(qApp->activeWindow());
if (isWayland())
d.setWindowFlag(Qt::WindowStaysOnTopHint);
d.setTitle(title);
d.setMessage(msg);
d.setIcon(QIcon::fromTheme(icon));
d.addButton(qApp->translate("dfmplugin_diskenc::ChgPassphraseDialog", "Confirm"));
return d.exec();
}
void device_utils::cacheToken(const QString &device, const QVariantMap &token)
{
if (token.isEmpty()) {
QDir tmp("/tmp");
tmp.rmpath(kGlobalTPMConfigPath + device);
return;
}
auto makeFile = [](const QString &fileName, const QByteArray &content) {
QFile f(fileName);
if (!f.open(QIODevice::Truncate | QIODevice::WriteOnly)) {
qWarning() << "cannot cache token!" << fileName;
return false;
}
f.write(content);
f.flush();
f.close();
return true;
};
QString devTpmConfigPath = kGlobalTPMConfigPath + device;
QDir tpmPath(devTpmConfigPath);
if (!tpmPath.exists())
tpmPath.mkpath(devTpmConfigPath);
QJsonObject obj = QJsonObject::fromVariantMap(token);
QJsonDocument doc(obj);
QByteArray iv = obj.value("iv").toString().toLocal8Bit();
QByteArray keyPriv = obj.value("kek-priv").toString().toLocal8Bit();
QByteArray keyPub = obj.value("kek-pub").toString().toLocal8Bit();
QByteArray cipher = obj.value("enc").toString().toLocal8Bit();
iv = QByteArray::fromBase64(iv);
keyPriv = QByteArray::fromBase64(keyPriv);
keyPub = QByteArray::fromBase64(keyPub);
cipher = QByteArray::fromBase64(cipher);
bool ret = true;
ret &= makeFile(devTpmConfigPath + "/token.json", doc.toJson());
ret &= makeFile(devTpmConfigPath + "/iv.bin", iv);
ret &= makeFile(devTpmConfigPath + "/key.priv", keyPriv);
ret &= makeFile(devTpmConfigPath + "/key.pub", keyPub);
ret &= makeFile(devTpmConfigPath + "/cipher.out", cipher);
QSettings algo(devTpmConfigPath + "/algo.ini", QSettings::IniFormat);
algo.setValue("session_hash_algo", obj.value("session-hash-alg").toString());
algo.setValue("session_key_algo", obj.value("session-key-alg").toString());
algo.setValue("primary_hash_algo", obj.value("primary-hash-alg").toString());
algo.setValue("primary_key_algo", obj.value("primary-key-alg").toString());
if (!ret)
tpmPath.rmpath(devTpmConfigPath);
}
void dialog_utils::showTPMError(const QString &title, tpm_passphrase_utils::TPMError err)
{
QString msg;
switch (err) {
case tpm_passphrase_utils::kTPMNoRandomNumber:
msg = QObject::tr("Cannot generate random number by TPM");
break;
case tpm_passphrase_utils::kTPMMissingAlog:
msg = QObject::tr("No available encrypt algorithm.");
break;
case tpm_passphrase_utils::kTPMEncryptFailed:
msg = QObject::tr("TPM encrypt failed.");
break;
case tpm_passphrase_utils::kTPMLocked:
msg = QObject::tr("TPM is locked.");
break;
default:
break;
}
if (!msg.isEmpty())
showDialog(title, msg, kError);
}
bool dialog_utils::isWayland()
{
return QApplication::platformName() == "wayland";
}
bool config_utils::enableEncrypt()
{
auto cfg = Dtk::Core::DConfig::create("org.deepin.dde.file-manager",
"org.deepin.dde.file-manager.diskencrypt");
cfg->deleteLater();
return cfg->value("enableEncrypt", true).toBool();
}
int dialog_utils::showConfirmEncryptionDialog(const QString &device, bool needReboot)
{
Dtk::Widget::DDialog dlg(qApp->activeWindow());
if (isWayland())
dlg.setWindowFlag(Qt::WindowStaysOnTopHint);
dlg.setIcon(QIcon::fromTheme("drive-harddisk-root"));
dlg.setTitle(QObject::tr("Confirm encrypt %1?").arg(device));
QWidget *wid = new QWidget(&dlg);
QVBoxLayout *lay = new QVBoxLayout(wid);
QLabel *hint1 = new QLabel(QObject::tr("The current partition is about to be encrypted and cannot be canceled during "
"the encryption process, please confirm the encryption."),
wid);
hint1->setAlignment(Qt::AlignLeft);
hint1->setWordWrap(true);
lay->addWidget(hint1);
QLabel *hint2 = new QLabel(QObject::tr("* After encrypting the partition, "
"the system cannot be rolled back to a lower version, "
"please confirm the encryption"),
wid);
hint2->setAlignment(Qt::AlignLeft);
hint2->setWordWrap(true);
QPalette pal = hint2->palette();
pal.setColor(QPalette::WindowText, QColor("red"));
hint2->setPalette(pal);
lay->addWidget(hint2);
dlg.addContent(wid);
dlg.addButton(QObject::tr("Cancel"));
needReboot ? dlg.addButton(QObject::tr("Confirm and Reboot"), true, Dtk::Widget::DDialog::ButtonRecommend)
: dlg.addButton(QObject::tr("Confirm"), true, Dtk::Widget::DDialog::ButtonRecommend);
return dlg.exec();
}
int dialog_utils::showConfirmDecryptionDialog(const QString &device, bool needReboot)
{
Dtk::Widget::DDialog dlg(qApp->activeWindow());
if (isWayland())
dlg.setWindowFlag(Qt::WindowStaysOnTopHint);
dlg.setIcon(QIcon::fromTheme("drive-harddisk-root"));
dlg.setTitle(QObject::tr("Decrypt %1?").arg(device));
dlg.setMessage(QObject::tr("Decryption can take a long time, "
"so make sure power is connected until the decryption is complete."));
dlg.addButton(QObject::tr("Cancel"));
QString confirmTxt = needReboot ? QObject::tr("Confirm and Reboot") : QObject::tr("Confirm");
dlg.addButton(confirmTxt, true, Dtk::Widget::DDialog::ButtonRecommend);
return dlg.exec();
}
QString tpm_passphrase_utils::getPassphraseFromTPM_NonBlock(const QString &dev, const QString &pin)
{
QEventLoop loop;
QFutureWatcher<QString> watcher;
QObject::connect(&watcher, &QFutureWatcher<QString>::finished, [&] { loop.exit(); });
watcher.setFuture(QtConcurrent::run(tpm_passphrase_utils::getPassphraseFromTPM,
dev,
pin));
qApp->setOverrideCursor(Qt::WaitCursor);
loop.exec();
qApp->restoreOverrideCursor();
return watcher.result();
}
int tpm_passphrase_utils::genPassphraseFromTPM_NonBlock(const QString &dev, const QString &pin, QString *passphrase)
{
QEventLoop loop;
QFutureWatcher<int> watcher;
QObject::connect(&watcher, &QFutureWatcher<int>::finished, [&] { loop.exit(); });
watcher.setFuture(QtConcurrent::run(tpm_passphrase_utils::genPassphraseFromTPM,
dev,
pin,
passphrase));
qApp->setOverrideCursor(Qt::WaitCursor);
loop.exec();
qApp->restoreOverrideCursor();
return watcher.result();
}