/
Mail.pm
562 lines (481 loc) · 17 KB
/
Mail.pm
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
#
# This program may be distributed under the terms of the GNU General
# Public License, Version 2.
#
=head1 NAME
Mail::MIMEDefang::Mail - Mail and SMTP related methods for email filters
=head1 DESCRIPTION
Mail::MIMEDefang::Mail are a set of methods that can be called
from F<mimedefang-filter> to send email messages or to run SMTP checks.
=head1 METHODS
=over 4
=cut
package Mail::MIMEDefang::Mail;
use strict;
use warnings;
use IO::Socket::SSL;
use Mail::MIMEDefang;
use Mail::MIMEDefang::MIME;
use Mail::MIMEDefang::Utils;
require Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw( resend_message_one_recipient resend_message_specifying_mode
resend_message pretty_print_mail md_check_against_smtp_server );
=item resend_message_one_recipient
Method that re-sends the message as if it came from original sender to
a single recipient.
=cut
#***********************************************************************
# %PROCEDURE: resend_message_one_recipient
# %ARGUMENTS:
# recip -- a single recipient
# deliverymode -- optional sendmail delivery mode arg (default "-odd")
# %RETURNS:
# True on success; false on failure.
# %DESCRIPTION:
# Re-sends the message (as if it came from original sender) to
# a single recipient.
#***********************************************************************
sub resend_message_one_recipient {
my($recip, $deliverymode) = @_;
return resend_message_specifying_mode($deliverymode, [ $recip ]);
}
=item resend_message_specifying_mode
Method that re-sends the message as if it came from original sender to
a list of recipients.
=cut
#***********************************************************************
# %PROCEDURE: resend_message_specifying_mode
# %ARGUMENTS:
# deliverymode -- delivery mode
# recipients -- reference to list of recipients to resend message to.
# %RETURNS:
# True on success; false on failure.
# %DESCRIPTION:
# Re-sends the message (as if it came from original sender) to
# a list of recipients.
#***********************************************************************
sub resend_message_specifying_mode {
my($deliverymode, $recips) = @_;
return 0 if (!in_message_context("resend_message_specifying_mode"));
$deliverymode = "-odd" unless defined($deliverymode);
if ($deliverymode ne "-odb" &&
$deliverymode ne "-odq" &&
$deliverymode ne "-odd" &&
$deliverymode ne "-odi") {
$deliverymode = "-odd";
}
# Fork and exec for safety instead of involving shell
my $pid = open(CHILD, "|-");
if (!defined($pid)) {
md_syslog('err', "Cannot fork to resend message");
return 0;
}
if ($pid) { # In the parent -- pipe mail message to the child
unless (open(IN, "<", "INPUTMSG")) {
md_syslog('err', "Could not open INPUTMSG in resend_message: $!");
return 0;
}
# Preserve relay's IP address if possible...
if ($ValidateIPHeader =~ /^X-MIMEDefang-Relay/) {
print CHILD "$ValidateIPHeader: $RelayAddr\n"
}
# Synthesize a Received: header
print CHILD synthesize_received_header();
# Copy message over
while(<IN>) {
print CHILD;
}
close(IN);
if (!close(CHILD)) {
if ($!) {
md_syslog('err', "sendmail failure in resend_message: $!");
} else {
md_syslog('err', "sendmail non-zero exit status in resend_message: $?");
}
return 0;
}
return 1;
}
# In the child -- invoke Sendmail
# Direct stdout to stderr, or we will screw up communication with
# the multiplexor..
open(STDOUT, ">&STDERR");
my(@cmd);
if ($Sender eq "") {
push(@cmd, "-f<>");
} else {
push(@cmd, "-f$Sender");
}
push(@cmd, $deliverymode);
push(@cmd, "-Ac");
push(@cmd, "-oi");
push(@cmd, "--");
push @cmd, @$recips;
# In curlies to silence Perl warning...
my $sm;
$sm = $Features{'Path:SENDMAIL'};
{ exec($sm, @cmd); }
# exec failed!
md_syslog('err', "Could not exec $sm: $!");
exit(1);
# NOTREACHED
}
=item resend_message
Method that re-sends the message as if it came from original sender to
a list of recipients.
=cut
#***********************************************************************
# %PROCEDURE: resend_message
# %ARGUMENTS:
# recipients -- list of recipients to resend message to.
# %RETURNS:
# True on success; false on failure.
# %DESCRIPTION:
# Re-sends the message (as if it came from original sender) to
# a list of recipients.
#***********************************************************************
sub resend_message {
return 0 if (!in_message_context("resend_message"));
my(@recips);
@recips = @_;
return resend_message_specifying_mode("-odd", \@recips);
}
=item pretty_print_mail
Method that makes a pretty-printed version of the e-mail body no longer
than size characters.
=cut
#***********************************************************************
# %PROCEDURE: pretty_print_mail
# %ARGUMENTS:
# e -- a MIME::Entity object
# size -- maximum size of value to return in characters
# chunk -- optional; used in recursive calls only. Do not supply as arg.
# depth -- used in recursive calls only. Do not supply as arg.
# %RETURNS:
# A "pretty-printed" version of the e-mail body
# %DESCRIPTION:
# Makes a pretty-printed version of the e-mail body no longer than size
# characters. This odd-looking function is used by CanIt...
#***********************************************************************
sub pretty_print_mail {
my($e, $size, $chunk, $depth) = @_;
$chunk = "" unless defined($chunk);
$depth = 0 unless defined($depth);
my(@parts) = $e->parts;
my($type) = $e->mime_type;
my($fname) = takeStabAtFilename($e);
$fname = "; filename=$fname" if ($fname ne "");
my($spaces) = " " x $depth;
$chunk .= "\n$spaces" . "[Part: ${type}${fname}]\n\n";
if ($#parts >= 0) {
my($part);
foreach $part (@parts) {
$chunk = pretty_print_mail($part, $size, $chunk, $depth+1);
last if (length($chunk) >= $size);
}
} else {
return $chunk unless ($type =~ m+^text/+);
my($body) = $e->bodyhandle;
return $chunk unless (defined($body));
my($path) = $body->path;
return $chunk unless (defined($path));
return $chunk unless (open(IN, "<", "$path"));
while (<IN>) {
$chunk .= $_;
last if (length($chunk) >= $size);
}
close(IN);
}
return $chunk;
}
=item get_smtp_return_code
Method that reads return codes from SMTP server, returns a four-element
list:(retval, code, dsn, text), where code is a 3-digit SMTP code.
Retval is 'CONTINUE', 'TEMPFAIL' or 'REJECT'.
=cut
#***********************************************************************
# %PROCEDURE: get_smtp_return_code
# %ARGUMENTS:
# sock -- a socket connected to an SMTP server
# recip -- the recipient we're inquring about
# server -- the server we're querying
# %RETURNS:
# A four-element list:(retval, code, dsn, text),
# where code is a 3-digit SMTP code.
# Retval is 'CONTINUE', 'TEMPFAIL' or 'REJECT'.
# %DESCRIPTION:
# Reads return codes from SMTP server
#***********************************************************************
sub get_smtp_return_code {
my($sock, $recip, $server) = @_;
my($line, $code, $text, $retval, $dsn);
while (defined ($line = $sock->getline())) {
# Chew up all trailing white space, including CR
$line =~ s/\s+$//;
if (($line =~ /^\d\d\d$/) or ($line =~ /^\d\d\d\s/)) {
$line =~ /^(\d\d\d)\s*(.*)$/;
$code = $1;
$text = $2;
# Check for DSN
if ($text =~ /^(\d\.\d{1,3}\.\d{1,3})\s+(.*)$/) {
$dsn = $1;
$text = $2;
} else {
$dsn = "";
}
if ($code =~ /^[123]/) {
$retval = 'CONTINUE';
} elsif ($code =~ /^4/) {
md_syslog('info', "get_smtp_return_code: for $recip on $server returned $code $dsn $text");
$retval = 'TEMPFAIL';
} elsif ($code =~ /^5/) {
md_syslog('info', "get_smtp_return_code: for $recip on $server returned $code $dsn $text");
$retval = 'REJECT';
} else {
md_syslog('warning', "get_smtp_return_code: Invalid SMTP reply code $code from server $server for $recip");
$retval = 'TEMPFAIL';
}
return ($retval, $code, $dsn, $text);
}
}
my $msg;
if( defined $line ) {
$msg = "get_smtp_return_code: Invalid response [$line] from SMTP server";
md_syslog('info', "get_smtp_return_code: Check for $recip on $server returned invalid response [$line]");
} else {
$msg = "get_smtp_return_code: Empty response from SMTP server";
md_syslog('info', "get_smtp_return_code: for $recip on $server returned an empty response");
}
return ('TEMPFAIL', "451", "4.3.0", $msg );
}
=item get_smtp_extensions
Method that checks SMTP server's supported extensions.
It expects EHLO to have been sent already (artifact of get_smtp_return_code).
The sub returns a four-element list:(retval, code, dsn, exts)
=over 4
=item * retval is 'CONTINUE', 'TEMPFAIL', or 'REJECT'.
=item * code is a 3-digit SMTP code.
=item * dsn is an extended SMTP status code
=item * exts is a hash of EXTNAME->EXTOPTS
=back
=cut
#***********************************************************************
# %PROCEDURE: get_smtp_extensions
# %ARGUMENTS:
# sock -- a socket connected to an SMTP server
# server -- the server we're querying
# %RETURNS:
# A four-element list:(retval, code, dsn, exts)
# retval is 'CONTINUE', 'TEMPFAIL', or 'REJECT'.
# code is a 3-digit SMTP code.
# dsn is an extended SMTP status code
# exts is a hash of EXTNAME->EXTOPTS
# %DESCRIPTION:
# Checks SMTP server's supported extensions.
# Expects EHLO to have been sent already (artifact of cribbing get_smtp_return_code)
#***********************************************************************
sub get_smtp_extensions {
my($sock, $server) = @_;
my($ext, $msg, $delim, $line, $code, $text, $retval, $dsn);
my %exts;
my $LineNum=0;
$delim='-';
while ( ($delim eq '-' ) && (defined ($line = $sock->getline()))) {
# Chew up all trailing white space, including CR
$line =~ s/\s+$//;
# Line can be:
# '[45]xy $ERROR' Failure. Don't really care why.
# '250-hostname' Initial line in multi-line response
# '250 hostname' ONLY line in successful response
# '250-$EXTNAME $EXTOPTS' Advertisement of extension with options
# '250 $EXTNAME $EXTOPTS' Advertisement of extension with options (Final line)
$line =~ m/([245][0-9][0-9])([- ])([^ ]+) *(.*)/ or return ('TEMPFAIL', "451", "4.3.0", "$server said: $line");
$code=$1;
$delim=$2;
$ext=$3;
$text=$4;
# uncomment to debug parsing
# md_syslog('debug',"get_smtp_extensions: line $LineNum: code=$code, delim=$delim, ext=$ext, text=$text");
if ( $LineNum == 0 ) {
$exts{'hostname'} = $3;
$LineNum++;
next;
}
$exts{$ext} = $text;
$LineNum++;
}
$code =~ m/2../ and return ('CONTINUE', "$code", "2.5.0", %exts );
$code =~ m/4../ and return ('TEMPFAIL', "$code", "4.0.0", %exts );
$code =~ m/5../ and return ('REJECT', "$code", "5.0.0", %exts );
}
=item md_check_against_smtp_server
Method that verifies a recipient against another SMTP server by issuing a
HELO / MAIL FROM: / RCPT TO: / QUIT sequence.
The method returns:
=over 4
=item * ('CONTINUE', "OK") if recipient is OK
=item * ('TEMPFAIL', "err") if temporary failure
=item * ('REJECT', "err") if recipient is not OK.
=back
=cut
#***********************************************************************
# %PROCEDURE: md_check_against_smtp_server
# %ARGUMENTS:
# sender -- sender e-mail address
# recip -- recipient e-mail address
# helo -- string to put in "HELO" command
# server -- SMTP server to try.
# port -- optional: Port to connect on (defaults to 25)
# %RETURNS:
# ('CONTINUE', "OK") if recipient is OK
# ('TEMPFAIL', "err") if temporary failure
# ('REJECT', "err") if recipient is not OK.
# %DESCRIPTION:
# Verifies a recipient against another SMTP server by issuing a
# HELO / MAIL FROM: / RCPT TO: / QUIT sequence
#***********************************************************************
sub md_check_against_smtp_server {
my($sender, $recip, $helo, $server, $port) = @_;
my($code, $text, $dsn, $retval);
$port = 'smtp(25)' unless defined($port);
# Add angle-brackets if needed
if (!($sender =~ /^<.*>$/)) {
$sender = "<$sender>";
}
if (!($recip =~ /^<.*>$/)) {
$recip = "<$recip>";
}
# Set SSL_startHandshake to start in plain mode,
# SSL_verify_mode to SSL_VERIFY_NONE to make the check work
# with self-signed certificates and SSL_hostname for SNI
my $sock;
my $plaintext = 0;
$sock = IO::Socket::SSL->new(PeerAddr => $server,
SSL_startHandshake => 0,
SSL_verify_mode => SSL_VERIFY_NONE,
SSL_hostname => "$server",
SSL_version => 'SSLv23',
SSL_cipher_list => 'ALL',
PeerPort => $port,
Proto => 'tcp',
Timeout => 25);
if (!defined($sock)) {
# fallback to plaintext if SSL connection doesn't succeed
md_syslog('warning', 'Falling back to plaintext connection');
$sock = IO::Socket::INET->new(PeerAddr => $server,
PeerPort => $port,
Proto => 'tcp',
Timeout => 25);
$plaintext = 1;
if(!defined($sock)) {
return ('TEMPFAIL', "Could not connect to other SMTP server $server, error=$!");
}
}
($retval, $code, $dsn, $text) = get_smtp_return_code($sock, $recip, $server);
if ($retval ne 'CONTINUE') {
$sock->print("QUIT\r\n");
$sock->flush();
# Swallow return value
get_smtp_return_code($sock, $recip, $server);
$sock->close();
return ($retval, $text, $code, $dsn);
}
# If the banner contains our host name, there's a loop!
# However, don't check if $server is explicitly 127.0.0.1
# because presumably that indicates the caller knows
# what he or she is doing.
if ($server ne '127.0.0.1' && $server ne '::1') {
my $host_expr = quotemeta(Mail::MIMEDefang::Net::get_host_name());
if ($text =~ /^$host_expr\b/) {
$sock->print("QUIT\r\n");
$sock->flush();
# Swallow return value
get_smtp_return_code($sock, $recip, $server);
$sock->close();
return('REJECT', "Verification server loop! Trying to verify $recip against myself!",
554, '5.4.6');
}
}
$sock->print("EHLO $helo\r\n");
$sock->flush();
my %exts;
my $ext;
($retval, $code, $dsn, %exts) = get_smtp_extensions($sock, $recip, $server);
if (($plaintext eq 1) or ($retval ne 'CONTINUE')) {
$sock->print("HELO $helo\r\n");
} else {
# Uncomment to debug (and/or uncomment similar line in get_smtp_extensions)
# foreach $ext ( keys %exts ) {
# md_syslog('debug',"md_check_against_smtp_server extension: $ext $exts{$ext}");
# }
if (exists $exts{'STARTTLS'}) {
# send STARTTLS command and read response
$sock->print("STARTTLS\r\n");
($retval, $code, $dsn, $text) = get_smtp_return_code($sock, $recip, $server);
if ($retval ne 'CONTINUE') {
$sock->print("QUIT\r\n");
$sock->flush();
# Swallow return value
get_smtp_return_code($sock, $recip, $server);
$sock->close();
return ($retval, $text, $code, $dsn);
}
# if response was successful we can upgrade the socket to SSL now:
if ( $sock->connect_SSL ) {
md_syslog('debug',"md_check_against_smtp_server: start_SSL succeeded!");
# send inside EHLO
$sock->print("EHLO $helo\r\n");
} else {
#back off from using STARTTLS
$sock->stop_SSL;
no warnings 'once';
md_syslog('debug',"md_check_against_smtp_server: $server offers STARTTLS but fails with error $IO::Socket::SSL::SSL_ERROR. Falling back to plaintext...");
$sock->print("EHLO $helo\r\n");
}
} else {
md_syslog('debug',"md_check_against_smtp_server: STARTTLS not available");
$sock->print("RSET\r\n");
$sock->flush();
# Swallow return value
get_smtp_return_code($sock, $recip, $server);
$sock->print("EHLO $helo\r\n");
}
}
# At this point we've either sent a fallback HELO, fallback EHLO, or internal EHLO.
# so, get the code...
($retval, $code, $dsn, $text) = get_smtp_return_code($sock, $recip, $server);
if ($retval ne 'CONTINUE') {
$sock->print("QUIT\r\n");
$sock->flush();
# Swallow return value
get_smtp_return_code($sock, $recip, $server);
$sock->close();
return ($retval, $text, $code, $dsn);
}
md_syslog('debug',"md_check_against_smtp_server: Checking sender $sender");
$sock->print("MAIL FROM:$sender\r\n");
$sock->flush();
($retval, $code, $dsn, $text) = get_smtp_return_code($sock, $recip, $server);
if ($retval ne 'CONTINUE') {
$sock->print("QUIT\r\n");
$sock->flush();
# Swallow return value
get_smtp_return_code($sock, $recip, $server);
$sock->close();
return ($retval, $text, $code, $dsn);
}
md_syslog('debug',"md_check_against_smtp_server: Checking recipient $recip");
$sock->print("RCPT TO:$recip\r\n");
$sock->flush();
($retval, $code, $dsn, $text) = get_smtp_return_code($sock, $recip, $server);
$sock->print("QUIT\r\n");
$sock->flush();
# Swallow return value
get_smtp_return_code($sock, $recip, $server);
$sock->close();
return ($retval, $text, $code, $dsn);
}
=back
=cut
1;