Debian Codegraph @

cassandane/Cassandane/Cyrus/Alpaca.pm

raw
1 #!/usr/bin/perl
2 #
3 # Copyright (c) 2011-2024 FastMail Pty Ltd. All rights reserved.
4 #
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions
7 # are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 #
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # 3. The name "Fastmail Pty Ltd" must not be used to
18 # endorse or promote products derived from this software without
19 # prior written permission. For permission or any legal
20 # details, please contact
21 # FastMail Pty Ltd
22 # PO Box 234
23 # Collins St West 8007
24 # Victoria
25 # Australia
26 #
27 # 4. Redistributions of any form whatsoever must retain the following
28 # acknowledgment:
29 # "This product includes software developed by Fastmail Pty. Ltd."
30 #
31 # FASTMAIL PTY LTD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
32 # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
33 # EVENT SHALL OPERA SOFTWARE AUSTRALIA BE LIABLE FOR ANY SPECIAL, INDIRECT
34 # OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
35 # USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
36 # TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
37 # OF THIS SOFTWARE.
38 #
39
40 package Cassandane::Cyrus::Alpaca;
41 use strict;
42 use warnings;
43 use Cwd qw(abs_path);
44 use Data::Dumper;
45
46 use lib '.';
47 use base qw(Cassandane::Cyrus::TestCase);
48 use Cassandane::Util::Log;
49 use Cassandane::Util::Socket;
50
51 sub new
52 {
53 my $class = shift;
54
55 my $config = Cassandane::Config->default()->clone();
56 $config->set(allowstarttls => 'on');
57
58 return $class->SUPER::new({config => $config}, @_);
59 }
60
61 sub set_up
62 {
63 my ($self) = @_;
64 $self->SUPER::set_up();
65 }
66
67 sub tear_down
68 {
69 my ($self) = @_;
70 $self->SUPER::tear_down();
71 }
72
73 sub imap_cmd_with_tag
74 {
75 my ($talk, $tag, @args) = @_;
76
77 die "not a Mail::IMAPTalk object" if ref $talk ne 'Mail::IMAPTalk';
78
79 # override next tag with the tag we want to use
80 local $talk->{CmdId} = $tag;
81
82 # suppress an expected warning from _imap_cmd because we (probably)
83 # just set CmdId to something non-numeric
84 local $SIG{__WARN__} = sub {
85 if ($_[0] !~ m/^Argument "\Q$tag\E" isn't numeric /) {
86 warn @_;
87 }
88 };
89
90 return $talk->_imap_cmd(@args);
91 }
92
93 sub test_consecutive_syntax_errors_drop_connection
94 {
95 my ($self) = @_;
96
97 $self->{store}->disconnect();
98 my $sock = create_client_socket($self->{store}->{address_family},
99 $self->{store}->{host},
100 $self->{store}->{port});
101
102 # 50 lines of just "bogus \r\n", that is the tag 'bogus' and a space
103 # but no command, which cyrus will reject with "bogus BAD Null command"
104 my @request = ('bogus ') x 50;
105 foreach my $line (@request) {
106 $sock->send("$line\015\012") or die "send: $!";
107 last if not $sock->connected();
108 }
109
110 # if the connection hasn't been dropped already, send a logout so the
111 # test doesn't hang
112 $sock->send(". logout\015\012") if $sock->connected();
113
114 my @response;
115 while (defined(my $line = $sock->getline())) {
116 $line =~ s/\015?\012//;
117 push @response, $line;
118 }
119
120 # double check that our request contained more lines than cyrus'
121 # syntax error limit of 10
122 $self->assert_num_gt(10, scalar @request);
123
124 # cyrus should have dropped the connection before we sent all the lines
125 $self->assert_num_lt(scalar @request, scalar @response);
126
127 # should have gotten as many BAD responses as cyrus's limit
128 $self->assert_num_equals(10, scalar grep { m/BAD/ } @response);
129
130 # snarky last response back from the server
131 $self->assert_matches(qr{This is an IMAP server}, $response[-1]);
132 }
133
134 sub test_html_tag_dont_reflect1
135 {
136 my ($self) = @_;
137
138 my $talk = $self->{store}->get_client();
139
140 # mimic a HTTP connection sending request content that contains a line
141 # that parses such that the tag is a chunk of javacript and the command
142 # is something that will provoke a tagged response, causing us to reflect
143 # the script back to the client.
144 # we'll say "BAD Invalid tag" for trivial forms of this such as
145 # <script>attack()</script> just because () are not valid characters in
146 # tags, but it's possible to invoke a javascript function without
147 # parentheses, and it's probably possible to do so without any whitespace
148 # or atom-specials at all
149 #
150 # https://portswigger.net/research/xss-without-parentheses-and-semi-colons
151 my $saw_untagged_bad = 0;
152 imap_cmd_with_tag($talk, '<script>do_attack</script>',
153 { IdleResponse => 1 },
154 'noop', 0,
155 { 'bad' => sub { $saw_untagged_bad++ } });
156
157 # the only acceptable response to this is an untagged BAD or BYE!
158 # any tagged response will reflect an attacker-supplied payload to
159 # the victim
160 $self->assert_num_equals(1, $saw_untagged_bad);
161 }
162
163 sub test_html_tag_dont_reflect2
164 {
165 my ($self) = @_;
166
167 my $talk = $self->{store}->get_client();
168
169 # as above, but with no command!
170 my $saw_untagged_bad = 0;
171 imap_cmd_with_tag($talk, '<script>do_attack</script>',
172 { IdleResponse => 1 },
173 '', 0,
174 { 'bad' => sub { $saw_untagged_bad++ } });
175
176 # the only acceptable response to this is an untagged BAD or BYE!
177 # any tagged response will reflect an attacker-supplied payload to
178 # the victim
179 $self->assert_num_equals(1, $saw_untagged_bad);
180 }
181
182 sub test_http_headers_bad
183 {
184 my ($self) = @_;
185
186 my $talk = $self->{store}->get_client();
187
188 # mimic a HTTP connection sending "key: value\r\n" headers.
189 # make sure one that looks like a valid imap command can't be used
190 # to reset any consecutive error counter, by rejecting the tag
191 my $saw_untagged_bad = 0;
192 imap_cmd_with_tag($talk, 'Accept:',
193 { IdleResponse => 1 },
194 'noop', 0,
195 { 'bad' => sub { $saw_untagged_bad++ } });
196
197 $self->assert_num_equals(1, $saw_untagged_bad);
198 }
199
200 sub test_http_request_drop_connection
201 {
202 my ($self) = @_;
203
204 $self->{store}->disconnect();
205 my $sock = create_client_socket($self->{store}->{address_family},
206 $self->{store}->{host},
207 $self->{store}->{port});
208
209 my @request = split /\n/, << 'FIN';
210 POST /some/url HTTP/1.1
211 Host: www.example.com
212 User-Agent: Mozilla/5.0 (redacted) Gecko/20100101 Firefox/130.0
213 Accept: */*
214 Accept-Language: en-US,en;q=0.5
215 Accept-Encoding: gzip, deflate
216 Content-Type: application/x-www-form-urlencoded
217 Content-Length: 15
218 Origin: http://www.example.com
219 DNT: 1
220 Connection: keep-alive
221 Referer: http://www.example.com/
222 Cookie: chocolate=chips
223
224 foo=bar&baz=qux
225 FIN
226 foreach my $line (@request) {
227 $sock->send("$line\015\012") or die "send: $!";
228 last if not $sock->connected();
229 }
230
231 # if the connection hasn't been dropped already, send a logout so the
232 # test doesn't hang
233 $sock->send(". logout\015\012") if $sock->connected();
234
235 my @response;
236 while (defined(my $line = $sock->getline())) {
237 $line =~ s/\015?\012//;
238 push @response, $line;
239 }
240
241 # double check that our request contained more lines than cyrus'
242 # syntax error limit of 10
243 $self->assert_num_gt(10, scalar @request);
244
245 # cyrus should have dropped the connection before we sent all the lines
246 $self->assert_num_lt(scalar @request, scalar @response);
247
248 # cyrus should have dropped the connection at the POST in first line
249 $self->assert_num_equals(0, scalar grep { m/^\* BAD/ } @response);
250
251 # snarky last response back from the server
252 $self->assert_matches(qr{This is an IMAP server}, $response[-1]);
253 }
254
255 sub test_http_post_drop_connection1
256 {
257 my ($self) = @_;
258
259 # get a pristine connection
260 $self->{store}->disconnect();
261 my $talk = $self->{store}->get_client(NoLogin => 1);
262
263 # consume initial capabilities response
264 my ($ok, $capability) = $talk->_parse_response('', { IdleResponse => 1 });
265 $self->assert_str_equals('ok', $ok);
266 $self->assert_str_equals('capability', $capability);
267
268 # mimic a HTTP client sending "POST / HTTP/1.1\r\n" command,
269 # expect "* BYE This is an IMAP server" and disconnect
270 # throws "IMAPTalk: Connection was unexpectedly closed by host"
271 eval {
272 imap_cmd_with_tag($talk, 'POST',
273 '/', 0, '/',
274 'HTTP/1.1');
275 };
276 # XXX can't see the real exception text cause cass obscures it,
277 # XXX but there should have at least been some exception
278 $self->assert_not_null($@);
279 $self->assert_str_equals('This is an IMAP server',
280 $talk->get_response_code('bye'));
281
282 # should be back to unconnected state
283 $self->assert_num_equals(0, $talk->state());
284 }
285
286 sub test_http_post_drop_connection2
287 {
288 my ($self) = @_;
289
290 # get a pristine connection
291 $self->{store}->disconnect();
292 my $talk = $self->{store}->get_client(NoLogin => 1);
293
294 # consume initial capabilities response
295 my ($ok, $capability) = $talk->_parse_response('', { IdleResponse => 1 });
296 $self->assert_str_equals('ok', $ok);
297 $self->assert_str_equals('capability', $capability);
298
299 # as above, but mimic a HTTP connection trying sneak a POST request
300 # past by requesting a resource whose name is a valid IMAP command
301 # which accepts an argument, e.g. "POST authenticate HTTP/1.1\r\n"
302 eval {
303 imap_cmd_with_tag($talk, 'POST',
304 'authenticate', 0, 'authenticate',
305 'HTTP/1.1');
306 };
307 # XXX can't see the real exception text cause cass obscures it,
308 # XXX but there should have at least been some exception
309 $self->assert_not_null($@);
310 $self->assert_str_equals('This is an IMAP server',
311 $talk->get_response_code('bye'));
312
313 # should be back to unconnected state
314 $self->assert_num_equals(0, $talk->state());
315 }
316
317 sub test_http_post_drop_connection3
318 :TLS :needs_dependency_openssl
319 {
320 my ($self) = @_;
321
322 # get a pristine connection
323 $self->{store}->disconnect();
324 my $talk = $self->{store}->get_client(NoLogin => 1);
325
326 # first command after STARTTLS should be treated same as first command
327 $talk->_imap_cmd('starttls', 0, 'starttls');
328 $self->assert_str_equals('ok', $talk->get_last_completion_response());
329 my $ca_file = abs_path("data/certs/cacert.pem");
330 IO::Socket::SSL->start_SSL($talk->{Socket},
331 SSL_ca_file => $ca_file,
332 SSL_verifycn_scheme => 'none',
333 );
334 $self->assert_str_equals('IO::Socket::SSL', ref $talk->{Socket});
335
336 # mimic a HTTP client sending "POST / HTTP/1.1\r\n" command,
337 # expect "* BYE This is an IMAP server" and disconnect
338 # throws "IMAPTalk: Connection was unexpectedly closed by host"
339 eval {
340 imap_cmd_with_tag($talk, 'POST',
341 '/', 0, '/',
342 'HTTP/1.1');
343 };
344 # XXX can't see the real exception text cause cass obscures it,
345 # XXX but there should have at least been some exception
346 $self->assert_not_null($@);
347 $self->assert_str_equals('This is an IMAP server',
348 $talk->get_response_code('bye'));
349
350 # should be back to unconnected state
351 $self->assert_num_equals(0, $talk->state());
352 }
353
354 sub test_imap_http_methods_ok
355 {
356 my ($self) = @_;
357
358 # get a normal, already logged in IMAP connection
359 my $talk = $self->{store}->get_client();
360
361 my @http_methods = qw(
362 ACL BIND LOCK MKCALENDAR MKCOL PATCH POST
363 PROPFIND PROPPATCH PUT REPORT SEARCH UNBIND
364 );
365
366 # HTTP method names are not forbidden tags during a normal IMAP session
367 foreach my $meth (@http_methods) {
368 imap_cmd_with_tag($talk, $meth, 'noop', 0, 'noop');
369 $self->assert_str_equals('ok', $talk->get_last_completion_response());
370 }
371 }
372
373 1;