summaryrefslogtreecommitdiffstats
path: root/src/tools/packager/packagingjob.cpp
blob: b2295d4473053632ce7c76006a3a3d11c3b876dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/****************************************************************************
**
** Copyright (C) 2019 Luxoft Sweden AB
** Copyright (C) 2018 Pelagicore AG
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Luxoft Application Manager.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT-QTAS$
** Commercial License Usage
** Licensees holding valid commercial Qt Automotive Suite licenses may use
** this file in accordance with the commercial license agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and The Qt Company.  For
** licensing terms and conditions see https://www.qt.io/terms-conditions.
** For further information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QFile>
#include <QFileInfo>
#include <QUrl>
#include <QRegExp>
#include <QDirIterator>
#include <QMessageAuthenticationCode>
#include <QJsonDocument>
#include <QTemporaryDir>

#include <stdio.h>
#include <stdlib.h>

#include "exception.h"
#include "signature.h"
#include "qtyaml.h"
#include "applicationinfo.h"
#include "installationreport.h"
#include "yamlapplicationscanner.h"
#include "packageextractor.h"
#include "packagecreator.h"

#include "packagingjob.h"

QT_USE_NAMESPACE_AM

// this corresponds to the -b parameter for mkfs.ext2 in sudo.cpp
static const int Ext2BlockSize = 1024;


PackagingJob *PackagingJob::create(const QString &destinationName, const QString &sourceDir,
                                   const QVariantMap &extraMetaData,
                                   const QVariantMap &extraSignedMetaData, bool asJson)
{
    PackagingJob *p = new PackagingJob();
    p->m_mode = Create;
    p->m_asJson = asJson;
    p->m_destinationName = destinationName;
    p->m_sourceDir = sourceDir;
    p->m_extraMetaData = extraMetaData;
    p->m_extraSignedMetaData = extraSignedMetaData;
    return p;
}

PackagingJob *PackagingJob::developerSign(const QString &sourceName, const QString &destinationName,
                                  const QString &certificateFile, const QString &passPhrase,
                                  bool asJson)
{
    PackagingJob *p = new PackagingJob();
    p->m_mode = DeveloperSign;
    p->m_asJson = asJson;
    p->m_sourceName = sourceName;
    p->m_destinationName = destinationName;
    p->m_passphrase = passPhrase;
    p->m_certificateFiles = QStringList { certificateFile };
    return p;
}

PackagingJob *PackagingJob::developerVerify(const QString &sourceName, const QStringList &certificateFiles)
{
    PackagingJob *p = new PackagingJob();
    p->m_mode = DeveloperVerify;
    p->m_sourceName = sourceName;
    p->m_certificateFiles = certificateFiles;
    return p;
}

PackagingJob *PackagingJob::storeSign(const QString &sourceName, const QString &destinationName,
                              const QString &certificateFile, const QString &passPhrase,
                              const QString &hardwareId, bool asJson)
{
    PackagingJob *p = new PackagingJob();
    p->m_mode = StoreSign;
    p->m_asJson = asJson;
    p->m_sourceName = sourceName;
    p->m_destinationName = destinationName;
    p->m_passphrase = passPhrase;
    p->m_certificateFiles = QStringList { certificateFile };
    p->m_hardwareId = hardwareId;
    return p;
}

PackagingJob *PackagingJob::storeVerify(const QString &sourceName, const QStringList &certificateFiles, const QString &hardwareId)
{
    PackagingJob *p = new PackagingJob();
    p->m_mode = StoreVerify;
    p->m_sourceName = sourceName;
    p->m_certificateFiles = certificateFiles;
    p->m_hardwareId = hardwareId;
    return p;
}

QString PackagingJob::output() const
{
    return m_output;
}

int PackagingJob::resultCode() const
{
    return m_resultCode;
}

PackagingJob::PackagingJob()
{ }

void PackagingJob::execute() Q_DECL_NOEXCEPT_EXPR(false)
{
    switch (m_mode) {
    case Create: {
        if (m_destinationName.isEmpty())
            throw Exception(Error::Package, "no destination package name given");

        QFile destination(m_destinationName);
        if (!destination.open(QIODevice::WriteOnly | QIODevice::Truncate))
            throw Exception(destination, "could not create package file");

        QString canonicalDestination = QFileInfo(destination).canonicalFilePath();

        QDir source(m_sourceDir);
        if (!source.exists())
            throw Exception(Error::Package, "source %1 is not a directory").arg(m_sourceDir);

        // check metadata
        YamlApplicationScanner yas;
        QString infoName = yas.metaDataFileName();
        QScopedPointer<ApplicationInfo> app(yas.scan(source.absoluteFilePath(infoName)));

        // build report
        InstallationReport report(app->id());
        report.addFile(infoName);

        // check icon
        if (!QFile::exists(source.absoluteFilePath(app->icon())))
            throw Exception(Error::Package, "missing the file referenced by the 'icon' field");
        report.addFile(app->icon());

        // check executable
        if (!QFile::exists(source.absoluteFilePath(app->codeFilePath())))
            throw Exception(Error::Package, "missing the file referenced by the 'code' field");

        quint64 estimatedImageSize = 0;
        QString canonicalSourcePath = source.canonicalPath();
        QDirIterator it(source.absolutePath(), QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot, QDirIterator::Subdirectories);

        while (it.hasNext()) {
            it.next();
            QFileInfo entryInfo = it.fileInfo();
            QString entryPath = entryInfo.canonicalFilePath();

            // do not package the package itself, in case someone builds the package within the source dir
            if (canonicalDestination == entryPath)
                continue;

            if (!entryPath.startsWith(canonicalSourcePath))
                throw Exception(Error::Package, "file %1 is not inside the source directory %2").arg(entryPath).arg(canonicalSourcePath);

            // QDirIterator::filePath() returns absolute paths, although the naming suggests otherwise
            entryPath = entryPath.mid(canonicalSourcePath.size() + 1);

            if (entryInfo.fileName().startsWith(qL1S("--PACKAGE-")))
                throw Exception(Error::Package, "file names starting with --PACKAGE- are reserved by the packager (found: %1)").arg(entryPath);

            estimatedImageSize += (entryInfo.size() + Ext2BlockSize - 1) / Ext2BlockSize;

            if (entryPath != infoName && entryPath != app->icon())
                report.addFile(entryPath);
        }

        // we have the estimatedImageSize for the raw content now, but we need to add the inode
        // overhead still. This algorithm comes from buildroot:
        // http://git.buildroot.net/buildroot/tree/package/mke2img/mke2img
        estimatedImageSize = (500 + (estimatedImageSize + report.files().count() + 400 / 8) * 11 / 10) * Ext2BlockSize;
        report.setDiskSpaceUsed(estimatedImageSize);

        // set extra metadata
        report.setExtraMetaData(m_extraMetaData);
        report.setExtraSignedMetaData(m_extraSignedMetaData);

        // finally create the package
        PackageCreator creator(source, &destination, report);
        if (!creator.create())
            throw Exception(Error::Package, "could not create package %1: %2").arg(app->id()).arg(creator.errorString());

        QVariantMap md = creator.metaData();
        m_output = m_asJson ? QJsonDocument::fromVariant(md).toJson().constData()
                            : QtYaml::yamlFromVariantDocuments({ md }).constData();
        break;
    }
    case DeveloperSign:
    case DeveloperVerify:
    case StoreSign:
    case StoreVerify: {
        if (!QFile::exists(m_sourceName))
            throw Exception(Error::Package, "package file %1 does not exist").arg(m_sourceName);

        // read certificates
        QList<QByteArray> certificates;
        for (const QString &cert : qAsConst(m_certificateFiles)) {
            QFile cf(cert);
            if (!cf.open(QIODevice::ReadOnly))
                throw Exception(cf, "could not open certificate file");
            certificates << cf.readAll();
        }

        // create temporary dir for extraction
        QTemporaryDir tmp;
        if (!tmp.isValid())
            throw Exception(Error::Package, "could not create temporary directory %1").arg(tmp.path());

        // extract source
        PackageExtractor extractor(QUrl::fromLocalFile(m_sourceName), tmp.path());
        if (!extractor.extract())
            throw Exception(Error::Package, "could not extract package %1: %2").arg(m_sourceName).arg(extractor.errorString());

        InstallationReport report = extractor.installationReport();

        // check signatures
        if (m_mode == DeveloperVerify) {
            if (report.developerSignature().isEmpty()) {
                m_output = qSL("no developer signature");
                m_resultCode = 1;
            } else {
                Signature sig(report.digest());
                if (!sig.verify(report.developerSignature(), certificates)) {
                    m_output = qSL("invalid developer signature (") + sig.errorString() + qSL(")");
                    m_resultCode = 2;
                } else {
                    m_output = qSL("valid developer signature");
                }
            }
            break; // done with DeveloperVerify

        } else if (m_mode == StoreVerify) {
            if (report.storeSignature().isEmpty()) {
                m_output = qSL("no store signature");
                m_resultCode = 1;
            } else {
                QByteArray sigDigest = report.digest();
                if (!m_hardwareId.isEmpty())
                    sigDigest = QMessageAuthenticationCode::hash(sigDigest, m_hardwareId.toUtf8(), QCryptographicHash::Sha256);

                Signature sig(sigDigest);
                if (!sig.verify(report.storeSignature(), certificates)) {
                    m_output = qSL("invalid store signature (") + sig.errorString() + qSL(")");
                    m_resultCode = 2;
                } else {
                    m_output = qSL("valid store signature");
                }

            }
            break; // done with StoreVerify
        }

        // create a signed package
        if (m_destinationName.isEmpty())
            throw Exception(Error::Package, "no destination package name given");

        QFile destination(m_destinationName);
        if (!destination.open(QIODevice::WriteOnly | QIODevice::Truncate))
            throw Exception(destination, "could not create package file");

        PackageCreator creator(tmp.path(), &destination, report);

        if (certificates.size() != 1)
            throw Exception(Error::Package, "cannot sign packages with more than one certificate");

        if (m_mode == DeveloperSign) {
            Signature sig(report.digest());
            QByteArray signature = sig.create(certificates.first(), m_passphrase.toUtf8());

            if (signature.isEmpty())
                throw Exception(Error::Package, "could not create signature: %1").arg(sig.errorString());
            report.setDeveloperSignature(signature);
        } else if (m_mode == StoreSign) {
            QByteArray sigDigest = report.digest();
            if (!m_hardwareId.isEmpty())
                sigDigest = QMessageAuthenticationCode::hash(sigDigest, m_hardwareId.toUtf8(), QCryptographicHash::Sha256);

            Signature sig(sigDigest);
            QByteArray signature = sig.create(certificates.first(), m_passphrase.toUtf8());

            if (signature.isEmpty())
                throw Exception(Error::Package, "could not create signature: %1").arg(sig.errorString());
            report.setStoreSignature(signature);
        }

        if (!creator.create())
            throw Exception(Error::Package, "could not create package %1: %2").arg(m_destinationName).arg(creator.errorString());

        QVariantMap md = creator.metaData();
        m_output = m_asJson ? QJsonDocument::fromVariant(md).toJson().constData()
                            : QtYaml::yamlFromVariantDocuments({ md }).constData();
        break;
    }
    default:
        throw Exception("invalid mode");
    }
}