-
Notifications
You must be signed in to change notification settings - Fork 3
/
Session.cpp
2072 lines (1765 loc) · 61 KB
/
Session.cpp
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
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
736
737
738
739
740
741
742
743
744
745
746
747
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
779
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
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
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
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
#include <algorithm>
#include <charconv>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>
#include "DNS.hpp"
#include "Domain.hpp"
#include "IP.hpp"
#include "IP4.hpp"
#include "IP6.hpp"
#include "MessageStore.hpp"
#include "Session.hpp"
#include "esc.hpp"
#include "iequal.hpp"
#include "is_ascii.hpp"
#include "osutil.hpp"
#include <experimental/iterator>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <fmt/ranges.h>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/xpressive/xpressive.hpp>
#include <syslog.h>
#include <gflags/gflags.h>
using namespace std::string_literals;
namespace Config {
/*
char const* wls[]{
"list.dnswl.org",
};
*/
/*
<https://www.dnswl.org/?page_id=15#query>
Return codes
The return codes are structured as 127.0.x.y, with “x” indicating the category
of an entry and “y” indicating how trustworthy an entry has been judged.
Categories (127.0.X.y):
2 – Financial services
3 – Email Service Providers
4 – Organisations (both for-profit [ie companies] and non-profit)
5 – Service/network providers
6 – Personal/private servers
7 – Travel/leisure industry
8 – Public sector/governments
9 – Media and Tech companies
10 – some special cases
11 – Education, academic
12 – Healthcare
13 – Manufacturing/Industrial
14 – Retail/Wholesale/Services
15 – Email Marketing Providers
20 – Added through Self Service without specific category
Trustworthiness / Score (127.0.x.Y):
0 = none – only avoid outright blocking (eg large ESP mailservers, -0.1)
1 = low – reduce chance of false positives (-1.0)
2 = medium – make sure to avoid false positives but allow override for clear
cases (-10.0) 3 = high – avoid override (-100.0).
The scores in parantheses are typical SpamAssassin scores.
Special return code 127.0.0.255
In cases where your nameserver issues more than 100’000 queries / 24 hours, you
may be blocked from further queries. The return code “127.0.0.255” indicates
this situation.
*/
char const* bls[]{
"b.barracudacentral.org",
"sbl-xbl.spamhaus.org",
};
/*** Last octet from A record returned by blocklists ***
<https://www.spamhaus.org/faq/section/DNSBL%20Usage#200>
Spamhaus uses this general convention for return codes:
Return Code Description
127.0.0.0/24 Spamhaus IP Blocklists
127.0.1.0/24 Spamhaus Domain Blocklists
127.0.2.0/24 Spamhaus Zero Reputation Domains list
127.255.255.0/24 ERRORS (not implying a "listed" response)
Currently used return codes for Spamhaus public IP zones:
Return Code Zone Description
127.0.0.2 SBL Spamhaus SBL Data
127.0.0.3 SBL Spamhaus SBL CSS Data
127.0.0.4 XBL CBL Data
127.0.0.9 SBL Spamhaus DROP/EDROP Data
(in addition to 127.0.0.2, since 01-Jun-2016)
127.0.0.10 PBL ISP Maintained
127.0.0.11 PBL Spamhaus Maintained
127.0.0.5-7 are allocated to XBL for possible future use;
127.0.0.8 is allocated to SBL for possible future use.
From <https://www.spamhaus.org/faq/section/Spamhaus%20DBL#291>
Return Codes Data Source
127.0.1.2 spam domain
127.0.1.4 phish domain
127.0.1.5 malware domain
127.0.1.6 botnet C&C domain
127.0.1.102 abused legit spam
127.0.1.103 abused spammed redirector domain
127.0.1.104 abused legit phish
127.0.1.105 abused legit malware
127.0.1.106 abused legit botnet C&C
127.0.1.255 IP queries prohibited!
The following special codes indicate an error condition and should not
be taken to imply that the queried domain is "listed":
Return Code Description
127.255.255.252 Typing error in DNSBL name
127.255.255.254 Anonymous query through public resolver
127.255.255.255 Excessive number of queries
From <http://www.surbl.org/lists#multi>
last octet indicates which lists it belongs to. The bit positions in
that last octet for membership in the different lists are:
8 = listed on PH
16 = listed on MW
64 = listed on ABUSE
128 = listed on CR
*/
/*
char const* uribls[]{
"dbl.spamhaus.org",
"multi.uribl.com",
};
*/
constexpr auto greeting_wait = std::chrono::seconds{6};
constexpr int max_recipients_per_message = 100;
constexpr int max_unrecognized_cmds = 20;
// Read timeout value gleaned from RFC-1123 section 5.3.2 and RFC-5321
// section 4.5.3.2.7.
constexpr auto read_timeout = std::chrono::minutes{5};
constexpr auto write_timeout = std::chrono::seconds{30};
} // namespace Config
DEFINE_bool(immortal, false, "don't set process timout");
DEFINE_uint64(max_read, 0, "max data to read");
DEFINE_uint64(max_write, 0, "max data to write");
DEFINE_bool(test_mode, false, "ease up on some checks");
DEFINE_bool(use_binarymime, true, "support BINARYMIME extension, RFC 3030");
DEFINE_bool(use_chunking, true, "support CHUNKING extension, RFC 3030");
DEFINE_bool(use_pipelining, true, "support PIPELINING extension, RFC 2920");
DEFINE_bool(use_rrvs, true, "support RRVS extension, RFC 7293");
DEFINE_bool(use_prdr, true, "support PRDR extension");
DEFINE_bool(use_smtputf8, true, "support SMTPUTF8 extension, RFC 6531");
boost::xpressive::mark_tag secs_(1);
boost::xpressive::sregex const all_rex = boost::xpressive::icase("wait-all-") >>
(secs_ = +boost::xpressive::_d);
Session::Session(fs::path config_path,
std::function<void(void)> read_hook,
int fd_in,
int fd_out)
: config_path_(config_path)
, res_(config_path)
, sock_(fd_in, fd_out, read_hook, Config::read_timeout, Config::write_timeout)
//, send_(config_path, "smtp")
//, srs_(config_path)
{
auto accept_db_name = config_path_ / "accept_domains";
auto allow_db_name = config_path_ / "allow";
auto block_db_name = config_path_ / "block";
// auto forward_db_name = config_path_ / "forward";
accept_domains_.open(accept_db_name);
allow_.open(allow_db_name);
block_.open(block_db_name);
// forward_.open(forward_db_name);
if (sock_.has_peername() && !IP::is_private(sock_.us_c_str())) {
auto fcrdns = DNS::fcrdns(res_, sock_.us_c_str());
for (auto const& fcr : fcrdns) {
server_fcrdns_.emplace_back(fcr);
}
}
server_identity_ = Domain{[this] {
auto const id_from_env{getenv("GHSMTP_SERVER_ID")};
if (id_from_env)
return std::string{id_from_env};
auto const hostname{osutil::get_hostname()};
if (hostname.find('.') != std::string::npos)
return hostname;
if (!server_fcrdns_.empty()) {
// first result should be shortest
return server_fcrdns_.front().ascii();
}
auto const us_c_str = sock_.us_c_str();
if (us_c_str && !IP::is_private(us_c_str)) {
return IP::to_address_literal(us_c_str);
}
LOG(FATAL) << "can't determine my server ID, set GHSMTP_SERVER_ID maybe";
return ""s;
}()};
// send_.set_sender(server_identity_);
max_msg_size(Config::max_msg_size_initial);
}
void Session::max_msg_size(size_t max)
{
max_msg_size_ = max; // number to advertise via RFC 1870
if (FLAGS_max_read) {
sock_.set_max_read(FLAGS_max_read);
}
else {
auto const overhead = std::max(max / 10, size_t(2048));
sock_.set_max_read(max + overhead);
}
}
void Session::bad_host_(char const* msg) const
{
if (sock_.has_peername()) {
// On my systems, this pattern triggers a fail2ban rule that
// blocks connections from this IP address on port 25 for a few
// days. See <https://www.fail2ban.org/> for more info.
syslog(LOG_MAIL | LOG_WARNING, "bad host [%s] %s", sock_.them_c_str(), msg);
}
std::exit(EXIT_SUCCESS);
}
void Session::reset_()
{
// RSET does not force another EHLO/HELO, the one piece of per
// transaction data saved is client_identity_:
// client_identity_.clear(); <-- not cleared!
reverse_path_.clear();
forward_path_.clear();
spf_received_.clear();
// fwd_path_.clear();
// fwd_from_.clear();
// rep_info_.clear();
binarymime_ = false;
smtputf8_ = false;
prdr_ = false;
if (msg_) {
msg_.reset();
}
max_msg_size(max_msg_size());
state_ = xact_step::mail;
// send_.rset();
}
// Return codes from connection establishment are 220 or 554, according
// to RFC 5321. That's it.
void Session::greeting()
{
CHECK(state_ == xact_step::helo);
if (sock_.has_peername()) {
close(2); // if we're a networked program, never send to stderr
std::string error_msg;
if (!verify_ip_address_(error_msg)) {
LOG(INFO) << error_msg;
bad_host_(error_msg.c_str());
}
/******************************************************************
<https://tools.ietf.org/html/rfc5321#section-4.3.1> says:
4.3. Sequencing of Commands and Replies
4.3.1. Sequencing Overview
The communication between the sender and receiver is an alternating
dialogue, controlled by the sender. As such, the sender issues a
command and the receiver responds with a reply. Unless other
arrangements are negotiated through service extensions, the sender
MUST wait for this response before sending further commands. One
important reply is the connection greeting. Normally, a receiver
will send a 220 "Service ready" reply when the connection is
completed. The sender SHOULD wait for this greeting message before
sending any commands.
So which is it?
“…the receiver responds with a reply.”
“…the sender MUST wait for this response…”
“One important reply is the connection greeting.”
“The sender SHOULD wait for this greeting…”
So is it MUST or SHOULD? I enforce MUST.
*******************************************************************/
// Wait a bit of time for pre-greeting traffic.
if (!(ip_allowed_ || fcrdns_allowed_)) {
if (sock_.input_ready(Config::greeting_wait)) {
out_() << "421 4.3.2 not accepting network messages\r\n" << std::flush;
LOG(INFO) << "input before any greeting from " << client_;
bad_host_("input before any greeting");
}
// Give a half greeting and wait again.
out_() << "220-" << server_id_() << " ESMTP slowstart - ghsmtp\r\n"
<< std::flush;
if (sock_.input_ready(Config::greeting_wait)) {
out_() << "421 4.3.2 not accepting network messages\r\n" << std::flush;
LOG(INFO) << "input before full greeting from " << client_;
bad_host_("input before full greeting");
}
/*
<https://www.rfc-editor.org/rfc/rfc5321#section-4.2>
An SMTP client MUST determine its actions only by the reply code, not
by the text (except for the "change of address" 251 and 551 and, if
necessary, 220, 221, and 421 replies); in the general case, any text,
including no text at all (although senders SHOULD NOT send bare
codes), MUST be acceptable. The space (blank) following the reply
code is considered part of the text. Whenever possible, a receiver-
SMTP SHOULD test the first digit (severity indication) of the reply
code.
Except the following chokes a lot of senders:
out_() << "220\r\n" << std::flush;
*/
out_() << "220 " << server_id_() << " ESMTP - ghsmtp\r\n" << std::flush;
}
else {
out_() << "220 " << server_id_() << " ESMTP faststart - ghsmtp\r\n"
<< std::flush;
}
}
else {
out_() << "220 " << server_id_() << " ESMTP - ghsmtp\r\n" << std::flush;
}
LOG(INFO) << "connect from " << client_;
if ((!FLAGS_immortal) && (getenv("GHSMTP_IMMORTAL") == nullptr)) {
alarm(2 * 60); // initial alarm
}
}
void Session::flush() { out_() << std::flush; }
void Session::last_in_group_(std::string_view verb)
{
if (sock_.input_ready(std::chrono::seconds(0))) {
LOG(WARNING) << "pipelining error; input ready processing " << verb;
}
}
void Session::check_for_pipeline_error_(std::string_view verb)
{
if (!(FLAGS_use_pipelining && extensions_)) {
if (sock_.input_ready(std::chrono::seconds(0))) {
LOG(WARNING) << "pipelining error; input ready processing " << verb;
}
}
}
void Session::lo_(char const* verb, std::string_view client_identity_str)
{
Domain client_identity{client_identity_str};
last_in_group_(verb);
reset_();
if (client_identity_ != client_identity) {
client_identity_ = client_identity;
std::string error_msg;
if (!verify_client_(client_identity_, error_msg)) {
LOG(INFO) << "client identity blocked: " << error_msg;
bad_host_(error_msg.c_str());
}
}
if (*verb == 'H') {
extensions_ = false;
out_() << "250 " << server_id_() << "\r\n";
}
if (*verb == 'E') {
extensions_ = true;
if (sock_.has_peername()) {
out_() << "250-" << server_id_() << " at your service, " << client_
<< "\r\n";
}
else {
out_() << "250-" << server_id_() << "\r\n";
}
// LIMITS SMTP Service Extension,
// <https://www.rfc-editor.org/rfc/rfc9422.html>
out_() << "250-LIMITS RCPTMAX=" << Config::max_recipients_per_message
<< "\r\n";
out_() << "250-SIZE " << max_msg_size() << "\r\n"; // RFC 1870
out_() << "250-8BITMIME\r\n"; // RFC 6152
if (FLAGS_use_rrvs) {
out_() << "250-RRVS\r\n"; // RFC 7293
}
if (FLAGS_use_prdr) {
out_() << "250-PRDR\r\n"; // draft-hall-prdr-00.txt
}
if (sock_.tls()) {
// Check sasl sources for auth types.
// out_() << "250-AUTH PLAIN\r\n";
out_() << "250-REQUIRETLS\r\n"; // RFC 8689
}
else {
// If we're not already TLS, offer TLS
out_() << "250-STARTTLS\r\n"; // RFC 3207
}
out_() << "250-ENHANCEDSTATUSCODES\r\n"; // RFC 2034
if (FLAGS_use_pipelining) {
out_() << "250-PIPELINING\r\n"; // RFC 2920
}
if (FLAGS_use_binarymime) {
out_() << "250-BINARYMIME\r\n"; // RFC 3030
}
if (FLAGS_use_chunking) {
out_() << "250-CHUNKING\r\n"; // RFC 3030
}
if (FLAGS_use_smtputf8) {
out_() << "250-SMTPUTF8\r\n"; // RFC 6531
}
out_() << "250 HELP\r\n";
}
out_() << std::flush;
if (sock_.has_peername()) {
if (std::find(begin(client_fcrdns_), end(client_fcrdns_),
client_identity_) != end(client_fcrdns_)) {
LOG(INFO) << verb << " " << client_identity_ << " from "
<< sock_.them_address_literal();
}
else {
LOG(INFO) << verb << " " << client_identity_ << " from " << client_;
}
}
else {
LOG(INFO) << verb << " " << client_identity_;
}
}
void Session::mail_from(Mailbox&& reverse_path, parameters_t const& parameters)
{
check_for_pipeline_error_("MAIL FROM");
switch (state_) {
case xact_step::helo:
out_() << "503 5.5.1 sequence error, expecting HELO/EHLO\r\n" << std::flush;
LOG(WARNING) << "'MAIL FROM' before HELO/EHLO"
<< (sock_.has_peername() ? " from " : "") << client_;
return;
case xact_step::mail: break;
case xact_step::rcpt:
out_() << "503 5.5.1 sequence error, expecting RCPT\r\n" << std::flush;
LOG(WARNING) << "nested MAIL command"
<< (sock_.has_peername() ? " from " : "") << client_;
return;
case xact_step::data:
case xact_step::bdat:
out_() << "503 5.5.1 sequence error, expecting DATA/BDAT\r\n" << std::flush;
LOG(WARNING) << "nested MAIL command"
<< (sock_.has_peername() ? " from " : "") << client_;
return;
case xact_step::rset:
out_() << "503 5.5.1 sequence error, expecting RSET\r\n" << std::flush;
LOG(WARNING) << "error state must be cleared with a RSET"
<< (sock_.has_peername() ? " from " : "") << client_;
return;
}
if (!verify_from_params_(parameters)) {
return;
}
if (!smtputf8_ && !is_ascii(reverse_path.local_part())) {
LOG(WARNING) << "non ascii reverse_path \"" << reverse_path
<< "\" without SMTPUTF8 paramater";
}
std::string error_msg;
if (!verify_sender_(reverse_path, error_msg)) {
LOG(INFO) << "verify sender failed: " << error_msg;
bad_host_(error_msg.c_str());
}
reverse_path_ = std::move(reverse_path);
// fwd_path_.clear();
// fwd_from_.clear();
forward_path_.clear();
out_() << "250 2.1.0 MAIL FROM OK\r\n";
// No flush RFC-2920 section 3.1, this could be part of a command group.
fmt::memory_buffer params;
for (auto const& [name, value] : parameters) {
fmt::format_to(std::back_inserter(params), " {}", name);
if (!value.empty()) {
fmt::format_to(std::back_inserter(params), "={}", value);
}
}
LOG(INFO) << "MAIL FROM:<" << reverse_path_ << ">" << fmt::to_string(params);
state_ = xact_step::rcpt;
}
void Session::rcpt_to(Mailbox&& forward_path, parameters_t const& parameters)
{
check_for_pipeline_error_("RCPT TO");
switch (state_) {
case xact_step::helo:
out_() << "503 5.5.1 sequence error, expecting HELO/EHLO\r\n" << std::flush;
LOG(WARNING) << "'RCPT TO' before HELO/EHLO"
<< (sock_.has_peername() ? " from " : "") << client_;
return;
case xact_step::mail:
out_() << "503 5.5.1 sequence error, expecting MAIL\r\n" << std::flush;
LOG(WARNING) << "'RCPT TO' before 'MAIL FROM'"
<< (sock_.has_peername() ? " from " : "") << client_;
return;
case xact_step::rcpt:
case xact_step::data: break;
case xact_step::bdat:
out_() << "503 5.5.1 sequence error, expecting BDAT\r\n" << std::flush;
LOG(WARNING) << "'RCPT TO' during BDAT transfer"
<< (sock_.has_peername() ? " from " : "") << client_;
return;
case xact_step::rset:
out_() << "503 5.5.1 sequence error, expecting RSET\r\n" << std::flush;
LOG(WARNING) << "error state must be cleared with a RSET"
<< (sock_.has_peername() ? " from " : "") << client_;
return;
}
if (!verify_rcpt_params_(parameters))
return;
if (!verify_recipient_(forward_path))
return;
if (!smtputf8_ && !is_ascii(forward_path.local_part())) {
LOG(WARNING) << "non ascii forward_path \"" << forward_path
<< "\" without SMTPUTF8 paramater";
}
if (forward_path_.size() >= Config::max_recipients_per_message) {
out_() << "452 4.5.3 too many recipients\r\n" << std::flush;
LOG(WARNING) << "too many recipients <" << forward_path << ">";
return;
}
// no check for dups, postfix doesn't
forward_path_.emplace_back(std::move(forward_path));
Mailbox const& rcpt_to_mbx = forward_path_.back();
LOG(INFO) << "RCPT TO:<" << rcpt_to_mbx << ">";
// No flush RFC-2920 section 3.1, this could be part of a command group.
out_() << "250 2.1.5 RCPT TO OK\r\n";
state_ = xact_step::data;
}
// The headers Return-Path:, Received-SPF:, and Received: are returned
// as a string.
std::string Session::added_headers_(MessageStore const& msg)
{
auto const protocol{[this]() {
if (sock_.tls() && !extensions_) {
LOG(WARNING) << "TLS active without extensions";
}
// <https://www.iana.org/assignments/mail-parameters/mail-parameters.xhtml#mail-parameters-5>
if (smtputf8_)
return sock_.tls() ? "UTF8SMTPS" : "UTF8SMTP";
else if (sock_.tls())
return "ESMTPS";
else if (extensions_)
return "ESMTP";
else
return "SMTP";
}()};
fmt::memory_buffer headers;
// Return-Path:
fmt::format_to(std::back_inserter(headers), "Return-Path: <{}>\r\n",
reverse_path_.as_string());
// Received-SPF:
if (!spf_received_.empty()) {
fmt::format_to(std::back_inserter(headers), "{}\r\n", spf_received_);
}
// Received:
// <https://tools.ietf.org/html/rfc5321#section-4.4>
fmt::format_to(std::back_inserter(headers), "Received: from {}",
client_identity_.utf8());
if (sock_.has_peername()) {
fmt::format_to(std::back_inserter(headers), " ({})", client_);
}
fmt::format_to(std::back_inserter(headers), "\r\n\tby {} with {} id {}",
server_identity_.utf8(), protocol, msg.id().as_string_view());
if (forward_path_.size()) {
fmt::format_to(std::back_inserter(headers), "\r\n\tfor <{}>",
forward_path_[0].as_string());
// From <https://datatracker.ietf.org/doc/html/rfc5321#section-4.4>:
// “If the FOR clause appears, it MUST contain exactly one <path>
// entry, even when multiple RCPT commands have been given. Multiple
// <path>s raise some security issues and have been deprecated, see
// Section 7.2.”
// for (auto i = 1u; i < forward_path_.size(); ++i)
// fmt::format_to(headers, ",\r\n\t <{}>", forward_path_[i]);
}
std::string const tls_info{sock_.tls_info()};
if (tls_info.length()) {
fmt::format_to(std::back_inserter(headers), "\r\n\t({})", tls_info);
}
fmt::format_to(std::back_inserter(headers), ";\r\n\t{}\r\n",
msg.when().as_string_view());
return fmt::to_string(headers);
}
namespace {
bool lookup_domain(CDB& cdb, Domain const& domain)
{
if (!domain.empty()) {
if (cdb.contains(domain.ascii())) {
return true;
}
if (domain.is_unicode() && cdb.contains(domain.utf8())) {
return true;
}
}
return false;
}
} // namespace
std::tuple<Session::SpamStatus, std::string> Session::spam_status_()
{
if (spf_result_ == SPF::Result::FAIL && !ip_allowed_) {
LOG(INFO) << "spam since SPF failed";
return {SpamStatus::spam, "SPF failed"};
}
// These should have already been rejected by verify_client_().
if ((reverse_path_.domain().ascii() == "localhost.local") ||
(reverse_path_.domain().ascii() == "localhost")) {
LOG(INFO) << "spam since reverse path is localhost";
return {SpamStatus::spam, "bogus reverse_path"};
}
std::vector<std::string> why_ham;
// Anything enciphered tastes a lot like ham.
if (sock_.tls())
why_ham.emplace_back("they used TLS");
if (spf_result_ == SPF::Result::PASS) {
if (lookup_domain(allow_, spf_sender_domain_)) {
why_ham.emplace_back(fmt::format("SPF sender domain ({}) is allowed",
spf_sender_domain_.utf8()));
}
else {
auto tld_dom{tld_db_.get_registered_domain(spf_sender_domain_.ascii())};
if (tld_dom && allow_.contains(tld_dom)) {
why_ham.emplace_back(fmt::format(
"SPF sender registered domain ({}) is allowed", tld_dom));
}
}
}
else {
LOG(INFO) << "not ham since SPF not PASS";
}
if (fcrdns_allowed_) {
why_ham.emplace_back(
fmt::format("FCrDNS (or it's registered domain) is allowed"));
}
else {
LOG(INFO) << "not ham since fcrdns not allowed";
}
if (!why_ham.empty())
return {SpamStatus::ham,
fmt::format("{}", fmt::join(std::begin(why_ham), std::end(why_ham),
", and "))};
return {SpamStatus::spam, "it's not ham"};
}
static std::string folder(Session::SpamStatus status,
std::vector<Mailbox> const& forward_path,
Mailbox const& reverse_path)
{
if (reverse_path ==
Mailbox("[email protected]"))
return ".Gmail";
if (reverse_path == Mailbox("[email protected]"))
return ".smtp";
struct assignment {
std::string_view local_part;
std::string_view folder;
};
assignment assignments[] = {
{"bootstrappable", ".bootstrappable"},
{"coreboot.org", ".coreboot"},
{"dmarc", ".dmarc"},
{"dns-privacy", ".dns-privacy"},
{"dnsmasq", ".INBOX.DNSmasq"},
{"emailcore", ".emailcore"},
{"fucking-facebook", ".FB"},
{"gene-ebay", ".EBay"},
{"i-hate-facebook", ".FB"},
{"i-hate-linked-in", ".linkedin"},
{"mailop", ".INBOX.mailop"},
{"modelfkeyboards.com", ""},
{"nest", ".INBOX.Nest"},
{"opendmarc-dev", ".dmarc"},
{"opendmarc-users", ".dmarc"},
{"papasys.com", ".INBOX.PAPA"},
{"postmaster-rua", ".INBOX.rua"},
{"quic=ietf.org", ".INBOX.quic"},
{"[email protected]", ".INBOX.shadowserver"},
{"theatlantic.com", ""},
{"time-nutz", ".time-nutz"},
{"zfsonlinux.topicbox.com", ".INBOX.zfs"},
};
for (auto ass : assignments) {
if (iequal(forward_path[0].local_part(), ass.local_part))
return std::string(ass.folder);
}
if (iends_with(forward_path[0].local_part(), "-at-duck"))
return ".JunkDuck";
if (status == Session::SpamStatus::spam)
return ".Junk";
return "";
}
bool Session::msg_new()
{
CHECK((state_ == xact_step::data) || (state_ == xact_step::bdat));
auto const& [status, reason]{spam_status_()};
LOG(INFO) << ((status == SpamStatus::ham) ? "ham since " : "spam since ")
<< reason;
// All sources of ham get a fresh 5 minute timeout per message.
if (status == SpamStatus::ham) {
if ((!FLAGS_immortal) && (getenv("GHSMTP_IMMORTAL") == nullptr))
alarm(5 * 60);
}
msg_ = std::make_unique<MessageStore>();
if (!FLAGS_max_write)
FLAGS_max_write = max_msg_size();
try {
msg_->open(server_id_(), FLAGS_max_write,
folder(status, forward_path_, reverse_path_));
auto const hdrs{added_headers_(*(msg_.get()))};
msg_->write(hdrs);
// fmt::memory_buffer spam_status;
// fmt::format_to(spam_status, "X-Spam-Status: {}, {}\r\n",
// ((status == SpamStatus::spam) ? "Yes" : "No"), reason);
// msg_->write(spam_status.data(), spam_status.size());
LOG(INFO) << "Spam-Status: "
<< ((status == SpamStatus::spam) ? "Yes" : "No") << ", "
<< reason;
return true;
}
catch (std::system_error const& e) {
switch (errno) {
case ENOSPC:
out_() << "452 4.3.1 insufficient system storage\r\n" << std::flush;
LOG(ERROR) << "no space";
msg_->trash();
msg_.reset();
return false;
default:
out_() << "451 4.0.0 mail system error\r\n" << std::flush;
LOG(ERROR) << "errno==" << errno << ": " << strerror(errno);
LOG(ERROR) << e.what();
msg_->trash();
msg_.reset();
return false;
}
}
catch (std::exception const& e) {
out_() << "451 4.0.0 mail system error\r\n" << std::flush;
LOG(ERROR) << e.what();
msg_->trash();
msg_.reset();
return false;
}
out_() << "451 4.0.0 mail system error\r\n" << std::flush;
LOG(ERROR) << "msg_new failed with no exception caught";
msg_->trash();
msg_.reset();
return false;
}
bool Session::msg_write(char const* s, std::streamsize count)
{
if ((state_ != xact_step::data) && (state_ != xact_step::bdat))
return false;
if (!msg_)
return false;
try {
if (msg_->write(s, count))
return true;
}
catch (std::system_error const& e) {
switch (errno) {
case ENOSPC:
out_() << "452 4.3.1 insufficient system storage\r\n" << std::flush;
LOG(ERROR) << "no space";
msg_->trash();
msg_.reset();
return false;
default:
out_() << "451 4.0.0 mail system error\r\n" << std::flush;
LOG(ERROR) << "errno==" << errno << ": " << strerror(errno);
LOG(ERROR) << e.what();
msg_->trash();
msg_.reset();
return false;
}
}
catch (std::exception const& e) {
out_() << "451 4.0.0 mail system error\r\n" << std::flush;
LOG(ERROR) << e.what();
msg_->trash();
msg_.reset();
return false;
}
out_() << "451 4.0.0 mail system error\r\n" << std::flush;
LOG(ERROR) << "msg_write failed with no exception caught";
msg_->trash();
msg_.reset();
return false;
}
bool Session::data_start()
{
last_in_group_("DATA");
switch (state_) {
case xact_step::helo:
out_() << "503 5.5.1 sequence error, expecting HELO/EHLO\r\n" << std::flush;
LOG(WARNING) << "'DATA' before HELO/EHLO"
<< (sock_.has_peername() ? " from " : "") << client_;
return false;
case xact_step::mail:
out_() << "503 5.5.1 sequence error, expecting MAIL\r\n" << std::flush;
LOG(WARNING) << "'DATA' before 'MAIL FROM'"
<< (sock_.has_peername() ? " from " : "") << client_;
return false;
case xact_step::rcpt:
/******************************************************************
<https://tools.ietf.org/html/rfc5321#section-3.3> says:
The DATA command can fail at only two points in the protocol
exchange:
If there was no MAIL, or no RCPT, command, or all such commands
were rejected, the server MAY return a "command out of sequence"
(503) or "no valid recipients" (554) reply in response to the DATA
command. If one of those replies (or any other 5yz reply) is
received, the client MUST NOT send the message data; more
generally, message data MUST NOT be sent unless a 354 reply is
received.
However, <https://tools.ietf.org/html/rfc2033#section-4.2> says:
The additional restriction is that when there have been no
successful RCPT commands in the mail transaction, the DATA command
MUST fail with a 503 reply code.
Therefore I will send the reply code (503) that is valid for both,
and do the same for the BDAT case.
*******************************************************************/
out_() << "503 5.5.1 sequence error, expecting RCPT\r\n" << std::flush;
LOG(WARNING) << "no valid recipients"
<< (sock_.has_peername() ? " from " : "") << client_;
return false;
case xact_step::data: break;
case xact_step::bdat:
out_() << "503 5.5.1 sequence error, expecting BDAT\r\n" << std::flush;
LOG(WARNING) << "'DATA' during BDAT transfer"
<< (sock_.has_peername() ? " from " : "") << client_;
return false;
case xact_step::rset:
out_() << "503 5.5.1 sequence error, expecting RSET\r\n" << std::flush;
LOG(WARNING) << "error state must be cleared with a RSET"
<< (sock_.has_peername() ? " from " : "") << client_;
return false;
}
if (binarymime_) {
out_() << "503 5.5.1 sequence error, DATA does not support BINARYMIME\r\n"
<< std::flush;
LOG(WARNING) << "DATA does not support BINARYMIME";
state_ = xact_step::rset; // RFC 3030 section 3 page 5
return false;
}
if (!msg_new()) {
LOG(ERROR) << "msg_new() failed";
return false;
}
out_() << "354 go, end with <CR><LF>.<CR><LF>\r\n" << std::flush;
LOG(INFO) << "DATA";
return true;
}
bool Session::do_deliver_()
{
CHECK(msg_);