/
ssu.cpp
619 lines (509 loc) · 19.7 KB
1
2
3
4
5
6
7
8
/**
* @file ssu.cpp
* @copyright 2012 Jolla Ltd.
* @author Bernd Wachter <bernd.wachter@jollamobile.com>
* @date 2012
*/
#include <QtXml/QDomDocument>
9
10
#include "ssu.h"
11
#include "ssulog.h"
12
#include "ssuvariables.h"
13
14
15
#include "../constants.h"
16
Ssu::Ssu(QString fallbackLog): QObject(){
17
errorFlag = false;
18
fallbackLogPath = fallbackLog;
19
pendingRequests = 0;
20
21
#ifdef SSUCONFHACK
22
23
24
25
26
27
28
29
30
31
// 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();
}
32
#endif
33
34
settings = new SsuSettings(SSU_CONFIGURATION, QSettings::IniFormat, SSU_DEFAULT_CONFIGURATION);
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
repoSettings = new QSettings(SSU_REPO_CONFIGURATION, QSettings::IniFormat);
#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();
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply *)),
SLOT(requestFinished(QNetworkReply *)));
}
QPair<QString, QString> Ssu::credentials(QString scope){
QPair<QString, QString> ret;
settings->beginGroup("credentials-" + scope);
ret.first = settings->value("username").toString();
ret.second = settings->value("password").toString();
settings->endGroup();
return ret;
}
QString Ssu::credentialsScope(QString repoName, bool rndRepo){
if (settings->contains("credentials-scope"))
return settings->value("credentials-scope").toString();
else
return "your-configuration-is-broken-and-does-not-contain-credentials-scope";
}
67
68
69
70
71
72
73
QString Ssu::credentialsUrl(QString scope){
if (settings->contains("credentials-url-" + scope))
return settings->value("credentials-url-" + scope).toString();
else
return "your-configuration-is-broken-and-does-not-contain-credentials-url-for-" + scope;
}
74
75
76
77
78
79
80
81
82
83
84
bool Ssu::error(){
return errorFlag;
}
QString Ssu::flavour(){
if (settings->contains("flavour"))
return settings->value("flavour").toString();
else
return "release";
}
85
86
87
88
89
90
91
QString Ssu::domain(){
if (settings->contains("domain"))
return settings->value("domain").toString();
else
return "";
}
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
bool Ssu::isRegistered(){
if (!settings->contains("privateKey"))
return false;
if (!settings->contains("certificate"))
return false;
return settings->value("registered").toBool();
}
QDateTime Ssu::lastCredentialsUpdate(){
return settings->value("lastCredentialsUpdate").toDateTime();
}
QString Ssu::lastError(){
return errorString;
}
bool Ssu::registerDevice(QDomDocument *response){
QString certificateString = response->elementsByTagName("certificate").at(0).toElement().text();
QSslCertificate certificate(certificateString.toAscii());
111
SsuLog *ssuLog = SsuLog::instance();
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
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();
QSslKey privateKey(privateKeyString.toAscii(), QSsl::Rsa);
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();
134
ssuLog->print(LOG_DEBUG, QString("Old user for your device was: %1").arg(oldUser));
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
// if we came that far everything required for device registration is done
settings->setValue("registered", true);
settings->sync();
emit registrationStatusChanged();
return true;
}
QString Ssu::release(bool rnd){
if (rnd)
return settings->value("rndRelease").toString();
else
return settings->value("release").toString();
}
// RND repos have flavour (devel, testing, release), and release (latest, next)
// Release repos only have release (latest, next, version number)
QString Ssu::repoUrl(QString repoName, bool rndRepo, QHash<QString, QString> repoParameters){
QString r;
QStringList configSections;
155
SsuVariables var;
156
SsuLog *ssuLog = SsuLog::instance();
157
158
159
errorFlag = false;
160
// fill in all arbitrary variables from ssu.ini
161
var.resolveSection(settings, "repository-url-variables", &repoParameters);
162
163
// add/overwrite some of the variables with sane ones
164
165
if (rndRepo){
repoParameters.insert("flavour", repoSettings->value(flavour()+"-flavour/flavour-pattern").toString());
166
167
repoParameters.insert("flavourPattern", repoSettings->value(flavour()+"-flavour/flavour-pattern").toString());
repoParameters.insert("flavourName", flavour());
168
configSections << flavour()+"-flavour" << "rnd" << "all";
169
170
171
// Make it possible to give any values with the flavour as well.
// These values can be overridden later with domain if needed.
172
var.resolveSection(repoSettings, flavour()+"-flavour", &repoParameters);
173
174
175
176
} else {
configSections << "release" << "all";
}
177
178
repoParameters.insert("release", release(rndRepo));
179
180
181
182
183
if (!repoParameters.contains("debugSplit"))
repoParameters.insert("debugSplit", "packages");
if (!repoParameters.contains("arch"))
repoParameters.insert("arch", settings->value("arch").toString());
184
185
186
187
188
189
190
191
192
// todo: allow override of deviceModel for cli url resolving
QStringList adaptationRepos = deviceInfo.adaptationRepos();
// read adaptation from settings, in case it can't be determined from
// board mappings. this is obsolete, and will be dropped soon
if (settings->contains("adaptation"))
repoParameters.insert("adaptation", settings->value("adaptation").toString());
193
194
repoParameters.insert("deviceFamily", deviceInfo.deviceFamily());
repoParameters.insert("deviceModel", deviceInfo.deviceModel());
195
196
197
// Those keys have now been obsoleted by generic variables, support for
// it will be removed soon
198
199
200
201
202
203
204
205
QStringList keys;
keys << "chip" << "adaptation" << "vendor";
foreach(QString key, keys){
QString value;
if (deviceInfo.getValue(key,value))
repoParameters.insert(key, value);
}
206
207
208
209
210
211
212
213
214
215
216
217
// special handling for adaptation-repositories
// - check if repo is in right format (adaptation\d*)
// - check if the configuration has that many adaptation repos
// - export the entry in the adaptation list as %(adaptation)
// - look up variables for that adaptation, and export matching
// adaptation variable
QRegExp regex("adaptation\\\d*", Qt::CaseSensitive, QRegExp::RegExp2);
if (regex.exactMatch(repoName)){
regex.setPattern("\\\d*");
regex.lastIndexIn(repoName);
int n = regex.cap().toInt();
218
219
220
221
222
223
if (!adaptationRepos.isEmpty()){
if (adaptationRepos.size() <= n) {
ssuLog->print(LOG_INFO, "Note: repo index out of bounds, substituting 0" + repoName);
n = 0;
}
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
QString adaptationRepo = adaptationRepos.at(n);
repoParameters.insert("adaptation", adaptationRepo);
ssuLog->print(LOG_DEBUG, "Found first adaptation " + repoName);
QHash<QString, QString> h = deviceInfo.variableSection(adaptationRepo);
QHash<QString, QString>::const_iterator i = h.constBegin();
while (i != h.constEnd()){
repoParameters.insert(i.key(), i.value());
i++;
}
} else
ssuLog->print(LOG_INFO, "Note: adaptation repo for invalid repo requested " + repoName);
repoName = "adaptation";
}
241
// Domain variables
242
// first read all variables from default-domain
243
244
var.resolveSection(repoSettings, "default-domain", &repoParameters);
245
// then overwrite with domain specific things if that block is available
246
var.resolveSection(repoSettings, domain()+"-domain", &repoParameters);
247
248
249
250
251
252
253
254
255
256
257
if (settings->contains("repository-urls/" + repoName))
r = settings->value("repository-urls/" + repoName).toString();
else {
foreach (const QString §ion, configSections){
repoSettings->beginGroup(section);
if (repoSettings->contains(repoName)){
r = repoSettings->value(repoName).toString();
repoSettings->endGroup();
break;
}
258
259
260
261
repoSettings->endGroup();
}
}
262
return var.resolveString(r, &repoParameters);
263
264
265
266
}
void Ssu::requestFinished(QNetworkReply *reply){
QSslConfiguration sslConfiguration = reply->sslConfiguration();
267
SsuLog *ssuLog = SsuLog::instance();
268
269
ssuLog->print(LOG_DEBUG, QString("Certificate used was issued for '%1' by '%2'. Complete chain:")
270
271
.arg(sslConfiguration.peerCertificate().subjectInfo(QSslCertificate::CommonName))
.arg(sslConfiguration.peerCertificate().issuerInfo(QSslCertificate::CommonName)));
272
273
foreach (const QSslCertificate cert, sslConfiguration.peerCertificateChain()){
274
ssuLog->print(LOG_DEBUG, QString("-> %1").arg(cert.subjectInfo(QSslCertificate::CommonName)));
275
276
}
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
// 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;
}
}
292
293
294
295
if (reply->error() > 0){
pendingRequests--;
setError(reply->errorString());
296
return;
297
298
299
300
301
302
303
304
305
306
307
} 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;
}
308
309
QString action = doc.elementsByTagName("action").at(0).toElement().text();
310
311
if (!verifyResponse(&doc)) break;
312
313
314
315
316
317
318
319
320
321
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;
}
322
}
323
} while (false);
324
325
pendingRequests--;
326
327
ssuLog->print(LOG_DEBUG, QString("Request finished, pending requests: %1").arg(pendingRequests));
328
if (pendingRequests == 0)
329
330
331
emit done();
}
332
void Ssu::sendRegistration(QString usernameDomain, QString password){
333
334
335
errorFlag = false;
QString ssuCaCertificate, ssuRegisterUrl;
336
QString username, domainName;
337
338
339
SsuLog *ssuLog = SsuLog::instance();
340
341
342
343
// Username can include also domain, (user@domain), separate those
if (usernameDomain.contains('@')) {
// separate domain/username and set domain
username = usernameDomain.section('@', 0, 0);
344
345
domainName = usernameDomain.section('@', 1, 1);
setDomain(domainName);
346
347
348
349
350
} else {
// No domain defined
username = usernameDomain;
}
351
352
353
354
355
356
357
if (!settings->contains("ca-certificate")){
setError("CA certificate for SSU not set (config key 'ca-certificate')");
return;
} else
ssuCaCertificate = settings->value("ca-certificate").toString();
if (!settings->contains("register-url")){
358
359
360
361
362
ssuRegisterUrl = repoUrl("register-url");
if (ssuRegisterUrl.isEmpty()){
setError("URL for SSU registration not set (config key 'register-url')");
return;
}
363
364
365
} else
ssuRegisterUrl = settings->value("register-url").toString();
366
QString IMEI = deviceInfo.deviceUid();
367
368
369
370
if (IMEI == ""){
setError("No valid UID available for your device. For phones: is your modem online?");
return;
}
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
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)
.toAscii()).toBase64());
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
QUrl form;
form.addQueryItem("protocolVersion", SSU_PROTOCOL_VERSION);
391
form.addQueryItem("deviceModel", deviceInfo.deviceModel());
392
393
394
if (!domain().isEmpty()){
form.addQueryItem("domain", domain());
}
395
396
qDebug() << "Sending request to " << request.url();
397
398
qDebug() << form.encodedQueryItems();
399
400
QNetworkReply *reply;
401
pendingRequests++;
402
403
reply = manager->post(request, form.encodedQuery());
// we could expose downloadProgress() from reply in case we want progress info
404
405
406
407
408
409
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");
410
ssuLog->print(LOG_DEBUG, QString("Trying to get SSH keys from %1").arg(request.url().toString()));
411
412
413
pendingRequests++;
manager->get(request);
}
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
}
bool Ssu::setCredentials(QDomDocument *response){
// 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;
462
463
464
SsuLog *ssuLog = SsuLog::instance();
465
// dump error message to systemd journal for easier debugging
466
ssuLog->print(LOG_WARNING, errorMessage);
467
468
// assume that we don't even need to wait for other pending requests,
469
// and just die. This is only relevant for CLI, which will exit after done()
470
471
472
473
474
emit done();
}
void Ssu::setFlavour(QString flavour){
settings->setValue("flavour", flavour);
475
settings->sync();
476
477
478
479
480
481
482
483
emit flavourChanged();
}
void Ssu::setRelease(QString release, bool rnd){
if (rnd)
settings->setValue("rndRelease", release);
else
settings->setValue("release", release);
484
settings->sync();
485
486
}
487
488
489
490
491
void Ssu::setDomain(QString domain){
settings->setValue("domain", domain);
settings->sync();
}
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
void Ssu::storeAuthorizedKeys(QByteArray data){
QDir dir;
// only set the key for unprivileged users
if (getuid() < 1000) return;
if (dir.exists(dir.homePath() + "/.ssh/authorized_keys"))
return;
if (!dir.exists(dir.homePath() + "/.ssh"))
if (!dir.mkdir(dir.homePath() + "/.ssh")) return;
QFile::setPermissions(dir.homePath() + "/.ssh",
QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner);
QFile authorizedKeys(dir.homePath() + "/.ssh/authorized_keys");
authorizedKeys.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate);
authorizedKeys.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
QTextStream out(&authorizedKeys);
out << data;
out.flush();
authorizedKeys.close();
}
516
517
518
void Ssu::updateCredentials(bool force){
errorFlag = false;
519
520
SsuLog *ssuLog = SsuLog::instance();
521
if (deviceInfo.deviceUid() == ""){
522
523
524
525
setError("No valid UID available for your device. For phones: is your modem online?");
return;
}
526
527
528
529
530
531
532
533
QString ssuCaCertificate, ssuCredentialsUrl;
if (!settings->contains("ca-certificate")){
setError("CA certificate for SSU not set (config key 'ca-certificate')");
return;
} else
ssuCaCertificate = settings->value("ca-certificate").toString();
if (!settings->contains("credentials-url")){
534
535
536
537
538
ssuCredentialsUrl = repoUrl("credentials-url");
if (ssuCredentialsUrl.isEmpty()){
setError("URL for credentials update not set (config key 'credentials-url')");
return;
}
539
540
541
542
543
544
545
546
547
} else
ssuCredentialsUrl = settings->value("credentials-url").toString();
if (!isRegistered()){
setError("Device is not registered.");
return;
}
if (!force){
548
// skip updating if the last update was less than 30 minutes ago
549
550
551
552
QDateTime now = QDateTime::currentDateTime();
if (settings->contains("lastCredentialsUpdate")){
QDateTime last = settings->value("lastCredentialsUpdate").toDateTime();
553
if (last >= now.addSecs(-1800)){
554
ssuLog->print(LOG_DEBUG, QString("Skipping credentials update, last update was at %1")
555
.arg(last.toString()));
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
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;
578
request.setUrl(QUrl(ssuCredentialsUrl.arg(deviceInfo.deviceUid())));
579
580
ssuLog->print(LOG_DEBUG, QString("Sending credential update request to %1")
581
.arg(request.url().toString()));
582
583
request.setSslConfiguration(sslConfiguration);
584
585
pendingRequests++;
manager->get(request);
586
587
588
589
590
591
592
593
594
595
596
597
598
}
bool Ssu::useSslVerify(){
if (settings->contains("ssl-verify"))
return settings->value("ssl-verify").toBool();
else
return true;
}
void Ssu::unregister(){
settings->setValue("privateKey", "");
settings->setValue("certificate", "");
settings->setValue("registered", false);
599
settings->sync();
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
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;
}