File Coverage

File:blib/lib/Class/Shared/Protocol.pm
Coverage:96.3%

linestmtbranpathcondsubpodtimecode
1package Class::Shared::Protocol;
2
3
161
161
161
1317420
137
2229
use strict;
4
161
161
161
300
120
2978
use warnings;
5
6
161
161
161
261
122
858
use Scalar::Util ();
7
161
161
161
22140
140064
122768
use Storable ();
8
9our $VERSION = '0.001.0';
10
11# Requests and responses are a 4 byte network order length followed by a
12# Storable image of a hashref.  One frame in flight per connection.
13our $MAX_FRAME = 64 * 1024 * 1024;
14
15# When a shared secret is in use the payload is an HMAC-SHA-256 of the body
16# followed by the body.  The digest is checked before Storable sees a byte, so
17# a peer that does not know the secret cannot make this process thaw -- and so
18# run -- code of its choosing.
19our $DIGEST_SIZE = 32;
20
21# Storable before 3.05 (perl 5.26 ships 2.62) has no recursion limit: freezing
22# data nested some tens of thousands deep overflows the C stack and kills the
23# process, which no eval can catch.  There, and only there, the depth is
24# checked first.
25our $MAX_DEPTH = 10_000;
26our $CHECK_DEPTH = !eval { Storable->VERSION('3.05'); 1 };
27
28sub encode_frame {
29
3478
23433627
        my ($message, $secret) = @_;
30
31
3478
4938
        return (undef, "cannot serialise message: it is nested more than $MAX_DEPTH deep")
32                if $CHECK_DEPTH && _too_deep($message);
33
34        # The caller's $@ is theirs: this eval must not leave a trace in it.
35
3477
2503
        local $@;
36
3477
3477
2662
7791
        my $frozen = eval { Storable::nfreeze($message) };
37
3477
213945
        if (!defined $frozen) {
38
53
81
                my $error = $@ || 'unknown error';
39
53
211
                $error =~ s/\s+\z//;
40
53
102
                return (undef, "cannot serialise message: $error");
41        }
42
43
3424
3635
        if (length($frozen) > $MAX_FRAME) {
44
38
104
                return (undef, 'message is too large (' . length($frozen)
45                        . " bytes, limit is $MAX_FRAME)");
46        }
47
48
3386
3234
        if (defined $secret) {
49
326
417
                my $digest = _digest($secret, $frozen);
50
326
1619
                return pack('N', length($digest) + length($frozen)) . $digest . $frozen;
51        }
52
53
3060
8998
        return pack('N', length($frozen)) . $frozen;
54}
55
56sub take_payload {
57
3555
85601
        my ($body) = @_;
58
59
3555
2131
        local $@;
60
3555
3555
2776
4539
        my $message = eval { Storable::thaw($body) };
61
3555
116472
        if ($@) {
62
709
520
                my $error = $@;
63
709
1999
                $error =~ s/\s+\z//;
64
709
1178
                return (undef, "cannot deserialise message: $error");
65        }
66
67        # thaw returns undef, without dying, for an image that is cut short.  That
68        # must not look like a frame that was read successfully: the caller would
69        # get no message and no error to report.
70
2846
2509
        return (undef, 'cannot deserialise message: the image is incomplete')
71                unless defined $message;
72
73
2762
4924
        return ($message, undef);
74}
75
76# Write every byte, or report why not.
77# Returns (1) on success, (0, $error) on failure.
78sub write_all {
79
2704
1770045
        my ($fh, $bytes) = @_;
80
81        # A backend that has just died must not take the client with it.
82
2704
16494
        local $SIG{PIPE} = 'IGNORE';
83
84
2704
2543
        my $length = length $bytes;
85
2704
1861
        my $offset = 0;
86
87
2704
3237
        while ($offset < $length) {
88
2718
2396012
                my $written = syswrite($fh, $bytes, $length - $offset, $offset);
89
90
2718
11795
                if (!defined $written) {
91                        # A signal the program handled is not a fault in the connection.  A
92                        # handler that dies still ends the write.
93
70
1285
                        next if $!{EINTR};
94
70
2605
                        return (0, "write failed: $!");
95                }
96                # TODO: Unreachable code detected during path analysis. Investigate for removal.
97
2648
3344
                if ($written == 0) {
98
6
36
                        return (0, 'write failed: peer closed the connection');
99                }
100
101
2642
3159
                $offset += $written;
102        }
103
104
2628
10002
        return (1);
105}
106
107# Blocking read of exactly one frame.  Returns ($message) or (undef, $error).
108# An optional timeout is in seconds.
109sub read_frame {
110
2838
1667752
        my ($fh, $timeout, $secret) = @_;
111
112
2838
3852
        my ($header, $error) = _read_exact($fh, 4, $timeout);
113
2837
3258
        return (undef, $error) unless defined $header;
114
115
2654
3758
        my $length = unpack('N', $header);
116
2654
3190
        my $room = defined $secret ? $MAX_FRAME + $DIGEST_SIZE : $MAX_FRAME;
117
118
2654
2986
        return (undef, "frame of $length bytes exceeds the limit of $room")
119                if $length > $room;
120
121
2602
2447
        my ($payload, $body_error) = _read_exact($fh, $length, $timeout);
122
2602
2929
        return (undef, $body_error) unless defined $payload;
123
124
2566
3014
        return _decode($payload, $secret);
125}
126
127sub _read_exact {
128
5583
55735
        my ($fh, $length, $timeout) = @_;
129
130
5583
5281
        my $buffer = '';
131
132
5583
5329
        while (length($buffer) < $length) {
133                # A TLS socket can be holding decrypted bytes that select cannot
134                # see, because they arrived in a record already read from the kernel.
135                # Take those before waiting for more.
136                # Only an object (a TLS socket) can say what it is holding.  Calling a
137                # method on a plain handle would make Perl load IO::File to answer.
138
5643
14834
                if (Scalar::Util::blessed($fh) && $fh->can('pending') && $fh->pending) {
139
132
1032
                        my $pending = sysread($fh, $buffer, $length - length($buffer),
140                                length($buffer));
141
142
132
2037
                        next if !defined $pending && $!{EINTR};
143
132
172
                        return (undef, "read failed: $!") if !defined $pending;
144
131
188
                        return (undef, 'connection closed by peer') if $pending == 0;
145
146
125
234
                        next;
147                }
148
149
5511
6234
                if (defined $timeout) {
150
3337
4121
                        if (_can_select($fh)) {
151
3334
3863
                                return (undef, 'timed out waiting for a reply')
152                                        unless _wait_readable($fh, $timeout);
153                        } elsif (!-f $fh) {
154                                # A plain file never makes a read wait; anything else might
155                                # wait for ever.
156
1
2
                                return (undef, 'cannot apply a timeout: on Windows only a socket '
157                                        . 'or a plain file can be waited for');
158                        }
159                }
160
161
5365
9446585
                my $got = sysread($fh, $buffer, $length - length($buffer), length($buffer));
162
163
5364
1014562
                if (!defined $got) {
164
22
408
                        next if $!{EINTR};
165
18
452
                        return (undef, "read failed: $!");
166                }
167
5342
6918
                if ($got == 0) {
168
75
419
                        return (undef, 'connection closed by peer');
169                }
170        }
171
172
5336
8474
        return ($buffer);
173}
174
175# Purpose:       say whether select can wait on $fh.
176# Entry:         $fh is an open handle.
177# Exit status:   1 if it can, 0 if not.
178# Side effects:  on Windows, loads Socket.
179# Why:           Windows select takes sockets and nothing else.
180sub _can_select {
181
3337
2460
        my ($fh) = @_;
182
183
3337
8492
        return 1 unless $^O eq 'MSWin32';
184
185
3
7
        require Socket;
186
187
3
15
        return defined getsockopt($fh, Socket::SOL_SOCKET(), Socket::SO_TYPE()) ? 1 : 0;
188}
189
190# Purpose:       wait up to $timeout seconds for $fh to have something to read.
191# Entry:         $fh is an open handle; $timeout is in seconds.
192# Exit status:   1 if it has, 0 if the time ran out or select failed.
193# Side effects:  loads Time::HiRes.
194# Why:           a signal ends select early.  The wait goes on for what is left
195#                of the time, so repeated signals cannot stretch it.
196sub _wait_readable {
197
3336
4749
        my ($fh, $timeout) = @_;
198
199
3336
10429
        require Time::HiRes;
200
201
3336
3046
        my $rin = '';
202
3336
4953
        vec($rin, fileno($fh), 1) = 1;
203
204
3336
5972
        my $deadline = Time::HiRes::time() + $timeout;
205
3336
2514
        my $left = $timeout;
206
207
3336
1842
        while (1) {
208
3356
25062067
                my $ready = select(my $rout = $rin, undef, undef, $left);
209
3356
7524
                return 1 if $ready > 0;
210
166
1540
                return 0 unless $ready < 0 && $!{EINTR};
211
212
20
612
                $left = $deadline - Time::HiRes::time();
213
20
44
                $left = 0 if $left < 0;
214        }
215}
216
217# Incremental parser for the backend's select loop.  With a secret, a frame
218# whose digest does not verify is reported as unusable without being thawed.
219# Returns ( 1, $message, undef) when a whole frame was taken out of the buffer,
220#         ( 0, undef,    undef) when more bytes are needed,
221#         (-1, undef,    $error) when the stream is unusable.
222sub take_frame {
223
586
7458672
        my ($buffer_ref, $secret, $check) = @_;
224
225
586
760
        return (0, undef, undef) if length($$buffer_ref) < 4;
226
227
455
623
        my $length = unpack('N', substr($$buffer_ref, 0, 4));
228
455
499
        my $room = defined $secret ? $MAX_FRAME + $DIGEST_SIZE : $MAX_FRAME;
229
230
455
481
        return (-1, undef, "frame of $length bytes exceeds the limit of $room")
231                if $length > $room;
232
233
408
428
        return (0, undef, undef) if length($$buffer_ref) < 4 + $length;
234
235
379
8636
        my $payload = substr($$buffer_ref, 4, $length);
236
379
356
        substr($$buffer_ref, 0, 4 + $length) = '';
237
238
379
413
        my ($message, $error) = _decode($payload, $secret, $check);
239
379
455
        return (-1, undef, $error) if defined $error;
240
241
181
287
        return (1, $message, undef);
242}
243
244# Purpose:       say whether data is nested more than $MAX_DEPTH deep.
245# Entry:         $data is anything.
246# Exit status:   1 if it is, 0 if not.
247# Side effects:  none.  It keeps its own list of what is left to visit rather
248#                than calling itself, and visits each thing once, so cycles
249#                end.
250sub _too_deep {
251
9
2707
        my @todo = ([$_[0], 0]);
252
9
9
        my %seen;
253
254
9
14
        while (@todo) {
255
24
24
15
31
                my ($item, $depth) = @{ pop @todo };
256
257
24
39
                my $type = Scalar::Util::reftype($item) or next;
258
23
40
                next if $seen{ Scalar::Util::refaddr($item) }++;
259
22
31
                return 1 if ++$depth > $MAX_DEPTH;
260
261
19
26
                if ($type eq 'ARRAY') {
262
12
10
16
12
10
17
18
16
                        push @todo, map { [$_, $depth] } grep { ref } @{$item};
263                } elsif ($type eq 'HASH') {
264
6
5
6
6
7
9
10
7
                        push @todo, map { [$_, $depth] } grep { ref } values %{$item};
265                } elsif ($type eq 'REF') {
266
0
0
0
0
                        push @todo, [${$item}, $depth];
267                }
268        }
269
270
6
16
        return 0;
271}
272
273# Payload to message.  With a secret the digest is checked first, and the body
274# is not handed to Storable unless it matches: thaw() runs whatever the sender
275# put in the image, so the authentication has to happen before it, not after.
276sub _decode {
277
3038
8042
        my ($payload, $secret, $check) = @_;
278
279        # TODO: Data Flow Anomaly - DD: when there is a secret, body is redefined below before it is read
280
3038
2236
        my $body = $payload;
281
282
3038
2710
        if (defined $secret) {
283
468
497
                return (undef, 'frame is too short to be authenticated')
284                        if length($payload) < $DIGEST_SIZE;
285
286
439
397
                my $digest = substr($payload, 0, $DIGEST_SIZE);
287
439
7856
                $body = substr($payload, $DIGEST_SIZE);
288
289
439
435
                return (undef, 'frame failed authentication')
290                        unless _authentic($secret, $body, $digest);
291        }
292
293
2797
2925
        return (undef, 'cannot deserialise message: reading it would crash the process')
294                if $check && !$check->($body);
295
296
2796
2914
        return take_payload($body);
297}
298
299# Loaded on demand: a client that only talks to a local unix socket without a
300# token never pays to load Digest::SHA.
301sub _digest {
302
909
29592
        my ($secret, $body) = @_;
303
304
909
11532
        require Digest::SHA;
305
306
909
129420
        return Digest::SHA::hmac_sha256($body, $secret);
307}
308
309# Compared without an early exit, so that the time taken says nothing about
310# how much of a guessed digest was right.
311sub _authentic {
312
527
7430
        my ($secret, $body, $digest) = @_;
313
314
527
449
        my $expected = _digest($secret, $body);
315
316
527
765
        return 0 unless length($expected) == length($digest);
317
318
502
327
        my $difference = 0;
319
502
627
        for my $offset (0 .. length($expected) - 1) {
320
16064
9733
                $difference |= ord(substr($expected, $offset, 1))
321                        ^ ord(substr($digest, $offset, 1));
322        }
323
324
502
961
        return $difference == 0 ? 1 : 0;
325}
326
3271;
328