aboutsummaryrefslogtreecommitdiffstats
path: root/verifynotification.cpp
blob: b195972ca9fcc4d29093b3546a0ffeec6161e75b (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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
/*
 *      verifynotification.cpp
 *
 *      Copyright 2008 gpg4usb-team <[email protected]>
 *
 *      This file is part of gpg4usb.
 *
 *      Gpg4usb is free software: you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation, either version 3 of the License, or
 *      (at your option) any later version.
 *
 *      Gpg4usb is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with gpg4usb.  If not, see <http://www.gnu.org/licenses/>
 */

#include "verifynotification.h"

VerifyNotification::VerifyNotification(QWidget *parent, GpgME::GpgContext *ctx, KeyList *keyList,QTextEdit *edit) :
    QWidget(parent)
{
    mCtx = ctx;
    mKeyList = keyList;
    mTextpage = edit;
    verifyLabel = new QLabel(this);

    connect(mCtx, SIGNAL(keyDBChanged()), this, SLOT(slotRefresh()));
    connect(edit, SIGNAL(textChanged()), this, SLOT(close()));

    importFromKeyserverAct = new QAction(tr("Import missing key from Keyserver"), this);
    connect(importFromKeyserverAct, SIGNAL(triggered()), this, SLOT(slotImportFromKeyserver()));

    showVerifyDetailsAct = new QAction(tr("Show detailed verify information"), this);
    connect(showVerifyDetailsAct, SIGNAL(triggered()), this, SLOT(slotShowVerifyDetails()));

    detailMenu = new QMenu(this);
    detailMenu->addAction(showVerifyDetailsAct);
    detailMenu->addAction(importFromKeyserverAct);
    importFromKeyserverAct->setVisible(false);

    keysNotInList = new QStringList();
    detailsButton = new QPushButton(tr("Details"),this);
    detailsButton->setMenu(detailMenu);
    QHBoxLayout *notificationWidgetLayout = new QHBoxLayout(this);
    notificationWidgetLayout->setContentsMargins(10,0,0,0);
    notificationWidgetLayout->addWidget(verifyLabel,2);
    notificationWidgetLayout->addWidget(detailsButton);
    this->setLayout(notificationWidgetLayout);
}

void VerifyNotification::slotImportFromKeyserver()
{
    KeyServerImportDialog *importDialog =new KeyServerImportDialog(mCtx,mKeyList, this);
    importDialog->slotImport(*keysNotInList);
}

void VerifyNotification::setVerifyLabel(QString text, verify_label_status verifyLabelStatus)
{
    QString color;
    verifyLabel->setText(text);
    switch (verifyLabelStatus) {
    case VERIFY_ERROR_OK:       color="#ccffcc";
                                break;
    case VERIFY_ERROR_WARN:     color="#ececba";
                                break;
    case VERIFY_ERROR_CRITICAL: color="#ff8080";
                                break;
    default:
                                break;
    }

    verifyLabel->setAutoFillBackground(true);
    QPalette status = verifyLabel->palette();
    status.setColor(QPalette::Background, color);
    verifyLabel->setPalette(status);
}                    

void VerifyNotification::showImportAction(bool visible)
{
    importFromKeyserverAct->setVisible(visible);
}

void VerifyNotification::slotShowVerifyDetails()
{
    //QByteArray text = mTextpage->toPlainText().toUtf8();
    //mCtx->preventNoDataErr(&text);
    new VerifyDetailsDialog(this, mCtx, mKeyList, mTextpage->toPlainText());
}

bool VerifyNotification::slotRefresh()
{
    verify_label_status verifyStatus=VERIFY_ERROR_OK;

    QByteArray text = mTextpage->toPlainText().toUtf8();
    mCtx->preventNoDataErr(&text);
    //int textIsSigned = mCtx->textIsSigned(text);

    //gpgme_signature_t sign = mCtx->verify(text);

    //KGpgVerify *verify = new KGpgVerify(this, message.mid(posstart, posend - posstart));
    KGpgVerify *verify = new KGpgVerify(this, text);
    connect(verify, SIGNAL(done(int)), SLOT(slotVerifyDone(int)));
    verify->start();

    /*
    if (sign == NULL) {
        return false;
    }

    QString verifyLabelText;
    bool unknownKeyFound=false;

    while (sign) {

        switch (gpg_err_code(sign->status))
        {
            case GPG_ERR_NO_PUBKEY:
            {
                verifyStatus=VERIFY_ERROR_WARN;
                verifyLabelText.append(tr("Key not present with id 0x")+QString(sign->fpr));
                this->keysNotInList->append(sign->fpr);
                unknownKeyFound=true;
                break;
            }
            case GPG_ERR_NO_ERROR:
            {
                GpgKey key = mCtx->getKeyByFpr(sign->fpr);
                verifyLabelText.append(key.name);
                if (!key.email.isEmpty()) {
                    verifyLabelText.append("<"+key.email+">");
                }
                break;
            }
            case GPG_ERR_BAD_SIGNATURE:
            {
                textIsSigned = 3;
                verifyStatus=VERIFY_ERROR_CRITICAL;
                GpgKey key = mCtx->getKeyById(sign->fpr);
                verifyLabelText.append(key.name);
                if (!key.email.isEmpty()) {
                    verifyLabelText.append("<"+key.email+">");
                }
                break;
            }
            default:
            {
                //textIsSigned = 3;
                verifyStatus=VERIFY_ERROR_WARN;
                //GpgKey key = mKeyList->getKeyByFpr(sign->fpr);
                verifyLabelText.append(tr("Error for key with fingerprint ")+mCtx->beautifyFingerprint(QString(sign->fpr)));
                break;
            }
        }
        verifyLabelText.append("\n");
        sign = sign->next;
    }

    switch (textIsSigned)
    {
        case 3:
            {
                verifyLabelText.prepend(tr("Error validating signature by: "));
                break;
            }
        case 2:
            {
                verifyLabelText.prepend(tr("Text was completely signed by: "));
                break;
            }
        case 1:
            {
                verifyLabelText.prepend(tr("Text was partially signed by: "));
                break;
            }
    }

    // If an unknown key is found, enable the importfromkeyserveraction
    this->showImportAction(unknownKeyFound);

    // Remove the last linebreak
    verifyLabelText.remove(verifyLabelText.length()-1,1);

    this->setVerifyLabel(verifyLabelText,verifyStatus);
    */
    return true;
}

void VerifyNotification::slotVerifyDone(int result)
{
    const KGpgVerify * const verify = qobject_cast<KGpgVerify *>(sender());
    sender()->deleteLater();
    Q_ASSERT(verify != NULL);

    QByteArray text = mTextpage->toPlainText().toUtf8();
    mCtx->preventNoDataErr(&text);
    int textIsSigned = mCtx->textIsSigned(text);

    QString verifyLabelText;
    verify_label_status verifyStatus=VERIFY_ERROR_CRITICAL;

    // unknown signer key
    if (result == KGpgVerify::TS_MISSING_KEY) {
        qDebug() << "missing keys" << verify->missingId();
        //this->keysNotInList->append(verify->missingId());
        this->showImportAction(true);

        verifyStatus=VERIFY_ERROR_WARN;
        verifyLabelText.append(tr("Key not present with id 0x")+QString(verify->missingId()));
        this->keysNotInList->append(verify->missingId());
        //unknownKeyFound=true;
    } else {

        const QStringList messages = verify->getMessages();
//        foreach(QString mess, messages) {
//            qDebug() << "vm: " <<  mess;
//        }

        foreach (const QString &line, messages) {
            qDebug() << "vm: " <<  line;

            if (!line.startsWith(QLatin1String("[GNUPG:] ")))
                continue;

            const QString msg = line.mid(9);

            // was: GPG_NO_ERROR
            if (msg.startsWith(QLatin1String("VALIDSIG "))) {
                // from GnuPG source, doc/DETAILS:
                //   VALIDSIG    <fingerprint in hex> <sig_creation_date> <sig-timestamp>
                //                <expire-timestamp> <sig-version> <reserved> <pubkey-algo>
                //                <hash-algo> <sig-class> <primary-key-fpr>
                const QStringList vsig = msg.mid(9).split(QLatin1Char(' '), QString::SkipEmptyParts);
                Q_ASSERT(vsig.count() >= 10);

                qDebug() << "sig: " << vsig[9];

                GpgKey key = mCtx->getKeyByFpr(vsig[9]);

                verifyLabelText.append(key.name);
                if (!key.email.isEmpty()) {
                    verifyLabelText.append("<"+key.email+">");
                }
                verifyStatus = VERIFY_ERROR_OK;
            } else if (msg.startsWith(QLatin1String("UNEXPECTED")) ||
                       msg.startsWith(QLatin1String("NODATA"))) {

               // verifyStatus=VERIFY_ERROR_CRITICAL;
               // verifyLabelText.append("no sig found");

                textIsSigned = 3;
                //verifyStatus=VERIFY_ERROR_CRITICAL;

                verifyLabelText.append("No signature found ");

                /*GpgKey key = mCtx->getKeyById(sign->fpr);
                verifyLabelText.append(key.name);
                if (!key.email.isEmpty()) {
                    verifyLabelText.append("<"+key.email+">");
                }*/
            } else if (msg.startsWith(QLatin1String("BADSIG"))) {

                int sigpos = msg.indexOf( ' ', 8);
                // name not used...?
                //QString name = msg.mid(sigpos + 1).replace(QLatin1Char('<'), QLatin1String("&lt;"));
                QString id = msg.mid(7, sigpos - 7);

                textIsSigned = 3;
                verifyStatus=VERIFY_ERROR_CRITICAL;
                GpgKey key = mCtx->getKeyById(id);
                verifyLabelText.append(key.name);
                if (!key.email.isEmpty()) {
                    verifyLabelText.append("&lt;"+key.email+"&gt;");
                }
                break;

            }
        }

        //verifyStatus=VERIFY_ERROR_WARN;
        //verifyLabelText.append("not yet implemented");
        //getReport(messages);
    }

    switch (textIsSigned)
    {
        case 3:
            {
                verifyLabelText.prepend(tr("Error validating signature by: "));
                break;
            }
        case 2:
            {
                verifyLabelText.prepend(tr("Text was completely signed by: "));
                break;
            }
        case 1:
            {
                verifyLabelText.prepend(tr("Text was partially signed by: "));
                break;
            }
    }

    verifyLabelText.remove(verifyLabelText.length()-1,1);
    this->setVerifyLabel(verifyLabelText,verifyStatus);

    /*emit verifyFinished();

    if (result == KGpgVerify::TS_MISSING_KEY) {
        verifyKeyNeeded(verify->missingId());
        return;
    }

    const QStringList messages = verify->getMessages();

    if (messages.isEmpty())
        return;

    QStringList msglist;
    foreach (QString rawmsg, messages)
        msglist << rawmsg.replace(QLatin1Char('<'), QLatin1String("&lt;"));

    (void) new KgpgDetailedInfo(this, KGpgVerify::getReport(messages, m_model),
            msglist.join(QLatin1String("<br/>")),
            QStringList(), i18nc("Caption of message box", "Verification Finished"));
    */
}

// TODO: Require good sigs on request?
QString VerifyNotification::getReport(const QStringList &log)
{
    QString verifyLabelText;
    verify_label_status verifyStatus=VERIFY_ERROR_OK;

    QString result;
    // newer versions of GnuPG emit both VALIDSIG and GOODSIG
    // for a good signature. Since VALIDSIG has more information
    // we use that.
    const QRegExp validsig(QLatin1String("^\\[GNUPG:\\] VALIDSIG([ ]+[^ ]+){10,}.*$"));


    QString sigtime;	// timestamp of signature creation

    foreach (const QString &line, log) {
        if (!line.startsWith(QLatin1String("[GNUPG:] ")))
            continue;

        const QString msg = line.mid(9);

        if (msg.startsWith(QLatin1String("VALIDSIG "))) {
            // from GnuPG source, doc/DETAILS:
            //   VALIDSIG    <fingerprint in hex> <sig_creation_date> <sig-timestamp>
            //                <expire-timestamp> <sig-version> <reserved> <pubkey-algo>
            //                <hash-algo> <sig-class> <primary-key-fpr>
            const QStringList vsig = msg.mid(9).split(QLatin1Char(' '), QString::SkipEmptyParts);
            Q_ASSERT(vsig.count() >= 10);

            qDebug() << "sig: " << vsig[9];

            verifyStatus=VERIFY_ERROR_WARN;
            verifyLabelText.append(tr("Error for key with fingerprint ")+mCtx->beautifyFingerprint(QString(vsig[9])));
        }
    }

    this->setVerifyLabel(verifyLabelText,verifyStatus);
            /*const KGpgKeyNode *node = model->findKeyNode(vsig[9]);

            if (node != NULL) {
                // ignore for now if this is signed with the primary id (vsig[0] == vsig[9]) or not
                if (node->getEmail().isEmpty())
                    result += tr("<qt>Good signature from:<br /><b>%1</b><br />Key ID: %2<br /></qt>")
                            .arg(node->getName()).arg(vsig[9]);
                else
                    result += tr("Good signature from: NAME <EMAIL>, Key ID: HEXID",
                            "<qt>Good signature from:<br /><b>%1 &lt;%2&gt;</b><br />Key ID: %3<br /></qt>")
                            .arg(node->getName()).arg(node->getEmail()).arg(vsig[9]);

                result += sigTimeMessage(vsig[2]);
            } else {
                // this should normally never happen, but one could delete
                // the key just after the verification. Brute force solution:
                // do the whole report generation again, but this time make
                // sure GOODSIG is used.
                return getReport(log, NULL);
            }
        } else if (msg.startsWith(QLatin1String("UNEXPECTED")) ||
                msg.startsWith(QLatin1String("NODATA"))) {
            result += tr("No signature found.") + QLatin1Char('\n');
        } else if (useGoodSig && msg.startsWith(QLatin1String("GOODSIG "))) {
            int sigpos = msg.indexOf( ' ' , 8);
            const QString keyid = msg.mid(8, sigpos - 8);

            // split the name/email pair to give translators more power to handle this
            QString email;
            QString name = msg.mid(sigpos + 1);

            int oPos = name.indexOf(QLatin1Char('<'));
            int cPos = name.indexOf(QLatin1Char('>'));
            if ((oPos >= 0) && (cPos >= 0)) {
                email = name.mid(oPos + 1, cPos - oPos - 1);
                name = name.left(oPos).simplified();
            }

            if (email.isEmpty())
                result += tr("<qt>Good signature from:<br /><b>%1</b><br />Key ID: %2<br /></qt>")
                        .arg(name).arg(keyid);
            else
                result += tr("Good signature from: NAME <EMAIL>, Key ID: HEXID",
                             "<qt>Good signature from:<br /><b>%1 &lt;%2&gt;</b><br />Key ID: %3<br /></qt>")
                        .arg(name).arg(email).arg(keyid);
            if (!sigtime.isEmpty()) {
                result += sigTimeMessage(sigtime);
                sigtime.clear();
            }
        } else if (msg.startsWith(QLatin1String("SIG_ID "))) {
            const QStringList parts = msg.simplified().split(QLatin1Char(' '));
            if (parts.count() > 2)
                sigtime = parts[2];
        } else if (msg.startsWith(QLatin1String("BADSIG"))) {
            int sigpos = msg.indexOf( ' ', 7);
            result += tr("<qt><b>BAD signature</b> from:<br /> %1<br />Key id: %2<br /><br /><b>The file is corrupted</b><br /></qt>")
                    .arg(msg.mid(sigpos + 1).replace(QLatin1Char('<'), QLatin1String("&lt;")))
                    .arg(msg.mid(7, sigpos - 7));
        } else  if (msg.startsWith(QLatin1String("TRUST_UNDEFINED"))) {
            result += tr("<qt>The signature is valid, but the key is untrusted<br /></qt>");
        } else if (msg.startsWith(QLatin1String("TRUST_ULTIMATE"))) {
            result += tr("<qt>The signature is valid, and the key is ultimately trusted<br /></qt>");
        }
    }
    */
    return result;
}