/
ssu.cpp
588 lines (482 loc) · 18.1 KB
1
2
3
4
5
6
7
/**
* @file ssu.cpp
* @copyright 2012 Jolla Ltd.
* @author Bernd Wachter <bernd.wachter@jollamobile.com>
* @date 2012
*/
8
#include <QtNetwork>
9
#include <QtXml/QDomDocument>
10
11
12
13
14
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
#include <QUrlQuery>
#endif
15
16
17
#include <getdef.h>
#include <pwd.h>
18
#include "ssu.h"
19
#include "ssulog.h"
20
#include "ssuvariables.h"
21
22
#include "ssucoreconfig.h"
#include "ssurepomanager.h"
23
24
25
#include "../constants.h"
26
Ssu::Ssu(): QObject(){
27
errorFlag = false;
28
pendingRequests = 0;
29
30
#ifdef SSUCONFHACK
31
32
33
34
35
36
37
38
39
40
// dirty hack to make sure we can write to the configuration
// this is currently required since there's no global gconf,
// and we migth not yet have users on bootstrap
QFileInfo settingsInfo(SSU_CONFIGURATION);
if (settingsInfo.groupId() != SSU_GROUP_ID ||
!settingsInfo.permission(QFile::WriteGroup)){
QProcess proc;
proc.start("/usr/bin/ssuconfperm");
proc.waitForFinished();
}
41
#endif
42
43
SsuCoreConfig *settings = SsuCoreConfig::instance();
44
45
46
47
48
49
50
51
52
53
#ifdef TARGET_ARCH
if (!settings->contains("arch"))
settings->setValue("arch", TARGET_ARCH);
#else
// FIXME, try to guess a matching architecture
#warning "TARGET_ARCH not defined"
#endif
settings->sync();
54
55
56
57
58
59
60
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply *)),
SLOT(requestFinished(QNetworkReply *)));
}
61
62
// FIXME, the whole credentials stuff needs reworking
// should probably be part of repo handling instead of core configuration
63
QPair<QString, QString> Ssu::credentials(QString scope){
64
65
SsuCoreConfig *settings = SsuCoreConfig::instance();
return settings->credentials(scope);
66
67
68
}
QString Ssu::credentialsScope(QString repoName, bool rndRepo){
69
70
SsuCoreConfig *settings = SsuCoreConfig::instance();
return settings->credentialsScope(repoName, rndRepo);
71
72
}
73
QString Ssu::credentialsUrl(QString scope){
74
75
SsuCoreConfig *settings = SsuCoreConfig::instance();
return settings->credentialsUrl(scope);
76
77
}
78
79
80
81
bool Ssu::error(){
return errorFlag;
}
82
// Wrappers around SsuCoreConfig
83
QString Ssu::flavour(){
84
85
SsuCoreConfig *settings = SsuCoreConfig::instance();
return settings->flavour();
86
87
}
88
int Ssu::deviceMode(){
89
90
SsuCoreConfig *settings = SsuCoreConfig::instance();
return settings->deviceMode();
91
92
}
93
QString Ssu::domain(){
94
SsuCoreConfig *settings = SsuCoreConfig::instance();
95
return settings->domain(true);
96
97
}
98
bool Ssu::isRegistered(){
99
100
SsuCoreConfig *settings = SsuCoreConfig::instance();
return settings->isRegistered();
101
102
103
}
QDateTime Ssu::lastCredentialsUpdate(){
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
SsuCoreConfig *settings = SsuCoreConfig::instance();
return settings->lastCredentialsUpdate();
}
QString Ssu::release(bool rnd){
SsuCoreConfig *settings = SsuCoreConfig::instance();
return settings->release(rnd);
}
void Ssu::setDeviceMode(int mode, int editMode){
SsuCoreConfig *settings = SsuCoreConfig::instance();
settings->setDeviceMode(mode, editMode);
}
void Ssu::setFlavour(QString flavour){
SsuCoreConfig *settings = SsuCoreConfig::instance();
settings->setFlavour(flavour);
}
void Ssu::setRelease(QString release, bool rnd){
SsuCoreConfig *settings = SsuCoreConfig::instance();
settings->setRelease(release, rnd);
}
void Ssu::setDomain(QString domain){
SsuCoreConfig *settings = SsuCoreConfig::instance();
130
settings->setDomain(domain);
131
132
133
134
135
}
bool Ssu::useSslVerify(){
SsuCoreConfig *settings = SsuCoreConfig::instance();
return settings->useSslVerify();
136
137
}
138
139
140
141
//...
142
143
144
145
146
147
QString Ssu::lastError(){
return errorString;
}
bool Ssu::registerDevice(QDomDocument *response){
QString certificateString = response->elementsByTagName("certificate").at(0).toElement().text();
148
QSslCertificate certificate(certificateString.toLatin1());
149
SsuLog *ssuLog = SsuLog::instance();
150
SsuCoreConfig *settings = SsuCoreConfig::instance();
151
152
153
154
155
156
157
158
159
160
if (certificate.isNull()){
// make sure device is in unregistered state on failed registration
settings->setValue("registered", false);
setError("Certificate is invalid");
return false;
} else
settings->setValue("certificate", certificate.toPem());
QString privateKeyString = response->elementsByTagName("privateKey").at(0).toElement().text();
161
QSslKey privateKey(privateKeyString.toLatin1(), QSsl::Rsa);
162
163
164
165
166
167
168
169
170
171
172
if (privateKey.isNull()){
settings->setValue("registered", false);
setError("Private key is invalid");
return false;
} else
settings->setValue("privateKey", privateKey.toPem());
// oldUser is just for reference purposes, in case we want to notify
// about owner changes for the device
QString oldUser = response->elementsByTagName("user").at(0).toElement().text();
173
ssuLog->print(LOG_DEBUG, QString("Old user for your device was: %1").arg(oldUser));
174
175
176
177
178
179
180
181
182
183
// if we came that far everything required for device registration is done
settings->setValue("registered", true);
settings->sync();
emit registrationStatusChanged();
return true;
}
// RND repos have flavour (devel, testing, release), and release (latest, next)
// Release repos only have release (latest, next, version number)
184
185
186
QString Ssu::repoUrl(QString repoName, bool rndRepo,
QHash<QString, QString> repoParameters,
QHash<QString, QString> parametersOverride){
187
188
SsuRepoManager manager;
return manager.url(repoName, rndRepo, repoParameters, parametersOverride);
189
190
191
192
}
void Ssu::requestFinished(QNetworkReply *reply){
QSslConfiguration sslConfiguration = reply->sslConfiguration();
193
SsuLog *ssuLog = SsuLog::instance();
194
SsuCoreConfig *settings = SsuCoreConfig::instance();
195
196
197
198
199
200
201
202
203
204
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
ssuLog->print(LOG_DEBUG, QString("Certificate used was issued for '%1' by '%2'. Complete chain:")
.arg(sslConfiguration.peerCertificate().subjectInfo(QSslCertificate::CommonName).join(""))
.arg(sslConfiguration.peerCertificate().issuerInfo(QSslCertificate::CommonName).join("")));
foreach (const QSslCertificate cert, sslConfiguration.peerCertificateChain()){
ssuLog->print(LOG_DEBUG, QString("-> %1").arg(cert.subjectInfo(QSslCertificate::CommonName).join("")));
}
#else
205
ssuLog->print(LOG_DEBUG, QString("Certificate used was issued for '%1' by '%2'. Complete chain:")
206
207
.arg(sslConfiguration.peerCertificate().subjectInfo(QSslCertificate::CommonName))
.arg(sslConfiguration.peerCertificate().issuerInfo(QSslCertificate::CommonName)));
208
209
foreach (const QSslCertificate cert, sslConfiguration.peerCertificateChain()){
210
ssuLog->print(LOG_DEBUG, QString("-> %1").arg(cert.subjectInfo(QSslCertificate::CommonName)));
211
}
212
#endif
213
214
/// @TODO: indicate that the device is not registered if there's a 404 on credentials update url
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
// what sucks more, this or goto?
do {
if (settings->contains("home-url")){
QString homeUrl = settings->value("home-url").toString().arg("");
homeUrl.remove(QRegExp("//+$"));
QNetworkRequest request = reply->request();
if (request.url().toString().startsWith(homeUrl, Qt::CaseInsensitive)){
// we don't care about errors on download request
if (reply->error() > 0) break;
QByteArray data = reply->readAll();
storeAuthorizedKeys(data);
break;
}
}
230
231
232
233
if (reply->error() > 0){
pendingRequests--;
setError(reply->errorString());
234
return;
235
236
237
238
239
240
241
242
243
244
245
} else {
QByteArray data = reply->readAll();
qDebug() << "RequestOutput" << data;
QDomDocument doc;
QString xmlError;
if (!doc.setContent(data, &xmlError)){
pendingRequests--;
setError(tr("Unable to parse server response (%1)").arg(xmlError));
return;
}
246
247
QString action = doc.elementsByTagName("action").at(0).toElement().text();
248
249
if (!verifyResponse(&doc)) break;
250
251
252
253
254
255
256
257
258
259
if (action == "register"){
if (!registerDevice(&doc)) break;
} else if (action == "credentials"){
if (!setCredentials(&doc)) break;
} else {
pendingRequests--;
setError(tr("Response to unknown action encountered: %1").arg(action));
return;
}
260
}
261
} while (false);
262
263
pendingRequests--;
264
265
ssuLog->print(LOG_DEBUG, QString("Request finished, pending requests: %1").arg(pendingRequests));
266
if (pendingRequests == 0)
267
268
269
emit done();
}
270
void Ssu::sendRegistration(QString usernameDomain, QString password){
271
272
273
errorFlag = false;
QString ssuCaCertificate, ssuRegisterUrl;
274
QString username, domainName;
275
276
SsuLog *ssuLog = SsuLog::instance();
277
SsuCoreConfig *settings = SsuCoreConfig::instance();
278
279
280
281
282
// Username can include also domain, (user@domain), separate those
if (usernameDomain.contains('@')) {
// separate domain/username and set domain
username = usernameDomain.section('@', 0, 0);
283
284
domainName = usernameDomain.section('@', 1, 1);
setDomain(domainName);
285
286
287
288
289
} else {
// No domain defined
username = usernameDomain;
}
290
291
292
ssuCaCertificate = SsuRepoManager::caCertificatePath();
if (ssuCaCertificate.isEmpty()){
setError("CA certificate for SSU not set ('_ca-certificate in domain')");
293
return;
294
}
295
296
if (!settings->contains("register-url")){
297
298
299
300
301
ssuRegisterUrl = repoUrl("register-url");
if (ssuRegisterUrl.isEmpty()){
setError("URL for SSU registration not set (config key 'register-url')");
return;
}
302
303
304
} else
ssuRegisterUrl = settings->value("register-url").toString();
305
QString IMEI = deviceInfo.deviceUid();
306
307
308
309
if (IMEI == ""){
setError("No valid UID available for your device. For phones: is your modem online?");
return;
}
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
QSslConfiguration sslConfiguration;
if (!useSslVerify())
sslConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone);
sslConfiguration.setCaCertificates(QSslCertificate::fromPath(ssuCaCertificate));
QNetworkRequest request;
request.setUrl(QUrl(QString(ssuRegisterUrl)
.arg(IMEI)
));
request.setSslConfiguration(sslConfiguration);
request.setRawHeader("Authorization", "Basic " +
QByteArray(QString("%1:%2")
.arg(username).arg(password)
325
.toLatin1()).toBase64());
326
327
328
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QUrl form;
329
330
331
332
333
334
335
336
337
338
339
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
QUrlQuery q;
q.addQueryItem("protocolVersion", SSU_PROTOCOL_VERSION);
q.addQueryItem("deviceModel", deviceInfo.deviceModel());
if (!domain().isEmpty()){
q.addQueryItem("domain", domain());
}
form.setQuery(q);
#else
340
form.addQueryItem("protocolVersion", SSU_PROTOCOL_VERSION);
341
form.addQueryItem("deviceModel", deviceInfo.deviceModel());
342
343
344
if (!domain().isEmpty()){
form.addQueryItem("domain", domain());
}
345
#endif
346
347
qDebug() << "Sending request to " << request.url();
348
//qDebug() << form.encodedQueryItems();
349
350
351
QNetworkReply *reply;
352
pendingRequests++;
353
354
355
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
reply = manager->post(request, form.query(QUrl::FullyEncoded).toStdString().c_str());
#else
356
reply = manager->post(request, form.encodedQuery());
357
#endif
358
// we could expose downloadProgress() from reply in case we want progress info
359
360
361
362
363
364
QString homeUrl = settings->value("home-url").toString().arg(username);
if (!homeUrl.isEmpty()){
// clear header, the other request bits are reusable
request.setHeader(QNetworkRequest::ContentTypeHeader, 0);
request.setUrl(homeUrl + "/authorized_keys");
365
ssuLog->print(LOG_DEBUG, QString("Trying to get SSH keys from %1").arg(request.url().toString()));
366
367
368
pendingRequests++;
manager->get(request);
}
369
370
371
}
bool Ssu::setCredentials(QDomDocument *response){
372
SsuCoreConfig *settings = SsuCoreConfig::instance();
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
// generate list with all scopes for generic section, add sections
QDomNodeList credentialsList = response->elementsByTagName("credentials");
QStringList credentialScopes;
for (int i=0;i<credentialsList.size();i++){
QDomNode node = credentialsList.at(i);
QString scope;
QDomNamedNodeMap attributes = node.attributes();
if (attributes.contains("scope")){
scope = attributes.namedItem("scope").toAttr().value();
} else {
setError(tr("Credentials element does not have scope"));
return false;
}
if (node.hasChildNodes()){
QDomElement username = node.firstChildElement("username");
QDomElement password = node.firstChildElement("password");
if (username.isNull() || password.isNull()){
setError(tr("Username and/or password not set"));
return false;
} else {
settings->beginGroup("credentials-" + scope);
settings->setValue("username", username.text());
settings->setValue("password", password.text());
settings->endGroup();
settings->sync();
credentialScopes.append(scope);
}
} else {
setError("");
return false;
}
}
settings->setValue("credentialScopes", credentialScopes);
settings->setValue("lastCredentialsUpdate", QDateTime::currentDateTime());
settings->sync();
emit credentialsChanged();
return true;
}
void Ssu::setError(QString errorMessage){
errorFlag = true;
errorString = errorMessage;
418
419
420
SsuLog *ssuLog = SsuLog::instance();
421
// dump error message to systemd journal for easier debugging
422
ssuLog->print(LOG_WARNING, errorMessage);
423
424
// assume that we don't even need to wait for other pending requests,
425
// and just die. This is only relevant for CLI, which will exit after done()
426
427
428
emit done();
}
429
430
void Ssu::storeAuthorizedKeys(QByteArray data){
QDir dir;
431
SsuLog *ssuLog = SsuLog::instance();
432
433
434
435
436
437
438
439
440
441
442
443
444
445
int uid_min = getdef_num("UID_MIN", -1);
QString homePath;
if (getuid() >= uid_min){
homePath = dir.homePath();
} else if (getuid() == 0){
// place authorized_keys in the default users home when run with uid0
struct passwd *pw = getpwuid(uid_min);
if (pw == NULL){
ssuLog->print(LOG_DEBUG, QString("Unable to find password entry for uid %1")
.arg(uid_min));
return;
}
446
447
448
449
450
451
452
453
454
455
456
//homePath = QString(pw->pw_dir);
homePath = pw->pw_dir;
// use users uid/gid for creating the directories and files
setegid(pw->pw_gid);
seteuid(uid_min);
ssuLog->print(LOG_DEBUG, QString("Dropping to %1/%2 for writing authorized keys")
.arg(uid_min)
.arg(pw->pw_gid));
} else
457
458
return;
459
460
461
462
463
464
465
466
467
468
469
470
if (dir.exists(homePath + "/.ssh/authorized_keys")){
ssuLog->print(LOG_DEBUG, QString(".ssh/authorized_keys already exists in %1")
.arg(homePath));
return;
}
if (!dir.exists(homePath + "/.ssh"))
if (!dir.mkdir(homePath + "/.ssh")){
ssuLog->print(LOG_DEBUG, QString("Unable to create .ssh in %1")
.arg(homePath));
return;
}
471
472
QFile::setPermissions(homePath + "/.ssh",
473
474
QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner);
475
QFile authorizedKeys(homePath + "/.ssh/authorized_keys");
476
477
478
479
480
481
authorizedKeys.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate);
authorizedKeys.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
QTextStream out(&authorizedKeys);
out << data;
out.flush();
authorizedKeys.close();
482
483
484
485
486
if (getuid() == 0){
seteuid(0);
setegid(0);
}
487
488
}
489
void Ssu::updateCredentials(bool force){
490
SsuCoreConfig *settings = SsuCoreConfig::instance();
491
492
errorFlag = false;
493
494
SsuLog *ssuLog = SsuLog::instance();
495
if (deviceInfo.deviceUid() == ""){
496
497
498
499
setError("No valid UID available for your device. For phones: is your modem online?");
return;
}
500
QString ssuCaCertificate, ssuCredentialsUrl;
501
502
503
ssuCaCertificate = SsuRepoManager::caCertificatePath();
if (ssuCaCertificate.isEmpty()){
setError("CA certificate for SSU not set ('_ca-certificate in domain')");
504
return;
505
}
506
507
if (!settings->contains("credentials-url")){
508
509
510
511
512
ssuCredentialsUrl = repoUrl("credentials-url");
if (ssuCredentialsUrl.isEmpty()){
setError("URL for credentials update not set (config key 'credentials-url')");
return;
}
513
514
515
516
517
518
519
520
521
} else
ssuCredentialsUrl = settings->value("credentials-url").toString();
if (!isRegistered()){
setError("Device is not registered.");
return;
}
if (!force){
522
// skip updating if the last update was less than 30 minutes ago
523
524
525
526
QDateTime now = QDateTime::currentDateTime();
if (settings->contains("lastCredentialsUpdate")){
QDateTime last = settings->value("lastCredentialsUpdate").toDateTime();
527
if (last >= now.addSecs(-1800)){
528
ssuLog->print(LOG_DEBUG, QString("Skipping credentials update, last update was at %1")
529
.arg(last.toString()));
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
emit done();
return;
}
}
}
// check when the last update was, decide if an update is required
QSslConfiguration sslConfiguration;
if (!useSslVerify())
sslConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone);
QSslKey privateKey(settings->value("privateKey").toByteArray(), QSsl::Rsa);
QSslCertificate certificate(settings->value("certificate").toByteArray());
QList<QSslCertificate> caCertificates;
caCertificates << QSslCertificate::fromPath(ssuCaCertificate);
sslConfiguration.setCaCertificates(caCertificates);
sslConfiguration.setPrivateKey(privateKey);
sslConfiguration.setLocalCertificate(certificate);
QNetworkRequest request;
552
request.setUrl(QUrl(ssuCredentialsUrl.arg(deviceInfo.deviceUid())));
553
554
ssuLog->print(LOG_DEBUG, QString("Sending credential update request to %1")
555
.arg(request.url().toString()));
556
557
request.setSslConfiguration(sslConfiguration);
558
559
pendingRequests++;
manager->get(request);
560
561
562
563
}
void Ssu::unregister(){
564
SsuCoreConfig *settings = SsuCoreConfig::instance();
565
566
567
settings->setValue("privateKey", "");
settings->setValue("certificate", "");
settings->setValue("registered", false);
568
settings->sync();
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
emit registrationStatusChanged();
}
bool Ssu::verifyResponse(QDomDocument *response){
QString action = response->elementsByTagName("action").at(0).toElement().text();
QString deviceId = response->elementsByTagName("deviceId").at(0).toElement().text();
QString protocolVersion = response->elementsByTagName("protocolVersion").at(0).toElement().text();
// compare device ids
if (protocolVersion != SSU_PROTOCOL_VERSION){
setError(
tr("Response has unsupported protocol version %1, client requires version %2")
.arg(protocolVersion)
.arg(SSU_PROTOCOL_VERSION)
);
return false;
}
return true;
}