-
Notifications
You must be signed in to change notification settings - Fork 6
/
sieve-connect.pre.pl
executable file
·2681 lines (2417 loc) · 86 KB
/
sieve-connect.pre.pl
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
#
# MANAGESIEVE (timsieved) client script
#
# Copyright © 2006-2018,2020,2022 Phil Pennock. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. The name of the author may not be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
use warnings;
use strict;
# Good modern Perl practice and some of our features warrant this:
BEGIN { @INC = grep {$_ ne '.'} @INC };
# If you can't update /etc/services to contain an entry for 'sieve' and you're
# not using 4190 (specified in RFC 5804) and you're not publishing an SRV
# record, then you might want to change the default port-number in the
# parentheses here:
my $DEFAULT_PORT = 'sieve(4190)';
# These are the defaults, some may be overriden on the command-line.
# Note that SSLv23_client_method in OpenSSL is the *only* one which can
# negotiate multiple protocols, so even to choose TLS v1.0/v1.1/v1.2, you
# must still specify SSLv23 and then cancel the undesired protocols.
my %ssl_options = (
SSL_version => 'SSLv23:!SSLv2:!SSLv3',
SSL_cipher_list => 'ALL:!aNULL:!NULL:!LOW:!EXP:!ADH:@STRENGTH',
SSL_verify_mode => 0x03,
# Most portable to let this be discovered automatically, but
# an installation might override it here:
#SSL_ca_path => '/etc/ssl/certs',
);
# These defaults can be overriden on the cmdline:
my ($forbid_clearauth, $forbid_clearchan) = (0, 0);
# Note Well: if SSL/TLS verification is enabled, that is equivalent to
# $forbid_clearchan, since no TLS means no verification possible. But
# if verification is not required then by default clearchan is allowed, not
# just unverified TLS. The command-line overrides these.
# This is a breaking change between v0.87 and v0.88 as these semantics were
# firmed up and --clearchan was added to restore the old default behaviour
# if TLS was never offered but verification was enabled.
#
# I expect this to cause complaints as it's not backwards compatible, but the
# old behaviour was susceptible to MitM connection downgrade by removing the
# capability advertisement. The new behaviour is a security improvement, and
# the old semantics can be obtained by explicitly setting --clearchan.
# Add a key to this to blacklist that authentication mechanism. Might be
# useful on some platforms with broken libraries. Make sure the key is
# upper-case!
my %blacklist_auth_mechanisms = ();
# my %blacklist_auth_mechanisms = ( GSSAPI => 1, SPNEGO => 1 );
# This says "go ahead and use SRV records and local hostname to figure out
# a server to connect to".
my $DERIVE_SIEVE_SERVER = 1;
# Command used for generating local-side listings.
my @cmd_localfs_ls = qw( ls -C );
# Unset this to disable probing for SSL certs and just use whatever is
# set above in %ssl_options.
my $SEARCH_FOR_CERTS_DIR_IF_NEEDED = 1;
# You can override this to a particular path; is only used to find default
# certificate stores; set to undef to skip asking OpenSSL and just check
# some common locations.
my $OPENSSL_COMMAND = 'openssl';
# ######################################################################
# No user-serviceable parts below
our $VERSION = 0; # MAGIC LINE REPLACED IN DISTRIBUTION
use Authen::SASL 2.11 qw(Perl);
# 2.11: first version with non-broken DIGEST-MD5
# Earlier versions don't allow server verification
# NB: code still explicitly checks for a new-enough version, so
# if you have an older version of Authen::SASL and know what you're
# doing then you can remove this version check here. I advise
# against it, though.
# Perl: Need a way to ask which mechanism to send
use Authen::SASL::Perl::EXTERNAL; # We munge inside its private stuff.
use Cwd qw();
use Errno;
use File::Basename qw();
use File::Spec;
use File::Temp qw/ tempfile /;
use Getopt::Long;
use IO::File;
use IO::Socket::IP;
use IO::Socket::SSL 1.14; # first version with automatic verification
use MIME::Base64;
use Net::DNS;
use Net::SSLeay 1.37; # see version note below
use Pod::Usage;
use POSIX qw/ strftime /;
use Sys::Hostname qw();
use Term::ReadKey;
# interactive mode will attempt to pull in Term::ReadLine too.
# Net::SSLeay -- we used to just conditionally use this if loaded, indirectly
# via the IO::Socket::SSL library. We now want to explicitly require it for a
# top-level feature, --tlsfingerprint.
# The first version supplying X509_get_fingerprint() was 1.37 (2011-09-16) per
# http://cpansearch.perl.org/src/MIKEM/Net-SSLeay-1.55/Changes
#
# Debian Squeeze is still on Net::SSLeay 1.36 but at this point I'm not going
# to worry about backport compatibility to "oldstable".
# This is only used to derive a default IMAP server using SRV records and
# isn't always needed even then, so is strictly optional.
our $have_mozilla_public_suffix;
BEGIN { eval {
require 'Mozilla/PublicSuffix.pm';
Mozilla::PublicSuffix->import('public_suffix');
$have_mozilla_public_suffix = 1;
} };
my $DEBUGGING = 0;
my $LOST_CONNECTION = 0;
sub do_version_display {
print "${0}: Version $VERSION\n";
if ($DEBUGGING) {
my @do_require = (
'Authen::SASL::Perl::GSSAPI',
'Term::ReadLine',
);
foreach my $r (@do_require) {
(my $rr = $r) =~ s,::,/,g;
eval { require "$rr.pm" };
}
foreach my $mod (
'Authen::SASL',
'Authen::SASL::Perl',
'IO::Socket::IP',
'IO::Socket::SSL',
'Mozilla::PublicSuffix',
'Net::DNS',
'Term::ReadKey',
@do_require) {
my $vname = "${mod}::VERSION";
my $ver;
eval { no strict 'refs'; $ver = ${$vname} };
if (defined $ver) {
print " Module $mod Version $ver\n";
} else {
print " Module $mod -- no version number available\n";
}
}
}
exit 0;
}
sub debug;
sub sent;
sub ssend;
sub sget;
sub sfinish;
sub received;
sub closedie;
sub closedie_NOmsg;
sub die_NOmsg;
sub fixup_ssl_configuration;
sub derive_sieve_server;
sub escalate_warnings_to_exitcode;
sub exit_with_result_based_on_escalated_warnings;
my $DEBUGGING_SASL = 0;
my $DATASTART = tell DATA;
my $localsievename;
my $remotesievename;
my $port = undef;
my ($user, $authzid, $authmech, $sslkeyfile, $sslcertfile, $ssl_cert_fingerprint, $passwordfd);
my ($tlscapath, $tlscafile);
my $tls_explicit_hostname = undef;
my $tls_sufficiently_configured = 0;
my $clearchan_explicitly_set = 0;
my $prioritise_auth_external = 0;
my $dump_tls_information = 0;
my $opt_version_req = 0;
my $ignore_server_version = 0;
my $no_srv = 0;
my ($server, $realm);
my $net_domain = AF_UNSPEC;
my $action = 'command-loop';
my $execscript;
GetOptions(
# settings which adjust how we connect
"localsieve=s" => \$localsievename,
"remotesieve=s" => \$remotesievename,
"server|s=s" => \$server,
"port|p=s" => \$port, # not num, allow service names
"nosrv" => \$no_srv,
"user|u=s" => \$user,
"realm|r=s" => \$realm,
"authzid|authname|a=s" => \$authzid, # authname for sieveshell compat
"authmech|m=s" => \$authmech,
"passwordfd=n" => \$passwordfd,
"clientkey=s" => \$sslkeyfile,
"clientcert=s" => \$sslcertfile,
"clientkeycert=s" => sub { $sslkeyfile = $sslcertfile = $_[1] },
"notlsverify|nosslverify" => sub { $ssl_options{'SSL_verify_mode'} = 0x00 },
"tlscertfingerprint|sslcertfingerprint=s" => \$ssl_cert_fingerprint,
"tlscapath=s" => \$tlscapath,
"tlscafile=s" => \$tlscafile,
"tlshostname=s" => \$tls_explicit_hostname,
"noclearauth" => \$forbid_clearauth,
"noclearchan" => sub { $clearchan_explicitly_set = $forbid_clearauth = $forbid_clearchan = 1 },
"clearchan" => sub { $forbid_clearchan = 0; $clearchan_explicitly_set = 1; },
"4" => sub { $net_domain = AF_INET },
"6" => sub { $net_domain = AF_INET6 },
"debug" => \$DEBUGGING,
"debugsasl" => \$DEBUGGING_SASL,
"dumptlsinfo|dumpsslinfo" => \$dump_tls_information,
"ignoreserverversion" => \$ignore_server_version,
# option names can be short-circuited, $action is complete:
# start with simple mappings to the protocol level
"upload" => sub { $action = 'upload' },
"download" => sub { $action = 'download' },
"list" => sub { $action = 'list' },
"delete" => sub { $action = 'delete' },
"activate" => sub { $action = 'activate' },
"deactivate" => sub { $action = 'deactivate' },
"checkscript" => sub { $action = 'checkscript' },
# then derived commands and alternate, more complex, actions
"edit" => sub { $action = 'edit' },
"exec|e=s" => sub { $execscript = $_[1]; $action='command-loop' },
# then administrivia
'help|?' => sub { pod2usage(-exitstatus => 0,
-verbose => 99, -sections => "SYNOPSIS",
-message => "Use --man for more help text\n") },
'man' => sub { pod2usage(-exitstatus => 0, -verbose => 2) },
'version' => \$opt_version_req, # --version --debug should work
) or pod2usage(2);
# We don't implement HAVESPACE <script> <size>
if (defined $tlscafile) {
$ssl_options{'SSL_ca_file'} = $tlscafile;
delete $ssl_options{'SSL_ca_path'};
} elsif (defined $tlscapath) {
$ssl_options{'SSL_ca_path'} = $tlscapath;
}
do_version_display() if $opt_version_req;
fixup_ssl_configuration();
if (defined $ARGV[0] and not defined $server) {
# sieveshell compatibility.
my $where = $ARGV[0];
if ($where =~ m!^\[([^]]+)\]:(.+)\z!) {
$server = $1; $port = $2;
} elsif ($where =~ m!^\[([^]]+)\]\z!) {
$server = $1;
} elsif ($where =~ m!^(.+):([^:]+)\z!) {
$server = $1; $port = $2;
} else {
$server = $where;
}
}
unless (defined $server) {
$server = 'localhost';
if (exists $ENV{'IMAP_SERVER'}
and $ENV{'IMAP_SERVER'} !~ m!^/!) {
$server = $ENV{'IMAP_SERVER'};
# deal with a port number.
unless ($server =~ /:.*:/) { # IPv6 address literal
# We ignore this port because it's for the IMAP server,
# but we're after the Sieve server.
$server =~ s/:\d+\z//;
}
} elsif ($DERIVE_SIEVE_SERVER and not $no_srv) {
my ($tmpdomain, $tmpport, $tmpnosrv) = derive_sieve_server();
$server = $tmpdomain if defined $tmpdomain;
$port = $tmpport if defined $tmpport;
$no_srv = $tmpnosrv if defined $tmpnosrv;
}
}
die "Bad server name\n"
unless $server =~ /^[A-Za-z0-9_.:-]+\z/;
if (defined $port) {
die "Bad port specification\n"
unless $port =~ /^[A-Za-z0-9_()-]+\z/;
}
unless (defined $user) {
if ($^O eq "MSWin32") {
# perlvar documents always "MSWin32" on Windows ...
# what about 64bit windows?
if (exists $ENV{USERNAME} and length $ENV{USERNAME}) {
$user = $ENV{USERNAME};
} elsif (exists $ENV{LOGNAME} and length $ENV{LOGNAME}) {
$user = $ENV{LOGNAME};
} else {
die "Unable to figure out a default user, sorry.\n";
}
} else {
$user = getpwuid $>;
}
# this should handle the non-mswin32 case if 64bit _is_ different.
die "Unable to figure out a default user, sorry!\n"
unless defined $user;
}
if ((defined $sslkeyfile and not defined $sslcertfile) or
(defined $sslcertfile and not defined $sslkeyfile)) {
die "Need both a client key and cert for SSL certificate auth.\n";
}
if (defined $sslkeyfile) {
$ssl_options{SSL_use_cert} = 1;
$ssl_options{SSL_key_file} = $sslkeyfile;
$ssl_options{SSL_cert_file} = $sslcertfile;
$prioritise_auth_external = 1;
}
if (defined $localsievename and not defined $remotesievename) {
$remotesievename = File::Basename::basename($localsievename);
}
if (defined $localsievename and $action =~ /upload|checkscript/) {
-r $localsievename or die "unable to read \"$localsievename\": $!\n";
}
if ($action eq 'download' and not defined $localsievename) {
die "Need a local filename (or '-') for download.\n";
}
if (($action eq 'activate' or $action eq 'delete' or $action eq 'download')
and not defined $remotesievename) {
die "Need a remote scriptname for '$action'\n";
}
if ($action eq 'deactivate' and defined $remotesievename) {
die "Deactivate deactivates the current script, may not specify one.\n";
# Future feature -- list and deactivate if specified script is
# current. That has a concurrency race condition and is not
# conceivably useful, so ignored at least for the present.
}
# This happens after fixup_ssl_configuration() above, so we've gone to
# some lengths to get CA anchors available already.
if (exists $ssl_options{SSL_ca_path} or exists $ssl_options{SSL_ca_file}) {
$tls_sufficiently_configured = 1;
}
if ($ssl_options{'SSL_verify_mode'} != 0x00) {
unless (exists $ENV{SIEVECONNECT_INSECURE_CLEARTEXT_FALLBACK} and
length $ENV{SIEVECONNECT_INSECURE_CLEARTEXT_FALLBACK}) {
$forbid_clearchan = 1 unless $clearchan_explicitly_set;
}
if ($forbid_clearchan and not $tls_sufficiently_configured) {
warn("TLS verification is ON, so non-TLS is DISABLED\n");
warn(" but we're MISSING configuration information for CA anchors.\n");
warn(" No secure connection possible, aborting early.\n");
die("fix TLS setup, else use --noclearchan or --notlsverify\n");
}
}
# ######################################################################
# Start work; connect, start TLS, authenticate
# host/port lookups are from DNS, we assume insecure. DANE might change that
# for us in future. So, TLS negotiations do not use insecure hostnames from
# DNS.
my $trusted_server = $server;
$trusted_server = $tls_explicit_hostname if defined $tls_explicit_hostname;
my @host_port_pairs;
# Find the real hostname to connect to.
# If the Sieve server was derived, then the DNS cache should be nice and warm
unless ($no_srv) {
my $res = Net::DNS::Resolver->new();
my $query = $res->query("_sieve._tcp.$server", 'SRV');
my @srv_recs;
if ($query) {
foreach my $rr ($query->answer) {
next unless $rr->type eq 'SRV';
push @srv_recs, $rr;
}
}
if (@srv_recs) {
@srv_recs = Net::DNS::rrsort('SRV', '', @srv_recs);
debug "dns: SRV results found for: $server";
foreach my $rr (@srv_recs) {
push @host_port_pairs, [$rr->target, $rr->port];
}
}
}
$port = $DEFAULT_PORT unless defined $port;
unless (@host_port_pairs) {
push @host_port_pairs, [$server, $port];
}
my $sock = undef;
my $first_hp_attempt = 1;
# Yes, this used to just try one connection and the list of candidates was
# bolted on; how could you tell?
foreach my $hp (@host_port_pairs) {
my $host_candidate = $hp->[0];
my $port_candidate = $hp->[1];
my $debug_host = $host_candidate =~ /:/ ? "[$host_candidate]" : $host_candidate;
my $debug_extra = '';
# Although we do log the actual port number, if we succeed in
# connecting, we don't log the actual port number tried if we don't
# connect because we don't have a socket to ask. The Perl IO::Socket
# convention for specifying a name and fallback is not intuitively
# obvious and causes debugging confusion.
if ($port_candidate =~ /^(.+)\((\d+)\)\z/) {
$debug_extra .= " (try '${1}' in /etc/services, fallback $2)";
if ($first_hp_attempt) {
my @serv = getservbyname($1, 'tcp');
if (@serv and $serv[2] != $2) {
debug("connection: WARNING: /etc/services defines $1 as ${serv[2]}, not $2");
}
}
}
debug "connection: trying <${debug_host}:${port_candidate}>$debug_extra";
my $s = IO::Socket::IP->new(
PeerHost => $host_candidate,
PeerPort => $port_candidate,
Proto => 'tcp',
Domain => $net_domain,
);
unless (defined $s) {
my $extra = '';
if ($!{EINVAL} and $net_domain != AF_UNSPEC) {
$extra = " (Probably no host record for overriden IP version)\n";
}
warn qq{Connection to <${debug_host}:${port_candidate}> failed: $!\n$extra};
next;
}
unless ($s->peerhost()) {
# why am I seeing successful returns for unconnected sockets? *sigh*
warn qq{Connection to <${debug_host}:${port_candidate}> failed.\n};
next;
}
$sock = $s;
$server = $host_candidate;
$port = $port_candidate;
last;
} continue {
$first_hp_attempt = 0;
}
exit(1) unless defined $sock;
$sock->autoflush(1);
debug "connection: remote host address is [@{[$sock->peerhost()]}] " .
"port [@{[$sock->peerport()]}]";
my %capa;
my %raw_capabilities;
my %capa_dosplit = map {$_ => 1} qw( SASL SIEVE );
# Key is permissably empty keyword, value if defined is closure to call with
# capabilities after receiving complete list, for verifying permissability.
# First param $sock, second \%capa, third \%raw_capabilities
my %capa_permit_empty = (
# draft 7 onwards clarify that empty SASL is permitted, but is error
# in absense of STARTTLS
SASL => sub {
return if exists $_[1]{STARTTLS};
# We die because there's no way to authenticate.
# Spec states "This list can be empty if and only if STARTTLS
# is also advertised" (section 1.7).
closedie $_[0], "Empty SASL not permitted without STARTTLS\n";
},
SIEVE => undef,
);
sub parse_capabilities
{
my $sock = shift;
local %_ = @_;
# Used under TLS to coerce EXTERNAL auth to be preferred:
my $external_first = 0;
$external_first = $_{external_first} if exists $_{external_first};
my @double_checks;
%raw_capabilities = ();
%capa = ();
while (<$sock>) {
received unless /^OK\b/;
chomp; s/\s*$//;
if (/^OK\b/) {
sget($sock, '-firstline', $_);
last unless exists $_{sent_a_noop};
# See large comment below in STARTTLS explaining the
# resync problem to understand why this is here.
my $end_tag = $_{sent_a_noop};
unless (defined $end_tag and length $end_tag) {
# In the initial NOOP-featuring draft, #10, we
# got back 'NOOP'. However, this was at odds
# with the general syntax rules, so #11/#12
# added the TAG response; with this, the
# supplied NOOP parameter is returned in the
# TAG response, but if there's no parameter
# then there's just arbitrary server text.
#
# So where this used to use a default $end_tag
# of 'NOOP', now we declare it a coding error
# for this script to pass sent_a_noop without
# a value consisting of the tag.
closedie $sock, "Internal error: sent_a_noop without tag\n";
}
# Play crude, just look for the tag anywhere in the
# response, honouring only word boundaries. It's our
# responsibility to make the tag long enough that this
# works without tokenising.
# Really, should check for: OK (TAG <tag-string>) text
# where <tag-string> is "$end_tag" or {<len>}\r\n$end_tag
if ($_ =~ m/\b\Q${end_tag}\E\b/) {
return;
}
# Okay, that's the "server understands NOOP" case, for
# which the server should have advertised the
# capability prior to TLS (and so subject to
# tampering); we play fast and loose, sending NOOP in
# all cases, so have to cover the NO case below too;
# the known instance of protocol violation we know of
# is an older server waiting for client command after
# TLS is up. That server doesn't support NOOP.
# Sending NOOP and expecting a NO response for the
# unsupported command was the original technique used
# by this code.
} elsif (/^\"([^"]+)\"\s+\"(.*)\"$/) {
my ($k, $v) = (uc($1), $2);
unless (length $v) {
unless (exists $capa_permit_empty{$k}) {
warn "Empty \"$k\" capability spec not permitted: $_\n";
# Don't keep the advertised capability unless
# it has some value which is needed. Eg,
# NOTIFY must list a mechanism to be useful.
next;
}
if (defined $capa_permit_empty{$k}) {
push @double_checks, $capa_permit_empty{$k};
}
}
if (exists $capa{$k}) {
# won't catch if the first instance was ignored for an
# impermissably empty value; by this point though we
# would already have issued a warning and the server
# is so fubar that it's not worth worrying about.
warn "Protocol violation. Already seen capability \"$k\".\n" .
"Ignoring second instance and continuing.\n";
next;
}
$raw_capabilities{$k} = $v;
$capa{$k} = $v;
if (exists $capa_dosplit{$k}) {
$capa{$k} = [ split /\s+/, $v ];
}
} elsif (/^\"([^"]+)\"$/) {
$raw_capabilities{$1} = '';
$capa{$1} = 1;
} elsif (/^NO\b/) {
return if exists $_{sent_a_noop};
warn "Unhandled server line: $_\n";
} elsif (/^BYE\b(.*)/) {
closedie_NOmsg $sock, $1,
"Server said BYE when we expected capabilities.\n";
} else {
warn "Unhandled server line: $_\n";
}
};
closedie $sock, "Server does not return SIEVE capability, unable to continue.\n"
unless exists $capa{SIEVE};
warn "Server does not return IMPLEMENTATION capability.\n"
unless exists $capa{IMPLEMENTATION};
foreach my $check_sub (@double_checks) {
$check_sub->($sock, \%capa, \%raw_capabilities);
}
if (grep {lc($_) eq 'enotify'} @{$capa{SIEVE}}) {
unless (exists $capa{NOTIFY}) {
warn "enotify extension present, NOTIFY capability missing\n" .
"This violates MANAGESIEVE specification.\n" .
"Continuing anyway.\n";
}
}
if (exists $capa{SASL} and $external_first
and grep {uc($_) eq 'EXTERNAL'} @{$capa{SASL}}) {
# We do two things. We shift the EXTERNAL to the head of the
# list, suggesting that it's the server's preferred choice.
# We then mess around inside the Authen::SASL::Perl::EXTERNAL
# private stuff (name starts with an underscore) to bump up
# its priority -- for some reason, the method which is not
# interactive and says "use information already available"
# is less favoured than some others.
debug "auth: shifting EXTERNAL to start of mechanism list";
my @sasl = ('EXTERNAL');
foreach (@{$capa{SASL}}) {
push @sasl, $_ unless uc($_) eq 'EXTERNAL';
}
$capa{SASL} = \@sasl;
$raw_capabilities{SASL} = join(' ', @sasl);
no warnings 'redefine';
$Authen::SASL::Perl::EXTERNAL::{_order} = sub { 10 };
}
}
parse_capabilities $sock;
my $tls_bitlength = -1;
# This will be called immediately after function definition if
# exists $capa{STARTTLS}; moved into a function to make it easy to abort when TLS
# is not mandatory.
#
# Return 1 if all okay, 0 if TLS not configured, or die on issues.
sub handle_capa_STARTTLS
{
# Always set SSL_hostname for SNI, only set the verification
# modes if not disabled.
$ssl_options{'SSL_hostname'} = $trusted_server;
if ($ssl_options{'SSL_verify_mode'} != 0x00) {
$ssl_options{'SSL_verifycn_name'} = $trusted_server;
# we want full wildcard support in same style that most admins
# are already familiar with:
$ssl_options{'SSL_verifycn_scheme'} = 'http';
unless ($tls_sufficiently_configured) {
debug("-T- offered STARTTLS, want verification, TLS insufficiently configured to proceed");
warn("offered STARTTLS, no CA anchor information available\n");
if ($forbid_clearchan) {
# we shouldn't even have tried to establish a connection in this scenario,
# but protect against screw-ups
debug("-T- we should not even be here (BUG please report!)");
warn("cleartext communications disabled, no TLS verification possible\n");
die("fix TLS setup, else use --clearchan or --notlsverify\n");
}
# to be at this line of code, in theory the invoker must have explictly set --clearchan
# (--notlsverify would skip this entire block).
return 0;
}
}
if ($DEBUGGING) {
debug("-T- will use TLS certs from " .
( exists $ssl_options{'SSL_ca_file'} ? "file" : "directory" ) .
" \"" .
( exists $ssl_options{'SSL_ca_file'}
? $ssl_options{'SSL_ca_file'}
: $ssl_options{'SSL_ca_path'} ) . "\"");
my $dbg_tls_verification = ' unknown';
if (exists $ssl_options{'SSL_verify_mode'}) {
my $mode = $ssl_options{'SSL_verify_mode'};
if ($mode == 0x00) {
$dbg_tls_verification = ' !DISABLED!';
} else {
$dbg_tls_verification = '';
$dbg_tls_verification .= ' verify-peer' if $mode & 0x01;
$dbg_tls_verification .= ' cert-required' if $mode & 0x02;
$dbg_tls_verification .= ' verify-once' if $mode & 0x04;
}
}
debug("-T- using hostname '${trusted_server}', verification$dbg_tls_verification");
} # DEBUGGING
ssend $sock, "STARTTLS";
sget $sock;
die "STARTTLS request rejected: $_\n" unless /^OK\b/;
IO::Socket::SSL->start_SSL($sock, %ssl_options) or do {
my $e = IO::Socket::SSL::errstr();
die "STARTTLS promotion failed: $e\n";
};
my $dbg_tls_conn_info = '';
if (exists $main::{"Net::"} and exists $main::{"Net::"}{"SSLeay::"}) {
my $ctx = $sock->_get_ssl_object();
my $t = Net::SSLeay::get_cipher_bits($ctx, 0);
$tls_bitlength = $t if defined $t and $t;
$dbg_tls_conn_info = ' [' .
Net::SSLeay::get_version($ctx) . ' / ' .
Net::SSLeay::get_cipher($ctx) . ']';
}
debug("-T- TLS activated here [$tls_bitlength bits]$dbg_tls_conn_info");
if ($dump_tls_information) {
print $sock->dump_peer_certificate();
if ($DEBUGGING and
exists $main::{"Net::"} and exists $main::{"Net::"}{"SSLeay::"}) {
# IO::Socket::SSL depends upon Net::SSLeay
# so this should be fairly safe, albeit messing
# around behind IO::Socket::SSL's back.
print STDERR Net::SSLeay::PEM_get_string_X509(
$sock->peer_certificate());
my $session = Net::SSLeay::get_session($sock->_get_ssl_object());
Net::SSLeay::SESSION_print_fp(*STDERR, $session);
}
}
if (defined $ssl_cert_fingerprint) {
my ($fp_type, $fp_want) = split(/:/, $ssl_cert_fingerprint, 2);
# type validation: Net::SSLeay::X509_get_fingerprint supports
# some set of algorithms, we don't want to overconstrain; when
# fed garbage, that routine silently falls back to SHA1. So,
# no error return, no die to catch, we just let the resulting
# mismatch be shown.
$fp_want = uc $fp_want;
my $server_fingerprint = Net::SSLeay::X509_get_fingerprint(
$sock->peer_certificate(), $fp_type);
if (uc($server_fingerprint) eq $fp_want) {
debug("-T- TLS X.509 Fingerprint matched; [${fp_type}] $fp_want");
} else {
die "TLS X.509 Fingerprint verification failed (digest type $fp_type):\n" .
" expected fingerprint: $fp_want\n" .
" got fingerprint: $server_fingerprint\n";
}
}
$forbid_clearauth = 0;
# The current protocol spec says that the capability response must
# be sent by the server after TLS is established by STARTTLS,
# without the client issuing a request. So after TLS,
# server-goes-first. The historical behaviour of Cyrus timseived
# is the inverse; the server waits after TLS for the client to issue
# CAPABILITY. That historical behaviour is still what happens in
# the current 'stable' release branch of Cyrus IMAP.
# To accommodate both, we need to be able to resynchronise to
# reality, so that we can get back to command-response.
# We can't just check to see if there's data to read or not, since
# that will break if the next data is delayed (race condition).
# There was no protocol-compliant method to determine this, short
# of "wait a while, see if anything comes along; if not, send
# CAPABILITY ourselves". So, I broke protocol by sending the
# non-existent command NOOP, then scan for the resulting NO.
# This at least is stably deterministic. However, from draft 10
# onwards, NOOP is a registered available extension which returns
# OK.
#
# New problem: again, Cyrus timsieved. As of 2.3.13, it drops the
# connection for an unknown command instead of returning NO. And
# logs "Lost connection to client -- exiting" which is an interesting
# way of saying "we dropped the connection". At this point, I give up
# on protocol-deterministic checks and fall back to version checking.
# Alas, Cyrus 2.2.x is still widely deployed because 2.3.x is the
# development series and 2.2.x is officially the stable series.
# This means that if they don't support NOOP by 2.3.14, I have to
# figure out how to decide what is safe and backtrack which version
# precisely was the first to send the capability response correctly.
#
# There is also at least one special version which needs special
# treatment despite having a higher version number: Kolab's patched
# "nocaps" Cyrus version (see below).
my $use_noop = 1;
my $timsieved_nocaps = 0;
my $cyrus_version_extension = '';
if (exists $capa{"IMPLEMENTATION"}) {
if ($capa{"IMPLEMENTATION"} =~ /^Cyrus timsieved v2\.3\.(\d+)\z/
and $1 >= 13) {
debug("--- Cyrus drops connection with dubious log msg if send NOOP, skip that");
$use_noop = 0;
} elsif ($capa{"IMPLEMENTATION"} =~
/^Cyrus timsieved v2\.3\.\d+-([\w-]*nocaps)\z/ ) {
$cyrus_version_extension = $1;
# Special case: Cyrus may have been patched to not resend its
# capabilities for compatibility with older Kontact versions.
# Kolab does this, for example; see
# https://roundup.kolab.org/issue2443. This patch may even
# have been applied to more modern versions such as v2.3.16.
# For this reason, we need to specifically check for this case.
# If a nocaps server is detected, nothing needs to be done (see
# the $timsieved_nocaps check below).
debug("--- Special Cyrus server version detected:" .
" $cyrus_version_extension");
$use_noop = 0;
$timsieved_nocaps = 1;
}
}
if ($use_noop) {
my $noop_tag = "STARTTLS-RESYNC-CAPA";
ssend $sock, qq{NOOP "$noop_tag"};
parse_capabilities($sock,
sent_a_noop => $noop_tag,
external_first => $prioritise_auth_external);
} elsif ($timsieved_nocaps) {
# For the nocaps version of Cyrus, nothing should be done here.
debug("--- $cyrus_version_extension: using capabilities" .
" transmitted before STARTTLS!");
} else {
parse_capabilities($sock,
external_first => $prioritise_auth_external);
}
unless (scalar keys %capa) {
ssend $sock, "CAPABILITY";
parse_capabilities($sock,
external_first => $prioritise_auth_external);
}
return 1;
}
my $tls_was_setup_okay = 0;
if (exists $capa{STARTTLS}) {
$tls_was_setup_okay = handle_capa_STARTTLS();
}
if ($forbid_clearchan and not $tls_was_setup_okay) {
die "TLS not established, SASL confidentiality not supported in client.\n";
}
my %authen_sasl_params;
if ($DEBUGGING_SASL) {
$authen_sasl_params{debug} = 15;
}
$authen_sasl_params{callback}{user} = $user;
if (defined $authzid) {
$authen_sasl_params{callback}{authname} = $authzid;
}
if (defined $realm) {
# for compatibility, we set it as a callback AND as a property (below)
$authen_sasl_params{callback}{realm} = $realm;
}
my $prompt_for_password = sub {
ReadMode('noecho');
{ print STDERR "Sieve/IMAP Password: "; local $| = 1; }
my $password = ReadLine(0);
ReadMode('normal');
print STDERR "\n";
chomp $password if defined $password;
return $password;
};
if (defined $passwordfd) {
open(PASSHANDLE, "<&=", $passwordfd)
or die "Unable to open fd $passwordfd for reading: $!\n";
my @data = <PASSHANDLE>;
close(PASSHANDLE);
chomp $data[-1];
$authen_sasl_params{callback}{pass} = join '', @data;
} else {
$authen_sasl_params{callback}{pass} = $prompt_for_password;
}
closedie($sock, "Do not have an authentication mechanism list\n")
unless ref($capa{SASL}) eq 'ARRAY';
if (defined $authmech) {
$authmech = uc $authmech;
if (grep {$_ eq $authmech} map {uc $_} @{$capa{SASL}}) {
debug "auth: will try requested SASL mechanism $authmech";
} else {
closedie($sock, "Server does not offer SASL mechanism $authmech\n");
}
$authen_sasl_params{mechanism} = $authmech;
} else {
if (scalar keys %blacklist_auth_mechanisms) {
$authen_sasl_params{mechanism} = join " ", grep
{not exists $blacklist_auth_mechanisms{uc $_}}
map {uc $_} @{$capa{SASL}};
debug("-A- Filtered mechanism list: $authen_sasl_params{mechanism}");
} else {
$authen_sasl_params{mechanism} = $raw_capabilities{SASL};
}
}
my $sasl = Authen::SASL->new(%authen_sasl_params);
die "SASL object init failed (local problem): $!\n"
unless defined $sasl;
my $secflags = 'noanonymous';
$secflags .= ' noplaintext' if $forbid_clearauth;
my $authconversation = $sasl->client_new('sieve', $server, $secflags)
or die "SASL conversation init failed (local problem): $!\n";
if ($tls_bitlength > 0) {
$authconversation->property(externalssf => $tls_bitlength);
}
if (defined $realm) {
$authconversation->property(realm => $realm);
}
{
my $sasl_m = $authconversation->mechanism()
or die "Oh why can't I decide which auth mech to send?\n";
if ($sasl_m eq 'GSSAPI') {
debug("-A- GSSAPI sasl_m <temp>");
# gross hack, but it was bad of us to assume anything.
# It also means that we ignore anything specified by the
# user, which is good since it's Kerberos anyway.
# (Major Assumption Alert!)
$authconversation->callback(
user => undef,
pass => undef,
);
}
my $sasl_tosend = $authconversation->client_start();
if ($authconversation->code()) {
my $emsg = $authconversation->error();
closedie($sock, "SASL Error: $emsg\n");
}
if (defined $sasl_tosend and length $sasl_tosend) {
my $mimedata = encode_base64($sasl_tosend, '');
my $mlen = length($mimedata);
ssend $sock, qq!AUTHENTICATE "$sasl_m" {${mlen}+}!;
ssend $sock, $mimedata;
} else {
ssend $sock, qq{AUTHENTICATE "$sasl_m"};
}
sget $sock;
while ($_ !~ /^(OK|NO)(?:\s.*)?$/m) {
my $challenge;
if (/^"(.*)"\r?\n?$/) {
$challenge = $1;
} else {
unless (/^\{(\d+)\+?}\r?$/m) {
sfinish $sock, "*";
closedie($sock, "Failure to parse server SASL response.\n");
}
($challenge = $_) =~ s/^{\d+\+?}\r?\n?//;
}
$challenge = decode_base64($challenge);
my $response = $authconversation->client_step($challenge);
if ($authconversation->code()) {
my $emsg = $authconversation->error();
closedie($sock, "SASL Error: $emsg\n");
}
$response = '' unless defined $response; # sigh
my $senddata = encode_base64($response, '');
my $sendlen = length $senddata;
ssend $sock, "{$sendlen+}";
# okay, we send a blank line here even for 0 length data
ssend $sock, $senddata;
sget $sock;
}
if (/^NO((?:\s.*)?)$/) {
closedie_NOmsg($sock, $1, "Authentication refused by server\n");
}
if (/^OK\s+\(SASL\s+\"([^"]+)\"\)$/) {
# This _should_ be present with server-verification steps which
# in other profiles expect an empty response. But Authen::SASL
# doesn't let us confirm that we've finished authentication!
# The assumption seems to be that the server only verifies us
# so if it says "okay", we don't keep trying.
my $final_auth = decode_base64($1);
my $valid = $authconversation->client_step($final_auth);
# With Authen::SASL before 2.11 (..::Perl 1.06),
# Authen::SASL::Perl::DIGEST-MD5 module will complain at this
# final step:
# Server did not provide required field(s): algorithm nonce
# which is bogus -- it's not required or expected.
# Authen::SASL 2.11 fixes this, with ..::Perl 1.06
# We explicitly permit silent failure with the security
# implications because we require a new enough version of
# Authen::SASL at import time above and if someone removes
# that check, then on their head be it.
if ($authconversation->code()) {
my $emsg = $authconversation->error();
if ($Authen::SASL::Perl::VERSION >= 1.06) {
closedie($sock, "SASL Error: $emsg\n");
}
}
if (defined $valid and length $valid) {
closedie($sock, "Server failed final verification [$valid]\n");
}
}
}
# ######################################################################
# We're in, we can do stuff. What can we do?
sub sieve_list;
sub sieve_deactivate;
sub sieve_activate;
sub sieve_delete;
sub sieve_download;