settingsvpnmodel.cpp 53.4 KB
Newer Older
1
/*
2 3
 * Copyright (c) 2016 - 2019 Jolla Ltd.
 * Copyright (c) 2019 Open Mobile Platform LLC.
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
 *
 * You may use this file under the terms of the BSD license as follows:
 *
 * "Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in
 *     the documentation and/or other materials provided with the
 *     distribution.
 *   * Neither the name of Nemo Mobile nor the names of its contributors
 *     may be used to endorse or promote products derived from this
 *     software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
 */

33
#include <QRegularExpression>
34
#include <QStandardPaths>
35
#include <QDataStream>
36
#include <QCryptographicHash>
37 38
#include <QQmlEngine>
#include <QDir>
39 40
#include <QXmlQuery>
#include <QXmlResultItems>
41
#include <QSettings>
42 43
#include "logging_p.h"
#include "vpnmanager.h"
44

45
#include "settingsvpnmodel.h"
46

47 48
namespace {

49 50
const auto defaultDomain = QStringLiteral("sailfishos.org");
const auto legacyDefaultDomain(QStringLiteral("merproject.org"));
51

52
int numericValue(VpnConnection::ConnectionState state)
53
{
54
    return (state == VpnConnection::Ready ? 3 :
55 56 57 58 59 60 61 62 63 64
                (state == VpnConnection::Configuration ? 2 : 0));
}

VpnConnection::ConnectionState getMaxState(VpnConnection::ConnectionState newState, VpnConnection::ConnectionState oldState)
{
    if (numericValue(newState) > numericValue(oldState)) {
        return newState;
    }

    return oldState;
65
}
66

67 68
} // end anonymous namespace

69 70
SettingsVpnModel::SettingsVpnModel(QObject* parent)
    : VpnModel(parent)
71 72 73 74 75
    , credentials_(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/system/privileged/vpn-data"))
    , bestState_(VpnConnection::Idle)
    , autoConnect_(false)
    , orderByConnected_(true)
    , provisioningOutputPath_(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QStringLiteral("/system/privileged/vpn-provisioning"))
76
    , roles(VpnModel::roleNames())
77
{
78
    VpnManager *manager = vpnManager();
79

80
    roles.insert(ConnectedRole, "connected");
81

82 83 84
    connect(manager, &VpnManager::connectionAdded, this, &SettingsVpnModel::connectionAdded, Qt::UniqueConnection);
    connect(manager, &VpnManager::connectionRemoved, this, &SettingsVpnModel::connectionRemoved, Qt::UniqueConnection);
    connect(manager, &VpnManager::connectionsRefreshed, this, &SettingsVpnModel::connectionsRefreshed, Qt::UniqueConnection);
85 86
}

87
SettingsVpnModel::~SettingsVpnModel()
88
{
89
    VpnManager *manager = vpnManager();
90

91
    disconnect(manager, 0, this, 0);
92 93
}

94
void SettingsVpnModel::createConnection(const QVariantMap &createProperties)
95
{
96 97 98 99 100 101 102
    QVariantMap properties(createProperties);
    const QString domain(properties.value(QString("domain")).toString());
    if (domain.isEmpty()) {
        properties.insert(QString("domain"), QVariant::fromValue(createDefaultDomain()));
    }

    vpnManager()->createConnection(properties);
103 104
}

105
QHash<int, QByteArray> SettingsVpnModel::roleNames() const
106
{
107
    return roles;
108 109
}

110
QVariant SettingsVpnModel::data(const QModelIndex &index, int role) const
111
{
112 113 114 115 116
    if (index.isValid() && index.row() >= 0 && index.row() < connections().count()) {
        switch (role) {
        case ConnectedRole:
            return QVariant::fromValue((bool)connections().at(index.row())->connected());
        default:
117
            return VpnModel::data(index, role);
118 119 120
        }
    }

121
    return QVariant();
122 123
}

124
VpnConnection::ConnectionState SettingsVpnModel::bestState() const
125
{
126
    return bestState_;
127 128
}

129
bool SettingsVpnModel::autoConnect() const
130
{
131 132
    return autoConnect_;
}
133

134
bool SettingsVpnModel::orderByConnected() const
135 136 137
{
    return orderByConnected_;
}
138

139
void SettingsVpnModel::setOrderByConnected(bool orderByConnected)
140 141 142
{
    if (orderByConnected != orderByConnected_) {
        orderByConnected_ = orderByConnected;
143
        VpnModel::connectionsChanged();
144 145
        emit orderByConnectedChanged();
    }
146 147
}

148
void SettingsVpnModel::modifyConnection(const QString &path, const QVariantMap &properties)
149
{
150 151 152 153
    VpnConnection *conn = vpnManager()->connection(path);
    if (conn) {
        QVariantMap updatedProperties(properties);
        const QString domain(updatedProperties.value(QString("domain")).toString());
154

155 156 157 158 159 160 161 162 163
        if (domain.isEmpty()) {
            if (isDefaultDomain(conn->domain())) {
                // The connection already has a default domain, no need to change it
                updatedProperties.remove("domain");
            }
            else {
                updatedProperties.insert(QString("domain"), QVariant::fromValue(createDefaultDomain()));
            }
        }
164

165 166 167
        const QString location(CredentialsRepository::locationForObjectPath(path));
        const bool couldStoreCredentials(credentials_.credentialsExist(location));
        const bool canStoreCredentials(properties.value(QString("storeCredentials")).toBool());
168

169
        vpnManager()->modifyConnection(path, updatedProperties);
170

171 172 173 174 175 176
        if (canStoreCredentials != couldStoreCredentials) {
            if (canStoreCredentials) {
                credentials_.storeCredentials(location, QVariantMap());
            } else {
                credentials_.removeCredentials(location);
            }
177 178
        }
    }
179 180
    else {
        qCWarning(lcVpnLog) << "VPN connection modification failed: connection doesn't exist";
181 182 183
    }
}

184
void SettingsVpnModel::deleteConnection(const QString &path)
185
{
186 187 188 189 190 191
    if (VpnConnection *conn = vpnManager()->connection(path)) {
        // Remove cached credentials
        const QString location(CredentialsRepository::locationForObjectPath(path));
        if (credentials_.credentialsExist(location)) {
            credentials_.removeCredentials(location);
        }
192

193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
        // Remove provisioned files
        if (conn->type() == QStringLiteral("openvpn")) {
            QVariantMap providerProperties = conn->providerProperties();
            QStringList fileProperties;
            fileProperties << QStringLiteral("OpenVPN.Cert") << QStringLiteral("OpenVPN.Key") << QStringLiteral("OpenVPN.CACert") << QStringLiteral("OpenVPN.ConfigFile");
            for (const QString property : fileProperties) {
                const QString filename = providerProperties.value(property).toString();

                // Check if the file has been provisioned
                if (filename.contains(provisioningOutputPath_)) {
                    int timesUsed = 0;

                    // Check the same file is not used by other connections
                    for (VpnConnection *c : connections()) {
                        if (filename == c->providerProperties().value(property).toString()) {
                            timesUsed++;
                            if (timesUsed > 1) {
                                break;
                            }
                        }
                    }
214

215 216 217 218
                    if (timesUsed > 1) {
                        qCInfo(lcVpnLog) << "VPN provisioning file kept, used by" << timesUsed << "connections.";
                        continue;
                    }
mvogt's avatar
mvogt committed
219

220 221 222 223 224 225 226 227 228
                    qCInfo(lcVpnLog) << "VPN provisioning file removed: " << filename;
                    if (!QFile::remove(filename)) {
                        qCWarning(lcVpnLog) << "VPN provisioning file could not be removed: " << filename;
                    }
                }
            }
        }

        vpnManager()->deleteConnection(path);
mvogt's avatar
mvogt committed
229 230 231 232
    }

}

233
void SettingsVpnModel::activateConnection(const QString &path)
mvogt's avatar
mvogt committed
234
{
235
    vpnManager()->activateConnection(path);
mvogt's avatar
mvogt committed
236 237
}

238
void SettingsVpnModel::deactivateConnection(const QString &path)
mvogt's avatar
mvogt committed
239
{
240
    vpnManager()->deactivateConnection(path);
mvogt's avatar
mvogt committed
241 242
}

243
VpnConnection *SettingsVpnModel::get(int index) const
mvogt's avatar
mvogt committed
244
{
245 246 247 248
    if (index >= 0 && index < connections().size()) {
        VpnConnection *item(connections().at(index));
        QQmlEngine::setObjectOwnership(item, QQmlEngine::CppOwnership);
        return item;
mvogt's avatar
mvogt committed
249 250
    }

251
    return 0;
mvogt's avatar
mvogt committed
252 253 254

}

255 256 257
// ==========================================================================
// QAbstractListModel Ordering
// ==========================================================================
mvogt's avatar
mvogt committed
258

259
bool SettingsVpnModel::compareConnections(const VpnConnection *i, const VpnConnection *j)
mvogt's avatar
mvogt committed
260
{
261 262 263
    return ((orderByConnected_ && (i->connected() > j->connected()))
            || ((!orderByConnected_ || (i->connected() == j->connected()))
                && (i->name().localeAwareCompare(j->name()) <= 0)));
mvogt's avatar
mvogt committed
264 265
}

266
void SettingsVpnModel::orderConnections(QVector<VpnConnection*> &connections)
267
{
268 269 270
    std::sort(connections.begin(), connections.end(), [this](const VpnConnection *i, const VpnConnection *j) -> bool {
        // Return true if i should appear before j in the list
        return compareConnections(i, j);
271
    });
272
}
273

274
void SettingsVpnModel::reorderConnection(VpnConnection * conn)
275 276
{
    const int itemCount(connections().size());
277

278 279 280 281 282 283 284 285 286
    if (itemCount > 1) {
        int index = 0;
        for ( ; index < itemCount; ++index) {
            const VpnConnection *existing = connections().at(index);
            // Scenario 1 orderByConnected == true: order first by connected, second by name
            // Scenario 2 orderByConnected == false: order only by name
            if (!compareConnections(existing, conn)) {
                break;
            }
287
        }
288 289 290
        const int currentIndex = connections().indexOf(conn);
        if (index != currentIndex && (index - 1) != currentIndex) {
            moveItem(currentIndex, (currentIndex < index ? (index - 1) : index));
291
        }
292
    }
293 294
}

295
void SettingsVpnModel::updatedConnectionPosition()
296
{
297 298
    VpnConnection *conn = qobject_cast<VpnConnection *>(sender());
    reorderConnection(conn);
299 300
}

301
void SettingsVpnModel::connectedChanged()
302
{
303
    VpnConnection *conn = qobject_cast<VpnConnection *>(sender());
304

305 306 307 308 309 310
    int row = connections().indexOf(conn);
    if (row >= 0) {
        QModelIndex index = createIndex(row, 0);;
        emit dataChanged(index, index);
    }
    reorderConnection(conn);
311 312
}

313
void SettingsVpnModel::connectionAdded(const QString &path)
314
{
315 316 317 318
    qCDebug(lcVpnLog) << "VPN connection added";
    if (VpnConnection *conn = vpnManager()->connection(path)) {
        bool credentialsExist = credentials_.credentialsExist(CredentialsRepository::locationForObjectPath(path));
        conn->setStoreCredentials(credentialsExist);
319

320 321 322
        connect(conn, &VpnConnection::nameChanged, this, &SettingsVpnModel::updatedConnectionPosition, Qt::UniqueConnection);
        connect(conn, &VpnConnection::connectedChanged, this, &SettingsVpnModel::connectedChanged, Qt::UniqueConnection);
        connect(conn, &VpnConnection::stateChanged, this, &SettingsVpnModel::stateChanged, Qt::UniqueConnection);
323 324 325
    }
}

326
void SettingsVpnModel::connectionRemoved(const QString &path)
327
{
328 329 330
    qCDebug(lcVpnLog) << "VPN connection removed";
    if (VpnConnection *conn = vpnManager()->connection(path)) {
        disconnect(conn, 0, this, 0);
331 332 333
    }
}

334
void SettingsVpnModel::connectionsRefreshed()
335 336 337
{
    qCDebug(lcVpnLog) << "VPN connections refreshed";
    QVector<VpnConnection*> connections = vpnManager()->connections();
338 339 340

    // Check to see if the best state has changed
    VpnConnection::ConnectionState maxState = VpnConnection::Idle;
341
    for (VpnConnection *conn : connections) {
342 343 344
        connect(conn, &VpnConnection::nameChanged, this, &SettingsVpnModel::updatedConnectionPosition, Qt::UniqueConnection);
        connect(conn, &VpnConnection::connectedChanged, this, &SettingsVpnModel::connectedChanged, Qt::UniqueConnection);
        connect(conn, &VpnConnection::stateChanged, this, &SettingsVpnModel::stateChanged, Qt::UniqueConnection);
345 346

        maxState = getMaxState(conn->state(), maxState);
347
    }
348 349

    updateBestState(maxState);
350 351
}

352
void SettingsVpnModel::stateChanged()
353
{
354 355
    // Emit the state changed signal needed for the VPN EnableSwitch
    VpnConnection *conn = qobject_cast<VpnConnection *>(sender());
356
    emit connectionStateChanged(conn->path(), conn->state());
357

358
    // Check to see if the best state has changed
359 360
    VpnConnection::ConnectionState maxState = getMaxState(conn->state(), VpnConnection::Idle);
    updateBestState(maxState);
361 362
}

363 364 365 366
// ==========================================================================
// Automatic domain allocation
// ==========================================================================

367
bool SettingsVpnModel::domainInUse(const QString &domain) const
368
{
369 370 371 372 373
    const int itemCount(count());
    for (int index = 0; index < itemCount; ++index) {
        const VpnConnection *connection = connections().at(index);
        if (connection->domain() == domain) {
            return true;
374 375
        }
    }
376 377
    return false;
}
378

379
QString SettingsVpnModel::createDefaultDomain() const
380 381 382 383 384 385
{
    QString newDomain = defaultDomain;
    int index = 1;
    while (domainInUse(newDomain)) {
        newDomain = defaultDomain + QString(".%1").arg(index);
        ++index;
386
    }
387
    return newDomain;
388 389
}

390
bool SettingsVpnModel::isDefaultDomain(const QString &domain)
391
{
392 393 394 395 396
    if (domain == legacyDefaultDomain)
        return true;

    static const QRegularExpression domainPattern(QStringLiteral("^%1(\\.\\d+)?$").arg(defaultDomain));
    return domainPattern.match(domain).hasMatch();
397 398
}

399 400 401 402
// ==========================================================================
// Credential storage
// ==========================================================================

403
QVariantMap SettingsVpnModel::connectionCredentials(const QString &path)
mvogt's avatar
mvogt committed
404 405 406
{
    QVariantMap rv;

407
    if (VpnConnection *conn = vpnManager()->connection(path)) {
mvogt's avatar
mvogt committed
408 409 410 411 412 413
        const QString location(CredentialsRepository::locationForObjectPath(path));
        const bool enabled(credentials_.credentialsExist(location));

        if (enabled) {
            rv = credentials_.credentials(location);
        } else {
414
            qWarning() << "VPN does not permit credentials storage:" << path;
mvogt's avatar
mvogt committed
415 416
        }

417
        conn->setStoreCredentials(enabled);
mvogt's avatar
mvogt committed
418
    } else {
419
        qWarning() << "Unable to return credentials for unknown VPN connection:" << path;
mvogt's avatar
mvogt committed
420 421 422 423 424
    }

    return rv;
}

425
void SettingsVpnModel::setConnectionCredentials(const QString &path, const QVariantMap &credentials)
mvogt's avatar
mvogt committed
426
{
427
    if (VpnConnection *conn = vpnManager()->connection(path)) {
mvogt's avatar
mvogt committed
428 429
        credentials_.storeCredentials(CredentialsRepository::locationForObjectPath(path), credentials);

430
        conn->setStoreCredentials(true);
mvogt's avatar
mvogt committed
431
    } else {
432
        qWarning() << "Unable to set credentials for unknown VPN connection:" << path;
mvogt's avatar
mvogt committed
433 434 435
    }
}

436
bool SettingsVpnModel::connectionCredentialsEnabled(const QString &path)
mvogt's avatar
mvogt committed
437
{
438
    if (VpnConnection *conn = vpnManager()->connection(path)) {
mvogt's avatar
mvogt committed
439 440 441
        const QString location(CredentialsRepository::locationForObjectPath(path));
        const bool enabled(credentials_.credentialsExist(location));

442
        conn->setStoreCredentials(enabled);
mvogt's avatar
mvogt committed
443 444
        return enabled;
    } else {
445
        qWarning() << "Unable to test credentials storage for unknown VPN connection:" << path;
mvogt's avatar
mvogt committed
446 447 448 449 450
    }

    return false;
}

451
void SettingsVpnModel::disableConnectionCredentials(const QString &path)
mvogt's avatar
mvogt committed
452
{
453
    if (VpnConnection *conn = vpnManager()->connection(path)) {
mvogt's avatar
mvogt committed
454 455 456 457 458
        const QString location(CredentialsRepository::locationForObjectPath(path));
        if (credentials_.credentialsExist(location)) {
            credentials_.removeCredentials(location);
        }

459
        conn->setStoreCredentials(false);
mvogt's avatar
mvogt committed
460
    } else {
461
        qWarning() << "Unable to set automatic connection for unknown VPN connection:" << path;
mvogt's avatar
mvogt committed
462 463 464
    }
}

465
QVariantMap SettingsVpnModel::connectionSettings(const QString &path)
466
{
467 468
    QVariantMap properties;
    if (VpnConnection *conn = vpnManager()->connection(path)) {
mvogt's avatar
mvogt committed
469 470
        // Check if the credentials storage has been changed
        const QString location(CredentialsRepository::locationForObjectPath(path));
471
        conn->setStoreCredentials(credentials_.credentialsExist(location));
mvogt's avatar
mvogt committed
472

473
        properties = VpnModel::connectionSettings(path);
474
    }
475
    return properties;
476 477
}

478 479 480
// ==========================================================================
// CredentialsRepository
// ==========================================================================
481

482
SettingsVpnModel::CredentialsRepository::CredentialsRepository(const QString &path)
483 484 485 486
    : baseDir_(path)
{
    if (!baseDir_.exists() && !baseDir_.mkpath(path)) {
        qWarning() << "Unable to create base directory for VPN credentials:" << path;
487 488 489
    }
}

490
QString SettingsVpnModel::CredentialsRepository::locationForObjectPath(const QString &path)
491
{
492 493 494 495
    int index = path.lastIndexOf(QChar('/'));
    if (index != -1) {
        return path.mid(index + 1);
    }
496

497 498
    return QString();
}
499

500
bool SettingsVpnModel::CredentialsRepository::credentialsExist(const QString &location) const
501 502 503
{
    // Test the FS, as another process may store/remove the credentials
    return baseDir_.exists(location);
504 505
}

506
bool SettingsVpnModel::CredentialsRepository::storeCredentials(const QString &location, const QVariantMap &credentials)
507
{
508 509 510 511 512 513 514 515
    QFile credentialsFile(baseDir_.absoluteFilePath(location));
    if (!credentialsFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        qWarning() << "Unable to write credentials file:" << credentialsFile.fileName();
        return false;
    } else {
        credentialsFile.write(encodeCredentials(credentials));
        credentialsFile.setPermissions(QFileDevice::ReadOwner | QFileDevice::WriteOwner | QFileDevice::ReadOther | QFileDevice::WriteOther);
        credentialsFile.close();
516 517
    }

518
    return true;
519 520
}

521
bool SettingsVpnModel::CredentialsRepository::removeCredentials(const QString &location)
522
{
523 524 525 526
    if (baseDir_.exists(location)) {
        if (!baseDir_.remove(location)) {
            qWarning() << "Unable to delete credentials file:" << location;
            return false;
527
        }
528
    }
529

530 531
    return true;
}
532

533
QVariantMap SettingsVpnModel::CredentialsRepository::credentials(const QString &location) const
534 535
{
    QVariantMap rv;
536

537 538 539 540 541 542
    QFile credentialsFile(baseDir_.absoluteFilePath(location));
    if (!credentialsFile.open(QIODevice::ReadOnly)) {
        qWarning() << "Unable to read credentials file:" << credentialsFile.fileName();
    } else {
        const QByteArray encoded = credentialsFile.readAll();
        credentialsFile.close();
543

544 545
        rv = decodeCredentials(encoded);
    }
546

547
    return rv;
548 549
}

550
QByteArray SettingsVpnModel::CredentialsRepository::encodeCredentials(const QVariantMap &credentials)
551
{
552 553
    // We can't store these values securely, but we may as well encode them to protect from grep, at least...
    QByteArray encoded;
554

555 556
    QDataStream os(&encoded, QIODevice::WriteOnly);
    os.setVersion(QDataStream::Qt_5_6);
557

558 559
    const quint32 version = 1u;
    os << version;
560

561 562
    const quint32 items = credentials.size();
    os << items;
563

564 565 566
    for (auto it = credentials.cbegin(), end = credentials.cend(); it != end; ++it) {
        os << it.key();
        os << it.value().toString();
567 568
    }

569 570
    return encoded.toBase64();
}
571

572
QVariantMap SettingsVpnModel::CredentialsRepository::decodeCredentials(const QByteArray &encoded)
573 574
{
    QVariantMap rv;
575

576
    QByteArray decoded(QByteArray::fromBase64(encoded));
577

578 579
    QDataStream is(decoded);
    is.setVersion(QDataStream::Qt_5_6);
580

581 582
    quint32 version;
    is >> version;
583

584 585 586 587 588
    if (version != 1u) {
        qWarning() << "Invalid version for stored credentials:" << version;
    } else {
        quint32 items;
        is >> items;
589

590 591 592 593 594 595
        for (quint32 i = 0; i < items; ++i) {
            QString key, value;
            is >> key;
            is >> value;
            rv.insert(key, QVariant::fromValue(value));
        }
596 597
    }

598
    return rv;
599 600
}

601 602 603 604
// ==========================================================================
// Provisioning files
// ==========================================================================

605
QVariantMap SettingsVpnModel::processProvisioningFile(const QString &path, const QString &type)
606
{
607
    QVariantMap rv;
608

609 610
    QFile provisioningFile(path);
    if (provisioningFile.open(QIODevice::ReadOnly)) {
611
        if (type == QStringLiteral("openvpn")) {
612
            rv = processOpenVpnProvisioningFile(provisioningFile);
613 614
        } else if (type == QStringLiteral("openconnect")) {
            rv = processOpenconnectProvisioningFile(provisioningFile);
615 616
        } else if (type == QStringLiteral("openfortivpn")) {
            rv = processOpenfortivpnProvisioningFile(provisioningFile);
617 618
        } else if (type == QStringLiteral("vpnc")) {
            rv = processVpncProvisioningFile(provisioningFile);
619 620 621 622 623 624 625 626
        } else if (type == QStringLiteral("l2tp")) {
            if (path.endsWith(QStringLiteral(".pbk"))) {
                rv = processPbkProvisioningFile(provisioningFile, type);
            } else {
                rv = processL2tpProvisioningFile(provisioningFile);
            }
        } else if (type == QStringLiteral("pptp")) {
            rv = processPbkProvisioningFile(provisioningFile, type);
627 628
        } else {
            qWarning() << "Provisioning not currently supported for VPN type:" << type;
629
        }
630 631
    } else {
        qWarning() << "Unable to open provisioning file:" << path;
632
    }
633 634

    return rv;
635 636
}

637
QVariantMap SettingsVpnModel::processOpenVpnProvisioningFile(QFile &provisioningFile)
638 639 640 641 642 643 644 645 646 647 648 649
{
    QVariantMap rv;

    QString embeddedMarker;
    QString embeddedContent;
    QStringList extraOptions;

    const QRegularExpression commentLeader(QStringLiteral("^\\s*(?:\\#|\\;)"));
    const QRegularExpression embeddedLeader(QStringLiteral("^\\s*<([^\\/>]+)>"));
    const QRegularExpression embeddedTrailer(QStringLiteral("^\\s*<\\/([^\\/>]+)>"));
    const QRegularExpression whitespace(QStringLiteral("\\s"));

650 651 652 653 654 655 656 657
    auto normaliseProtocol = [](const QString &proto) {
        if (proto == QStringLiteral("tcp")) {
            // 'tcp' is an undocumented option, which is interpreted by openvpn as 'tcp-client'
            return QStringLiteral("tcp-client");
        }
        return proto;
    };

658 659 660 661 662 663 664 665 666 667
    QTextStream is(&provisioningFile);
    while (!is.atEnd()) {
        QString line(is.readLine());

        QRegularExpressionMatch match;
        if (line.contains(commentLeader)) {
            // Skip
        } else if (line.contains(embeddedLeader, &match)) {
            embeddedMarker = match.captured(1);
            if (embeddedMarker.isEmpty()) {
668
                qWarning() << "Invalid embedded content";
669 670 671 672
            }
        } else if (line.contains(embeddedTrailer, &match)) {
            const QString marker = match.captured(1);
            if (marker != embeddedMarker) {
673
                qWarning() << "Invalid embedded content:" << marker << "!=" << embeddedMarker;
674 675
            } else {
                if (embeddedContent.isEmpty()) {
676
                    qWarning() << "Ignoring empty embedded content:" << embeddedMarker;
677 678 679 680 681 682
                } else {
                    if (embeddedMarker == QStringLiteral("connection")) {
                        // Special case: not embedded content, but a <connection> structure - pass through as an extra option
                        extraOptions.append(QStringLiteral("<connection>\n") + embeddedContent + QStringLiteral("</connection>"));
                    } else {
                        // Embedded content
683 684
                        QDir outputDir(provisioningOutputPath_);
                        if (!outputDir.exists() && !outputDir.mkpath(provisioningOutputPath_)) {
685
                            qWarning() << "Unable to create base directory for VPN provisioning content:" << provisioningOutputPath_;
686 687 688 689 690 691 692 693
                        } else {
                            // Name the file according to content
                            QCryptographicHash hash(QCryptographicHash::Sha1);
                            hash.addData(embeddedContent.toUtf8());

                            const QString outputFileName(QString(hash.result().toHex()) + QChar('.') + embeddedMarker);
                            QFile outputFile(outputDir.absoluteFilePath(outputFileName));
                            if (!outputFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
694
                                qWarning() << "Unable to write VPN provisioning content file:" << outputFile.fileName();
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
                            } else {
                                QTextStream os(&outputFile);
                                os << embeddedContent;

                                // Add the file to the configuration
                                if (embeddedMarker == QStringLiteral("ca")) {
                                    rv.insert(QStringLiteral("OpenVPN.CACert"), outputFile.fileName());
                                } else if (embeddedMarker == QStringLiteral("cert")) {
                                    rv.insert(QStringLiteral("OpenVPN.Cert"), outputFile.fileName());
                                } else if (embeddedMarker == QStringLiteral("key")) {
                                    rv.insert(QStringLiteral("OpenVPN.Key"), outputFile.fileName());
                                } else {
                                    // Assume that the marker corresponds to the openvpn option, (such as 'tls-auth')
                                    extraOptions.append(embeddedMarker + QChar(' ') + outputFile.fileName());
                                }
                            }
                        }
                    }
                }
            }
            embeddedMarker.clear();
            embeddedContent.clear();
        } else if (!embeddedMarker.isEmpty()) {
            embeddedContent.append(line + QStringLiteral("\n"));
        } else {
            QStringList tokens(line.split(whitespace, QString::SkipEmptyParts));
            if (!tokens.isEmpty()) {
                // Find directives that become part of the connman configuration
                const QString& directive(tokens.front());
                const QStringList arguments(tokens.count() > 1 ? tokens.mid(1) : QStringList());

                if (directive == QStringLiteral("remote")) {
                    // Connman supports a single remote host - if we get further instances, pass them through the config file
                    if (!rv.contains(QStringLiteral("Host"))) {
                        if (arguments.count() > 0) {
                            rv.insert(QStringLiteral("Host"), arguments.at(0));
                        }
                        if (arguments.count() > 1) {
                            rv.insert(QStringLiteral("OpenVPN.Port"), arguments.at(1));
                        }
                        if (arguments.count() > 2) {
736
                            rv.insert(QStringLiteral("OpenVPN.Proto"), normaliseProtocol(arguments.at(2)));
737 738 739 740 741 742 743 744 745 746
                        }
                    } else {
                        extraOptions.append(line);
                    }
                } else if (directive == QStringLiteral("ca") ||
                           directive == QStringLiteral("cert") ||
                           directive == QStringLiteral("key") ||
                           directive == QStringLiteral("auth-user-pass")) {
                    if (!arguments.isEmpty()) {
                        // If these file paths are not absolute, assume they are in the same directory as the provisioning file
747
                        QString file(arguments.at(0));
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
                        if (!file.startsWith(QChar('/'))) {
                            const QFileInfo info(provisioningFile.fileName());
                            file = info.dir().absoluteFilePath(file);
                        }
                        if (directive == QStringLiteral("ca")) {
                            rv.insert(QStringLiteral("OpenVPN.CACert"), file);
                        } else if (directive == QStringLiteral("cert")) {
                            rv.insert(QStringLiteral("OpenVPN.Cert"), file);
                        } else if (directive == QStringLiteral("key")) {
                            rv.insert(QStringLiteral("OpenVPN.Key"), file);
                        } else if (directive == QStringLiteral("auth-user-pass")) {
                            rv.insert(QStringLiteral("OpenVPN.AuthUserPass"), file);
                        }
                    } else if (directive == QStringLiteral("auth-user-pass")) {
                        // Preserve this option to mean ask for credentials
                        rv.insert(QStringLiteral("OpenVPN.AuthUserPass"), QStringLiteral("-"));
                    }
                } else if (directive == QStringLiteral("mtu") ||
                           directive == QStringLiteral("tun-mtu")) {
                    // Connman appears to use a long obsolete form of this option...
                    if (!arguments.isEmpty()) {
                        rv.insert(QStringLiteral("OpenVPN.MTU"), arguments.join(QChar(' ')));
                    }
                } else if (directive == QStringLiteral("ns-cert-type")) {
                    if (!arguments.isEmpty()) {
                        rv.insert(QStringLiteral("OpenVPN.NSCertType"), arguments.join(QChar(' ')));
                    }
                } else if (directive == QStringLiteral("proto")) {
                    if (!arguments.isEmpty()) {
                        // All values from a 'remote' directive to take precedence
                        if (!rv.contains(QStringLiteral("OpenVPN.Proto"))) {
779
                            rv.insert(QStringLiteral("OpenVPN.Proto"), normaliseProtocol(arguments.join(QChar(' '))));
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
                        }
                    }
                } else if (directive == QStringLiteral("port")) {
                    // All values from a 'remote' directive to take precedence
                    if (!rv.contains(QStringLiteral("OpenVPN.Port"))) {
                        if (!arguments.isEmpty()) {
                            rv.insert(QStringLiteral("OpenVPN.Port"), arguments.join(QChar(' ')));
                        }
                    }
                } else if (directive == QStringLiteral("askpass")) {
                    if (!arguments.isEmpty()) {
                        rv.insert(QStringLiteral("OpenVPN.AskPass"), arguments.join(QChar(' ')));
                    } else {
                        rv.insert(QStringLiteral("OpenVPN.AskPass"), QString());
                    }
                } else if (directive == QStringLiteral("auth-nocache")) {
                    rv.insert(QStringLiteral("OpenVPN.AuthNoCache"), QStringLiteral("true"));
                } else if (directive == QStringLiteral("tls-remote")) {
                    if (!arguments.isEmpty()) {
                        rv.insert(QStringLiteral("OpenVPN.TLSRemote"), arguments.join(QChar(' ')));
                    }
                } else if (directive == QStringLiteral("cipher")) {
                    if (!arguments.isEmpty()) {
                        rv.insert(QStringLiteral("OpenVPN.Cipher"), arguments.join(QChar(' ')));
                    }
                } else if (directive == QStringLiteral("auth")) {
                    if (!arguments.isEmpty()) {
                        rv.insert(QStringLiteral("OpenVPN.Auth"), arguments.join(QChar(' ')));
                    }
                } else if (directive == QStringLiteral("comp-lzo")) {
                    if (!arguments.isEmpty()) {
                        rv.insert(QStringLiteral("OpenVPN.CompLZO"), arguments.join(QChar(' ')));
                    } else {
                        rv.insert(QStringLiteral("OpenVPN.CompLZO"), QStringLiteral("adaptive"));
                    }
                } else if (directive == QStringLiteral("remote-cert-tls")) {
                    if (!arguments.isEmpty()) {
                        rv.insert(QStringLiteral("OpenVPN.RemoteCertTls"), arguments.join(QChar(' ')));
                    }
819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
                } else if (directive == QStringLiteral("ping")) {
                    if (!arguments.isEmpty()) {
                        rv.insert(QStringLiteral("OpenVPN.Ping"), arguments.join(QChar(' ')));
                    }
                } else if (directive == QStringLiteral("ping-exit")) {
                    if (!arguments.isEmpty()) {
                        rv.insert(QStringLiteral("OpenVPN.PingExit"), arguments.join(QChar(' ')));
                    }
                } else if (directive == QStringLiteral("remap-usr1")) {
                     if (!arguments.isEmpty()) {
                        rv.insert(QStringLiteral("OpenVPN.RemapUsr1"), arguments.join(QChar(' ')));
                     }
                } else if (directive == QStringLiteral("ping-restart")) {
                    // Ignore, must not be set with ConnMan
                    qInfo() << "Ignoring ping-restart with OpenVPN";
                } else if (directive == QStringLiteral("connect-retry-max")) {
                    // Ignore, must not be set with ConnMan
                    qInfo() << "Ignoring connect-retry-max with OpenVPN";
837
                } else {
838
                    // A directive that ConnMan does not care about - pass through to the config file
839 840 841 842 843 844 845 846
                    extraOptions.append(line);
                }
            }
        }
    }

    if (!extraOptions.isEmpty()) {
        // Write a config file to contain the extra options
847 848
        QDir outputDir(provisioningOutputPath_);
        if (!outputDir.exists() && !outputDir.mkpath(provisioningOutputPath_)) {
849
            qWarning() << "Unable to create base directory for VPN provisioning content:" << provisioningOutputPath_;
850 851 852 853 854 855 856 857 858 859
        } else {
            // Name the file according to content
            QCryptographicHash hash(QCryptographicHash::Sha1);
            foreach (const QString &line, extraOptions) {
                hash.addData(line.toUtf8());
            }

            const QString outputFileName(QString(hash.result().toHex()) + QStringLiteral(".conf"));
            QFile outputFile(outputDir.absoluteFilePath(outputFileName));
            if (!outputFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
860
                qWarning() << "Unable to write VPN provisioning configuration file:" << outputFile.fileName();
861 862 863 864 865 866 867 868 869 870 871 872 873
            } else {
                QTextStream os(&outputFile);
                foreach (const QString &line, extraOptions) {
                    os << line << endl;
                }

                rv.insert(QStringLiteral("OpenVPN.ConfigFile"), outputFile.fileName());
            }
        }
    }

    return rv;
}
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
QVariantMap SettingsVpnModel::processVpncProvisioningFile(QFile &provisioningFile)
{
    QVariantMap rv;

    QTextStream is(&provisioningFile);
#define ENTRY(x, y, z) { QStringLiteral(x), QStringLiteral(y), z }
    static const struct {
        QString key;
        QString targetProperty;
        bool hasValue;
    } options[] = {
        ENTRY("IPSec gateway", "Host", true),
        ENTRY("IPSec ID", "VPNC.IPSec.ID", true),
        ENTRY("Domain", "VPNC.Domain", true),
        ENTRY("Vendor", "VPNC.Vendor", true),
        ENTRY("IKE DH Group", "VPNC.IKE.DHGroup", true),
        ENTRY("Perfect Forward Secrecy", "VPNC.PFS", true),
        ENTRY("NAT Traversal Mode", "VPNC.NATTMode", true),
        ENTRY("Enable Single DES", "VPNC.SingleDES", false),
        ENTRY("Enable no encryption", "VPNC.NoEncryption", false),
        ENTRY("Application version", "VPNC.AppVersion", true),
        ENTRY("Local Port", "VPNC.LocalPort", true),
        ENTRY("Cisco UDP Encapsulation Port", "VPNC.CiscoPort", true),
        ENTRY("DPD idle timeout (our side)", "VPNC.DPDTimeout", true),
        ENTRY("IKE Authmode", "VPNC.IKE.AuthMode", true),
        /* Unhandled config options
        ENTRY("IPSec secret", "VPNC.IPSec.Secret", true),
        ENTRY("IPSec obfuscated secret", "?", true),
        ENTRY("Xauth username", "VPNC.XAuth.Username", true),
        ENTRY("Xauth password", "VPNC.XAuth.Password", true),
        ENTRY("Xauth obfuscated password", "?", true),
        ENTRY("Xauth interactive", "?", false),
        ENTRY("Script", "?", true),
        ENTRY("Interface name", "?", true),
        ENTRY("Interface mode", "?", true),
        ENTRY("Interface MTU", "?", true),
        ENTRY("Debug", "?", true),
        ENTRY("No Detach", "?", false),
        ENTRY("Pidfile", "?", true),
        ENTRY("Local Addr", "?", true),
        ENTRY("Noninteractive", "?", false),
        ENTRY("CA-File", "?", true),
        ENTRY("CA-Dir", "?", true),
        ENTRY("IPSEC target network", "?", true),
        ENTRY("Password helper", "?", true),
        */
    };
#undef ENTRY
    while (!is.atEnd()) {
        QString line(is.readLine());

        for (size_t i = 0; i < sizeof(options) / sizeof(*options); i++) {
            if (!line.startsWith(options[i].key, Qt::CaseInsensitive)) {
                continue;
            }
            if (!options[i].hasValue) {
                rv[options[i].targetProperty] = true;
            } else {
                int pos = options[i].key.length();
                if (line.length() == pos
                    || (line[pos] != ' '
                        && line[pos] != '\t')) {
                    continue;
                }
                rv[options[i].targetProperty] = line.mid(pos + 1);
            }
        }
    }

    if (rv.contains("VPNC.IPSec.ID")) {
        if (rv.contains("Host")) {
            rv["Name"] = QStringLiteral("%1 %2").arg(rv["Host"].value<QString>()).arg(rv["VPNC.IPSec.ID"].value<QString>());
        } else {
            rv["Name"] = rv["VPNC.IPSec.ID"];
        }
    } else {
        rv["Name"] = QFileInfo(provisioningFile).baseName();
    }

    return rv;
}

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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
QVariantMap SettingsVpnModel::processOpenconnectProvisioningFile(QFile &provisioningFile)
{
    char first;
    QVariantMap rv;

    if (provisioningFile.peek(&first, 1) != 1) {
        return QVariantMap();
    }

    if (first == '<') {
#define NS "declare default element namespace \"http://schemas.xmlsoap.org/encoding/\"; "
        QXmlQuery query;
        QXmlResultItems entries;

        if (!query.setFocus(&provisioningFile)) {
            qWarning() << "Unable to read provisioning configuration file";
            return QVariantMap();
        }

        query.setQuery(QStringLiteral(NS "/AnyConnectProfile/ServerList/HostEntry"));
        query.evaluateTo(&entries);
        if (!query.isValid()) {
            qWarning() << "Unable to query provisioning configuration file";
            return QVariantMap();
        }

        for (QXmlItem entry = entries.next(); !entry.isNull(); entry = entries.next()) {
            QXmlQuery subQuery(query.namePool());
            QStringList name;
            QStringList address;
            QStringList userGroup;
            subQuery.setFocus(entry);
            subQuery.setQuery(QStringLiteral(NS "normalize-space(HostName[1]/text())"));
            subQuery.evaluateTo(&name);
            subQuery.setQuery(QStringLiteral(NS "normalize-space(HostAddress[1]/text())"));
            subQuery.evaluateTo(&address);
            subQuery.setQuery(QStringLiteral(NS "normalize-space(UserGroup[1]/text())"));
            subQuery.evaluateTo(&userGroup);

            if (!name[0].isEmpty()) {
                rv.insert(QStringLiteral("Name"), name[0]);
            }

            if (!address[0].isEmpty()) {
                rv.insert(QStringLiteral("Host"), address[0]);
            }

            if (!userGroup[0].isEmpty()) {
                rv.insert(QStringLiteral("OpenConnect.Usergroup"), userGroup[0]);
            }
        }
    } else {
        struct ArgMapping {
            bool hasArgument;
            QString targetProperty;
        };
#define ENTRY(x, y, z) { QStringLiteral(x), { y, QStringLiteral(z) }}
        static const QHash<QString, ArgMapping> fields {
            ENTRY("user", true, "OpenConnect.Username"),
            ENTRY("certificate", true, "OpenConnect.ClientCert"),
            ENTRY("sslkey", true, "OpenConnect.UserPrivateKey"),
            ENTRY("key-password", true, "OpenConnect.PKCSPassword"),
            ENTRY("cookie", true, "OpenConnect.Cookie"),
            ENTRY("cafile", true, "OpenConnect.CACert"),
            ENTRY("disable-ipv6", false, "OpenConnect.DisableIPv6"),
            ENTRY("protocol", true, "OpenConnect.Protocol"),
            ENTRY("no-http-keepalive", false, "OpenConnect.NoHTTPKeepalive"),
            ENTRY("servercert", true, "OpenConnect.ServerCert"),
            ENTRY("usergroup", true, "OpenConnect.Usergroup"),
            ENTRY("base-mtu", true, "OpenConnect.MTU"),
        };
#undef ENTRY
        QTextStream is(&provisioningFile);

        const QRegularExpression commentLine(QStringLiteral("^\\s*(?:\\#|$)"));
        const QRegularExpression record(QStringLiteral("^\\s*([^ \\t=]+)\\s*(?:=\\s*|)(.*?)$"));

        while (!is.atEnd()) {
            QString line(is.readLine());

            if (line.contains(commentLine)) {
                continue;
            }

            QRegularExpressionMatch match = record.match(line);

            if (!match.hasMatch()) {
                continue;
            }

            QString field = match.captured(1);
            auto i = fields.find(field);

            if (i != fields.end()) {
                if (i.value().hasArgument) {
                    if (!match.captured(2).isEmpty()) {
                        rv[i.value().targetProperty] = match.captured(2);
                    }
                } else {
                    rv[i.value().targetProperty] = true;
                }
            }
        }

        if (rv.contains(QStringLiteral("OpenConnect.UserPrivateKey"))) {
            rv[QStringLiteral("OpenConnect.AuthType")] = QStringLiteral("publickey");
        } else if (rv.contains(QStringLiteral("OpenConnect.ClientCert"))) {
            rv[QStringLiteral("OpenConnect.PKCSClientCert")] = rv[QStringLiteral("OpenConnect.ClientCert")];
            rv.remove(QStringLiteral("OpenConnect.ClientCert"));
            rv[QStringLiteral("OpenConnect.AuthType")] = QStringLiteral("pkcs");
        } else if (rv.contains(QStringLiteral("OpenConnect.Username"))) {
            if (rv.contains(QStringLiteral("OpenConnect.Cookie"))) {
                rv[QStringLiteral("OpenConnect.AuthType")] = QStringLiteral("cookie_with_userpass");
            } else {
                rv[QStringLiteral("OpenConnect.AuthType")] = QStringLiteral("userpass");
            }
        } else if (rv.contains(QStringLiteral("OpenConnect.Cookie"))) {
            rv[QStringLiteral("OpenConnect.AuthType")] = QStringLiteral("cookie");
        }

Santtu Lakkala's avatar
Santtu Lakkala committed
1077
        if (!rv.isEmpty()) {
1078 1079 1080 1081 1082
            // The config file does not have server name, guess file name instead
            QString fileName = provisioningFile.fileName();
            int slashPos = fileName.lastIndexOf('/');
            int dotPos = fileName.lastIndexOf('.');
            rv[QStringLiteral("Host")] = fileName.mid(slashPos + 1, dotPos - slashPos - 1);
Santtu Lakkala's avatar
Santtu Lakkala committed
1083
        }
1084 1085 1086 1087 1088 1089
    }

    return rv;
#undef NS
}

1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
QVariantMap SettingsVpnModel::processOpenfortivpnProvisioningFile(QFile &provisioningFile)
{
    char first;
    QVariantMap rv;
    QStringList option;

    if (provisioningFile.peek(&first, 1) != 1) {
        return QVariantMap();
    }

    if (first == '<') {
        QXmlQuery query;
        QXmlResultItems entries;

        if (!query.setFocus(&provisioningFile)) {
            qWarning() << "Unable to read provisioning configuration file";
            return QVariantMap();
        }

        query.setQuery(QStringLiteral("/forticlient_configuration/vpn/sslvpn/connections/connection"));
        query.evaluateTo(&entries);
        if (!query.isValid()) {
            qWarning() << "Unable to query provisioning configuration file";
            return QVariantMap();
        }

        for (QXmlItem entry = entries.next(); !entry.isNull(); entry = entries.next()) {
            QXmlQuery subQuery(query.namePool());
            QStringList name;
            QStringList address;
            QStringList userGroup;
            subQuery.setFocus(entry);

            // Other fields that might be of interest
            // username
            // password
            // warn_invalid_server_certificate
            subQuery.setQuery(QStringLiteral("normalize-space(name[1]/text())"));
            subQuery.evaluateTo(&name);
            subQuery.setQuery(QStringLiteral("normalize-space(server[1]/text())"));
            subQuery.evaluateTo(&address);

            if (!name[0].isEmpty()) {
                rv.insert(QStringLiteral("Name"), name[0]);
            }

            if (!address[0].isEmpty()) {
                int pos = address[0].indexOf(':');
                if (pos == -1) {
                    rv.insert(QStringLiteral("Host"), address[0]);
                } else {
                    rv.insert(QStringLiteral("Host"), address[0].left(pos));
                    rv.insert(QStringLiteral("openfortivpn.Port"), address[0].midRef(pos + 1).toInt());
                }

                // We have a connection address, ignore the rest.
                break;
            }
        }

        // There's also other boolean (1/0) options under sslvpn/options:
        // preferred_dtls_tunnel
        // no_dhcp_server_route
        // keep_connection_alive
        query.setQuery(QStringLiteral("normalize-space(/forticlient_configuration/vpn/sslvpn/options/disallow_invalid_server_certificate/text())"));
        query.evaluateTo(&option);
        if (option[0] == QLatin1String("0")) {
            rv.insert(QStringLiteral("openfortivpn.AllowSelfSignedCert"), QStringLiteral("true"));
        }

    } else {
        QTextStream is(&provisioningFile);

        const QRegularExpression commentLine(QStringLiteral("^\\#"));
        const QRegularExpression record(QStringLiteral("^\\s*([^=]+)\\s*=\\s*(.*?)\\s*$"));
#define ENTRY(x, y) { QStringLiteral(x), QStringLiteral(y) }
        const QHash<QString, QString> fields {
            ENTRY("host", "Host"),
            ENTRY("port", "openfortivpn.Port"),
            ENTRY("trusted-cert", "openfortivpn.TrustedCert"),
            // possibly useful fields for the future, not supported by connman plugin
            // ENTRY("username", "?"),
            // ENTRY("password", "?"),
            // ENTRY("no-ftm-push", "?"),
            // ENTRY("realm", "?"),
            // ENTRY("ca-file", "?"),
            // ENTRY("user-cert", "?"),
            // ENTRY("user-key", "?"),
            // ENTRY("insercure-ssl", "?"),
            // ENTRY("cipher-list", "?"),
            // ENTRY("user-agent", "?"),
            // ENTRY("hostcheck", "?"),
        };
#undef ENTRY

        while (!is.atEnd()) {
            QString line(is.readLine());

            if (line.contains(commentLine)) {
                continue;
            }

            QRegularExpressionMatch match = record.match(line);

            if (!match.hasMatch()) {
                continue;
            }

            QString field = match.captured(1);
            auto i = fields.find(field);

            if (i != fields.end()) {
                rv[i.value()] = match.captured(2);
            }
        }
    }

    return rv;
}

1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
bool SettingsVpnModel::processPppdProvisioningFile(QFile &provisioningFile, QVariantMap &result)
{
#define ENTRY(x, y) { QStringLiteral(x), QStringLiteral(y) }
    const QHash<QString, QString> stringOpts {
        ENTRY("lcp-echo-failure", "PPPD.EchoFailure"),
        ENTRY("lcp-echo-interval", "PPPD.EchoInterval"),
    };

    const QHash<QString, QString> boolOpts {
        ENTRY("debug", "PPPD.Debug"),
        ENTRY("refuse-eap", "PPPD.RefuseEAP"),
        ENTRY("refuse-pap", "PPPD.RefusePAP"),
        ENTRY("refuse-chap", "PPPD.RefuseCHAP"),
        ENTRY("refuse-mschap", "PPPD.RefuseMSCHAP"),
        ENTRY("refuse-mschapv2", "PPPD.RefuseMSCHAP2"),
        ENTRY("nobsdcomp", "PPPD.NoBSDComp"),
        ENTRY("nopcomp", "PPPD.NoPcomp"),
        ENTRY("noaccomp", "PPPD.UseAccomp"),
        ENTRY("nodeflate", "PPPD.NoDeflate"),
        ENTRY("require-mppe", "PPPD.ReqMPPE"),
        ENTRY("require-mppe-40", "PPPD.ReqMPPE40"),
        ENTRY("require-mppe-128", "PPPD.ReqMPPE128"),
        ENTRY("mppe-stateful", "PPPD.ReqMPPEStateful"),
        ENTRY("novj", "PPPD.NoVJ"),
    };
#undef ENTRY

    QTextStream is(&provisioningFile);
    const QRegularExpression nonCommentRe(R"!((?:[^#]|[^\]|"[^"*]"|'[^']*')*)!");
    const QRegularExpression keyValueRe(R"!(^([^\s]*)\s+(?:"([^"]*)"|'([^']*)'|([^\s"']*))$)!");

    while (!is.atEnd()) {
        QString line(is.readLine());
        QString trimmed = nonCommentRe.match(line).captured(0).trimmed();

        if (trimmed.isEmpty()) {
            continue;
        }

        if (boolOpts.contains(trimmed)) {
            result[boolOpts[trimmed]] = true;
        } else {
            QRegularExpressionMatch match = keyValueRe.match(trimmed);

            if (match.isValid()) {
                QString key = match.captured(1);

                if (stringOpts.contains(key)) {
                    result[stringOpts[key]] = match.captured(2) + match.captured(3) + match.captured(4);
                }
            }
        }
    }

    return true;
}

QVariantMap SettingsVpnModel::processL2tpProvisioningFile(QFile &provisioningFile)
{
    QString provisioningFileName = provisioningFile.fileName();
    QSettings settings(provisioningFileName, QSettings::IniFormat);
    QStringList groups = settings.childGroups();
    QVariantMap rv;

#define ENTRY(x, y) { QStringLiteral(x), QStringLiteral(y) }
    const QHash<QString, QString> globalOptions {
        ENTRY("access control", "L2TP.AccessControl"),
        ENTRY("auth file", "L2TP.AuthFile"),
        ENTRY("force userspace", "L2TP.ForceUserSpace"),
        ENTRY("listen-addr", "L2TP.ListenAddr"),
        ENTRY("rand source", "L2TP.Rand Source"),
        ENTRY("ipsec saref", "L2TP.IPsecSaref"),
        ENTRY("port", "L2TP.Port"),
    };

    const QHash<QString, QString> lacOptions {
        ENTRY("lns", "Host"),
        ENTRY("bps", "L2TP.BPS"),
        ENTRY("tx bps", "L2TP.TXBPS"),
        ENTRY("rx bps", "L2TP.RXBPS"),
        ENTRY("length bit", "L2TP.LengthBit"),
        ENTRY("challenge", "L2TP.Challenge"),
        ENTRY("defaultroute", "L2TP.DefaultRoute"),
        ENTRY("flow bit", "L2TP.FlowBit"),
        ENTRY("tunnel rws", "L2TP.TunnelRWS"),
        ENTRY("autodial", "L2TP.Autodial"),
        ENTRY("redial", "L2TP.Redial"),
        ENTRY("redial timeout", "L2TP.RedialTimeout"),
        ENTRY("max redials", "L2TP.MaxRedials"),
        ENTRY("require pap", "L2TP.RequirePAP"),
        ENTRY("require chap", "L2TP.RequireCHAP"),
        ENTRY("require authentication", "L2TP.ReqAuth"),
        ENTRY("pppoptfile", "__PPP_FILE"),
    };
#undef ENTRY

    settings.beginGroup(QStringLiteral("global"));
    for (const auto &key : settings.allKeys()) {
        if (globalOptions.contains(key)) {
            rv[globalOptions[key]] = settings.value(key);
        }
    }
    settings.endGroup();

    if (groups.contains(QStringLiteral("lac default"))) {
        settings.beginGroup(QStringLiteral("lac default"));
        for (const auto &key : settings.allKeys()) {
            if (lacOptions.contains(key)) {
                rv[lacOptions[key]] = settings.value(key);
            }
        }
        settings.endGroup();
    }

    for (const auto &group : groups) {
        if (group.startsWith(QLatin1String("lac ")) && group != QLatin1String("lac default")) {
            rv[QStringLiteral("Name")] = group.mid(4);
            settings.beginGroup(group);
            for (const auto &key : settings.allKeys()) {
                if (lacOptions.contains(key)) {
                    rv[lacOptions[key]] = settings.value(key);
                }
            }
            settings.endGroup();

            break;
        }
    }

    if (rv.contains(QStringLiteral("__PPP_FILE"))) {
        QFileInfo pppFileInfo(rv[QStringLiteral("__PPP_FILE")].toString());
        QString pppFileName = QFileInfo(provisioningFileName).dir().filePath(pppFileInfo.fileName());
        QFile pppFile(pppFileName);
        if (pppFile.open(QIODevice::ReadOnly)) {
            processPppdProvisioningFile(pppFile, rv);

            pppFile.close();
        }
        rv.remove(QStringLiteral("__PPP_FILE"));
    }

    return rv;
}

QVariantMap SettingsVpnModel::processPbkProvisioningFile(QFile &provisioningFile, const QString type)
{
    QString provisioningFileName = provisioningFile.fileName();
    QSettings settings(provisioningFileName, QSettings::IniFormat);
    QStringList groups = settings.childGroups();
    QVariantMap rv;

    QString expectedVpnStrategy;

    if (type == QLatin1String("l2tp")) {
        expectedVpnStrategy = QStringLiteral("3"); // L2TP only
    } else if (type == QLatin1String("pptp")) {
        expectedVpnStrategy = QStringLiteral("1"); // PPTP only
    } // 2 would be "try PPTP, then L2TP"

    const QString expectedType = QStringLiteral("2");  // VPN
    const QString expectedDEVICE = QStringLiteral("vpn");

    for (const auto &group : groups) {
        settings.beginGroup(group);

        if (settings.value(QStringLiteral("Type")).toString() == expectedType
            && settings.value(QStringLiteral("DEVICE")).toString() == expectedDEVICE
            && settings.value(QStringLiteral("VpnStrategy")).toString() == expectedVpnStrategy) {
            rv["Host"] = settings.value(QStringLiteral("PhoneNumber"));
            rv["Name"] = group;
            break;
        }

        settings.endGroup();
    }

    return rv;
}

1389 1390 1391 1392 1393 1394 1395
void SettingsVpnModel::updateBestState(VpnConnection::ConnectionState maxState)
{
    if (bestState_ != maxState) {
        bestState_ = maxState;
        emit bestStateChanged();
    }
}