blib/lib/Web/Authn/Parse.pm untested

filter: Statementstmt 0.0% 0 / 306 Branchbran 0.0% 0 / 154 Conditioncond 0.0% 0 / 127 MC/DCmcdc 0.0% 0 / 76 Subroutinesub 0.0% 0 / 40 Podpod 0.0% 0 / 22 totaltotal 0.0% 0 / 725 CC 78 SCAR 42.5
CC
78
Cov
0%
options_to_json_dict
240.0
parse_authenticator_data
156.0
parse_attestation_statement
90.0
CRAP 69.8
1 ##----------------------------------------------------------------------------
2 ## WebAuthn - ~/lib/Web/Authn/Parse.pm
3 ## Version v0.2.0
4 ## Copyright(c) 2026 DEGUEST Pte. Ltd.
5 ## Author: Jacques Deguest <jack@deguest.jp>
6 ## Created 2026/09/09
7 ## Modified 2026/09/12
8 ## All rights reserved
9 ##
10 ## This program is free software; you can redistribute it and/or modify it
11 ## under the same terms as Perl itself.
12 ##----------------------------------------------------------------------------
13 package Web::Authn::Parse;
14 BEGIN
15 {
16 use v5.16.0;
17 use strict;
18 use warnings;
19 warnings::register_categories( 'Web::Authn' );
20 use vars qw( $VERSION $JSON_CLASS );
21 use overload ();
22 use Bytes::Random::Secure ();
23 use Digest::SHA qw( sha256 );
24 use MIME::Base64 qw( encode_base64 decode_base64 );
25 use Scalar::Util;
26 use Web::Authn::CBOR;
27 use Web::Authn::COSE;
28 use Web::Authn::Exception;
29 # JSON backend detection: prefer Cpanel::JSON::XS (fastest, most rigorous), fall back
30 # to JSON::XS, then JSON::PP (core since Perl 5.14).
31 our $JSON_CLASS;
32 local $@;
33 if( eval{ require Cpanel::JSON::XS; 1 } )
34 {
35 $JSON_CLASS = 'Cpanel::JSON::XS';
36 }
37 elsif( eval{ require JSON::XS; 1 } )
38 {
39 $JSON_CLASS = 'JSON::XS';
40 }
41 else
42 {
43 require JSON::PP;
44 $JSON_CLASS = 'JSON::PP';
45 }
46 our $VERSION = 'v0.2.0';
47 };
48  
49 use strict;
50 use warnings;
51  
52 sub aaguid_to_string
53 {
54 my $b = maybe_bytes( shift( @_ ) );
55 unless( length( $b ) == 16 )
56 {
57 Web::Authn::Exception::InvalidStructure->throw( 'AAGUID must be 16 bytes' );
58 }
59 my $h = unpack( 'H*', $b );
60 return( sprintf( '%s-%s-%s-%s-%s',
61 substr( $h, 0, 8 ), substr( $h, 8, 4 ), substr( $h, 12, 4 ),
62 substr( $h, 16, 4 ), substr( $h, 20, 12 )
63 ) );
64 }
65  
66 sub b64u_decode
67 {
68 my $s = _plain( shift( @_ ) );
69 unless( defined( $s ) )
70 {
71 Web::Authn::Exception::InvalidStructure->throw('missing base64url value');
72 }
73 $s =~ s/\s+//g;
74 $s =~ tr{-_}{+/};
75 my $pad = ( 4 - length( $s ) % 4 ) % 4;
76 $s .= '=' x $pad;
77 my $bin = decode_base64( $s );
78 defined( $bin ) or Web::Authn::Exception::InvalidStructure->throw( 'invalid base64url' );
79 return( $bin );
80 }
81  
82 sub b64u_encode
83 {
84 my $bin = maybe_bytes( shift( @_ ) );
85 my $s = encode_base64( $bin, '' );
86 $s =~ tr{+/}{-_};
87 $s =~ s/=+\z//;
88 return( $s );
89 }
90  
91 sub decode_credential_public_key
92 {
93 my $key = shift( @_ );
94 $key = maybe_bytes( $key );
95 if( length( $key ) &&
96 unpack( 'C', substr( $key, 0, 1 ) ) == 0x04 && length( $key ) == 65 )
97 {
98 return({
99 kty => Web::Authn::COSE::KTY_EC2,
100 alg => Web::Authn::COSE::ECDSA_SHA_256,
101 crv => Web::Authn::COSE::CRV_P256,
102 'x' => substr( $key, 1, 32 ),
103 'y' => substr( $key, 33, 32 ),
104 });
105 }
106 my $decoded = Web::Authn::CBOR::decode( $key );
107 unless( ref( $decoded ) eq 'HASH' )
108 {
109 Web::Authn::Exception::InvalidStructure->throw( 'COSE key is not a map' );
110 }
111 my $kty = $decoded->{ Web::Authn::COSE::KEY_KTY() };
112 my $alg = $decoded->{ Web::Authn::COSE::KEY_ALG() };
113 unless( defined( $kty ) && defined( $alg ) )
114 {
115 Web::Authn::Exception::InvalidStructure->throw( 'Credential public key missing kty/alg' );
116 }
117 if( $kty == Web::Authn::COSE::KTY_OKP )
118 {
119 return({
120 kty => $kty, alg => $alg,
121 crv => $decoded->{ Web::Authn::COSE::KEY_CRV() },
122 x => $decoded->{ Web::Authn::COSE::KEY_X() },
123 });
124 }
125 if( $kty == Web::Authn::COSE::KTY_EC2 )
126 {
127 return({
128 kty => $kty,
129 alg => $alg,
130 crv => $decoded->{ Web::Authn::COSE::KEY_CRV() },
131 'x' => $decoded->{ Web::Authn::COSE::KEY_X() },
132 'y' => $decoded->{ Web::Authn::COSE::KEY_Y() },
133 });
134 }
135 if( $kty == Web::Authn::COSE::KTY_RSA )
136 {
137 return({
138 kty => $kty,
139 alg => $alg,
140 n => $decoded->{ Web::Authn::COSE::KEY_N() },
141 e => $decoded->{ Web::Authn::COSE::KEY_E() },
142 });
143 }
144 if( $kty == Web::Authn::COSE::KTY_ML_DSA )
145 {
146 return({
147 kty => $kty,
148 alg => $alg,
149 pub => $decoded->{ Web::Authn::COSE::KEY_PUB() },
150 });
151 }
152 Web::Authn::Exception::UnsupportedAlgorithm->throw( qq{Unsupported credential public key type "$kty"} );
153 }
154  
155 sub generate_challenge
156 {
157 my $len = _plain( shift( @_ ) );
158 $len ||= 64;
159 return( _random( $len ) );
160 }
161  
162 sub generate_user_handle { return( _random(64) ); }
163  
164 sub maybe_bytes
165 {
166 my $v = shift( @_ );
167 return( $v ) unless( defined( $v ) );
168 $v = _plain( $v );
169 return( $v ) if( !ref( $v ) );
170 return( $$v ) if( ( Scalar::Util::reftype( $v ) || '' ) eq 'SCALAR' );
171 Web::Authn::Exception::InvalidStructure->throw( 'expected bytes' );
172 }
173  
174 sub options_to_json
175 {
176 my $opt = shift( @_ );
177 return( $JSON_CLASS->new->utf8->canonical->encode( options_to_json_dict( $opt ) ) );
178 }
179  
180 sub options_to_json_dict
181 {
182 my $opt = shift( @_ );
183 my %out;
184 if( $opt->{user} )
185 {
186 # registration
187 $out{rp} = { name => _plain( $opt->{rp}->{name} ), id => _plain( $opt->{rp}->{id} ) };
188 $out{user} =
189 {
190 id => b64u_encode( $opt->{user}->{id} ),
191 name => _plain( $opt->{user}->{name} ),
192 displayName => _plain( $opt->{user}->{display_name} // $opt->{user}->{displayName} // $opt->{user}->{name} ),
193 };
194 $out{challenge} = b64u_encode( $opt->{challenge} );
195 $out{pubKeyCredParams} = [map{
196 { type => $_->{type} || 'public-key', alg => 0 + $_->{alg} }
197 } @{$opt->{pub_key_cred_params} || $opt->{pubKeyCredParams} || []}];
198 $out{timeout} = 0 + _plain( $opt->{timeout} ) if( defined( $opt->{timeout} ) );
199 if( $opt->{exclude_credentials} )
200 {
201 $out{excludeCredentials} = [map{ _desc($_) } @{$opt->{exclude_credentials} || [] }];
202 }
203 $out{attestation} = _plain( $opt->{attestation} ) if( defined( $opt->{attestation} ) );
204 if( my $sel = $opt->{authenticator_selection} || $opt->{authenticatorSelection} )
205 {
206 my %s;
207 if( $sel->{authenticator_attachment} || $sel->{authenticatorAttachment} )
208 {
209 $s{authenticatorAttachment} = _plain( $sel->{authenticator_attachment} || $sel->{authenticatorAttachment} );
210 }
211 if( $sel->{resident_key} || $sel->{residentKey} )
212 {
213 $s{residentKey} = _plain( $sel->{resident_key} || $sel->{residentKey} );
214 }
215 if( exists( $sel->{require_resident_key} ) || exists( $sel->{requireResidentKey} ) )
216 {
217 no strict 'refs';
218 $s{requireResidentKey} = $sel->{require_resident_key} ? &{"$JSON_CLASS\::true"} : &{"$JSON_CLASS\::false"};
219 }
220 if( $sel->{user_verification} || $sel->{userVerification} )
221 {
222 $s{userVerification} = _plain( $sel->{user_verification} || $sel->{userVerification} );
223 }
224 $out{authenticatorSelection} = \%s;
225 }
226 $out{hints} = $opt->{hints} if( $opt->{hints} );
227 }
228 else
229 {
230 $out{challenge} = b64u_encode( $opt->{challenge} );
231 $out{timeout} = 0 + _plain( $opt->{timeout} ) if( defined( $opt->{timeout} ) );
232 $out{rpId} = _plain( $opt->{rp_id} || $opt->{rpId} );
233 if( $opt->{allow_credentials} )
234 {
235 $out{allowCredentials} = [map{ _desc($_) } @{ $opt->{allow_credentials} || [] }];
236 }
237 if( $opt->{user_verification} || $opt->{userVerification} )
238 {
239 $out{userVerification} = _plain( $opt->{user_verification} || $opt->{userVerification} );
240 }
241 }
242 return( \%out );
243 }
244  
245 sub parse_attestation_object
246 {
247 my $bytes = shift( @_ );
248 $bytes = maybe_bytes( $bytes );
249 my $obj = Web::Authn::CBOR::decode( $bytes );
250 unless( ref( $obj ) eq 'HASH' )
251 {
252 Web::Authn::Exception::InvalidStructure->throw( 'attestationObject is not a map' );
253 }
254 my $fmt = $obj->{fmt};
255 my $auth = $obj->{authData};
256 unless( defined( $fmt ) && defined( $auth ) )
257 {
258 Web::Authn::Exception::InvalidStructure->throw( 'attestationObject missing fmt/authData' );
259 }
260 my $auth_parsed = parse_authenticator_data( $auth );
261 my $stmt = parse_attestation_statement( $obj->{attStmt} );
262 return({
263 fmt => $fmt,
264 auth_data => $auth_parsed,
265 att_stmt => $stmt,
266 raw => $bytes,
267 auth_raw => $auth,
268 });
269 }
270  
271 sub parse_attestation_statement
272 {
273 my $stmt = shift( @_ );
274 return({}) unless( defined( $stmt ) && ref( $stmt ) eq 'HASH' );
275 my %out;
276 $out{sig} = $stmt->{sig} if( exists( $stmt->{sig} ) );
277 $out{alg} = $stmt->{alg} if( exists( $stmt->{alg} ) );
278 $out{x5c} = $stmt->{x5c} if( exists( $stmt->{x5c} ) );
279 $out{ver} = $stmt->{ver} if( exists( $stmt->{ver} ) );
280 $out{cert_info} = $stmt->{certInfo} if( exists( $stmt->{certInfo} ) );
281 $out{pub_area} = $stmt->{pubArea} if( exists( $stmt->{pubArea} ) );
282 $out{response} = $stmt->{response} if( exists( $stmt->{response} ) );
283 return( \%out );
284 }
285  
286 sub parse_authentication_credential_json
287 {
288 my $cred = shift( @_ );
289 $cred = _as_hash( $cred );
290 my $id = $cred->{id};
291 my $raw = exists( $cred->{rawId} ) ? b64u_decode( $cred->{rawId} ) : b64u_decode( $id );
292 my $resp = $cred->{response} || {};
293 return({
294 id => $id,
295 raw_id => $raw,
296 type => $cred->{type} || 'public-key',
297 response =>
298 {
299 client_data_json => _field_bytes( $resp, qw(clientDataJSON client_data_json) ),
300 authenticator_data => _field_bytes( $resp, qw(authenticatorData authenticator_data) ),
301 signature => _field_bytes( $resp, qw(signature) ),
302 user_handle => ( exists( $resp->{userHandle} ) && defined( $resp->{userHandle} ) && length( _plain( $resp->{userHandle} ) ) ) ? b64u_decode( $resp->{userHandle} ) : undef,
303 },
304 });
305 }
306  
307 sub parse_authenticator_data
308 {
309 my $val = shift( @_ );
310 $val = maybe_bytes( $val );
311 unless( length( $val ) >= 37 )
312 {
313 Web::Authn::Exception::InvalidStructure->throw( 'Authenticator data was ' . length($val) . ' bytes, expected at least 37' );
314 }
315 my $p = 0;
316 my $rp_id_hash = substr( $val, $p, 32 );
317 $p += 32;
318 my $flags_b = unpack( 'C', substr( $val, $p, 1 ) );
319 $p += 1;
320 my $sign_count = unpack( 'N', substr( $val, $p, 4 ) );
321 $p += 4;
322 my $flags =
323 {
324 up => ( $flags_b & ( 1 << 0 ) ) ? 1 : 0,
325 uv => ( $flags_b & ( 1 << 2 ) ) ? 1 : 0,
326 be => ( $flags_b & ( 1 << 3 ) ) ? 1 : 0,
327 bs => ( $flags_b & ( 1 << 4 ) ) ? 1 : 0,
328 at => ( $flags_b & ( 1 << 6 ) ) ? 1 : 0,
329 ed => ( $flags_b & ( 1 << 7 ) ) ? 1 : 0,
330 };
331 my $out =
332 {
333 rp_id_hash => $rp_id_hash,
334 flags => $flags,
335 sign_count => $sign_count,
336 };
337 if( $flags->{at} )
338 {
339 my $aaguid = substr( $val, $p, 16 );
340 $p += 16;
341 my $cid_len = unpack( 'n', substr( $val, $p, 2 ) );
342 $p += 2;
343 my $cid = substr( $val, $p, $cid_len );
344 $p += $cid_len;
345 my $bad = pack( 'H*', 'a301634f4b500327206745643235353139' );
346 if( substr( $val, $p, length( $bad ) ) eq $bad )
347 {
348 substr( $val, $p, 1 ) = pack( 'C', 0xA4 );
349 }
350 my( $pk_obj, $consumed ) = Web::Authn::CBOR::decode( substr( $val, $p ) );
351 my $pk_bytes = substr( $val, $p, $consumed );
352 $p += $consumed;
353 $out->{attested_credential_data} =
354 {
355 aaguid => $aaguid,
356 credential_id => $cid,
357 credential_public_key => $pk_bytes,
358 };
359 }
360 if( $flags->{ed} )
361 {
362 my( $ext, $consumed ) = Web::Authn::CBOR::decode( substr( $val, $p ) );
363 $out->{extensions} = substr( $val, $p, $consumed );
364 $p += $consumed;
365 }
366 if( length( $val) > $p )
367 {
368 Web::Authn::Exception::InvalidStructure->throw( 'Leftover bytes detected while parsing authenticator data' );
369 }
370 return( $out );
371 }
372  
373 sub parse_backup_flags
374 {
375 my $flags = shift( @_ );
376 my $be = $flags->{be};
377 my $bs = $flags->{bs};
378 if( !$be && $bs )
379 {
380 Web::Authn::Exception::InvalidStructure->throw( 'Backup state is true but backup eligibility is false' );
381 }
382 return({
383 credential_device_type => $be ? 'multiDevice' : 'singleDevice',
384 credential_backed_up => $bs ? 1 : 0,
385 });
386 }
387  
388 sub parse_client_data_json
389 {
390 my $bytes = shift( @_ );
391 $bytes = maybe_bytes( $bytes );
392 local $@;
393 my $json = eval{ $JSON_CLASS->new->utf8->decode( $bytes ) };
394 unless( $json && ref( $json ) eq 'HASH' )
395 {
396 Web::Authn::Exception::InvalidStructure->throw( 'Unable to decode clientDataJSON as JSON object' );
397 }
398  
399 foreach my $k ( qw( type challenge origin ) )
400 {
401 unless( exists( $json->{ $k } ) )
402 {
403 Web::Authn::Exception::InvalidStructure->throw( qq{clientDataJSON missing required property "$k"} );
404 }
405 }
406 my $out = {
407 type => $json->{type},
408 challenge => b64u_decode($json->{challenge}),
409 origin => $json->{origin},
410 };
411 $out->{cross_origin} = $json->{crossOrigin} ? 1 : 0 if( exists( $json->{crossOrigin} ) );
412 if( exists( $json->{tokenBinding} ) &&
413 ref( $json->{tokenBinding} ) eq 'HASH' )
414 {
415 my $tb = $json->{tokenBinding};
416 if( $tb->{status} &&
417 ( $tb->{status} eq 'present' || $tb->{status} eq 'supported' ) )
418 {
419 $out->{token_binding} = { status => $tb->{status}, id => $tb->{id} };
420 }
421 }
422 return( $out );
423 }
424  
425 sub parse_registration_credential_json
426 {
427 my $cred = shift( @_ );
428 $cred = _as_hash( $cred );
429 my $id = $cred->{id};
430 my $raw = exists( $cred->{rawId} ) ? b64u_decode( $cred->{rawId} ) : b64u_decode( $id );
431 my $type = $cred->{type} || 'public-key';
432 my $resp = $cred->{response} || {};
433 return({
434 id => $id,
435 raw_id => $raw,
436 type => $type,
437 response =>
438 {
439 client_data_json => _field_bytes( $resp, qw(clientDataJSON client_data_json) ),
440 attestation_object => _field_bytes( $resp, qw(attestationObject attestation_object) ),
441 },
442 authenticator_attachment => $cred->{authenticatorAttachment},
443 client_extension_results => $cred->{clientExtensionResults} || {},
444 });
445 }
446  
447 sub _as_hash
448 {
449 my $cred = shift( @_ );
450 return( $cred ) if( ref( $cred ) eq 'HASH' );
451 $cred = _plain( $cred );
452 if( !ref( $cred ) )
453 {
454 my $j = $JSON_CLASS->new->utf8->decode( $cred );
455 return( $j ) if( ref( $j ) eq 'HASH' );
456 }
457 Web::Authn::Exception::InvalidStructure->throw( 'credential must be JSON or a hash' );
458 }
459  
460 sub _desc
461 {
462 my $d = shift( @_ );
463 my $raw_id = maybe_bytes( $d->{id} );
464 my $id_out = $raw_id;
465 if( $id_out =~ /[^\x20-\x7E]/ )
466 {
467 $id_out = b64u_encode( $id_out );
468 }
469 elsif( length( $id_out ) && $id_out !~ /^[A-Za-z0-9_-]+\z/ )
470 {
471 $id_out = b64u_encode( $id_out );
472 }
473 else
474 {
475 # We ssume already base64url or raw that happens to be printable; if it looks like raw 16+ binary-ish we keep encoded
476 $id_out = b64u_encode( $raw_id ) if( $d->{_raw} );
477 }
478 # Always treat Perl bytes IDs as raw when they were generated internally
479 if( exists( $d->{_bytes} ) || ( defined( $raw_id ) && $raw_id =~ /[\x00-\x1F\x80-\xFF]/ ) )
480 {
481 $id_out = b64u_encode( $raw_id );
482 }
483 my $h = { type => _plain( $d->{type} ) || 'public-key', id => $id_out };
484 $h->{transports} = $d->{transports} if( $d->{transports} );
485 return( $h );
486 }
487  
488 sub _field_bytes
489 {
490 my( $resp, @names ) = @_;
491 foreach my $n ( @names )
492 {
493 next unless( defined( $resp->{ $n } ) );
494 my $v = _plain( $resp->{ $n } );
495 if( !ref( $v ) )
496 {
497 if( $v =~ /[^\x20-\x7E]/ )
498 {
499 return( $v );
500 }
501 return( b64u_decode( $v ) );
502 }
503 return( maybe_bytes( $v ) );
504 }
505 Web::Authn::Exception::InvalidStructure->throw( "missing response field @names" );
506 }
507  
508 sub _plain
509 {
510 my $v = shift( @_ );
511 return( $v ) if( !defined( $v ) || !ref( $v ) );
512 my $rt = Scalar::Util::reftype( $v ) || '';
513 if( $rt eq 'SCALAR' && !Scalar::Util::blessed( $v ) )
514 {
515 return( $$v );
516 }
517 if( Scalar::Util::blessed( $v ) && overload::Method( $v, '""' ) )
518 {
519 return( $v . '' );
520 }
521 return( $$v ) if( $rt eq 'SCALAR' );
522 return( $v );
523 }
524  
525 # NOTE: A fresh Bytes::Random::Secure object per call. The generator holds OS RNG state
526 # that must not be shared across Perl ithreads (CLONE would leave a stale object from
527 # the parent interpreter). Challenge generation is rare compared to CryptX, so the cost
528 # is acceptable.
529 sub _random
530 {
531 my $n = shift( @_ );
532 $n = int( _plain( $n ) || 0 );
533 unless( $n > 0 )
534 {
535 Web::Authn::Exception->throw( 'random length must be a positive integer' );
536 }
537 my $rng = Bytes::Random::Secure->new(
538 Bits => 256,
539 NonBlocking => 1,
540 );
541 return( $rng->bytes( $n ) );
542 }
543  
544 1;
545 # NOTE: POD
546 __END__