Age/Header.pm

filter: Statementstmt 99.2% 134 / 135 Branchbran 95.4% 63 / 66 Conditioncond 89.4% 17 / 19 MC/DCmcdc 72.7% 8 / 11 Subroutinesub 94.1% 16 / 17 Podpod 100% 6 / 6 totaltotal 96.0% 244 / 254 CC 46 SCAR 23.9
CC
46
Cov
97%
parse_from_fh
21.0
unwrap_file_key
10.0
create
8.0
CRAP 10.9
↑ Summary Age.pm »
1 package Crypt::Age::Header;
2 # ABSTRACT: age file header parsing and generation
3 7 our $VERSION = '0.005';
4 7 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 7 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 7 ▶use Crypt::Misc qw(slow_eq);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 7 ▶use Crypt::Age::Primitives;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 7 ▶use Crypt::Age::Stanza;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 7 ▶use Crypt::Age::Stanza::X25519;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 7 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12  
13 7 ▶use constant VERSION_LINE => "age-encryption.org/v1";
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 # The one number in this module that c2sp.org/age does NOT dictate. Its ABNF is
16 # "header = v1-line 1*stanza end" -- one or more, with no upper bound -- and
17 # neither reference implementation imposes one: age 1.2.1 reads a 50000-stanza
18 # header (8.9 s), rage 0.12.1 a 4000-stanza one (5.81 s). See parse_from_fh for
19 # why we deviate and how a caller opts out.
20 7 ▶use constant DEFAULT_MAX_STANZAS => 128;
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 has stanzas => (
23 is => 'ro',
24 0 ▶ default => sub { [] },
Subroutine __ANON__: not called CC=1 SCAR=6.9
25 7 );
26  
27  
28 7 has mac => (
29 is => 'rw',
30 );
31  
32  
33 7 has _bytes => (
34 is => 'lazy',
35 );
36  
37 # The header bytes the MAC is computed over: everything up to and including the
38 # '---' of the footer line, without the space after it and without a trailing
39 # newline. Internal, hence the leading underscore and the matching constructor
40 # key used by parse_from_fh.
41 #
42 # On the read path parse_from_fh passes the literal bytes it read, so the MAC is
43 # verified against what the file actually contained. On the write path there is
44 # nothing to capture and the builder below re-serializes the stanzas instead.
45  
46 48 ▶sub create {
Subroutine create: called CC=8 SCAR=20.8
Pod documented
47 48 my ($class, $file_key, $recipients) = @_;
48  
49 # The shape check the loop below assumed. $#{$recipients} dereferences
50 # whatever arrives, so every wrong shape used to be reported by perl from
51 # inside this module: a plain string as "Can't use string (\"...\") as an
52 # ARRAY ref while \"strict refs\" in use", undef as "Can't use an undefined
53 # value as an ARRAY reference", any other ref as "Not an ARRAY reference".
54 #
55 # The first of those quotes the caller's string, truncated at perl's 32
56 # characters. Here that string is normally a recipient and so public, but
57 # the mistake that puts a bare string in this parameter is the same one
58 # that swaps recipient and identity -- both are plain strings, and the
59 # croak below in the loop exists because that swap happens -- so the value
60 # perl would quote is not reliably a public one. Nothing is interpolated,
61 # for the reason written out at that croak and again in unwrap_file_key.
62 #
63 # The clause after the colon carries the requirement and its reason rather
64 # than a description of what arrived, because one message answers all three
65 # shapes above.
66 48 ▶ croak 'recipients must be an ArrayRef: this method wraps the file key '
Branch: 1 branch
BranchTrueFalseTotal
if ref $recipients ne "ARRAY" 5 43 48
67 .'once per entry, pass [$recipient] rather than $recipient'
68 if ref $recipients ne 'ARRAY';
69  
70 # The spec's header grammar is "header = v1-line 1*stanza end": one or
71 # more stanzas, never zero. An empty list satisfied the check above and
72 # returned a header of a version line and a MAC over it, wrapping the file
73 # key for nobody -- so the file it starts can never be decrypted, by the
74 # caller least of all, since the file key is generated per file and kept
75 # nowhere else. Measured on a file built from such a header: rage 0.12.1
76 # refuses it as "Unknown age format" because the grammar is not satisfied,
77 # age 1.2.1 parses it and fails with "no identity matched any of the
78 # recipients". Both are right, and both say so once the plaintext is gone.
79 #
80 # Same skeleton as the check above, carrying this method's own reason.
81 43 ▶ croak 'recipients must not be empty: this method wraps the file key once '
Branch: 1 branch
BranchTrueFalseTotal
unless @$recipients 2 41 43
82 .'per entry, so a header with no stanzas can never be unwrapped, '
83 .'pass at least one recipient'
84 unless @$recipients;
85  
86 41 my @stanzas;
87 41 for my $i (0 .. $#{$recipients}) {
88 50 my $recipient = $recipients->[$i];
89 # The prefix test is case-insensitive because BIP-173 makes the
90 # all-uppercase form the same encoding of the same string, and
91 # Keys::decode_public_key already accepts it. A mixed-case recipient
92 # still dies: it reaches decode_public_key and is rejected there by
93 # bech32_decode's mixed-case guard.
94 #
95 # Definedness is tested first so that an undef entry never reaches this
96 # pattern match, nor the one in the hint below. Both would emit a "Use
97 # of uninitialized value" warning -- noise from library code, arriving
98 # ahead of the croak that actually explains the problem. The entry is
99 # rejected either way; undef is not an age1 recipient.
100 50 ▶ if (defined $recipient && $recipient =~ /^age1/i) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $recipient and $recipient =~ /^age1/i) { } 43 7 50
Condition100%3/3
defined $recipient and $recipient =~ /^age1/i
!ll&&!rl&&r
3443
MC/DC100%2/2
defined $recipient and $recipient =~ /^age1/i
defined $recipient $recipient =~ /^age1/i
Truth table100%3/3
A and B
A= defined $recipientB= $recipient =~ /^age1/i
ABresult
0X0
100
111
101 43 push @stanzas, Crypt::Age::Stanza::X25519->wrap($file_key, $recipient);
102 } else {
103 # Never interpolate $recipient. The likeliest way to reach this
104 # croak is a caller swapping recipient and identity -- both are
105 # plain strings -- and the exception travels into whatever log
106 # catches it, so echoing the string puts a whole secret key there.
107 # The message is therefore built from literals plus the array
108 # index, which locates the bad entry in the caller's own array and
109 # copies no byte of it. The identity hint is a classification
110 # against a public format prefix, not a quotation of the value: it
111 # carries one bit about a constant that every age tutorial prints,
112 # and structurally cannot expose key material. age(1) and rage(1)
113 # do echo the string, but there it was already a command-line
114 # argument; a library error message is not.
115 #
116 # undef gets no message of its own: ", got undef" fills the same
117 # "what arrived instead" slot the identity hint already occupies,
118 # so the skeleton and the prefix stay one shape, and one croak
119 # keeps the variants from drifting apart. It is a classification
120 # too -- there is nothing to interpolate in the first place.
121 7 ▶ my $hint = !defined $recipient ? ', got undef'
Branch: 2 branches
BranchTrueFalseTotal
!defined($recipient) ? : 3 4 7
$recipient =~ /^AGE-SECRET-KEY-1/i ? : 2 2 4
122 : $recipient =~ /^AGE-SECRET-KEY-1/i
123 ? ', got an AGE-SECRET-KEY-1 identity' : '';
124 7 croak 'Unsupported recipient format at index '.$i
125 .': expected an age1 recipient'.$hint;
126 }
127 }
128  
129 33 my $header = $class->new(stanzas => \@stanzas);
130  
131 # Compute and set MAC
132 33 my $header_bytes = $header->_bytes;
133 33 my $mac = Crypt::Age::Primitives->compute_header_mac($file_key, $header_bytes);
134 33 $header->mac($mac);
135  
136 33 return $header;
137 }
138  
139  
140 24 ▶sub to_string {
Subroutine to_string: called CC=2 SCAR=6.9
Pod documented
141 24 my ($self) = @_;
142  
143 24 my @lines = (VERSION_LINE);
144  
145 24 for my $stanza (@{$self->stanzas}) {
146 25 push @lines, $stanza->to_string;
147 }
148  
149 # MAC line
150 24 my $mac_b64 = Crypt::Age::Stanza::encode_base64_no_padding($self->mac);
151 24 push @lines, "--- $mac_b64";
152  
153 24 return join("\n", @lines) . "\n";
154 }
155  
156  
157 34 ▶sub _build__bytes {
Subroutine _build__bytes: called CC=2 SCAR=6.9
158 34 my ($self) = @_;
159  
160 34 my @lines = (VERSION_LINE);
161  
162 34 for my $stanza (@{$self->stanzas}) {
163 37 push @lines, $stanza->to_string;
164 }
165  
166 # For MAC, we include everything up to but not including the MAC itself
167 # The footer line is "---" (without the MAC)
168 34 push @lines, "---";
169  
170 34 return join("\n", @lines);
171 }
172  
173 165 ▶sub parse_from_fh {
Subroutine parse_from_fh: called CC=21 SCAR=30.4
Pod documented
174 165 my ($class, $fh, @opt) = @_;
175  
176 # Checked before the hash assignment below, which would otherwise warn
177 # "Odd number of elements in hash assignment" out of this file for a
178 # mistake made one frame up -- the same reasoning as the shape checks in
179 # parse. The mis-call worth catching is parse_from_fh($fh, 300): the limit
180 # passed positionally is silently not a limit, so the default one below
181 # still refuses the caller's 300-recipient file and tells them to pass
182 # max_stanzas, which is exactly what they thought they had done. Nothing is
183 # interpolated: a caller who got the arguments wrong here may have put an
184 # identity in this position.
185 165 ▶ croak 'parse_from_fh takes a filehandle followed by named options: '
Branch: 1 branch
BranchTrueFalseTotal
if @opt % 2 1 164 165
186 .'pass max_stanzas => $n rather than a bare value'
187 if @opt % 2;
188 164 my %opt = @opt;
189  
190 # Our own denial-of-service limit, and the only constant here that is not
191 # the format's -- see DEFAULT_MAX_STANZAS above. It exists because the cost
192 # of a header is paid before any of it can be authenticated: the header MAC
193 # key is derived from the file key, which does not exist until a stanza has
194 # been unwrapped, so unwrap_file_key has to try every identity against every
195 # stanza -- an X25519 scalar multiplication, an HKDF and a ChaCha20-Poly1305
196 # open each -- on a header nobody has vouched for. Measured on 0.003, ~3.9
197 # ms per stanza per identity: 98 attacker-controlled bytes buy a scalar
198 # multiplication, 382 KB buy 15.7 s (CVE-2026-85783).
199 #
200 # 128 is a maintainer decision, not a measurement of the format. What the
201 # measurements say is where the room is: the upstream test kit tops out at
202 # three stanzas and real files carry a handful, but `age -R` writes a
203 # 300-recipient file without complaint and a real 301-recipient file from
204 # age 1.2.1 decrypts here correctly in 1.17 s. So this cap deliberately
205 # rejects files a reference implementation produces, which is why it MUST
206 # stay overridable and why the croak below names max_stanzas: a caller who
207 # legitimately has such a file needs to be told how to read it.
208 #
209 # A missing max_stanzas means the default. An explicit undef or 0 is an
210 # error rather than "no limit": 0 read literally means "allow zero stanzas",
211 # which the grammar forbids anyway, so taking it as "allow unbounded" would
212 # invert the most natural reading of the value -- and a security limit that
213 # a falsy value silently switches off is one that disappears exactly when a
214 # caller computes it and the computation goes wrong. A caller who wants
215 # age's unbounded behaviour asks for a number large enough to say so.
216 my $max_stanzas = exists $opt{max_stanzas} ? $opt{max_stanzas}
217 164 ▶ : DEFAULT_MAX_STANZAS;
Branch: 1 branch
BranchTrueFalseTotal
exists $opt{'max_stanzas'} ? : 9 155 164
218 164 ▶ croak 'max_stanzas must be a positive integer: it caps how many recipient '
Branch: 1 branch
BranchTrueFalseTotal
unless defined $max_stanzas and $max_stanzas =~ /\A[0-9]+\z/ and $max_stanzas > 0 4 160 164
Condition100%6/6
defined $max_stanzas and $max_stanzas =~ /\A[0-9]+\z/ and $max_stanzas > 0
!ll&&!rl&&r
31160
defined $max_stanzas and $max_stanzas =~ /\A[0-9]+\z/
!ll&&!rl&&r
12161
MC/DC100%3/3
defined $max_stanzas and $max_stanzas =~ /\A[0-9]+\z/ and $max_stanzas > 0
defined $max_stanzas $max_stanzas =~ /\A[0-9]+\z/ $max_stanzas > 0
Truth table100%4/4
A and B and C
A= defined $max_stanzasB= $max_stanzas =~ /\A[0-9]+\z/C= $max_stanzas > 0
ABCresult
0XX0
10X0
1100
1111
219 .'stanzas this header may carry, and 0 or undef would be a header no '
220 .'identity could ever unwrap, pass a number large enough for the files '
221 .'you read'
222 unless defined $max_stanzas
223 && $max_stanzas =~ m{\A[0-9]+\z}
224 && $max_stanzas > 0;
225  
226 # make sure to read the whole thing in the correct way
227 160 ▶ binmode($fh, ':raw') or croak "binmode: $!";
Branch: 1 branch
BranchTrueFalseTotal
binmode $fh, ":raw" or croak("binmode: $!") 160 0 160
228 160 local $/ = "\x{0a}";
229  
230 # $header will eventually contain the whole header, for MAC validation.
231 # We start from the first line.
232 160 my $bytes = <$fh>;
233  
234 # readline gives undef at end of input, and arriving here with nothing to
235 # read is a legitimate "this is not an age file": an empty $data, or an
236 # offset already at its end. That is exactly what the version croak below
237 # reports -- but chomp and eq on undef warned out of this file first, with
238 # line numbers from here for a mistake made one frame up. An absent version
239 # line is not the expected literal either, so carry it into the same check
240 # the empty first line takes rather than warning on the way to it.
241 160 ▶ $bytes = '' unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 2 158 160
242  
243 # Check version
244 160 chomp(my $version_line = $bytes); # remove \x{0a}
245 # Never interpolate $version_line: reaching this croak means the input is
246 # not an age file, so the line is whatever the caller handed over -- a line
247 # of plaintext, or the entire input when it contains no newline at all.
248 # The check is against a single literal, so naming the expected value says
249 # everything the caller needs without quoting theirs.
250 160 ▶ croak 'Invalid age version: expected the literal '.VERSION_LINE
Branch: 1 branch
BranchTrueFalseTotal
unless $version_line eq "age-encryption.org/v1" 5 155 160
251 .' version line' unless $version_line eq VERSION_LINE;
252  
253 # read the rest of the header
254 155 my (@stanzas, $mac);
255 155 my $n = 0;
256 # A lexical line, never a bare while (<$fh>): that form assigns to the
257 # caller's global $_, and a caller decrypting inside for (@files) has $_
258 # aliased to its own array element -- or to a read-only literal, which
259 # turns the assignment into a die (k49).
260 155 ▶ while (defined(my $line = <$fh>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $line = readline $fh)) 2084 1 2085
261 2084 ▶ if (my ($mac64) = $line =~ m{\A ---\x{20} (\S{43}) \x{0a} \z}mxs) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($mac64) = $line =~ /\A ---\x{20} (\S{43}) \x{0a} \z/msx) 106 1978 2084
262 106 $bytes .= '---';
263 106 $mac = Crypt::Age::Stanza::decode_base64_no_padding($mac64);
264 105 last;
265 }
266 1978 ++$n;
267 # Here rather than on @stanzas after the loop, and before this stanza's
268 # arg line is even matched: the point of the limit is that the work is
269 # never done. Refusing after the fact would still have read the whole
270 # 382 KB header into $bytes and built every stanza object; refusing here
271 # stops at the first line of stanza max+1, so neither the body nor any
272 # of the scalar multiplications that follow it are ever paid for.
273 #
274 # Only $max_stanzas is interpolated, and it is the caller's own value.
275 # $n is not: it is always $max_stanzas + 1 here, so it says nothing the
276 # message does not, and the count comes from the header, which is
277 # attacker-controlled input that this module quotes nowhere.
278 1978 ▶ croak 'age header carries more than '.$max_stanzas.' recipient '
Branch: 1 branch
BranchTrueFalseTotal
if $n > $max_stanzas 8 1970 1978
279 .'stanzas: every stanza costs an X25519 scalar multiplication per '
280 .'identity before any of the header can be authenticated, so an '
281 .'unbounded header is a denial of service, this limit comes from '
282 .'this implementation and not from the age format, raise it with '
283 .'max_stanzas if the file is a legitimate one'
284 if $n > $max_stanzas;
285 # c2sp.org/age, "ABNF definition of file header":
286 #
287 # arg-line = "-> " argument *(SP argument) LF
288 # argument = 1*VCHAR
289 #
290 # VCHAR is RFC 5234's core rule %x21-7E, the printable ASCII
291 # characters, so every argument is one or more of those and an empty
292 # argument (two spaces in a row, or a trailing space) is not an
293 # argument at all. The ABNF has no separate rule for the stanza type:
294 # the type is simply the first argument and carries exactly the same
295 # character set.
296 #
297 # This is why the check lives here rather than in a stanza class. The
298 # character set is a property of the header's grammar, not of any one
299 # recipient type, so a byte outside it makes the WHOLE header invalid
300 # -- including in a stanza whose type we do not recognize and would
301 # otherwise be required to ignore. Hence: validate before the type
302 # dispatch below. (\S used to stand in for VCHAR here and let every
303 # non-whitespace byte through, which is what the test kit's
304 # stanza_invalid_character vector caught.)
305 1970 ▶ my ($ta) = $line =~ m{\A ->\x{20} ([\x21-\x7e]+ (?:\x{20}[\x21-\x7e]+)*) \x{0a} \z}mxs
Branch: 1 branch
BranchTrueFalseTotal
my($ta) = $line =~ /\A ->\x{20} ([\x21-\x7e]+ (?:\x{20}[\x21-\x7e]+)*) \x{0a} \z/msx or croak("Invalid age stanza #$n start line: expected '-> ' followed" . ' by space-separated arguments of printable ASCII (0x21-0x7e)') 1954 16 1970
306 or croak "Invalid age stanza #$n start line: expected '-> ' followed"
307 . " by space-separated arguments of printable ASCII (0x21-0x7e)";
308  
309 1954 $bytes .= $line;
310  
311 # Read stanza's body lines
312 1954 my $body_b64 = '';
313 1954 my $body_completed = 0;
314 1954 ▶ while (defined(my $body_line = <$fh>)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $body_line = readline $fh)) 1973 5 1978
315 1973 $bytes .= $body_line;
316 1973 chomp $body_line;
317 1973 my $len = length($body_line);
318 1973 ▶ croak "Invalid age stanza #$n body" if $len > 64;
Branch: 1 branch
BranchTrueFalseTotal
if $len > 64 1 1972 1973
319 1972 $body_b64 .= $body_line;
320 1972 ▶ if ($len < 64) {
Branch: 1 branch
BranchTrueFalseTotal
if ($len < 64) 1948 24 1972
321 1948 $body_completed = 1;
322 1948 last;
323 }
324 }
325 # "The body MUST end with a line shorter than 64 characters, which
326 # MAY be empty."
327 1953 ▶ croak "Invalid age stanza #$n body" unless $body_completed;
Branch: 1 branch
BranchTrueFalseTotal
unless $body_completed 5 1948 1953
328  
329 1948 my ($type, @args) = split m{\x{20}}mxs, $ta;
330 1948 my $body = Crypt::Age::Stanza::decode_base64_no_padding($body_b64);
331  
332 1942 my $stanza_class = 'Crypt::Age::Stanza';
333 1942 ▶ if ($type eq 'X25519') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "X25519") 1929 13 1942
334 1929 $stanza_class = 'Crypt::Age::Stanza::X25519';
335 }
336  
337 1942 push @stanzas, $stanza_class->new(
338 type => $type,
339 args => \@args,
340 body => $body,
341 );
342 }
343 106 ▶ croak "Invalid age file, no valid header MAC line" unless length($mac // '');
Branch: 1 branch
BranchTrueFalseTotal
unless length($mac // "") 1 105 106
Condition100%2/2
$mac // ""
l!l
1051
MC/DC100%1/1
$mac // ""
$mac
Truth table100%2/2
A
A= $mac
Aresult
11
00
344  
345 # c2sp.org/age, "ABNF definition of file header":
346 #
347 # header = v1-line 1*stanza end
348 #
349 # One or more stanzas, never zero, and the prose above that grammar says
350 # it again in words: "followed by one or more recipient stanzas". A
351 # version line followed straight by the MAC footer passed every check
352 # above and parsed into a header with an empty stanza list -- one whose
353 # MAC even verifies, because it is a well-formed MAC over a header the
354 # grammar forbids. Nothing here refused it, so such a file travelled on to
355 # unwrap_file_key and died there with "No matching identity found", naming
356 # the caller's keys as the cause of a file that is addressed to nobody at
357 # all.
358 #
359 # This is an interop difference, not only a tidiness one, which is why it
360 # is refused rather than tolerated. Measured on such a file: rage 0.12.1
361 # rejects it at parse time as "Unknown age format", age 1.2.1 parses it
362 # and reports "no identity matched any of the recipients". This
363 # implementation was the most permissive of the three; it now refuses
364 # where rage does, at the point the grammar is actually violated.
365 #
366 # After the MAC check on purpose. A truncated header -- a version line and
367 # nothing after it -- carries no stanzas either, but its cause is that the
368 # handle ran out, which the croak above already names; only a header that
369 # is complete and stanza-less reaches this line.
370 #
371 # #36 put the same clause on the write side, in create. Nothing is
372 # interpolated here: reaching this croak says nothing about the caller's
373 # arguments, and the header it describes is the file's, not theirs.
374 105 ▶ croak 'age header must carry at least one recipient stanza: the file key '
Branch: 1 branch
BranchTrueFalseTotal
unless @stanzas 2 103 105
375 .'is wrapped once per stanza, so a header with none can never be '
376 .'unwrapped by anyone, decrypt a file encrypted to at least one '
377 .'recipient'
378 unless @stanzas;
379  
380 103 return $class->new(
381 stanzas => \@stanzas,
382 _bytes => $bytes,
383 mac => $mac,
384 );
385 }
386  
387  
388 42 ▶sub parse {
Subroutine parse: called CC=7 SCAR=19.5
Pod documented
389 42 my ($class, $data_ref, $offset_ref, @opt) = @_;
390  
391 # The type test perl's open does not do for us. Everything below assumes a
392 # ScalarRef -- the scan dereferences it, and the open maps it into an
393 # in-memory handle -- but open silently means something else for every
394 # other shape, and the wrong meanings are worse than an error: a plain
395 # string is a *filename*, so a caller who drops the backslash reads the
396 # file that string names, measured here as parse returning a header built
397 # from that file and advancing the caller's $offset past it. A blessed
398 # SCALAR ref stringifies into a filename the same way, a REF reads back the
399 # address of the inner ref, and undef warned out of this module about a
400 # mistake made one frame up. So: ref eq 'SCALAR', the only shape that maps
401 # to the bytes the caller meant -- open takes a REF too, it just reads
402 # something else -- checked before anything touches the argument.
403 #
404 # Never interpolate $data_ref. This is the one path where perl's own
405 # message would do it for us -- the string it would quote is either the
406 # ciphertext the caller meant to pass or a filesystem path.
407 42 ▶ croak 'data must be a ScalarRef: this method opens it, and a plain string '
Branch: 1 branch
BranchTrueFalseTotal
if ref $data_ref ne "SCALAR" 4 38 42
408 .'is a filename, pass \$data rather than $data'
409 if ref $data_ref ne 'SCALAR';
410  
411 # The same test for the second parameter, and here for the opposite
412 # reason: nothing is read through this ref -- the new offset is written
413 # back out through it, which is how the caller learns where the payload
414 # starts, and only a ref carries a value back out of a call. Both shape
415 # checks sit before the scan below on purpose. They decide whether this
416 # call can succeed at all, while the scan reads the caller's data, so a
417 # complaint about that data is worth producing only once the call itself
418 # is well formed -- and a caller who passed the two arguments the other
419 # way round is exactly such a call, wrong in both of them.
420 #
421 # Never interpolate $offset_ref either, for the same reason as above with
422 # the arguments swapped: perl's own "Can't use string (...) as a SCALAR
423 # ref" quoted the ciphertext that lands here, and blamed a line in this
424 # file for a mistake made one frame up.
425 38 ▶ croak 'offset must be a ScalarRef: this method writes the new offset back '
Branch: 1 branch
BranchTrueFalseTotal
if ref $offset_ref ne "SCALAR" 4 34 38
426 .'through it, pass \$offset rather than $offset'
427 if ref $offset_ref ne 'SCALAR';
428  
429 # And now the content, before anything dereferences it for real. A ref to
430 # an undefined scalar passes both shape checks above -- it genuinely is a
431 # ScalarRef -- and then reached the scan below, the open under it and the
432 # readline in parse_from_fh, warning ten times about uninitialized values
433 # with line numbers from this file for a mistake made one frame up.
434 #
435 # This gets a croak of its own rather than being normalized to the empty
436 # string and left to the version-line croak in parse_from_fh, because the
437 # two are different mistakes with different fixes: "there is nothing behind
438 # the ref you handed me" is a caller error, while "these bytes are not an
439 # age file" is a statement about data that really arrived. Folding the
440 # first into the second would name a cause the caller does not have. Empty
441 # bytes stay the second kind and still get the version-line croak, which
442 # no longer warns on its way there either -- see parse_from_fh.
443 #
444 # Nothing interpolated here either, for the reason given above: there is no
445 # value to quote in this case, and the message must read the same when the
446 # check moves or the caller's scalar turns out to hold ciphertext.
447 34 ▶ croak 'data must refer to a defined scalar: this method reads the age '
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$data_ref 1 33 34
448 .'file out of it, assign the bytes before passing \$data'
449 unless defined $$data_ref;
450  
451 # Perl's own test for the in-memory open below, hoisted so the failure
452 # names its cause instead of arriving as "cannot read". The reasoning is
453 # written out over the same check in Crypt::Age::encrypt; the delta here is
454 # the mechanism. That one may downgrade because it holds a copy off @_, and
455 # "our own copy" is the whole safety argument -- it does not carry when the
456 # parameter is the caller's scalar behind a ref, so this reads instead of
457 # converting. The scan is free on the unflagged byte string this is
458 # normally given (200 passes over 16 MiB: 0.00s CPU, against 11.4s on a
459 # flagged one), and nothing internal repeats it -- lib/ reaches the parser
460 # through parse_from_fh, so parse has no caller here. It buys less than it
461 # looks: on success perl's open downgrades the referenced scalar in place
462 # anyway, so what is ours is only that a rejected $data is left as it was.
463 # Dereferencing needs no guard of its own: the check above settled the type.
464 33 ▶ croak 'data must be a byte string: it holds a code point above 0xFF, '
Branch: 1 branch
BranchTrueFalseTotal
if $$data_ref =~ /[^\x00-\xff]/ 1 32 33
465 .'read it with :raw rather than decoding it'
466 if $$data_ref =~ /[^\x00-\xff]/;
467  
468 32 ▶ open my $fh, '<:raw', $data_ref or croak "Invalid age input: cannot read";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $data_ref or croak("Invalid age input: cannot read") 32 0 32
469 32 ▶ seek($fh, $$offset_ref // 0, 0);
Condition50%1/2
$$offset_ref // 0
l!l
320
MC/DC0%0/1
$$offset_ref // 0
$$offset_ref
Truth table50%1/2
A
A= $$offset_ref
Aresult
11
00
470 # Named options travel on unread and unvalidated: max_stanzas is
471 # parse_from_fh's, and duplicating its check here would be a second place
472 # to keep the message and the default in step. An odd @opt is caught there
473 # too, before it can warn.
474 32 my $retval = $class->parse_from_fh($fh, @opt);
475 18 $$offset_ref = tell($fh);
476 18 return $retval;
477 }
478  
479  
480 93 ▶sub verify_mac {
Subroutine verify_mac: called CC=2 SCAR=6.9
Pod documented
481 93 my ($self, $file_key) = @_;
482  
483 93 my $header_bytes = $self->_bytes;
484 93 my $expected_mac = Crypt::Age::Primitives->compute_header_mac($file_key, $header_bytes);
485  
486 # slow_eq is CryptX's XS wrapper around libtomcrypt's mem_neq: for two
487 # equal-length strings it reads both in full instead of returning at the
488 # first differing byte. It does not hide the length -- a length mismatch is
489 # reported as unequal, which is fine here since the MAC length is fixed by
490 # the format and not secret. undef compares as unequal rather than dying.
491 93 ▶ return slow_eq($self->mac, $expected_mac) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
slow_eq($self->mac, $expected_mac) ? : 85 8 93
492 }
493  
494  
495 94 ▶sub unwrap_file_key {
Subroutine unwrap_file_key: called CC=10 SCAR=23.1
Pod documented
496 94 my ($self, $identities) = @_;
497  
498 # The same shape check as in create, and the one place in this distribution
499 # where omitting it leaked a secret. @$identities dereferences whatever
500 # arrives, and for a bare string perl reports "Can't use string (\"...\")
501 # as an ARRAY ref while \"strict refs\" in use" with the first 32
502 # characters of that string quoted in it. The string in this parameter is
503 # an identity, so those 32 characters are secret key material, written into
504 # an exception by this module -- and an exception travels into logs, bug
505 # reports and terminal scrollback that the caller cannot redact after the
506 # fact. A single identity passed without the brackets is the likeliest way
507 # to get here at all, since one identity does not look like a list.
508 #
509 # undef and other refs reach the same dereference and are answered by the
510 # same message; as in create it carries the requirement and its reason, and
511 # quotes nothing.
512 94 ▶ croak 'identities must be an ArrayRef: this method tries each entry in '
Branch: 1 branch
BranchTrueFalseTotal
if ref $identities ne "ARRAY" 4 90 94
513 .'turn, pass [$identity] rather than $identity'
514 if ref $identities ne 'ARRAY';
515  
516 90 for my $identity (@$identities) {
517 # Skipped before the prefix test below, which would otherwise emit a
518 # "Use of uninitialized value" warning once per X25519 stanza. Skipping
519 # is exactly what already happens to any string that is not an
520 # AGE-SECRET-KEY-1: unlike a recipient in create, an identity that does
521 # not match is not an error, it is simply not the one. So this drops
522 # the warnings and changes no outcome -- a list whose entries all fail
523 # to unwrap still ends at the croak below.
524 91 ▶ next unless defined $identity;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $identity 3 88 91
525  
526 # Hoisted out of the stanza loop below, where it used to sit in the
527 # same condition as the isa test: it asks about the identity only, so
528 # asking it once per identity rather than once per stanza changes no
529 # outcome. An identity that is not an AGE-SECRET-KEY-1 was already
530 # skipped against every stanza; it is now skipped once.
531 88 ▶ next unless $identity =~ /^AGE-SECRET-KEY-1/i;
Branch: 1 branch
BranchTrueFalseTotal
unless $identity =~ /^AGE-SECRET-KEY-1/i 0 88 88
532  
533 # Built at the first X25519 stanza this identity is tried against, and
534 # then reused for the rest of them. The Bech32 decode and the scalar
535 # multiplication that recovers the identity's own public key depend on
536 # the identity and not on the stanza -- on a header with many stanzas
537 # that was the same work done again per stanza for no reason. Measured
538 # over 500 stanzas and one identity: 3.95 ms per stanza before, 2.71 ms
539 # after, so ~31% of the cost went (the CPANSec report for
540 # CVE-2026-85783 estimates ~36%). The rest is the shared-secret scalar
541 # multiplication, which is per stanza by construction.
542 #
543 # Lazily, not before the loop, because decode_secret_key dies on an
544 # invalid identity: deriving eagerly would move that death earlier, to
545 # a header whose stanzas are all of some other type, where today the
546 # identity is never decoded at all and the call ends in "No matching
547 # identity found". The // keeps the failure exactly where it was.
548 88 my $identity_keys;
549 88 for my $stanza (@{$self->stanzas}) {
550 607 ▶ next unless $stanza->isa('Crypt::Age::Stanza::X25519');
Branch: 1 branch
BranchTrueFalseTotal
unless $stanza->isa("Crypt::Age::Stanza::X25519") 4 603 607
551 603 ▶ $identity_keys //= Crypt::Age::Stanza::X25519->identity_keys($identity);
Condition66%2/3
$identity_keys //= "Crypt::Age::Stanza::X25519"->identity_keys($identity)
l!l&&r!l&&!r
516870
MC/DC0%0/2
$identity_keys //= "Crypt::Age::Stanza::X25519"->identity_keys($identity)
$identity_keys "Crypt::Age::Stanza::X25519"->identity_keys($identity)
Truth table66%2/3
A //= B
A= $identity_keysB= "Crypt::Age::Stanza::X25519"->identity_keys($identity)
ABresult
1X1
011
000
552 603 my $file_key = $stanza->unwrap($identity, $identity_keys);
553 601 ▶ if (defined $file_key && $self->verify_mac($file_key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $file_key and $self->verify_mac($file_key)) 81 520 601
Condition100%3/3
defined $file_key and $self->verify_mac($file_key)
!ll&&!rl&&r
519181
MC/DC100%2/2
defined $file_key and $self->verify_mac($file_key)
defined $file_key $self->verify_mac($file_key)
Truth table100%3/3
A and B
A= defined $file_keyB= $self->verify_mac($file_key)
ABresult
0X0
100
111
554 81 return $file_key;
555 }
556 }
557 }
558  
559 7 croak "No matching identity found";
560 }
561  
562  
563  
564 7 1;
565  
566 __END__
↑ Summary Age.pm »