File Coverage

File:blib/lib/Database/BI/SafeUA.pm
Coverage:99.3%

linestmtbrancondsubtimecode
1package Database::BI::SafeUA;
2
3
13
13
13
168747
8
110
use strict;
4
13
13
13
16
10
358
use warnings;
5
6our $VERSION = '0.025.0';
7
8
13
13
13
21
9
54
use parent 'LWP::UserAgent';
9
10
13
13
13
73593
12
106
use HTTP::Response;
11
13
13
13
157
998
282
use Readonly;
12
13
13
13
28
10
4243
use Socket qw(getaddrinfo getnameinfo inet_ntoa inet_pton AF_INET AF_INET6 SOCK_STREAM NI_NUMERICHOST NIx_NOSERV);
13
14# The fetcher for url: sources and /import.  A page that names a URL gets the
15# server to fetch it, so the URL must not lead to this machine or a private
16# network (SSRF): an admin page on 127.0.0.1, a database on 10.x, a cloud's
17# metadata service on 169.254.169.254.  Checking the URL's text is not enough
18# (a name such as localtest.me, or one whose DNS answers 127.0.0.1, says
19# nothing in its text), and resolving it first is not enough either: LWP
20# resolves again when it connects, and a name can answer differently the
21# second time (DNS rebinding).  So every request, redirects included, is
22# resolved here, refused if any address is not public, and sent to the
23# address that was checked, with the name kept for the Host header, the TLS
24# server name and the certificate check.
25
26Readonly my $MAX_REDIRECT => 5;
27Readonly my $TIMEOUT      => 30;
28
29# [ network, prefix length, why ] for IPv4 and IPv6.  An address in any of them
30# is refused.
31Readonly my @V4_BLOCKED => (
32        [ '0.0.0.0',       8, 'not an address' ],
33        [ '10.0.0.0',      8, 'a private network' ],
34        [ '100.64.0.0',   10, 'a shared (carrier) network' ],
35        [ '127.0.0.0',     8, 'this machine' ],
36        [ '169.254.0.0',  16, 'link-local, where cloud metadata services are' ],
37        [ '172.16.0.0',   12, 'a private network' ],
38        [ '192.0.0.0',    24, 'reserved' ],
39        [ '192.0.2.0',    24, 'reserved for documentation' ],
40        [ '192.168.0.0',  16, 'a private network' ],
41        [ '198.18.0.0',   15, 'reserved for testing' ],
42        [ '198.51.100.0', 24, 'reserved for documentation' ],
43        [ '203.0.113.0',  24, 'reserved for documentation' ],
44        [ '224.0.0.0',     4, 'multicast' ],
45        [ '240.0.0.0',     4, 'reserved' ],
46);
47Readonly my @V6_BLOCKED => (
48        [ '::',             128, 'not an address' ],
49        [ '::1',            128, 'this machine' ],
50        [ '100::',           64, 'reserved' ],
51        [ '2001:db8::',      32, 'reserved for documentation' ],
52        [ 'fc00::',           7, 'a private network' ],
53        [ 'fe80::',          10, 'link-local' ],
54        [ 'fec0::',          10, 'a private network' ],
55        [ 'ff00::',           8, 'multicast' ],
56);
57
58sub _in_net {
59
2361
6291
        my ($packed, $net, $bits) = @_;
60
2361
3208
        my $full = int($bits / 8);
61
2361
2034
        return 0 unless substr($packed, 0, $full) eq substr($net, 0, $full);
62
448
335
        my $rest = $bits % 8 or return 1;
63
258
135
        my $mask = (0xff << (8 - $rest)) & 0xff;
64
258
282
        return (ord(substr($packed, $full, 1)) & $mask) == (ord(substr($net, $full, 1)) & $mask) ? 1 : 0;
65}
66
67sub blocked_address {
68
442
105124
        my ($ip) = @_;
69
442
434
        return 'not an address' unless defined $ip && length $ip;
70
437
36406
        (my $bare = $ip) =~ s/\A\[|\]\z//g;
71
437
248
        $bare =~ s/%.*\z//;     # a zone index (fe80::1%eth0)
72
73
437
291
        if ($bare =~ /:/) {
74
109
114
                my $packed = inet_pton(AF_INET6, $bare) // return 'not an address';
75                # IPv4 inside IPv6: mapped (::ffff:a.b.c.d), NAT64 (64:ff9b::a.b.c.d),
76                # compatible (::a.b.c.d) and 6to4 (2002:aabb:ccdd::) all reach that
77                # IPv4 address, so it is the one checked.
78
107
73
                for my $prefix ("\0" x 10 . "\xff\xff", "\0\x64\xff\x9b" . "\0" x 8, "\0" x 12) {
79
214
305
                        return blocked_address(inet_ntoa(substr($packed, 12, 4)))
80                                if substr($packed, 0, 12) eq $prefix && $packed ne "\0" x 15 . "\1" && $packed ne "\0" x 16;
81                }
82
43
63
                return blocked_address(inet_ntoa(substr($packed, 2, 4))) if substr($packed, 0, 2) eq "\x20\x02";
83
25
25
                for my $net (@V6_BLOCKED) {
84
109
137
                        return $net->[2] if _in_net($packed, inet_pton(AF_INET6, $net->[0]), $net->[1]);
85                }
86
5
10
                return undef;
87        }
88
89        # Premise: only a full dotted quad names one address on every platform;
90        # Windows' inet_pton also reads 1.2.3 as 1.2.0.3.  Conclusion: anything
91        # else is not an address here (numeric_host spells the short forms out).
92        # A leading zero (10.0.0.01) is octal to some libraries and decimal to
93        # others, so it names no one address either: refused, not guessed.
94
328
423
        return 'not an address' unless $bare =~ /\A(?:0|[1-9][0-9]{0,2})(?:\.(?:0|[1-9][0-9]{0,2})){3}\z/;
95
308
356
        my $packed = inet_pton(AF_INET, $bare) // return 'not an address';
96
307
300
        for my $net (@V4_BLOCKED) {
97
2252
2705
                return $net->[2] if _in_net($packed, inet_pton(AF_INET, $net->[0]), $net->[1]);
98        }
99
75
128
        return undef;
100}
101
102sub numeric_host {
103
338
20413
        my ($host) = @_;
104
338
274
        return undef unless defined $host;
105
336
1525
        (my $h = lc $host) =~ s/\.\z//;
106
336
321
        if ($h =~ /\A\[([0-9a-f:.%a-z]+)\]\z/) {
107
3
4
                my $inner = $1;
108
3
5
                return $inner =~ /:/ ? $inner : undef;
109        }
110
333
430
        return $h if $h =~ /:/ && defined inet_pton(AF_INET6, $h);
111
312
259
        return _numeric_v4($h);
112}
113
114# _numeric_v4($host) -> 'a.b.c.d' | undef
115#
116# The forms the BSD and glibc inet_aton read as an address: 127.1,
117# 2130706433, 0x7f000001, 0177.0.0.1.  Each part is decimal, 0x hex or
118# 0-led octal; the last fills the bits the others leave.  Read here rather
119# than by the system's inet_aton, whose reading differs (on macOS 0177.0.0.1 is
120# not 127.0.0.1), so every platform checks, and connects to, the same address.
121sub _numeric_v4 {
122
312
271
        my ($h) = @_;
123
312
1197
        return undef unless $h =~ /\A(?:0x[0-9a-f]+|[0-9]+)(?:\.(?:0x[0-9a-f]+|[0-9]+)){0,3}\z/;
124
179
86
        my @parts;
125
179
1130
        for my $part (split /\./, $h) {
126
565
185
                my $n;
127
565
1080
                if ($part =~ /\A0x([0-9a-f]*)\z/) {
128
20
454
                        my $hex = $1 =~ s/\A0+//r;
129
20
31
                        return undef if length($hex) > 8;
130
17
19
                        $n = length $hex ? hex $hex : 0;
131                } elsif ($part =~ /\A0([0-7]*)\z/) {
132
164
100
                        my $oct = $1 =~ s/\A0+//r;
133
164
120
                        return undef if length($oct) > 11;
134                        # Eleven octal digits can pass 32 bits: perl warns, and the range check below refuses it.
135
13
13
13
163
163
82
13
4348
52
110
                        { no warnings 'portable'; $n = length $oct ? oct $oct : 0; }
136                } elsif ($part =~ /\A[1-9][0-9]{0,9}\z/) {
137
377
182
                        $n = $part + 0;
138                } else {
139
4
9
                        return undef;   # 08, or too long to be a number
140                }
141
557
266
                push @parts, $n;
142        }
143
171
103
        my $last = pop @parts;
144
171
95
        for my $n (@parts) {
145
380
205
                return undef if $n > 0xff;
146        }
147
168
148
        return undef if $last >= 2 ** (8 * (4 - @parts));
148
164
84
        my $value = $last;
149
164
217
        $value += $parts[$_] * 2 ** (8 * (3 - $_)) for 0 .. $#parts;
150
164
406
        return join '.', unpack 'C4', pack 'N', $value;
151}
152
153sub resolve_host {
154
7
1932
        my ($host) = @_;
155
7
6
        local ($@, $!);
156        # A host the resolver will not even take as text (a wide character)
157        # does not resolve, which the POD states as an empty list.
158
7
7
5
14558
        my ($err, @res) = eval { getaddrinfo($host, undef, { socktype => SOCK_STREAM }) };
159
7
42
        return () if $@ || !defined($err) || $err;
160
2
3
        my (%seen, @ips);
161
2
3
        for my $r (@res) {
162
6
8
                my ($e, $ip) = getnameinfo($r->{addr}, NI_NUMERICHOST, NIx_NOSERV);
163
6
21
                push @ips, $ip if !$e && defined $ip && !$seen{$ip}++;
164        }
165
2
7
        return @ips;
166}
167
168sub new {
169
1114
26446
        my ($class, %args) = @_;
170
1114
475
        my $resolve = delete $args{resolve};
171
1114
475
        my $private = delete $args{private_hosts};
172
1114
1199
        my $self = $class->SUPER::new(
173                timeout           => $TIMEOUT,
174                max_redirect      => $MAX_REDIRECT,
175                protocols_allowed => [ 'http', 'https' ],
176                agent             => "Database-BI/$VERSION",
177                %args,
178        );
179
1114
79923
        $self->{bi_resolve} = ref($resolve) eq 'CODE' ? $resolve : \&resolve_host;
180
1114
1016
1018
1114
431
606
809
692
        $self->{bi_private} = [ map { lc } grep { defined && !ref } @{ ref($private) eq 'ARRAY' ? $private : [] } ];
181
1114
866
        return $self;
182}
183
184sub private_host_allowed {
185
1071
6074
        my ($self, $host) = @_;
186
1071
463
        $host = lc($host // '');
187
1071
1071
371
950
        for my $name (@{ $self->{bi_private} }) {
188
1060
425
                return 1 if $name eq $host;
189
1052
610
                return 1 if $name =~ /\A\*(\..+)\z/ && length($host) > length($1) && substr($host, -length $1) eq $1;
190        }
191
1057
468
        return 0;
192}
193
194sub _refuse {
195
68
43
        my ($request, $why) = @_;
196
68
88
        my $res = HTTP::Response->new(403, "Refused: $why");
197
68
952
        $res->header('Client-Warning' => 'Internal response');
198
68
1606
        $res->request($request);
199
68
233
        return $res;
200}
201
202sub send_request {
203
89
27436
        my ($self, $request, $arg, $size) = @_;
204
89
53
        my $uri    = $request->uri;
205
89
232
        my $scheme = lc($uri->scheme // '');
206
89
594
        return _refuse($request, 'only http and https addresses are fetched')
207                unless $scheme eq 'http' || $scheme eq 'https';
208
80
55
        (my $name = lc($uri->host // '')) =~ s/\.\z//;
209
80
747
        return _refuse($request, 'the address names no host') unless length $name;
210
211
78
53
        my $literal = numeric_host($name);
212
78
96
        my @addrs   = defined $literal ? ($literal) : $self->{bi_resolve}->($name);
213
78
118
        return _refuse($request, "$name was not found") unless @addrs;
214
74
83
        unless (!defined $literal && $self->private_host_allowed($name)) {
215
71
36
                for my $ip (@addrs) {
216
75
52
                        my $why = blocked_address($ip) // next;
217
53
140
                        my $shown = $ip // '';
218
53
65
                        return _refuse($request, $shown eq $name ? "$name is $why" : "$name is $shown, which is $why");
219                }
220        }
221
222        # Connect to the address checked, not to the name again.
223
21
21
        my $pinned = $request->clone;
224
21
1226
        my $to     = $uri->clone;
225
21
55
        $to->host($addrs[0] =~ /:/ ? "[$addrs[0]]" : $addrs[0]);
226
21
2749
        $pinned->uri($to);
227
21
168
        my $authority = $uri->authority;
228
21
62
        $authority =~ s/\A[^\@]*\@//;
229
21
32
        $pinned->header(Host => $authority);
230        local $self->{ssl_opts} = $scheme eq 'https'
231
4
8
                ? { %{ $self->{ssl_opts} // {} }, SSL_hostname => $uri->host, SSL_verifycn_name => $uri->host }
232
21
314
                : $self->{ssl_opts};
233
234
21
85
        my $res = $self->SUPER::send_request($pinned, $arg, $size);
235
21
1029
        $res->request($request);
236
21
87
        return $res;
237}
238
2391;
240