Age/Primitives.pm

filter: Statementstmt 98.1% 157 / 160 Branchbran 75.7% 53 / 70 Conditioncond 88.8% 8 / 9 MC/DCmcdc 83.3% 5 / 6 Subroutinesub 100% 27 / 27 Podpod 100% 14 / 14 totaltotal 92.3% 264 / 286 CC 39 SCAR 16.6
CC
39
Cov
91%
decrypt_payload_fh
12.0
paranoid_read
7.7
encrypt_payload
6.3
CRAP 5.2
« Age.pm ↑ Summary Age/Keys.pm »
1 package Crypt::Age::Primitives;
2 # ABSTRACT: Low-level cryptographic primitives for age encryption
3 8 our $VERSION = '0.005';
4 8 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 8 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 8 ▶use Crypt::PK::X25519;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 8 ▶use Crypt::AuthEnc::ChaCha20Poly1305;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 8 ▶use Crypt::KeyDerivation qw(hkdf);
Subroutine BEGIN: called CC=1 SCAR=0.0
9 8 ▶use Crypt::Mac::HMAC qw(hmac);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 8 ▶use Crypt::PRNG qw(random_bytes);
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 8 ▶use constant READ_ATTEMPTS => 3;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 8 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16  
17 # Constants from age spec
18 8 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
19 8 FILE_KEY_SIZE => 16,
20 X25519_KEY_SIZE => 32,
21 CHUNK_SIZE => 64 * 1024, # 64 KiB
22 NONCE_SIZE => 12,
23 TAG_SIZE => 16,
24 8 };
25  
26 # HKDF labels from age spec
27 8 ▶use constant {
Subroutine BEGIN: called CC=1 SCAR=0.0
28 8 LABEL_X25519 => "age-encryption.org/v1/X25519",
29 LABEL_HEADER => "header",
30 LABEL_PAYLOAD => "payload",
31 8 };
32  
33 46 ▶sub generate_file_key {
Subroutine generate_file_key: called CC=1 SCAR=0.0
Pod documented
34 46 return random_bytes(FILE_KEY_SIZE);
35 }
36  
37  
38 52 ▶sub x25519_generate_keypair {
Subroutine x25519_generate_keypair: called CC=1 SCAR=0.0
Pod documented
39 52 my ($class) = @_;
40 52 my $pk = Crypt::PK::X25519->new;
41 52 $pk->generate_key;
42 52 return ($pk->export_key_raw('public'), $pk->export_key_raw('private'));
43 }
44  
45  
46 655 ▶sub x25519_shared_secret {
Subroutine x25519_shared_secret: called CC=2 SCAR=6.9
Pod documented
47 655 my ($class, $our_private, $their_public) = @_;
48  
49 655 my $our_pk = Crypt::PK::X25519->new;
50 655 $our_pk->import_key_raw($our_private, 'private');
51  
52 655 my $their_pk = Crypt::PK::X25519->new;
53 655 $their_pk->import_key_raw($their_public, 'public');
54  
55 655 my $shared_secret = $our_pk->shared_secret($their_pk);
56  
57 # c2sp.org/age, X25519 recipient type: "If the shared secret is all 0x00
58 # bytes, the identity implementation MUST abort." That is the low-order
59 # point check. The peer key is public, so this comparison does not need to
60 # be constant time. Recent CryptX/libtomcrypt rejects such peer keys inside
61 # shared_secret() with its own error, but the cpanfile pins no minimum
62 # CryptX version and the spec puts the duty on us, so we check regardless.
63 652 ▶ croak "X25519 shared secret is all zero: peer key is a low-order point"
Branch: 1 branch
BranchTrueFalseTotal
unless $shared_secret =~ /[^\x00]/ 1 651 652
64 if $shared_secret !~ /[^\x00]/;
65  
66 651 return $shared_secret;
67 }
68  
69  
70 649 ▶sub derive_wrap_key {
Subroutine derive_wrap_key: called CC=1 SCAR=0.0
Pod documented
71 649 my ($class, $shared_secret, $ephemeral_public, $recipient_public) = @_;
72  
73 # salt = ephemeral_public || recipient_public
74 649 my $salt = $ephemeral_public . $recipient_public;
75  
76 # hkdf($secret, $salt, $hash, $length, $info)
77 649 return hkdf($shared_secret, $salt, 'SHA256', 32, LABEL_X25519);
78 }
79  
80  
81 48 ▶sub wrap_file_key {
Subroutine wrap_file_key: called CC=3 SCAR=11.1
Pod documented
82 48 my ($class, $wrap_key, $file_key) = @_;
83  
84 48 ▶ croak "Wrap key must be 32 bytes" unless length($wrap_key) == 32;
Branch: 1 branch
BranchTrueFalseTotal
unless length $wrap_key == 32 0 48 48
85 48 ▶ croak "File key must be 16 bytes" unless length($file_key) == FILE_KEY_SIZE;
Branch: 1 branch
BranchTrueFalseTotal
unless length $file_key == 16 0 48 48
86  
87 # ChaCha20-Poly1305 with zero nonce
88 48 my $nonce = "\x00" x NONCE_SIZE;
89 48 my $ae = Crypt::AuthEnc::ChaCha20Poly1305->new($wrap_key, $nonce);
90 48 my $ciphertext = $ae->encrypt_add($file_key);
91 48 my $tag = $ae->encrypt_done;
92  
93 48 return $ciphertext . $tag;
94 }
95  
96  
97 601 ▶sub unwrap_file_key {
Subroutine unwrap_file_key: called CC=4 SCAR=13.9
Pod documented
98 601 my ($class, $wrap_key, $wrapped_key) = @_;
99  
100 601 ▶ croak "Wrap key must be 32 bytes" unless length($wrap_key) == 32;
Branch: 1 branch
BranchTrueFalseTotal
unless length $wrap_key == 32 0 601 601
101 601 ▶ croak "Wrapped key must be 32 bytes" unless length($wrapped_key) == FILE_KEY_SIZE + TAG_SIZE;
Branch: 1 branch
BranchTrueFalseTotal
unless length $wrapped_key == 32 0 601 601
102  
103 601 my $ciphertext = substr($wrapped_key, 0, FILE_KEY_SIZE);
104 601 my $tag = substr($wrapped_key, FILE_KEY_SIZE, TAG_SIZE);
105  
106 601 my $nonce = "\x00" x NONCE_SIZE;
107 601 my $ae = Crypt::AuthEnc::ChaCha20Poly1305->new($wrap_key, $nonce);
108 601 my $file_key = $ae->decrypt_add($ciphertext);
109  
110 601 ▶ croak "Authentication failed" unless $ae->decrypt_done($tag);
Branch: 1 branch
BranchTrueFalseTotal
unless $ae->decrypt_done($tag) 519 82 601
111  
112 82 return $file_key;
113 }
114  
115  
116 86 ▶sub derive_payload_key {
Subroutine derive_payload_key: called CC=3 SCAR=11.4
Pod documented
117 86 my ($class, $file_key, $nonce) = @_;
118  
119 86 ▶ croak "nonce required" unless defined $nonce;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $nonce 0 86 86
120 86 ▶ croak "nonce must be 16 bytes" unless length($nonce) == 16;
Branch: 1 branch
BranchTrueFalseTotal
unless length $nonce == 16 0 86 86
121  
122 # Derive payload key using HKDF
123 # hkdf($secret, $salt, $hash, $length, $info)
124 # The nonce is used as salt, and "payload" is the info string
125 86 return hkdf($file_key, $nonce, 'SHA256', 32, LABEL_PAYLOAD);
126 }
127  
128 19 ▶sub generate_payload_nonce {
Subroutine generate_payload_nonce: called CC=1 SCAR=0.0
Pod documented
129 19 return random_bytes(16);
130 }
131  
132  
133 144 ▶sub compute_header_mac {
Subroutine compute_header_mac: called CC=1 SCAR=0.0
Pod documented
134 144 my ($class, $file_key, $header_bytes) = @_;
135  
136 # Derive MAC key using HKDF
137 # hkdf($secret, $salt, $hash, $length, $info)
138 144 my $mac_key = hkdf($file_key, '', 'SHA256', 32, LABEL_HEADER);
139  
140 144 return hmac('SHA256', $mac_key, $header_bytes);
141 }
142  
143  
144 5 ▶sub encrypt_payload {
Subroutine encrypt_payload: called CC=6 SCAR=18.5
Pod documented
145 5 my ($class, $payload_key, $plaintext) = @_;
146  
147 # Perl's own test for the in-memory open below, hoisted so the failure
148 # names its cause instead of arriving as EINVAL from the open. Why
149 # utf8::downgrade rather than utf8::is_utf8 or a /[^\x00-\xff]/ scan, and
150 # why mutating this copy is safe, is written out over the same check in
151 # Crypt::Age::encrypt.
152 5 ▶ utf8::downgrade($plaintext, 1)
Branch: 1 branch
BranchTrueFalseTotal
utf8::downgrade($plaintext, 1) or croak("plaintext must be a byte string: it holds a code point above 0xFF, encode it before passing it in") 4 1 5
153 or croak 'plaintext must be a byte string: it holds a code point '
154 .'above 0xFF, encode it before passing it in';
155  
156 4 ▶ open my $ifh, '<:raw', \$plaintext or croak "Cannot open input string: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $ifh, "<:raw", \$plaintext or croak("Cannot open input string: $!") 4 0 4
157  
158 4 my $output = '';
159 4 ▶ open my $ofh, '>:raw', \$output or croak "Cannot open output string: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $ofh, ">:raw", \$output or croak("Cannot open output string: $!") 4 0 4
160  
161 4 $class->encrypt_payload_fh($payload_key, $ifh, $ofh);
162  
163 4 ▶ close $ofh or croak "Cannot close output string: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $ofh or croak("Cannot close output string: $!") 4 0 4
164 4 ▶ close $ifh or croak "Cannot close input string: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $ifh or croak("Cannot close input string: $!") 4 0 4
165  
166 4 return $output;
167 }
168  
169  
170 22 ▶sub encrypt_payload_fh {
Subroutine encrypt_payload_fh: called CC=2 SCAR=6.9
Pod documented
171 22 my ($class, $payload_key, $ifh, $ofh) = @_;
172  
173 22 my $counter = 0;
174 22 my $is_final = 0;
175 22 ▶ while (! $is_final) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($is_final) 26 22 48
176 26 my $chunk = $class->paranoid_read($ifh, CHUNK_SIZE);
177 26 $is_final = eof($ifh);
178  
179 26 my $nonce = $class->_make_nonce($counter, $is_final);
180 26 my $ae = Crypt::AuthEnc::ChaCha20Poly1305->new($payload_key, $nonce);
181  
182 26 my $ciphertext = $ae->encrypt_add($chunk);
183 26 my $tag = $ae->encrypt_done;
184  
185 26 print {$ofh} $ciphertext, $tag;
186  
187 26 $counter++;
188 }
189  
190 22 return;
191 }
192  
193  
194 2 ▶sub decrypt_payload {
Subroutine decrypt_payload: called CC=6 SCAR=18.5
Pod documented
195 2 my ($class, $payload_key, $ciphertext) = @_;
196  
197 # Same test, same reasons as in encrypt_payload above; the advice differs
198 # because an age payload is binary, so a wide character in it means the
199 # caller decoded bytes that were never text.
200 2 ▶ utf8::downgrade($ciphertext, 1)
Branch: 1 branch
BranchTrueFalseTotal
utf8::downgrade($ciphertext, 1) or croak("ciphertext must be a byte string: it holds a code point above 0xFF, read it with :raw rather than decoding it") 1 1 2
201 or croak 'ciphertext must be a byte string: it holds a code point '
202 .'above 0xFF, read it with :raw rather than decoding it';
203  
204 1 ▶ open my $ifh, '<:raw', \$ciphertext or croak "Cannot open input string: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $ifh, "<:raw", \$ciphertext or croak("Cannot open input string: $!") 1 0 1
205  
206 1 my $output = '';
207 1 ▶ open my $ofh, '>:raw', \$output or croak "Cannot open output string: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $ofh, ">:raw", \$output or croak("Cannot open output string: $!") 1 0 1
208  
209 1 $class->decrypt_payload_fh($payload_key, $ifh, $ofh);
210  
211 1 ▶ close $ofh or croak "Cannot close output string: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $ofh or croak("Cannot close output string: $!") 1 0 1
212 1 ▶ close $ifh or croak "Cannot close input string: $!";
Branch: 1 branch
BranchTrueFalseTotal
close $ifh or croak("Cannot close input string: $!") 1 0 1
213  
214 1 return $output;
215 }
216  
217  
218 75 ▶sub decrypt_payload_fh {
Subroutine decrypt_payload_fh: called CC=12 SCAR=24.8
Pod documented
219 75 my ($class, $payload_key, $ifh, $ofh) = @_;
220  
221 75 my $max_encrypted_chunk = CHUNK_SIZE + TAG_SIZE;
222 75 my $counter = 0;
223 75 while (1) {
224 # Each encrypted chunk is plaintext + 16 byte tag
225 862 my $ct = $class->paranoid_read($ifh, $max_encrypted_chunk);
226  
227 # paranoid_read only comes back short at end of file, so a short read
228 # is how this loop learns the file ends here. A *full* read says
229 # nothing either way: more chunks may follow, or this may be the final
230 # chunk sitting flush against the end of the file.
231 862 my $short_read = length($ct) < $max_encrypted_chunk;
232  
233 862 ▶ if ($short_read) {
Branch: 1 branch
BranchTrueFalseTotal
if ($short_read) 60 802 862
234 # Spec: "Streaming decryption MUST signal an error if the end of
235 # file is reached without successfully decrypting a final chunk."
236 60 ▶ croak 'Payload authentication failed at chunk '.$counter
Branch: 1 branch
BranchTrueFalseTotal
if length $ct == 0 5 55 60
237 . ': end of file reached without a final chunk'
238 if length($ct) == 0;
239 55 ▶ croak 'Payload authentication failed at chunk '.$counter
Branch: 1 branch
BranchTrueFalseTotal
if length $ct < 16 4 51 55
240 . ': chunk is shorter than its authentication tag'
241 if length($ct) < TAG_SIZE;
242 # Spec: "The final chunk MAY be shorter than 64 KiB but MUST NOT
243 # be empty unless the whole payload is empty."
244 51 ▶ croak 'Payload authentication failed at chunk '.$counter
Branch: 1 branch
BranchTrueFalseTotal
if length $ct == 16 and $counter > 0 2 49 51
Condition100%3/3
length $ct == 16 and $counter > 0
!ll&&!rl&&r
4632
MC/DC100%2/2
length $ct == 16 and $counter > 0
length $ct == 16 $counter > 0
Truth table100%3/3
A and B
A= length $ct == 16B= $counter > 0
ABresult
0X0
100
111
245 . ': final chunk is empty and is not the only chunk'
246 if length($ct) == TAG_SIZE && $counter > 0;
247 }
248  
249 851 my $tag = substr($ct, -TAG_SIZE, TAG_SIZE, '');
250  
251 # The final-chunk flag lives in the nonce, so the only way to learn
252 # which nonce the writer used is to authenticate under it -- the
253 # file's length cannot answer it. A short chunk can only be the final
254 # one. A full chunk is tried as non-final first and, failing that, as
255 # a full-length final chunk. No ciphertext can authenticate under both
256 # nonces, so the second attempt cannot accept a chunk the writer did
257 # not mark that way: it is a second verification, not a second chance.
258 851 ▶ my $is_final = $short_read ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$short_read ? : 49 802 851
259 851 my $plaintext = $class->_open_chunk($payload_key, $counter, $is_final, $ct, $tag);
260 851 ▶ if (! defined($plaintext) && ! $is_final) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $plaintext or $is_final) 15 836 851
Condition100%3/3
defined $plaintext or $is_final
l!l&&r!l&&!r
831515
MC/DC100%2/2
defined $plaintext or $is_final
defined $plaintext $is_final
Truth table100%3/3
A or B
A= defined $plaintextB= $is_final
ABresult
1X1
011
000
261 15 $is_final = 1;
262 15 $plaintext = $class->_open_chunk($payload_key, $counter, $is_final, $ct, $tag);
263 }
264 851 ▶ croak "Payload authentication failed at chunk $counter" unless defined $plaintext;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $plaintext 6 845 851
265  
266 845 print {$ofh} $plaintext;
267  
268 845 ▶ if ($is_final) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_final) 58 787 845
269 # A final chunk ends the payload, so anything still in the file
270 # invalidates it -- trailing garbage as much as another
271 # well-formed chunk.
272 58 ▶ croak 'Payload authentication failed at chunk '.$counter
Branch: 1 branch
BranchTrueFalseTotal
if length $class->paranoid_read($ifh, 1) 8 50 58
273 . ': trailing data after the final chunk'
274 if length($class->paranoid_read($ifh, 1));
275 50 return;
276 }
277  
278 787 $counter++;
279 }
280 }
281  
282  
283 866 ▶sub _open_chunk {
Subroutine _open_chunk: called CC=2 SCAR=6.9
284 866 my ($class, $payload_key, $counter, $is_final, $ciphertext, $tag) = @_;
285  
286 866 my $nonce = $class->_make_nonce($counter, $is_final);
287 866 my $ae = Crypt::AuthEnc::ChaCha20Poly1305->new($payload_key, $nonce);
288  
289 # decrypt_add hands back unauthenticated plaintext, so it is only returned
290 # to the caller once decrypt_done has verified the tag over it.
291 866 my $plaintext = $ae->decrypt_add($ciphertext);
292 866 ▶ return unless $ae->decrypt_done($tag);
Branch: 1 branch
BranchTrueFalseTotal
unless $ae->decrypt_done($tag) 21 845 866
293  
294 845 return $plaintext;
295 }
296  
297 898 ▶sub _make_nonce {
Subroutine _make_nonce: called CC=2 SCAR=6.9
298 898 my ($class, $counter, $is_final) = @_;
299  
300 # 11 bytes counter (big-endian) + 1 byte final flag
301 898 my $nonce = "\x00" x 3; # First 3 bytes zero
302 898 $nonce .= pack('N', ($counter >> 32) & 0xFFFFFFFF); # Next 4 bytes
303 898 $nonce .= pack('N', $counter & 0xFFFFFFFF); # Next 4 bytes
304 898 ▶ $nonce .= pack('C', $is_final ? 1 : 0); # Last byte: final flag
Branch: 1 branch
BranchTrueFalseTotal
$is_final ? : 88 810 898
305  
306 898 return $nonce;
307 }
308  
309 1016 ▶sub paranoid_read {
Subroutine paranoid_read: called CC=7 SCAR=20.4
Pod documented
310 1016 my ($class, $fh, $length) = @_;
311 1016 my $retval = '';
312 1016 my $attempts = READ_ATTEMPTS;
313 1016 ▶ while ($length > 0 && $attempts > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($length > 0 and $attempts > 0) 1094 881 1975
Condition66%2/3
$length > 0 and $attempts > 0
!ll&&!rl&&r
88101094
MC/DC50%1/2
$length > 0 and $attempts > 0
$length > 0 $attempts > 0
Truth table66%2/3
A and B
A= $length > 0B= $attempts > 0
ABresult
0X0
100
111
314 1094 my $buffer = '';
315 1094 my $n_read = read($fh, $buffer, $length);
316 1094 ▶ croak "read(): $!" if ! defined($n_read);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $n_read 0 1094 1094
317 1094 ▶ if ($n_read == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_read == 0) 135 959 1094
318 135 ▶ last if eof($fh); # no more data, we're good
Branch: 1 branch
BranchTrueFalseTotal
if eof $fh 135 0 135
319 0 --$attempts;
320 0 next;
321 }
322  
323 # reset attempts after successful read of *some* data
324 959 $attempts = READ_ATTEMPTS;
325 959 $retval .= $buffer;
326 959 $length -= $n_read;
327 }
328 1016 ▶ return $retval if $attempts > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $attempts > 0 1016 0 1016
329 0 croak "could not get requested data up to the end";
330 }
331  
332  
333  
334 8 1;
335  
336 __END__
« Age.pm ↑ Summary Age/Keys.pm »