-
Notifications
You must be signed in to change notification settings - Fork 2
/
swaks
executable file
·3688 lines (2960 loc) · 149 KB
/
swaks
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
#!/usr/bin/perl
# use 'swaks --help' to view documentation for this program
#
# Homepage: http://jetmore.org/john/code/swaks/
# Online Docs: http://jetmore.org/john/code/swaks/latest/doc/ref.txt
# http://jetmore.org/john/code/swaks/faq.html
# Announce List: send mail to updates-swaks@jetmore.net
# Project RSS: http://jetmore.org/john/blog/c/swaks/feed/
# Google+: https://plus.google.com/u/0/110270727761256449657
# Twitter: http://www.twitter.com/SwaksSMTP
use strict;
$| = 1;
my($p_name) = $0 =~ m|/?([^/]+)$|;
my $p_version = build_version("20130209.0", '$Id: swaks 332 2013-02-09 19:39:32Z jetmore $');
my $p_usage = "Usage: $p_name [--help|--version] (see --help for details)";
my $p_cp = <<'EOM';
Copyright (c) 2003-2008,2010-2013 John Jetmore <jj33@pobox.com>
This program 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 2 of the License, or
(at your option) any later version.
This program 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 this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
EOM
# before we do anything else, check for --help
ext_usage();
# Get all input provided to our program, via file, env, command line, etc
my %O = %{ load_args() };
# Get our functional dependencies and then print and exit early if requested
load_dependencies();
if ($O{get_support}) {
test_support();
exit(0);
}
# This 'synthetic' command line used for debug and reference
$G::cmdline = reconstruct_options(\%O);
# We need to fix things up a bit and set a couple of global options
my $opts = process_args(\%O);
if ($G::dump_args) {
test_support();
print "\n";
my $running_state = get_running_state($opts);
# --dump is intended as a debug tool for swaks internally. Always,
# unconditionally, show the user's auth password if one is given
$running_state =~ s%'PROVIDED_BUT_REMOVED'%shquote($opts->{a_pass})%ge;
print $running_state;
print "\nDATA Info:\n"
. " data = <<.\n$opts->{data}\n";
exit(0);
}
# we're going to abstract away the actual connection layer from the mail
# process, so move the act of connecting into its own sub. The sub will
# set info in global hash %G::link
# XXX instead of passing raw data, have processs_opts create a link_data
# XXX hash that we can pass verbatim here
open_link();
sendmail($opts->{from}, $opts->{to}, $opts->{helo}, $opts->{data},
$opts->{a_user}, $opts->{a_pass}, $opts->{a_type});
teardown_link();
exit(0);
sub teardown_link {
if ($G::link{type} eq 'socket-inet' || $G::link{type} eq 'socket-unix') {
# XXX need anything special for tls teardown?
close($G::link{sock});
ptrans(11, "Connection closed with remote host.");
} elsif ($G::link{type} eq 'pipe') {
delete($SIG{PIPE});
$SIG{CHLD} = 'IGNORE';
close($G::link{sock}{wr});
close($G::link{sock}{re});
ptrans(11, "Connection closed with child process.");
}
}
sub open_link {
if ($G::link{type} eq 'socket-inet') {
ptrans(11, "Trying $G::link{server}:$G::link{port}...");
$@ = "";
my @extra_options = ();
push(@extra_options, "LocalAddr", $G::link{lint}) if ($G::link{lint});
push(@extra_options, "LocalPort", $G::link{lport}) if ($G::link{lport});
# INET6 also support v4, so use it for everything if it's available. That
# allows the module to handle A vs AAAA records on domain lookups where te
# user hasn't set a specific ip version to be used. If INET6 isn't available
# and it's a domain that only has AAAA records, INET will just handle it like
# a bogus record and we just won't be able to connect
if (avail("ipv6")) {
if ($G::link{force_ipv6}) {
push(@extra_options, "Domain", Socket::AF_INET6() );
} elsif ($G::link{force_ipv4}) {
push(@extra_options, "Domain", Socket::AF_INET() );
}
$G::link{sock} = IO::Socket::INET6->new(
PeerAddr => $G::link{server},
PeerPort => $G::link{port},
Proto => 'tcp',
Timeout => $G::link{timeout},
@extra_options
);
} else {
$G::link{sock} = IO::Socket::INET->new(
PeerAddr => $G::link{server},
PeerPort => $G::link{port},
Proto => 'tcp',
Timeout => $G::link{timeout},
@extra_options
);
}
if ($@) {
ptrans(12, "Error connecting" . ($G::link{lint} ? " $G::link{lint}" : '') .
" to $G::link{server}:$G::link{port}:\n\t$@");
exit(2);
}
ptrans(11, "Connected to $G::link{server}.");
} elsif ($G::link{type} eq 'socket-unix') {
ptrans(11, "Trying $G::link{sockfile}...");
$SIG{PIPE} = 'IGNORE';
$@ = "";
$G::link{sock} = IO::Socket::UNIX->new(Peer => $G::link{sockfile}, Timeout => $G::link{timeout});
if ($@) {
ptrans(12, "Error connecting to $G::link{sockfile}:\n\t$@");
exit(2);
}
ptrans(11, "Connected to $G::link{sockfile}.");
} elsif ($G::link{type} eq 'pipe') {
$SIG{PIPE} = 'IGNORE';
$SIG{CHLD} = 'IGNORE';
ptrans(11, "Trying pipe to $G::link{process}...");
eval{ open2($G::link{sock}{re}, $G::link{sock}{wr}, $G::link{process}); };
if ($@) {
ptrans(12, "Error connecting to $G::link{process}:\n\t$@");
exit(2);
}
select((select($G::link{sock}{wr}), $| = 1)[0]);
select((select($G::link{sock}{re}), $| = 1)[0]);
ptrans(11, "Connected to $G::link{process}.");
} else {
ptrans(12, "Unknown or unimplemented connection type $G::link{type}");
exit(3);
}
}
sub sendmail {
my $from = shift; # envelope-from
my $to = shift; # envelope-to
my $helo = shift; # who am I?
my $data = shift; # body of message (content after DATA command)
my $a_user = shift; # what user to auth with?
my $a_pass = shift; # what pass to auth with
my $a_type = shift; # what kind of auth (this must be set to to attempt)
my $ehlo = {}; # If server is esmtp, save advertised features here
# start up tls if -tlsc specified
if ($G::tls_on_connect) {
if (start_tls()) {
tls_post_start();
# QUIT here if the user has asked us to do so
do_smtp_quit(1, 0) if ($G::quit_after eq 'tls');
} else {
ptrans(12, "TLS startup failed ($G::link{tls}{res})");
exit(29);
}
}
# read the server's 220 banner
do_smtp_gen(undef, '220') || do_smtp_quit(1, 21);
# QUIT here if the user has asked us to do so
do_smtp_quit(1, 0) if ($G::quit_after eq 'connect');
# Send a HELO string
do_smtp_helo($helo, $ehlo, $G::protocol) || do_smtp_quit(1, 22);
# QUIT here if the user has asked us to do so
do_smtp_quit(1, 0) if ($G::quit_after eq 'first-helo');
if ($G::xclient{try}) {
# 0 - xclient succeeded normally
# 1 - xclient not advertised
# 2 - xclient advertised but not attempted, mismatch in requested attrs
# 3 - xclient attempted but did not succeed
my $result = do_smtp_xclient($ehlo);
if ($result == 1) {
ptrans(12, "Host did not advertise XCLIENT");
do_smtp_quit(1, 33) if (!$G::xclient{optional});
} elsif ($result == 2) {
ptrans(12, "Host did not advertise requested XCLIENT attributes");
do_smtp_quit(1, 33) if (!$G::xclient{optional});
} elsif ($result == 3) {
ptrans(12, "XCLIENT attempted but failed. Exiting");
do_smtp_quit(1, 33) if ($G::xclient{optional} != 1);
} else {
do_smtp_quit(1, 0) if ($G::quit_after eq 'xclient');
# re-helo if the XCLIENT command succeeded
do_smtp_helo($helo, $ehlo, $G::protocol) || do_smtp_quit(1, 34);
do_smtp_quit(1, 0) if ($G::quit_after eq 'helo');
}
}
# handle TLS here if user has requested it
if ($G::tls) {
# 0 = tls succeeded
# 1 = tls not advertised
# 2 = tls advertised and attempted negotiations failed
# note there's some duplicate logic here (with process_args) but I think
# it's best to do as thorough a job covering the options in both places
# so as to minimize chance of options falling through the cracks
my $result = do_smtp_tls($ehlo);
if ($result == 1) {
ptrans(12, "Host did not advertise STARTTLS");
do_smtp_quit(1, 29) if (!$G::tls_optional);
} elsif ($result == 2) {
ptrans(12, "STARTTLS attempted but failed");
exit(29) if ($G::tls_optional != 1);
}
} elsif ($G::tls_optional == 2 && $ehlo->{STARTTLS}) {
ptrans(12, "TLS requested, advertised, and locally unavailable. Exiting");
do_smtp_quit(1, 29);
}
# QUIT here if the user has asked us to do so
do_smtp_quit(1, 0) if ($G::quit_after eq 'tls');
#if ($G::link{tls}{active} && $ehlo->{STARTTLS}) {
if ($G::link{tls}{active} && !$G::tls_on_connect) {
# According to RFC3207, we need to forget state info and re-EHLO here
$ehlo = {};
do_smtp_helo($helo, $ehlo, $G::protocol) || do_smtp_quit(1, 32);
}
# QUIT here if the user has asked us to do so
do_smtp_quit(1, 0) if ($G::quit_after eq 'helo');
# handle auth here if user has requested it
if ($a_type) {
# 0 = auth succeeded
# 1 = auth not advertised
# 2 = auth advertised but not attempted, no matching auth types
# 3 = auth advertised but not attempted, auth not supported
# 4 = auth advertised and attempted but no type succeeded
# note there's some duplicate logic here (with process_args) but I think
# it's best to do as thorough a job covering the options in both places
# so as to minimize chance of options falling through the cracks
my $result = do_smtp_auth($ehlo, $a_type, $a_user, $a_pass);
if ($result == 1) {
ptrans(12, "Host did not advertise authentication");
do_smtp_quit(1, 28) if (!$G::auth_optional);
} elsif ($result == 2) {
if ($G::auth_type eq 'ANY') {
ptrans(12, "Auth not attempted, no advertised types available");
do_smtp_quit(1, 28) if ($G::auth_optional != 1);
} else {
ptrans(12, "Auth not attempted, requested type not available");
do_smtp_quit(1, 28) if (!$G::auth_optional);
}
} elsif ($result == 3) {
ptrans(12, "Auth advertised but not supported locally");
do_smtp_quit(1, 28) if ($G::auth_optional != 1);
} elsif ($result == 4) {
ptrans(12, "No authentication type succeeded");
do_smtp_quit(1, 28) if ($G::auth_optional != 1);
}
} elsif ($G::auth_optional == 2 && $ehlo->{AUTH}) {
ptrans(12, "Auth requested, advertised, and locally unavailable. Exiting");
do_smtp_quit(1, 28);
}
# QUIT here if the user has asked us to do so
do_smtp_quit(1, 0) if ($G::quit_after eq 'auth');
# send MAIL
do_smtp_mail($from); # failures in this handled by smtp_mail_callback
# QUIT here if the user has asked us to do so
do_smtp_quit(1, 0) if ($G::quit_after eq 'mail');
# send RCPT (sub handles multiple, comma-delimited recips
do_smtp_rcpt($to); # failures in this handled by smtp_rcpt_callback
# note that smtp_rcpt_callback increments
# $G::smtp_rcpt_failures at every failure. This and
# $G::smtp_rcpt_total are used after DATA for LMTP
# QUIT here if the user has asked us to do so
do_smtp_quit(1, 0) if ($G::quit_after eq 'rcpt');
# send DATA
do_smtp_gen('DATA', '354') || do_smtp_quit(1, 25);
# send the actual data
do_smtp_data($data, $G::suppress_data) || do_smtp_quit(1, 26);
# send QUIT
do_smtp_quit(0) || do_smtp_quit(1, 27);
}
sub tls_post_start {
ptrans(11, "TLS started with cipher $G::link{tls}{cipher_string}");
if ($G::link{tls}{local_cert_subject}) {
ptrans(11, "TLS local DN=\"$G::link{tls}{cert_subject}\"");
} else {
ptrans(11, "TLS no local certificate set");
}
ptrans(11, "TLS peer DN=\"$G::link{tls}{cert_subject}\"");
if ($G::tls_get_peer_cert eq 'STDOUT') {
ptrans(11, $G::link{tls}{cert_x509});
} elsif ($G::tls_get_peer_cert) {
open(CERT, ">$G::tls_get_peer_cert") ||
ptrans(12, "Couldn't open $G::tls_get_peer_cert for writing: $!");
print CERT $G::link{tls}{cert_x509}, "\n";
close(CERT);
}
}
sub start_tls {
my %t = (); # This is a convenience var to access $G::link{tls}{...}
$G::link{tls} = \%t;
Net::SSLeay::load_error_strings();
Net::SSLeay::SSLeay_add_ssl_algorithms();
Net::SSLeay::randomize();
if (!($t{con} = Net::SSLeay::CTX_new())) {
$t{res} = "CTX_new(): " . Net::SSLeay::ERR_error_string(Net::SSLeay::ERR_get_error());
return(0);
}
my $ctx_options = &Net::SSLeay::OP_ALL;
if (scalar(@G::tls_protocols)) {
if ($G::tls_protocols[0] =~ /^no_/i) {
foreach my $p (@G::tls_supported_protocols) {
if (grep /^no_$p$/i, @G::tls_protocols) {
no strict "refs";
$ctx_options |= &{"Net::SSLeay::OP_NO_$p"}();
}
}
} else {
foreach my $p (@G::tls_supported_protocols) {
if (!grep /^$p$/i, @G::tls_protocols) {
no strict "refs";
$ctx_options |= &{"Net::SSLeay::OP_NO_$p"}();
}
}
}
}
Net::SSLeay::CTX_set_options($t{con}, $ctx_options);
Net::SSLeay::CTX_set_verify($t{con}, 0x01, 0) if ($G::tls_verify);
if ($G::tls_ca_path) {
my @args = ('', $G::tls_ca_path);
@args = ($G::tls_ca_path, '') if (-f $G::tls_ca_path);
if (!Net::SSLeay::CTX_load_verify_locations($t{con}, @args)) {
$t{res} = "Unable to set set CA path to (" . join(',', @args) . "): "
. Net::SSLeay::ERR_error_string(Net::SSLeay::ERR_get_error());
return(0);
}
} else {
Net::SSLeay::CTX_set_default_verify_paths($t{con});
}
if ($G::tls_cipher) {
if (!Net::SSLeay::CTX_set_cipher_list($t{con}, $G::tls_cipher)) {
$t{res} = "Unable to set cipher list to $G::tls_cipher: "
. Net::SSLeay::ERR_error_string(Net::SSLeay::ERR_get_error());
return(0);
}
}
if ($G::tls_cert && $G::tls_key) {
if (!Net::SSLeay::CTX_use_certificate_file($t{con}, $G::tls_cert, &Net::SSLeay::FILETYPE_PEM)) {
$t{res} = "Unable to add cert file $G::tls_cert to SSL CTX: "
. Net::SSLeay::ERR_error_string(Net::SSLeay::ERR_get_error());
return(0);
}
if (!Net::SSLeay::CTX_use_PrivateKey_file($t{con}, $G::tls_key, &Net::SSLeay::FILETYPE_PEM)) {
$t{res} = "Unable to add key file $G::tls_key to SSL CTX: "
. Net::SSLeay::ERR_error_string(Net::SSLeay::ERR_get_error());
return(0);
}
}
if (!($t{ssl} = Net::SSLeay::new($t{con}))) {
$t{res} = "new(): " . Net::SSLeay::ERR_error_string(Net::SSLeay::ERR_get_error());
return(0);
}
if ($G::link{type} eq 'pipe') {
Net::SSLeay::set_wfd($t{ssl}, fileno($G::link{sock}{wr})); # error check?
Net::SSLeay::set_rfd($t{ssl}, fileno($G::link{sock}{re})); # error check?
} else {
Net::SSLeay::set_fd($t{ssl}, fileno($G::link{sock})); # error check?
}
$t{active} = Net::SSLeay::connect($t{ssl}) == 1 ? 1 : 0;
if (!$t{active}) {
$t{res} = "connect(): " . Net::SSLeay::ERR_error_string(Net::SSLeay::ERR_get_error());
return(0);
}
$t{version} = Net::SSLeay::version($t{ssl});
if ($t{version} == 0x0002) {
$t{version} = "SSLv2";
} elsif ($t{version} == 0x0300) {
$t{version} = "SSLv3";
} elsif ($t{version} == 0x0301) {
$t{version} = "TLSv1";
} elsif ($t{version} == 0x0302) {
$t{version} = "TLSv1.1"; # openssl/tls1.h
} elsif ($t{version} == 0x0303) {
$t{version} = "TLSv1.2"; # openssl/tls1.h
} elsif ($t{version} == 0xFEFF) {
$t{version} = "DTLSv1";
} else {
$t{version} = sprintf("UNKNOWN(0x%04X)", $t{version});
}
$t{cipher} = Net::SSLeay::get_cipher($t{ssl});
if (!$t{cipher}) {
$t{res} = "empty response from get_cipher()";
return(0);
}
$t{cipher_bits} = Net::SSLeay::get_cipher_bits($t{ssl}, undef);
if (!$t{cipher_bits}) {
$t{res} = "empty response from get_cipher_bits()";
return(0);
}
$t{cipher_string} = sprintf("%s:%s:%s", $t{version}, $t{cipher}, $t{cipher_bits});
$t{cert} = Net::SSLeay::get_peer_certificate($t{ssl});
if (!$t{cert}) {
$t{res} = "error response from get_peer_certificate()";
return(0);
}
chomp($t{cert_x509} = Net::SSLeay::PEM_get_string_X509($t{cert}));
$t{cert_subject} = Net::SSLeay::X509_NAME_oneline(Net::SSLeay::X509_get_subject_name($t{cert}));
if ($G::tls_cert && $G::tls_key) {
$t{local_cert} = Net::SSLeay::get_certificate($t{ssl});
chomp($t{local_cert_x509} = Net::SSLeay::PEM_get_string_X509($t{local_cert}));
$t{local_cert_subject} = Net::SSLeay::X509_NAME_oneline(Net::SSLeay::X509_get_subject_name($t{local_cert}));
}
return($t{active});
}
sub ptrans {
my $c = shift; # transaction flag
my $m = shift; # message to print
my $b = shift; # be brief in what we print
my $o = $G::trans_fh_oh || \*STDOUT;
my $f = '';
return if (($G::hide_send && int($c/10) == 2) ||
($G::hide_receive && int($c/10) == 3) ||
($G::hide_informational && $c == 11) ||
($G::hide_all));
# global option silent controls what we echo to the terminal
# 0 - print everything
# 1 - don't show anything until you hit an error, then show everything
# received after that (done by setting option to 0 on first error)
# 2 - don't show anything but errors
# >=3 - don't print anything
if ($G::silent > 0) {
return if ($G::silent >= 3);
return if ($G::silent == 2 && $c%2 != 0);
if ($G::silent == 1 && !$G::ptrans_seen_error) {
if ($c%2 != 0) {
return();
} else {
$G::ptrans_seen_error = 1;
}
}
}
# 1x is program messages
# 2x is smtp send
# 3x is smtp recv
# x = 1 is info/normal
# x = 2 is error
# x = 3 dump output
# program info
if ($c == 11) { $f = $G::no_hints_info ? '' : '==='; }
# program error
elsif ($c == 12) { $f = $G::no_hints_info ? '' : '***'; $o = $G::trans_fh_eh || \*STDERR; }
# smtp send info
elsif ($c == 21) { $f = $G::no_hints_send ? '' : ($G::link{tls}{active} ? ' ~>' : ' ->'); }
# smtp send error
elsif ($c == 22) { $f = $G::no_hints_send ? '' : ($G::link{tls}{active} ? '*~>' : '**>'); }
# smtp send dump output
elsif ($c == 23) { $f = $G::no_hints_send ? '' : ' >'; }
# smtp recv info
elsif ($c == 31) { $f = $G::no_hints_recv ? '' : ($G::link{tls}{active} ? '<~ ' : '<- '); }
# smtp recv error
elsif ($c == 32) { $f = $G::no_hints_recv ? '' : ($G::link{tls}{active} ? '<~*' : '<**'); }
# smtp recv dump output
elsif ($c == 33) { $f = $G::no_hints_recv ? '' : '< '; }
# something went unexpectedly
else { $f = '???'; }
$f .= ' ' if ($f);
if ($b) {
# split to tmp list to prevent -w gripe
my @t = split(/\n/ms, $m); $m = scalar(@t) . " lines sent";
}
$m =~ s/\n/\n$f/msg;
print $o "$f$m\n";
}
sub do_smtp_quit {
my $exit = shift;
my $err = shift;
# Ugh. Because PIPELINING allows mail's and rcpt's send to be disconnected,
# and possibly with a QUIT between them, we need to set a global "we have
# told the server we quit already" flag to prevent double-quits
return(1) if ($G::link{quit_sent});
$G::link{quit_sent} = 1;
$G::link{allow_lost_cxn} = 1;
my $r = do_smtp_gen('QUIT', '221');
$G::link{allow_lost_cxn} = 0;
handle_disconnect($err) if ($G::link{lost_cxn});
if ($exit) {
teardown_link();
exit $err;
}
return($r);
}
sub do_smtp_tls {
my $e = shift; # ehlo config hash
# 0 = tls succeeded
# 1 = tls not advertised
# 2 = tls advertised and attempted negotiations failed
if (!$e->{STARTTLS}) {
return(1);
} elsif (!do_smtp_gen("STARTTLS", '220')) {
return(2);
} elsif (!start_tls()) {
ptrans(12, "TLS startup failed ($G::link{tls}{res})");
return(2);
}
tls_post_start();
return(0);
}
sub do_smtp_xclient {
my $e = shift;
# 0 - xclient succeeded normally
# 1 - xclient not advertised
# 2 - xclient advertised but not attempted, mismatch in requested attrs
# 3 - xclient attempted but did not succeed
if (!$e->{XCLIENT}) {
return(1);
}
my @parts = ();
foreach my $attr (keys %{$G::xclient{attr}}) {
if (!$e->{XCLIENT}{$attr}) {
return(2);
}
# see xtext encoding in http://tools.ietf.org/html/rfc1891
push(@parts, "$attr=" . join('', map { ($_ == 0x2b || $_ == 0x3D || $_ <= 20 || $_ >= 127)
? sprintf("+%02X", $_)
: chr($_)
} (unpack("C*", $G::xclient{attr}{$attr}))));
}
push(@parts, $G::xclient{raw}) if ($G::xclient{raw});
my $str = "XCLIENT " . join(' ', @parts);
do_smtp_gen($str, '220') || return(3);
return(0);
}
sub do_smtp_auth {
my $e = shift; # ehlo config hash
my $at = shift; # auth type
my $au = shift; # auth user
my $ap = shift; # auth password
return(1) if (!$e->{AUTH});
return(3) if ($G::auth_unavailable);
my $auth_attempted = 0; # set to true if we ever attempt auth
foreach my $btype (@$at) {
# if server doesn't support, skip type (may change in future)
next if (!$e->{AUTH}{$btype});
foreach my $type (@{$G::auth_map_t{'CRAM-MD5'}}) {
if ($btype eq $type) {
return(0) if (do_smtp_auth_cram($au, $ap, $type));
$auth_attempted = 1;
}
}
foreach my $type (@{$G::auth_map_t{'CRAM-SHA1'}}) {
if ($btype eq $type) {
return(0) if (do_smtp_auth_cram($au, $ap, $type));
$auth_attempted = 1;
}
}
foreach my $type (@{$G::auth_map_t{'DIGEST-MD5'}}) {
if ($btype eq $type) {
return(0) if (do_smtp_auth_digest($au, $ap, $type));
$auth_attempted = 1;
}
}
foreach my $type (@{$G::auth_map_t{'NTLM'}}) {
if ($btype eq $type) {
return(0) if (do_smtp_auth_ntlm($au, $ap, $type));
$auth_attempted = 1;
}
}
foreach my $type (@{$G::auth_map_t{'PLAIN'}}) {
if ($btype eq $type) {
return(0) if (do_smtp_auth_plain($au, $ap, $type));
$auth_attempted = 1;
}
}
foreach my $type (@{$G::auth_map_t{'LOGIN'}}) {
if ($btype eq $type) {
return(0) if (do_smtp_auth_login($au, $ap, $type));
$auth_attempted = 1;
}
}
}
return $auth_attempted ? 4 : 2;
}
sub do_smtp_auth_ntlm {
my $u = shift; # auth user
my $p = shift; # auth password
my $as = shift; # auth type (since NTLM might be SPA or MSN)
my $r = ''; # will store smtp response
my $auth_string = "AUTH $as";
do_smtp_gen($auth_string, '334') || return(0);
my $d = db64(Authen::NTLM::ntlm());
$auth_string = eb64($d);
do_smtp_gen($auth_string, '334', \$r, '',
$G::auth_showpt ? "$d" : '',
$G::auth_showpt ? \&unencode_smtp : '') || return(0);
$r =~ s/^....//; # maybe something a little better here?
Authen::NTLM::ntlm_domain($G::auth_extras{DOMAIN});
Authen::NTLM::ntlm_user($u);
Authen::NTLM::ntlm_password($p);
$d = db64(Authen::NTLM::ntlm($r));
$auth_string = eb64($d);
do_smtp_gen($auth_string, '235', \$r, '', $G::auth_showpt ? "$d" : '') || return(0);
return(1);
}
sub do_smtp_auth_digest {
my $u = shift; # auth user
my $p = shift; # auth password
my $as = shift; # auth string
my $r = ''; # will store smtp response
my $e = ''; # will store Authen::SASL errors
my @digest_uri = ();
if (exists($G::auth_extras{"DMD5-SERV-TYPE"})) {
$digest_uri[0] = $G::auth_extras{"DMD5-SERV-TYPE"};
} else {
$digest_uri[0] = 'smtp';
}
if (exists($G::auth_extras{"DMD5-HOST"})) {
$digest_uri[1] = $G::auth_extras{"DMD5-HOST"};
} else {
if ($G::link{type} eq 'socket-unix') {
$digest_uri[1] = $G::link{sockfile};
$digest_uri[1] =~ s|[^a-zA-Z0-9\.\-]|-|g;
} elsif ($G::link{type} eq 'pipe') {
$digest_uri[1] = $G::link{process};
$digest_uri[1] =~ s|[^a-zA-Z0-9\.\-]|-|g;
} else {
$digest_uri[1] = $G::link{server};
}
}
if (exists($G::auth_extras{"DMD5-SERV-NAME"})) {
# There seems to be a hole in the Authen::SASL interface where there's
# no option to directory provide the digest-uri serv-name. But we can
# trick it into using the value we want by tacking it onto the end of host
$digest_uri[1] .= '/' . $G::auth_extras{"DMD5-SERV-NAME"};
}
my $auth_string = "AUTH $as";
do_smtp_gen($auth_string, '334', \$r, '', '', $G::auth_showpt ? \&unencode_smtp : '')
|| return(0);
$r =~ s/^....//; # maybe something a little better here?
$r = db64($r);
my $callbacks = { user => $u, pass => $p };
if (exists($G::auth_extras{REALM})) {
$callbacks->{realm} = $G::auth_extras{REALM};
}
my $sasl = Authen::SASL->new(
debug => 1,
mechanism => 'DIGEST-MD5',
callback => $callbacks,
);
my $sasl_client = $sasl->client_new(@digest_uri);
# Force the DIGEST-MD5 session to use qop=auth. I'm open to exposing this setting
# via some swaks options, but I don't know enough about the protocol to just guess
# here. I do know that letting it auto-negotiate didn't work in my reference
# environment. sendmail advertised auth,auth-int,auth-conf, but when Authen::SASL
# chose auth-int the session would fail (server would say auth succeeded, but then
# immediately terminate my session when I sent MAIL). My reference client
# (Mulberry) always sent auth, and indeed forcing swaks to auth also seems to work.
# If anyone out there knows more about this please let me know.
$sasl_client->property('maxssf' => 0);
$auth_string = $sasl_client->client_step($r);
if ($e = $sasl_client->error()) {
ptrans('12', "Error received from Authen::SASL sub-system: $e");
return(0);
}
do_smtp_gen(eb64($auth_string), '334', \$r, '',
$G::auth_showpt ? "$auth_string" : '',
$G::auth_showpt ? \&unencode_smtp : '')
|| return(0);
$r =~ s/^....//; # maybe something a little better here?
$r = db64($r);
$auth_string = $sasl_client->client_step($r);
if ($e = $sasl_client->error()) {
ptrans('12', "Canceling SASL exchange, error received from Authen::SASL sub-system: $e");
$auth_string = '*';
}
#do_smtp_gen(eb64($auth_string), '235', \$r, '', $G::auth_showpt ? "$auth_string" : '')
do_smtp_gen($auth_string, '235', \$r, '', $auth_string)
|| return(0);
if ($e = $sasl_client->error()) {
ptrans('12', "Error received from Authen::SASL sub-system: $e");
return(0);
}
return(0) if (!$sasl_client->is_success());
return(1);
}
# This can handle both CRAM-MD5 and CRAM-SHA1
sub do_smtp_auth_cram {
my $u = shift; # auth user
my $p = shift; # auth password
my $as = shift; # auth string
my $r = ''; # will store smtp response
my $auth_string = "AUTH $as";
do_smtp_gen($auth_string, '334', \$r, '', '', $G::auth_showpt ? \&unencode_smtp : '')
|| return(0);
$r =~ s/^....//; # maybe something a little better here?
# specify which type of digest we need based on $as
my $d = get_digest($p, $r, ($as =~ /-SHA1$/ ? 'sha1' : 'md5'));
$auth_string = eb64("$u $d");
do_smtp_gen($auth_string, '235', undef, '', $G::auth_showpt ? "$u $d" : '') || return(0);
return(1);
}
sub do_smtp_auth_login {
my $u = shift; # auth user
my $p = shift; # auth password
my $as = shift; # auth string
do_smtp_gen("AUTH $as", '334', undef, '', '', $G::auth_showpt ? \&unencode_smtp : '')
|| return(0);
do_smtp_gen(eb64($u), '334', undef, '', $G::auth_showpt ? $u : '', $G::auth_showpt ? \&unencode_smtp : '')
|| return(0);
do_smtp_gen(eb64($p), '235', undef, '',
$G::auth_showpt ? ($G::auth_hidepw || $p) : eb64($G::auth_hidepw || $p))
|| return(0);
return(1);
}
sub do_smtp_auth_plain {
my $u = shift; # auth user
my $p = shift; # auth password
my $as = shift; # auth string
return(do_smtp_gen("AUTH $as " . eb64("\0$u\0$p"), '235', undef, '',
$G::auth_showpt ? "AUTH $as \\0$u\\0" . ($G::auth_hidepw || $p)
: "AUTH $as " . eb64("\0$u\0" . ($G::auth_hidepw || $p))));
}
sub do_smtp_helo {
my $h = shift; # helo string to use
my $e = shift; # this is a hashref that will be populated w/ server options
my $p = shift; # protocol for the transaction
my $r = ''; # this'll be populated by do_smtp_gen
if ($p eq 'esmtp' || $p eq 'lmtp') {
my $l = $p eq 'lmtp' ? "LHLO" : "EHLO";
if (do_smtp_gen("$l $h", '250', \$r)) {
# There's not a standard structure for the $e hashref, each
# key is stored in the manner that makes the most sense
foreach my $l (split(/\n/, $r)) {
$l =~ s/^....//;
if ($l =~ /^AUTH=?(.*)$/) {
map { $e->{AUTH}{uc($_)} = 1 } (split(' ', $1));
} elsif ($l =~ /^XCLIENT\s+(.*)$/) {
map { $e->{XCLIENT}{uc($_)} = 1 } (split(' ', $1));
} elsif ($l =~ /^STARTTLS$/) {
$e->{STARTTLS} = 1;
} elsif ($l =~ /^PIPELINING$/) {
$e->{PIPELINING} = 1;
$G::pipeline_adv = 1;
}
}
return(1);
}
}
if ($p eq 'esmtp' || $p eq 'smtp') {
return(do_smtp_gen("HELO $h", '250'));
}
return(0);
}
sub do_smtp_mail {
my $m = shift; # from address
transact(cxn_string => "MAIL FROM:<$m>", expect => '250', defer => 1, fail_callback => \&smtp_mail_callback);
return(1); # the callback handles failures, so just return here
}
# this only really needs to exist until I figure out a clever way of making
# do_smtp_quit the callback while still preserving the exit codes
sub smtp_mail_callback {
do_smtp_quit(1, 23);
}
sub do_smtp_rcpt {
my $m = shift; # string of comma separated recipients
my $f = 0; # The number of failures we've experienced
my @a = split(/,/, $m);
$G::smtp_rcpt_total = scalar(@a);
foreach my $addr (@a) {
transact(cxn_string => "RCPT TO:<$addr>", expect => '250', defer => 1,
fail_callback => \&smtp_rcpt_callback);
}
return(1); # the callback handles failures, so just return here
}
sub smtp_rcpt_callback {
# record that a failure occurred
$G::smtp_rcpt_failures++;
# if the number of failures is the same as the total rcpts (if every rcpt rejected), quit.
if ($G::smtp_rcpt_failures == $G::smtp_rcpt_total) {
do_smtp_quit(1, 24);
}
}
sub do_smtp_data {
my $m = shift; # string to send
my $b = shift; # be brief in the data we send
my $calls = $G::smtp_rcpt_total - $G::smtp_rcpt_failures;
my $ok = transact(cxn_string => $m, expect => '250', summarize_output => $b);
# now be a little messy - lmtp is not a lockstep after data - we need to
# listen for as many calls as we had accepted recipients
if ($G::protocol eq 'lmtp') {
foreach my $c (1..($calls-1)) { # -1 because we already got 1 above
$ok += transact(cxn_string => undef, expect => '250');
}
}
return($ok)
}
sub do_smtp_gen {
my $m = shift; # string to send
my $e = shift; # String we're expecting to get back
my $p = shift; # this is a scalar ref, assign the server return string to it
my $b = shift; # be brief in the data we send
my $x = shift; # if this is populated, print this instead of $m
my $c = shift; # if this is a code ref, call it on the return value b4 print
my $r = ''; # This'll be the return value from transact()
my $time;
return transact(cxn_string => $m, expect => $e, return_text => $p,
summarize_output => $b, show_string => $x,
print_callback => $c
);
}
# If we detect that the other side has gone away when we were expecting
# to still be reading, come in here to error and die. Abstracted because
# the error message will vary depending on the type of connection
sub handle_disconnect {
my $e = shift || 6; # this is the code we will exit with
if ($G::link{type} eq 'socket-inet') {
ptrans(12, "Remote host closed connection unexpectedly.");
} elsif ($G::link{type} eq 'socket-unix') {
ptrans(12, "Socket closed connection unexpectedly.");
} elsif ($G::link{type} eq 'pipe') {
ptrans(12, "Child process closed connection unexpectedly.");
}
exit($e);
}
sub flush_send_buffer {
my $s = $G::link{type} eq 'pipe' ? $G::link{sock}->{wr} : $G::link{sock};
return if (!$G::send_buffer);
if ($G::link{tls}{active}) {
my $res = Net::SSLeay::write($G::link{tls}{ssl}, $G::send_buffer);
} else {
print $s $G::send_buffer;
}
ptrans(23, hdump($G::send_buffer)) if ($G::show_raw_text);
$G::send_buffer = '';
}
sub send_data {
my $d = shift; # data to write
$G::send_buffer .= "$d\r\n";
}
sub recv_line {
# Either an IO::Socket obj or a FH to my child - the thing to read from
my $s = $G::link{type} eq 'pipe' ? $G::link{sock}->{re} : $G::link{sock};
my $r = undef;
my $t = undef;
my $c = 0;
while ($G::recv_buffer !~ m|\n|si) {
last if (++$c > 1000); # Maybe I'll remove this once I trust this code more
if ($G::link{tls}{active}) {
$t = Net::SSLeay::read($G::link{tls}{ssl});
return($t) if (!defined($t));
# THIS CODE COPIED FROM THE ELSE BELOW. Found I could trip this condition
# by having the server sever the connection but not have swaks realize the
# connection was gone. For instance, send a PIPELINE mail that includes a
# "-q rcpt". There wass a bug in swaks that made it try to send another quit
# later, thus tripping this "1000 reads" error (but only in TLS).
# Short term: add line below to prevent these reads
# Short Term: fix the "double-quit" bug
# Longer term: test to see if remote side closed connection
# the above line should be good enough but it isn't returning
# undef for some reason. I think heuristically it will be sufficient
# to just look for an empty packet (I hope. gulp). Comment out the
# following line if your swaks seems to be saying that it lost connection
# for no good reason. Then email me about it.
return(undef()) if (!length($t));
} elsif ($G::link{type} eq 'pipe') {
# XXX in a future release see if I can get read() or equiv to work on a pipe
$t = <$s>;
return($t) if (!defined($t));
# THIS CODE COPIED FROM THE ELSE BELOW.
# the above line should be good enough but it isn't returning
# undef for some reason. I think heuristically it will be sufficient