blib/lib/Lemonldap/NG/Portal/Lib/WebAuthn.pm

filter: Statementstmt 37.2% 64 / 172 Branchbran 16.1% 10 / 62 Conditioncond 0.0% 0 / 20 MC/DCmcdc 0.0% 0 / 11 Subroutinesub 57.6% 15 / 26 Podpod 0.0% 0 / 12 totaltotal 29.3% 89 / 303 CC 40 SCAR 36.0
CC
40
Cov
29%
validateAssertion
132.0
validateCredential
56.0
getUserFromCredential
42.0
CRAP 36.6
« blib/lib/Lemonldap/NG/Portal/CDC.pm ↑ Summary blib/lib/Lemonldap/NG/Portal/Issuer/Get.pm »
1 package Lemonldap::NG::Portal::Lib::WebAuthn;
2  
3 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 ▶use Mouse::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 5 ▶use MIME::Base64 qw(encode_base64url decode_base64url);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 5 ▶use JSON qw(decode_json from_json to_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 5 ▶use Digest::SHA qw(sha256);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 5 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 5 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 5 with 'Lemonldap::NG::Portal::Lib::2fDevices';
11 5 ▶use Lemonldap::NG::Common::Util qw/display2F/;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 5 our $VERSION = '2.23.0';
14  
15 5 has trust_anchors => (
16 is => 'rw',
17 lazy => 1,
18 isa => "ArrayRef",
19 builder => "_build_trust_anchors"
20 );
21  
22 0 ▶sub _build_trust_anchors {
Subroutine _build_trust_anchors: not called CC=1 SCAR=6.9
23 0 return [];
24 }
25  
26 0 ▶sub verifier {
Subroutine verifier: not called CC=1 SCAR=6.9
Pod undocumented
27 0 my ( $self, $req ) = @_;
28 0 return Authen::WebAuthn->new(
29 rp_id => $self->rp_id($req),
30 origin => $self->origin($req),
31 );
32 }
33  
34 1 ▶sub rp_id {
Subroutine rp_id: called CC=4 SCAR=19.4
Pod undocumented
35 1 my ( $self, $req ) = @_;
36  
37 # In case a plugin calls this method without arguments
38 1 ▶ my $portal = $req ? $req->portal : $self->p->portal;
Branch: 1 branch
BranchTrueFalseTotal
$req ? : 1 0 1
39  
40 1 ▶ if ( $self->conf->{webauthnRpId} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->conf->{'webauthnRpId'}) { } 1 0 1
41 1 return $self->conf->{webauthnRpId};
42 }
43 else {
44 0 my $portal_uri = URI->new($portal);
45 0 ▶ if ( $portal_uri->can('host') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($portal_uri->can('host')) { } 0 0 0
46 0 return $portal_uri->host;
47 }
48 else {
49 0 return $portal_uri->authority;
50 }
51 }
52 }
53  
54 0 ▶sub origin {
Subroutine origin: not called CC=2 SCAR=17.9
Pod undocumented
55 0 my ( $self, $req ) = @_;
56  
57 # In case a plugin calls this method without arguments
58 0 ▶ my $portal = $req ? $req->portal : $self->p->portal;
Branch: 1 branch
BranchTrueFalseTotal
$req ? : 0 0 0
59  
60 0 my $portal_uri = URI->new($portal);
61 0 return ( $portal_uri->scheme . "://" . $portal_uri->authority );
62 }
63  
64 1 ▶sub appid {
Subroutine appid: called CC=2 SCAR=7.6
Pod undocumented
65 1 my ( $self, $req ) = @_;
66  
67 1 ▶ if ( $self->conf->{webauthnAppId} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->conf->{'webauthnAppId'}) { } 0 1 1
68 0 return $self->origin($req);
69 }
70 else {
71 1 return;
72 }
73 }
74  
75 11 ▶around 'init' => sub {
Subroutine __ANON__: called CC=2 SCAR=7.8
76 11 my $orig = shift;
77 11 my $self = shift;
78  
79 11 eval { require Authen::WebAuthn };
80 11 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 11 11
81 0 $self->logger->error("Can't load WebAuthn library: $@");
82 0 $self->error("Can't load WebAuthn library: $@");
83 0 return 0;
84 }
85  
86 11 return $orig->( $self, @_ );
87 5 };
88  
89 0 ▶sub getUserHandle {
Subroutine getUserHandle: not called CC=1 SCAR=6.9
Pod undocumented
90 0 my ( $self, $req, $data ) = @_;
91 0 return $data->{_webAuthnUserHandle};
92 }
93  
94 0 ▶sub setUserHandle {
Subroutine setUserHandle: not called CC=1 SCAR=6.9
Pod undocumented
95 0 my ( $self, $req, $user_handle ) = @_;
96 0 $self->p->updatePersistentSession( $req,
97 { _webAuthnUserHandle => $user_handle } );
98 0 return;
99 }
100  
101 1 ▶sub generateChallenge {
Subroutine generateChallenge: called CC=3 SCAR=11.3
Pod undocumented
102 1 my ( $self, $req, $data ) = @_;
103  
104 # Find webauthn devices for user
105 1 my @webauthn_devices =
106 $self->find2fDevicesByType( $req, $data, $self->type );
107 1 ▶ return unless @webauthn_devices;
Branch: 1 branch
BranchTrueFalseTotal
unless @webauthn_devices 0 1 1
108  
109 1 my $challenge = $self->_generateBasicChallenge($req);
110  
111 $challenge->{allowCredentials} =
112 1 [ map { $self->_formatCredentialForRequest($_) } @webauthn_devices ];
113  
114 1 ▶ if ( my $appid = $self->appid($req) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $appid = $self->appid($req)) 0 1 1
115 0 $challenge->{extensions}->{appid} = $appid;
116 }
117  
118 $self->logger->debug(
119 1 "WebAuthn authentication parameters " . to_json($challenge) );
120  
121 1 return $challenge;
122 }
123  
124 1 ▶sub _formatCredentialForRequest {
Subroutine _formatCredentialForRequest: called CC=2 SCAR=7.1
125 1 my ( $self, $credential ) = @_;
126  
127 1 my $transports = $self->_getTransportsFromCredential($credential);
128 return {
129 type => "public-key",
130 id => $_->{_credentialId},
131 1 ▶ ( $transports ? ( transports => $transports ) : () ),
Branch: 1 branch
BranchTrueFalseTotal
$transports ? : 0 1 1
132 };
133 }
134  
135 0 ▶sub generateDiscoverableChallenge {
Subroutine generateDiscoverableChallenge: not called CC=1 SCAR=6.9
Pod undocumented
136 0 my ( $self, $req ) = @_;
137  
138 0 my $challenge = $self->_generateBasicChallenge($req);
139  
140 0 $self->logger->debug(
141 "WebAuthn authentication parameters " . to_json($challenge) );
142  
143 0 return $challenge;
144 }
145  
146 1 ▶sub _generateBasicChallenge {
Subroutine _generateBasicChallenge: called CC=2 SCAR=7.0
147 1 my ( $self, $req ) = @_;
148  
149 1 my $challenge_base64 = encode_base64url( Crypt::URandom::urandom(32) );
150 1 my $userVerification = $self->conf->{webauthn2fUserVerification};
151  
152 1 ▶ my $challenge = {
Branch: 1 branch
BranchTrueFalseTotal
$userVerification ? : 1 0 1
153 challenge => $challenge_base64,
154 rpId => $self->rp_id($req),
155 allowCredentials => [],
156 ( $userVerification ? ( userVerification => $userVerification ) : () ),
157 };
158 1 return $challenge;
159 }
160  
161 0 ▶sub getUserFromCredential {
Subroutine getUserFromCredential: not called CC=6 SCAR=37.4
Pod undocumented
162 0 my ( $self, $req, $credential_json ) = @_;
163 0 my $credential = eval { from_json($credential_json) };
164 0 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 0 0
165 0 $self->logger->error("Could not deserialize WebAuthn credential: $@");
166 0 return;
167 }
168 0 my $userHandle = $credential->{response}->{userHandle};
169 0 ▶ if ( !$userHandle ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($userHandle) 0 0 0
170 0 $self->logger->error(
171 "Could not find userHandle in WebAuthn credential");
172 0 return;
173 }
174  
175 my $opts = {
176 0 %{ $self->p->conf->{persistentStorageOptions} },
177 backend => $self->p->conf->{persistentStorage}
178 0 };
179  
180 0 my $sessions = Lemonldap::NG::Common::Apache::Session->searchOn( $opts,
181 "_webAuthnUserHandle", $userHandle );
182 0 ▶ if ( $sessions
Branch: 1 branch
BranchTrueFalseTotal
if ($sessions and ref $sessions eq 'HASH' and scalar keys %$sessions == 1) { } 0 0 0
Condition0%0/6
$sessions and ref $sessions eq "HASH" and scalar keys %$sessions == 1
!ll&&!rl&&r
000
$sessions and ref $sessions eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/3
$sessions and ref $sessions eq "HASH" and scalar keys %$sessions == 1
$sessions ref $sessions eq "HASH" scalar keys %$sessions == 1
Truth table0%0/4
A and B and C
A= $sessionsB= ref $sessions eq "HASH"C= scalar keys %$sessions == 1
ABCresult
0XX0
10X0
1100
1111
183 and ref($sessions) eq "HASH"
184 and scalar( keys %$sessions ) == 1 )
185 {
186 0 my ($session) = values %$sessions;
187 return {
188 uid => $session->{_session_uid},
189 _2fDevices => $session->{_2fDevices},
190 0 _webAuthnUserHandle => $userHandle,
191 };
192  
193 }
194 else {
195 0 $self->logger->error( "Could not locate a persistent session for"
196 . " WebAuthn user handle $userHandle" );
197 0 return;
198 }
199  
200 }
201  
202 0 ▶sub validateCredential {
Subroutine validateCredential: not called CC=7 SCAR=40.3
Pod undocumented
203 0 my ( $self, $req, $registration_options, $credential_json ) = @_;
204 0 my $credential = from_json($credential_json);
205 0 my $client_data_json_b64 = $credential->{response}->{clientDataJSON};
206 0 my $attestation_object_b64 = $credential->{response}->{attestationObject};
207 my $requested_uv =
208 0 ▶ $registration_options->{authenticatorSelection}->{userVerification} || '';
Condition0%0/2
$registration_options->{'authenticatorSelection'}{'userVerification'} || ''
l!l
00
MC/DC0%0/1
$registration_options->{'authenticatorSelection'}{'userVerification'} || ''
$registration_options->{'authenticatorSelection'}{'userVerification'}
Truth table0%0/2
A
A= $registration_options->{'authenticatorSelection'}{'userVerification'}
Aresult
11
00
209 0 my $challenge_b64 = $registration_options->{challenge};
210 0 ▶ my $token_binding_id_b64 =
Branch: 1 branch
BranchTrueFalseTotal
$req->headers->header('Sec-Provided-Token-Binding-ID') ? : 0 0 0
211 $req->headers->header('Sec-Provided-Token-Binding-ID')
212 ? encode_base64url(
213 $req->headers->header('Sec-Provided-Token-Binding-ID') )
214 : '';
215  
216 # If Authen::WebAuthn is too old, we can't check attestation
217 0 ▶ my $attestation = $registration_options->{attestation} || "none";
Condition0%0/2
$registration_options->{'attestation'} || 'none'
l!l
00
MC/DC0%0/1
$registration_options->{'attestation'} || 'none'
$registration_options->{'attestation'}
Truth table0%0/2
A
A= $registration_options->{'attestation'}
Aresult
11
00
218 0 ▶ if ( $attestation ne "none" and $Authen::WebAuthn::VERSION < 0.002 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attestation ne "none" and $Authen::WebAuthn::VERSION < "0.002") 0 0 0
Condition0%0/3
$attestation ne "none" and $Authen::WebAuthn::VERSION < "0.002"
!ll&&!rl&&r
000
MC/DC0%0/2
$attestation ne "none" and $Authen::WebAuthn::VERSION < "0.002"
$attestation ne "none" $Authen::WebAuthn::VERSION < "0.002"
Truth table0%0/3
A and B
A= $attestation ne "none"B= $Authen::WebAuthn::VERSION < "0.002"
ABresult
0X0
100
111
219 0 croak( "Authen::WebAuthn version is too old"
220 . " ($Authen::WebAuthn::VERSION < 0.002),"
221 . " cannot validate attestation" );
222 }
223  
224 0 ▶ return $self->verifier($req)->validate_registration(
Branch: 1 branch
BranchTrueFalseTotal
$attestation ne 'none' ? : 0 0 0
225 challenge_b64 => $challenge_b64,
226 requested_uv => $requested_uv,
227 client_data_json_b64 => $client_data_json_b64,
228 attestation_object_b64 => $attestation_object_b64,
229 token_binding_id_b64 => $token_binding_id_b64,
230 trust_anchors => $self->trust_anchors,
231 (
232 $attestation ne "none"
233 ? ( allowed_attestation_types => ["Basic"] )
234 : ()
235 ),
236 );
237 }
238  
239 0 ▶sub validateAssertion {
Subroutine validateAssertion: not called CC=11 SCAR=48.8
Pod undocumented
240 0 my ( $self, $req, $data, $signature_options, $credential_json ) = @_;
241 0 my $user = $data->{ $self->conf->{whatToTrace} };
242  
243 0 $self->logger->debug("Get asserted credential $credential_json");
244 0 my $credential = from_json($credential_json);
245 0 my $credential_id = $credential->{id};
246 0 ▶ croak("Empty credential id in credential response") unless $credential_id;
Branch: 1 branch
BranchTrueFalseTotal
unless $credential_id 0 0 0
247  
248 # 5. If options.allowCredentials is not empty, verify that credential.id
249 # identifies one of the public key credentials listed in
250 # options.allowCredentials.
251 my @allowed_credential_ids =
252 0 map { $_->{id} } @{ $signature_options->{allowCredentials} };
253 croak("Received credential ID $credential_id was not requested")
254 if ( @allowed_credential_ids
255 0 ▶ and not grep { $_ eq $credential_id } @allowed_credential_ids );
Branch: 1 branch
BranchTrueFalseTotal
if @allowed_credential_ids and not grep({$_ eq $credential_id;} @allowed_credential_ids) 0 0 0
Condition0%0/3
@allowed_credential_ids and not grep({$_ eq $credential_id;} @allowed_credential_ids)
!ll&&!rl&&r
000
MC/DC0%0/2
@allowed_credential_ids and not grep({$_ eq $credential_id;} @allowed_credential_ids)
@allowed_credential_ids not grep({$_ eq $credential_id;} @allowed_credential_ids)
Truth table0%0/3
A and not(B)
A= @allowed_credential_idsB= not grep({$_ eq $credential_id;} @allowed_credential_ids)
ABresult
0X0
100
111
256  
257 # 6. Identify the user being authenticated and verify that this user is the
258 # owner of the public key credential source credentialSource identified by
259 # credential.id If the user was identified before the authentication
260 # ceremony was initiated, e.g., via a username or cookie, verify that the
261 # identified user is the owner of credentialSource.
262 0 my @webauthn_devices =
263 $self->find2fDevicesByType( $req, $data, $self->type );
264 my @matching_credentials =
265 0 grep { $_->{_credentialId} eq $credential_id } @webauthn_devices;
266  
267 0 ▶ croak("Received credential ID $credential_id does not belong to user")
Branch: 1 branch
BranchTrueFalseTotal
if @matching_credentials < 1 0 0 0
268 if ( @matching_credentials < 1 );
269 0 ▶ croak("Found multiple credentials with ID $credential_id for user")
Branch: 1 branch
BranchTrueFalseTotal
if @matching_credentials > 1 0 0 0
270 if ( @matching_credentials > 1 );
271 0 my $matching_credential = $matching_credentials[0];
272  
273 # If response.userHandle is present, let userHandle be its value.
274 # Verify that userHandle also maps to the same user.
275 0 ▶ if ( $credential->{response}->{userHandle} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($credential->{"response"}{"userHandle"}) 0 0 0
276 0 my $user_handle = $credential->{response}->{userHandle};
277 0 my $current_user_handle = $self->getUserHandle( $req, $data );
278 0 ▶ croak(
Branch: 1 branch
BranchTrueFalseTotal
unless $user_handle eq $current_user_handle 0 0 0
279 "Received user handle ($user_handle) does not match current user ($current_user_handle)"
280 ) unless ( $user_handle eq $current_user_handle );
281 }
282  
283 # TODO If the user was not identified before the authentication ceremony
284 # was initiated, verify that response.userHandle is present, and that the
285 # user identified by this value is the owner of credentialSource.
286 # NOTE: irrelevant for now, take this into account when implementing
287 # Auth::WebAuthn
288  
289 0 my $client_data_json_b64 = $credential->{response}->{clientDataJSON};
290 0 my $authenticator_data_b64 = $credential->{response}->{authenticatorData};
291 0 my $signature_b64 = $credential->{response}->{signature};
292 0 my $extension_results = $credential->{clientExtensionResults};
293 0 ▶ my $requested_uv = $signature_options->{userVerification} || "";
Condition0%0/2
$signature_options->{'userVerification'} || ''
l!l
00
MC/DC0%0/1
$signature_options->{'userVerification'} || ''
$signature_options->{'userVerification'}
Truth table0%0/2
A
A= $signature_options->{'userVerification'}
Aresult
11
00
294  
295 0 ▶ my $token_binding_id_b64 =
Branch: 1 branch
BranchTrueFalseTotal
$req->headers->header('Sec-Provided-Token-Binding-ID') ? : 0 0 0
296 $req->headers->header('Sec-Provided-Token-Binding-ID')
297 ? encode_base64url(
298 $req->headers->header('Sec-Provided-Token-Binding-ID') )
299 : '';
300  
301 my $validation_result = $self->verifier($req)->validate_assertion(
302 challenge_b64 => $signature_options->{challenge},
303 credential_pubkey_b64 => $matching_credential->{_credentialPublicKey},
304 stored_sign_count => $matching_credential->{_signCount},
305 0 requested_uv => $requested_uv,
306 client_data_json_b64 => $client_data_json_b64,
307 authenticator_data_b64 => $authenticator_data_b64,
308 signature_b64 => $signature_b64,
309 extension_results => $extension_results,
310 token_binding_id_b64 => $token_binding_id_b64,
311 );
312  
313 0 $validation_result->{matching_credential} = $matching_credential;
314  
315 0 ▶ if ( $validation_result->{success} == 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($validation_result->{"success"} == 1) 0 0 0
316 0 my $new_signature_count = $validation_result->{signature_count};
317  
318 # Update storedSignCount to be the value of authData.signCount
319 $validation_result->{matching_credential}->{_signCount} =
320 0 $new_signature_count;
321 0 $self->update2fDevice( $req, $data, $self->type,
322 "_credentialId", $credential_id, "_signCount",
323 $new_signature_count );
324 }
325  
326 0 return $validation_result;
327 }
328  
329 0 ▶sub decode_credential {
Subroutine decode_credential: not called CC=5 SCAR=34.0
Pod undocumented
330 0 my ( $self, $json ) = @_;
331 0 my $credential = decode_json($json);
332  
333 # Decode ClientDataJSON
334 0 ▶ if ( $credential->{response}->{clientDataJSON} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($credential->{"response"}{"clientDataJSON"}) 0 0 0
335 $credential->{response}->{clientDataJSON} = decode_json(
336 0 decode_base64url( $credential->{response}->{clientDataJSON} ) );
337 }
338  
339 # Decode attestation object
340 0 ▶ if ( $credential->{response}->{attestationObject} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($credential->{"response"}{"attestationObject"}) 0 0 0
341 $credential->{response}->{attestationObject} =
342 0 getAttestationObject( $credential->{response}->{attestationObject} );
343 }
344  
345 # Decode authenticator data
346 0 ▶ if ( $credential->{response}->{authenticatorData} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($credential->{"response"}{"authenticatorData"}) 0 0 0
347 $credential->{response}->{authenticatorData} =
348 getAuthData(
349 0 decode_base64url( $credential->{response}->{authenticatorData} ) );
350 }
351  
352 # Decode rawID
353 0 ▶ if ( $credential->{rawId} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($credential->{"rawId"}) 0 0 0
354 0 $credential->{rawId} = decode_base64url( $credential->{rawId} );
355 }
356  
357 0 return $credential;
358 }
359  
360 0 ▶sub _serializeTransportsFromJsonResponse {
Subroutine _serializeTransportsFromJsonResponse: not called CC=3 SCAR=24.8
361 0 my ( $self, $credential_json ) = @_;
362  
363 my $transports =
364 0 eval { from_json($credential_json)->{response}->{transports} };
365 0 ▶ $self->logger->debug("Could not read transports from response: $@") if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 0 0
366  
367 0 ▶ my $transports_str = join( ",", @{ $transports || [] } );
Condition0%0/2
$transports || []
l!l
00
MC/DC0%0/1
$transports || []
$transports
Truth table0%0/2
A
A= $transports
Aresult
11
00
368 0 return $transports_str;
369 }
370  
371 1 ▶sub _getTransportsFromCredential {
Subroutine _getTransportsFromCredential: called CC=3 SCAR=12.3
372 1 my ( $self, $credential ) = @_;
373  
374 1 my $transports_str = $credential->{_transports};
375 1 ▶ if ($transports_str) {
Branch: 1 branch
BranchTrueFalseTotal
if ($transports_str) { } 0 1 1
376 0 return [ split( qr/\s*,\s*/, $transports_str ) ];
377 }
378 else {
379 1 ▶ if ( $self->conf->{webauthnDefaultTransports} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->conf->{'webauthnDefaultTransports'}) { } 0 1 1
380 return [
381 split( qr/\s*,\s*/, $self->conf->{webauthnDefaultTransports} )
382 0 ];
383 }
384 else {
385 1 return;
386 }
387 }
388 }
389  
390 5 1;
« blib/lib/Lemonldap/NG/Portal/CDC.pm ↑ Summary blib/lib/Lemonldap/NG/Portal/Issuer/Get.pm »