aboutsummaryrefslogtreecommitdiffstats
path: root/src/m_im/ImCodec.cpp
blob: fa36e2ed0f53f2408111af622fee7cc9a26075eb (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
/**
 * Copyright (C) 2021-2024 Saturneric <eric@bktus.com>
 *
 * This file is part of GpgFrontend.
 *
 * GpgFrontend 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.
 *
 * GpgFrontend 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 GpgFrontend. If not, see <https://www.gnu.org/licenses/>.
 *
 * The initial version of the source code is inherited from
 * the gpg4usb project, which is under GPL-3.0-or-later.
 *
 * All the source code of GpgFrontend was modified and released by
 * Saturneric <eric@bktus.com> starting on May 12, 2021.
 *
 * SPDX-License-Identifier: GPL-3.0-or-later
 *
 */

#include "ImCodec.h"

#include <QCoreApplication>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>

#include "GFModuleTr.h"
#include "ImToken.h"

using namespace Qt::StringLiterals;

namespace ImCodec {

namespace {

constexpr char kPhraseBlobVersion = '\x01';

/**
 * @brief The "Instant Messaging" card: how the token is framed and, above
 * all, whether a shared book phrase is in use -- the default book only hides
 * the format from naive scanners, so it is reported as a warning.
 */
auto BookCard(const QString& phrase, qsizetype payload, qsizetype token_len)
    -> QJsonObject {
  const bool configured = !phrase.isEmpty();
  QJsonArray fields;
  const auto add = [&fields](const QString& k, const QString& v) {
    fields.append(QJsonArray{k, v});
  };

  add(GTrC::tr("Encoding"), u"Base58 (Bitcoin/IPFS)"_s);
  add(GTrC::tr("Container Format"),
      QString("v%1").arg(ImToken::FormatVersion()));
  add(GTrC::tr("Message Book"),
      configured ? GTrC::tr("Shared phrase (Argon2id)")
                 : GTrC::tr("Default, no shared phrase set"));
  // Lets both sides confirm they are on the same book. Only meaningful with a
  // phrase: everyone shares the default book, so its digest says nothing.
  if (configured) {
    add(GTrC::tr("Book Fingerprint"), ImToken::BookFingerprintOf(phrase));
  } else {
    add(GTrC::tr("Set a Phrase"), GTrC::tr("Settings > Instant Messaging"));
  }
  if (payload > 0) {
    add(GTrC::tr("OpenPGP Payload"), GTrC::tr("%1 bytes").arg(payload));
  }
  if (token_len > 0) {
    add(GTrC::tr("Token Length"), GTrC::tr("%1 characters").arg(token_len));
  }
  if (payload > 0 && token_len > 0) {
    // Random padding plus Base58 expansion. The padding part is deliberately
    // random, so this ratio does not pin down the true payload length.
    const auto ratio =
        static_cast<double>(token_len) / static_cast<double>(payload);
    add(GTrC::tr("Wire Overhead"),
        QString("+%1%").arg((ratio * 100.0) - 100.0, 0, 'f', 0));
  }

  return QJsonObject{{u"title"_s, GTrC::tr("Instant Messaging")},
                     {u"status"_s, configured ? u"ok"_s : u"warn"_s},
                     {u"fields"_s, fields}};
}

auto CardsJson(const QJsonObject& card) -> QString {
  const QJsonObject payload{
      {u"description"_s,
       GTrC::tr(
           "An Instant Messaging section followed by the OpenPGP result.")},
      {u"cards"_s, QJsonArray{card}}};
  return QString::fromUtf8(
      QJsonDocument(payload).toJson(QJsonDocument::Compact));
}

}  // namespace

auto DecodeInput(const QByteArray& input, const QString& phrase) -> Answer {
  // The token format rejects ordinary text and armored OpenPGP on its shape
  // alone, before the memory-hard derivation.
  const auto result = ImToken::Decode(QString::fromUtf8(input), phrase);
  if (!result.ok) return {};

  Answer a;
  a.outcome = Outcome::kHandled;
  a.output = result.pgp_message;
  a.cards = CardsJson(BookCard(phrase, 0, 0));
  return a;
}

auto EncodeOutput(const QByteArray& pgp, const QString& phrase) -> Answer {
  Answer a;
  a.outcome = Outcome::kFailed;

  // The payload limit exists so a token we emit is one we can read back.
  // Checked here so the user is told what went wrong and what to do about it.
  const auto limit = ImToken::MaxPayloadBytes();
  if (pgp.size() > limit) {
    a.error = GTrC::tr(
                  "This message is too long to send as an instant message.\n\n"
                  "The encrypted message is %1 bytes, and the "
                  "instant-messaging format carries at most %2. Shorten the "
                  "text, or send it as a normal OpenPGP message instead.")
                  .arg(pgp.size())
                  .arg(limit);
    return a;
  }

  const auto token = ImToken::Encode(pgp, phrase);
  if (token.isEmpty()) {
    a.error = GTrC::tr(
        "Failed to prepare the instant message: the encrypted "
        "message could not be converted into a token.");
    return a;
  }

  a.outcome = Outcome::kHandled;
  a.output = token.toUtf8();
  a.cards = CardsJson(BookCard(phrase, pgp.size(), token.size()));
  return a;
}

auto EncodePhraseBlob(const QString& phrase) -> QByteArray {
  QByteArray blob(1, kPhraseBlobVersion);
  blob.append(phrase.trimmed().toUtf8());
  return blob;
}

auto DecodePhraseBlob(const QByteArray& blob) -> QString {
  if (blob.isEmpty() || blob.at(0) != kPhraseBlobVersion) return {};
  return QString::fromUtf8(blob.mid(1)).trimmed();
}

}  // namespace ImCodec