Authen-WebAuthn-0.001000755001750001750 014176453400 14376 5ustar00maxbesmaxbes000000000000README100644001750001750 62414176453400 15321 0ustar00maxbesmaxbes000000000000Authen-WebAuthn-0.001This archive contains the distribution Authen-WebAuthn, version 0.001: A library to add Web Authentication support to server applications This software is copyright (c) 2022 by Maxime Besson. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. This README file was generated by Dist::Zilla::Plugin::Readme v6.017. LICENSE100644001750001750 4366014176453400 15515 0ustar00maxbesmaxbes000000000000Authen-WebAuthn-0.001This software is copyright (c) 2022 by Maxime Besson. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2022 by Maxime Besson. This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2022 by Maxime Besson. This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End dist.ini100644001750001750 46514176453400 16110 0ustar00maxbesmaxbes000000000000Authen-WebAuthn-0.001name = Authen-WebAuthn author = Maxime Besson license = Perl_5 copyright_holder = Maxime Besson copyright_year = 2022 version = 0.001 abstract = A library to add Web Authentication support to server applications [@Basic] [@Git] [AutoPrereqs] [PodWeaver] [PkgVersion] [GithubMeta] META.yml100644001750001750 177514176453400 15742 0ustar00maxbesmaxbes000000000000Authen-WebAuthn-0.001--- abstract: 'A library to add Web Authentication support to server applications' author: - 'Maxime Besson ' build_requires: Crypt::URandom: '0' Test::More: '0' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 0 generated_by: 'Dist::Zilla version 6.017, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Authen-WebAuthn requires: CBOR::XS: '0' Carp: '0' Crypt::OpenSSL::X509: '0' Crypt::PK::ECC: '0' Crypt::PK::RSA: '0' Digest::SHA: '0' Hash::Merge::Simple: '0' JSON: '0' MIME::Base64: '0' Mouse: '0' URI: '0' constant: '0' strict: '0' utf8: '0' warnings: '0' resources: homepage: https://github.com/LemonLDAPNG/Authen-WebAuthn repository: https://github.com/LemonLDAPNG/Authen-WebAuthn.git version: '0.001' x_generated_by_perl: v5.32.1 x_serialization_backend: 'YAML::Tiny version 1.73' x_spdx_expression: 'Artistic-1.0-Perl OR GPL-1.0-or-later' MANIFEST100644001750001750 40114176453400 15563 0ustar00maxbesmaxbes000000000000Authen-WebAuthn-0.001# This file was automatically generated by Dist::Zilla::Plugin::Manifest v6.017. LICENSE MANIFEST META.yml Makefile.PL README README.md dist.ini lib/Authen/WebAuthn.pm lib/Authen/WebAuthn.pod lib/Authen/WebAuthn/Test.pm t/00-WebAuthn-Ext1.t t/00-WebAuthn.t README.md100644001750001750 100514176453400 15732 0ustar00maxbesmaxbes000000000000Authen-WebAuthn-0.001# Authen::WebAuthn A library to add [Web Authentication](https://www.w3.org/TR/webauthn-2/) support to server applications ![](image.png){width=100%} # Status * Authentication works * ECC/RSA keys supported * Registration works with "none" attestation type # TODO * Support more attestation types * Support more public key types (EdDSA...) * Support attestation authority certificates * Support FIDO Metadata Service * Handle request creation too # Documentation https://metacpan.org/pod/Authen::WebAuthn Makefile.PL100644001750001750 321714176453400 16434 0ustar00maxbesmaxbes000000000000Authen-WebAuthn-0.001# This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v6.017. use strict; use warnings; use ExtUtils::MakeMaker; my %WriteMakefileArgs = ( "ABSTRACT" => "A library to add Web Authentication support to server applications", "AUTHOR" => "Maxime Besson ", "CONFIGURE_REQUIRES" => { "ExtUtils::MakeMaker" => 0 }, "DISTNAME" => "Authen-WebAuthn", "LICENSE" => "perl", "NAME" => "Authen::WebAuthn", "PREREQ_PM" => { "CBOR::XS" => 0, "Carp" => 0, "Crypt::OpenSSL::X509" => 0, "Crypt::PK::ECC" => 0, "Crypt::PK::RSA" => 0, "Digest::SHA" => 0, "Hash::Merge::Simple" => 0, "JSON" => 0, "MIME::Base64" => 0, "Mouse" => 0, "URI" => 0, "constant" => 0, "strict" => 0, "utf8" => 0, "warnings" => 0 }, "TEST_REQUIRES" => { "Crypt::URandom" => 0, "Test::More" => 0 }, "VERSION" => "0.001", "test" => { "TESTS" => "t/*.t" } ); my %FallbackPrereqs = ( "CBOR::XS" => 0, "Carp" => 0, "Crypt::OpenSSL::X509" => 0, "Crypt::PK::ECC" => 0, "Crypt::PK::RSA" => 0, "Crypt::URandom" => 0, "Digest::SHA" => 0, "Hash::Merge::Simple" => 0, "JSON" => 0, "MIME::Base64" => 0, "Mouse" => 0, "Test::More" => 0, "URI" => 0, "constant" => 0, "strict" => 0, "utf8" => 0, "warnings" => 0 ); unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) { delete $WriteMakefileArgs{TEST_REQUIRES}; delete $WriteMakefileArgs{BUILD_REQUIRES}; $WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs; } delete $WriteMakefileArgs{CONFIGURE_REQUIRES} unless eval { ExtUtils::MakeMaker->VERSION(6.52) }; WriteMakefile(%WriteMakefileArgs); t000755001750001750 014176453400 14562 5ustar00maxbesmaxbes000000000000Authen-WebAuthn-0.00100-WebAuthn.t100644001750001750 2135514176453400 17067 0ustar00maxbesmaxbes000000000000Authen-WebAuthn-0.001/tuse Test::More; use MIME::Base64 'encode_base64url'; use Crypt::URandom qw( urandom ); use Hash::Merge::Simple qw/merge/; use Carp; use strict; use Authen::WebAuthn; use Authen::WebAuthn::Test; # The RP lib used for these tests my $rp = Authen::WebAuthn->new( origin => "http://auth.example.com", rp_id => "auth.example.com", ); my $ecdsa_key = <new( origin => "http://auth.example.com", rp_id => "auth.example.com", credential_id => "lZYltP9MtoRNuXK8f8tWf", aaguid => "00000000-0000-0000-0000-000000000000", key => $ecdsa_key, ); my $res; # This method generates a registration response from the authenticator and # attempts to validate it with the RP. # $option lets you override options for the validation method # Use the $override hash to manipulate the authenticator response and do funky # stuff sub validate_registration { my ( $authenticator, $rp, $options, $override ) = @_; my $challenge = encode_base64url( urandom(10) ); my $credential = $authenticator->get_credential_response( { request => { challenge => $challenge, authenticatorSelection => { ( $options->{requested_uv} ? ( userVerification => $options->{requested_uv} ) : () ), }, }, }, $override ); my $registration_params = merge { challenge_b64 => $challenge, client_data_json_b64 => encode_base64url( $credential->{response}->{clientDataJSON} ), attestation_object_b64 => encode_base64url( $credential->{response}->{attestationObject} ), }, $options; return $rp->validate_registration( %{$registration_params} ); } # This method generates an authentication response from the authenticator and # attempts to validate it with the RP. # Use the override hash to manipulate the authenticator response and do funky # stuff sub validate_authentication { my ( $authenticator, $rp, $options, $override ) = @_; my $challenge = encode_base64url( urandom(10) ); my $credential = $authenticator->get_assertion_response( { request => { challenge => $challenge, ( $options->{requested_uv} ? ( userVerification => $options->{requested_uv} ) : () ), }, }, $override ); my $assertion_params = merge { challenge_b64 => $challenge, credential_pubkey_b64 => encode_base64url( $authenticator->encode_cosekey ), client_data_json_b64 => encode_base64url( $credential->{response}->{clientDataJSON} ), authenticator_data_b64 => encode_base64url( $credential->{response}->{authenticatorData} ), signature_b64 => encode_base64url( $credential->{response}->{signature} ), }, $options; return $rp->validate_assertion( %{$assertion_params} ); } sub test_registration { my ( $options, $override, $test_name, $exception_message ) = @_; my $res; eval { $res = validate_registration( $authenticator, $rp, $options, $override ); }; my $exception = $@; if ($exception_message) { like( $exception, $exception_message, "$test_name fails with expected message" ); } else { is( $res->{attestation_result}->{success}, 1, "$test_name succeeds" ); } return $res; } sub test_authentication { my ( $options, $override, $test_name, $exception_message ) = @_; my $res; eval { $res = validate_authentication( $authenticator, $rp, $options, $override ); }; my $exception = $@; if ($exception_message) { like( $exception, $exception_message, "$test_name fails with expected message" ); } else { is( $res->{success}, 1, "$test_name succeed as expected" ); } return $res; } # Registration tests test_registration( {}, {}, "Success with default options" ); test_registration( { requested_uv => "required" }, {}, "Success with required UV" ); test_registration( { requested_uv => "required" }, { response => { attestationObject => { authData => { flags => { userVerified => 0 } } } } }, "Fail when authenticator does not send required UV", qr,User not verified during WebAuthn registration, ); $authenticator->rp_id('invalid'); test_registration( {}, {}, "Fails with wrong RP ID", qr,RP ID hash received from authenticator.*does not match the hash of this RP ID, ); $authenticator->rp_id('auth.example.com'); $authenticator->origin('invalid'); test_registration( {}, {}, "Fails with wrong Origin", qr,Origin received from client data.*does not match server origin, ); $authenticator->origin('http://auth.example.com'); test_registration( {}, { response => { clientDataJSON => { challenge => "xxx" } } }, "Fails with wrong challenge", qr,Challenge received from client data.*does not match server challenge, ); # Authentication tests test_authentication( {}, {}, "Success with default options" ); test_authentication( { requested_uv => "required" }, {}, "Success with required UV" ); test_authentication( { requested_uv => "required" }, { response => { authenticatorData => { flags => { userVerified => 0 } } } }, "Fail when authenticator does not send required UV", qr,User not verified during WebAuthn authentication, ); $authenticator->rp_id('invalid'); test_authentication( {}, {}, "Fails with wrong RP ID", qr,RP ID hash received from authenticator.*does not match the hash of this RP ID, ); $authenticator->rp_id('auth.example.com'); $authenticator->origin('invalid'); test_authentication( {}, {}, "Fails with wrong Origin", qr,Origin received from client data.*does not match server origin, ); $authenticator->origin('http://auth.example.com'); test_authentication( {}, { response => { clientDataJSON => { challenge => "xxx" } } }, "Fails with wrong challenge", qr,Challenge received from client data.*does not match server challenge, ); $authenticator->sign_count(10); $res = test_authentication( { stored_sign_count => 5 }, {}, "Success with normal signature count" ); is( $res->{signature_count}, 10, "Signature count is updated" ); $authenticator->sign_count(10); test_authentication( { stored_sign_count => 20 }, {}, "Fails with wrong signature count", qr,Stored signature count.*higher than device signature count, ); test_authentication( { stored_sign_count => 10 }, {}, "Fails with wrong signature count", qr,Stored signature count.*higher than device signature count, ); $authenticator->sign_count(0); test_authentication( { token_binding_id_b64 => "YWJjCg" }, { response => { clientDataJSON => { tokenBinding => { status => "present", id => "ZmFpbAo" } } } }, "Mismatching token binding ID fails", qr,Token Binding ID.*does not match, ); test_authentication( {}, { response => { clientDataJSON => { tokenBinding => { status => "present", id => "ZmFpbAo" } } } }, "Token binding used in Client Data JSON but not in TLS connection", qr,The Token Binding ID from the current connection.*does not match Token Binding ID in client data, ); test_authentication( { token_binding_id_b64 => "YWJjCg" }, { response => { clientDataJSON => { tokenBinding => { status => "present", id => "YWJjCg" } } } }, "Correct token binding ID works", ); test_authentication( { signature_b64 => "" }, {}, "Empty signature fails to validate", qr,Webauthn signature was not valid, ); test_authentication( { signature_b64 => "xxxyyy" }, {}, "Invalid signature fails to validate", qr,Webauthn signature was not valid, ); test_authentication( { signature_b64 => "xxxyyy", client_data_json_b64 => "" }, {}, "Invalid client data fails to validate", qr,Error deserializing client data, ); done_testing(); 00-WebAuthn-Ext1.t100644001750001750 2363714176453400 17713 0ustar00maxbesmaxbes000000000000Authen-WebAuthn-0.001/tuse Test::More; use MIME::Base64 'encode_base64url'; use strict; use Authen::WebAuthn; use Authen::WebAuthn::Test; # Interoperability tests, data from # https://github.com/duo-labs/py_webauthn my $webauthn = Authen::WebAuthn->new( origin => "http://localhost:5000", rp_id => "localhost", ); my $reg; # None attestation type $reg = $webauthn->validate_registration( challenge_b64 => "TwN7n4WTyGKLc4ZY-qGsFqKnHM4nglqsyV0ICJlN2TO9XiRyFtrkaDwUvsql-gkLJXP6fnF1MlrZ53Mm4R7Cvw", requested_uv => "required", attestation_object_b64 => "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YVjESZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2NFAAAAFwAAAAAAAAAAAAAAAAAAAAAAQPctcQPE5oNRRJk_nO_371mf7qE7qIodzr0eOf6ACvnMB1oQG165dqutoi1U44shGezu5_gkTjmOPeJO0N8a7P-lAQIDJiABIVggSFbUJF-42Ug3pdM8rDRFu_N5oiVEysPDB6n66r_7dZAiWCDUVnB39FlGypL-qAoIO9xWHtJygo2jfDmHl-_eKFRLDA", client_data_json_b64 => "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiVHdON240V1R5R0tMYzRaWS1xR3NGcUtuSE00bmdscXN5VjBJQ0psTjJUTzlYaVJ5RnRya2FEd1V2c3FsLWdrTEpYUDZmbkYxTWxyWjUzTW00UjdDdnciLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjUwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9", ); is( $reg->{attestation_result}->{success}, 1, "None attestation" ); is( $reg->{attestation_result}->{type}, "None" ); is( $reg->{credential_id}, "9y1xA8Tmg1FEmT-c7_fvWZ_uoTuoih3OvR45_oAK-cwHWhAbXrl2q62iLVTjiyEZ7O7n-CROOY494k7Q3xrs_w" ); is( $reg->{credential_pubkey}, "pQECAyYgASFYIEhW1CRfuNlIN6XTPKw0RbvzeaIlRMrDwwep-uq_-3WQIlgg1FZwd_RZRsqS_qgKCDvcVh7ScoKNo3w5h5fv3ihUSww" ); is( $reg->{signature_count}, 23 ); # packed attestation $reg = $webauthn->validate_registration( challenge_b64 => "8LBCiOY3q1cBZHFAWtS4AZZChzGphy67lK7I70zKi4yC7pgrQ2Pch7nAjLk1wq9greshIAsW2AjibhXjjI0TmQ", requested_uv => 0, client_data_json_b64 => "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiOExCQ2lPWTNxMWNCWkhGQVd0UzRBWlpDaHpHcGh5NjdsSzdJNzB6S2k0eUM3cGdyUTJQY2g3bkFqTGsxd3E5Z3Jlc2hJQXNXMkFqaWJoWGpqSTBUbVEiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjUwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9", attestation_object_b64 => "o2NmbXRmcGFja2VkZ2F0dFN0bXSjY2FsZyZjc2lnWEcwRQIhAOfrFlQpbavT6dJeTDJSCDzYSYPjBDHli2-syT2c1IiKAiAx5gQ2z5cHjdQX-jEHTb7JcjfQoVSW8fXszF5ihSgeOGN4NWOBWQLBMIICvTCCAaWgAwIBAgIEKudiYzANBgkqhkiG9w0BAQsFADAuMSwwKgYDVQQDEyNZdWJpY28gVTJGIFJvb3QgQ0EgU2VyaWFsIDQ1NzIwMDYzMTAgFw0xNDA4MDEwMDAwMDBaGA8yMDUwMDkwNDAwMDAwMFowbjELMAkGA1UEBhMCU0UxEjAQBgNVBAoMCVl1YmljbyBBQjEiMCAGA1UECwwZQXV0aGVudGljYXRvciBBdHRlc3RhdGlvbjEnMCUGA1UEAwweWXViaWNvIFUyRiBFRSBTZXJpYWwgNzE5ODA3MDc1MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEKgOGXmBD2Z4R_xCqJVRXhL8Jr45rHjsyFykhb1USGozZENOZ3cdovf5Ke8fj2rxi5tJGn_VnW4_6iQzKdIaeP6NsMGowIgYJKwYBBAGCxAoCBBUxLjMuNi4xLjQuMS40MTQ4Mi4xLjEwEwYLKwYBBAGC5RwCAQEEBAMCBDAwIQYLKwYBBAGC5RwBAQQEEgQQbUS6m_bsLkm5MAyP6SDLczAMBgNVHRMBAf8EAjAAMA0GCSqGSIb3DQEBCwUAA4IBAQByV9A83MPhFWmEkNb4DvlbUwcjc9nmRzJjKxHc3HeK7GvVkm0H4XucVDB4jeMvTke0WHb_jFUiApvpOHh5VyMx5ydwFoKKcRs5x0_WwSWL0eTZ5WbVcHkDR9pSNcA_D_5AsUKOBcbpF5nkdVRxaQHuuIuwV4k1iK2IqtMNcU8vL6w21U261xCcWwJ6sMq4zzVO8QCKCQhsoIaWrwz828GDmPzfAjFsJiLJXuYivdHACkeJ5KHMt0mjVLpfJ2BCML7_rgbmvwL7wBW80VHfNdcKmKjkLcpEiPzwcQQhiN_qHV90t-p4iyr5xRSpurlP5zic2hlRkLKxMH2_kRjhqSn4aGF1dGhEYXRhWMRJlg3liA6MaHQ0Fw9kdmBbj-SuuaKGMseZXPO6gx2XY0UAAAA0bUS6m_bsLkm5MAyP6SDLcwBAsyGQPDZRUYdb4m3rdWeyPaIMYlbmydGp1TP_33vE_lqJ3PHNyTd0iKsnKr5WjnCcBzcesZrDEfB_RBLFzU3k46UBAgMmIAEhWCBAX_i3O3DvBnkGq_uLNk_PeAX5WwO_MIxBp0mhX6Lw7yJYIOW-1-Fch829McWvRUYAHTWZTx5IycKSGECL1UzUaK_8", ); is( $reg->{attestation_result}->{success}, 1, "Yubico packed attestation" ); ## EdDSA #$reg = $webauthn->validate_registration( # challenge_b64 => #"7JUBjWZFdFozulxb71DvHkh3P6WKUG4ElUo7wEkKic2JETJMAIKCf7rBE9YksI5oNjDzQ6Hqh6E73Oy6SPcMnw", # requested_uv => 0, # client_data_json_b64 => #"eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiN0pVQmpXWkZkRm96dWx4YjcxRHZIa2gzUDZXS1VHNEVsVW83d0VrS2ljMkpFVEpNQUlLQ2Y3ckJFOVlrc0k1b05qRHpRNkhxaDZFNzNPeTZTUGNNbnciLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjUwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9", # attestation_object_b64 => #"o2NmbXRmcGFja2VkZ2F0dFN0bXSjY2FsZyZjc2lnWEcwRQIgB3c0BvOsyJut14wj4XVWxXliicWZMZLDNF621Zz7h_8CIQCIOqRyWOazVhqlBrD-HL-83KWAvGZRgvW-4A9SE8BLFWN4NWOBWQLBMIICvTCCAaWgAwIBAgIEK_F8eDANBgkqhkiG9w0BAQsFADAuMSwwKgYDVQQDEyNZdWJpY28gVTJGIFJvb3QgQ0EgU2VyaWFsIDQ1NzIwMDYzMTAgFw0xNDA4MDEwMDAwMDBaGA8yMDUwMDkwNDAwMDAwMFowbjELMAkGA1UEBhMCU0UxEjAQBgNVBAoMCVl1YmljbyBBQjEiMCAGA1UECwwZQXV0aGVudGljYXRvciBBdHRlc3RhdGlvbjEnMCUGA1UEAwweWXViaWNvIFUyRiBFRSBTZXJpYWwgNzM3MjQ2MzI4MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEdMLHhCPIcS6bSPJZWGb8cECuTN8H13fVha8Ek5nt-pI8vrSflxb59Vp4bDQlH8jzXj3oW1ZwUDjHC6EnGWB5i6NsMGowIgYJKwYBBAGCxAoCBBUxLjMuNi4xLjQuMS40MTQ4Mi4xLjcwEwYLKwYBBAGC5RwCAQEEBAMCAiQwIQYLKwYBBAGC5RwBAQQEEgQQxe9V_62aS5-1gK3rr-Am0DAMBgNVHRMBAf8EAjAAMA0GCSqGSIb3DQEBCwUAA4IBAQCLbpN2nXhNbunZANJxAn_Cd-S4JuZsObnUiLnLLS0FPWa01TY8F7oJ8bE-aFa4kTe6NQQfi8-yiZrQ8N-JL4f7gNdQPSrH-r3iFd4SvroDe1jaJO4J9LeiFjmRdcVa-5cqNF4G1fPCofvw9W4lKnObuPakr0x_icdVq1MXhYdUtQk6Zr5mBnc4FhN9qi7DXqLHD5G7ZFUmGwfIcD2-0m1f1mwQS8yRD5-_aDCf3vutwddoi3crtivzyromwbKklR4qHunJ75LGZLZA8pJ_mXnUQ6TTsgRqPvPXgQPbSyGMf2z_DIPbQqCD_Bmc4dj9o6LozheBdDtcZCAjSPTAd_uiaGF1dGhEYXRhWOFJlg3liA6MaHQ0Fw9kdmBbj-SuuaKGMseZXPO6gx2XY0EAAAACxe9V_62aS5-1gK3rr-Am0ACAWlHiMqH6UhUs-d43z-aGlE3nsXuEOQpa9P9pwpqb4tmvtBMBfGvAV2wUrqBCDENjkkxd6kIRzZQKcluyOFlyW_vXVZSAEgod1xj-1QmFpuwyBVnlkQGefRbmUjbEt5iE4q3tdjy65EWIekO0SNjCQx3LxIJMzi25fgUkI9Y-gg2kAQEDJyAGIVggnB_oUZDQU0esRlNPmjEO96aMDTgs34D8Dv31tAwhUZo", # ); #diag explain $reg; # U2F $reg = $webauthn->validate_registration( challenge_b64 => "c0WxorWwEToOxlbb5MsDZPWKdNiUhyOJL8s-MIcjI-Q5SFJOnoWe_q2ZhgYKHykv4PGw3L-_plgNBnKgww3dAw", requested_uv => 0, client_data_json_b64 => "eyJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjUwMDAiLCJjaGFsbGVuZ2UiOiJjMFd4b3JXd0VUb094bGJiNU1zRFpQV0tkTmlVaHlPSkw4cy1NSWNqSS1RNVNGSk9ub1dlX3EyWmhnWUtIeWt2NFBHdzNMLV9wbGdOQm5LZ3d3M2RBdyIsInR5cGUiOiJ3ZWJhdXRobi5jcmVhdGUifQ", attestation_object_b64 => "o2NmbXRoZmlkby11MmZnYXR0U3RtdKJjc2lnWEcwRQIgYCbOYmJrEQy_oJqbBpgT_V8DhOUA-Kt3578zKalWyPkCIQDkyAm3YO98SF3AFi5Px1LChUDMLfPzL_p7um8sqxel0GN4NWOBWQQvMIIEKzCCAhOgAwIBAgIBATANBgkqhkiG9w0BAQUFADCBoTEYMBYGA1UEAwwPRklETzIgVEVTVCBST09UMTEwLwYJKoZIhvcNAQkBFiJjb25mb3JtYW5jZS10b29sc0BmaWRvYWxsaWFuY2Uub3JnMRYwFAYDVQQKDA1GSURPIEFsbGlhbmNlMQwwCgYDVQQLDANDV0cxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJNWTESMBAGA1UEBwwJV2FrZWZpZWxkMB4XDTE4MDMxNjE0MzUyN1oXDTI4MDMxMzE0MzUyN1owgawxIzAhBgNVBAMMGkZJRE8yIEJBVENIIEtFWSBwcmltZTI1NnYxMTEwLwYJKoZIhvcNAQkBFiJjb25mb3JtYW5jZS10b29sc0BmaWRvYWxsaWFuY2Uub3JnMRYwFAYDVQQKDA1GSURPIEFsbGlhbmNlMQwwCgYDVQQLDANDV0cxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJNWTESMBAGA1UEBwwJV2FrZWZpZWxkMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAETzpeXqtsH7yul_bfZEmWdix773IAQCp2xvIw9lVvF6qZm1l_xL9Qiq-OnvDNAT9aub0nkUvwgEN4y8yxG4m1RqMsMCowCQYDVR0TBAIwADAdBgNVHQ4EFgQUVk33wPjGVbahH2xNGfO_QeL9AXkwDQYJKoZIhvcNAQEFBQADggIBAI-_jI31FB-8J2XxzBXMuI4Yg-vAtq07ABHJqnQpUmt8lpOzmvJ0COKcwtq_7bpsgSVBJ26zhnyWcm1q8V0ZbxUvN2kH8N7nteIGn-CJOJkHDII-IbiH4-TUQCJjuCB52duUWL0fGVw2R13J6V-K7U5r0OWBzmtmwwiRVTggVbjDpbx2oqGAwzupG3RmBFDX1M92s3tgywnLr-e6NZal5yZdS8VblJGjswDZbdY-Qobo2DCN6vxvn5TVkukAHiArjpBBpAmuQfKa52vqSCYRpTCm57fQUZ1c1n29OsvDw1x9ckyH8j_9Xgk0AG-MlQ9Rdg3hCb7LkSPvC_zYDeS2Cj_yFw6OWahnnIRwO6t4UtLuRAkLrjP1T7nk0zu1whwj7YEwtva45niWWh6rdyg_SZlfsph3o_MZN5DwKaSrUaEO6b-numELH5GWjjiPgfgPKkIof-D40xaKUFBpNJzorQkAZCJWuHvXRpBZWFVh_UhNlGhX0mhz2yFlBrujYa9BgvIkdJ8Keok6qfAn-r5EEFXcSI8vGY7OEF01QKXVpu8-FW0uSxtQ991AcFD6KjvR51l7e61visUgduhZRIq9bYzeCIxnK5Jhm3o_NJE2bOp2NmVwVe4kjuJX87wo3Ba41bXgwIpdiLWyWJhSHPmJI_1ibRTZ5XO92xbPPSnnkXrFaGF1dGhEYXRhWKRJlg3liA6MaHQ0Fw9kdmBbj-SuuaKGMseZXPO6gx2XY0EAAAACAAAAAAAAAAAAAAAAAAAAAAAg2i53XtAuBVv2ztu9hdTkG_I4_zc-MhmYOjM2HWDCIlmlAQIDJiABIVggFgD81bv3uFCOrjw3DfHTIuscQkA7gikvjGdE6ltNPjoiWCA_7nP-fPzwp30E4kLjh4nyMyHQ2tfPJR8lA0h7SQ1dfA" ); is( $reg->{attestation_result}->{success}, 1, "Yubico U2F attestation" ); # Auth ECC key my $val = $webauthn->validate_assertion( challenge_b64 => "xi30GPGAFYRxVDpY1sM10DaLzVQG66nv-_7RUazH0vI2YvG8LYgDEnvN5fZZNVuvEDuMi9te3VLqb42N0fkLGA", credential_pubkey_b64 => "pQECAyYgASFYIIeDTe-gN8A-zQclHoRnGFWN8ehM1b7yAsa8I8KIvmplIlgg4nFGT5px8o6gpPZZhO01wdy9crDSA_Ngtkx0vGpvPHI", stored_sign_count => 10, requested_uv => 1, client_data_json_b64 => "eyJjaGFsbGVuZ2UiOiJ4aTMwR1BHQUZZUnhWRHBZMXNNMTBEYUx6VlFHNjZudi1fN1JVYXpIMHZJMll2RzhMWWdERW52TjVmWlpOVnV2RUR1TWk5dGUzVkxxYjQyTjBma0xHQSIsImNsaWVudEV4dGVuc2lvbnMiOnt9LCJoYXNoQWxnb3JpdGhtIjoiU0hBLTI1NiIsIm9yaWdpbiI6Imh0dHA6Ly9sb2NhbGhvc3Q6NTAwMCIsInR5cGUiOiJ3ZWJhdXRobi5nZXQifQ", authenticator_data_b64 => "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MBAAAATg", signature_b64 => "MEUCIGisVZOBapCWbnJJvjelIzwpixxIwkjCCb5aCHafQu68AiEA88v-2pJNNApPFwAKFiNuf82-2hBxYW5kGwVweeoxCwo", ); is( $val->{success}, 1, "Authentication with ECC key" ); # Auth RSA key my $val = $webauthn->validate_assertion( challenge_b64 => "iPmAi1Pp1XL6oAgq3PWZtZPnZa1zFUDoGbaQ0_KvVG1lF2s3Rt_3o4uSzccy0tmcTIpTTT4BU1T-I4maavndjQ", credential_pubkey_b64 => "pAEDAzkBACBZAQDfV20epzvQP-HtcdDpX-cGzdOxy73WQEvsU7Dnr9UWJophEfpngouvgnRLXaEUn_d8HGkp_HIx8rrpkx4BVs6X_B6ZjhLlezjIdJbLbVeb92BaEsmNn1HW2N9Xj2QM8cH-yx28_vCjf82ahQ9gyAr552Bn96G22n8jqFRQKdVpO-f-bvpvaP3IQ9F5LCX7CUaxptgbog1SFO6FI6ob5SlVVB00lVXsaYg8cIDZxCkkENkGiFPgwEaZ7995SCbiyCpUJbMqToLMgojPkAhWeyktu7TlK6UBWdJMHc3FPAIs0lH_2_2hKS-mGI1uZAFVAfW1X-mzKL0czUm2P1UlUox7IUMBAAE", stored_sign_count => 0, requested_uv => 1, client_data_json_b64 => "eyJ0eXBlIjoid2ViYXV0aG4uZ2V0IiwiY2hhbGxlbmdlIjoiaVBtQWkxUHAxWEw2b0FncTNQV1p0WlBuWmExekZVRG9HYmFRMF9LdlZHMWxGMnMzUnRfM280dVN6Y2N5MHRtY1RJcFRUVDRCVTFULUk0bWFhdm5kalEiLCJvcmlnaW4iOiJodHRwOi8vbG9jYWxob3N0OjUwMDAiLCJjcm9zc09yaWdpbiI6ZmFsc2V9", authenticator_data_b64 => "SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MFAAAAAQ", signature_b64 => "iOHKX3erU5_OYP_r_9HLZ-CexCE4bQRrxM8WmuoKTDdhAnZSeTP0sjECjvjfeS8MJzN1ArmvV0H0C3yy_FdRFfcpUPZzdZ7bBcmPh1XPdxRwY747OrIzcTLTFQUPdn1U-izCZtP_78VGw9pCpdMsv4CUzZdJbEcRtQuRS03qUjqDaovoJhOqEBmxJn9Wu8tBi_Qx7A33RbYjlfyLm_EDqimzDZhyietyop6XUcpKarKqVH0M6mMrM5zTjp8xf3W7odFCadXEJg-ERZqFM0-9Uup6kJNLbr6C5J4NDYmSm3HCSA6lp2iEiMPKU8Ii7QZ61kybXLxsX4w4Dm3fOLjmDw", ); is( $val->{success}, 1, "Authentication with RSA key" ); done_testing(); Authen000755001750001750 014176453400 16311 5ustar00maxbesmaxbes000000000000Authen-WebAuthn-0.001/libWebAuthn.pm100644001750001750 7707314176453400 20562 0ustar00maxbesmaxbes000000000000Authen-WebAuthn-0.001/lib/Authenpackage Authen::WebAuthn; $Authen::WebAuthn::VERSION = '0.001'; use strict; use warnings; use Mouse; use MIME::Base64 qw(encode_base64url decode_base64url); use JSON qw(decode_json from_json to_json); use Digest::SHA qw(sha256); use Crypt::PK::ECC; use Crypt::PK::RSA; use Crypt::OpenSSL::X509; use CBOR::XS; use URI; use Carp; has rp_id => ( is => 'rw', required => 1 ); has origin => ( is => 'rw', required => 1 ); my $ATTESTATION_FUNCTIONS = { none => \&attest_none, packed => \&attest_packed, "fido-u2f" => \&attest_u2f, }; my $KEY_TYPES = { ECC => { parse_pem => \&parse_ecc_pem, parse_cose => \&parse_ecc_cose, make_verifier => \&make_cryptx_verifier, }, RSA => { parse_pem => \&parse_rsa_pem, parse_cose => \&parse_rsa_cose, make_verifier => \&make_cryptx_verifier, } }; my $COSE_ALG = { -7 => { name => "ES256", key_type => "ECC", signature_options => ["SHA256"] }, -257 => { name => "RS256", key_type => "RSA", signature_options => [ "SHA256", "v1.5" ] }, -37 => { name => "PS256", key_type => "RSA", signature_options => [ "SHA256", "pss" ] }, -65535 => { name => "RS1", key_type => "RSA", signature_options => [ "SHA1", "v1.5" ] } }; sub validate_registration { my ( $self, %params ) = @_; my ( $challenge_b64, $requested_uv, $client_data_json_b64, $attestation_object_b64, $token_binding_id_b64 ) = @params{ qw( challenge_b64 requested_uv client_data_json_b64 attestation_object_b64 token_binding_id_b64 ) }; my $client_data_json = decode_base64url($client_data_json_b64); my $client_data = eval { decode_json($client_data_json) }; if ($@) { croak("Error deserializing client data: $@"); } # 7. Verify that the value of C.type is webauthn.create unless ( $client_data->{type} eq "webauthn.create" ) { croak("Type is not webauthn.create"); } # 8. Verify that the value of C.challenge equals the base64url encoding # of options.challenge. unless ($challenge_b64) { croak("Empty registration challenge"); } unless ( $challenge_b64 eq $client_data->{challenge} ) { croak( "Challenge received from client data " . "($client_data->{challenge}) " . "does not match server challenge " . "($challenge_b64)" ); } # 9. Verify that the value of C.origin matches the Relying Party's origin. unless ( $client_data->{origin} ) { croak("Empty origin in client data"); } unless ( $client_data->{origin} eq $self->origin ) { croak( "Origin received from client data " . "($client_data->{origin}) " . "does not match server origin " . "(" . $self->origin . ")" ); } # 10. Verify that the value of C.tokenBinding.status matches the state of # Token Binding for the TLS connection over which the assertion was # obtained. If Token Binding was used on that TLS connection, also verify # that C.tokenBinding.id matches the base64url encoding of the Token # Binding ID for the connection. $self->check_token_binding( $client_data->{tokenBinding}, $token_binding_id_b64 ); # 11. Let hash be the result of computing a hash over # response.clientDataJSON using SHA-256. my $client_data_hash = sha256($client_data_json); # 12. Perform CBOR decoding on the attestationObject field of the # AuthenticatorAttestationResponse structure to obtain the attestation # statement format fmt, the authenticator data authData, and the # attestation statement attStmt. my $attestation_object = getAttestationObject($attestation_object_b64); my $authenticator_data = $attestation_object->{authData}; unless ($authenticator_data) { croak("Authenticator data not found in attestation object"); } unless ( $authenticator_data->{attestedCredentialData} ) { croak("Attested credential data not found in authenticator data"); } # 13. Verify that the rpIdHash in authData is the SHA-256 hash of the RP ID # expected by the Relying Party. my $hash_rp_id = sha256( $self->rp_id ); unless ( $authenticator_data->{rpIdHash} eq $hash_rp_id ) { croak( "RP ID hash received from authenticator " . "(" . unpack( "H*", $authenticator_data->{rpIdHash} ) . ") " . "does not match the hash of this RP ID " . "(" . unpack( "H*", $hash_rp_id ) . ")" ); } # 14. Verify that the User Present bit of the flags in authData is set. unless ( $authenticator_data->{flags}->{userPresent} == 1 ) { croak("User not present during WebAuthn registration"); } # 15. If user verification is required for this registration, verify that # the User Verified bit of the flags in authData is set. $requested_uv ||= "preferred"; if ( $requested_uv eq "required" and $authenticator_data->{flags}->{userVerified} != 1 ) { croak("User not verified during WebAuthn registration"); } # 16. Verify that the "alg" parameter in the credential public key in # authData matches the alg attribute of one of the items in # options.pubKeyCredParams. # TODO For now, allow all known key types # 17. Verify that the values of the client extension outputs in # clientExtensionResults and the authenticator extension outputs in the # extensions in authData are as expected # TODO # 18. Determine the attestation statement format by performing a USASCII # case-sensitive match on fmt against the set of supported WebAuthn # Attestation Statement Format Identifier values. my $attestation_statement_format = $attestation_object->{'fmt'}; my $attestation_function = $ATTESTATION_FUNCTIONS->{$attestation_statement_format}; unless ( ref($attestation_function) eq "CODE" ) { croak( "Unsupported attestation format during WebAuthn registration: " . $attestation_statement_format ); } # 19. Verify that attStmt is a correct attestation statement, conveying a # valid attestation signature, by using the attestation statement format # fmt’s verification procedure given attStmt, authData and hash. my $attestation_statement = $attestation_object->{attStmt}; my $authenticator_data_raw = $attestation_object->{authDataRaw}; my $attestation_result = eval { $attestation_function->( $attestation_statement, $authenticator_data, $authenticator_data_raw, $client_data_hash ); }; croak( "Failed to validate attestation: " . $@ ) if ($@); unless ( $attestation_result->{success} == 1 ) { croak( "Failed to validate attestation: " . $attestation_result->{error} ); } # 20. If validation is successful, obtain a list of acceptable trust # anchors (i.e. attestation root certificates) for that attestation type # and attestation statement format fmt, from a trusted source or from # policy. # TODO # 21. Assess the attestation trustworthiness using the outputs of the # verification procedure in step 19, as follows: # TODO # 22. Check that the credentialId is not yet registered to any other user # TODO # 23. If the attestation statement attStmt verified successfully and is # found to be trustworthy, then register the new credential with the # account that was denoted in options.user: my $credential_id_bin = $authenticator_data->{attestedCredentialData}->{credentialId}; my $credential_pubkey_cose = $authenticator_data->{attestedCredentialData}->{credentialPublicKey}; my $signature_count = $authenticator_data->{signCount}; return { credential_id => encode_base64url($credential_id_bin), credential_pubkey => encode_base64url($credential_pubkey_cose), signature_count => $signature_count, attestation_result => $attestation_result }; } sub validate_assertion { my ( $self, %params ) = @_; my ( $challenge_b64, $credential_pubkey_b64, $stored_sign_count, $requested_uv, $client_data_json_b64, $authenticator_data_b64, $signature_b64, $extension_results, $token_binding_id_b64, ) = @params{ qw(challenge_b64 credential_pubkey_b64 stored_sign_count requested_uv client_data_json_b64 authenticator_data_b64 signature_b64 extension_results token_binding_id_b64) }; # 7. Using credential.id (or credential.rawId, if base64url encoding is # inappropriate for your use case), look up the corresponding credential # public key and let credentialPublicKey be that credential public key. my $credential_verifier = eval { getPubKeyVerifier( decode_base64url($credential_pubkey_b64) ) }; croak "Cannot get signature validator for assertion: $@" if ($@); # 8. Let cData, authData and sig denote the value of response’s # clientDataJSON, authenticatorData, and signature respectively. my $client_data_json = decode_base64url($client_data_json_b64); my $authenticator_data_raw = decode_base64url($authenticator_data_b64); my $authenticator_data = getAuthData($authenticator_data_raw); my $signature = decode_base64url($signature_b64); # 9. Let JSONtext be the result of running UTF-8 decode on the value of # cData. # 10. Let C, the client data claimed as used for the signature, be the # result of running an implementation-specific JSON parser on JSONtext. my $client_data = eval { decode_json($client_data_json) }; if ($@) { croak("Error deserializing client data: $@"); } # 11. Verify that the value of C.type is the string webauthn.get. unless ( $client_data->{type} eq "webauthn.get" ) { croak("Type is not webauthn.get"); } # 12. Verify that the value of C.challenge equals the base64url encoding of # options.challenge. unless ($challenge_b64) { croak("Empty registration challenge"); } unless ( $challenge_b64 eq $client_data->{challenge} ) { croak( "Challenge received from client data " . "($client_data->{challenge}) " . "does not match server challenge " . "($challenge_b64)" ); } # 13. Verify that the value of C.origin matches the Relying Party's origin. unless ( $client_data->{origin} ) { croak("Empty origin"); } unless ( $client_data->{origin} eq $self->origin ) { croak( "Origin received from client data " . "($client_data->{origin}) " . "does not match server origin " . "(" . $self->origin . ")" ); } # 14. Verify that the value of C.tokenBinding.status matches the state of # Token Binding for the TLS connection over which the attestation was # obtained. If Token Binding was used on that TLS connection, also verify # that C.tokenBinding.id matches the base64url encoding of the Token # Binding ID for the connection. $self->check_token_binding( $client_data->{tokenBinding}, $token_binding_id_b64 ); # 15. Verify that the rpIdHash in authData is the SHA-256 hash of the RP ID # expected by the Relying Party. # If using the appid extension, this step needs some special logic. See # § 10.1 FIDO AppID Extension (appid) for details. my $hash_rp_id; if ( $extension_results->{appid} ) { $hash_rp_id = sha256( $self->origin ); } else { $hash_rp_id = sha256( $self->rp_id ); } unless ( $authenticator_data->{rpIdHash} eq $hash_rp_id ) { croak( "RP ID hash received from authenticator " . "(" . unpack( "H*", $authenticator_data->{rpIdHash} ) . ") " . "does not match the hash of this RP ID " . "(" . unpack( "H*", $hash_rp_id ) . ")" ); } # 16. Verify that the User Present bit of the flags in authData is set. unless ( $authenticator_data->{flags}->{userPresent} == 1 ) { croak("User not present during WebAuthn authentication"); } # 17. If user verification is required for this assertion, verify that the # User Verified bit of the flags in authData is set. $requested_uv ||= "preferred"; if ( $requested_uv eq "required" and $authenticator_data->{flags}->{userVerified} != 1 ) { croak("User not verified during WebAuthn authentication"); } # 18. Verify that the values of the client extension outputs in # clientExtensionResults and the authenticator extension outputs in the # extensions in authData are as expected, # TODO # 19. Let hash be the result of computing a hash over the cData using # SHA-256. my $client_data_hash = sha256($client_data_json); # 20. Using credentialPublicKey, verify that sig is a valid signature over # the binary concatenation of authData and hash. my $to_sign = $authenticator_data_raw . $client_data_hash; unless ( $credential_verifier->( $signature, $to_sign ) ) { croak("Webauthn signature was not valid"); } # 21. Let storedSignCount be the stored signature counter value associated # with credential.id. If authData.signCount is nonzero or storedSignCount # is nonzero, then run the following sub-step: $stored_sign_count //= 0; my $signature_count = $authenticator_data->{signCount}; if ( $signature_count > 0 or $stored_sign_count > 0 ) { if ( $signature_count <= $stored_sign_count ) { croak( "Stored signature count $stored_sign_count " . "higher than device signature count $signature_count" ); } } return { success => 1, signature_count => $signature_count, }; } sub _ecc_obj_to_cose { my ($key) = @_; $key = $key->key2hash; unless ( $key->{curve_name} eq "secp256r1" ) { croak "Invalid ECC curve: " . $key->{curve_name}; } # We want to be compatible with old CBOR::XS versions that don't have as_map # The correct code should be #return encode_cbor CBOR::XS::as_map [ # 1 => 2, # 3 => -7, # -1 => 1, # -2 => pack( "H*", $key->{pub_x} ), # -3 => pack( "H*", $key->{pub_y} ), #]; # Manually encode the COSE key return "\xa5" . #Map of 5 items "\x01\x02" . # kty => EC2 "\x03\x26" . # alg => ES256 "\x20\x01" . # crv => P-256 "\x21" . # x => "\x58\x20" . pack( "H*", $key->{pub_x} ) . # x coordinate as a bstr "\x22" . # y => "\x58\x20" . pack( "H*", $key->{pub_y} ) # y coordinate as a bstr ; } # This function converts public keys from U2F format to COSE format. It can be useful # for applications who want to migrate existing U2F registrations sub convert_raw_ecc_to_cose { my ($raw_ecc_b64) = @_; my $key = Crypt::PK::ECC->new; $key->import_key_raw( decode_base64url($raw_ecc_b64), "secp256r1" ); return encode_base64url( _ecc_obj_to_cose($key) ); } # Check Token Binding in client data against Token Binding in incoming TLS # connection. This only works if the web server supports it. sub check_token_binding { my ( $self, $client_data_token_binding, $connection_tbid_b64 ) = @_; $connection_tbid_b64 //= ""; # Token binding is not used if ( ref($client_data_token_binding) ne "HASH" ) { return; } my $token_binding_status = $client_data_token_binding->{status}; if ( $token_binding_status eq "present" ) { my $client_data_cbid_b64 = $client_data_token_binding->{id}; # Token binding is in use: the "id" field must be present and must # match the connection's Token Binding ID if ($client_data_cbid_b64) { if ( $client_data_cbid_b64 eq $connection_tbid_b64 ) { # All is well return; } else { croak "The Token Binding ID from the current connection " . "($connection_tbid_b64) " . "does not match Token Binding ID in client data " . "($client_data_cbid_b64)"; } } else { croak "Missing tokenBinding.id in client data " . "while tokenBinding.status == present"; } } else { # Token binding "supported" but not used, or unknown/missing value return; } } # Used by u2f assertion types sub _getU2FKeyFromCose { my ($cose_key) = @_; $cose_key = decode_cbor($cose_key); # TODO: do we need to support more algs? croak( "Unexpected COSE Alg: " . $cose_key->{3} ) unless ( $COSE_ALG->{ $cose_key->{3} }->{name} eq "ES256" ); my $pk = parse_ecc_cose($cose_key); return $pk->export_key_raw('public'); } sub parse_ecc_cose { my ($cose_struct) = @_; my $curve = $cose_struct->{-1}; my $x = $cose_struct->{-2}; my $y = $cose_struct->{-3}; my $id_to_curve = { 1 => 'secp256r1', }; my $pk = Crypt::PK::ECC->new(); my $curve_name = $id_to_curve->{$curve}; unless ($curve_name) { croak "Unsupported curve $curve"; } $pk->import_key( { curve_name => $curve_name, pub_x => unpack( "H*", $x ), pub_y => unpack( "H*", $y ), } ); return $pk; } # This generic method generates a two-argument signature method from # the public key (RSA, ECC, etc.) and signature options from the COSE_ALG hash sub make_cryptx_verifier { my ( $public_key, @signature_options ) = @_; return sub { my ( $signature, $message ) = @_; return $public_key->verify_message( $signature, $message, @signature_options ); }; } sub parse_ecc_pem { my ($pem) = @_; my $pk = Crypt::PK::ECC->new(); $pk->import_key( \$pem ); return $pk; } sub parse_rsa_pem { my ($pem) = @_; my $pk = Crypt::PK::RSA->new(); $pk->import_key( \$pem ); return $pk; } sub parse_rsa_cose { my ($cose_struct) = @_; my $n = $cose_struct->{-1}; my $e = $cose_struct->{-2}; my $pk = Crypt::PK::RSA->new(); $pk->import_key( { N => unpack( "H*", $n ), e => unpack( "H*", $e ), } ); return $pk; } # This function returns a verification method that is used like this: # verifier->($signature, $message) returns 1 iff the message matches the # signature # Arguments are the COSE alg number from # https://www.iana.org/assignments/cose/cose.xhtml#algorithms # some key data, and the name of the function that converts the key data into a # CryptX key (in KEY_TYPE array) sub get_verifier_for_alg { my ( $alg_num, $key_data, $parse_method ) = @_; my $alg_config = $COSE_ALG->{$alg_num}; unless ($alg_config) { croak "Unsupported algorithm $alg_num"; } my $key_type = $alg_config->{key_type}; my $key_type_config = $KEY_TYPES->{$key_type}; unless ($key_type_config) { croak "Unsupported key type $key_type"; } # Get key conversion function my $key_function = $key_type_config->{$parse_method}; unless ( ref($key_function) eq "CODE" ) { croak "No conversion method named $parse_method for key type $key_type"; } # Get key my $public_key = $key_function->($key_data); unless ($public_key) { croak "Could not parse public key"; } my @signature_options = @{ $alg_config->{signature_options} }; return $key_type_config->{make_verifier} ->( $public_key, @signature_options ); } # This function takes a Base64url encoded COSE key and returns a verification # method sub getPubKeyVerifier { my ($pubkey_cose) = @_; my $cose_key = decode_cbor($pubkey_cose); my $alg_num = $cose_key->{3}; return get_verifier_for_alg( $alg_num, $cose_key, "parse_cose" ); } # Same, but input is a PEM and a COSE alg name (used in assertion validation) sub getPEMPubKeyVerifier { my ( $pem, $alg_num ) = @_; return get_verifier_for_alg( $alg_num, $pem, "parse_pem" ); } sub getCoseAlgAndLength { my ($cbor_raw) = @_; my ( $cbor, $length ) = CBOR::XS->new->decode_prefix($cbor_raw); my $alg_num = $cbor->{3}; my $alg = $COSE_ALG->{$alg_num}->{name}; if ($alg) { return ( $alg, $length ); } else { croak "Unsupported algorithm $alg_num"; } } # Transform binary AAGUID into string representation sub formatAaguid { my ($aaguid) = @_; if ( length($aaguid) == 16 ) { return lc join "-", unpack( "H*", substr( $aaguid, 0, 4 ) ), unpack( "H*", substr( $aaguid, 4, 2 ) ), unpack( "H*", substr( $aaguid, 6, 2 ) ), unpack( "H*", substr( $aaguid, 8, 2 ) ), unpack( "H*", substr( $aaguid, 10, 6 ) ), ; } else { croak "Invalid AAGUID length"; } } sub getAttestedCredentialData { my ($attestedCredentialData) = @_; check_length( $attestedCredentialData, "Attested credential data", 18 ); my $res = {}; my $aaguid = formatAaguid( substr( $attestedCredentialData, 0, 16 ) ); $res->{aaguid} = $aaguid; $res->{credentialIdLength} = unpack( 'n', substr( $attestedCredentialData, 16, 2 ) ); $res->{credentialId} = substr( $attestedCredentialData, 18, $res->{credentialIdLength} ); my ( $cose_alg, $length_cbor_pubkey ) = getCoseAlgAndLength( substr( $attestedCredentialData, 18 + $res->{credentialIdLength} ) ); $res->{credentialPublicKeyAlg} = $cose_alg; $res->{credentialPublicKey} = substr( $attestedCredentialData, 18 + $res->{credentialIdLength}, $length_cbor_pubkey ); $res->{credentialPublicKeyLength} = $length_cbor_pubkey; return $res; } sub check_length { my ( $data, $name, $expected_len ) = @_; my $len = length($data); if ( $len < $expected_len ) { croak("$name has incorrect length $len (min: $expected_len)"); } } sub getAuthData { my ($ad) = @_; my $res = {}; check_length( $ad, "Authenticator data", 37 ); $res->{rpIdHash} = substr( $ad, 0, 32 ); $res->{flags} = resolveFlags( unpack( 'C', substr( $ad, 32, 1 ) ) ); $res->{signCount} = unpack( 'N', substr( $ad, 33, 4 ) ); my $attestedCredentialDataLength = 0; if ( $res->{flags}->{atIncluded} ) { my $attestedCredentialData = getAttestedCredentialData( substr( $ad, 37 ) ); $res->{attestedCredentialData} = $attestedCredentialData; $attestedCredentialDataLength = 18 + $attestedCredentialData->{credentialIdLength} + $attestedCredentialData->{credentialPublicKeyLength}; } if ( $res->{flags}->{edIncluded} ) { my $ext = substr( $ad, 37 + $attestedCredentialDataLength ); if ($ext) { $res->{extensions} = decode_cbor($ext); } } else { # Check for trailing bytes croak("Trailing bytes in authenticator data") if ( length($ad) > ( 37 + $attestedCredentialDataLength ) ); } return $res; } sub resolveFlags { my ($bits) = @_; return { userPresent => ( ( $bits & 1 ) == 1 ), userVerified => ( ( $bits & 4 ) == 4 ), atIncluded => ( ( $bits & 64 ) == 64 ), edIncluded => ( ( $bits & 128 ) == 128 ), }; } sub getAttestationObject { my ($dat) = @_; my $decoded = decode_base64url($dat); my $res = {}; my $h = decode_cbor($decoded); $res->{authData} = getAuthData( $h->{authData} ); $res->{authDataRaw} = $h->{authData}; $res->{attStmt} = $h->{attStmt}; $res->{fmt} = $h->{fmt}; return $res; } # https://www.w3.org/TR/webauthn-2/#sctn-none-attestation sub attest_none { my ( $attestation_statement, $auhenticator_data, $authenticator_data_raw, $client_data_hash ) = @_; return { success => 1, type => "None", trust_path => [], }; } # https://www.w3.org/TR/webauthn-2/#sctn-packed-attestation sub attest_packed { my ( $attestation_statement, $authenticator_data, $authenticator_data_raw, $client_data_hash ) = @_; # Verify that attStmt is valid CBOR conforming to the syntax defined above # and perform CBOR decoding on it to extract the contained fields. croak "Missing algorithm field in attestation statement" unless ( $attestation_statement->{alg} ); croak "Missing signature field in attestation statement" unless ( $attestation_statement->{sig} ); my $signed_value = $authenticator_data_raw . $client_data_hash; #If x5c is present: if ( $attestation_statement->{x5c} ) { return attest_packed_x5c( $attestation_statement, $authenticator_data, $signed_value ); #If x5c is not present, self attestation is in use. } else { return attest_packed_self( $attestation_statement, $authenticator_data, $signed_value ); } } sub attest_packed_x5c { my ( $attestation_statement, $authenticator_data, $signed_value ) = @_; my $x5c_der = $attestation_statement->{x5c}->[0]; my $sig_alg = $attestation_statement->{alg}; my $sig = $attestation_statement->{sig}; my ( $x5c, $key, $key_alg ); eval { $x5c = Crypt::OpenSSL::X509->new_from_string( $x5c_der, Crypt::OpenSSL::X509::FORMAT_ASN1 ); $key = $x5c->pubkey(); }; croak "Cannot extract public key from attestation certificate: $@" if ($@); # Verify that sig is a valid signature over the concatenation of # authenticatorData and clientDataHash using the attestation public key in # attestnCert with the algorithm specified in alg. my $attestation_verifier = eval { getPEMPubKeyVerifier( $key, $sig_alg ) }; croak "Cannot get signature validator for attestation: $@" if ($@); # Verify that attestnCert meets the requirements in § 8.2.1 Packed # Attestation Statement Certificate Requirements. # TODO # If attestnCert contains an extension with OID 1.3.6.1.4.1.45724.1.1.4 # (id-fido-gen-ce-aaguid) verify that the value of this extension matches # the aaguid in authenticatorData. # TODO # Optionally, inspect x5c and consult externally provided knowledge to # determine whether attStmt conveys a Basic or AttCA attestation. # TODO # If successful, return implementation-specific values representing # attestation type Basic, AttCA or uncertainty, and attestation trust path # x5c. if ( $attestation_verifier->( $sig, $signed_value ) ) { return { success => 1, type => "Unsure", trust_path => $attestation_statement->{x5c}, }; } else { croak "Invalid attestation signature"; } } sub attest_packed_self { my ( $attestation_statement, $authenticator_data, $signed_value ) = @_; my $sig = $attestation_statement->{sig}; my $sign_alg_num = $attestation_statement->{alg}; my $cose_key = $authenticator_data->{attestedCredentialData}->{credentialPublicKey}; # Validate that alg matches the algorithm of the credentialPublicKey in # authenticatorData. my $cose_alg = $authenticator_data->{attestedCredentialData}->{credentialPublicKeyAlg}; my $sign_alg = $COSE_ALG->{$sign_alg_num}->{name}; croak "Unknown key type in attestation data: $sign_alg_num" unless ($sign_alg); unless ( $sign_alg eq $cose_alg ) { croak "Attestation algorithm $sign_alg does not match " . "credential key type $cose_alg"; } # Verify that sig is a valid signature over the concatenation of # authenticatorData and clientDataHash using the credential public key with # alg. my $credential_verifier = eval { getPubKeyVerifier($cose_key) }; croak "Cannot get signature validator for attestation: $@" if ($@); # If successful, return implementation-specific values representing # attestation type Self and an empty attestation trust path. if ( $credential_verifier->( $sig, $signed_value ) ) { return { success => 1, type => "Self", trust_path => [], }; } else { croak "Invalid attestation signature"; } } # https://www.w3.org/TR/webauthn-2/#sctn-fido-u2f-attestation sub attest_u2f { my ( $attestation_statement, $authenticator_data, $authenticator_data_raw, $client_data_hash ) = @_; # 1. Verify that attStmt is valid CBOR conforming to the syntax defined above # and perform CBOR decoding on it to extract the contained fields. croak "Missing signature field in attestation statement" unless ( $attestation_statement->{sig} ); my $sig = $attestation_statement->{sig}; # 2. Check that x5c has exactly one element and let attCert be that # element. Let certificate public key be the public key conveyed by # attCert. If certificate public key is not an Elliptic Curve (EC) public # key over the P-256 curve, terminate this algorithm and return an # appropriate error. unless ($attestation_statement->{x5c} and ref( $attestation_statement->{x5c} ) eq "ARRAY" and $attestation_statement->{x5c}->[0] ) { croak "Missing certificate field in attestation statement"; } my $x5c_der = $attestation_statement->{x5c}->[0]; my $attestation_key = Crypt::PK::ECC->new(); eval { my $x5c = Crypt::OpenSSL::X509->new_from_string( $x5c_der, Crypt::OpenSSL::X509::FORMAT_ASN1 ); my $key_pem = $x5c->pubkey(); $attestation_key->import_key( \$key_pem ); }; croak "Could not extract ECC key from attestation certificate: $@" if ($@); if ( $attestation_key->key2hash->{curve_name} ne "secp256r1" ) { croak "Invalid attestation certificate curve name: " . $attestation_key->key2hash->{curve_name}; } # 3. Extract the claimed rpIdHash from authenticatorData, and the claimed # credentialId and credentialPublicKey from # authenticatorData.attestedCredentialData. my $rp_id_hash = $authenticator_data->{rpIdHash}; my $credential_id = $authenticator_data->{attestedCredentialData}->{credentialId}; my $credential_public_key = $authenticator_data->{attestedCredentialData}->{credentialPublicKey}; # 4.Convert the COSE_KEY formatted credentialPublicKey (see Section 7 of # [RFC8152]) to Raw ANSI X9.62 public key format my $public_u2f_key = eval { _getU2FKeyFromCose($credential_public_key) }; croak "Could not convert attested credential to U2F key: $@" if ($@); # 5.Let verificationData be the concatenation of (0x00 || rpIdHash || # clientDataHash || credentialId || publicKeyU2F) my $verification_data = "\x00" . $rp_id_hash . $client_data_hash . $credential_id . $public_u2f_key; if ( $attestation_key->verify_message( $sig, $verification_data, "SHA256" ) ) { return { success => 1, type => "Unsure", trust_path => $attestation_statement->{x5c}, }; } else { croak "Signature verification failed"; } } 1; __END__ =pod =encoding UTF-8 =head1 NAME Authen::WebAuthn =head1 VERSION version 0.001 =head1 AUTHOR Maxime Besson =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2022 by Maxime Besson. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut WebAuthn.pod100644001750001750 1525214176453400 20717 0ustar00maxbesmaxbes000000000000Authen-WebAuthn-0.001/lib/Authen# PODNAME: Authen::WebAuthn # ABSTRACT: A library to add Web Authentication support to server applications __END__ =pod =encoding UTF-8 =head1 NAME Authen::WebAuthn - A library to add Web Authentication support to server applications =head1 VERSION version 0.001 =head1 SYNOPSIS This module lets you validate WebAuthn registration and authentication responses. Currently, it does not handle the generation of registration and authentication requests. The transmission of requests and responses from the application server to the user's browser, and interaction with the WebAuthn browser API is also out of scope and could be handled by a dedicated JS library. To register a new device: # Obtain registration response from web browser # Then, my $webauthn_rp = Authen::WebAuthn->new( rp_id => "app.example.com", origin => "https://app.example.com" ); my $registration_result = eval { $webauthn_rp->validate_registration( challenge_b64 => ... , requested_uv => ... , client_data_json_b64 => ... , attestation_object_b64 => ... , token_binding_id_b64 => ... , ) }; if ($@) { die "Error validating registration: $@"; } To authenticate a user: # Obtain authentication response from web browser # Then, my $webauthn_rp = Authen::WebAuthn->new( rp_id => "app.example.com", origin => "https://app.example.com" ); my $validation_result = eval { $webauthn_rp->validate_assertion( challenge_b64 => ..., credential_pubkey_b64 => ..., stored_sign_count => ..., requested_uv => ..., client_data_json_b64 => ..., authenticator_data_b64 => ..., signature_b64 => ..., extension_results => ..., token_binding_id_b64 => ..., ) }; if ($@) { die "Error validating authentication: $@"; } =head1 ATTRIBUTES =head2 rp_id The identifier of your Relying Party. Usually, this is set to the domain name over which your application is accessed (app.example.com). =head2 origin The origin, as defined by the HTML standard, that your Relying Party is expecting to find in registration or authentication responses. This must contain the scheme and port of your application, but no path (http://app.example.com:8080 or https://app.example.com) =head1 METHODS =head2 validate_registration This method validates the registration response emitted by the authenticator. It takes the following named arguments =over 4 =item challenge_b64 The base64url-encoded challenge that was submitted to the authenticator =item requested_uv Whether or not the Relying Party required user verification for this operation. Possible values are C, C, C. =item client_data_json_b64 The base64url-encoded client data received from the authenticator =item attestation_object_b64 The base64url-encoded attestation object received from the authenticator =item token_binding_id_b64 The base64url-encoded Token Binding ID for the current connection. Usually this comes from a C HTTP header. If you are not using Token Binding, you can omit this parameter. =back This method croaks on errors. If the registration was successful, it returns a hashref with the following subkeys: =over 4 =item credential_id The base64url-encoded credential ID for this authenticator =item credential_pubkey The base64url-encoded public key for this authenticator, in COSE format =item signature_count The initial signature count of this authenticator =back This information is supposed to be persisted in the Relying Party, usually in some sort of database =head2 validate_assertion This method validates the registration response emitted by the authenticator. It takes the following named arguments =over 4 =item challenge_b64 The base64url-encoded challenge that was submitted to the authenticator =item credential_pubkey_b64 The base64url-encoded credential public key corresponding to the received Credential ID =item stored_sign_count The current signature count in the Relying Party's database. Set it to 0 to disable verification of the signature count =item requested_uv Whether or not the Relying Party required user verification for this operation. Possible values are C, C, C. =item client_data_json_b64 The base64url-encoded client data received from the authenticator =item authenticator_data_b64 The base64url-encoded authenticator data received from the authenticator =item signature_b64 The base64url-encoded signature received from the authenticator =item extension_results A hashref containing extension results received from the authenticator =item token_binding_id_b64 The base64url-encoded Token Binding ID for the current connection. Usually this comes from a C HTTP header. If you are not using Token Binding, you can omit this parameter. =back This method croaks on errors. If the registration was successful, it returns a hashref with the following subkeys: =over 4 =item signature_count The new signature count, to be updated in the Relying Party's database =back =head2 convert_raw_ecc_to_cose my $cose_b64 = Authen::WebAuthn::convert_raw_ecc_to_cose($u2f_b64); This method takes the base64url-encoded raw ECC key (U2F format) and converts it to a base64url-encoded COSE representation. It can be useful for converting existing U2F device registration to WebAuthen device registrations in your Relying Party. =head1 CAVEAT This module only supports the "None" attestation type at the moment, which means Relying Parties cannot have a strong guarantee of the authenticator's security properties. This makes it possible for users to register weak authenticators. Because of that, is it not recommended to use this module in passwordless authentication scenarios. However, it should be good enough for using security keys as a second factor. This limitation may be addressed in a future version. =head1 SEE ALSO =over 4 =item L A library with a similar purpose, based on Yubico's libfido2 =item L A library for adding U2F support to server applications =item L A library for adding U2F support to server applications, based on Yubico's libu2f-server =back =head1 AUTHOR Maxime Besson =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2022 by Maxime Besson. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut WebAuthn000755001750001750 014176453400 20026 5ustar00maxbesmaxbes000000000000Authen-WebAuthn-0.001/lib/AuthenTest.pm100644001750001750 1765414176453400 21500 0ustar00maxbesmaxbes000000000000Authen-WebAuthn-0.001/lib/Authen/WebAuthnpackage Authen::WebAuthn::Test; $Authen::WebAuthn::Test::VERSION = '0.001'; use Mouse; use CBOR::XS; use MIME::Base64 qw(encode_base64url decode_base64url); use Digest::SHA qw(sha256); use Crypt::PK::ECC; use Hash::Merge::Simple qw/merge/; use JSON qw(encode_json decode_json); use Authen::WebAuthn; use utf8; has origin => ( is => 'rw' ); has rp_id => ( is => 'rw', lazy => 1, default => sub { $_[0]->origin } ); has credential_id => ( is => 'rw' ); has aaguid => ( is => 'rw' ); has key => ( is => 'rw' ); has sign_count => ( is => 'rw', default => 0 ); use constant { FLAG_UP => 1, FLAG_UV => 4, FLAG_AT => 64, FLAG_ED => 128, }; sub makeAttestedCredentialData { my ($acd) = @_; return '' unless ($acd); my $aaguid = exportAaguid( $acd->{aaguid} ); my $credentialIdLength = pack( 'n', length( $acd->{credentialId} ) ); my $credentialId = $acd->{credentialId}; my $credentialPublicKey = $acd->{credentialPublicKey}; my $attestedCredentialData = ( $aaguid . $credentialIdLength . $credentialId . $credentialPublicKey ); return $attestedCredentialData; } sub makeAuthData { my ($authdata) = @_; my $rpIdHash = $authdata->{rpIdHash}; my $flags = pack( 'C', makeFlags( $authdata->{flags} ) ); my $signCount = pack( 'N', $authdata->{signCount} ); my $acd = makeAttestedCredentialData( $authdata->{attestedCredentialData} ); my $ed = $authdata->{extensions} ? encode_cbor( $authdata->{extensions} ) : ''; my $res = $rpIdHash . $flags . $signCount . $acd . $ed; return $res; } sub makeAttestationObject { my ($dat) = @_; my $attestationObject = { 'fmt' => $dat->{fmt}, 'authData' => makeAuthData( $dat->{authData} ), 'attStmt' => {} # TODO }; my $cbor = CBOR::XS->new; $cbor->text_keys(1); return $cbor->encode($attestationObject); } sub makeFlags { my ($flags) = @_; my $up = $flags->{userPresent} ? 1 : 0; my $uv = $flags->{userVerified} ? 1 : 0; my $at = $flags->{atIncluded} ? 1 : 0; my $ed = $flags->{edIncluded} ? 1 : 0; return ( FLAG_UP * $up + FLAG_UV * $uv + FLAG_AT * $at + FLAG_ED * $ed ); } # Transform string GUID into binary sub exportAaguid { my ($aaguid) = @_; $aaguid =~ s/-//g; if ( length($aaguid) == 32 ) { return pack( 'H*', $aaguid ); } else { die "Invalid AAGUID length"; } } sub encode_credential { my ( $self, $credential ) = @_; # Encode clientDataJSON if ( $credential->{response}->{clientDataJSON} ) { $credential->{response}->{clientDataJSON} = encode_base64url( $credential->{response}->{clientDataJSON} ); } # Encode attestationObject if ( $credential->{response}->{attestationObject} ) { $credential->{response}->{attestationObject} = encode_base64url( $credential->{response}->{attestationObject} ); } # Encode authenticatorData if ( $credential->{response}->{authenticatorData} ) { $credential->{response}->{authenticatorData} = encode_base64url( $credential->{response}->{authenticatorData} ); } # Encode signature if ( $credential->{response}->{signature} ) { $credential->{response}->{signature} = encode_base64url( $credential->{response}->{signature} ); } # Encode rawId if ( $credential->{rawId} ) { $credential->{rawId} = encode_base64url( $credential->{rawId} ); } return JSON->new->utf8->pretty->encode($credential); } sub encode_cosekey { my ($self) = @_; my $key_str = $self->key; my $key = Crypt::PK::ECC->new( \$key_str ); return Authen::WebAuthn::_ecc_obj_to_cose($key); } sub sign { my ( $self, $message ) = @_; my $key_str = $self->key; my $key = Crypt::PK::ECC->new( \$key_str ); return $key->sign_message( $message, 'SHA256' ); } sub get_credential_response { my ( $self, $input, $override ) = @_; my $challenge = $input->{request}->{challenge}; my $uv = $input->{request}->{authenticatorSelection}->{userVerification} || "preferred"; # Everything is build from this array, you can override it for testing # various scenarios my $credential = merge { response => { type => "public-key", rawId => $self->credential_id, id => encode_base64url( $self->credential_id ), clientDataJSON => { type => "webauthn.create", challenge => "$challenge", origin => $self->origin, crossOrigin => JSON::false, }, attestationObject => { 'fmt' => 'none', 'authData' => { rpIdHash => sha256( $self->rp_id ), flags => { userPresent => 1, ( $uv eq "required" ? ( userVerified => 1 ) : () ), atIncluded => 1, }, signCount => $self->sign_count, attestedCredentialData => { aaguid => $self->aaguid, credentialId => $self->credential_id, credentialPublicKey => $self->encode_cosekey, }, }, 'attStmt' => {} } } }, $override; $credential->{response}->{clientDataJSON} = encode_json $credential->{response}->{clientDataJSON}; $credential->{response}->{attestationObject} = makeAttestationObject $credential->{response}->{attestationObject}; return $credential; } sub get_assertion_response { my ( $self, $input, $override ) = @_; my $challenge = $input->{request}->{challenge}; my $uv = $input->{request}->{userVerification} || "preferred"; # Everything is build from this array, you can override it for testing # various scenarios my $credential = merge { type => "public-key", rawId => $self->credential_id, id => encode_base64url( $self->credential_id ), response => { clientDataJSON => { type => "webauthn.get", challenge => "$challenge", origin => $self->origin, crossOrigin => JSON::false, }, authenticatorData => { rpIdHash => sha256( $self->rp_id ), flags => { userPresent => 1, ( $uv eq "required" ? ( userVerified => 1 ) : () ), }, signCount => $self->sign_count, }, userHandle => "", #TODO } }, $override; my $clientData = { type => "webauthn.get", challenge => "$challenge", origin => $self->origin, crossOrigin => JSON::false, }; $credential->{response}->{clientDataJSON} = encode_json $credential->{response}->{clientDataJSON}; $credential->{response}->{authenticatorData} = makeAuthData $credential->{response}->{authenticatorData}; my $hash = sha256( $credential->{response}->{clientDataJSON} ); my $authData = $credential->{response}->{authenticatorData}; my $signature = $self->sign( $authData . $hash ); # Add signature to hash unless we have overriden it unless ( $credential->{response}->{signature} ) { $credential->{response}->{signature} = $signature; } return $credential; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Authen::WebAuthn::Test =head1 VERSION version 0.001 =head1 AUTHOR Maxime Besson =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2022 by Maxime Besson. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut