lib/HTTPS/Handy.pm

filter: Statementstmt 79.4% 1285 / 1618 Branchbran 59.7% 461 / 772 Conditioncond 43.1% 98 / 227 MC/DCmcdc 26.2% 36 / 137 Subroutinesub 90.9% 151 / 166 Podpod 100% 10 / 10 totaltotal 69.6% 2041 / 2930 CC 481 SCAR 47.0
CC
481
Cov
70%
server_handshake
1332.0
run
462.0
__ANON__
306.0
CRAP 109.6
↑ Summary
1 package HTTPS::Handy;
2 ######################################################################
3 #
4 # HTTPS::Handy - A tiny HTTPS/1.0 server, TLS included, in pure Perl
5 #
6 # https://metacpan.org/dist/HTTPS-Handy
7 #
8 # Copyright (c) 2026 INABA Hitoshi <ina.cpan@gmail.com>
9 ######################################################################
10 #
11 # Compatible : Perl 5.005_03 and later
12 # Platform : Windows and UNIX/Linux
13 #
14 # This single file contains everything the server needs, including the
15 # TLS 1.2 implementation itself: big integer arithmetic, the P-256
16 # elliptic curve, SHA-256, HMAC, the TLS pseudo random function,
17 # ChaCha20-Poly1305, DER and PEM encoding, X.509 certificate
18 # generation, and the TLS record layer and handshake. No other module
19 # and no external program is used, so the whole of HTTPS can be read
20 # in one sitting.
21 #
22 # The packages in this file, in the order they appear:
23 #
24 # HTTPS::Handy the web server and the PSGI subset
25 # HTTPS::Handy::Input an in memory handle for psgi.input
26 # HTTPS::Handy::TLS the record layer and the handshake
27 # HTTPS::Handy::EC the P-256 curve: ECDH and ECDSA
28 # HTTPS::Handy::ChaCha ChaCha20-Poly1305, the record cipher
29 # HTTPS::Handy::Crypt SHA-256, HMAC, the PRF, randomness
30 # HTTPS::Handy::X509 DER, PEM and self-signed certificates
31 # HTTPS::Handy::RSA signing, for a certificate somebody else issued
32 # HTTPS::Handy::BigInt multiple precision integers
33 #
34 # Read them in that order: each one is used by the one above it.
35 #
36 ######################################################################
37  
38 8 ▶use 5.00503; # Universal Consensus 1998 for primetools
Subroutine BEGIN: called CC=1 SCAR=0.0
39 # Perl 5.005_03 compatibility for historical toolchains
40 # use 5.008001; # Lancaster Consensus 2013 for toolchains
41  
42 8 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
43 0 ▶BEGIN { if ($] < 5.006 && !defined(&warnings::import)) { $INC{'warnings.pm'} = 'stub'; eval 'package warnings; sub import {}' } }
Subroutine BEGIN: called CC=3 SCAR=16.5
Branch: 1 branch
BranchTrueFalseTotal
if ($] < "5.006" and not defined &warnings::import) 0 8 8
Condition33%1/3
$] < "5.006" and not defined &warnings::import
!ll&&!rl&&r
800
MC/DC0%0/2
$] < "5.006" and not defined &warnings::import
$] < "5.006" not defined &warnings::import
Truth table33%1/3
A and not(B)
A= $] < "5.006"B= not defined &warnings::import
ABresult
0X0
100
111
44 8 ▶use warnings; local $^W = 1;
Subroutine BEGIN: called CC=1 SCAR=0.0
45 # warnings.pm compatibility: stub with import() for Perl < 5.6
46  
47 8 ▶BEGIN { pop @INC if $INC[-1] eq '.' } # CVE-2016-1238: Important unsafe module load path flaw
Subroutine BEGIN: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
if $INC[-1] eq "." 0 8 8
48  
49 8 ▶use IO::Socket;
Subroutine BEGIN: called CC=1 SCAR=0.0
50 8 ▶use POSIX qw(strftime);
Subroutine BEGIN: called CC=1 SCAR=0.0
51 8 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
52  
53 8 ▶use vars qw($VERSION);
Subroutine BEGIN: called CC=1 SCAR=0.0
54 8 $VERSION = '1.01';
55 8 $VERSION = $VERSION;
56 # VERSION policy: avoid `our` for 5.005_03 compatibility.
57 # Self-assignment prevents "used only once" warning under `use strict`.
58  
59 # ----------------------------------------------------------------
60 # Status text map
61 # ----------------------------------------------------------------
62 # HTTP status codes and their standard text phrases.
63 # Keeping this as a simple hash makes it easy for beginners to see
64 # how status lines like "200 OK" are constructed.
65 # ----------------------------------------------------------------
66 8 my %STATUS_TEXT = (
67 200 => 'OK',
68 201 => 'Created',
69 204 => 'No Content',
70 301 => 'Moved Permanently',
71 302 => 'Found',
72 304 => 'Not Modified',
73 400 => 'Bad Request',
74 403 => 'Forbidden',
75 404 => 'Not Found',
76 405 => 'Method Not Allowed',
77 413 => 'Request Entity Too Large',
78 500 => 'Internal Server Error',
79 );
80  
81 # ----------------------------------------------------------------
82 # MIME type map
83 # ----------------------------------------------------------------
84 8 my %MIME = (
85 'html' => 'text/html; charset=utf-8',
86 'htm' => 'text/html; charset=utf-8',
87 'txt' => 'text/plain; charset=utf-8',
88 'text' => 'text/plain; charset=utf-8',
89 'css' => 'text/css',
90 'js' => 'application/javascript',
91 'json' => 'application/json',
92 'xml' => 'application/xml',
93 'png' => 'image/png',
94 'jpg' => 'image/jpeg',
95 'jpeg' => 'image/jpeg',
96 'gif' => 'image/gif',
97 'ico' => 'image/x-icon',
98 'svg' => 'image/svg+xml',
99 'pdf' => 'application/pdf',
100 'zip' => 'application/zip',
101 'gz' => 'application/gzip',
102 'ltsv' => 'text/plain; charset=utf-8',
103 'csv' => 'text/csv; charset=utf-8',
104 'tsv' => 'text/tab-separated-values; charset=utf-8',
105 );
106  
107 # Default max POST body size: 10MB
108 8 my $DEFAULT_MAX_POST_SIZE = 10 * 1024 * 1024;
109  
110 # How long a generated certificate is valid. Browsers refuse a
111 # certificate whose lifetime is much longer than this.
112 8 my $CERT_DAYS = 397;
113  
114 # ----------------------------------------------------------------
115 # run - Start the HTTPS server (blocking)
116 # ----------------------------------------------------------------
117 # This is the main entry point. It resolves the TLS certificate,
118 # listens on a plain TCP socket, and for every connection runs the
119 # TLS handshake before reading the HTTP request.
120 #
121 # Certificate resolution priority:
122 # 1. Explicit ssl_cert_file + ssl_key_file (user provided)
123 # 2. An existing Let's Encrypt certificate for the first of
124 # 'domains', if one is already installed on this machine
125 # 3. A self-signed certificate generated here, in Perl, and cached
126 # in cert_dir so that later runs start immediately
127 # ----------------------------------------------------------------
128 0 ▶sub run {
Subroutine run: not called CC=21 SCAR=61.4
Pod documented
129 0 my ($class, %args) = @_;
130  
131 0 ▶ my $app = $args{app} or croak "HTTPS::Handy->run: 'app' is required";
Branch: 1 branch
BranchTrueFalseTotal
my $app = $args{"app"} or croak("HTTPS::Handy->run: 'app' is required") 0 0 0
132 0 ▶ my $host = defined $args{host} ? $args{host} : '0.0.0.0';
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'host'} ? : 0 0 0
133 0 ▶ my $port = defined $args{port} ? $args{port} : 8443;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'port'} ? : 0 0 0
134 0 ▶ my $log = defined $args{log} ? $args{log} : 1;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'log'} ? : 0 0 0
135 0 ▶ my $max_post_size = defined $args{max_post_size} ? $args{max_post_size} : $DEFAULT_MAX_POST_SIZE;
Branch: 1 branch
BranchTrueFalseTotal
defined $args{'max_post_size'} ? : 0 0 0
136  
137 0 ▶ ref($app) eq 'CODE' or croak "HTTPS::Handy->run: 'app' must be a code reference";
Branch: 1 branch
BranchTrueFalseTotal
ref $app eq "CODE" or croak("HTTPS::Handy->run: 'app' must be a code reference") 0 0 0
138 0 ▶ $port =~ /^\d+$/ or croak "HTTPS::Handy->run: 'port' must be a number";
Branch: 1 branch
BranchTrueFalseTotal
$port =~ /^\d+$/ or croak("HTTPS::Handy->run: 'port' must be a number") 0 0 0
139 0 ▶ $max_post_size =~ /^\d+$/ or croak "HTTPS::Handy->run: 'max_post_size' must be a number";
Branch: 1 branch
BranchTrueFalseTotal
$max_post_size =~ /^\d+$/ or croak("HTTPS::Handy->run: 'max_post_size' must be a number") 0 0 0
140  
141 # Certificate resolution
142 0 my $cert_file = $args{ssl_cert_file};
143 0 my $key_file = $args{ssl_key_file};
144 0 my $domains = $args{domains};
145 0 ▶ my $cert_dir = $args{cert_dir} || '.https_handy_certs';
Condition0%0/2
$args{'cert_dir'} || '.https_handy_certs'
l!l
00
MC/DC0%0/1
$args{'cert_dir'} || '.https_handy_certs'
$args{'cert_dir'}
Truth table0%0/2
A
A= $args{'cert_dir'}
Aresult
11
00
146  
147 0 ▶ unless ($cert_file && $key_file) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($cert_file and $key_file) 0 0 0
Condition0%0/3
$cert_file and $key_file
!ll&&!rl&&r
000
MC/DC0%0/2
$cert_file and $key_file
$cert_file $key_file
Truth table0%0/3
A and B
A= $cert_fileB= $key_file
ABresult
0X0
100
111
148 0 ($cert_file, $key_file) = _resolve_certificate(
149 domains => $domains,
150 cert_dir => $cert_dir,
151 log => $log,
152 );
153 }
154  
155 0 my $ctx = _load_context($cert_file, $key_file);
156  
157 # A plain TCP socket. Everything above it -- the handshake, the
158 # record layer, the encryption -- is done by HTTPS::Handy::TLS.
159 0 my $server = IO::Socket::INET->new(
160 LocalAddr => $host,
161 LocalPort => $port,
162 Proto => 'tcp',
163 Listen => 10,
164 ReuseAddr => 1,
165 );
166 0 ▶ unless ($server) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($server) 0 0 0
167 0 croak "HTTPS::Handy: Cannot bind to $host:$port - $!";
168 }
169  
170 0 ▶ _log_message("HTTPS::Handy $HTTPS::Handy::VERSION started on https://$host:$port/") if $log;
Branch: 1 branch
BranchTrueFalseTotal
if $log 0 0 0
171 0 ▶ _log_message("Press Ctrl+C to stop.") if $log;
Branch: 1 branch
BranchTrueFalseTotal
if $log 0 0 0
172  
173 0 while (1) {
174 0 my $client = $server->accept;
175 0 ▶ unless ($client) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($client) 0 0 0
176 0 ▶ _log_message("Accept failed: $!") if $log;
Branch: 1 branch
BranchTrueFalseTotal
if $log 0 0 0
177 0 next;
178 }
179  
180 # Disable CRLF translation on Windows
181 0 binmode $client;
182  
183 # The TLS handshake happens here, after the TCP connection has
184 # been accepted. If the client does not speak TLS 1.2, or
185 # offers no cipher suite this module implements, it fails and
186 # the connection is dropped.
187 0 my $tls = HTTPS::Handy::TLS->server_handshake($client, $ctx);
188 0 ▶ unless ($tls) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($tls) 0 0 0
189 0 ▶ _log_message("TLS handshake failed: $@") if $log;
Branch: 1 branch
BranchTrueFalseTotal
if $log 0 0 0
190 0 close $client;
191 0 next;
192 }
193  
194 0 eval {
195 0 _handle_connection($tls, $app, $log, $max_post_size, $port);
196 };
197 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
198 0 ▶ _log_message("Error handling connection: $@") if $log;
Branch: 1 branch
BranchTrueFalseTotal
if $log 0 0 0
199 }
200  
201 0 $tls->close_tls;
202 0 close $client;
203 }
204 }
205  
206 # ----------------------------------------------------------------
207 # Certificate helpers
208 # ----------------------------------------------------------------
209 # A TLS server needs two things: a certificate to show to the client
210 # and the private key that belongs to it. Both are ordinary PEM files,
211 # and this module can either read the ones you already have or make a
212 # new self-signed pair itself.
213 # ----------------------------------------------------------------
214  
215 # _resolve_certificate - Decide which certificate files to use
216 0 ▶sub _resolve_certificate {
Subroutine _resolve_certificate: not called CC=8 SCAR=42.8
217 0 my (%opt) = @_;
218 0 my $domains = $opt{domains};
219 0 ▶ my $cert_dir = $opt{cert_dir} || '.https_handy_certs';
Condition0%0/2
$opt{'cert_dir'} || '.https_handy_certs'
l!l
00
MC/DC0%0/1
$opt{'cert_dir'} || '.https_handy_certs'
$opt{'cert_dir'}
Truth table0%0/2
A
A= $opt{'cert_dir'}
Aresult
11
00
220 0 my $log = $opt{log};
221  
222 0 ▶ if ($domains) {
Branch: 1 branch
BranchTrueFalseTotal
if ($domains) 0 0 0
223 0 ▶ my $domain = (ref($domains) eq 'ARRAY') ? $domains->[0] : $domains;
Branch: 1 branch
BranchTrueFalseTotal
ref $domains eq 'ARRAY' ? : 0 0 0
224 0 my $le_dir = "/etc/letsencrypt/live/$domain";
225 0 ▶ if (-f "$le_dir/fullchain.pem" && -f "$le_dir/privkey.pem") {
Branch: 1 branch
BranchTrueFalseTotal
if (-f "$le_dir/fullchain.pem" and -f "$le_dir/privkey.pem") 0 0 0
Condition0%0/3
-f "$le_dir/fullchain.pem" and -f "$le_dir/privkey.pem"
!ll&&!rl&&r
000
MC/DC0%0/2
-f "$le_dir/fullchain.pem" and -f "$le_dir/privkey.pem"
-f "$le_dir/fullchain.pem" -f "$le_dir/privkey.pem"
Truth table0%0/3
A and B
A= -f "$le_dir/fullchain.pem"B= -f "$le_dir/privkey.pem"
ABresult
0X0
100
111
226 0 ▶ _log_message("Using the Let's Encrypt certificate for $domain") if $log;
Branch: 1 branch
BranchTrueFalseTotal
if $log 0 0 0
227 0 return ("$le_dir/fullchain.pem", "$le_dir/privkey.pem");
228 }
229 0 ▶ _log_message("No certificate installed for $domain. "
Branch: 1 branch
BranchTrueFalseTotal
if $log 0 0 0
230 . "Generating a self-signed one instead.") if $log;
231 }
232 0 return _generate_self_signed(%opt);
233 }
234  
235 # _generate_self_signed - Create a self-signed certificate in Perl
236 #
237 # Self-signed certificates make a browser show a warning, but they
238 # need no certificate authority and no network, so a lesson can start
239 # with HTTPS working in the first minute. The key is an elliptic curve
240 # key, which takes about half a second to make here; an RSA key of
241 # comparable strength would take minutes of pure Perl. The pair is
242 # cached in cert_dir and reused on later runs.
243 3 ▶sub _generate_self_signed {
Subroutine _generate_self_signed: called CC=11 SCAR=27.8
244 3 my (%opt) = @_;
245 3 ▶ my $cert_dir = $opt{cert_dir} || '.https_handy_certs';
Condition50%1/2
$opt{'cert_dir'} || '.https_handy_certs'
l!l
30
MC/DC0%0/1
$opt{'cert_dir'} || '.https_handy_certs'
$opt{'cert_dir'}
Truth table50%1/2
A
A= $opt{'cert_dir'}
Aresult
11
00
246 3 my $log = $opt{log};
247 3 my $key_file = "$cert_dir/selfsigned-key.pem";
248 3 my $cert_file = "$cert_dir/selfsigned-cert.pem";
249  
250 3 ▶ if (-f $cert_file && -f $key_file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-f $cert_file and -f $key_file) 1 2 3
Condition66%2/3
-f $cert_file and -f $key_file
!ll&&!rl&&r
201
MC/DC50%1/2
-f $cert_file and -f $key_file
-f $cert_file -f $key_file
Truth table66%2/3
A and B
A= -f $cert_fileB= -f $key_file
ABresult
0X0
100
111
251 1 ▶ _log_message("Using existing self-signed certificate.") if $log;
Branch: 1 branch
BranchTrueFalseTotal
if $log 0 1 1
252 1 return ($cert_file, $key_file);
253 }
254  
255 2 ▶ mkdir $cert_dir, 0700 unless -d $cert_dir;
Branch: 1 branch
BranchTrueFalseTotal
unless -d $cert_dir 2 0 2
256  
257 2 my @hosts = ('localhost', '127.0.0.1');
258 2 my $cn = 'localhost';
259 2 ▶ if ($opt{domains}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opt{"domains"}) 0 2 2
260 0 ▶ my @d = (ref($opt{domains}) eq 'ARRAY') ? @{ $opt{domains} } : ($opt{domains});
Branch: 1 branch
BranchTrueFalseTotal
ref $opt{'domains'} eq 'ARRAY' ? : 0 0 0
261 0 ▶ if (@d) {
Branch: 1 branch
BranchTrueFalseTotal
if (@d) 0 0 0
262 0 $cn = $d[0];
263 0 @hosts = (@d, 'localhost', '127.0.0.1');
264 }
265 }
266  
267 2 ▶ _log_message("Generating a P-256 key and a self-signed certificate for $cn ...") if $log;
Branch: 1 branch
BranchTrueFalseTotal
if $log 0 2 2
268 2 my $key = HTTPS::Handy::EC::generate_key();
269 2 my $der = HTTPS::Handy::X509::make_self_signed(
270 key => $key,
271 cn => $cn,
272 hosts => [ @hosts ],
273 days => $CERT_DAYS,
274 );
275  
276 2 _write_file($key_file, HTTPS::Handy::X509::private_key_to_pem_any($key));
277 2 _write_file($cert_file, HTTPS::Handy::X509::pem_wrap('CERTIFICATE', $der));
278 2 chmod 0600, $key_file;
279  
280 2 ▶ _log_message("Self-signed certificate created at $cert_file") if $log;
Branch: 1 branch
BranchTrueFalseTotal
if $log 0 2 2
281 2 return ($cert_file, $key_file);
282 }
283  
284 # _load_context - Read the certificate chain and the private key
285 #
286 # The key may be an elliptic curve key (BEGIN EC PRIVATE KEY) or an
287 # RSA key (BEGIN RSA PRIVATE KEY), in either case unencrypted, and
288 # either may also arrive in the PKCS #8 wrapper that simply says
289 # BEGIN PRIVATE KEY.
290 1 ▶sub _load_context {
Subroutine _load_context: called CC=9 SCAR=27.3
291 1 my ($cert_file, $key_file) = @_;
292  
293 1 my $cert_pem = _read_file($cert_file);
294 1 ▶ defined $cert_pem
Branch: 1 branch
BranchTrueFalseTotal
defined $cert_pem or croak("HTTPS::Handy: Cannot read certificate file ${cert_file}: $!") 1 0 1
295 or croak "HTTPS::Handy: Cannot read certificate file $cert_file: $!";
296 1 my @chain = HTTPS::Handy::X509::pem_blocks($cert_pem, 'CERTIFICATE');
297 @chain
298 1 ▶ or croak "HTTPS::Handy: No CERTIFICATE block found in $cert_file";
Branch: 1 branch
BranchTrueFalseTotal
@chain or croak("HTTPS::Handy: No CERTIFICATE block found in $cert_file") 1 0 1
299  
300 1 my $key_pem = _read_file($key_file);
301 1 ▶ defined $key_pem
Branch: 1 branch
BranchTrueFalseTotal
defined $key_pem or croak("HTTPS::Handy: Cannot read private key file ${key_file}: $!") 1 0 1
302 or croak "HTTPS::Handy: Cannot read private key file $key_file: $!";
303  
304 1 my $key;
305 1 my @ec = HTTPS::Handy::X509::pem_blocks($key_pem, 'EC PRIVATE KEY');
306 1 my @rsa = HTTPS::Handy::X509::pem_blocks($key_pem, 'RSA PRIVATE KEY');
307 1 my @p8 = HTTPS::Handy::X509::pem_blocks($key_pem, 'PRIVATE KEY');
308 1 ▶ if (@ec) {
Branch: 3 branches
BranchTrueFalseTotal
if (@ec) { } 1 0 1
elsif (@rsa) { } 0 0 0
elsif (@p8) { } 0 0 0
309 1 $key = HTTPS::Handy::X509::ec_private_key_from_der($ec[0]);
310 }
311 elsif (@rsa) {
312 0 $key = HTTPS::Handy::X509::private_key_from_der($rsa[0]);
313 }
314 elsif (@p8) {
315 0 $key = HTTPS::Handy::X509::ec_private_key_from_der($p8[0]);
316 0 ▶ $key = HTTPS::Handy::X509::private_key_from_der($p8[0]) unless $key;
Branch: 1 branch
BranchTrueFalseTotal
unless $key 0 0 0
317 }
318 else {
319 0 croak "HTTPS::Handy: No PRIVATE KEY block found in $key_file";
320 }
321 1 ▶ $key
Branch: 1 branch
BranchTrueFalseTotal
$key or croak("HTTPS::Handy: $key_file is not a P-256 or RSA private key this module can read") 1 0 1
322 or croak "HTTPS::Handy: $key_file is not a P-256 or RSA private key this module can read";
323  
324 1 return { 'cert_chain' => [ @chain ], 'key' => $key };
325 }
326  
327 # _read_file - Slurp a file, or return undef
328 2 ▶sub _read_file {
Subroutine _read_file: called CC=3 SCAR=11.1
329 2 my ($path) = @_;
330 2 local *FH;
331 2 ▶ open(FH, "<$path") or return undef;
Branch: 1 branch
BranchTrueFalseTotal
open FH, "<$path" or return undef 2 0 2
332 2 binmode FH;
333 2 local $/;
334 2 my $data = <FH>;
335 2 close FH;
336 2 ▶ return defined $data ? $data : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $data ? : 2 0 2
337 }
338  
339 # _write_file - Write a file, or die
340 4 ▶sub _write_file {
Subroutine _write_file: called CC=2 SCAR=7.0
341 4 my ($path, $data) = @_;
342 4 local *FH;
343 4 ▶ open(FH, ">$path") or croak "HTTPS::Handy: Cannot write $path: $!";
Branch: 1 branch
BranchTrueFalseTotal
open FH, ">$path" or croak("HTTPS::Handy: Cannot write ${path}: $!") 4 0 4
344 4 binmode FH;
345 4 print FH $data;
346 4 close FH;
347 4 return 1;
348 }
349  
350 # ----------------------------------------------------------------
351 # _handle_connection - Parse request and dispatch to app
352 # ----------------------------------------------------------------
353 # By the time this runs, the TLS handshake is over and $client is a
354 # HTTPS::Handy::TLS connection: read_line, read_bytes and write_data
355 # on it encrypt and decrypt without this code knowing anything about
356 # it. What is left is plain HTTP/1.0 -- a request line, some headers,
357 # an optional body -- and it is the same code as HTTP::Handy's, except
358 # for four keys in the PSGI environment:
359 # psgi.url_scheme => "https" (instead of "http")
360 # psgi.ssl => 1 (new key, indicates TLS is active)
361 # psgix.tls_cipher => the cipher suite this connection negotiated
362 # psgix.tls_resumed => 1 when the handshake was resumed, 0 when full
363 #
364 # The last two are there to be looked at: reload the demo page and watch
365 # psgix.tls_resumed turn from 0 into 1 as the session cache does its
366 # work. The "psgix." prefix is the conventional PSGI spelling for a
367 # key a particular server adds.
368 # ----------------------------------------------------------------
369 20 ▶sub _handle_connection {
Subroutine _handle_connection: called CC=40 SCAR=37.2
370 20 my ($client, $app, $log, $max_post_size, $server_port) = @_;
371  
372 # Read request line
373 20 my $request_line = $client->read_line();
374 20 ▶ return unless defined $request_line && $request_line ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $request_line and $request_line ne "" 1 19 20
Condition66%2/3
defined $request_line and $request_line ne ""
!ll&&!rl&&r
1019
MC/DC50%1/2
defined $request_line and $request_line ne ""
defined $request_line $request_line ne ""
Truth table66%2/3
A and B
A= defined $request_lineB= $request_line ne ""
ABresult
0X0
100
111
375  
376 19 $request_line =~ s/\r?\n$//;
377  
378 # "GET /path HTTP/1.1" splits into three. The version the client
379 # asked for is read but not used: this server always answers
380 # HTTP/1.0 and closes the connection afterwards.
381 19 my ($method, $request_uri, $http_version) = split /\s+/, $request_line, 3;
382  
383 # Only allow GET and POST
384 19 ▶ unless (defined $method && ($method eq 'GET' || $method eq 'POST')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $method and $method eq "GET" || $method eq "POST") 2 17 19
Condition100%6/6
defined $method and $method eq "GET" || $method eq "POST"
!ll&&!rl&&r
1117
$method eq "GET" or $method eq "POST"
l!l&&r!l&&!r
1431
MC/DC100%3/3
defined $method and $method eq "GET" || $method eq "POST"
defined $method $method eq "GET" $method eq "POST"
Truth table100%4/4
A and B or C
A= defined $methodB= $method eq "GET"C= $method eq "POST"
ABCresult
0XX0
1000
11X1
1011
385 2 _send_error($client, 405, 'Method Not Allowed');
386 2 return;
387 }
388  
389 # Parse URI into path and query
390 17 my ($path, $query_string) = ('/', '');
391 17 ▶ if (defined $request_uri) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $request_uri) 17 0 17
392 17 ▶ if ($request_uri =~ /^([^?]*)\?(.*)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($request_uri =~ /^([^?]*)\?(.*)$/) { } 1 16 17
393 1 $path = $1;
394 1 $query_string = $2;
395 }
396 else {
397 16 $path = $request_uri;
398 }
399 }
400 17 ▶ $path = '/' unless defined $path && $path ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $path and $path ne "" 0 17 17
Condition33%1/3
defined $path and $path ne ""
!ll&&!rl&&r
0017
MC/DC0%0/2
defined $path and $path ne ""
defined $path $path ne ""
Truth table33%1/3
A and B
A= defined $pathB= $path ne ""
ABresult
0X0
100
111
401  
402 # Read headers
403 17 my %headers;
404 17 while (1) {
405 24 my $line = $client->read_line();
406 24 ▶ last unless defined $line;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $line 0 24 24
407 24 $line =~ s/\r?\n$//;
408 24 ▶ last if $line eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $line eq "" 17 7 24
409  
410 7 ▶ if ($line =~ /^([^:]+):\s*(.*)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($line =~ /^([^:]+):\s*(.*)$/) 7 0 7
411 7 my ($name, $value) = ($1, $2);
412 # Normalize: lowercase, then convert to HTTP_* style
413 7 $name = lc $name;
414 7 $headers{$name} = $value;
415 }
416 }
417  
418 # Build $env
419 17 ▶ my $server_name = $headers{'host'} || 'localhost';
Condition100%2/2
$headers{'host'} || 'localhost'
l!l
116
MC/DC100%1/1
$headers{'host'} || 'localhost'
$headers{'host'}
Truth table100%2/2
A
A= $headers{'host'}
Aresult
11
00
420 17 $server_name =~ s/:\d+$//; # strip port from Host header
421  
422 # SERVER_PORT: prefer the port from Host header if present,
423 # otherwise use the actual bound port passed from run().
424 17 ▶ my $env_port = ($headers{'host'} && $headers{'host'} =~ /:(\d+)$/)
Branch: 1 branch
BranchTrueFalseTotal
$headers{'host'} && $headers{'host'} =~ /:(\d+)$/ ? : 1 16 17
Condition66%2/3
$headers{"host"} and $headers{"host"} =~ /:(\d+)$/
!ll&&!rl&&r
1601
MC/DC50%1/2
$headers{"host"} and $headers{"host"} =~ /:(\d+)$/
$headers{"host"} $headers{"host"} =~ /:(\d+)$/
Truth table66%2/3
A and B
A= $headers{"host"}B= $headers{"host"} =~ /:(\d+)$/
ABresult
0X0
100
111
425 ? int($1)
426 : $server_port;
427  
428 # Content-Length comes from the client, so it is believed only when
429 # it is a plain number. Anything else counts as no body at all.
430 my $content_length = defined $headers{'content-length'}
431 17 ▶ ? $headers{'content-length'} : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $headers{'content-length'} ? : 3 14 17
432 17 ▶ $content_length = ($content_length =~ /^\s*(\d+)\s*$/) ? $1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$content_length =~ /^\s*(\d+)\s*$/ ? : 16 1 17
433  
434 17 ▶ if ($content_length > $max_post_size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($content_length > $max_post_size) 1 16 17
435 1 _send_error($client, 413, 'Request Entity Too Large');
436 1 return;
437 }
438  
439 # Read POST body
440 16 my $post_body = '';
441 16 ▶ if ($method eq 'POST' && $content_length > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "POST" and $content_length > 0) 1 15 16
Condition100%3/3
$method eq "POST" and $content_length > 0
!ll&&!rl&&r
1411
MC/DC100%2/2
$method eq "POST" and $content_length > 0
$method eq "POST" $content_length > 0
Truth table100%3/3
A and B
A= $method eq "POST"B= $content_length > 0
ABresult
0X0
100
111
442 1 $post_body = $client->read_bytes($content_length);
443 }
444  
445 # Build psgi.input as an in-memory filehandle
446 # For 5.5.3 compatibility, use a simple object instead of
447 # open my $fh, '<', \$scalar (which requires Perl 5.8+)
448 16 my $input = HTTPS::Handy::Input->new($post_body);
449  
450 my %env = (
451 'REQUEST_METHOD' => $method,
452 'PATH_INFO' => $path,
453 'QUERY_STRING' => $query_string,
454 'SERVER_NAME' => $server_name,
455 'SERVER_PORT' => $env_port,
456 16 ▶ 'CONTENT_TYPE' => $headers{'content-type'} || '',
Condition100%2/2
$headers{'content-type'} || ''
l!l
115
MC/DC100%1/1
$headers{'content-type'} || ''
$headers{'content-type'}
Truth table100%2/2
A
A= $headers{'content-type'}
Aresult
11
00
457 'CONTENT_LENGTH' => $content_length,
458 'psgi.input' => $input,
459 'psgi.errors' => \*STDERR,
460 'psgi.url_scheme' => 'https',
461 'psgi.ssl' => 1,
462 'psgix.tls_cipher' => $client->cipher_name,
463 'psgix.tls_resumed' => $client->was_resumed,
464 );
465  
466 # Add HTTP_* headers
467 16 for my $name (keys %headers) {
468 6 my $key = 'HTTP_' . uc($name);
469 6 $key =~ s/-/_/g;
470 6 $env{$key} = $headers{$name};
471 }
472  
473 # Dispatch to app
474 16 my $response;
475 16 eval {
476 16 $response = $app->(\%env);
477 };
478 16 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 3 13 16
479 3 my $err = $@;
480 # Like every other message from this module, this one obeys the
481 # log option. An application that wants to record its own
482 # errors when logging is off can write to psgi.errors.
483 3 ▶ _log_message("App error: $err") if $log;
Branch: 1 branch
BranchTrueFalseTotal
if $log 1 2 3
484 3 _send_error($client, 500, 'Internal Server Error');
485 3 return;
486 }
487  
488 # Validate response
489 13 ▶ unless (ref($response) eq 'ARRAY' && scalar(@$response) == 3) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $response eq "ARRAY" and scalar @$response == 3) 2 11 13
Condition100%3/3
ref $response eq "ARRAY" and scalar @$response == 3
!ll&&!rl&&r
1111
MC/DC100%2/2
ref $response eq "ARRAY" and scalar @$response == 3
ref $response eq "ARRAY" scalar @$response == 3
Truth table100%3/3
A and B
A= ref $response eq "ARRAY"B= scalar @$response == 3
ABresult
0X0
100
111
490 2 _send_error($client, 500, 'Internal Server Error');
491 2 return;
492 }
493  
494 11 my ($status, $resp_headers, $body) = @$response;
495  
496 # The status has to be a number, or the status line it is pasted
497 # into would not be a status line any more.
498 11 ▶ $status = (defined $status && ($status =~ /^\s*(\d{3})\s*$/)) ? $1 : 500;
Branch: 1 branch
BranchTrueFalseTotal
defined $status && $status =~ /^\s*(\d{3})\s*$/ ? : 10 1 11
Condition66%2/3
defined $status and $status =~ /^\s*(\d{3})\s*$/
!ll&&!rl&&r
0110
MC/DC50%1/2
defined $status and $status =~ /^\s*(\d{3})\s*$/
defined $status $status =~ /^\s*(\d{3})\s*$/
Truth table66%2/3
A and B
A= defined $statusB= $status =~ /^\s*(\d{3})\s*$/
ABresult
0X0
100
111
499  
500 # Send response
501 11 ▶ my $status_text = $STATUS_TEXT{$status} || 'Unknown';
Condition100%2/2
$STATUS_TEXT{$status} || 'Unknown'
l!l
101
MC/DC100%1/1
$STATUS_TEXT{$status} || 'Unknown'
$STATUS_TEXT{$status}
Truth table100%2/2
A
A= $STATUS_TEXT{$status}
Aresult
11
00
502 11 my $response_str = "HTTP/1.0 $status $status_text\r\n";
503 11 $response_str .= "Connection: close\r\n";
504  
505 # Process response headers (flat array: key, value, key, value, ...)
506 #
507 # A carriage return or newline inside a header would end the header
508 # and start something else -- another header, or the body. An
509 # application that puts user input into a header without noticing
510 # would then let that user write the rest of the response, an old
511 # trick called response splitting. Removing those characters here
512 # means no application can make that mistake.
513 11 my @header_list;
514 11 ▶ if (ref($resp_headers) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $resp_headers eq "ARRAY") 11 0 11
515 11 my @h = @$resp_headers;
516 11 ▶ while (@h) {
Branch: 1 branch
BranchTrueFalseTotal
if (@h) 16 11 27
517 16 my $k = shift @h;
518 16 my $v = shift @h;
519 16 ▶ next unless defined $k;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $k 0 16 16
520 16 ▶ $v = '' unless defined $v;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $v 0 16 16
521 16 $k =~ s/[\r\n]//g;
522 16 $v =~ s/[\r\n]//g;
523 16 ▶ next if $k eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $k eq "" 0 16 16
524 16 push @header_list, "$k: $v";
525 }
526 }
527 11 ▶ $response_str .= join("\r\n", @header_list) . "\r\n" if @header_list;
Branch: 1 branch
BranchTrueFalseTotal
if @header_list 9 2 11
528 11 $response_str .= "\r\n";
529  
530 # Build body
531 11 my $body_str = '';
532 11 ▶ if (ref($body) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $body eq "ARRAY") 11 0 11
533 11 $body_str = join('', @$body);
534 }
535  
536 11 my $body_length = length($body_str);
537 11 $response_str .= $body_str;
538  
539 11 $client->write_data($response_str);
540  
541 # Access log in LTSV format.
542 # Sanitize field values: LTSV forbids tab and newline characters in values.
543 11 ▶ if ($log) {
Branch: 1 branch
BranchTrueFalseTotal
if ($log) 1 10 11
544 1 my $ts = strftime('%Y-%m-%dT%H:%M:%S', localtime);
545 1 ▶ my $ua = $headers{'user-agent'} || '';
Condition50%1/2
$headers{'user-agent'} || ''
l!l
01
MC/DC0%0/1
$headers{'user-agent'} || ''
$headers{'user-agent'}
Truth table50%1/2
A
A= $headers{'user-agent'}
Aresult
11
00
546 1 ▶ my $referer = $headers{'referer'} || '';
Condition50%1/2
$headers{'referer'} || ''
l!l
01
MC/DC0%0/1
$headers{'referer'} || ''
$headers{'referer'}
Truth table50%1/2
A
A= $headers{'referer'}
Aresult
11
00
547 1 $ua =~ s/[\t\n\r]/ /g;
548 1 $referer =~ s/[\t\n\r]/ /g;
549 1 print STDERR join("\t",
550 "time:$ts",
551 "method:$method",
552 "path:$path",
553 "status:$status",
554 "size:$body_length",
555 "ua:$ua",
556 "referer:$referer",
557 ) . "\n";
558 }
559 }
560  
561 # ----------------------------------------------------------------
562 # _send_error - Send a simple HTTP error response
563 # ----------------------------------------------------------------
564 8 ▶sub _send_error {
Subroutine _send_error: called CC=2 SCAR=7.4
565 8 my ($client, $code, $message) = @_;
566 8 ▶ my $text = $STATUS_TEXT{$code} || $message;
Condition33%1/3
$STATUS_TEXT{$code} || $message
l!l&&r!l&&!r
800
MC/DC0%0/2
$STATUS_TEXT{$code} || $message
$STATUS_TEXT{$code} $message
Truth table33%1/3
A || B
A= $STATUS_TEXT{$code}B= $message
ABresult
1X1
011
000
567 8 my $body = "<html><head><title>$code $text</title></head>"
568 . "<body><h1>$code $text</h1><p>$message</p>"
569 . "<hr><small>HTTPS::Handy/$HTTPS::Handy::VERSION</small></body></html>";
570 8 $client->write_data("HTTP/1.0 $code $text\r\n"
571 . "Content-Type: text/html\r\n"
572 . "Content-Length: " . length($body) . "\r\n"
573 . "Connection: close\r\n"
574 . "\r\n"
575 . $body);
576 }
577  
578 # ----------------------------------------------------------------
579 # _log_message - Print timestamped log to STDERR
580 # ----------------------------------------------------------------
581 1 ▶sub _log_message {
Subroutine _log_message: called CC=1 SCAR=0.0
582 1 my ($msg) = @_;
583 1 my $ts = strftime('%Y-%m-%d %H:%M:%S', localtime);
584 1 print STDERR "[$ts] $msg\n";
585 }
586  
587 # ----------------------------------------------------------------
588 # serve_static - Serve files from a document root
589 # ----------------------------------------------------------------
590 25 ▶sub serve_static {
Subroutine serve_static: called CC=12 SCAR=24.9
Pod documented
591 25 my ($class, $env, $docroot, %opts) = @_;
592  
593 25 ▶ $docroot ||= '.';
Condition100%2/2
$docroot ||= "."
l!l
241
MC/DC100%1/1
$docroot ||= "."
$docroot
Truth table100%2/2
A
A= $docroot
Aresult
11
00
594 # Remove trailing slash
595 25 $docroot =~ s{[/\\]$}{};
596  
597 25 ▶ my $path = $env->{PATH_INFO} || '/';
Condition50%1/2
$env->{'PATH_INFO'} || '/'
l!l
250
MC/DC0%0/1
$env->{'PATH_INFO'} || '/'
$env->{'PATH_INFO'}
Truth table50%1/2
A
A= $env->{'PATH_INFO'}
Aresult
11
00
598  
599 # Prevent path traversal via ".."
600 25 ▶ if ($path =~ /\.\./) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ /\.\./) 4 21 25
601 4 return [403, ['Content-Type', 'text/plain'], ['Forbidden']];
602 }
603  
604 # A null byte in a path once truncated file names inside the
605 # operating system, which turned "secret.txt\0.html" into
606 # "secret.txt". Perl is not fooled, but it warns, and a path with
607 # control characters in it is not a real request in any case.
608 21 ▶ if ($path =~ /[\x00-\x1F\x7F]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ /[\x00-\x1F\x7F]/) 2 19 21
609 2 return [403, ['Content-Type', 'text/plain'], ['Forbidden']];
610 }
611  
612 # Normalize separators on Windows
613 19 $path =~ s{\\}{/}g;
614  
615 # Strip leading slashes to prevent absolute path injection
616 19 $path =~ s{^/+}{/};
617  
618 19 my $file = $docroot . $path;
619  
620 # Directory: try index.html
621 19 ▶ if (-d $file) {
Branch: 1 branch
BranchTrueFalseTotal
if (-d $file) 3 16 19
622 3 $file =~ s{/?$}{/index.html};
623 }
624  
625 19 ▶ unless (-f $file) {
Branch: 1 branch
BranchTrueFalseTotal
unless (-f $file) 3 16 19
626 3 return [404, ['Content-Type', 'text/plain'], ['Not Found']];
627 }
628  
629 # Determine MIME type from extension
630 16 my $ext = '';
631 16 ▶ if ($file =~ /\.([^.]+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($file =~ /\.([^.]+)$/) 16 0 16
632 16 $ext = lc $1;
633 }
634 16 ▶ my $mime = $MIME{$ext} || 'application/octet-stream';
Condition100%2/2
$MIME{$ext} || 'application/octet-stream'
l!l
151
MC/DC100%1/1
$MIME{$ext} || 'application/octet-stream'
$MIME{$ext}
Truth table100%2/2
A
A= $MIME{$ext}
Aresult
11
00
635  
636 # Read file
637 16 local *FH;
638 16 ▶ unless (open FH, "<$file") {
Branch: 1 branch
BranchTrueFalseTotal
unless (open FH, "<$file") 0 16 16
639 0 return [403, ['Content-Type', 'text/plain'], ['Forbidden']];
640 }
641 16 binmode FH;
642 16 local $/;
643 16 my $content = <FH>;
644 16 close FH;
645  
646 # Cache-Control header
647 16 my @cache_headers;
648 16 ▶ if (exists $opts{cache_max_age}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts{'cache_max_age'}) { } 3 13 16
649 3 my $age = int($opts{cache_max_age});
650 3 ▶ if ($age > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($age > 0) { } 2 1 3
651 2 push @cache_headers, 'Cache-Control', "public, max-age=$age";
652 }
653 else {
654 1 push @cache_headers, 'Cache-Control', 'no-cache';
655 }
656 }
657 else {
658 # Default: no-cache (safe for development use)
659 13 push @cache_headers, 'Cache-Control', 'no-cache';
660 }
661  
662 16 return [200,
663 ['Content-Type', $mime,
664 'Content-Length', length($content),
665 @cache_headers],
666 [$content]];
667 }
668  
669 # ----------------------------------------------------------------
670 # url_decode - Decode percent-encoded string
671 # ----------------------------------------------------------------
672 35 ▶sub url_decode {
Subroutine url_decode: called CC=2 SCAR=6.9
Pod documented
673 35 my ($class, $str) = @_;
674 35 ▶ return '' unless defined $str;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $str 1 34 35
675 34 $str =~ s/\+/ /g;
676 34 $str =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/eg;
677 34 return $str;
678 }
679  
680 # ----------------------------------------------------------------
681 # parse_query - Parse query string into hash
682 # ----------------------------------------------------------------
683 9 ▶sub parse_query {
Subroutine parse_query: called CC=8 SCAR=20.8
Pod documented
684 9 my ($class, $query) = @_;
685 9 ▶ return () unless defined $query && $query ne '';
Branch: 1 branch
BranchTrueFalseTotal
unless defined $query and $query ne "" 2 7 9
Condition100%3/3
defined $query and $query ne ""
!ll&&!rl&&r
117
MC/DC100%2/2
defined $query and $query ne ""
defined $query $query ne ""
Truth table100%3/3
A and B
A= defined $queryB= $query ne ""
ABresult
0X0
100
111
686 7 my %params;
687 7 for my $pair (split /&/, $query) {
688 13 my ($key, $val) = split /=/, $pair, 2;
689 13 ▶ next unless defined $key;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $key 0 13 13
690 13 $key = $class->url_decode($key);
691 13 ▶ $val = defined $val ? $class->url_decode($val) : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $val ? : 12 1 13
692 13 ▶ if (exists $params{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{$key}) { } 3 10 13
693 3 ▶ if (ref $params{$key} eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $params{$key} eq 'ARRAY') { } 1 2 3
694 1 push @{$params{$key}}, $val;
695 }
696 else {
697 2 $params{$key} = [$params{$key}, $val];
698 }
699 }
700 else {
701 10 $params{$key} = $val;
702 }
703 }
704 7 return %params;
705 }
706  
707 # ----------------------------------------------------------------
708 # mime_type - Return MIME type for a file extension
709 # ----------------------------------------------------------------
710 13 ▶sub mime_type {
Subroutine mime_type: called CC=2 SCAR=6.9
Pod documented
711 13 my ($class, $ext) = @_;
712 13 $ext = lc $ext;
713 13 $ext =~ s/^\.//;
714 13 ▶ return $MIME{$ext} || 'application/octet-stream';
Condition100%2/2
$MIME{$ext} || 'application/octet-stream'
l!l
121
MC/DC100%1/1
$MIME{$ext} || 'application/octet-stream'
$MIME{$ext}
Truth table100%2/2
A
A= $MIME{$ext}
Aresult
11
00
715 }
716  
717 # ----------------------------------------------------------------
718 # is_htmx - Return true if the request was made by htmx
719 # ----------------------------------------------------------------
720 3 ▶sub is_htmx {
Subroutine is_htmx: called CC=3 SCAR=11.0
Pod documented
721 3 my ($class, $env) = @_;
722 3 ▶ return (defined $env->{HTTP_HX_REQUEST} && $env->{HTTP_HX_REQUEST} eq 'true') ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $env->{'HTTP_HX_REQUEST'} && $env->{'HTTP_HX_REQUEST'} eq 'true' ? : 1 2 3
Condition100%3/3
defined $env->{"HTTP_HX_REQUEST"} and $env->{"HTTP_HX_REQUEST"} eq "true"
!ll&&!rl&&r
111
MC/DC100%2/2
defined $env->{"HTTP_HX_REQUEST"} and $env->{"HTTP_HX_REQUEST"} eq "true"
defined $env->{"HTTP_HX_REQUEST"} $env->{"HTTP_HX_REQUEST"} eq "true"
Truth table100%3/3
A and B
A= defined $env->{"HTTP_HX_REQUEST"}B= $env->{"HTTP_HX_REQUEST"} eq "true"
ABresult
0X0
100
111
723 }
724  
725 # ----------------------------------------------------------------
726 # response_redirect - Build a redirect response
727 # ----------------------------------------------------------------
728 2 ▶sub response_redirect {
Subroutine response_redirect: called CC=2 SCAR=6.9
Pod documented
729 2 my ($class, $location, $code) = @_;
730 2 ▶ $code ||= 302;
Condition100%2/2
$code ||= 302
l!l
11
MC/DC100%1/1
$code ||= 302
$code
Truth table100%2/2
A
A= $code
Aresult
11
00
731 2 return [$code,
732 ['Location', $location,
733 'Content-Type', 'text/plain'],
734 ["Redirect to $location"]];
735 }
736  
737 # ----------------------------------------------------------------
738 # response_json - Build a JSON response (no JSON encoding, caller provides)
739 # ----------------------------------------------------------------
740 2 ▶sub response_json {
Subroutine response_json: called CC=2 SCAR=6.9
Pod documented
741 2 my ($class, $json_str, $code) = @_;
742 2 ▶ $code ||= 200;
Condition100%2/2
$code ||= 200
l!l
11
MC/DC100%1/1
$code ||= 200
$code
Truth table100%2/2
A
A= $code
Aresult
11
00
743 2 return [$code,
744 ['Content-Type', 'application/json',
745 'Content-Length', length($json_str)],
746 [$json_str]];
747 }
748  
749 # ----------------------------------------------------------------
750 # response_html - Build an HTML response
751 # ----------------------------------------------------------------
752 1 ▶sub response_html {
Subroutine response_html: called CC=2 SCAR=7.1
Pod documented
753 1 my ($class, $html, $code) = @_;
754 1 ▶ $code ||= 200;
Condition50%1/2
$code ||= 200
l!l
01
MC/DC0%0/1
$code ||= 200
$code
Truth table50%1/2
A
A= $code
Aresult
11
00
755 1 return [$code,
756 ['Content-Type', 'text/html; charset=utf-8',
757 'Content-Length', length($html)],
758 [$html]];
759 }
760  
761 # ----------------------------------------------------------------
762 # response_text - Build a plain text response
763 # ----------------------------------------------------------------
764 9 ▶sub response_text {
Subroutine response_text: called CC=2 SCAR=6.9
Pod documented
765 9 my ($class, $text, $code) = @_;
766 9 ▶ $code ||= 200;
Condition100%2/2
$code ||= 200
l!l
18
MC/DC100%1/1
$code ||= 200
$code
Truth table100%2/2
A
A= $code
Aresult
11
00
767 9 return [$code,
768 ['Content-Type', 'text/plain; charset=utf-8',
769 'Content-Length', length($text)],
770 [$text]];
771 }
772  
773 # ----------------------------------------------------------------
774 # HTTPS::Handy::Input - Minimal in-memory filehandle for psgi.input
775 # Compatible with Perl 5.5.3 (no open with scalar ref)
776 # ----------------------------------------------------------------
777 # This is the same implementation as HTTP::Handy::Input.
778 # It exists because Perl 5.5.3 does not support:
779 # open my $fh, '<', \$scalar;
780 # Instead, we implement read(), seek(), tell(), getline(), and
781 # getlines() as methods on a blessed hash.
782 # ----------------------------------------------------------------
783 package HTTPS::Handy::Input;
784  
785 18 ▶sub new {
Subroutine new: called CC=2 SCAR=7.1
786 18 my ($class, $data) = @_;
787 18 ▶ $data = '' unless defined $data;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data 0 18 18
788 18 return bless { data => $data, pos => 0 }, $class;
789 }
790  
791 3 ▶sub read {
Subroutine read: called CC=5 SCAR=16.2
792 # Note: $_[1] is the caller's buffer variable -- modified in place.
793 # We do NOT include it in the my() list because:
794 # (a) we must write back via $_[1], not a copy, and
795 # (b) "my ($self, undef, $length)" requires Perl 5.10+.
796 3 my $self = $_[0];
797 3 my $length = $_[2];
798 3 ▶ my $offset = $_[3] || 0;
Condition50%1/2
$_[3] || 0
l!l
03
MC/DC0%0/1
$_[3] || 0
$_[3]
Truth table50%1/2
A
A= $_[3]
Aresult
11
00
799 3 my $remaining = length($self->{data}) - $self->{pos};
800 3 ▶ $length = $remaining if $length > $remaining;
Branch: 1 branch
BranchTrueFalseTotal
if $length > $remaining 0 3 3
801 3 ▶ return 0 if $length <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $length <= 0 1 2 3
802 2 my $chunk = substr($self->{data}, $self->{pos}, $length);
803 2 $self->{pos} += $length;
804 # Write into $_[1] at $offset (like POSIX read). The built-in read
805 # populates the buffer regardless of its prior contents and does not
806 # warn when the caller passes an undefined buffer; match that contract
807 # by treating an undefined buffer as empty before the in-place substr.
808 2 ▶ $_[1] = '' unless defined $_[1];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[1] 1 1 2
809 2 substr($_[1], $offset) = $chunk;
810 2 return $length;
811 }
812  
813 1 ▶sub seek {
Subroutine seek: called CC=6 SCAR=23.5
814 1 my ($self, $pos, $whence) = @_;
815 1 ▶ $whence ||= 0;
Condition50%1/2
$whence ||= 0
l!l
01
MC/DC0%0/1
$whence ||= 0
$whence
Truth table50%1/2
A
A= $whence
Aresult
11
00
816 1 ▶ if ($whence == 0) {
Branch: 3 branches
BranchTrueFalseTotal
if ($whence == 0) { } 1 0 1
elsif ($whence == 1) { } 0 0 0
elsif ($whence == 2) { } 0 0 0
817 1 $self->{pos} = $pos;
818 }
819 elsif ($whence == 1) {
820 0 $self->{pos} += $pos;
821 }
822 elsif ($whence == 2) {
823 0 $self->{pos} = length($self->{data}) + $pos;
824 }
825 1 ▶ $self->{pos} = 0 if $self->{pos} < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"pos"} < 0 0 1 1
826 1 return 1;
827 }
828  
829 3 ▶sub tell {
Subroutine tell: called CC=1 SCAR=0.0
830 3 my ($self) = @_;
831 3 return $self->{pos};
832 }
833  
834 5 ▶sub getline {
Subroutine getline: called CC=3 SCAR=11.0
835 5 my ($self) = @_;
836 5 ▶ return undef if $self->{pos} >= length($self->{data});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"pos"} >= length $self->{"data"} 1 4 5
837 4 my $nl = index($self->{data}, "\n", $self->{pos});
838 4 my $line;
839 4 ▶ if ($nl < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nl < 0) { } 2 2 4
840 2 $line = substr($self->{data}, $self->{pos});
841 2 $self->{pos} = length($self->{data});
842 }
843 else {
844 2 $line = substr($self->{data}, $self->{pos}, $nl - $self->{pos} + 1);
845 2 $self->{pos} = $nl + 1;
846 }
847 4 return $line;
848 }
849  
850 1 ▶sub getlines {
Subroutine getlines: called CC=2 SCAR=6.9
851 1 my ($self) = @_;
852 1 my @lines;
853 1 ▶ while (defined(my $line = $self->getline)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = $self->getline)) 3 1 4
854 3 push @lines, $line;
855 }
856 1 return @lines;
857 }
858  
859 ######################################################################
860 # HTTPS::Handy::TLS - A TLS 1.2 record layer and handshake
861 ######################################################################
862 # This is the core of the module. Everything above it is an ordinary
863 # web server and everything below it is arithmetic; here is where the
864 # two meet.
865 #
866 # A full handshake, in the order it happens:
867 #
868 # client -> ClientHello which versions and ciphers it knows
869 # server -> ServerHello the version and cipher it picked
870 # server -> Certificate the server public key, signed
871 # server -> ServerKeyExchange a one time curve point, signed
872 # server -> ServerHelloDone
873 # client -> ClientKeyExchange its own one time curve point
874 # client -> ChangeCipherSpec everything after this is encrypted
875 # client -> Finished a hash of the whole handshake
876 # server -> ChangeCipherSpec
877 # server -> Finished
878 #
879 # Both sides multiply their own secret number by the other side's
880 # point. The two results are equal, nobody watching can work out what
881 # it is, and neither side ever sends it. That shared value becomes the
882 # pre-master secret, the PRF turns it into keys, and every record from
883 # then on is sealed with ChaCha20-Poly1305.
884 #
885 # Because each side's secret number is thrown away when the connection
886 # ends, recorded traffic cannot be decrypted later even if the server
887 # key is stolen. That property is called forward secrecy, and it is the
888 # reason this module does the extra work of ECDHE instead of simply
889 # encrypting a secret to the server certificate.
890 ######################################################################
891  
892 package HTTPS::Handy::TLS;
893  
894 # Record content types
895 8 my $CT_CCS = 20;
896 8 my $CT_ALERT = 21;
897 8 my $CT_HANDSHAKE = 22;
898 8 my $CT_APPDATA = 23;
899  
900 # Handshake message types
901 8 my $HS_CLIENT_HELLO = 1;
902 8 my $HS_SERVER_HELLO = 2;
903 8 my $HS_CERTIFICATE = 11;
904 8 my $HS_SERVER_KEY_EXCH = 12;
905 8 my $HS_SERVER_HELLO_DONE = 14;
906 8 my $HS_CLIENT_KEY_EXCH = 16;
907 8 my $HS_FINISHED = 20;
908  
909 # TLS 1.2 on the wire
910 8 my $TLS12 = "\x03\x03";
911  
912 # The two cipher suites understood here. Both use ECDHE for forward
913 # secrecy and ChaCha20-Poly1305 to protect the data; they differ only
914 # in the kind of key the server certificate holds.
915 #
916 # 0xCCA9 TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
917 # 0xCCA8 TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
918 # The number in front of each name is what travels on the wire; a
919 # packet capture shows exactly these two bytes.
920 8 my %SUITE = (
921 0xCCA9 => { 'name' => 'TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256' },
922 0xCCA8 => { 'name' => 'TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256' },
923 );
924  
925 # Which suite goes with which kind of certificate key
926 8 my %SUITE_FOR_KEY = ( 'ec' => 0xCCA9, 'rsa' => 0xCCA8 );
927  
928 # Key material: a 32 byte key and a 12 byte fixed nonce for each side
929 8 my $KEY_LEN = 32;
930 8 my $IV_LEN = 12;
931  
932 8 my $MAX_FRAGMENT = 16384;
933  
934 # secp256r1, the one curve implemented here (RFC 8422 calls it 23)
935 8 my $NAMED_CURVE_P256 = 23;
936  
937 # Sessions that may be resumed, as
938 # session_id => { master, cipher, time, serial }
939 # where serial counts upwards on every store and every hit, so that the
940 # entry with the lowest serial is always the one used longest ago.
941 8 my %SESSION;
942 8 my $SESSION_SERIAL = 0;
943 8 my $SESSION_LIMIT = 64;
944 8 my $SESSION_LIFETIME = 3600;
945  
946 # ----------------------------------------------------------------
947 # Small helpers
948 # ----------------------------------------------------------------
949  
950 # _u24 - Three byte length field, as handshake messages use
951 49 ▶sub _u24 {
Subroutine _u24: called CC=1 SCAR=0.0
952 49 my ($n) = @_;
953 49 return pack('C3', int($n / 65536) % 256, int($n / 256) % 256, $n % 256);
954 }
955  
956 91 ▶sub _get_u24 {
Subroutine _get_u24: called CC=1 SCAR=0.0
957 91 my ($s, $off) = @_;
958 91 my @b = unpack('C3', substr($s, $off, 3));
959 91 return $b[0] * 65536 + $b[1] * 256 + $b[2];
960 }
961  
962 # ----------------------------------------------------------------
963 # Connection object
964 # ----------------------------------------------------------------
965  
966 29 ▶sub _new {
Subroutine _new: called CC=1 SCAR=0.0
967 29 my ($class, $sock, $is_server) = @_;
968 29 return bless {
969 'sock' => $sock,
970 'is_server' => $is_server,
971 'rawbuf' => '', # bytes read from the socket, not yet parsed
972 'appbuf' => '', # decrypted application data
973 'hsbuf' => '', # handshake messages seen so far (for the hash)
974 'hs_pending' => '', # a partly received handshake message
975 'read_seq' => 0,
976 'write_seq' => 0,
977 'read_on' => 0, # is the read side encrypted yet
978 'write_on' => 0,
979 'closed' => 0,
980 'resumed' => 0,
981 'error' => '',
982 }, $class;
983 }
984  
985 # ----------------------------------------------------------------
986 # Raw socket input and output
987 # ----------------------------------------------------------------
988  
989 240 ▶sub _fill {
Subroutine _fill: called CC=4 SCAR=15.0
990 240 my ($self, $want) = @_;
991 240 ▶ while (length($self->{'rawbuf'}) < $want) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->{"rawbuf"} < $want) 104 240 344
992 104 my $buf = '';
993 104 my $got = sysread($self->{'sock'}, $buf, 16384);
994 104 ▶ if (!defined $got || ($got == 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $got or $got == 0) 0 104 104
Condition33%1/3
not defined $got or $got == 0
l!l&&r!l&&!r
00104
MC/DC0%0/2
not defined $got or $got == 0
not defined $got $got == 0
Truth table33%1/3
not(A) or B
A= not defined $gotB= $got == 0
ABresult
1X1
011
000
995 0 $self->{'closed'} = 1;
996 0 return 0;
997 }
998 104 $self->{'rawbuf'} .= $buf;
999 }
1000 240 return 1;
1001 }
1002  
1003 75 ▶sub _send_raw {
Subroutine _send_raw: called CC=4 SCAR=15.0
1004 75 my ($self, $data) = @_;
1005 75 my $off = 0;
1006 75 ▶ while ($off < length($data)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($off < length $data) 75 75 150
1007 75 my $n = syswrite($self->{'sock'}, $data, length($data) - $off, $off);
1008 75 ▶ if (!defined $n || ($n <= 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $n or $n <= 0) 0 75 75
Condition33%1/3
not defined $n or $n <= 0
l!l&&r!l&&!r
0075
MC/DC0%0/2
not defined $n or $n <= 0
not defined $n $n <= 0
Truth table33%1/3
not(A) or B
A= not defined $nB= $n <= 0
ABresult
1X1
011
000
1009 0 $self->{'closed'} = 1;
1010 0 return 0;
1011 }
1012 75 $off += $n;
1013 }
1014 75 return 1;
1015 }
1016  
1017 # ----------------------------------------------------------------
1018 # Record layer
1019 # ----------------------------------------------------------------
1020 # A record is type(1) version(2) length(2) payload. Once the cipher
1021 # is switched on, the payload is the sealed data: ciphertext followed
1022 # by the 16 byte Poly1305 tag.
1023 #
1024 # The nonce is the fixed 12 byte value from the key block, exclusive
1025 # ored with the record sequence number. Every record therefore gets a
1026 # different nonce, which ChaCha20 requires absolutely: two records
1027 # under one nonce would expose both.
1028 # ----------------------------------------------------------------
1029  
1030 # _seq_bytes - The eight byte record sequence number
1031 #
1032 # The halves are separated by division rather than by a remainder,
1033 # because 2 ** 32 does not fit in a 32 bit integer and Perl would read
1034 # such a modulus as zero there.
1035 180 ▶sub _seq_bytes {
Subroutine _seq_bytes: called CC=1 SCAR=0.0
1036 180 my ($n) = @_;
1037 180 my $hi = int($n / (65536 * 65536));
1038 180 return pack('NN', $hi, $n - $hi * 65536 * 65536);
1039 }
1040  
1041 88 ▶sub _nonce {
Subroutine _nonce: called CC=1 SCAR=0.0
1042 88 my ($iv, $seq) = @_;
1043 88 return $iv ^ ("\x00\x00\x00\x00" . _seq_bytes($seq));
1044 }
1045  
1046 36 ▶sub _encrypt {
Subroutine _encrypt: called CC=3 SCAR=11.0
1047 36 my ($self, $type, $plain) = @_;
1048 36 ▶ my $key = $self->{'is_server'} ? $self->{'server_key'} : $self->{'client_key'};
Branch: 1 branch
BranchTrueFalseTotal
$self->{'is_server'} ? : 6 30 36
1049 36 ▶ my $iv = $self->{'is_server'} ? $self->{'server_iv'} : $self->{'client_iv'};
Branch: 1 branch
BranchTrueFalseTotal
$self->{'is_server'} ? : 6 30 36
1050 36 my $seq = $self->{'write_seq'};
1051 36 $self->{'write_seq'}++;
1052  
1053 # The additional data is authenticated but not encrypted, so an
1054 # attacker cannot move a record to another position or change its
1055 # declared type without the tag failing.
1056 36 my $aad = _seq_bytes($seq) . pack('C', $type) . $TLS12
1057 . pack('n', length($plain));
1058 36 return HTTPS::Handy::ChaCha::aead_encrypt($key, _nonce($iv, $seq),
1059 $aad, $plain);
1060 }
1061  
1062 53 ▶sub _decrypt {
Subroutine _decrypt: called CC=4 SCAR=14.0
1063 53 my ($self, $type, $sealed) = @_;
1064 53 ▶ my $key = $self->{'is_server'} ? $self->{'client_key'} : $self->{'server_key'};
Branch: 1 branch
BranchTrueFalseTotal
$self->{'is_server'} ? : 0 53 53
1065 53 ▶ my $iv = $self->{'is_server'} ? $self->{'client_iv'} : $self->{'server_iv'};
Branch: 1 branch
BranchTrueFalseTotal
$self->{'is_server'} ? : 0 53 53
1066 53 ▶ return undef if length($sealed) < 16;
Branch: 1 branch
BranchTrueFalseTotal
if length $sealed < 16 1 52 53
1067 52 my $seq = $self->{'read_seq'};
1068 52 $self->{'read_seq'}++;
1069  
1070 52 my $aad = _seq_bytes($seq) . pack('C', $type) . $TLS12
1071 . pack('n', length($sealed) - 16);
1072 52 return HTTPS::Handy::ChaCha::aead_decrypt($key, _nonce($iv, $seq),
1073 $aad, $sealed);
1074 }
1075  
1076 # _send_record - Write one record, encrypting it when the cipher is on
1077 75 ▶sub _send_record {
Subroutine _send_record: called CC=5 SCAR=16.4
1078 75 my ($self, $type, $data) = @_;
1079 75 while (1) {
1080 75 my $chunk = substr($data, 0, $MAX_FRAGMENT);
1081 75 ▶ $data = (length($data) > $MAX_FRAGMENT) ? substr($data, $MAX_FRAGMENT) : '';
Branch: 1 branch
BranchTrueFalseTotal
length $data > $MAX_FRAGMENT ? : 0 75 75
1082 75 ▶ my $payload = $self->{'write_on'} ? $self->_encrypt($type, $chunk) : $chunk;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'write_on'} ? : 30 45 75
1083 75 ▶ return 0 unless $self->_send_raw(pack('C', $type) . $TLS12
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_send_raw(pack("C", $type) . $TLS12 . pack("n", length $payload) . $payload) 0 75 75
1084 . pack('n', length($payload)) . $payload);
1085 75 ▶ last if $data eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $data eq "" 75 0 75
1086 }
1087 75 return 1;
1088 }
1089  
1090 # _read_record - Read one record; returns (type, plaintext)
1091 120 ▶sub _read_record {
Subroutine _read_record: called CC=10 SCAR=27.7
1092 120 my ($self) = @_;
1093 120 ▶ return () unless $self->_fill(5);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_fill(5) 0 120 120
1094 120 my $type = unpack('C', substr($self->{'rawbuf'}, 0, 1));
1095 120 my $major = unpack('C', substr($self->{'rawbuf'}, 1, 1));
1096 120 my $len = unpack('n', substr($self->{'rawbuf'}, 3, 2));
1097  
1098 # A plain HTTP request sent to this port arrives here as a record
1099 # whose type is the letter "G". Refusing anything that is not a
1100 # valid record type keeps the server from waiting for the rest of a
1101 # record that will never come.
1102 120 ▶ if ((($type < $CT_CCS) || ($type > $CT_APPDATA)) || ($major != 3)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type < $CT_CCS or $type > $CT_APPDATA or $major != 3) 0 120 120
Condition33%2/6
$type < $CT_CCS or $type > $CT_APPDATA or $major != 3
l!l&&r!l&&!r
00120
$type < $CT_CCS or $type > $CT_APPDATA
l!l&&r!l&&!r
00120
MC/DC0%0/3
$type < $CT_CCS or $type > $CT_APPDATA or $major != 3
$type < $CT_CCS $type > $CT_APPDATA $major != 3
Truth table25%1/4
A or B or C
A= $type < $CT_CCSB= $type > $CT_APPDATAC= $major != 3
ABCresult
1XX1
01X1
0011
0000
1103 0 $self->{'error'} = 'not a TLS record (is the client speaking plain HTTP?)';
1104 0 return ();
1105 }
1106 120 ▶ if ($len > $MAX_FRAGMENT + 2048) {
Branch: 1 branch
BranchTrueFalseTotal
if ($len > $MAX_FRAGMENT + 2048) 0 120 120
1107 0 $self->{'error'} = 'record too long';
1108 0 return ();
1109 }
1110 120 ▶ return () unless $self->_fill(5 + $len);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_fill(5 + $len) 0 120 120
1111 120 my $payload = substr($self->{'rawbuf'}, 5, $len);
1112 120 $self->{'rawbuf'} = substr($self->{'rawbuf'}, 5 + $len);
1113  
1114 120 ▶ if ($self->{'read_on'} && ($type != $CT_CCS)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"read_on"} and $type != $CT_CCS) 45 75 120
Condition66%2/3
$self->{"read_on"} and $type != $CT_CCS
!ll&&!rl&&r
75045
MC/DC50%1/2
$self->{"read_on"} and $type != $CT_CCS
$self->{"read_on"} $type != $CT_CCS
Truth table66%2/3
A and B
A= $self->{"read_on"}B= $type != $CT_CCS
ABresult
0X0
100
111
1115 45 $payload = $self->_decrypt($type, $payload);
1116 45 ▶ unless (defined $payload) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $payload) 0 45 45
1117 0 $self->{'error'} = 'record failed its authentication tag';
1118 0 return ();
1119 }
1120 }
1121 120 return ($type, $payload);
1122 }
1123  
1124 0 ▶sub _send_alert {
Subroutine _send_alert: not called CC=1 SCAR=6.9
1125 0 my ($self, $level, $desc) = @_;
1126 0 $self->_send_record($CT_ALERT, pack('CC', $level, $desc));
1127 0 return;
1128 }
1129  
1130 # ----------------------------------------------------------------
1131 # Handshake message plumbing
1132 # ----------------------------------------------------------------
1133  
1134 45 ▶sub _send_handshake {
Subroutine _send_handshake: called CC=1 SCAR=0.0
1135 45 my ($self, $type, $body) = @_;
1136 45 my $msg = pack('C', $type) . _u24(length($body)) . $body;
1137 45 $self->{'hsbuf'} .= $msg;
1138 45 return $self->_send_record($CT_HANDSHAKE, $msg);
1139 }
1140  
1141 # _read_handshake - Read the next handshake message; returns (type, body)
1142 75 ▶sub _read_handshake {
Subroutine _read_handshake: called CC=6 SCAR=19.2
1143 75 my ($self) = @_;
1144 75 while (1) {
1145 150 ▶ if (length($self->{'hs_pending'}) >= 4) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->{"hs_pending"} >= 4) 75 75 150
1146 75 my $body_len = _get_u24($self->{'hs_pending'}, 1);
1147 75 ▶ if (length($self->{'hs_pending'}) >= 4 + $body_len) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->{"hs_pending"} >= 4 + $body_len) 75 0 75
1148 75 my $msg = substr($self->{'hs_pending'}, 0, 4 + $body_len);
1149 75 $self->{'hs_pending'} = substr($self->{'hs_pending'}, 4 + $body_len);
1150 75 $self->{'hsbuf'} .= $msg;
1151 75 return (unpack('C', substr($msg, 0, 1)), substr($msg, 4));
1152 }
1153 }
1154 75 my ($type, $data) = $self->_read_record();
1155 75 ▶ return () unless defined $type;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type 0 75 75
1156 75 ▶ if ($type == $CT_ALERT) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type == $CT_ALERT) 0 75 75
1157 0 $self->{'error'} = 'alert from peer: ' . join('/', unpack('C*', $data));
1158 0 return ();
1159 }
1160 75 ▶ unless ($type == $CT_HANDSHAKE) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($type == $CT_HANDSHAKE) 0 75 75
1161 0 $self->{'error'} = 'unexpected record type ' . $type;
1162 0 return ();
1163 }
1164 75 $self->{'hs_pending'} .= $data;
1165 }
1166 }
1167  
1168 # _expect_ccs - Read the ChangeCipherSpec record
1169 15 ▶sub _expect_ccs {
Subroutine _expect_ccs: called CC=3 SCAR=11.8
1170 15 my ($self) = @_;
1171 15 my ($type, $data) = $self->_read_record();
1172 15 ▶ return 0 unless defined $type;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type 0 15 15
1173 15 ▶ unless ($type == $CT_CCS) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($type == $CT_CCS) 0 15 15
1174 0 $self->{'error'} = 'expected ChangeCipherSpec';
1175 0 return 0;
1176 }
1177 15 $self->{'read_on'} = 1;
1178 15 $self->{'read_seq'} = 0;
1179 15 return 1;
1180 }
1181  
1182 15 ▶sub _send_ccs {
Subroutine _send_ccs: called CC=1 SCAR=0.0
1183 15 my ($self) = @_;
1184 15 $self->_send_record($CT_CCS, "\x01");
1185 15 $self->{'write_on'} = 1;
1186 15 $self->{'write_seq'} = 0;
1187 15 return 1;
1188 }
1189  
1190 # ----------------------------------------------------------------
1191 # Key derivation (RFC 5246 section 6.3)
1192 # ----------------------------------------------------------------
1193  
1194 30 ▶sub _derive_keys {
Subroutine _derive_keys: called CC=2 SCAR=6.9
1195 30 my ($self, $premaster) = @_;
1196  
1197 $self->{'master'} = HTTPS::Handy::Crypt::prf(
1198 $premaster, 'master secret',
1199 30 ▶ $self->{'client_random'} . $self->{'server_random'}, 48)
Branch: 1 branch
BranchTrueFalseTotal
if defined $premaster 15 15 30
1200 if defined $premaster;
1201  
1202 my $block = HTTPS::Handy::Crypt::prf(
1203 $self->{'master'}, 'key expansion',
1204 30 $self->{'server_random'} . $self->{'client_random'},
1205 2 * $KEY_LEN + 2 * $IV_LEN);
1206  
1207 30 $self->{'client_key'} = substr($block, 0, $KEY_LEN);
1208 30 $self->{'server_key'} = substr($block, $KEY_LEN, $KEY_LEN);
1209 30 $self->{'client_iv'} = substr($block, 2 * $KEY_LEN, $IV_LEN);
1210 30 $self->{'server_iv'} = substr($block, 2 * $KEY_LEN + $IV_LEN, $IV_LEN);
1211 30 return 1;
1212 }
1213  
1214 # _finished_value - The 12 byte proof that both sides saw the same
1215 # handshake and hold the same master secret
1216 30 ▶sub _finished_value {
Subroutine _finished_value: called CC=1 SCAR=0.0
1217 30 my ($self, $label) = @_;
1218 return HTTPS::Handy::Crypt::prf($self->{'master'}, $label,
1219 30 HTTPS::Handy::Crypt::sha256($self->{'hsbuf'}), 12);
1220 }
1221  
1222 # ----------------------------------------------------------------
1223 # Reading a ClientHello
1224 # ----------------------------------------------------------------
1225  
1226 # _parse_hello - Pull apart a ClientHello; returns a hash reference,
1227 # or undef when the message is too short to be one
1228 #
1229 # Every length in here comes from the other end of a socket, so each
1230 # one is checked against what actually arrived before it is used. A
1231 # message that stops in the middle is refused rather than parsed into
1232 # nonsense; that is the whole reason for the repeated length tests.
1233 81 ▶sub _parse_hello {
Subroutine _parse_hello: called CC=10 SCAR=23.0
1234 81 my ($body) = @_;
1235 81 my $len = length($body);
1236 81 ▶ return undef if $len < 38; # version, random, and two lengths
Branch: 1 branch
BranchTrueFalseTotal
if $len < 38 38 43 81
1237  
1238 43 my $h = {
1239 'version' => substr($body, 0, 2),
1240 'random' => substr($body, 2, 32),
1241 'suites' => [],
1242 'ext' => {},
1243 };
1244 43 my $pos = 34;
1245 43 my $sid_len = unpack('C', substr($body, $pos, 1));
1246 43 $pos++;
1247 43 ▶ return undef if $pos + $sid_len + 2 > $len;
Branch: 1 branch
BranchTrueFalseTotal
if $pos + $sid_len + 2 > $len 31 12 43
1248 12 $h->{'session_id'} = substr($body, $pos, $sid_len);
1249 12 $pos += $sid_len;
1250  
1251 12 my $cs_len = unpack('n', substr($body, $pos, 2));
1252 12 $pos += 2;
1253 12 ▶ return undef if ($cs_len % 2) || ($pos + $cs_len + 1 > $len);
Branch: 1 branch
BranchTrueFalseTotal
if $cs_len % 2 or $pos + $cs_len + 1 > $len 3 9 12
Condition66%2/3
$cs_len % 2 or $pos + $cs_len + 1 > $len
l!l&&r!l&&!r
039
MC/DC50%1/2
$cs_len % 2 or $pos + $cs_len + 1 > $len
$cs_len % 2 $pos + $cs_len + 1 > $len
Truth table66%2/3
A or B
A= $cs_len % 2B= $pos + $cs_len + 1 > $len
ABresult
1X1
011
000
1254 9 $h->{'suites'} = [ unpack('n*', substr($body, $pos, $cs_len)) ];
1255 9 $pos += $cs_len;
1256  
1257 9 my $comp_len = unpack('C', substr($body, $pos, 1));
1258 9 $pos += 1 + $comp_len;
1259  
1260 # Extensions are optional; each is type(2) length(2) data.
1261 # A block that does not add up is a malformed message, not a
1262 # message without extensions, so it is refused outright.
1263 9 ▶ if ($pos + 2 <= $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos + 2 <= $len) 4 5 9
1264 4 my $ext_len = unpack('n', substr($body, $pos, 2));
1265 4 $pos += 2;
1266 4 ▶ return undef if $pos + $ext_len > $len;
Branch: 1 branch
BranchTrueFalseTotal
if $pos + $ext_len > $len 0 4 4
1267 4 my $ext = substr($body, $pos, $ext_len);
1268 4 my $p = 0;
1269 4 ▶ while ($p < length($ext)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($p < length $ext) 4 2 6
1270 4 ▶ return undef if $p + 4 > length($ext);
Branch: 1 branch
BranchTrueFalseTotal
if $p + 4 > length $ext 1 3 4
1271 3 my $t = unpack('n', substr($ext, $p, 2));
1272 3 my $l = unpack('n', substr($ext, $p + 2, 2));
1273 3 ▶ return undef if $p + 4 + $l > length($ext);
Branch: 1 branch
BranchTrueFalseTotal
if $p + 4 + $l > length $ext 1 2 3
1274 2 $h->{'ext'}{$t} = substr($ext, $p + 4, $l);
1275 2 $p += 4 + $l;
1276 }
1277 }
1278 7 return $h;
1279 }
1280  
1281 # _client_supports_p256 - Does the client accept the curve we implement
1282 3 ▶sub _client_supports_p256 {
Subroutine _client_supports_p256: called CC=6 SCAR=18.0
1283 3 my ($hello) = @_;
1284 3 my $groups = $hello->{'ext'}{10};
1285 3 ▶ return 1 unless defined $groups; # no opinion means anything goes
Branch: 1 branch
BranchTrueFalseTotal
unless defined $groups 1 2 3
1286 2 ▶ return 0 if length($groups) < 2;
Branch: 1 branch
BranchTrueFalseTotal
if length $groups < 2 0 2 2
1287 2 my $len = unpack('n', substr($groups, 0, 2));
1288 2 ▶ $len = length($groups) - 2 if $len > length($groups) - 2;
Branch: 1 branch
BranchTrueFalseTotal
if $len > length($groups) - 2 0 2 2
1289 2 for my $g (unpack('n*', substr($groups, 2, $len - ($len % 2)))) {
1290 2 ▶ return 1 if $g == $NAMED_CURVE_P256;
Branch: 1 branch
BranchTrueFalseTotal
if $g == $NAMED_CURVE_P256 1 1 2
1291 }
1292 1 return 0;
1293 }
1294  
1295 # ----------------------------------------------------------------
1296 # Session cache
1297 # ----------------------------------------------------------------
1298 # A full handshake costs three elliptic curve multiplications, which is
1299 # about a second and a half of pure Perl. Remembering the master secret
1300 # under a session id lets the next connection skip all of it. Browsers
1301 # open several connections per page, so without this a demonstration
1302 # would crawl.
1303 # ----------------------------------------------------------------
1304  
1305 201 ▶sub _session_store {
Subroutine _session_store: called CC=7 SCAR=19.5
1306 201 my ($id, $master, $cipher) = @_;
1307 201 my $now = time();
1308  
1309 # Throw away anything too old to be offered again
1310 201 for my $k (keys %SESSION) {
1311 10784 ▶ delete $SESSION{$k} if ($now - $SESSION{$k}{'time'}) > $SESSION_LIFETIME;
Branch: 1 branch
BranchTrueFalseTotal
if $now - $SESSION{$k}{"time"} > $SESSION_LIFETIME 0 10784 10784
1312 }
1313  
1314 # Then, if the table is still full, throw away whatever was used
1315 # longest ago until there is room. Counting with a serial number
1316 # rather than a clock keeps the order exact even when several
1317 # sessions are made within the same second.
1318 201 ▶ while (scalar(keys %SESSION) >= $SESSION_LIMIT) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar keys %SESSION >= $SESSION_LIMIT) 137 201 338
1319 137 my $oldest;
1320 137 for my $k (keys %SESSION) {
1321 $oldest = $k
1322 if !defined $oldest
1323 8768 ▶ || ($SESSION{$k}{'serial'} < $SESSION{$oldest}{'serial'});
Branch: 1 branch
BranchTrueFalseTotal
if not defined $oldest or $SESSION{$k}{"serial"} < $SESSION{$oldest}{"serial"} 658 8110 8768
Condition100%3/3
not defined $oldest or $SESSION{$k}{"serial"} < $SESSION{$oldest}{"serial"}
l!l&&r!l&&!r
1375218110
MC/DC100%2/2
not defined $oldest or $SESSION{$k}{"serial"} < $SESSION{$oldest}{"serial"}
not defined $oldest $SESSION{$k}{"serial"} < $SESSION{$oldest}{"serial"}
Truth table100%3/3
not(A) or B
A= not defined $oldestB= $SESSION{$k}{"serial"} < $SESSION{$oldest}{"serial"}
ABresult
1X1
011
000
1324 }
1325 137 delete $SESSION{$oldest};
1326 }
1327  
1328 201 $SESSION_SERIAL++;
1329 201 $SESSION{$id} = {
1330 'master' => $master,
1331 'cipher' => $cipher,
1332 'time' => $now,
1333 'serial' => $SESSION_SERIAL,
1334 };
1335 201 return;
1336 }
1337  
1338 7 ▶sub _session_find {
Subroutine _session_find: called CC=5 SCAR=16.3
1339 7 my ($id) = @_;
1340 7 ▶ return undef unless defined $id && (length($id) == 32);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and length $id == 32 3 4 7
Condition100%3/3
defined $id and length $id == 32
!ll&&!rl&&r
124
MC/DC100%2/2
defined $id and length $id == 32
defined $id length $id == 32
Truth table100%3/3
A and B
A= defined $idB= length $id == 32
ABresult
0X0
100
111
1341 4 my $s = $SESSION{$id};
1342 4 ▶ return undef unless $s;
Branch: 1 branch
BranchTrueFalseTotal
unless $s 2 2 4
1343 2 ▶ if ((time() - $s->{'time'}) > $SESSION_LIFETIME) {
Branch: 1 branch
BranchTrueFalseTotal
if (time - $s->{"time"} > $SESSION_LIFETIME) 0 2 2
1344 0 delete $SESSION{$id};
1345 0 return undef;
1346 }
1347 # Using a session keeps it alive and moves it to the front
1348 2 $SESSION_SERIAL++;
1349 2 $s->{'time'} = time();
1350 2 $s->{'serial'} = $SESSION_SERIAL;
1351 2 return $s;
1352 }
1353  
1354 # ----------------------------------------------------------------
1355 # Server side handshake
1356 # ----------------------------------------------------------------
1357 # $ctx is { cert_chain => [ DER, ... ], key => private key }
1358 # Returns the connection object, or undef with the reason in $@.
1359 # ----------------------------------------------------------------
1360  
1361 0 ▶sub server_handshake {
Subroutine server_handshake: not called CC=36 SCAR=71.9
1362 0 my ($class, $sock, $ctx) = @_;
1363 0 my $self = _new('HTTPS::Handy::TLS', $sock, 1);
1364  
1365 # --- ClientHello ---
1366 0 my ($type, $body) = $self->_read_handshake();
1367 0 ▶ unless (defined $type && ($type == $HS_CLIENT_HELLO)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $type and $type == $HS_CLIENT_HELLO) 0 0 0
Condition0%0/3
defined $type and $type == $HS_CLIENT_HELLO
!ll&&!rl&&r
000
MC/DC0%0/2
defined $type and $type == $HS_CLIENT_HELLO
defined $type $type == $HS_CLIENT_HELLO
Truth table0%0/3
A and B
A= defined $typeB= $type == $HS_CLIENT_HELLO
ABresult
0X0
100
111
1368 0 ▶ $@ = $self->{'error'} || 'no ClientHello received';
Condition0%0/2
$self->{'error'} || 'no ClientHello received'
l!l
00
MC/DC0%0/1
$self->{'error'} || 'no ClientHello received'
$self->{'error'}
Truth table0%0/2
A
A= $self->{'error'}
Aresult
11
00
1369 0 return undef;
1370 }
1371 0 my $hello = _parse_hello($body);
1372 0 ▶ unless ($hello) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($hello) 0 0 0
1373 0 $self->_send_alert(2, 50); # decode_error
1374 0 $@ = 'the ClientHello was too short to read';
1375 0 return undef;
1376 }
1377  
1378 0 ▶ if ($hello->{'version'} lt $TLS12) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hello->{"version"} lt $TLS12) 0 0 0
1379 0 $self->_send_alert(2, 70); # protocol_version
1380 0 $@ = 'client offered an older protocol than TLS 1.2';
1381 0 return undef;
1382 }
1383 0 $self->{'client_random'} = $hello->{'random'};
1384  
1385 # The cipher suite follows from the kind of key the server holds
1386 0 my $want = $SUITE_FOR_KEY{ $ctx->{'key'}{'type'} };
1387 0 my $chosen;
1388 0 for my $have (@{ $hello->{'suites'} }) {
1389 0 ▶ if ($have == $want) {
Branch: 1 branch
BranchTrueFalseTotal
if ($have == $want) 0 0 0
1390 0 $chosen = $want;
1391 0 last;
1392 }
1393 }
1394 0 ▶ unless (defined $chosen && _client_supports_p256($hello)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $chosen and _client_supports_p256($hello)) 0 0 0
Condition0%0/3
defined $chosen and _client_supports_p256($hello)
!ll&&!rl&&r
000
MC/DC0%0/2
defined $chosen and _client_supports_p256($hello)
defined $chosen _client_supports_p256($hello)
Truth table0%0/3
A and B
A= defined $chosenB= _client_supports_p256($hello)
ABresult
0X0
100
111
1395 0 $self->_send_alert(2, 40); # handshake_failure
1396 $@ = 'no cipher suite in common (this server speaks '
1397 0 . $SUITE{$want}{'name'} . ' over the P-256 curve)';
1398 0 return undef;
1399 }
1400 0 $self->{'cipher'} = $chosen;
1401 0 $self->{'suite'} = $SUITE{$chosen};
1402 0 $self->{'server_random'} = pack('N', time())
1403 . HTTPS::Handy::Crypt::random_bytes(28);
1404  
1405 # --- An abbreviated handshake, when the client knows this session ---
1406 0 my $old = _session_find($hello->{'session_id'});
1407 0 ▶ if ($old && ($old->{'cipher'} == $chosen)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($old and $old->{"cipher"} == $chosen) 0 0 0
Condition0%0/3
$old and $old->{"cipher"} == $chosen
!ll&&!rl&&r
000
MC/DC0%0/2
$old and $old->{"cipher"} == $chosen
$old $old->{"cipher"} == $chosen
Truth table0%0/3
A and B
A= $oldB= $old->{"cipher"} == $chosen
ABresult
0X0
100
111
1408 0 $self->{'master'} = $old->{'master'};
1409 0 $self->{'resumed'} = 1;
1410 return undef unless $self->_send_handshake($HS_SERVER_HELLO,
1411 0 ▶ $self->_server_hello_body($hello->{'session_id'}, $chosen));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_send_handshake($HS_SERVER_HELLO, $self->_server_hello_body($hello->{"session_id"}, $chosen)) 0 0 0
1412 0 $self->_derive_keys(undef);
1413 0 $self->_send_ccs();
1414 0 ▶ return undef unless $self->_send_handshake($HS_FINISHED,
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_send_handshake($HS_FINISHED, $self->_finished_value("server finished")) 0 0 0
1415 $self->_finished_value('server finished'));
1416 0 ▶ return undef unless $self->_expect_ccs();
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_expect_ccs 0 0 0
1417 0 my $expect = $self->_finished_value('client finished');
1418 0 ($type, $body) = $self->_read_handshake();
1419 0 ▶ unless (defined $type && ($type == $HS_FINISHED) && ($body eq $expect)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $type and $type == $HS_FINISHED and $body eq $expect) 0 0 0
Condition0%0/6
defined $type and $type == $HS_FINISHED and $body eq $expect
!ll&&!rl&&r
000
defined $type and $type == $HS_FINISHED
!ll&&!rl&&r
000
MC/DC0%0/3
defined $type and $type == $HS_FINISHED and $body eq $expect
defined $type $type == $HS_FINISHED $body eq $expect
Truth table0%0/4
A and B and C
A= defined $typeB= $type == $HS_FINISHEDC= $body eq $expect
ABCresult
0XX0
10X0
1100
1111
1420 0 ▶ $@ = $self->{'error'} || 'client Finished did not verify';
Condition0%0/2
$self->{'error'} || 'client Finished did not verify'
l!l
00
MC/DC0%0/1
$self->{'error'} || 'client Finished did not verify'
$self->{'error'}
Truth table0%0/2
A
A= $self->{'error'}
Aresult
11
00
1421 0 return undef;
1422 }
1423 0 return $self;
1424 }
1425  
1426 # --- ServerHello ---
1427 0 my $session_id = HTTPS::Handy::Crypt::random_bytes(32);
1428 0 $self->{'session_id'} = $session_id;
1429 0 ▶ return undef unless $self->_send_handshake($HS_SERVER_HELLO,
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_send_handshake($HS_SERVER_HELLO, $self->_server_hello_body($session_id, $chosen)) 0 0 0
1430 $self->_server_hello_body($session_id, $chosen));
1431  
1432 # --- Certificate ---
1433 0 my $certs = '';
1434 0 for my $der (@{ $ctx->{'cert_chain'} }) {
1435 0 $certs .= _u24(length($der)) . $der;
1436 }
1437 0 ▶ return undef unless $self->_send_handshake($HS_CERTIFICATE,
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_send_handshake($HS_CERTIFICATE, _u24(length $certs) . $certs) 0 0 0
1438 _u24(length($certs)) . $certs);
1439  
1440 # --- ServerKeyExchange ---
1441 # A fresh curve key for this connection only, and a signature over
1442 # it with the certificate key so the client knows who sent it.
1443 0 my $eph = HTTPS::Handy::EC::generate_key();
1444 0 my $point = HTTPS::Handy::EC::point_to_bin($eph->{'x'}, $eph->{'y'});
1445 0 my $params = "\x03" . pack('n', $NAMED_CURVE_P256)
1446 . pack('C', length($point)) . $point;
1447 0 ▶ my $sig_alg = ($ctx->{'key'}{'type'} eq 'ec') ? "\x04\x03" : "\x04\x01";
Branch: 1 branch
BranchTrueFalseTotal
$ctx->{'key'}{'type'} eq 'ec' ? : 0 0 0
1448 my $sig = HTTPS::Handy::X509::sign_data($ctx->{'key'},
1449 0 $self->{'client_random'} . $self->{'server_random'} . $params);
1450 0 ▶ return undef unless $self->_send_handshake($HS_SERVER_KEY_EXCH,
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_send_handshake($HS_SERVER_KEY_EXCH, $params . $sig_alg . pack("n", length $sig) . $sig) 0 0 0
1451 $params . $sig_alg . pack('n', length($sig)) . $sig);
1452  
1453 # --- ServerHelloDone ---
1454 0 ▶ return undef unless $self->_send_handshake($HS_SERVER_HELLO_DONE, '');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_send_handshake($HS_SERVER_HELLO_DONE, "") 0 0 0
1455  
1456 # --- ClientKeyExchange ---
1457 0 ($type, $body) = $self->_read_handshake();
1458 0 ▶ unless (defined $type && ($type == $HS_CLIENT_KEY_EXCH)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $type and $type == $HS_CLIENT_KEY_EXCH) 0 0 0
Condition0%0/3
defined $type and $type == $HS_CLIENT_KEY_EXCH
!ll&&!rl&&r
000
MC/DC0%0/2
defined $type and $type == $HS_CLIENT_KEY_EXCH
defined $type $type == $HS_CLIENT_KEY_EXCH
Truth table0%0/3
A and B
A= defined $typeB= $type == $HS_CLIENT_KEY_EXCH
ABresult
0X0
100
111
1459 0 ▶ $@ = $self->{'error'} || 'no ClientKeyExchange received';
Condition0%0/2
$self->{'error'} || 'no ClientKeyExchange received'
l!l
00
MC/DC0%0/1
$self->{'error'} || 'no ClientKeyExchange received'
$self->{'error'}
Truth table0%0/2
A
A= $self->{'error'}
Aresult
11
00
1460 0 return undef;
1461 }
1462 0 my $plen = unpack('C', substr($body, 0, 1));
1463 0 my ($px, $py) = HTTPS::Handy::EC::point_from_bin(substr($body, 1, $plen));
1464 0 ▶ unless (defined $px) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $px) 0 0 0
1465 0 $self->_send_alert(2, 47); # illegal_parameter
1466 0 $@ = 'the client sent a curve point this server cannot read';
1467 0 return undef;
1468 }
1469 0 my $premaster = HTTPS::Handy::EC::ecdh_shared($eph->{'d'}, $px, $py);
1470 0 ▶ unless (defined $premaster) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $premaster) 0 0 0
1471 0 $self->_send_alert(2, 47);
1472 0 $@ = 'the client sent a point that is not on the P-256 curve';
1473 0 return undef;
1474 }
1475 0 $self->_derive_keys($premaster);
1476  
1477 # --- ChangeCipherSpec and Finished from the client ---
1478 0 ▶ return undef unless $self->_expect_ccs();
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_expect_ccs 0 0 0
1479 0 my $expect = $self->_finished_value('client finished');
1480 0 ($type, $body) = $self->_read_handshake();
1481 0 ▶ unless (defined $type && ($type == $HS_FINISHED)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $type and $type == $HS_FINISHED) 0 0 0
Condition0%0/3
defined $type and $type == $HS_FINISHED
!ll&&!rl&&r
000
MC/DC0%0/2
defined $type and $type == $HS_FINISHED
defined $type $type == $HS_FINISHED
Truth table0%0/3
A and B
A= defined $typeB= $type == $HS_FINISHED
ABresult
0X0
100
111
1482 0 ▶ $@ = $self->{'error'} || 'no Finished received';
Condition0%0/2
$self->{'error'} || 'no Finished received'
l!l
00
MC/DC0%0/1
$self->{'error'} || 'no Finished received'
$self->{'error'}
Truth table0%0/2
A
A= $self->{'error'}
Aresult
11
00
1483 0 return undef;
1484 }
1485 0 ▶ unless ($body eq $expect) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($body eq $expect) 0 0 0
1486 0 $self->_send_alert(2, 51); # decrypt_error
1487 0 $@ = 'client Finished did not verify';
1488 0 return undef;
1489 }
1490  
1491 # --- ChangeCipherSpec and Finished from the server ---
1492 0 $self->_send_ccs();
1493 0 ▶ return undef unless $self->_send_handshake($HS_FINISHED,
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_send_handshake($HS_FINISHED, $self->_finished_value("server finished")) 0 0 0
1494 $self->_finished_value('server finished'));
1495  
1496 0 _session_store($session_id, $self->{'master'}, $chosen);
1497 0 return $self;
1498 }
1499  
1500 # _server_hello_body - version, random, session id, cipher, extensions
1501 0 ▶sub _server_hello_body {
Subroutine _server_hello_body: not called CC=1 SCAR=6.9
1502 0 my ($self, $session_id, $chosen) = @_;
1503 0 my $ext = pack('n', 0xFF01) . pack('n', 1) . "\x00"; # renegotiation_info
1504 0 $ext .= pack('n', 11) . pack('n', 2) . "\x01\x00"; # ec_point_formats
1505 0 return $TLS12 . $self->{'server_random'}
1506 . pack('C', length($session_id)) . $session_id
1507 . pack('n', $chosen) . "\x00"
1508 . pack('n', length($ext)) . $ext;
1509 }
1510  
1511 # ----------------------------------------------------------------
1512 # Client side handshake
1513 # ----------------------------------------------------------------
1514 # The module brings its own client so that the test suite can talk to
1515 # the server without any other TLS implementation present, and so that
1516 # both halves of the conversation can be read side by side. It does not
1517 # check the server certificate; see the SECURITY section.
1518 # ----------------------------------------------------------------
1519  
1520 15 ▶sub client_handshake {
Subroutine client_handshake: called CC=23 SCAR=38.2
1521 15 my ($class, $sock, %opt) = @_;
1522 15 my $self = _new('HTTPS::Handy::TLS', $sock, 0);
1523  
1524 15 $self->{'client_random'} = pack('N', time())
1525 . HTTPS::Handy::Crypt::random_bytes(28);
1526 15 my $suites = pack('n', 0xCCA9) . pack('n', 0xCCA8);
1527 15 my $hello = $TLS12 . $self->{'client_random'} . "\x00"
1528 . pack('n', length($suites)) . $suites
1529 . "\x01\x00"; # one compression method: none
1530  
1531 15 my $ext = '';
1532 15 ▶ if (defined $opt{'host'} && ($opt{'host'} !~ /^[\d.]+$/)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $opt{"host"} and not $opt{"host"} =~ /^[\d.]+$/) 15 0 15
Condition33%1/3
defined $opt{"host"} and not $opt{"host"} =~ /^[\d.]+$/
!ll&&!rl&&r
0015
MC/DC0%0/2
defined $opt{"host"} and not $opt{"host"} =~ /^[\d.]+$/
defined $opt{"host"} not $opt{"host"} =~ /^[\d.]+$/
Truth table33%1/3
A and not(B)
A= defined $opt{"host"}B= not $opt{"host"} =~ /^[\d.]+$/
ABresult
0X0
100
111
1533 15 my $sni = "\x00" . pack('n', length($opt{'host'})) . $opt{'host'};
1534 15 $sni = pack('n', length($sni)) . $sni;
1535 15 $ext .= pack('n', 0) . pack('n', length($sni)) . $sni;
1536 }
1537 15 my $groups = pack('n', 2) . pack('n', $NAMED_CURVE_P256);
1538 15 $ext .= pack('n', 10) . pack('n', length($groups)) . $groups;
1539 15 $ext .= pack('n', 11) . pack('n', 2) . "\x01\x00"; # uncompressed points
1540 15 my $sa = pack('n', 4) . "\x04\x03\x04\x01"; # ECDSA and RSA, SHA-256
1541 15 $ext .= pack('n', 13) . pack('n', length($sa)) . $sa;
1542 15 $hello .= pack('n', length($ext)) . $ext;
1543 15 ▶ return undef unless $self->_send_handshake($HS_CLIENT_HELLO, $hello);
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_send_handshake($HS_CLIENT_HELLO, $hello) 0 15 15
1544  
1545 # --- ServerHello ---
1546 15 my ($type, $body) = $self->_read_handshake();
1547 15 ▶ unless (defined $type && ($type == $HS_SERVER_HELLO)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $type and $type == $HS_SERVER_HELLO) 0 15 15
Condition33%1/3
defined $type and $type == $HS_SERVER_HELLO
!ll&&!rl&&r
0015
MC/DC0%0/2
defined $type and $type == $HS_SERVER_HELLO
defined $type $type == $HS_SERVER_HELLO
Truth table33%1/3
A and B
A= defined $typeB= $type == $HS_SERVER_HELLO
ABresult
0X0
100
111
1548 0 ▶ $@ = $self->{'error'} || 'no ServerHello received';
Condition0%0/2
$self->{'error'} || 'no ServerHello received'
l!l
00
MC/DC0%0/1
$self->{'error'} || 'no ServerHello received'
$self->{'error'}
Truth table0%0/2
A
A= $self->{'error'}
Aresult
11
00
1549 0 return undef;
1550 }
1551 15 $self->{'server_random'} = substr($body, 2, 32);
1552 15 my $pos = 34;
1553 15 my $sid_len = unpack('C', substr($body, $pos, 1));
1554 15 $pos += 1 + $sid_len;
1555 15 my $chosen = unpack('n', substr($body, $pos, 2));
1556 15 ▶ unless (exists $SUITE{$chosen}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $SUITE{$chosen}) 0 15 15
1557 0 $@ = 'server chose a cipher suite this client does not know';
1558 0 return undef;
1559 }
1560 15 $self->{'cipher'} = $chosen;
1561 15 $self->{'suite'} = $SUITE{$chosen};
1562  
1563 # --- Certificate, ServerKeyExchange, ServerHelloDone ---
1564 15 my $eph = HTTPS::Handy::EC::generate_key();
1565 15 my $premaster;
1566 15 while (1) {
1567 45 ($type, $body) = $self->_read_handshake();
1568 45 ▶ unless (defined $type) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $type) 0 45 45
1569 0 ▶ $@ = $self->{'error'} || 'handshake ended early';
Condition0%0/2
$self->{'error'} || 'handshake ended early'
l!l
00
MC/DC0%0/1
$self->{'error'} || 'handshake ended early'
$self->{'error'}
Truth table0%0/2
A
A= $self->{'error'}
Aresult
11
00
1570 0 return undef;
1571 }
1572 45 ▶ if ($type == $HS_CERTIFICATE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type == $HS_CERTIFICATE) 15 30 45
1573 15 my $first_len = _get_u24($body, 3);
1574 15 $self->{'peer_cert'} = substr($body, 6, $first_len);
1575 15 next;
1576 }
1577 30 ▶ if ($type == $HS_SERVER_KEY_EXCH) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type == $HS_SERVER_KEY_EXCH) 15 15 30
1578 15 ▶ unless (substr($body, 0, 1) eq "\x03") {
Branch: 1 branch
BranchTrueFalseTotal
unless (substr($body, 0, 1) eq "\3") 0 15 15
1579 0 $@ = 'the server did not offer a named curve';
1580 0 return undef;
1581 }
1582 15 my $plen = unpack('C', substr($body, 3, 1));
1583 15 my ($px, $py) = HTTPS::Handy::EC::point_from_bin(substr($body, 4, $plen));
1584 15 ▶ unless (defined $px) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $px) 0 15 15
1585 0 $@ = 'the server sent a curve point this client cannot read';
1586 0 return undef;
1587 }
1588 15 $premaster = HTTPS::Handy::EC::ecdh_shared($eph->{'d'}, $px, $py);
1589 15 next;
1590 }
1591 15 ▶ last if $type == $HS_SERVER_HELLO_DONE;
Branch: 1 branch
BranchTrueFalseTotal
if $type == $HS_SERVER_HELLO_DONE 15 0 15
1592 }
1593 15 ▶ unless (defined $premaster) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $premaster) 0 15 15
1594 0 $@ = 'no usable ServerKeyExchange received';
1595 0 return undef;
1596 }
1597  
1598 # --- ClientKeyExchange ---
1599 15 my $point = HTTPS::Handy::EC::point_to_bin($eph->{'x'}, $eph->{'y'});
1600 15 ▶ return undef unless $self->_send_handshake($HS_CLIENT_KEY_EXCH,
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_send_handshake($HS_CLIENT_KEY_EXCH, pack("C", length $point) . $point) 0 15 15
1601 pack('C', length($point)) . $point);
1602 15 $self->_derive_keys($premaster);
1603  
1604 # --- Finished, then the server answer ---
1605 15 $self->_send_ccs();
1606 15 ▶ return undef unless $self->_send_handshake($HS_FINISHED,
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_send_handshake($HS_FINISHED, $self->_finished_value("client finished")) 0 15 15
1607 $self->_finished_value('client finished'));
1608 15 ▶ return undef unless $self->_expect_ccs();
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_expect_ccs 0 15 15
1609 15 my $expect = $self->_finished_value('server finished');
1610 15 ($type, $body) = $self->_read_handshake();
1611 15 ▶ unless (defined $type && ($type == $HS_FINISHED) && ($body eq $expect)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $type and $type == $HS_FINISHED and $body eq $expect) 0 15 15
Condition33%2/6
defined $type and $type == $HS_FINISHED and $body eq $expect
!ll&&!rl&&r
0015
defined $type and $type == $HS_FINISHED
!ll&&!rl&&r
0015
MC/DC0%0/3
defined $type and $type == $HS_FINISHED and $body eq $expect
defined $type $type == $HS_FINISHED $body eq $expect
Truth table25%1/4
A and B and C
A= defined $typeB= $type == $HS_FINISHEDC= $body eq $expect
ABCresult
0XX0
10X0
1100
1111
1612 0 ▶ $@ = $self->{'error'} || 'server Finished did not verify';
Condition0%0/2
$self->{'error'} || 'server Finished did not verify'
l!l
00
MC/DC0%0/1
$self->{'error'} || 'server Finished did not verify'
$self->{'error'}
Truth table0%0/2
A
A= $self->{'error'}
Aresult
11
00
1613 0 return undef;
1614 }
1615 15 return $self;
1616 }
1617  
1618 # cert_public_key - Pull the public key out of a DER certificate
1619 # Returns an EC key { type, x, y } or an RSA key { type, n, e, size }.
1620 4 ▶sub cert_public_key {
Subroutine cert_public_key: called CC=19 SCAR=35.8
1621 4 my ($der) = @_;
1622 4 my ($tag, $cert) = HTTPS::Handy::X509::der_next($der, 0);
1623 4 ▶ return undef unless defined $tag && ($tag == 0x30);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tag and $tag == 48 1 3 4
Condition66%2/3
defined $tag and $tag == 48
!ll&&!rl&&r
013
MC/DC50%1/2
defined $tag and $tag == 48
defined $tag $tag == 48
Truth table66%2/3
A and B
A= defined $tagB= $tag == 48
ABresult
0X0
100
111
1624 3 my ($t2, $tbs) = HTTPS::Handy::X509::der_next($cert, 0);
1625 3 ▶ return undef unless defined $t2;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t2 0 3 3
1626  
1627 # Walk the fields of the TBSCertificate to the seventh one,
1628 # subjectPublicKeyInfo. The optional [0] version comes first when
1629 # it is present, which is why the fields are counted, not indexed.
1630 3 my @field = ();
1631 3 my $pos = 0;
1632 3 ▶ while ($pos < length($tbs)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < length $tbs) 18 3 21
1633 18 my ($t, $c, $next) = HTTPS::Handy::X509::der_next($tbs, $pos);
1634 18 ▶ last unless defined $t;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t 0 18 18
1635 18 push @field, [ $t, $c ];
1636 18 $pos = $next;
1637 }
1638 3 ▶ my $offset = (scalar(@field) && ($field[0][0] == 0xA0)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
scalar @field && $field[0][0] == 160 ? : 3 0 3
Condition33%1/3
scalar @field and $field[0][0] == 160
!ll&&!rl&&r
003
MC/DC0%0/2
scalar @field and $field[0][0] == 160
scalar @field $field[0][0] == 160
Truth table33%1/3
A and B
A= scalar @fieldB= $field[0][0] == 160
ABresult
0X0
100
111
1639 3 my $spki = $field[5 + $offset];
1640 3 ▶ return undef unless $spki;
Branch: 1 branch
BranchTrueFalseTotal
unless $spki 1 2 3
1641  
1642 # SubjectPublicKeyInfo = SEQUENCE { algorithm, BIT STRING key }
1643 2 my @inner = ();
1644 2 $pos = 0;
1645 2 ▶ while ($pos < length($spki->[1])) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < length $spki->[1]) 4 2 6
1646 4 my ($t, $c, $next) = HTTPS::Handy::X509::der_next($spki->[1], $pos);
1647 4 ▶ last unless defined $t;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t 0 4 4
1648 4 push @inner, [ $t, $c ];
1649 4 $pos = $next;
1650 }
1651 2 ▶ return undef unless (scalar(@inner) >= 2) && ($inner[1][0] == 0x03);
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @inner >= 2 and $inner[1][0] == 3 0 2 2
Condition33%1/3
scalar @inner >= 2 and $inner[1][0] == 3
!ll&&!rl&&r
002
MC/DC0%0/2
scalar @inner >= 2 and $inner[1][0] == 3
scalar @inner >= 2 $inner[1][0] == 3
Truth table33%1/3
A and B
A= scalar @inner >= 2B= $inner[1][0] == 3
ABresult
0X0
100
111
1652 2 my $bits = substr($inner[1][1], 1); # drop the unused bits byte
1653  
1654 # Which algorithm? The first object identifier inside the algorithm
1655 # field says whether this is an elliptic curve or an RSA key.
1656 2 my ($at, $aoid) = HTTPS::Handy::X509::der_next($inner[0][1], 0);
1657 2 ▶ my $is_ec = (defined $aoid)
Condition33%1/3
defined $aoid && unpack('H*', $aoid) eq '2a8648ce3d0201'
!ll&&!rl&&r
002
MC/DC0%0/2
defined $aoid && unpack('H*', $aoid) eq '2a8648ce3d0201'
defined $aoid unpack('H*', $aoid) eq '2a8648ce3d0201'
Truth table33%1/3
A && B
A= defined $aoidB= unpack('H*', $aoid) eq '2a8648ce3d0201'
ABresult
0X0
100
111
1658 && (unpack('H*', $aoid) eq '2a8648ce3d0201'); # 1.2.840.10045.2.1
1659 2 ▶ if ($is_ec) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_ec) 2 0 2
1660 2 my ($x, $y) = HTTPS::Handy::EC::point_from_bin($bits);
1661 2 ▶ return undef unless defined $x;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $x 0 2 2
1662 2 return { 'type' => 'ec', 'x' => $x, 'y' => $y };
1663 }
1664  
1665 0 my ($t3, $seq) = HTTPS::Handy::X509::der_next($bits, 0);
1666 0 ▶ return undef unless defined $t3;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t3 0 0 0
1667 0 my ($tn, $n, $p2) = HTTPS::Handy::X509::der_next($seq, 0);
1668 0 my ($te, $e) = HTTPS::Handy::X509::der_next($seq, $p2);
1669 0 ▶ return undef unless defined $tn && defined $te;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tn and defined $te 0 0 0
Condition0%0/3
defined $tn and defined $te
!ll&&!rl&&r
000
MC/DC0%0/2
defined $tn and defined $te
defined $tn defined $te
Truth table0%0/3
A and B
A= defined $tnB= defined $te
ABresult
0X0
100
111
1670 0 my $nn = HTTPS::Handy::BigInt::b_from_bin($n);
1671 return {
1672 0 'type' => 'rsa',
1673 'n' => $nn,
1674 'e' => HTTPS::Handy::BigInt::b_from_bin($e),
1675 'size' => length(HTTPS::Handy::BigInt::b_to_bin($nn)),
1676 };
1677 }
1678  
1679 # ----------------------------------------------------------------
1680 # Reading and writing application data
1681 # ----------------------------------------------------------------
1682  
1683 # read_bytes - Return up to $n bytes, or '' at end of stream
1684 0 ▶sub read_bytes {
Subroutine read_bytes: not called CC=6 SCAR=37.4
1685 0 my ($self, $n) = @_;
1686 0 ▶ while (length($self->{'appbuf'}) < $n) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->{"appbuf"} < $n) 0 0 0
1687 0 my ($type, $data) = $self->_read_record();
1688 0 ▶ last unless defined $type;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type 0 0 0
1689 0 ▶ if ($type == $CT_ALERT) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type == $CT_ALERT) 0 0 0
1690 0 $self->{'closed'} = 1;
1691 0 last;
1692 }
1693 0 ▶ next unless $type == $CT_APPDATA;
Branch: 1 branch
BranchTrueFalseTotal
unless $type == $CT_APPDATA 0 0 0
1694 0 $self->{'appbuf'} .= $data;
1695 }
1696 0 my $out = substr($self->{'appbuf'}, 0, $n);
1697 $self->{'appbuf'} = (length($self->{'appbuf'}) > $n)
1698 0 ▶ ? substr($self->{'appbuf'}, $n)
Branch: 1 branch
BranchTrueFalseTotal
length $self->{'appbuf'} > $n ? : 0 0 0
1699 : '';
1700 0 return $out;
1701 }
1702  
1703 # read_line - Return one line, including its terminator
1704 93 ▶sub read_line {
Subroutine read_line: called CC=11 SCAR=25.5
1705 93 my ($self, $limit) = @_;
1706 93 ▶ $limit = 8192 unless defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $limit 93 0 93
1707 93 my $line = '';
1708 93 while (1) {
1709 108 my $nl = index($self->{'appbuf'}, "\n");
1710 108 ▶ if ($nl >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($nl >= 0) 63 45 108
1711 63 $line .= substr($self->{'appbuf'}, 0, $nl + 1);
1712 63 $self->{'appbuf'} = substr($self->{'appbuf'}, $nl + 1);
1713 63 return $line;
1714 }
1715 45 $line .= $self->{'appbuf'};
1716 45 $self->{'appbuf'} = '';
1717 45 ▶ return (($line eq '') ? undef : $line) if $self->{'closed'};
Branch: 2 branches
BranchTrueFalseTotal
if $self->{"closed"} 15 30 45
$line eq '' ? : 15 0 15
1718 30 ▶ return undef if length($line) > $limit;
Branch: 1 branch
BranchTrueFalseTotal
if length $line > $limit 0 30 30
1719 30 my ($type, $data) = $self->_read_record();
1720 30 ▶ unless (defined $type) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $type) 0 30 30
1721 0 $self->{'closed'} = 1;
1722 0 ▶ return ($line eq '') ? undef : $line;
Branch: 1 branch
BranchTrueFalseTotal
$line eq '' ? : 0 0 0
1723 }
1724 30 ▶ if ($type == $CT_ALERT) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type == $CT_ALERT) 15 15 30
1725 15 $self->{'closed'} = 1;
1726 15 ▶ return ($line eq '') ? undef : $line;
Branch: 1 branch
BranchTrueFalseTotal
$line eq '' ? : 0 15 15
1727 }
1728 15 ▶ $self->{'appbuf'} .= $data if $type == $CT_APPDATA;
Branch: 1 branch
BranchTrueFalseTotal
if $type == $CT_APPDATA 15 0 15
1729 }
1730 }
1731  
1732 15 ▶sub write_data {
Subroutine write_data: called CC=2 SCAR=7.1
1733 15 my ($self, $data) = @_;
1734 15 ▶ return 0 if $self->{'closed'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} 0 15 15
1735 15 return $self->_send_record($CT_APPDATA, $data);
1736 }
1737  
1738 # ----------------------------------------------------------------
1739 # Looking at a finished connection
1740 # ----------------------------------------------------------------
1741 # Both of these end up in the PSGI environment, as psgix.tls_cipher and
1742 # psgix.tls_resumed, so an application -- or the demo page -- can show
1743 # what the handshake actually did.
1744 # ----------------------------------------------------------------
1745  
1746 # cipher_name - The name of the cipher suite in use
1747 0 ▶sub cipher_name {
Subroutine cipher_name: not called CC=2 SCAR=17.9
1748 0 my ($self) = @_;
1749 0 ▶ return $self->{'suite'} ? $self->{'suite'}{'name'} : 'none';
Branch: 1 branch
BranchTrueFalseTotal
$self->{'suite'} ? : 0 0 0
1750 }
1751  
1752 # was_resumed - 1 when this connection reused a remembered session and
1753 # skipped the curve arithmetic, 0 when it did the full handshake
1754 0 ▶sub was_resumed {
Subroutine was_resumed: not called CC=2 SCAR=17.9
1755 0 my ($self) = @_;
1756 0 ▶ return $self->{'resumed'} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'resumed'} ? : 0 0 0
1757 }
1758  
1759 0 ▶sub close_tls {
Subroutine close_tls: not called CC=2 SCAR=17.9
1760 0 my ($self) = @_;
1761 0 ▶ return if $self->{'closed'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} 0 0 0
1762 0 $self->_send_alert(1, 0); # warning, close_notify
1763 0 $self->{'closed'} = 1;
1764 0 return;
1765 }
1766  
1767 ######################################################################
1768 # HTTPS::Handy::EC - The P-256 elliptic curve
1769 ######################################################################
1770 # TLS uses an elliptic curve for two jobs: agreeing on a shared secret
1771 # (ECDH) and proving who the server is (ECDSA). Both are built from one
1772 # operation, "multiply a point by a number":
1773 #
1774 # public key = private number * G (G is a fixed point)
1775 # shared secret = my private number * your public point
1776 #
1777 # Multiplying is easy, dividing is not, and that asymmetry is the whole
1778 # of the security. The curve here is NIST P-256 (also called
1779 # secp256r1 or prime256v1), the one every browser supports.
1780 #
1781 # Points are held in Jacobian coordinates (X, Y, Z), where the affine
1782 # point is (X / Z**2, Y / Z**3). Carrying Z along means the expensive
1783 # modular inverse is done once at the end instead of once per step.
1784 # Field elements are kept in Montgomery form so that every
1785 # multiplication is a b_mont_mul with no division at all.
1786 ######################################################################
1787  
1788 package HTTPS::Handy::EC;
1789  
1790 # Curve parameters, from FIPS 186-4 / SEC 2
1791 8 my $P256_P = 'ffffffff00000001000000000000000000000000ffffffffffffffffffffffff';
1792 8 my $P256_N = 'ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551';
1793 8 my $P256_B = '5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b';
1794 8 my $P256_GX = '6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296';
1795 8 my $P256_GY = '4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5';
1796  
1797 # The curve is set up once and cached here.
1798 8 my $CURVE;
1799  
1800 92 ▶sub curve {
Subroutine curve: called CC=2 SCAR=6.9
1801 92 ▶ return $CURVE if $CURVE;
Branch: 1 branch
BranchTrueFalseTotal
if $CURVE 88 4 92
1802 4 my $p = HTTPS::Handy::BigInt::b_from_hex($P256_P);
1803 4 my $n = HTTPS::Handy::BigInt::b_from_hex($P256_N);
1804 4 my $mp = HTTPS::Handy::BigInt::b_mont_context($p);
1805 4 $CURVE = {
1806 'p' => $p,
1807 'n' => $n,
1808 'mp' => $mp, # field arithmetic
1809 'mn' => HTTPS::Handy::BigInt::b_mont_context($n), # arithmetic mod the order
1810 'gx' => HTTPS::Handy::BigInt::b_from_hex($P256_GX),
1811 'gy' => HTTPS::Handy::BigInt::b_from_hex($P256_GY),
1812 'b' => HTTPS::Handy::BigInt::b_from_hex($P256_B),
1813 };
1814 # The generator, in Montgomery form, ready for point arithmetic
1815 $CURVE->{'g'} = [
1816 HTTPS::Handy::BigInt::b_to_mont($mp, $CURVE->{'gx'}),
1817 4 HTTPS::Handy::BigInt::b_to_mont($mp, $CURVE->{'gy'}),
1818 ];
1819 4 return $CURVE;
1820 }
1821  
1822 # ----------------------------------------------------------------
1823 # Field arithmetic, modulo the curve prime, in Montgomery form
1824 # ----------------------------------------------------------------
1825  
1826 148806 ▶sub _f_add {
Subroutine _f_add: called CC=2 SCAR=6.9
1827 148806 my ($c, $a, $b) = @_;
1828 148806 my $r = HTTPS::Handy::BigInt::b_add($a, $b);
1829 $r = HTTPS::Handy::BigInt::b_sub($r, $c->{'p'})
1830 148806 ▶ if HTTPS::Handy::BigInt::b_cmp($r, $c->{'p'}) >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if HTTPS::Handy::BigInt::b_cmp($r, $c->{"p"}) >= 0 74553 74253 148806
1831 148806 return $r;
1832 }
1833  
1834 114572 ▶sub _f_sub {
Subroutine _f_sub: called CC=2 SCAR=6.9
1835 114572 my ($c, $a, $b) = @_;
1836 114572 ▶ return HTTPS::Handy::BigInt::b_sub($a, $b)
Branch: 1 branch
BranchTrueFalseTotal
if HTTPS::Handy::BigInt::b_cmp($a, $b) >= 0 57297 57275 114572
1837 if HTTPS::Handy::BigInt::b_cmp($a, $b) >= 0;
1838 return HTTPS::Handy::BigInt::b_sub(
1839 57275 HTTPS::Handy::BigInt::b_add($a, $c->{'p'}), $b);
1840 }
1841  
1842 154897 ▶sub _f_mul {
Subroutine _f_mul: called CC=1 SCAR=0.0
1843 154897 my ($c, $a, $b) = @_;
1844 154897 return HTTPS::Handy::BigInt::b_mont_mul($c->{'mp'}, $a, $b);
1845 }
1846  
1847 # _f_inv - Inverse in the field, by Fermat: a ** (p - 2) = a ** -1
1848 46 ▶sub _f_inv {
Subroutine _f_inv: called CC=1 SCAR=0.0
1849 46 my ($c, $a) = @_;
1850 46 my $e = HTTPS::Handy::BigInt::b_sub($c->{'p'}, [ 2 ]);
1851 46 return HTTPS::Handy::BigInt::b_mont_pow($c->{'mp'}, $a, $e);
1852 }
1853  
1854 # ----------------------------------------------------------------
1855 # Point arithmetic in Jacobian coordinates
1856 # ----------------------------------------------------------------
1857 # The point at infinity, which acts as zero, is written as Z = 0.
1858 # ----------------------------------------------------------------
1859  
1860 46 ▶sub _jac_infinity {
Subroutine _jac_infinity: called CC=1 SCAR=0.0
1861 46 my ($c) = @_;
1862 46 return [ $c->{'mp'}{'one'}, $c->{'mp'}{'one'}, [ 0 ] ];
1863 }
1864  
1865 17313 ▶sub _is_infinity {
Subroutine _is_infinity: called CC=2 SCAR=6.9
1866 17313 my ($pt) = @_;
1867 17313 ▶ return HTTPS::Handy::BigInt::b_is_zero($pt->[2]) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
HTTPS::Handy::BigInt::b_is_zero($pt->[2]) ? : 92 17221 17313
1868 }
1869  
1870 # _jac_double - Add a point to itself, using a = -3 (true for P-256)
1871 11470 ▶sub _jac_double {
Subroutine _jac_double: called CC=2 SCAR=6.9
1872 11470 my ($c, $pt) = @_;
1873 11470 ▶ return $pt if _is_infinity($pt);
Branch: 1 branch
BranchTrueFalseTotal
if _is_infinity($pt) 46 11424 11470
1874 11424 my ($x, $y, $z) = @$pt;
1875  
1876 11424 my $delta = _f_mul($c, $z, $z);
1877 11424 my $gamma = _f_mul($c, $y, $y);
1878 11424 my $beta = _f_mul($c, $x, $gamma);
1879  
1880 11424 my $t = _f_mul($c, _f_sub($c, $x, $delta), _f_add($c, $x, $delta));
1881 11424 my $alpha = _f_add($c, _f_add($c, $t, $t), $t); # 3 * t
1882  
1883 11424 my $beta4 = _f_add($c, $beta, $beta);
1884 11424 $beta4 = _f_add($c, $beta4, $beta4); # 4 * beta
1885 11424 my $x3 = _f_sub($c, _f_mul($c, $alpha, $alpha),
1886 _f_add($c, $beta4, $beta4)); # alpha^2 - 8 beta
1887  
1888 11424 my $yz = _f_add($c, $y, $z);
1889 11424 my $z3 = _f_sub($c, _f_sub($c, _f_mul($c, $yz, $yz), $gamma), $delta);
1890  
1891 11424 my $g2 = _f_mul($c, $gamma, $gamma);
1892 11424 my $g8 = _f_add($c, $g2, $g2);
1893 11424 $g8 = _f_add($c, $g8, $g8);
1894 11424 $g8 = _f_add($c, $g8, $g8); # 8 * gamma^2
1895 11424 my $y3 = _f_sub($c, _f_mul($c, $alpha, _f_sub($c, $beta4, $x3)), $g8);
1896  
1897 11424 return [ $x3, $y3, $z3 ];
1898 }
1899  
1900 # _jac_add_affine - Add an affine point (x, y) to a Jacobian point
1901 5797 ▶sub _jac_add_affine {
Subroutine _jac_add_affine: called CC=4 SCAR=14.1
1902 5797 my ($c, $pt, $ax, $ay) = @_;
1903 5797 ▶ return [ $ax, $ay, $c->{'mp'}{'one'} ] if _is_infinity($pt);
Branch: 1 branch
BranchTrueFalseTotal
if _is_infinity($pt) 46 5751 5797
1904 5751 my ($x1, $y1, $z1) = @$pt;
1905  
1906 5751 my $zz = _f_mul($c, $z1, $z1);
1907 5751 my $u2 = _f_mul($c, $ax, $zz);
1908 5751 my $s2 = _f_mul($c, $ay, _f_mul($c, $z1, $zz));
1909 5751 my $h = _f_sub($c, $u2, $x1);
1910 5751 my $r = _f_sub($c, $s2, $y1);
1911  
1912 5751 ▶ if (HTTPS::Handy::BigInt::b_is_zero($h)) {
Branch: 1 branch
BranchTrueFalseTotal
if (HTTPS::Handy::BigInt::b_is_zero($h)) 0 5751 5751
1913 0 ▶ return _jac_double($c, $pt) if HTTPS::Handy::BigInt::b_is_zero($r);
Branch: 1 branch
BranchTrueFalseTotal
if HTTPS::Handy::BigInt::b_is_zero($r) 0 0 0
1914 0 return _jac_infinity($c);
1915 }
1916  
1917 5751 my $hh = _f_mul($c, $h, $h);
1918 5751 my $i = _f_add($c, $hh, $hh);
1919 5751 $i = _f_add($c, $i, $i); # 4 * h^2
1920 5751 my $j = _f_mul($c, $h, $i);
1921 5751 my $r2 = _f_add($c, $r, $r); # 2 * r
1922 5751 my $v = _f_mul($c, $x1, $i);
1923  
1924 5751 my $x3 = _f_sub($c, _f_sub($c, _f_mul($c, $r2, $r2), $j),
1925 _f_add($c, $v, $v));
1926 5751 my $y1j = _f_mul($c, $y1, $j);
1927 5751 my $y3 = _f_sub($c, _f_mul($c, $r2, _f_sub($c, $v, $x3)),
1928 _f_add($c, $y1j, $y1j));
1929 5751 my $zh = _f_add($c, $z1, $h);
1930 5751 my $z3 = _f_sub($c, _f_sub($c, _f_mul($c, $zh, $zh), $zz), $hh);
1931  
1932 5751 return [ $x3, $y3, $z3 ];
1933 }
1934  
1935 # _jac_to_affine - Divide out Z, giving ordinary (x, y) in Montgomery form
1936 46 ▶sub _jac_to_affine {
Subroutine _jac_to_affine: called CC=2 SCAR=7.0
1937 46 my ($c, $pt) = @_;
1938 46 ▶ return (undef, undef) if _is_infinity($pt);
Branch: 1 branch
BranchTrueFalseTotal
if _is_infinity($pt) 0 46 46
1939 46 my $zi = _f_inv($c, $pt->[2]);
1940 46 my $zi2 = _f_mul($c, $zi, $zi);
1941 46 my $zi3 = _f_mul($c, $zi2, $zi);
1942 46 return (_f_mul($c, $pt->[0], $zi2), _f_mul($c, $pt->[1], $zi3));
1943 }
1944  
1945 # ----------------------------------------------------------------
1946 # Scalar multiplication
1947 # ----------------------------------------------------------------
1948  
1949 # _mul_point - Multiply the affine point (ax, ay) by the number $k
1950 # Returns the result as a pair of ordinary big integers, or undef for
1951 # the point at infinity.
1952 46 ▶sub _mul_point {
Subroutine _mul_point: called CC=4 SCAR=13.9
1953 46 my ($c, $k, $ax, $ay) = @_;
1954 46 my $acc = _jac_infinity($c);
1955 46 ▶ for (my $i = HTTPS::Handy::BigInt::b_bits($k) - 1; $i >= 0; $i--) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i >= 0) 11470 46 11516
1956 11470 $acc = _jac_double($c, $acc);
1957 11470 ▶ $acc = _jac_add_affine($c, $acc, $ax, $ay)
Branch: 1 branch
BranchTrueFalseTotal
if HTTPS::Handy::BigInt::b_bit($k, $i) 5797 5673 11470
1958 if HTTPS::Handy::BigInt::b_bit($k, $i);
1959 }
1960 46 my ($x, $y) = _jac_to_affine($c, $acc);
1961 46 ▶ return (undef, undef) unless defined $x;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $x 0 46 46
1962 return (HTTPS::Handy::BigInt::b_from_mont($c->{'mp'}, $x),
1963 46 HTTPS::Handy::BigInt::b_from_mont($c->{'mp'}, $y));
1964 }
1965  
1966 # mul_generator - Multiply the curve generator G by $k
1967 29 ▶sub mul_generator {
Subroutine mul_generator: called CC=1 SCAR=0.0
1968 29 my ($k) = @_;
1969 29 my $c = curve();
1970 29 return _mul_point($c, $k, $c->{'g'}[0], $c->{'g'}[1]);
1971 }
1972  
1973 # ----------------------------------------------------------------
1974 # Keys and points on the wire
1975 # ----------------------------------------------------------------
1976 # TLS sends a point as 0x04 followed by x and y, each 32 bytes
1977 # (RFC 8422, uncompressed form).
1978 # ----------------------------------------------------------------
1979  
1980 21 ▶sub point_to_bin {
Subroutine point_to_bin: called CC=1 SCAR=0.0
1981 21 my ($x, $y) = @_;
1982 21 return "\x04" . HTTPS::Handy::BigInt::b_to_bin($x, 32)
1983 . HTTPS::Handy::BigInt::b_to_bin($y, 32);
1984 }
1985  
1986 18 ▶sub point_from_bin {
Subroutine point_from_bin: called CC=3 SCAR=11.4
1987 18 my ($bin) = @_;
1988 18 ▶ return () unless length($bin) == 65;
Branch: 1 branch
BranchTrueFalseTotal
unless length $bin == 65 0 18 18
1989 18 ▶ return () unless substr($bin, 0, 1) eq "\x04";
Branch: 1 branch
BranchTrueFalseTotal
unless substr($bin, 0, 1) eq "\4" 0 18 18
1990 18 return (HTTPS::Handy::BigInt::b_from_bin(substr($bin, 1, 32)),
1991 HTTPS::Handy::BigInt::b_from_bin(substr($bin, 33, 32)));
1992 }
1993  
1994 # generate_key - A private number and the public point it gives
1995 20 ▶sub generate_key {
Subroutine generate_key: called CC=4 SCAR=14.2
1996 20 my $c = curve();
1997 20 while (1) {
1998 20 my $d = HTTPS::Handy::BigInt::b_from_bin(
1999 HTTPS::Handy::Crypt::random_bytes(32));
2000 20 ▶ next if HTTPS::Handy::BigInt::b_is_zero($d);
Branch: 1 branch
BranchTrueFalseTotal
if HTTPS::Handy::BigInt::b_is_zero($d) 0 20 20
2001 20 ▶ next if HTTPS::Handy::BigInt::b_cmp($d, $c->{'n'}) >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if HTTPS::Handy::BigInt::b_cmp($d, $c->{"n"}) >= 0 0 20 20
2002 20 my ($x, $y) = mul_generator($d);
2003 20 ▶ next unless defined $x;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $x 0 20 20
2004 20 return { 'type' => 'ec', 'd' => $d, 'x' => $x, 'y' => $y };
2005 }
2006 }
2007  
2008 # is_on_curve - Check y**2 = x**3 - 3x + b, so that a hostile peer
2009 # cannot push us onto a weaker curve of its own choosing
2010 20 ▶sub is_on_curve {
Subroutine is_on_curve: called CC=4 SCAR=13.9
2011 20 my ($x, $y) = @_;
2012 20 my $c = curve();
2013 20 ▶ return 0 if HTTPS::Handy::BigInt::b_cmp($x, $c->{'p'}) >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if HTTPS::Handy::BigInt::b_cmp($x, $c->{"p"}) >= 0 0 20 20
2014 20 ▶ return 0 if HTTPS::Handy::BigInt::b_cmp($y, $c->{'p'}) >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if HTTPS::Handy::BigInt::b_cmp($y, $c->{"p"}) >= 0 0 20 20
2015 20 my $mx = HTTPS::Handy::BigInt::b_to_mont($c->{'mp'}, $x);
2016 20 my $my = HTTPS::Handy::BigInt::b_to_mont($c->{'mp'}, $y);
2017 20 my $mb = HTTPS::Handy::BigInt::b_to_mont($c->{'mp'}, $c->{'b'});
2018 20 my $lhs = _f_mul($c, $my, $my);
2019 20 my $x3 = _f_mul($c, $mx, _f_mul($c, $mx, $mx));
2020 20 my $x3a = _f_sub($c, $x3, _f_add($c, $mx, _f_add($c, $mx, $mx))); # - 3x
2021 20 my $rhs = _f_add($c, $x3a, $mb);
2022 20 ▶ return (HTTPS::Handy::BigInt::b_cmp($lhs, $rhs) == 0) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
HTTPS::Handy::BigInt::b_cmp($lhs, $rhs) == 0 ? : 19 1 20
2023 }
2024  
2025 # ecdh_shared - The x coordinate of (my private number * peer point),
2026 # which is the pre-master secret in TLS
2027 17 ▶sub ecdh_shared {
Subroutine ecdh_shared: called CC=3 SCAR=11.1
2028 17 my ($d, $px, $py) = @_;
2029 17 my $c = curve();
2030 17 ▶ return undef unless is_on_curve($px, $py);
Branch: 1 branch
BranchTrueFalseTotal
unless is_on_curve($px, $py) 0 17 17
2031 17 my $mx = HTTPS::Handy::BigInt::b_to_mont($c->{'mp'}, $px);
2032 17 my $my = HTTPS::Handy::BigInt::b_to_mont($c->{'mp'}, $py);
2033 17 my ($x, $y) = _mul_point($c, $d, $mx, $my);
2034 17 ▶ return undef unless defined $x;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $x 0 17 17
2035 17 return HTTPS::Handy::BigInt::b_to_bin($x, 32);
2036 }
2037  
2038 # ----------------------------------------------------------------
2039 # ECDSA
2040 # ----------------------------------------------------------------
2041 # A signature is a pair (r, s):
2042 #
2043 # r = x coordinate of (k * G) for a fresh random k
2044 # s = (hash + r * private) / k all modulo the curve order n
2045 #
2046 # k must never repeat and never be guessable: two signatures made with
2047 # the same k reveal the private key outright.
2048 # ----------------------------------------------------------------
2049  
2050 # _n_mul / _n_inv - Arithmetic modulo the curve order
2051 12 ▶sub _n_mul {
Subroutine _n_mul: called CC=1 SCAR=0.0
2052 12 my ($c, $a, $b) = @_;
2053 12 my $mn = $c->{'mn'};
2054 12 return HTTPS::Handy::BigInt::b_from_mont($mn,
2055 HTTPS::Handy::BigInt::b_mont_mul($mn,
2056 HTTPS::Handy::BigInt::b_to_mont($mn, $a),
2057 HTTPS::Handy::BigInt::b_to_mont($mn, $b)));
2058 }
2059  
2060 6 ▶sub _n_inv {
Subroutine _n_inv: called CC=1 SCAR=0.0
2061 6 my ($c, $a) = @_;
2062 6 return HTTPS::Handy::BigInt::b_modinv($a, $c->{'n'});
2063 }
2064  
2065 # sign - Sign a message with SHA-256 and the private number $d
2066 # Returns the signature as the DER SEQUENCE { INTEGER r, INTEGER s }
2067 # that TLS and X.509 both expect.
2068 6 ▶sub sign {
Subroutine sign: called CC=7 SCAR=19.8
2069 6 my ($key, $message) = @_;
2070 6 my $c = curve();
2071 6 my $hash = HTTPS::Handy::BigInt::b_from_bin(
2072 HTTPS::Handy::Crypt::sha256($message));
2073 6 $hash = HTTPS::Handy::BigInt::b_mod($hash, $c->{'n'});
2074  
2075 6 while (1) {
2076 6 my $k = HTTPS::Handy::BigInt::b_from_bin(
2077 HTTPS::Handy::Crypt::random_bytes(32));
2078 6 ▶ next if HTTPS::Handy::BigInt::b_is_zero($k);
Branch: 1 branch
BranchTrueFalseTotal
if HTTPS::Handy::BigInt::b_is_zero($k) 0 6 6
2079 6 ▶ next if HTTPS::Handy::BigInt::b_cmp($k, $c->{'n'}) >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if HTTPS::Handy::BigInt::b_cmp($k, $c->{"n"}) >= 0 0 6 6
2080  
2081 6 my ($x, $y) = mul_generator($k);
2082 6 ▶ next unless defined $x;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $x 0 6 6
2083 6 my $r = HTTPS::Handy::BigInt::b_mod($x, $c->{'n'});
2084 6 ▶ next if HTTPS::Handy::BigInt::b_is_zero($r);
Branch: 1 branch
BranchTrueFalseTotal
if HTTPS::Handy::BigInt::b_is_zero($r) 0 6 6
2085  
2086 6 my $rd = _n_mul($c, $r, $key->{'d'});
2087 6 my $sum = HTTPS::Handy::BigInt::b_add($hash, $rd);
2088 $sum = HTTPS::Handy::BigInt::b_sub($sum, $c->{'n'})
2089 6 ▶ if HTTPS::Handy::BigInt::b_cmp($sum, $c->{'n'}) >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if HTTPS::Handy::BigInt::b_cmp($sum, $c->{"n"}) >= 0 2 4 6
2090 6 my $s = _n_mul($c, _n_inv($c, $k), $sum);
2091 6 ▶ next if HTTPS::Handy::BigInt::b_is_zero($s);
Branch: 1 branch
BranchTrueFalseTotal
if HTTPS::Handy::BigInt::b_is_zero($s) 0 6 6
2092  
2093 6 return HTTPS::Handy::X509::der_sequence(
2094 HTTPS::Handy::X509::der_integer_big($r),
2095 HTTPS::Handy::X509::der_integer_big($s));
2096 }
2097 }
2098  
2099 ######################################################################
2100 # HTTPS::Handy::ChaCha - ChaCha20-Poly1305 authenticated encryption
2101 ######################################################################
2102 # This is the cipher that protects every byte after the handshake.
2103 # It does two things at once:
2104 #
2105 # ChaCha20 turns a key, a nonce and a counter into a keystream,
2106 # which is XORed with the data. Encryption and decryption
2107 # are the same operation.
2108 # Poly1305 computes a 16 byte tag over the ciphertext, so that a
2109 # record that was altered in transit is rejected instead
2110 # of decrypted.
2111 #
2112 # ChaCha20 is built from nothing but 32 bit addition, exclusive or and
2113 # rotation, which is why it is short enough to read and quick enough to
2114 # run in Perl. Poly1305 is one multiplication modulo 2**130 - 5 per
2115 # 16 bytes, and it borrows that arithmetic from HTTPS::Handy::BigInt.
2116 #
2117 # Reference: RFC 8439.
2118 ######################################################################
2119  
2120 package HTTPS::Handy::ChaCha;
2121  
2122 # 2 ** 32. It is written as a product because a 32 bit integer cannot
2123 # hold it: on such a build Perl would read a literal that large as a
2124 # remainder modulus of zero. Nothing below takes a remainder by it;
2125 # carries are removed by subtraction, which is exact and portable.
2126 8 my $TWO32 = 65536 * 65536;
2127  
2128 # ----------------------------------------------------------------
2129 # ChaCha20
2130 # ----------------------------------------------------------------
2131  
2132 # _quarter_round - The core mixing step, applied to four state words
2133 16400 ▶sub _quarter_round {
Subroutine _quarter_round: called CC=5 SCAR=16.1
2134 16400 my ($s, $a, $b, $c, $d) = @_;
2135 16400 my $x;
2136  
2137 16400 $s->[$a] += $s->[$b];
2138 16400 ▶ $s->[$a] -= $TWO32 if $s->[$a] >= $TWO32;
Branch: 1 branch
BranchTrueFalseTotal
if $s->[$a] >= $TWO32 8043 8357 16400
2139 16400 $x = $s->[$d] ^ $s->[$a];
2140 16400 $s->[$d] = (($x << 16) | ($x >> 16)) & 0xFFFFFFFF;
2141  
2142 16400 $s->[$c] += $s->[$d];
2143 16400 ▶ $s->[$c] -= $TWO32 if $s->[$c] >= $TWO32;
Branch: 1 branch
BranchTrueFalseTotal
if $s->[$c] >= $TWO32 8235 8165 16400
2144 16400 $x = $s->[$b] ^ $s->[$c];
2145 16400 $s->[$b] = (($x << 12) | ($x >> 20)) & 0xFFFFFFFF;
2146  
2147 16400 $s->[$a] += $s->[$b];
2148 16400 ▶ $s->[$a] -= $TWO32 if $s->[$a] >= $TWO32;
Branch: 1 branch
BranchTrueFalseTotal
if $s->[$a] >= $TWO32 8134 8266 16400
2149 16400 $x = $s->[$d] ^ $s->[$a];
2150 16400 $s->[$d] = (($x << 8) | ($x >> 24)) & 0xFFFFFFFF;
2151  
2152 16400 $s->[$c] += $s->[$d];
2153 16400 ▶ $s->[$c] -= $TWO32 if $s->[$c] >= $TWO32;
Branch: 1 branch
BranchTrueFalseTotal
if $s->[$c] >= $TWO32 8127 8273 16400
2154 16400 $x = $s->[$b] ^ $s->[$c];
2155 16400 $s->[$b] = (($x << 7) | ($x >> 25)) & 0xFFFFFFFF;
2156 16400 return;
2157 }
2158  
2159 # block - One 64 byte block of keystream
2160 # $key 32 bytes
2161 # $nonce 12 bytes
2162 # $counter block number, starting at 0 or 1
2163 205 ▶sub block {
Subroutine block: called CC=4 SCAR=13.9
2164 205 my ($key, $counter, $nonce) = @_;
2165  
2166 # "expand 32-byte k", the constant that starts every state
2167 205 my @s = (0x61707865, 0x3320646e, 0x79622d32, 0x6b206574,
2168 unpack('V8', $key),
2169 $counter - $TWO32 * int($counter / $TWO32),
2170 unpack('V3', $nonce));
2171 205 my @initial = @s;
2172  
2173 # Ten double rounds: four columns, then four diagonals
2174 205 ▶ for (my $i = 0; $i < 10; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < 10) 2050 205 2255
2175 2050 _quarter_round(\@s, 0, 4, 8, 12);
2176 2050 _quarter_round(\@s, 1, 5, 9, 13);
2177 2050 _quarter_round(\@s, 2, 6, 10, 14);
2178 2050 _quarter_round(\@s, 3, 7, 11, 15);
2179 2050 _quarter_round(\@s, 0, 5, 10, 15);
2180 2050 _quarter_round(\@s, 1, 6, 11, 12);
2181 2050 _quarter_round(\@s, 2, 7, 8, 13);
2182 2050 _quarter_round(\@s, 3, 4, 9, 14);
2183 }
2184  
2185 205 ▶ for (my $i = 0; $i < 16; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < 16) 3280 205 3485
2186 3280 $s[$i] += $initial[$i];
2187 3280 ▶ $s[$i] -= $TWO32 if $s[$i] >= $TWO32;
Branch: 1 branch
BranchTrueFalseTotal
if $s[$i] >= $TWO32 1560 1720 3280
2188 }
2189 205 return pack('V16', @s);
2190 }
2191  
2192 # encrypt - XOR the data with the keystream (decryption is the same)
2193 87 ▶sub encrypt {
Subroutine encrypt: called CC=2 SCAR=6.9
2194 87 my ($key, $counter, $nonce, $data) = @_;
2195 87 my $out = '';
2196 87 my $len = length($data);
2197 87 ▶ for (my $off = 0; $off < $len; $off += 64) {
Branch: 1 branch
BranchTrueFalseTotal
if ($off < $len) 112 87 199
2198 112 my $chunk = substr($data, $off, 64);
2199 112 my $stream = block($key, $counter + int($off / 64), $nonce);
2200 112 $out .= $chunk ^ substr($stream, 0, length($chunk));
2201 }
2202 87 return $out;
2203 }
2204  
2205 # ----------------------------------------------------------------
2206 # Poly1305
2207 # ----------------------------------------------------------------
2208 # The tag is ((m1 * r**n + m2 * r**(n-1) + ... ) mod (2**130 - 5)) + s
2209 # where each mi is 16 bytes of the message with a 1 bit appended.
2210 # ----------------------------------------------------------------
2211  
2212 8 my $POLY_CTX; # Montgomery context for 2**130 - 5, built once
2213  
2214 92 ▶sub _poly_ctx {
Subroutine _poly_ctx: called CC=2 SCAR=6.9
2215 92 ▶ return $POLY_CTX if $POLY_CTX;
Branch: 1 branch
BranchTrueFalseTotal
if $POLY_CTX 89 3 92
2216 # 2**130 - 5
2217 3 my $p = HTTPS::Handy::BigInt::b_from_hex('3fffffffffffffffffffffffffffffffb');
2218 3 $POLY_CTX = HTTPS::Handy::BigInt::b_mont_context($p);
2219 3 return $POLY_CTX;
2220 }
2221  
2222 # _le_to_big / _big_to_le - Poly1305 reads and writes little endian
2223 616 ▶sub _le_to_big {
Subroutine _le_to_big: called CC=1 SCAR=0.0
2224 616 my ($bin) = @_;
2225 616 return HTTPS::Handy::BigInt::b_from_bin(scalar reverse $bin);
2226 }
2227  
2228 92 ▶sub _big_to_le {
Subroutine _big_to_le: called CC=1 SCAR=0.0
2229 92 my ($big, $len) = @_;
2230 92 return scalar reverse HTTPS::Handy::BigInt::b_to_bin($big, $len);
2231 }
2232  
2233 # mac - The 16 byte Poly1305 tag of $msg under the 32 byte $key
2234 92 ▶sub mac {
Subroutine mac: called CC=2 SCAR=6.9
2235 92 my ($key, $msg) = @_;
2236 92 my $ctx = _poly_ctx();
2237  
2238 # r is clamped: some bits are cleared so that the multiplication
2239 # cannot overflow the reduction that follows.
2240 92 my @rb = unpack('C16', substr($key, 0, 16));
2241 92 $rb[3] = $rb[3] & 15;
2242 92 $rb[7] = $rb[7] & 15;
2243 92 $rb[11] = $rb[11] & 15;
2244 92 $rb[15] = $rb[15] & 15;
2245 92 $rb[4] = $rb[4] & 252;
2246 92 $rb[8] = $rb[8] & 252;
2247 92 $rb[12] = $rb[12] & 252;
2248 92 my $r = _le_to_big(pack('C16', @rb));
2249 92 my $s = _le_to_big(substr($key, 16, 16));
2250  
2251 # r stays in Montgomery form, the accumulator stays ordinary, so
2252 # one b_mont_mul per block gives exactly (acc + n) * r mod p.
2253 92 my $r_mont = HTTPS::Handy::BigInt::b_to_mont($ctx, $r);
2254 92 my $acc = [ 0 ];
2255  
2256 92 my $len = length($msg);
2257 92 ▶ for (my $off = 0; $off < $len; $off += 16) {
Branch: 1 branch
BranchTrueFalseTotal
if ($off < $len) 432 92 524
2258 432 my $chunk = substr($msg, $off, 16);
2259 # Append a 1 bit just above the block
2260 432 my $n = _le_to_big($chunk . "\x01");
2261 432 $acc = HTTPS::Handy::BigInt::b_add($acc, $n);
2262 432 $acc = HTTPS::Handy::BigInt::b_mont_mul($ctx, $acc, $r_mont);
2263 }
2264  
2265 92 $acc = HTTPS::Handy::BigInt::b_add($acc, $s);
2266 92 return substr(_big_to_le($acc, 20), 0, 16); # keep the low 128 bits
2267 }
2268  
2269 # ----------------------------------------------------------------
2270 # The AEAD construction (RFC 8439 section 2.8)
2271 # ----------------------------------------------------------------
2272  
2273 184 ▶sub _pad16 {
Subroutine _pad16: called CC=2 SCAR=6.9
2274 184 my ($n) = @_;
2275 184 ▶ return ($n % 16) ? ("\x00" x (16 - ($n % 16))) : '';
Branch: 1 branch
BranchTrueFalseTotal
$n % 16 ? : 147 37 184
2276 }
2277  
2278 # _le64 - An eight byte little endian length, split for 32 bit Perl
2279 184 ▶sub _le64 {
Subroutine _le64: called CC=1 SCAR=0.0
2280 184 my ($n) = @_;
2281 184 my $hi = int($n / $TWO32);
2282 184 return pack('VV', $n - $hi * $TWO32, $hi);
2283 }
2284  
2285 92 ▶sub _tag {
Subroutine _tag: called CC=1 SCAR=0.0
2286 92 my ($key, $nonce, $aad, $cipher) = @_;
2287 # The one time Poly1305 key is the first block of the keystream
2288 92 my $poly_key = substr(block($key, 0, $nonce), 0, 32);
2289 92 my $data = $aad . _pad16(length($aad))
2290 . $cipher . _pad16(length($cipher))
2291 . _le64(length($aad)) . _le64(length($cipher));
2292 92 return mac($poly_key, $data);
2293 }
2294  
2295 # aead_encrypt - Returns ciphertext with the 16 byte tag appended
2296 37 ▶sub aead_encrypt {
Subroutine aead_encrypt: called CC=1 SCAR=0.0
2297 37 my ($key, $nonce, $aad, $plain) = @_;
2298 37 my $cipher = encrypt($key, 1, $nonce, $plain);
2299 37 return $cipher . _tag($key, $nonce, $aad, $cipher);
2300 }
2301  
2302 # aead_decrypt - Returns the plaintext, or undef if the tag is wrong
2303 55 ▶sub aead_decrypt {
Subroutine aead_decrypt: called CC=3 SCAR=11.0
2304 55 my ($key, $nonce, $aad, $sealed) = @_;
2305 55 ▶ return undef if length($sealed) < 16;
Branch: 1 branch
BranchTrueFalseTotal
if length $sealed < 16 0 55 55
2306 55 my $cipher = substr($sealed, 0, length($sealed) - 16);
2307 55 my $tag = substr($sealed, length($sealed) - 16);
2308 55 ▶ return undef if _tag($key, $nonce, $aad, $cipher) ne $tag;
Branch: 1 branch
BranchTrueFalseTotal
if _tag($key, $nonce, $aad, $cipher) ne $tag 5 50 55
2309 50 return encrypt($key, 1, $nonce, $cipher);
2310 }
2311  
2312 ######################################################################
2313 # HTTPS::Handy::Crypt - Hashing, message authentication, randomness
2314 ######################################################################
2315 # Everything here is written in plain Perl with no module and no
2316 # external program. Each routine takes and returns byte strings.
2317 #
2318 # sha256 a one way hash function (FIPS 180-4)
2319 # hmac_sha256 a keyed hash (RFC 2104)
2320 # prf the TLS 1.2 pseudo random function (RFC 5246)
2321 # random_bytes bytes for keys, nonces and serial numbers
2322 #
2323 # All arithmetic is done on 32 bit values kept inside Perl numbers.
2324 # Nothing here takes a remainder modulo 2 ** 32, and nothing relies on
2325 # a bit mask to discard a carry: where an integer is only 32 bits wide,
2326 # 2 ** 32 itself does not fit in one, and Perl would turn such a
2327 # modulus into zero. Carries are removed by subtraction instead, which
2328 # is exact in a floating point number and behaves the same everywhere.
2329 ######################################################################
2330  
2331 package HTTPS::Handy::Crypt;
2332  
2333 8 my $WRAP32 = 65536 * 65536; # 2 ** 32, which a 32 bit integer cannot hold
2334  
2335 # _add32 - Add numbers, keeping only the low 32 bits
2336 602160 ▶sub _add32 {
Subroutine _add32: called CC=3 SCAR=11.0
2337 602160 my $sum = 0;
2338 602160 for my $v (@_) {
2339 1760160 $sum += $v;
2340 1760160 ▶ $sum -= $WRAP32 while $sum >= $WRAP32;
Branch: 1 branch
BranchTrueFalseTotal
$sum >= $WRAP32 and do { $sum -= $WRAP32 } 558347 1760160 2318507
2341 }
2342 602160 return $sum;
2343 }
2344  
2345 # _split32 - Split a number into its high and low 32 bit halves
2346 691 ▶sub _split32 {
Subroutine _split32: called CC=1 SCAR=0.0
2347 691 my ($n) = @_;
2348 691 my $hi = int($n / $WRAP32);
2349 691 return ($hi, $n - $hi * $WRAP32);
2350 }
2351  
2352 # _rotr32 - Rotate a 32 bit value to the right
2353 1111680 ▶sub _rotr32 {
Subroutine _rotr32: called CC=1 SCAR=0.0
2354 1111680 my ($x, $n) = @_;
2355 1111680 return ((($x >> $n) | ($x << (32 - $n))) & 0xFFFFFFFF);
2356 }
2357  
2358 # ----------------------------------------------------------------
2359 # SHA-256
2360 # ----------------------------------------------------------------
2361  
2362 8 my @SHA256_K = (
2363 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1,
2364 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
2365 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786,
2366 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
2367 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147,
2368 0x06CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
2369 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B,
2370 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
2371 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A,
2372 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
2373 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2,
2374 );
2375  
2376 691 ▶sub sha256 {
Subroutine sha256: called CC=5 SCAR=16.1
2377 691 my ($msg) = @_;
2378 691 my $ml = length($msg) * 8;
2379 691 $msg .= "\x80";
2380 691 ▶ $msg .= "\x00" while (length($msg) % 64) != 56;
Branch: 1 branch
BranchTrueFalseTotal
length($msg) % 64 != 56 and do { $msg .= "\000" } 15995 691 16686
2381 691 $msg .= pack('NN', _split32($ml));
2382  
2383 691 my @h = (0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,
2384 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19);
2385  
2386 691 ▶ for (my $off = 0; $off < length($msg); $off += 64) {
Branch: 1 branch
BranchTrueFalseTotal
if ($off < length $msg) 1930 691 2621
2387 1930 my @w = unpack('N16', substr($msg, $off, 64));
2388 1930 ▶ for (my $i = 16; $i < 64; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < 64) 92640 1930 94570
2389 92640 my $s0 = _rotr32($w[$i-15], 7) ^ _rotr32($w[$i-15], 18) ^ ($w[$i-15] >> 3);
2390 92640 my $s1 = _rotr32($w[$i-2], 17) ^ _rotr32($w[$i-2], 19) ^ ($w[$i-2] >> 10);
2391 92640 $w[$i] = _add32($w[$i-16], $s0, $w[$i-7], $s1);
2392 }
2393 1930 my ($a, $b, $c, $d, $e, $f, $g, $hh) = @h;
2394 1930 ▶ for (my $i = 0; $i < 64; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < 64) 123520 1930 125450
2395 123520 my $S1 = _rotr32($e, 6) ^ _rotr32($e, 11) ^ _rotr32($e, 25);
2396 123520 my $ch = ($e & $f) ^ ((~$e & 0xFFFFFFFF) & $g);
2397 123520 my $t1 = _add32($hh, $S1, $ch, $SHA256_K[$i], $w[$i]);
2398 123520 my $S0 = _rotr32($a, 2) ^ _rotr32($a, 13) ^ _rotr32($a, 22);
2399 123520 my $mj = ($a & $b) ^ ($a & $c) ^ ($b & $c);
2400 123520 my $t2 = _add32($S0, $mj);
2401 123520 $hh = $g;
2402 123520 $g = $f;
2403 123520 $f = $e;
2404 123520 $e = _add32($d, $t1);
2405 123520 $d = $c;
2406 123520 $c = $b;
2407 123520 $b = $a;
2408 123520 $a = _add32($t1, $t2);
2409 }
2410 1930 @h = (_add32($h[0], $a), _add32($h[1], $b), _add32($h[2], $c),
2411 _add32($h[3], $d), _add32($h[4], $e), _add32($h[5], $f),
2412 _add32($h[6], $g), _add32($h[7], $hh));
2413 }
2414 691 return pack('N8', @h);
2415 }
2416  
2417 # ----------------------------------------------------------------
2418 # HMAC (RFC 2104)
2419 # ----------------------------------------------------------------
2420 # A hash keyed with a secret: nobody without the key can produce the
2421 # same value, which is what makes the Finished message and the PRF
2422 # below trustworthy.
2423 # ----------------------------------------------------------------
2424  
2425 325 ▶sub hmac_sha256 {
Subroutine hmac_sha256: called CC=2 SCAR=6.9
2426 325 my ($key, $data) = @_;
2427 325 ▶ $key = sha256($key) if length($key) > 64;
Branch: 1 branch
BranchTrueFalseTotal
if length $key > 64 1 324 325
2428 325 $key .= "\x00" x (64 - length($key));
2429 325 my $ipad = $key ^ ("\x36" x 64);
2430 325 my $opad = $key ^ ("\x5c" x 64);
2431 325 return sha256($opad . sha256($ipad . $data));
2432 }
2433  
2434 # ----------------------------------------------------------------
2435 # TLS 1.2 pseudo random function (RFC 5246 section 5)
2436 # ----------------------------------------------------------------
2437 # PRF(secret, label, seed) = P_SHA256(secret, label + seed)
2438 #
2439 # P_hash(secret, seed) = HMAC(secret, A(1) + seed)
2440 # + HMAC(secret, A(2) + seed) + ...
2441 # A(0) = seed, A(i) = HMAC(secret, A(i-1))
2442 #
2443 # Every key, IV and Finished value in the handshake comes out of this
2444 # one function, which is why it is the heart of TLS key derivation.
2445 # ----------------------------------------------------------------
2446  
2447 80 ▶sub prf {
Subroutine prf: called CC=2 SCAR=6.9
2448 80 my ($secret, $label, $seed, $want) = @_;
2449 80 my $full = $label . $seed;
2450 80 my $a = $full;
2451 80 my $out = '';
2452 80 ▶ while (length($out) < $want) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $out < $want) 161 80 241
2453 161 $a = hmac_sha256($secret, $a);
2454 161 $out .= hmac_sha256($secret, $a . $full);
2455 }
2456 80 return substr($out, 0, $want);
2457 }
2458  
2459 # ----------------------------------------------------------------
2460 # Randomness
2461 # ----------------------------------------------------------------
2462 # Keys and nonces must be unpredictable. The operating system random
2463 # device is used when it can be read. Otherwise the module falls back
2464 # to a hash of whatever varying values are at hand, which is enough for
2465 # a classroom but not for protecting anything of value; see the
2466 # SECURITY section of the documentation.
2467 # ----------------------------------------------------------------
2468  
2469 8 my $RAND_POOL = '';
2470 8 my $RAND_COUNT = 0;
2471  
2472 46 ▶sub random_bytes {
Subroutine random_bytes: called CC=7 SCAR=29.1
2473 46 my ($n) = @_;
2474 46 my $out = '';
2475  
2476 # Preferred source: the operating system
2477 46 local *RANDDEV;
2478 46 ▶ if (open(RANDDEV, '</dev/urandom')) {
Branch: 1 branch
BranchTrueFalseTotal
if (open RANDDEV, "</dev/urandom") 46 0 46
2479 46 binmode RANDDEV;
2480 46 my $buf = '';
2481 46 my $got = read(RANDDEV, $buf, $n);
2482 46 close RANDDEV;
2483 46 ▶ return $buf if defined $got && ($got == $n);
Branch: 1 branch
BranchTrueFalseTotal
if defined $got and $got == $n 46 0 46
Condition33%1/3
defined $got and $got == $n
!ll&&!rl&&r
0046
MC/DC0%0/2
defined $got and $got == $n
defined $got $got == $n
Truth table33%1/3
A and B
A= defined $gotB= $got == $n
ABresult
0X0
100
111
2484 }
2485  
2486 # Fallback: stir a pool with everything that varies and hash it
2487 0 ▶ unless ($RAND_POOL) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($RAND_POOL) 0 0 0
2488 0 $RAND_POOL = join('|', $$, time(), rand(), $0, scalar(%ENV),
2489 scalar(localtime), 'HTTPS::Handy');
2490 0 ▶ for (my $i = 0; $i < 64; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < 64) 0 0 0
2491 0 $RAND_POOL .= pack('d', rand());
2492 }
2493 }
2494 0 ▶ while (length($out) < $n) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $out < $n) 0 0 0
2495 0 $RAND_COUNT++;
2496 0 $RAND_POOL = sha256($RAND_POOL . pack('NN', $RAND_COUNT, time())
2497 . pack('d', rand()));
2498 0 $out .= $RAND_POOL;
2499 }
2500 0 return substr($out, 0, $n);
2501 }
2502  
2503 ######################################################################
2504 # HTTPS::Handy::X509 - DER and PEM encoding, self-signed certificates
2505 ######################################################################
2506 # A certificate is a nest of ASN.1 structures encoded with DER, which
2507 # writes every value as three parts: a tag byte, a length, and the
2508 # contents. Nesting is what makes it look complicated; each individual
2509 # step is simple, as the builders below show.
2510 #
2511 # This package can
2512 #
2513 # * build a self-signed certificate and its RSA private key,
2514 # * write and read the PEM files that hold them,
2515 # * read a certificate or key that was made by another tool.
2516 ######################################################################
2517  
2518 package HTTPS::Handy::X509;
2519  
2520 # ----------------------------------------------------------------
2521 # Base64 (RFC 4648), written out so that MIME::Base64 is not needed
2522 # ----------------------------------------------------------------
2523  
2524 8 my $B64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
2525  
2526 6 ▶sub b64_encode {
Subroutine b64_encode: called CC=7 SCAR=19.5
2527 6 my ($data, $eol) = @_;
2528 6 ▶ $eol = "\n" unless defined $eol;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $eol 6 0 6
2529 6 my $out = '';
2530 6 ▶ for (my $i = 0; $i < length($data); $i += 3) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < length $data) 404 6 410
2531 404 my $chunk = substr($data, $i, 3);
2532 404 my $n = length($chunk);
2533 404 my @b = unpack('C3', $chunk . "\x00\x00");
2534 404 my $v = $b[0] * 65536 + $b[1] * 256 + $b[2];
2535 404 my @c = (int($v / 262144) % 64, int($v / 4096) % 64,
2536 int($v / 64) % 64, $v % 64);
2537 404 my $group = '';
2538 404 ▶ for (my $j = 0; $j < 4; $j++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < 4) 1616 404 2020
2539 1616 $group .= substr($B64_CHARS, $c[$j], 1);
2540 }
2541 404 ▶ substr($group, 3, 1) = '=' if $n < 3;
Branch: 1 branch
BranchTrueFalseTotal
if $n < 3 6 398 404
2542 404 ▶ substr($group, 2, 1) = '=' if $n < 2;
Branch: 1 branch
BranchTrueFalseTotal
if $n < 2 2 402 404
2543 404 $out .= $group;
2544 }
2545 # Wrap at 64 characters, as PEM requires
2546 6 my $wrapped = '';
2547 6 ▶ for (my $i = 0; $i < length($out); $i += 64) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < length $out) 28 6 34
2548 28 $wrapped .= substr($out, $i, 64) . $eol;
2549 }
2550 6 return $wrapped;
2551 }
2552  
2553 5 ▶sub b64_decode {
Subroutine b64_decode: called CC=4 SCAR=13.9
2554 5 my ($text) = @_;
2555 5 $text =~ s/[^A-Za-z0-9+\/=]//g;
2556 5 $text =~ s/=+$//;
2557 5 my $out = '';
2558 5 my $bits = 0;
2559 5 my $acc = 0;
2560 5 ▶ for (my $i = 0; $i < length($text); $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < length $text) 1446 5 1451
2561 1446 my $v = index($B64_CHARS, substr($text, $i, 1));
2562 1446 ▶ next if $v < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $v < 0 0 1446 1446
2563 1446 $acc = $acc * 64 + $v;
2564 1446 $bits += 6;
2565 1446 ▶ if ($bits >= 8) {
Branch: 1 branch
BranchTrueFalseTotal
if ($bits >= 8) 1083 363 1446
2566 1083 $bits -= 8;
2567 1083 my $div = 2 ** $bits;
2568 1083 $out .= chr(int($acc / $div) % 256);
2569 1083 $acc = $acc % $div;
2570 }
2571 }
2572 5 return $out;
2573 }
2574  
2575 # ----------------------------------------------------------------
2576 # DER building blocks
2577 # ----------------------------------------------------------------
2578  
2579 # _der - Wrap contents in a tag and a length
2580 183 ▶sub _der {
Subroutine _der: called CC=3 SCAR=11.0
2581 183 my ($tag, $contents) = @_;
2582 183 my $len = length($contents);
2583 183 my $enc;
2584 183 ▶ if ($len < 128) {
Branch: 1 branch
BranchTrueFalseTotal
if ($len < 128) { } 176 7 183
2585 176 $enc = pack('C', $len);
2586 }
2587 else {
2588 7 my $bytes = '';
2589 7 my $n = $len;
2590 7 ▶ while ($n > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n > 0) 14 7 21
2591 14 $bytes = pack('C', $n % 256) . $bytes;
2592 14 $n = int($n / 256);
2593 }
2594 7 $enc = pack('C', 0x80 + length($bytes)) . $bytes;
2595 }
2596 183 return pack('C', $tag) . $enc . $contents;
2597 }
2598  
2599 64 ▶sub der_sequence { return _der(0x30, join('', @_)) }
Subroutine der_sequence: called CC=1 SCAR=0.0
2600 6 ▶sub der_set { return _der(0x31, join('', @_)) }
Subroutine der_set: called CC=1 SCAR=0.0
2601  
2602 # der_integer - A non negative integer, from a big endian byte string
2603 21 ▶sub der_integer {
Subroutine der_integer: called CC=3 SCAR=11.0
2604 21 my ($bin) = @_;
2605 21 $bin =~ s/^\x00+//;
2606 21 ▶ $bin = "\x00" if $bin eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $bin eq "" 0 21 21
2607 # A leading bit of 1 would mean a negative number, so pad with zero
2608 21 ▶ $bin = "\x00" . $bin if unpack('C', substr($bin, 0, 1)) >= 0x80;
Branch: 1 branch
BranchTrueFalseTotal
if unpack("C", substr($bin, 0, 1)) >= 128 8 13 21
2609 21 return _der(0x02, $bin);
2610 }
2611  
2612 12 ▶sub der_integer_big {
Subroutine der_integer_big: called CC=1 SCAR=0.0
2613 12 my ($big) = @_;
2614 12 return der_integer(HTTPS::Handy::BigInt::b_to_bin($big));
2615 }
2616  
2617 8 ▶sub der_bitstring {
Subroutine der_bitstring: called CC=1 SCAR=0.0
2618 8 my ($bin) = @_;
2619 8 return _der(0x03, "\x00" . $bin); # zero unused bits
2620 }
2621  
2622 14 ▶sub der_octetstring { return _der(0x04, $_[0]) }
Subroutine der_octetstring: called CC=1 SCAR=0.0
2623 1 ▶sub der_null { return _der(0x05, '') }
Subroutine der_null: called CC=1 SCAR=0.0
2624 6 ▶sub der_printable { return _der(0x13, $_[0]) }
Subroutine der_printable: called CC=1 SCAR=0.0
2625 6 ▶sub der_utctime { return _der(0x17, $_[0]) }
Subroutine der_utctime: called CC=1 SCAR=0.0
2626 6 ▶sub der_boolean { return _der(0x01, $_[0] ? "\xFF" : "\x00") }
Subroutine der_boolean: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$_[0] ? : 6 0 6
2627  
2628 # der_oid - Encode an object identifier such as "1.2.840.113549.1.1.11"
2629 33 ▶sub der_oid {
Subroutine der_oid: called CC=3 SCAR=11.0
2630 33 my ($oid) = @_;
2631 33 my @n = split /\./, $oid;
2632 33 my $out = pack('C', $n[0] * 40 + $n[1]);
2633 33 ▶ for (my $i = 2; $i < scalar(@n); $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < scalar @n) 114 33 147
2634 114 my $v = $n[$i];
2635 114 my @seven = ($v % 128);
2636 114 $v = int($v / 128);
2637 114 ▶ while ($v > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v > 0) 25 114 139
2638 25 unshift @seven, ($v % 128) + 128;
2639 25 $v = int($v / 128);
2640 }
2641 114 $out .= pack('C*', @seven);
2642 }
2643 33 return _der(0x06, $out);
2644 }
2645  
2646 # der_context - A context specific, constructed tag such as [0] or [3]
2647 10 ▶sub der_context {
Subroutine der_context: called CC=1 SCAR=0.0
2648 10 my ($number, $contents) = @_;
2649 10 return _der(0xA0 + $number, $contents);
2650 }
2651  
2652 # ----------------------------------------------------------------
2653 # A very small DER reader, enough to walk a certificate or a key
2654 # ----------------------------------------------------------------
2655  
2656 # der_next - Read one TLV at $pos; returns (tag, contents, next position)
2657 40 ▶sub der_next {
Subroutine der_next: called CC=4 SCAR=13.9
2658 40 my ($der, $pos) = @_;
2659 40 ▶ return () if $pos + 2 > length($der);
Branch: 1 branch
BranchTrueFalseTotal
if $pos + 2 > length $der 0 40 40
2660 40 my $tag = unpack('C', substr($der, $pos, 1));
2661 40 my $b = unpack('C', substr($der, $pos + 1, 1));
2662 40 my $len;
2663 40 my $hdr = 2;
2664 40 ▶ if ($b < 128) {
Branch: 1 branch
BranchTrueFalseTotal
if ($b < 128) { } 33 7 40
2665 33 $len = $b;
2666 }
2667 else {
2668 7 my $n = $b - 128;
2669 7 $len = 0;
2670 7 ▶ for (my $i = 0; $i < $n; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $n) 14 7 21
2671 14 $len = $len * 256 + unpack('C', substr($der, $pos + 2 + $i, 1));
2672 }
2673 7 $hdr = 2 + $n;
2674 }
2675 40 return ($tag, substr($der, $pos + $hdr, $len), $pos + $hdr + $len);
2676 }
2677  
2678 # ----------------------------------------------------------------
2679 # PEM files
2680 # ----------------------------------------------------------------
2681  
2682 4 ▶sub pem_wrap {
Subroutine pem_wrap: called CC=1 SCAR=0.0
2683 4 my ($label, $der) = @_;
2684 4 return "-----BEGIN $label-----\n" . b64_encode($der) . "-----END $label-----\n";
2685 }
2686  
2687 # pem_blocks - Return every DER block of the given label found in $text
2688 5 ▶sub pem_blocks {
Subroutine pem_blocks: called CC=3 SCAR=11.0
2689 5 my ($text, $label) = @_;
2690 5 my @out = ();
2691 5 ▶ my $re = defined $label ? quotemeta($label) : '[A-Z0-9 ]+';
Branch: 1 branch
BranchTrueFalseTotal
defined $label ? : 5 0 5
2692 5 ▶ while ($text =~ /-----BEGIN ($re)-----(.*?)-----END \1-----/gs) {
Branch: 1 branch
BranchTrueFalseTotal
if ($text =~ /-----BEGIN ($re)-----(.*?)-----END \1-----/gs) 3 5 8
2693 3 push @out, b64_decode($2);
2694 }
2695 5 return @out;
2696 }
2697  
2698 # ----------------------------------------------------------------
2699 # RSA private keys in PKCS #1 and PKCS #8 form
2700 # ----------------------------------------------------------------
2701  
2702 0 ▶sub private_key_to_der {
Subroutine private_key_to_der: not called CC=1 SCAR=6.9
2703 0 my ($key) = @_;
2704 return der_sequence(
2705 der_integer("\x00"), # version 0
2706 der_integer_big($key->{'n'}),
2707 der_integer_big($key->{'e'}),
2708 der_integer_big($key->{'d'}),
2709 der_integer_big($key->{'p'}),
2710 der_integer_big($key->{'q'}),
2711 der_integer_big($key->{'dp'}),
2712 der_integer_big($key->{'dq'}),
2713 0 der_integer_big($key->{'qinv'}),
2714 );
2715 }
2716  
2717 0 ▶sub private_key_to_pem {
Subroutine private_key_to_pem: not called CC=1 SCAR=6.9
2718 0 my ($key) = @_;
2719 0 return pem_wrap('RSA PRIVATE KEY', private_key_to_der($key));
2720 }
2721  
2722 # private_key_from_der - Read a PKCS #1 (or PKCS #8 wrapped) RSA key
2723 0 ▶sub private_key_from_der {
Subroutine private_key_from_der: not called CC=9 SCAR=45.0
2724 0 my ($der) = @_;
2725 0 my ($tag, $body) = der_next($der, 0);
2726 0 ▶ return undef unless defined $tag && $tag == 0x30;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tag and $tag == 48 0 0 0
Condition0%0/3
defined $tag and $tag == 48
!ll&&!rl&&r
000
MC/DC0%0/2
defined $tag and $tag == 48
defined $tag $tag == 48
Truth table0%0/3
A and B
A= defined $tagB= $tag == 48
ABresult
0X0
100
111
2727  
2728 0 my @field = ();
2729 0 my $pos = 0;
2730 0 while (1) {
2731 0 my ($t, $c, $next) = der_next($body, $pos);
2732 0 ▶ last unless defined $t;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t 0 0 0
2733 0 push @field, [ $t, $c ];
2734 0 $pos = $next;
2735 0 ▶ last if $pos >= length($body);
Branch: 1 branch
BranchTrueFalseTotal
if $pos >= length $body 0 0 0
2736 }
2737 0 ▶ return undef unless scalar(@field) >= 3;
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @field >= 3 0 0 0
2738  
2739 # PKCS #8: version, AlgorithmIdentifier, OCTET STRING with the key
2740 0 ▶ if (($field[1][0] == 0x30) && ($field[2][0] == 0x04)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($field[1][0] == 48 and $field[2][0] == 4) 0 0 0
Condition0%0/3
$field[1][0] == 48 and $field[2][0] == 4
!ll&&!rl&&r
000
MC/DC0%0/2
$field[1][0] == 48 and $field[2][0] == 4
$field[1][0] == 48 $field[2][0] == 4
Truth table0%0/3
A and B
A= $field[1][0] == 48B= $field[2][0] == 4
ABresult
0X0
100
111
2741 0 return private_key_from_der($field[2][1]);
2742 }
2743 0 ▶ return undef unless scalar(@field) >= 9;
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @field >= 9 0 0 0
2744  
2745 0 my @v = map { HTTPS::Handy::BigInt::b_from_bin($_->[1]) } @field[1 .. 8];
2746 return {
2747 0 'type' => 'rsa',
2748 'n' => $v[0],
2749 'e' => $v[1],
2750 'd' => $v[2],
2751 'p' => $v[3],
2752 'q' => $v[4],
2753 'dp' => $v[5],
2754 'dq' => $v[6],
2755 'qinv' => $v[7],
2756 'size' => length(HTTPS::Handy::BigInt::b_to_bin($v[0])),
2757 };
2758 }
2759  
2760 # ----------------------------------------------------------------
2761 # Elliptic curve keys (SEC 1, and PKCS #8 wrapped)
2762 # ----------------------------------------------------------------
2763  
2764 # Object identifiers used for P-256 keys and signatures
2765 8 my $OID_EC_PUBLIC_KEY = '1.2.840.10045.2.1';
2766 8 my $OID_PRIME256V1 = '1.2.840.10045.3.1.7';
2767 8 my $OID_ECDSA_SHA256 = '1.2.840.10045.4.3.2';
2768 8 my $OID_RSA_ENC = '1.2.840.113549.1.1.1';
2769 8 my $OID_RSA_SHA256 = '1.2.840.113549.1.1.11';
2770  
2771 2 ▶sub ec_private_key_to_der {
Subroutine ec_private_key_to_der: called CC=1 SCAR=0.0
2772 2 my ($key) = @_;
2773 2 my $point = HTTPS::Handy::EC::point_to_bin($key->{'x'}, $key->{'y'});
2774 return der_sequence(
2775 der_integer("\x01"), # version 1
2776 2 der_octetstring(HTTPS::Handy::BigInt::b_to_bin($key->{'d'}, 32)),
2777 der_context(0, der_oid($OID_PRIME256V1)),
2778 der_context(1, der_bitstring($point)),
2779 );
2780 }
2781  
2782 2 ▶sub ec_private_key_to_pem {
Subroutine ec_private_key_to_pem: called CC=1 SCAR=0.0
2783 2 my ($key) = @_;
2784 2 return pem_wrap('EC PRIVATE KEY', ec_private_key_to_der($key));
2785 }
2786  
2787 # ec_private_key_from_der - Read a SEC 1 (or PKCS #8 wrapped) EC key
2788 1 ▶sub ec_private_key_from_der {
Subroutine ec_private_key_from_der: called CC=11 SCAR=27.0
2789 1 my ($der) = @_;
2790 1 my ($tag, $body) = der_next($der, 0);
2791 1 ▶ return undef unless defined $tag && ($tag == 0x30);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $tag and $tag == 48 0 1 1
Condition33%1/3
defined $tag and $tag == 48
!ll&&!rl&&r
001
MC/DC0%0/2
defined $tag and $tag == 48
defined $tag $tag == 48
Truth table33%1/3
A and B
A= defined $tagB= $tag == 48
ABresult
0X0
100
111
2792  
2793 1 my @field = ();
2794 1 my $pos = 0;
2795 1 ▶ while ($pos < length($body)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < length $body) 4 1 5
2796 4 my ($t, $c, $next) = der_next($body, $pos);
2797 4 ▶ last unless defined $t;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $t 0 4 4
2798 4 push @field, [ $t, $c ];
2799 4 $pos = $next;
2800 }
2801 1 ▶ return undef unless scalar(@field) >= 2;
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @field >= 2 0 1 1
2802  
2803 # PKCS #8: version, AlgorithmIdentifier, OCTET STRING with the key
2804 1 ▶ if (($field[1][0] == 0x30) && (scalar(@field) >= 3)
Branch: 1 branch
BranchTrueFalseTotal
if ($field[1][0] == 48 and scalar @field >= 3 and $field[2][0] == 4) 0 1 1
Condition33%2/6
$field[1][0] == 48 and scalar @field >= 3 and $field[2][0] == 4
!ll&&!rl&&r
100
$field[1][0] == 48 and scalar @field >= 3
!ll&&!rl&&r
100
MC/DC0%0/3
$field[1][0] == 48 and scalar @field >= 3 and $field[2][0] == 4
$field[1][0] == 48 scalar @field >= 3 $field[2][0] == 4
Truth table25%1/4
A and B and C
A= $field[1][0] == 48B= scalar @field >= 3C= $field[2][0] == 4
ABCresult
0XX0
10X0
1100
1111
2805 && ($field[2][0] == 0x04)) {
2806 0 return ec_private_key_from_der($field[2][1]);
2807 }
2808 1 ▶ return undef unless $field[1][0] == 0x04;
Branch: 1 branch
BranchTrueFalseTotal
unless $field[1][0] == 4 0 1 1
2809  
2810 1 my $d = HTTPS::Handy::BigInt::b_from_bin($field[1][1]);
2811 1 my ($x, $y) = HTTPS::Handy::EC::mul_generator($d);
2812 1 ▶ return undef unless defined $x;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $x 0 1 1
2813 1 return { 'type' => 'ec', 'd' => $d, 'x' => $x, 'y' => $y };
2814 }
2815  
2816 # ----------------------------------------------------------------
2817 # Public keys
2818 # ----------------------------------------------------------------
2819  
2820 # public_key_der - SubjectPublicKeyInfo, for either kind of key
2821 3 ▶sub public_key_der {
Subroutine public_key_der: called CC=2 SCAR=8.4
2822 3 my ($key) = @_;
2823 3 ▶ if ($key->{'type'} eq 'ec') {
Branch: 1 branch
BranchTrueFalseTotal
if ($key->{"type"} eq "ec") 3 0 3
2824 return der_sequence(
2825 der_sequence(der_oid($OID_EC_PUBLIC_KEY), der_oid($OID_PRIME256V1)),
2826 3 der_bitstring(HTTPS::Handy::EC::point_to_bin($key->{'x'}, $key->{'y'})),
2827 );
2828 }
2829 my $rsa = der_sequence(der_integer_big($key->{'n'}),
2830 0 der_integer_big($key->{'e'}));
2831 0 return der_sequence(
2832 der_sequence(der_oid($OID_RSA_ENC), der_null()),
2833 der_bitstring($rsa),
2834 );
2835 }
2836  
2837 # signature_algorithm_der - The AlgorithmIdentifier a certificate signed
2838 # with this key carries
2839 3 ▶sub signature_algorithm_der {
Subroutine signature_algorithm_der: called CC=2 SCAR=8.1
2840 3 my ($key) = @_;
2841 3 ▶ return der_sequence(der_oid($OID_ECDSA_SHA256)) if $key->{'type'} eq 'ec';
Branch: 1 branch
BranchTrueFalseTotal
if $key->{"type"} eq "ec" 3 0 3
2842 0 return der_sequence(der_oid($OID_RSA_SHA256), der_null());
2843 }
2844  
2845 # sign_data - Sign with SHA-256, whichever kind of key this is
2846 4 ▶sub sign_data {
Subroutine sign_data: called CC=2 SCAR=8.1
2847 4 my ($key, $data) = @_;
2848 4 ▶ return HTTPS::Handy::EC::sign($key, $data) if $key->{'type'} eq 'ec';
Branch: 1 branch
BranchTrueFalseTotal
if $key->{"type"} eq "ec" 4 0 4
2849 0 return HTTPS::Handy::RSA::sign_pkcs1_sha256($key, $data);
2850 }
2851  
2852 # private_key_to_pem_any - PEM for either kind of key
2853 2 ▶sub private_key_to_pem_any {
Subroutine private_key_to_pem_any: called CC=2 SCAR=8.1
2854 2 my ($key) = @_;
2855 2 ▶ return ec_private_key_to_pem($key) if $key->{'type'} eq 'ec';
Branch: 1 branch
BranchTrueFalseTotal
if $key->{"type"} eq "ec" 2 0 2
2856 0 return private_key_to_pem($key);
2857 }
2858  
2859 # ----------------------------------------------------------------
2860 # Building a self-signed certificate
2861 # ----------------------------------------------------------------
2862  
2863 # _utctime - Format a time stamp as YYMMDDHHMMSSZ in UTC
2864 6 ▶sub _utctime {
Subroutine _utctime: called CC=1 SCAR=0.0
2865 6 my ($t) = @_;
2866 6 my @g = gmtime($t);
2867 6 return sprintf('%02d%02d%02d%02d%02d%02dZ',
2868 $g[5] % 100, $g[4] + 1, $g[3], $g[2], $g[1], $g[0]);
2869 }
2870  
2871 # _name - An X.500 name holding a single common name
2872 6 ▶sub _name {
Subroutine _name: called CC=1 SCAR=0.0
2873 6 my ($cn) = @_;
2874 6 return der_sequence(
2875 der_set(der_sequence(der_oid('2.5.4.3'), der_printable($cn))));
2876 }
2877  
2878 # _subject_alt_name - The extension browsers use to match the host name
2879 3 ▶sub _subject_alt_name {
Subroutine _subject_alt_name: called CC=3 SCAR=11.0
2880 3 my (@host) = @_;
2881 3 my $names = '';
2882 3 for my $h (@host) {
2883 5 ▶ if ($h =~ /^\d+\.\d+\.\d+\.\d+$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($h =~ /^\d+\.\d+\.\d+\.\d+$/) { } 2 3 5
2884 # iPAddress [7]
2885 2 $names .= _der(0x87, pack('C4', split(/\./, $h)));
2886 }
2887 else {
2888 # dNSName [2]
2889 3 $names .= _der(0x82, $h);
2890 }
2891 }
2892 3 return der_sequence(der_oid('2.5.29.17'),
2893 der_octetstring(der_sequence($names)));
2894 }
2895  
2896 # make_self_signed - Build a certificate and sign it with its own key
2897 #
2898 # key RSA key from HTTPS::Handy::RSA::generate_key
2899 # cn common name, usually the host name
2900 # hosts list of names or addresses for subjectAltName
2901 # days validity in days
2902 #
2903 # Returns the certificate as DER.
2904 3 ▶sub make_self_signed {
Subroutine make_self_signed: called CC=5 SCAR=16.6
2905 3 my (%opt) = @_;
2906 3 my $key = $opt{'key'};
2907 3 ▶ my $cn = defined $opt{'cn'} ? $opt{'cn'} : 'localhost';
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'cn'} ? : 3 0 3
2908 3 ▶ my $days = defined $opt{'days'} ? $opt{'days'} : 3650;
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'days'} ? : 3 0 3
2909 my @hosts = (defined $opt{'hosts'} && ref($opt{'hosts'}) eq 'ARRAY')
2910 3 ▶ ? @{ $opt{'hosts'} }
Branch: 1 branch
BranchTrueFalseTotal
defined $opt{'hosts'} && ref $opt{'hosts'} eq 'ARRAY' ? : 3 0 3
Condition33%1/3
defined $opt{"hosts"} and ref $opt{"hosts"} eq "ARRAY"
!ll&&!rl&&r
003
MC/DC0%0/2
defined $opt{"hosts"} and ref $opt{"hosts"} eq "ARRAY"
defined $opt{"hosts"} ref $opt{"hosts"} eq "ARRAY"
Truth table33%1/3
A and B
A= defined $opt{"hosts"}B= ref $opt{"hosts"} eq "ARRAY"
ABresult
0X0
100
111
2911 : ($cn);
2912  
2913 3 my $now = time();
2914 3 my $serial = HTTPS::Handy::Crypt::random_bytes(8);
2915 3 substr($serial, 0, 1) = pack('C', unpack('C', substr($serial, 0, 1)) & 0x7F);
2916  
2917 3 my $sig_alg = signature_algorithm_der($key);
2918  
2919 3 my $extensions = der_context(3, der_sequence(
2920 # basicConstraints: not a certificate authority
2921 der_sequence(der_oid('2.5.29.19'), der_boolean(1),
2922 der_octetstring(der_sequence())),
2923 # keyUsage: digitalSignature + keyEncipherment
2924 der_sequence(der_oid('2.5.29.15'), der_boolean(1),
2925 der_octetstring(_der(0x03, "\x05\xA0"))),
2926 # extendedKeyUsage: TLS server authentication
2927 der_sequence(der_oid('2.5.29.37'),
2928 der_octetstring(der_sequence(der_oid('1.3.6.1.5.5.7.3.1')))),
2929 _subject_alt_name(@hosts),
2930 ));
2931  
2932 3 my $tbs = der_sequence(
2933 der_context(0, der_integer("\x02")), # version 3
2934 der_integer($serial),
2935 $sig_alg,
2936 _name($cn), # issuer (itself)
2937 der_sequence(der_utctime(_utctime($now - 86400)),
2938 der_utctime(_utctime($now + $days * 86400))),
2939 _name($cn), # subject
2940 public_key_der($key),
2941 $extensions,
2942 );
2943  
2944 3 my $sig = sign_data($key, $tbs);
2945 3 return der_sequence($tbs, $sig_alg, der_bitstring($sig));
2946 }
2947  
2948 ######################################################################
2949 # HTTPS::Handy::RSA - Signing with an RSA key
2950 ######################################################################
2951 # This module generates elliptic curve keys of its own, so the RSA
2952 # code here exists for one purpose: to use an RSA certificate and key
2953 # that somebody else issued, for instance from a certificate
2954 # authority. Only the private operation is needed for that, which is
2955 # raising the message to the power d modulo n. It is split with the
2956 # Chinese Remainder Theorem, which works on numbers of half the size
2957 # and is about four times faster.
2958 #
2959 # A key is a hash reference whose values are big integers as defined
2960 # by HTTPS::Handy::BigInt:
2961 #
2962 # n e d p q dp dq qinv and size (modulus length in bytes)
2963 ######################################################################
2964  
2965 package HTTPS::Handy::RSA;
2966  
2967 # ----------------------------------------------------------------
2968 # The private operation
2969 # ----------------------------------------------------------------
2970  
2971 # private_op - m = c ** d mod n, computed with the CRT when possible
2972 0 ▶sub private_op {
Subroutine private_op: not called CC=5 SCAR=34.0
2973 0 my ($key, $c) = @_;
2974 0 ▶ unless (defined $key->{'p'} && defined $key->{'dp'}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $key->{"p"} and defined $key->{"dp"}) 0 0 0
Condition0%0/3
defined $key->{"p"} and defined $key->{"dp"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $key->{"p"} and defined $key->{"dp"}
defined $key->{"p"} defined $key->{"dp"}
Truth table0%0/3
A and B
A= defined $key->{"p"}B= defined $key->{"dp"}
ABresult
0X0
100
111
2975 0 return HTTPS::Handy::BigInt::b_modexp($c, $key->{'d'}, $key->{'n'});
2976 }
2977 my $m1 = HTTPS::Handy::BigInt::b_modexp(
2978 HTTPS::Handy::BigInt::b_mod($c, $key->{'p'}),
2979 0 $key->{'dp'}, $key->{'p'});
2980 my $m2 = HTTPS::Handy::BigInt::b_modexp(
2981 HTTPS::Handy::BigInt::b_mod($c, $key->{'q'}),
2982 0 $key->{'dq'}, $key->{'q'});
2983 # h = qinv * (m1 - m2) mod p ; m = m2 + h * q
2984 0 my $diff;
2985 0 ▶ if (HTTPS::Handy::BigInt::b_cmp($m1, $m2) >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (HTTPS::Handy::BigInt::b_cmp($m1, $m2) >= 0) { } 0 0 0
2986 0 $diff = HTTPS::Handy::BigInt::b_sub($m1, $m2);
2987 }
2988 else {
2989 0 my $t = HTTPS::Handy::BigInt::b_sub($m2, $m1);
2990 0 $t = HTTPS::Handy::BigInt::b_mod($t, $key->{'p'});
2991 $diff = HTTPS::Handy::BigInt::b_is_zero($t)
2992 ? $t
2993 0 ▶ : HTTPS::Handy::BigInt::b_sub($key->{'p'}, $t);
Branch: 1 branch
BranchTrueFalseTotal
HTTPS::Handy::BigInt::b_is_zero($t) ? : 0 0 0
2994 }
2995 my $h = HTTPS::Handy::BigInt::b_mod(
2996 HTTPS::Handy::BigInt::b_mul($key->{'qinv'}, $diff),
2997 0 $key->{'p'});
2998 return HTTPS::Handy::BigInt::b_add($m2,
2999 0 HTTPS::Handy::BigInt::b_mul($h, $key->{'q'}));
3000 }
3001  
3002 # ----------------------------------------------------------------
3003 # PKCS #1 v1.5 signatures (RFC 8017)
3004 # ----------------------------------------------------------------
3005 # The block that gets raised to the power d is
3006 #
3007 # 0x00 0x01 <0xFF padding> 0x00 <algorithm id and hash>
3008 #
3009 # so that it is as wide as the modulus and cannot be confused with
3010 # any other value of the same length.
3011 # ----------------------------------------------------------------
3012  
3013 # DER prefix of DigestInfo for SHA-256, as required by RFC 8017
3014 8 my $SHA256_DIGESTINFO = pack('H*', '3031300d060960864801650304020105000420');
3015  
3016 # sign_pkcs1_sha256 - Sign data with the private key
3017 0 ▶sub sign_pkcs1_sha256 {
Subroutine sign_pkcs1_sha256: not called CC=1 SCAR=6.9
3018 0 my ($key, $data) = @_;
3019 0 my $k = $key->{'size'};
3020 0 my $t = $SHA256_DIGESTINFO . HTTPS::Handy::Crypt::sha256($data);
3021 0 my $block = "\x00\x01" . ("\xFF" x ($k - 3 - length($t))) . "\x00" . $t;
3022 0 my $s = private_op($key, HTTPS::Handy::BigInt::b_from_bin($block));
3023 0 return HTTPS::Handy::BigInt::b_to_bin($s, $k);
3024 }
3025  
3026 ######################################################################
3027 # HTTPS::Handy::BigInt - Multiple precision integer arithmetic
3028 ######################################################################
3029 # Public key cryptography needs numbers far larger than a Perl scalar
3030 # can hold exactly, so this package stores an integer as a reference to
3031 # an array of 16 bit "limbs", least significant limb first:
3032 #
3033 # 65537 -> [ 1, 1 ] # 1 + 1 * 65536
3034 #
3035 # Only ordinary arithmetic (+ - * / %) is used, never bit operations.
3036 # A 16 bit limb keeps every intermediate product below 2**53, which is
3037 # the largest integer a floating point number represents exactly, so
3038 # the same code gives identical results on 32 bit and 64 bit Perl, and
3039 # on Perl 5.005_03 which has no 64 bit integers at all.
3040 ######################################################################
3041  
3042 package HTTPS::Handy::BigInt;
3043  
3044 # Limb base. Products of two limbs stay below 2**32, and the CIOS loop
3045 # below adds at most two more limbs to such a product, so intermediate
3046 # values never exceed 2**53.
3047 8 my $BASE = 65536;
3048  
3049 # ----------------------------------------------------------------
3050 # Construction and conversion
3051 # ----------------------------------------------------------------
3052  
3053 # b_norm - Remove leading zero limbs (in place) and return the number
3054 751416 ▶sub b_norm {
Subroutine b_norm: called CC=3 SCAR=11.0
3055 751416 my ($a) = @_;
3056 751416 ▶ pop @$a while (scalar(@$a) > 1) && ($a->[-1] == 0);
Branch: 1 branch
BranchTrueFalseTotal
scalar @$a > 1 and $a->[-1] == 0 and do { pop @$a } 315262 751416 1066678
Condition100%3/3
scalar @$a > 1 and $a->[-1] == 0
!ll&&!rl&&r
15689735727315262
MC/DC100%2/2
scalar @$a > 1 and $a->[-1] == 0
scalar @$a > 1 $a->[-1] == 0
Truth table100%3/3
A and B
A= scalar @$a > 1B= $a->[-1] == 0
ABresult
0X0
100
111
3057 751416 return $a;
3058 }
3059  
3060 # b_from_int - Convert a Perl integer (0 .. 2**48) to a big integer
3061 2 ▶sub b_from_int {
Subroutine b_from_int: called CC=3 SCAR=11.0
3062 2 my ($n) = @_;
3063 2 my @limb = ();
3064 2 $n = int($n);
3065 2 ▶ while ($n > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n > 0) 3 2 5
3066 3 push @limb, $n % $BASE;
3067 3 $n = int($n / $BASE);
3068 }
3069 2 ▶ push @limb, 0 unless @limb;
Branch: 1 branch
BranchTrueFalseTotal
unless @limb 0 2 2
3070 2 return [ @limb ];
3071 }
3072  
3073 # b_to_int - Convert a small big integer back to a Perl integer
3074 1 ▶sub b_to_int {
Subroutine b_to_int: called CC=2 SCAR=6.9
3075 1 my ($a) = @_;
3076 1 my $n = 0;
3077 1 ▶ for (my $i = scalar(@$a) - 1; $i >= 0; $i--) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i >= 0) 2 1 3
3078 2 $n = $n * $BASE + $a->[$i];
3079 }
3080 1 return $n;
3081 }
3082  
3083 # b_copy - Duplicate a big integer
3084 257 ▶sub b_copy {
Subroutine b_copy: called CC=1 SCAR=0.0
3085 257 my ($a) = @_;
3086 257 return [ @$a ];
3087 }
3088  
3089 # b_from_bin - Convert a big endian byte string to a big integer
3090 712 ▶sub b_from_bin {
Subroutine b_from_bin: called CC=4 SCAR=13.9
3091 712 my ($bin) = @_;
3092 712 my @limb = ();
3093 712 my $len = length($bin);
3094 # Read the string from the right, two bytes at a time.
3095 712 ▶ for (my $i = $len; $i > 0; $i -= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i > 0) 6834 712 7546
3096 6834 ▶ my $pair = ($i >= 2) ? substr($bin, $i - 2, 2) : ("\x00" . substr($bin, 0, 1));
Branch: 1 branch
BranchTrueFalseTotal
$i >= 2 ? : 6397 437 6834
3097 6834 push @limb, unpack('n', $pair);
3098 }
3099 712 ▶ push @limb, 0 unless @limb;
Branch: 1 branch
BranchTrueFalseTotal
unless @limb 0 712 712
3100 712 return b_norm([ @limb ]);
3101 }
3102  
3103 # b_to_bin - Convert a big integer to a big endian byte string
3104 # With $want_len the result is zero padded (or truncated) to that length.
3105 184 ▶sub b_to_bin {
Subroutine b_to_bin: called CC=6 SCAR=18.1
3106 184 my ($a, $want_len) = @_;
3107 184 my $bin = '';
3108 184 ▶ for (my $i = scalar(@$a) - 1; $i >= 0; $i--) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i >= 0) 2218 184 2402
3109 2218 $bin .= pack('n', $a->[$i]);
3110 }
3111 184 $bin =~ s/^\x00+//; # strip leading zero bytes
3112 184 ▶ $bin = "\x00" if $bin eq '';
Branch: 1 branch
BranchTrueFalseTotal
if $bin eq "" 0 184 184
3113 184 ▶ if (defined $want_len) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $want_len) 155 29 184
3114 155 ▶ if (length($bin) < $want_len) {
Branch: 2 branches
BranchTrueFalseTotal
if (length $bin < $want_len) { } 93 62 155
elsif (length $bin > $want_len) { } 0 62 62
3115 93 $bin = ("\x00" x ($want_len - length($bin))) . $bin;
3116 }
3117 elsif (length($bin) > $want_len) {
3118 0 $bin = substr($bin, length($bin) - $want_len);
3119 }
3120 }
3121 184 return $bin;
3122 }
3123  
3124 # b_from_hex - Convert a hexadecimal string to a big integer
3125 26 ▶sub b_from_hex {
Subroutine b_from_hex: called CC=2 SCAR=6.9
3126 26 my ($hex) = @_;
3127 26 $hex =~ s/[^0-9A-Fa-f]//g;
3128 26 ▶ $hex = "0$hex" if length($hex) % 2;
Branch: 1 branch
BranchTrueFalseTotal
if length($hex) % 2 3 23 26
3129 26 return b_from_bin(pack('H*', $hex));
3130 }
3131  
3132 # b_to_hex - Convert a big integer to a lower case hexadecimal string
3133 17 ▶sub b_to_hex {
Subroutine b_to_hex: called CC=1 SCAR=0.0
3134 17 my ($a) = @_;
3135 17 return unpack('H*', b_to_bin($a));
3136 }
3137  
3138 # ----------------------------------------------------------------
3139 # Tests and comparisons
3140 # ----------------------------------------------------------------
3141  
3142 26363 ▶sub b_is_zero {
Subroutine b_is_zero: called CC=3 SCAR=11.0
3143 26363 my ($a) = @_;
3144 26363 ▶ return ((scalar(@$a) == 1) && ($a->[0] == 0)) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
scalar @$a == 1 && $a->[0] == 0 ? : 99 26264 26363
Condition100%3/3
scalar @$a == 1 and $a->[0] == 0
!ll&&!rl&&r
2607319199
MC/DC100%2/2
scalar @$a == 1 and $a->[0] == 0
scalar @$a == 1 $a->[0] == 0
Truth table100%3/3
A and B
A= scalar @$a == 1B= $a->[0] == 0
ABresult
0X0
100
111
3145 }
3146  
3147 1 ▶sub b_is_odd {
Subroutine b_is_odd: called CC=2 SCAR=7.2
3148 1 my ($a) = @_;
3149 1 ▶ return ($a->[0] % 2) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$a->[0] % 2 ? : 1 0 1
3150 }
3151  
3152 # b_cmp - Return -1, 0 or 1 like the spaceship operator
3153 563821 ▶sub b_cmp {
Subroutine b_cmp: called CC=10 SCAR=23.2
3154 563821 my ($a, $b) = @_;
3155 563821 my $la = scalar(@$a);
3156 563821 my $lb = scalar(@$b);
3157 563821 ▶ $la-- while ($la > 1) && ($a->[$la - 1] == 0);
Branch: 1 branch
BranchTrueFalseTotal
$la > 1 and $$a[$la - 1] == 0 and do { --$la } 0 563821 563821
Condition66%2/3
$la > 1 and $$a[$la - 1] == 0
!ll&&!rl&&r
145895492320
MC/DC0%0/2
$la > 1 and $$a[$la - 1] == 0
$la > 1 $$a[$la - 1] == 0
Truth table66%2/3
A and B
A= $la > 1B= $$a[$la - 1] == 0
ABresult
0X0
100
111
3158 563821 ▶ $lb-- while ($lb > 1) && ($b->[$lb - 1] == 0);
Branch: 1 branch
BranchTrueFalseTotal
$lb > 1 and $$b[$lb - 1] == 0 and do { --$lb } 0 563821 563821
Condition66%2/3
$lb > 1 and $$b[$lb - 1] == 0
!ll&&!rl&&r
7565630650
MC/DC0%0/2
$lb > 1 and $$b[$lb - 1] == 0
$lb > 1 $$b[$lb - 1] == 0
Truth table66%2/3
A and B
A= $lb > 1B= $$b[$lb - 1] == 0
ABresult
0X0
100
111
3159 563821 ▶ return 1 if $la > $lb;
Branch: 1 branch
BranchTrueFalseTotal
if $la > $lb 126409 437412 563821
3160 437412 ▶ return -1 if $la < $lb;
Branch: 1 branch
BranchTrueFalseTotal
if $la < $lb 114610 322802 437412
3161 322802 ▶ for (my $i = $la - 1; $i >= 0; $i--) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i >= 0) 323456 40 323496
3162 323456 ▶ return 1 if $a->[$i] > $b->[$i];
Branch: 1 branch
BranchTrueFalseTotal
if $a->[$i] > $b->[$i] 59347 264109 323456
3163 264109 ▶ return -1 if $a->[$i] < $b->[$i];
Branch: 1 branch
BranchTrueFalseTotal
if $a->[$i] < $b->[$i] 263415 694 264109
3164 }
3165 40 return 0;
3166 }
3167  
3168 # b_bits - Number of significant bits
3169 1008 ▶sub b_bits {
Subroutine b_bits: called CC=6 SCAR=18.3
3170 1008 my ($a) = @_;
3171 1008 my $top = scalar(@$a) - 1;
3172 1008 ▶ $top-- while ($top > 0) && ($a->[$top] == 0);
Branch: 1 branch
BranchTrueFalseTotal
$top > 0 and $a->[$top] == 0 and do { --$top } 0 1008 1008
Condition66%2/3
$top > 0 and $a->[$top] == 0
!ll&&!rl&&r
609480
MC/DC0%0/2
$top > 0 and $a->[$top] == 0
$top > 0 $a->[$top] == 0
Truth table66%2/3
A and B
A= $top > 0B= $a->[$top] == 0
ABresult
0X0
100
111
3173 1008 ▶ return 0 if ($top == 0) && ($a->[0] == 0);
Branch: 1 branch
BranchTrueFalseTotal
if $top == 0 and $a->[0] == 0 0 1008 1008
Condition66%2/3
$top == 0 and $a->[0] == 0
!ll&&!rl&&r
948600
MC/DC0%0/2
$top == 0 and $a->[0] == 0
$top == 0 $a->[0] == 0
Truth table66%2/3
A and B
A= $top == 0B= $a->[0] == 0
ABresult
0X0
100
111
3174 1008 my $bits = $top * 16;
3175 1008 my $v = $a->[$top];
3176 1008 ▶ while ($v > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($v > 0) 9214 1008 10222
3177 9214 $bits++;
3178 9214 $v = int($v / 2);
3179 }
3180 1008 return $bits;
3181 }
3182  
3183 # b_bit - Value (0 or 1) of bit number $n, counted from the bottom
3184 143918 ▶sub b_bit {
Subroutine b_bit: called CC=2 SCAR=7.0
3185 143918 my ($a, $n) = @_;
3186 143918 my $limb = int($n / 16);
3187 143918 ▶ return 0 if $limb >= scalar(@$a);
Branch: 1 branch
BranchTrueFalseTotal
if $limb >= scalar @$a 0 143918 143918
3188 143918 return int($a->[$limb] / (2 ** ($n % 16))) % 2;
3189 }
3190  
3191 # ----------------------------------------------------------------
3192 # Addition, subtraction, multiplication
3193 # ----------------------------------------------------------------
3194  
3195 207518 ▶sub b_add {
Subroutine b_add: called CC=7 SCAR=19.5
3196 207518 my ($a, $b) = @_;
3197 207518 my @r = ();
3198 207518 my $carry = 0;
3199 207518 ▶ my $len = (scalar(@$a) > scalar(@$b)) ? scalar(@$a) : scalar(@$b);
Branch: 1 branch
BranchTrueFalseTotal
scalar @$a > scalar @$b ? : 162 207356 207518
3200 207518 ▶ for (my $i = 0; $i < $len; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 3309596 207518 3517114
3201 3309596 ▶ my $t = (defined $a->[$i] ? $a->[$i] : 0)
Branch: 2 branches
BranchTrueFalseTotal
defined $a->[$i] ? : 3308616 980 3309596
defined $b->[$i] ? : 3309328 268 3309596
3202 + (defined $b->[$i] ? $b->[$i] : 0)
3203 + $carry;
3204 3309596 ▶ if ($t >= $BASE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($t >= $BASE) { } 1652592 1657004 3309596
3205 1652592 $r[$i] = $t - $BASE;
3206 1652592 $carry = 1;
3207 }
3208 else {
3209 1657004 $r[$i] = $t;
3210 1657004 $carry = 0;
3211 }
3212 }
3213 207518 ▶ push @r, 1 if $carry;
Branch: 1 branch
BranchTrueFalseTotal
if $carry 131858 75660 207518
3214 207518 return b_norm([ @r ]);
3215 }
3216  
3217 # b_sub - Subtract $b from $a. The caller guarantees $a >= $b.
3218 242186 ▶sub b_sub {
Subroutine b_sub: called CC=4 SCAR=13.9
3219 242186 my ($a, $b) = @_;
3220 242186 my @r = ();
3221 242186 my $borrow = 0;
3222 242186 my $len = scalar(@$a);
3223 242186 ▶ for (my $i = 0; $i < $len; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $len) 4045928 242186 4288114
3224 4045928 ▶ my $t = $a->[$i] - (defined $b->[$i] ? $b->[$i] : 0) - $borrow;
Branch: 1 branch
BranchTrueFalseTotal
defined $b->[$i] ? : 3861556 184372 4045928
3225 4045928 ▶ if ($t < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($t < 0) { } 1932770 2113158 4045928
3226 1932770 $r[$i] = $t + $BASE;
3227 1932770 $borrow = 1;
3228 }
3229 else {
3230 2113158 $r[$i] = $t;
3231 2113158 $borrow = 0;
3232 }
3233 }
3234 242186 return b_norm([ @r ]);
3235 }
3236  
3237 920 ▶sub b_mul {
Subroutine b_mul: called CC=5 SCAR=16.1
3238 920 my ($a, $b) = @_;
3239 920 my $la = scalar(@$a);
3240 920 my $lb = scalar(@$b);
3241 920 my @r = (0) x ($la + $lb);
3242 920 ▶ for (my $i = 0; $i < $la; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $la) 931 920 1851
3243 931 my $ai = $a->[$i];
3244 931 ▶ next if $ai == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $ai == 0 7 924 931
3245 924 my $carry = 0;
3246 924 ▶ for (my $j = 0; $j < $lb; $j++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $lb) 7498 924 8422
3247 7498 my $t = $r[$i + $j] + $ai * $b->[$j] + $carry;
3248 7498 $carry = int($t / $BASE);
3249 7498 $r[$i + $j] = $t - $carry * $BASE;
3250 }
3251 924 my $k = $i + $lb;
3252 924 ▶ while ($carry > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($carry > 0) 85 924 1009
3253 85 my $t = $r[$k] + $carry;
3254 85 $carry = int($t / $BASE);
3255 85 $r[$k] = $t - $carry * $BASE;
3256 85 $k++;
3257 }
3258 }
3259 920 return b_norm([ @r ]);
3260 }
3261  
3262 # b_shl1 - Double a number (shift left one bit)
3263 125632 ▶sub b_shl1 {
Subroutine b_shl1: called CC=4 SCAR=13.9
3264 125632 my ($a) = @_;
3265 125632 my @r = ();
3266 125632 my $carry = 0;
3267 125632 ▶ for (my $i = 0; $i < scalar(@$a); $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < scalar @$a) 763376 125632 889008
3268 763376 my $t = $a->[$i] * 2 + $carry;
3269 763376 ▶ if ($t >= $BASE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($t >= $BASE) { } 319304 444072 763376
3270 319304 $r[$i] = $t - $BASE;
3271 319304 $carry = 1;
3272 }
3273 else {
3274 444072 $r[$i] = $t;
3275 444072 $carry = 0;
3276 }
3277 }
3278 125632 ▶ push @r, 1 if $carry;
Branch: 1 branch
BranchTrueFalseTotal
if $carry 8645 116987 125632
3279 125632 return b_norm([ @r ]);
3280 }
3281  
3282 # ----------------------------------------------------------------
3283 # Division
3284 # ----------------------------------------------------------------
3285 # Plain shift and subtract long division in binary. It is not the
3286 # fastest algorithm, but it is short enough to read, and the hot path
3287 # of RSA uses Montgomery multiplication below, which needs no division
3288 # at all.
3289 # ----------------------------------------------------------------
3290  
3291 1165 ▶sub b_divmod {
Subroutine b_divmod: called CC=6 SCAR=18.0
3292 1165 my ($a, $b) = @_;
3293 1165 ▶ die "HTTPS::Handy::BigInt: division by zero" if b_is_zero($b);
Branch: 1 branch
BranchTrueFalseTotal
if b_is_zero($b) 0 1165 1165
3294 1165 ▶ return ([ 0 ], [ 0 ]) if b_is_zero($a);
Branch: 1 branch
BranchTrueFalseTotal
if b_is_zero($a) 0 1165 1165
3295 1165 ▶ return ([ 0 ], b_copy($a)) if b_cmp($a, $b) < 0;
Branch: 1 branch
BranchTrueFalseTotal
if b_cmp($a, $b) < 0 250 915 1165
3296  
3297 915 my $bits = b_bits($a);
3298 915 my @q = (0) x scalar(@$a);
3299 915 my $r = [ 0 ];
3300 915 ▶ for (my $i = $bits - 1; $i >= 0; $i--) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i >= 0) 120544 915 121459
3301 120544 $r = b_shl1($r);
3302 120544 $r->[0] += b_bit($a, $i);
3303 120544 ▶ if (b_cmp($r, $b) >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (b_cmp($r, $b) >= 0) 1448 119096 120544
3304 1448 $r = b_sub($r, $b);
3305 1448 $q[int($i / 16)] += 2 ** ($i % 16);
3306 }
3307 }
3308 915 return (b_norm([ @q ]), $r);
3309 }
3310  
3311 245 ▶sub b_mod {
Subroutine b_mod: called CC=1 SCAR=0.0
3312 245 my ($a, $b) = @_;
3313 245 my ($q, $r) = b_divmod($a, $b);
3314 245 return $r;
3315 }
3316  
3317 # ----------------------------------------------------------------
3318 # Montgomery multiplication
3319 # ----------------------------------------------------------------
3320 # Montgomery arithmetic replaces the division in "multiply, then take
3321 # the remainder" with a shift. Numbers are kept in "Montgomery form",
3322 # that is multiplied by R = 65536 ** k (mod n), where k is the number
3323 # of limbs of the modulus n. mont_mul(a, b) then computes
3324 #
3325 # a * b * R ** -1 (mod n)
3326 #
3327 # so Montgomery form is preserved. n must be odd, which is always true
3328 # for an RSA modulus and for the primes tested during key generation.
3329 # ----------------------------------------------------------------
3330  
3331 # _mont_n0inv - Compute (-n) ** -1 mod 65536 by Newton iteration
3332 12 ▶sub _mont_n0inv {
Subroutine _mont_n0inv: called CC=3 SCAR=11.0
3333 12 my ($n) = @_;
3334 12 my $n0 = $n->[0];
3335 12 my $inv = 1;
3336 12 ▶ for (my $i = 0; $i < 5; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < 5) 60 12 72
3337 # inv <- inv * (2 - n0 * inv) mod 65536
3338 # The products reach 2 ** 32, so the remainder is taken by
3339 # subtracting a multiple rather than with the % operator,
3340 # which would have to cast them into a 32 bit integer first.
3341 60 my $p = $n0 * $inv;
3342 60 my $t = 2 - ($p - $BASE * int($p / $BASE));
3343 60 ▶ $t += $BASE while $t < 0;
Branch: 1 branch
BranchTrueFalseTotal
$t < 0 and do { $t += $BASE } 38 60 98
3344 60 $p = $inv * $t;
3345 60 $inv = $p - $BASE * int($p / $BASE);
3346 }
3347 12 return ($BASE - $inv) - $BASE * int((($BASE - $inv)) / $BASE);
3348 }
3349  
3350 # b_mont_context - Everything the Montgomery routines need for a modulus
3351 #
3352 # The context is built once per modulus and then reused, which matters
3353 # because the elliptic curve code below does tens of thousands of
3354 # multiplications with the same prime.
3355 12 ▶sub b_mont_context {
Subroutine b_mont_context: called CC=3 SCAR=11.0
3356 12 my ($n) = @_;
3357 12 my $k = scalar(@$n);
3358 12 my $ctx = {
3359 'n' => $n,
3360 'k' => $k,
3361 'n0inv' => _mont_n0inv($n),
3362 };
3363 # rr = R ** 2 mod n, by doubling 1 exactly 2 * k * 16 times
3364 12 my $rr = [ 1 ];
3365 12 ▶ for (my $i = 0; $i < 2 * $k * 16; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < 2 * $k * 16) 5088 12 5100
3366 5088 $rr = b_shl1($rr);
3367 5088 ▶ $rr = b_sub($rr, $n) if b_cmp($rr, $n) >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if b_cmp($rr, $n) >= 0 1326 3762 5088
3368 }
3369 12 $ctx->{'rr'} = $rr;
3370 12 $ctx->{'one'} = b_mont_mul($ctx, [ 1 ], $rr); # R mod n
3371 12 return $ctx;
3372 }
3373  
3374 # b_mont_mul - Montgomery product using the CIOS method
3375 173533 ▶sub b_mont_mul {
Subroutine b_mont_mul: called CC=7 SCAR=19.5
3376 173533 my ($ctx, $a, $b) = @_;
3377 173533 my $n = $ctx->{'n'};
3378 173533 my $k = $ctx->{'k'};
3379 173533 my $n0inv = $ctx->{'n0inv'};
3380 173533 my @t = (0) x ($k + 2);
3381 173533 ▶ for (my $i = 0; $i < $k; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $k) 2770499 173533 2944032
3382 2770499 ▶ my $ai = (defined $a->[$i]) ? $a->[$i] : 0;
Branch: 1 branch
BranchTrueFalseTotal
defined $a->[$i] ? : 2769977 522 2770499
3383 2770499 my $carry = 0;
3384 2770499 my $t0;
3385 2770499 ▶ for (my $j = 0; $j < $k; $j++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $k) 44285423 2770499 47055922
3386 44285423 ▶ $t0 = $t[$j] + $ai * ((defined $b->[$j]) ? $b->[$j] : 0) + $carry;
Branch: 1 branch
BranchTrueFalseTotal
defined $b->[$j] ? : 44249672 35751 44285423
3387 44285423 $carry = int($t0 / $BASE);
3388 44285423 $t[$j] = $t0 - $carry * $BASE;
3389 }
3390 2770499 $t0 = $t[$k] + $carry;
3391 2770499 $carry = int($t0 / $BASE);
3392 2770499 $t[$k] = $t0 - $carry * $BASE;
3393 2770499 $t[$k + 1] += $carry;
3394  
3395 # t[0] * n0inv reaches 2 ** 32, so again no % operator here
3396 2770499 my $mp = $t[0] * $n0inv;
3397 2770499 my $m = $mp - $BASE * int($mp / $BASE);
3398 2770499 $t0 = $t[0] + $m * $n->[0];
3399 2770499 $carry = int($t0 / $BASE);
3400 2770499 ▶ for (my $j = 1; $j < $k; $j++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < $k) 41514924 2770499 44285423
3401 41514924 $t0 = $t[$j] + $m * $n->[$j] + $carry;
3402 41514924 $carry = int($t0 / $BASE);
3403 41514924 $t[$j - 1] = $t0 - $carry * $BASE;
3404 }
3405 2770499 $t0 = $t[$k] + $carry;
3406 2770499 $carry = int($t0 / $BASE);
3407 2770499 $t[$k - 1] = $t0 - $carry * $BASE;
3408 2770499 $t[$k] = $t[$k + 1] + $carry;
3409 2770499 $t[$k + 1] = 0;
3410 }
3411 173533 my $r = b_norm([ @t[0 .. $k] ]);
3412 173533 ▶ $r = b_sub($r, $n) if b_cmp($r, $n) >= 0;
Branch: 1 branch
BranchTrueFalseTotal
if b_cmp($r, $n) >= 0 50222 123311 173533
3413 173533 return $r;
3414 }
3415  
3416 # b_to_mont / b_from_mont - Move in and out of Montgomery form
3417 219 ▶sub b_to_mont {
Subroutine b_to_mont: called CC=1 SCAR=0.0
3418 219 my ($ctx, $a) = @_;
3419 219 return b_mont_mul($ctx, b_mod($a, $ctx->{'n'}), $ctx->{'rr'});
3420 }
3421  
3422 105 ▶sub b_from_mont {
Subroutine b_from_mont: called CC=1 SCAR=0.0
3423 105 my ($ctx, $a) = @_;
3424 105 return b_mont_mul($ctx, $a, [ 1 ]);
3425 }
3426  
3427 # b_mont_pow - Exponentiation with the base already in Montgomery form
3428 47 ▶sub b_mont_pow {
Subroutine b_mont_pow: called CC=3 SCAR=11.0
3429 47 my ($ctx, $a, $e) = @_;
3430 47 my $r = $ctx->{'one'};
3431 47 ▶ for (my $i = b_bits($e) - 1; $i >= 0; $i--) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i >= 0) 11904 47 11951
3432 11904 $r = b_mont_mul($ctx, $r, $r);
3433 11904 ▶ $r = b_mont_mul($ctx, $r, $a) if b_bit($e, $i);
Branch: 1 branch
BranchTrueFalseTotal
if b_bit($e, $i) 5952 5952 11904
3434 }
3435 47 return $r;
3436 }
3437  
3438 # b_modexp - Modular exponentiation: $a ** $e mod $n
3439 1 ▶sub b_modexp {
Subroutine b_modexp: called CC=6 SCAR=26.0
3440 1 my ($a, $e, $n) = @_;
3441 1 ▶ return [ 0 ] if b_is_zero($n);
Branch: 1 branch
BranchTrueFalseTotal
if b_is_zero($n) 0 1 1
3442 1 ▶ return [ 1 ] if b_is_zero($e);
Branch: 1 branch
BranchTrueFalseTotal
if b_is_zero($e) 0 1 1
3443 1 ▶ if (!b_is_odd($n)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (b_is_odd($n)) 0 1 1
3444 # Even modulus: Montgomery does not apply, so fall back to the
3445 # slow but general square and multiply.
3446 0 my $r = [ 1 ];
3447 0 my $base = b_mod($a, $n);
3448 0 ▶ for (my $i = 0; $i < b_bits($e); $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < b_bits($e)) 0 0 0
3449 0 ▶ $r = b_mod(b_mul($r, $base), $n) if b_bit($e, $i);
Branch: 1 branch
BranchTrueFalseTotal
if b_bit($e, $i) 0 0 0
3450 0 $base = b_mod(b_mul($base, $base), $n);
3451 }
3452 0 return $r;
3453 }
3454 1 my $ctx = b_mont_context($n);
3455 1 return b_from_mont($ctx, b_mont_pow($ctx, b_to_mont($ctx, $a), $e));
3456 }
3457  
3458 # ----------------------------------------------------------------
3459 # Extended Euclid
3460 # ----------------------------------------------------------------
3461  
3462 # b_modinv - Modular inverse: find x with a * x = 1 (mod m)
3463 # The signs of the Bezout coefficients are tracked by hand because
3464 # these big integers are unsigned.
3465 7 ▶sub b_modinv {
Subroutine b_modinv: called CC=7 SCAR=19.5
3466 7 my ($a, $m) = @_;
3467 7 my $old_r = b_mod($a, $m);
3468 7 my $r = b_copy($m);
3469 7 my $old_s = [ 1 ]; my $old_sign = 1;
3470 7 my $s = [ 0 ]; my $sign = 1;
3471  
3472 7 ▶ while (!b_is_zero($r)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (b_is_zero($r)) 919 7 926
3473 919 my ($q, $rem) = b_divmod($old_r, $r);
3474 919 $old_r = $r;
3475 919 $r = $rem;
3476 # (old_s, s) <- (s, old_s - q * s) with explicit signs
3477 919 my $qs = b_mul($q, $s);
3478 919 my ($new, $new_sign);
3479 919 ▶ if ($old_sign == $sign) {
Branch: 1 branch
BranchTrueFalseTotal
if ($old_sign == $sign) { } 14 905 919
3480 14 ▶ if (b_cmp($old_s, $qs) >= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (b_cmp($old_s, $qs) >= 0) { } 7 7 14
3481 7 $new = b_sub($old_s, $qs);
3482 7 $new_sign = $old_sign;
3483 }
3484 else {
3485 7 $new = b_sub($qs, $old_s);
3486 7 $new_sign = -$old_sign;
3487 }
3488 }
3489 else {
3490 905 $new = b_add($old_s, $qs);
3491 905 $new_sign = $old_sign;
3492 }
3493 919 $old_s = $s; $old_sign = $sign;
3494 919 $s = $new; $sign = $new_sign;
3495 }
3496 7 ▶ return [ 0 ] if b_cmp($old_r, [ 1 ]) != 0; # not invertible
Branch: 1 branch
BranchTrueFalseTotal
if b_cmp($old_r, [1]) != 0 0 7 7
3497  
3498 7 my $inv = b_mod($old_s, $m);
3499 7 ▶ $inv = b_sub($m, $inv) if ($old_sign < 0) && !b_is_zero($inv);
Branch: 1 branch
BranchTrueFalseTotal
if $old_sign < 0 and not b_is_zero($inv) 3 4 7
Condition66%2/3
$old_sign < 0 and not b_is_zero($inv)
!ll&&!rl&&r
403
MC/DC50%1/2
$old_sign < 0 and not b_is_zero($inv)
$old_sign < 0 not b_is_zero($inv)
Truth table66%2/3
A and not(B)
A= $old_sign < 0B= not b_is_zero($inv)
ABresult
0X0
100
111
3500 7 return $inv;
3501 }
3502  
3503  
3504 # ----------------------------------------------------------------
3505 # Back to main package -- demo/self-test when run directly
3506 # ----------------------------------------------------------------
3507 package HTTPS::Handy;
3508  
3509 # Run as script: perl HTTPS::Handy.pm [port]
3510 8 ▶unless (caller) {
Branch: 1 branch
BranchTrueFalseTotal
unless (caller) 0 8 8
3511 0 ▶ my $port = $ARGV[0] || 8443;
Condition0%0/2
$ARGV[0] || 8443
l!l
00
MC/DC0%0/1
$ARGV[0] || 8443
$ARGV[0]
Truth table0%0/2
A
A= $ARGV[0]
Aresult
11
00
3512  
3513 0 ▶ my $demo_app = sub {
Subroutine __ANON__: not called CC=17 SCAR=57.2
3514 0 my $env = shift;
3515 0 my $method = $env->{REQUEST_METHOD};
3516 0 my $path = $env->{PATH_INFO};
3517 0 my $query = $env->{QUERY_STRING};
3518  
3519 # Route: GET /
3520 0 ▶ if ($method eq 'GET' && $path eq '/') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "GET" and $path eq "/") 0 0 0
Condition0%0/3
$method eq "GET" and $path eq "/"
!ll&&!rl&&r
000
MC/DC0%0/2
$method eq "GET" and $path eq "/"
$method eq "GET" $path eq "/"
Truth table0%0/3
A and B
A= $method eq "GET"B= $path eq "/"
ABresult
0X0
100
111
3521 0 my $scheme = $env->{'psgi.url_scheme'};
3522 0 my $cipher = $env->{'psgix.tls_cipher'};
3523 # Reloading this page shows the second line change: the
3524 # first connection does the full handshake, the ones after
3525 # it resume the session and skip the curve arithmetic.
3526 0 ▶ my $shake = $env->{'psgix.tls_resumed'}
Branch: 1 branch
BranchTrueFalseTotal
$env->{'psgix.tls_resumed'} ? : 0 0 0
3527 ? 'resumed from the session cache'
3528 : 'full, including the curve arithmetic';
3529 0 my $html = <<"HTML";
3530 <!DOCTYPE html>
3531 <html>
3532 <head><meta charset="utf-8"><title>HTTPS::Handy Demo</title>
3533 <style>
3534 body { font-family: sans-serif; max-width: 600px; margin: 40px auto; padding: 0 20px; }
3535 h1 { color: #336699; }
3536 .secure { color: green; font-weight: bold; }
3537 code { background: #f0f0f0; padding: 2px 6px; border-radius: 3px; }
3538 form { margin: 20px 0; }
3539 input, textarea { display: block; margin: 8px 0; padding: 6px; width: 100%; box-sizing: border-box; }
3540 button { padding: 8px 20px; background: #336699; color: white; border: none; cursor: pointer; }
3541 </style>
3542 </head>
3543 <body>
3544 <h1>HTTPS::Handy Demo</h1>
3545 <p class="secure">&#x1F512; Secure connection: $scheme</p>
3546 <p>A tiny HTTPS/1.0 server for Perl 5.5.3 and later. Everything below
3547 this page &mdash; the handshake, the certificate, the encryption &mdash;
3548 is written in pure Perl in one file, with no other module and no
3549 external program.</p>
3550 <p>Cipher suite: <code>$cipher</code><br>
3551 Handshake: <code>$shake</code> (reload this page and watch it change)</p>
3552 <h2>GET with query string</h2>
3553 <form method="get" action="/echo">
3554 <input type="text" name="message" placeholder="Type something...">
3555 <button type="submit">Send GET</button>
3556 </form>
3557 <h2>POST form</h2>
3558 <form method="post" action="/echo">
3559 <input type="text" name="name" placeholder="Name">
3560 <textarea name="body" placeholder="Message" rows="3"></textarea>
3561 <button type="submit">Send POST</button>
3562 </form>
3563 <p><a href="/info">Server info</a></p>
3564 </body>
3565 </html>
3566 HTML
3567 0 return HTTPS::Handy->response_html($html);
3568 }
3569  
3570 # Route: GET or POST /echo
3571 0 ▶ if ($path eq '/echo') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/echo") 0 0 0
3572 0 my %params;
3573 0 ▶ if ($method eq 'GET') {
Branch: 2 branches
BranchTrueFalseTotal
if ($method eq 'GET') { } 0 0 0
elsif ($method eq 'POST') { } 0 0 0
3574 0 %params = HTTPS::Handy->parse_query($query);
3575 }
3576 elsif ($method eq 'POST') {
3577 0 my $body = '';
3578 0 ▶ $env->{'psgi.input'}->read($body, $env->{CONTENT_LENGTH} || 0);
Condition0%0/2
$env->{'CONTENT_LENGTH'} || 0
l!l
00
MC/DC0%0/1
$env->{'CONTENT_LENGTH'} || 0
$env->{'CONTENT_LENGTH'}
Truth table0%0/2
A
A= $env->{'CONTENT_LENGTH'}
Aresult
11
00
3579 0 %params = HTTPS::Handy->parse_query($body);
3580 }
3581  
3582 0 my $params_html = '';
3583 0 for my $key (sort keys %params) {
3584 0 my $val = $params{$key};
3585 0 ▶ $val = ref($val) eq 'ARRAY' ? join(', ', @$val) : $val;
Branch: 1 branch
BranchTrueFalseTotal
ref $val eq 'ARRAY' ? : 0 0 0
3586 # simple HTML escape
3587 0 $val =~ s/&/&amp;/g;
3588 0 $val =~ s/</&lt;/g;
3589 0 $val =~ s/>/&gt;/g;
3590 0 $key =~ s/&/&amp;/g;
3591 0 $key =~ s/</&lt;/g;
3592 0 $params_html .= "<tr><td><b>$key</b></td><td>$val</td></tr>";
3593 }
3594 0 ▶ $params_html ||= '<tr><td colspan="2">(no parameters)</td></tr>';
Condition0%0/2
$params_html ||= "<tr><td colspan=\"2\">(no parameters)</td></tr>"
l!l
00
MC/DC0%0/1
$params_html ||= "<tr><td colspan=\"2\">(no parameters)</td></tr>"
$params_html
Truth table0%0/2
A
A= $params_html
Aresult
11
00
3595  
3596 0 my $html = <<"HTML";
3597 <!DOCTYPE html>
3598 <html><head><meta charset="utf-8"><title>Echo</title>
3599 <style>body{font-family:sans-serif;max-width:600px;margin:40px auto;padding:0 20px}
3600 table{border-collapse:collapse;width:100%}td{padding:6px 10px;border:1px solid #ccc}
3601 </style></head>
3602 <body>
3603 <h1>Echo: $method $path</h1>
3604 <table>$params_html</table>
3605 <p><a href="/">Back</a></p>
3606 </body></html>
3607 HTML
3608 0 return HTTPS::Handy->response_html($html);
3609 }
3610  
3611 # Route: GET /info
3612 0 ▶ if ($method eq 'GET' && $path eq '/info') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "GET" and $path eq "/info") 0 0 0
Condition0%0/3
$method eq "GET" and $path eq "/info"
!ll&&!rl&&r
000
MC/DC0%0/2
$method eq "GET" and $path eq "/info"
$method eq "GET" $path eq "/info"
Truth table0%0/3
A and B
A= $method eq "GET"B= $path eq "/info"
ABresult
0X0
100
111
3613 0 my $env_html = '';
3614 0 for my $key (sort keys %$env) {
3615 0 ▶ next if $key eq 'psgi.input' || $key eq 'psgi.errors';
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "psgi.input" or $key eq "psgi.errors" 0 0 0
Condition0%0/3
$key eq "psgi.input" or $key eq "psgi.errors"
l!l&&r!l&&!r
000
MC/DC0%0/2
$key eq "psgi.input" or $key eq "psgi.errors"
$key eq "psgi.input" $key eq "psgi.errors"
Truth table0%0/3
A or B
A= $key eq "psgi.input"B= $key eq "psgi.errors"
ABresult
1X1
011
000
3616 0 my $val = $env->{$key};
3617 0 ▶ $val = '' unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 0 0 0
3618 0 $val =~ s/&/&amp;/g;
3619 0 $val =~ s/</&lt;/g;
3620 0 $env_html .= "<tr><td><code>$key</code></td><td>$val</td></tr>";
3621 }
3622 0 my $html = <<"HTML";
3623 <!DOCTYPE html>
3624 <html><head><meta charset="utf-8"><title>Server Info</title>
3625 <style>body{font-family:sans-serif;max-width:700px;margin:40px auto;padding:0 20px}
3626 table{border-collapse:collapse;width:100%}td{padding:4px 8px;border:1px solid #ddd;font-size:13px}
3627 tr:nth-child(even){background:#f8f8f8}code{font-size:12px}
3628 </style></head>
3629 <body>
3630 <h1>PSGI Environment</h1>
3631 <table>$env_html</table>
3632 <p><a href="/">Back</a></p>
3633 </body></html>
3634 HTML
3635 0 return HTTPS::Handy->response_html($html);
3636 }
3637  
3638 # 404 fallback
3639 0 return [404,
3640 ['Content-Type', 'text/html'],
3641 ["<h1>404 Not Found</h1><p>$path</p><a href='/'>Home</a>"]];
3642 0 };
3643  
3644 0 HTTPS::Handy->run(app => $demo_app, port => $port);
3645 }
3646  
3647 8 1;
3648  
3649 __END__
↑ Summary