aboutsummaryrefslogtreecommitdiffstats
path: root/src/m_email/EMailSmtpWorker.cpp
blob: 04d32e5ae6f483c947327bbda91f4751fa953dd2 (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
/**
 * 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 "EMailSmtpWorker.h"

#include <vmime/net/smtp/SMTPExceptions.hpp>
#include <vmime/security/defaultAuthenticator.hpp>

#include "EMailTlsSetup.h"
#include "GFModule.h"

namespace {

/// See the IMAP worker: the password is only produced on a secured link, so a
/// policy failure becomes a failed login rather than a leaked credential.
class SecureAuthenticator : public vmime::security::defaultAuthenticator {
 public:
  SecureAuthenticator(QString username, EMailSecretPtr password,
                      bool allow_cleartext)
      : username_(std::move(username)),
        password_(std::move(password)),
        allow_cleartext_(allow_cleartext) {}

  // No wipe here: the bytes belong to EMailSecret and are erased when the
  // last holder releases them. Wiping a local copy was the old mistake -- it
  // detached and zeroed a fresh buffer, leaving the original intact.
  ~SecureAuthenticator() override = default;

  auto getUsername() const -> const vmime::string override {
    return username_.toStdString();
  }

  auto getPassword() const -> const vmime::string override {
    if (!allow_cleartext_) {
      auto service = getService().lock();
      if (!EMailTlsSetup::IsSecured(service)) {
        LOG_ERROR("refusing to send mail password over an unencrypted link");
        throw vmime::exceptions::authentication_error(
            "refusing to authenticate over an unencrypted connection");
      }
    }
    // A copy vmime owns and goes on to copy again while encoding AUTH.
    // Neither is ours to erase; see EMailSecret.
    return password_ ? password_->StdStringCopy() : std::string();
  }

 private:
  QString username_;
  EMailSecretPtr password_;
  bool allow_cleartext_;
};

/**
 * @brief Watches the body leave, so an ambiguous failure can be recognised.
 *
 * The distinction this exists for: if the connection dies *before* the body is
 * fully written, nothing was delivered and saying so is safe. If it dies
 * *after*, the server may or may not have accepted the message, and claiming
 * either outcome would be a guess. vmime drives this listener from the stream
 * copy that writes the body, so completion here is the dividing line.
 */
class BodyProgress : public vmime::utility::progressListener {
 public:
  void start(const size_t predicted_total) override {
    total_ = predicted_total;
  }

  void progress(const size_t current, const size_t current_total) override {
    total_ = current_total;
    if (current >= current_total && current_total > 0) written_ = true;
  }

  void stop(const size_t total) override {
    if (total > 0 && total >= total_) written_ = true;
  }

  [[nodiscard]] auto BodyFullyWritten() const -> bool { return written_; }

 private:
  size_t total_{0};
  bool written_{false};
};

auto SecurityLabel(MailTlsMode mode) -> QString {
  switch (mode) {
    case MailTlsMode::kIMPLICIT:
      return "TLS";
    case MailTlsMode::kSTARTTLS:
      return "STARTTLS";
    case MailTlsMode::kNONE:
      return "unencrypted";
  }
  return {};
}

}  // namespace

EMailSmtpWorker::EMailSmtpWorker(QObject* parent)
    : QObject(parent), token_(std::make_shared<EMailCancelToken>()) {}

EMailSmtpWorker::~EMailSmtpWorker() = default;

void EMailSmtpWorker::TestConnection(quint64 seq,
                                     const MailAccountConfig& account,
                                     EMailSecretPtr password) {
  // Announces the operation rather than clearing the token: a stop issued
  // while this request was still queued was aimed at THIS operation and must
  // survive until the guard below sees it.
  token_->Begin(seq);

  const auto& config = account.smtp;

  EMailSendReceipt receipt;
  receipt.host =
      QString("%1:%2").arg(config.host).arg(config.EffectivePort(false));
  receipt.security = SecurityLabel(config.tls);

  // A stop that arrived while this request was still queued applies to it.
  // Nothing has been written yet, so this is a clean stop with nothing in
  // doubt -- unlike one that lands after the body is on the wire.
  if (token_->IsCancelled()) {
    receipt.error = MailCancelledError();
    emit SignalFinished(seq, receipt);
    return;
  }
  const auto cleartext = config.tls == MailTlsMode::kNONE;
  if (cleartext && !MailHostAllowsCleartext(config.host)) {
    receipt.error = MailTlsRequiredError(config.host);
    emit SignalFinished(seq, receipt);
    return;
  }

  // Declared out here so the catch below can read it: what the verifier
  // records belongs to this connection attempt, and is the only honest source
  // for the fingerprint the user may be offered a pin for.
  EMailTlsSetup::SeenCertificatePtr seen;

  auto timeouts = vmime::make_shared<EMailTimeoutHandlerFactory>(token_, 30);

  try {
    auto session = vmime::net::session::create();
    const auto protocol = EMailTlsSetup::ProtocolName(false, config.tls);

    vmime::utility::url url(protocol.toStdString(), config.host.toStdString());
    url.setPort(config.EffectivePort(false));

    auto transport = session->getTransport(url);
    transport->setTimeoutHandlerFactory(timeouts);

    seen = EMailTlsSetup::Apply(session, transport,
                                QString("transport.%1").arg(protocol), config,
                                false);

    transport->setAuthenticator(vmime::make_shared<SecureAuthenticator>(
        config.username, password, cleartext));

    transport->connect();

    if (!cleartext && !EMailTlsSetup::IsSecured(transport)) {
      receipt.error = MailTlsRequiredError(config.host);
    } else {
      // Reaching here means the server completed the greeting, secured the
      // link, and -- because the session demands authentication -- accepted
      // the credentials. All three are required, which is the whole question
      // a connection test asks.
      receipt.accepted = true;
    }

    try {
      transport->disconnect();
    } catch (...) {
    }

    emit SignalFinished(seq, receipt);
  } catch (const vmime::exception& e) {
    receipt.error = ClassifyVmimeException(e, MailStage::kCONNECT,
                                           timeouts->LastWasCancelled());
    // From THIS connection's verifier; see EMailTlsSetup::SeenCertificate.
    if (seen) {
      MailAttachCertificate(receipt.error, seen->fingerprint, seen->summary);
    }
    emit SignalFinished(seq, receipt);
  } catch (const std::exception& e) {
    receipt.error = MailInternalError(QString::fromUtf8(e.what()));
    emit SignalFinished(seq, receipt);
  }
}

void EMailSmtpWorker::Submit(quint64 seq, const MailAccountConfig& account,
                             EMailSecretPtr password,
                             const EMailOutgoingMessage& message) {
  token_->Begin(seq);

  const auto& config = account.smtp;

  EMailSendReceipt receipt;
  receipt.message_id = message.message_id;
  receipt.host =
      QString("%1:%2").arg(config.host).arg(config.EffectivePort(false));
  receipt.security = SecurityLabel(config.tls);

  // A stop that arrived while this request was still queued applies to it.
  // Nothing has been written yet, so this is a clean stop with nothing in
  // doubt -- unlike one that lands after the body is on the wire.
  if (token_->IsCancelled()) {
    receipt.error = MailCancelledError();
    emit SignalFinished(seq, receipt);
    return;
  }
  const auto cleartext = config.tls == MailTlsMode::kNONE;
  if (cleartext && !MailHostAllowsCleartext(config.host)) {
    receipt.error = MailTlsRequiredError(config.host);
    emit SignalFinished(seq, receipt);
    return;
  }

  if (!message.IsValid()) {
    receipt.error = MailInternalError("outgoing message is incomplete");
    emit SignalFinished(seq, receipt);
    return;
  }

  // Declared out here so the catch below can read it: what the verifier
  // records belongs to this connection attempt, and is the only honest source
  // for the fingerprint the user may be offered a pin for.
  EMailTlsSetup::SeenCertificatePtr seen;

  auto timeouts = vmime::make_shared<EMailTimeoutHandlerFactory>(token_, 60);
  BodyProgress progress;
  auto stage = MailStage::kCONNECT;

  vmime::shared_ptr<vmime::net::transport> transport;

  try {
    auto session = vmime::net::session::create();
    const auto protocol = EMailTlsSetup::ProtocolName(false, config.tls);

    vmime::utility::url url(protocol.toStdString(), config.host.toStdString());
    url.setPort(config.EffectivePort(false));

    transport = session->getTransport(url);
    transport->setTimeoutHandlerFactory(timeouts);

    seen = EMailTlsSetup::Apply(session, transport,
                                QString("transport.%1").arg(protocol), config,
                                false);

    transport->setAuthenticator(vmime::make_shared<SecureAuthenticator>(
        config.username, password, cleartext));

    stage = MailStage::kCONNECT;
    transport->connect();

    if (!cleartext && !EMailTlsSetup::IsSecured(transport)) {
      receipt.error = MailTlsRequiredError(config.host);
      emit SignalFinished(seq, receipt);
      return;
    }

    vmime::mailbox expeditor(message.envelope_from.toStdString());
    vmime::mailboxList recipients;
    for (const auto& address : message.envelope_rcpt) {
      recipients.appendMailbox(
          vmime::make_shared<vmime::mailbox>(address.toStdString()));
    }

    const std::string data(message.eml.constData(),
                           static_cast<size_t>(message.eml.size()));
    vmime::utility::inputStreamStringAdapter input(data);

    receipt.submitted_at = QDateTime::currentDateTime();

    // The stream overload, deliberately. The message-taking overload
    // regenerates the header on a clone -- inventing a Message-ID the caller
    // never learns and re-serializing the body -- which would both break a
    // signature and make the sent copy impossible to find afterwards.
    stage = MailStage::kSUBMIT_BODY;
    transport->send(expeditor, recipients, input,
                    static_cast<size_t>(message.eml.size()), &progress);

    // Reached only when the server's final reply arrived and was positive.
    receipt.accepted = true;
    receipt.reply_code = 250;

    try {
      transport->disconnect();
    } catch (...) {
      // A failure closing the connection says nothing about the message: it
      // has already been accepted, and reporting it would be alarming noise.
    }

    emit SignalFinished(seq, receipt);
    return;
  } catch (const vmime::exception& e) {
    // The heart of the ambiguity handling. Once the body has been fully
    // written, a socket-level failure means we do not know whether the server
    // took the message -- so the stage handed to the classifier changes, and
    // with it the answer the user is given.
    if (progress.BodyFullyWritten() && stage == MailStage::kSUBMIT_BODY) {
      stage = MailStage::kSUBMIT_FINAL;
    }

    if (const auto* smtp =
            dynamic_cast<const vmime::net::smtp::SMTPCommandError*>(&e);
        smtp != nullptr) {
      receipt.reply_code = smtp->statusCode();
      receipt.reply_text = QString::fromStdString(smtp->response()).trimmed();
    }

    receipt.error =
        ClassifyVmimeException(e, stage, timeouts->LastWasCancelled());
    receipt.ambiguous =
        receipt.error.category == MailErrorCategory::kSMTP_AMBIGUOUS;

    try {
      if (transport && transport->isConnected()) transport->disconnect();
    } catch (...) {
    }

    emit SignalFinished(seq, receipt);
    return;
  } catch (const std::exception& e) {
    receipt.error = MailInternalError(QString::fromUtf8(e.what()));
    emit SignalFinished(seq, receipt);
    return;
  }
}