├── .eslintignore ├── .phpunit.result.cache ├── LICENSE ├── README.md ├── UPGRADE.md ├── bin └── updateMetadata.php ├── composer.json ├── config ├── module_webauthn.php.dist └── webauthn-aaguid.json ├── default-enable ├── docs └── tested_tokens.md ├── locales ├── de │ └── LC_MESSAGES │ │ └── webauthn.po ├── en │ └── LC_MESSAGES │ │ └── webauthn.po ├── fr │ └── LC_MESSAGES │ │ └── webauthn.po └── lb │ └── LC_MESSAGES │ └── webauthn.po ├── phpstan-baseline.neon ├── phpstan-dev.neon ├── phpstan.neon ├── public └── assets │ ├── base │ └── icons │ │ ├── 2nd.png │ │ ├── face.png │ │ ├── fingerprint.png │ │ ├── nothing.png │ │ └── pwless.png │ ├── css │ └── webauthn.css │ └── js │ ├── authentication.js │ └── webauthn.js ├── resources └── icons.odp ├── routing └── routes │ └── routes.yaml ├── src ├── Auth │ ├── Process │ │ └── WebAuthn.php │ └── Source │ │ ├── Passwordless.php │ │ └── Supercharged.php ├── Controller │ ├── AuthProcess.php │ ├── ManageToken.php │ ├── PushbackUserPass.php │ ├── RegProcess.php │ ├── Registration.php │ ├── Supercharged.php │ └── WebAuthn.php ├── Store.php └── WebAuthn │ ├── AAGUID.php │ ├── StateData.php │ ├── StaticProcessHelper.php │ ├── Store │ └── Database.php │ ├── WebAuthnAbstractEvent.php │ ├── WebAuthnAuthenticationEvent.php │ └── WebAuthnRegistrationEvent.php └── templates ├── authentication.twig ├── supercharged.twig └── webauthn.twig /.eslintignore: -------------------------------------------------------------------------------- 1 | config/webauthn-aaguid.json 2 | -------------------------------------------------------------------------------- /.phpunit.result.cache: -------------------------------------------------------------------------------- 1 | {"version":1,"defects":{"SimpleSAML\\Test\\Module\\webauthn\\Controller\\RegProcessTest::testRegProcess":1,"SimpleSAML\\Test\\Module\\webauthn\\Controller\\RegistrationTest::testRegistration":1},"times":{"SimpleSAML\\TestUtils\\TemplateTest::testSyntax":0.059,"SimpleSAML\\Test\\Module\\webauthn\\Controller\\AuthProcessTest::testAuthProcessWithoutProperTokenRaisesException":0.005,"SimpleSAML\\Test\\Module\\webauthn\\Controller\\ManageTokenTest::testManageTokenWithSubmitNeverMind":0.003,"SimpleSAML\\Test\\Module\\webauthn\\Controller\\ManageTokenTest::testManageTokenWithoutSubmitThrowsException":0,"SimpleSAML\\Test\\Module\\webauthn\\Controller\\ManageTokenTest::testManageTokenWithoutAuthenticationThrowsException":0,"SimpleSAML\\Test\\Module\\webauthn\\Controller\\RegProcessTest::testRegProcess":0,"SimpleSAML\\Test\\Module\\webauthn\\Controller\\RegistrationTest::testRegistration":0,"SimpleSAML\\Test\\Module\\webauthn\\Controller\\StateTest::testMissingState with data set #0":0.001,"SimpleSAML\\Test\\Module\\webauthn\\Controller\\StateTest::testMissingState with data set #1":0,"SimpleSAML\\Test\\Module\\webauthn\\Controller\\StateTest::testMissingState with data set #2":0,"SimpleSAML\\Test\\Module\\webauthn\\Controller\\StateTest::testMissingState with data set #3":0,"SimpleSAML\\Test\\Module\\webauthn\\Controller\\StateTest::testNoState with data set #0":0,"SimpleSAML\\Test\\Module\\webauthn\\Controller\\StateTest::testNoState with data set #1":0,"SimpleSAML\\Test\\Module\\webauthn\\Controller\\StateTest::testNoState with data set #2":0,"SimpleSAML\\Test\\Module\\webauthn\\Controller\\StateTest::testNoState with data set #3":0,"SimpleSAML\\Test\\Module\\webauthn\\Controller\\WebAuthnTest::testWebAuthn":0.003}} -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WebAuthn as Second Factor module 2 | 3 | ![Build Status](https://github.com/simplesamlphp/simplesamlphp-module-webauthn/actions/workflows/php.yml/badge.svg) 4 | [![Coverage Status](https://codecov.io/gh/simplesamlphp/simplesamlphp-module-webauthn/branch/master/graph/badge.svg)](https://codecov.io/gh/simplesamlphp/simplesamlphp-module-webauthn) 5 | [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/simplesamlphp/simplesamlphp-module-webauthn/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/simplesamlphp/simplesamlphp-module-webauthn/?branch=master) 6 | [![Type Coverage](https://shepherd.dev/github/simplesamlphp/simplesamlphp-module-webauthn/coverage.svg)](https://shepherd.dev/github/simplesamlphp/simplesamlphp-module-webauthn) 7 | [![Psalm Level](https://shepherd.dev/github/simplesamlphp/simplesamlphp-module-webauthn/level.svg)](https://shepherd.dev/github/simplesamlphp/simplesamlphp-module-webauthn) 8 | 9 | 10 | 11 | The module is implemented as an Authentication Processing Filter. That 12 | means it can be configured in the global config.php file or the SP remote or 13 | IdP hosted metadata. 14 | 15 | ## Installation 16 | 17 | You can install this module with composer: 18 | 19 | ```bash 20 | % composer require simplesamlphp/simplesamlphp-module-webauthn 21 | ``` 22 | 23 | If you are using PHP 7, you also need to install either the GMP extension (recommended) or the BCMath extension. 24 | 25 | ## How to setup the webauthn module as a second-factor (an authprocfilter) 26 | 27 | You need to enable the module's authprocfilter at a priority level 28 | so that it takes place AFTER the first-factor authentication. E.g. at 100 and 29 | if standalone registration and name2oid are used together, then the WebAuthn 30 | auth proc filter has to run after name2oid. 31 | 32 | The authproc filter takes a number of optional parameter that steer which users 33 | will be forced into 2FA. 34 | 35 | ```php 36 | 100 => [ 37 | 'class' => 'webauthn:WebAuthn', 38 | 39 | /* should FIDO2 be enabled by default for all users? If not, users need to 40 | * be white-listed in the database - other users simply pass through the 41 | * filter without being subjected to 2FA. 42 | * 43 | * defaults to "disabled by default" === false 44 | */ 45 | 'default_enable' => false, 46 | 47 | /* only if default_enable is false: 48 | * the toggle to turn on 2FA can either be a database lookup in the module's 49 | * internal database or be dependent on the existence or absence of a 50 | * user attribute as retrieved in the first-factor auth. The following 51 | * options control which variant to use. 52 | */ 53 | 54 | /* 55 | * this parameter determines if the database will be used to check 56 | * whether to trigger second factor authentication or use the "attrib_toggle" instead. 57 | * Default value of this attribute is true 58 | */ 59 | 'use_database' => true, 60 | 61 | /* this parameter is used only if "use_database" is false. If the value of 62 | * "force" is true then we trigger WebAuthn only if "attrib_toggle" from the 63 | * user is not empty. If the value of "force" is false then we switch the value of 64 | * "default_enable" only if "attrib_toggle" from the user is not empty. 65 | * Default falue is true. 66 | */ 67 | 'force' => true, 68 | 69 | /* this parameter stores the name of the attribute that is sent with user and which 70 | * determines whether to trigger WebAuthn. 71 | * Default value is 'toggle' 72 | */ 73 | 'attrib_toggle' => 'toggle', 74 | 75 | /** 76 | * The module can be configured to assert that MFA was executed towards the 77 | * SP by setting an appropriate tag in the response. 78 | * The original SAML 2.0 spec in that regard contains only contexts which 79 | * are rather useless in a FIDO2 context. 80 | * 81 | * FIDO alliance has its own to indicate that a FIDO key was used, and it 82 | * is the default if unset. The semantics does not indicate then that an 83 | * additional authentication besides the FIDO key was used (i.e. your 84 | * first-factor authsource authentication). Thus, you may want to consider 85 | * setting the more accurate REFEDS identifier below instead. 86 | * 87 | * Defaults to 'urn:rsa:names:tc:SAML:2.0:ac:classes:FIDO' if not set 88 | * 89 | * If you authenticate towards Microsoft 365 SPs which may trigger their 90 | * own variant of 2FA, then you can tell them to skip this by 91 | * - setting the SP tenant parameter "supportsMFA" to "true" 92 | * - returning the AuthnContextClassRef 93 | * "http://schemas.microsoft.com/claims/multipleauthn" 94 | */ 95 | 96 | // 'authncontextclassref' => 'https://refeds.org/profile/mfa', 97 | 98 | /** 99 | * Earlier versions of the Authproc filter required the second factor 100 | * every time a new SP requested user auth, even if the user was already 101 | * (first-factor) authenticated at the IdP. 102 | * This can be seen as an inconvenience or a security feature, as it 103 | * mitigates even unlikely scenarios such as a session cookie theft. 104 | * 105 | * This new option makes the behaviour configurable. 106 | * 107 | * If set to any negative number or unset, the old behaviour is maintained. 108 | * 109 | * If set to an amount of seconds (i.e. integer value), second-factor auth 110 | * is requested only on initial authentication and if the last second-factor 111 | * was more than this amount of seconds ago. 112 | */ 113 | // 'secondfactormaxage' => -1, 114 | ], 115 | ``` 116 | 117 | Then you need to copy config-templates/module_webauthn.php to your config directory 118 | and adjust settings accordingly. See the file for parameters description. 119 | 120 | ## How to set up (pure) Passwordless authentication 121 | 122 | In passwordless mode, the module provides an AuthSource, to be configured as 123 | usual in simpleSAMLphp's config/authsources.php 124 | 125 | Users' FIDO2 Keys need to be registered with the "Passwordless" checkbox set - 126 | this triggers the mandatory registration with a second factor intrinsic to the 127 | key (fingerprint, face recognition, transaction PIN, etc. ). 128 | 129 | This authsource takes little configuration because authentications happen before 130 | the username is known - so no user-specific configuration is possible. 131 | 132 | The authsource takes the following parameters in authsources.php: 133 | 134 | ```php 135 | 'name-your-source' => [ 136 | 'webauthn:Passwordless', 137 | /* 138 | * Defaults to 'urn:rsa:names:tc:SAML:2.0:ac:classes:FIDO' if not set 139 | * 140 | * If you authenticate towards Microsoft 365 SPs which may trigger their 141 | * own variant of 2FA, then you can tell them to skip this by 142 | * - setting the SP tenant parameter "supportsMFA" to "true" 143 | * - returning the AuthnContextClassRef 144 | * "http://schemas.microsoft.com/claims/multipleauthn" 145 | */ 146 | 147 | // 'authncontextclassref' => 'https://refeds.org/profile/mfa', 148 | ], 149 | ``` 150 | 151 | ## How to set up simultaneous Passwordless and traditional two-factor 152 | 153 | In this mode, the authentication prompt simultaneously allows for either 154 | triggering a Passwordless auth, or to enter a username/password as traditional 155 | first-factor. 156 | 157 | The configuration is almost identical to Passwordless above, but requires one 158 | extra required configuration parameter: the authsource that should be used to 159 | validate the username/password, if supplied by the user. 160 | 161 | The authsource takes the following parameters in authsources.php: 162 | 163 | ```php 164 | 'name-your-source' => [ 165 | 'webauthn:Supercharged', 166 | 'password_authsource' => 'whatever-authsource', 167 | // 'authncontextclassref' => 'https://refeds.org/profile/mfa', 168 | 169 | ], 170 | ``` 171 | 172 | ## Using storage 173 | 174 | The database schema sets itself up on first use automatically. The schema can be 175 | found in the sources at src/WebAuthN/Store/Database.php (\_\_construct). 176 | 177 | If you want to trim down permissions for the database user, here is the minimal 178 | set of required permissions: 179 | 180 | ```sql 181 | 182 | GRANT SELECT,INSERT,UPDATE,DELETE ON ...credentials TO '...dbuser'@'1.2.3.4' IDENTIFIED BY '...dbpass'; 183 | 184 | 185 | GRANT SELECT ON ...userstatus TO '...dbuser'@'1.2.3.4' IDENTIFIED BY '...dbpass'; 186 | ``` 187 | 188 | The `webauthn:Database` backend storage has the following options: 189 | 190 | `class` 191 | : Must be set to `webauthn:Database`. 192 | 193 | `database.dsn` 194 | : Data Source Name must comply to the syntax for the PHP PDO layer. 195 | 196 | `database.username` 197 | : Username for the database user to be used for the connection. 198 | 199 | `database.password` 200 | : Password for the database user used for the connection. 201 | 202 | `timeout` 203 | : The number of seconds to wait for a connection to the database server. This option is optional. If unset, it uses the default from the database-driver. 204 | 205 | Example config using PostgreSQL database: 206 | 207 | ```php 208 | 100 => [ 209 | 'class' => 'webauthn:WebAuthn', 210 | 'store' => [ 211 | 'webauthn:Database', 212 | 'database.dsn' => 'pgsql:host=sql.example.org;dbname=fido2', 213 | 'database.username' => 'simplesaml', 214 | 'database.password' => 'sdfsdf', 215 | ], 216 | ], 217 | ``` 218 | 219 | Example config using MySQL database: 220 | 221 | ```php 222 | 100 => [ 223 | 'class' => 'webauthn:WebAuthn', 224 | 'store' => [ 225 | 'webauthn:Database', 226 | 'database.dsn' => 'mysql:host=db.example.org;dbname=fido2', 227 | 'database.username' => 'simplesaml', 228 | 'database.password' => 'sdfsdf', 229 | ], 230 | ], 231 | ``` 232 | 233 | ## Options 234 | 235 | ### Options of auth proc filter 236 | 237 | `default_enable` 238 | : Should WebAuthn be enabled by default for all users? If not, users need to be white-listed in the database - other users simply pass through the filter without being subjected to 2FA. Defaults to "disabled by default" === false 239 | 240 | `force` 241 | : This parameter is used only if "use_database" is false. If the value of "force" is true then we trigger WebAuthn only if "attrib_toggle" from the user is not empty. If the value of "force" is false then we switch the value of "default_enable" only if "attrib_toggle" from the user is not empty. Default value is true. 242 | 243 | `attrib_toggle` 244 | : This parameter stores the name of the attribute that is sent with user and which determines whether to trigger WebAuthn. Default value is 'toggle'. 245 | 246 | `use_database` 247 | : This parameter determines if the database will be used to check whether to trigger second factor authentication or use the "attrib_toggle" instead. Default value of this attribute is true. 248 | 249 | ### Options in `module_webauthn.php` 250 | 251 | `scope` 252 | : FIDO2 is phishing-resistent by binding generated credentials to a scope. Browsers will only invoke the registration/authentication if the scope matches the principal domain name the user is currently visiting. If not specified, the scope will be the hostname of the IdP as per its metadata. It is permissible to widen the scope up to the prinicpal domain though (e.g. authentication service is "saml.example.com" => scope can be extended to "example.com"; but not "examp1e.com". A registered FIDO2 token can then also be used on other servers in the same domain. If configuring this item, be sure that the authentication server name and the desired scope are a suffix match. 253 | 254 | `registration / use_inflow_registration` 255 | : Optional parameter which determines whether you will be able to register and manage tokens while authenticating or you want to use the standalone registration page for these purposes. If set to false => standalone registration page, if true => inflow registration. If this parameter is not explicitly set, the value is considered to be true. 256 | 257 | `registration / auth_source` 258 | : Optional parameter to define how the user authenticates to the dedicated registration page. Defaults to "default-sp"; ignored if inflow registration was configured. 259 | 260 | `registration / policy_2fa / minimum_certification_level` 261 | : Required parameter which specifies the required FIDO certification level for registration, allowed values: 262 | 263 | - `CERTIFICATION_NOT_REQUIRED` - attestation is not checked 264 | - `FIDO_CERTIFIED_L1` - FIDO L1 certified 265 | - `FIDO_CERTIFIED_L1plus` - FIDO L1+ certified 266 | - `FIDO_CERTIFIED_L2` - FIDO L2 certified 267 | - `FIDO_CERTIFIED_L3` - FIDO L3 certified 268 | - `FIDO_CERTIFIED_L3plus` - FIDO L3+ certified 269 | 270 | `registration / policy_2fa / aaguid_whitelist` 271 | : Optional list of AAGUIDs which are excluded from the minimum certification level check. Defaults to an empty list. Ignored when `minimum_certification_level` is set to `CERTIFICATION_NOT_REQUIRED`. 272 | 273 | `registration / policy_2fa / attestation_format_whitelist` 274 | : Optional list of attestation formats which are excluded from the minimum certification level check. Defaults to an empty list. Ignored when `minimum_certification_level` is set to `CERTIFICATION_NOT_REQUIRED`. 275 | 276 | `registration / policy_passwordless / minimum_certification_level` 277 | : Required parameter, same meaning as `registration / policy_2fa / minimum_certification_level` but for passwordless authentication 278 | 279 | `registration / policy_passwordless / aaguid_whitelist` 280 | : Optional parameter, same meaning as `registration / policy_2fa / aaguid_whitelist` but for passwordless authentication 281 | 282 | `registration / policy_passwordless / attestation_format_whitelist` 283 | : Optional parameter, same meaning as `registration / policy_2fa / attestation_format_whitelist` but for passwordless authentication 284 | 285 | ## User Experience / Workflow 286 | 287 | Users for which WebAuthn is enabled cannot continue without a FIDO2 token. The 288 | UI is different depending on the number of tokens the user has registered: 289 | 290 | - User has 0 tokens: UI requires the user to register a token. The user can 291 | choose a convenient name for the token to recognise it later. If 292 | request_tokenmodel is set, the name will be appended with the token model and 293 | vendor. 294 | After successful registration, the authprocfilter is done (user continues to 295 | SP) 296 | - User has 1 token: UI requires the user to authenticate. After the 297 | authentication, user can optionally enroll another token. 298 | - User has 2+ tokens: UI requires the user to authenticate. After the 299 | authentication, user can optionally enroll another token or delete an obsolete 300 | one. 301 | 302 | If a user is enabled but has forgotten all of his tokens, the person would need 303 | to contact his administrator and have his account temporarily disabled for two- 304 | factor authentication. 305 | 306 | As long as a user account has 0 tokens there is no benefit yet; it's effectively 307 | still single factor authentication because anyone with the user's password can 308 | register any token. That is in the nature of things. It could be avoided with 309 | an out-of-band registration process (in the same scope). 310 | 311 | If the standalone registration page is used, the user can't optionally enroll 312 | and manage tokens while logging in. 313 | The standalone registration page can be found under `module.php/webauthn/registration`, 314 | it requires authentication (with the auth source registration_auth_source) and 315 | after that you are redirected to a page where you can manage tokens. 316 | 317 | ## Device model detection 318 | 319 | The option `registration / minimum_certification_level` can be used to get a 320 | token's so-called AAGUID which uniquely identifies the model and manufacturer 321 | (it is not a serial number). You can then make decisions about the acceptability 322 | of a certain authenticator model. 323 | 324 | Mapping the AAGUID to a cleartext model and manufacturer name is done by having 325 | (or not) meta-information about the AAGUID. The FIDO Alliance operates a 326 | Metadata Service (MDS) which has a good number of AAGUIDs registered. However, 327 | manufacturers are not required to submit their AAGUIDs and metadata to that MDS, 328 | and indeed, some manufacturers are missing. 329 | 330 | The module contains a full list of AAGUIDs and relevant metadata as pulled from 331 | the FIDO MDS. This list is in the `config/webauthn-aaguid.json` file, and this 332 | file needs to be moved to your SimpleSAMLphp configuration directory. 333 | 334 | If you want, you can also manually update this file, if you believe there might 335 | be new models listed. In order to do that, run the `bin/updateMetadata.php` 336 | script like this: 337 | 338 | ```bash 339 | % php bin/updateMetadata.php 340 | ``` 341 | 342 | where `` is the metadata JWT blob you get from 343 | [here](https://mds3.fidoalliance.org). 344 | 345 | As a consequence, depending on the token model the user uses, even if the AAGUID 346 | is being sent as part of the registration process, it may be that the device is 347 | still stored as unknown model/unknown vendor. 348 | 349 | I contacted FIDO Alliance to ask about the lack of complete information in their 350 | MDS. Purportedly, listing in the MDS has chances of becoming mandatory in a 351 | future FIDO Certification. Until then, there is no good solution to the problem. 352 | 353 | ## Disabling WebAuthn 354 | 355 | You can disable the module entirely by not listing it as an authprocfilter. 356 | 357 | You can disable the module by default by setting default_enable = false. You can 358 | then enable WebAuthn second-factor authentication for individual users by adding 359 | them with status "FIDO2Enabled" to the `userstatus` table or if you don't want to 360 | use the `userstatus` table, you can send an attribute whose name is stored in 361 | `attrib_toggle` for this. 362 | 363 | If the module is enabled by default, you can selectively disable WebAuthn 364 | second-factor authentication by adding the username with status FIDO2Disabled to 365 | the `userstatus` table or if you don't want to use the `userstatus` table, you 366 | can send an attribute whose name is stored in `attrib_toggle` for this. 367 | 368 | ## Limitations / Design Decisions 369 | 370 | This implementation does not validate token bindings, if sent by the 371 | authenticator (§7.1 Step 7 / §7.2 Step 11 skip token binding information 372 | validation if present). That is because Yubikeys do not support token binding 373 | and the corresponding functionality thus has no test case. 374 | 375 | Both User Present and User Verified variants are considered sufficient to 376 | authenticate successfully in second-factor scenarios (§7.1 steps 11 and 12 are 377 | joined into one condition). 378 | The module logs into the credential database which of the two was used during 379 | registration time and does not allow downgrades during authentication time. 380 | Passwordless authentication always requires User Verified during registration 381 | and authentication transactions. 382 | 383 | The implementation requests and supports ECDSA and RSA keys (algorithms -7, 384 | -257). 385 | 386 | The implementation does not request any client extensions. The specification 387 | gives implementations a policy choice on what to do if a client sends extensions 388 | anyway: this implementation chose to then fail the registration/authentication. 389 | 390 | The implementation supports the attestation formats 391 | 392 | - "none" (No Attestation) 393 | - "packed / x5c" (Packed Attestation, X.509 certificate) 394 | - "packed / self" (Packed Attestation, Self-Attestation) 395 | - "fido-u2f" (FIDO U2F Attestation) 396 | - "apple" (Apple Anonymous Attestation) 397 | - "android-key" (Android key attestation with Keymaster 4, for Android 9 and up) 398 | Other attestation formats lead to a registration failure. 399 | 400 | For the attation type "packed / x5c", 401 | 402 | - the optional OCSP checks are not performed (this is explicitly permitted in 403 | the spec due to other means of revocation checking in the FIDO MDS). 404 | 405 | For both "packed / x5c" and "fido-u2f": 406 | 407 | - all attestations are classified as "Basic" (i.e. no "AttCA" level); i.e. 408 | validation as per §7.1 Step 18 is not executed. 409 | - Regarding §7.1 Step 21: When minimum certification levels are configured, 410 | "Self" and "Basic" attestation levels are considered acceptable; "None" is 411 | not acceptable. 412 | 413 | If the implementation detects signs of physical object cloning (not incremented 414 | signature counter), it follows the policy of failing authentication. 415 | -------------------------------------------------------------------------------- /UPGRADE.md: -------------------------------------------------------------------------------- 1 | # Upgrade instructions 2 | 3 | ## Upgrade from 0.11.x to 2.0.x 4 | 5 | Note that the database schema has additional columns as of 2.0.0: 6 | 7 | algo INT DEFAULT NULL, 8 | presenceLevel INT DEFAULT NULL, 9 | isResidentKey BOOL DEFAULT NULL, 10 | `hashedId` VARCHAR(100) DEFAULT '---', 11 | 12 | If you have a previous installation of the module, you need to add this column 13 | manually ( 14 | ALTER TABLE credentials ADD COLUMN `algo` INT DEFAULT NULL AFTER `credential`; 15 | ALTER TABLE credentials ADD COLUMN `presenceLevel` INT DEFAULT NULL AFTER `algo`; 16 | ALTER TABLE credentials ADD COLUMN `isResidentKey` BOOL DEFAULT NULL AFTER `presenceLevel`; 17 | ALTER TABLE credentials ADD COLUMN `hashedId` VARCHAR(100) DEFAULT '---' AFTER `friendlyName`; 18 | ). 19 | The updated schema is compatible with the 0.11.x releases, so a roll-back to an 20 | older version is still possible without removing the column. 21 | 22 | Also note that the parameter attribute_username was changed to 23 | identifyingAttribute to achieve better consistency with other authproc filters. 24 | 25 | ## Upgrade from 2.0.x to 2.1.x 26 | 27 | Two more columns were added to record the AAGUID of the authenticator and its 28 | attestation level: 29 | 30 | aaguid VARCHAR(64) DEFAULT NULL, 31 | attLevel ENUM('None','Basic','AttCA') NOT NULL DEFAULT 'None', 32 | 33 | On existing installs, you need to add those with 34 | 35 | ALTER TABLE credentials ADD COLUMN aaguid VARCHAR(64) DEFAULT NULL AFTER `hashedId`; 36 | ALTER TABLE credentials ADD COLUMN attLevel ENUM('None','Basic','Self','AttCA') NOT NULL DEFAULT 'None' AFTER `aaguid`; 37 | 38 | The configuration options around request_tokenmodel morphed into three 39 | attributes that specify which category of authenticators is acceptable for the 40 | deployment at hand: 41 | 42 | minimum_certification_level = "0" means the authenticator model is not important 43 | and corresponds to request_tokenmodel = false. Every other setting will trigger 44 | behaviour matching the previous request_tokenmodel = true. 45 | 46 | ## Upgrade from 2.1.x to 2.2.x 47 | 48 | There are minor schema changes. The following two columns MUST be added before 49 | upgrading: 50 | 51 | ALTER TABLE credentials ADD COLUMN lastUsedTime TIMESTAMP DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP() AFTER `attLevel`; 52 | ALTER TABLE credentials ADD COLUMN lastUsedIp VARCHAR(64) DEFAULT NULL AFTER `lastUsedTime`; 53 | 54 | For consistency with new deployments, the following changes SHOULD be executed 55 | to align table definitions to new deployments. The module will not break 56 | if the old definition remains in place, but you may encounter issue #76 then. 57 | 58 | When using MySQL or MariaDB: 59 | 60 | ALTER TABLE credentials MODIFY COLUMN credentialId varchar(1024) CHARACTER SET 'binary' NOT NULL; 61 | 62 | -------------------------------------------------------------------------------- /bin/updateMetadata.php: -------------------------------------------------------------------------------- 1 | #!/usr/bin/php 2 | false, 8 | 9 | /* required configuration parameters */ 10 | 'store' => [ 11 | 'webauthn:Database', 12 | 'database.dsn' => 'mysql:host=db.example.org;dbname=fido2', 13 | 'database.username' => 'simplesaml', 14 | 'database.password' => 'sdfsdf', 15 | ], 16 | 17 | 'identifyingAttribute' => 'uid', 18 | 'attrib_displayname' => 'urn:oid:2.5.4.3', 19 | 20 | /* FIDO2 is phishing-resistent by binding generated credentials to a scope. 21 | * Browsers will only invoke the registration/authentication if the scope 22 | * matches the principal domain name the user is currently visiting. 23 | * If not specified, the scope will be the hostname of the IdP as per 24 | * its metadata. It is permissible to widen the scope up to the prinicpal 25 | * domain though (e.g. authentication service is "saml.example.com" => scope 26 | * can be extended to "example.com"; but not "examp1e2.com". A registered 27 | * FIDO2 token can then also be used on other servers in the same domain. 28 | * If configuring this item, be sure that the authentication server name and 29 | * the desired scope are a suffix match. 30 | * 31 | * If you do not control the entirety of your second-level domain, you must 32 | * set the scope here explicitly to your own hostname to prevent some 33 | * contrived attack scenarios with other servers in that same second-level 34 | * domain. 35 | */ 36 | 'scope' => 'example.com', 37 | 38 | /** 39 | * The following options control how new FIDO2 keys are registered for a 40 | * given user. 41 | */ 42 | 'registration' => [ 43 | 44 | /* 45 | * You can specify which authenticators are considered acceptable. 46 | * This can be done with the following two configuration parameters. 47 | * 48 | * They are additive; if either the level is acceptable OR the authenti- 49 | * cator is in the whitelist, OR the attestation format matches, 50 | * registration will succeed. 51 | */ 52 | 53 | /* 54 | * Do you require authenticators to be FIDO Certified, and if so, which 55 | * certification level? 56 | * 57 | * Setting this to anything but "0" will require the user to accept that 58 | * make and model are sent during the registration process, so that the 59 | * characteristics of the authenticator can be verified. 60 | * 61 | * WebAuthnRegistrationEvent::CERTIFICATION_NOT_REQUIRED is probably 62 | * acceptable for second-factor use, but most certainly not for Passwordless. 63 | * 64 | * Possible values: 65 | * WebAuthnRegistrationEvent::CERTIFICATION_NOT_REQUIRED => no 66 | * restriction (even authenticators which are NOT FIDO Certified 67 | * or not known to FIDO Alliance at all are acceptable!) 68 | * WebAuthnRegistrationEvent::FIDO_CERTIFIED_L1 => FIDO Certified Level 1 69 | * WebAuthnRegistrationEvent::FIDO_CERTIFIED_L1plus => FIDO Certified Level 1+ 70 | * WebAuthnRegistrationEvent::FIDO_CERTIFIED_L2 => FIDO Certified Level 2 71 | * WebAuthnRegistrationEvent::FIDO_CERTIFIED_L3 => FIDO Certified Level 3 72 | * WebAuthnRegistrationEvent::FIDO_CERTIFIED_L3plus => FIDO Certified Level 3+ 73 | */ 74 | 'policy_2fa' => [ 75 | 'minimum_certification_level' => WebAuthnRegistrationEvent::CERTIFICATION_NOT_REQUIRED, 76 | /* 77 | * If you specify a level above, you may want to make exceptions for 78 | * specific authenticators that are not on that level. This array 79 | * holds all the authenticators that are considered acceptable by 80 | * exception. 81 | * 82 | */ 83 | 'aaguid_whitelist' => [ ], 84 | /* 85 | * Some authenticators are more equal than others. Apple TouchID and 86 | * FaceID set their AAGUID to all-zeroes so can't be whitelisted. But 87 | * they do send their attestation data in a Apple-specific attestation 88 | * format. So seeing that format means an Apple product is identified. 89 | * Since these authenticators are quite common, here is an option that 90 | * allows to whitelist authenticators by their attestation format. 91 | * 92 | * The example is the obvious and single really useful value. 93 | * 94 | * https://webkit.org/blog/11312/meet-face-id-and-touch-id-for-the-web/ 95 | */ 96 | 'attestation_format_whitelist' => [ ], 97 | ], 98 | 'policy_passwordless' => [ 99 | 'minimum_certification_level' => WebAuthnRegistrationEvent::FIDO_CERTIFIED_L1, 100 | 'aaguid_whitelist' => [ ], 101 | 'attestation_format_whitelist' => ['apple'], 102 | ], 103 | 104 | /* optional parameter which determines whether you will be able to 105 | * register and manage tokens while authenticating or you want to use 106 | * the standalone registration page for these purposes. 107 | * If false => standalone registration page (user needs to visit 108 | * dedicated token management page and authenticate to that) 109 | * if true => inflow registration (automatically ask for registration 110 | * if no key registered; enable key management with a 111 | * checkbox post-authentication) 112 | * Defaults to true. 113 | */ 114 | 'use_inflow_registration' => true, 115 | 116 | /* optional parameter that determines what auth source will be used to 117 | * authenticate to the standalone registration page. 118 | * Defaults to 'default-sp'. 119 | */ 120 | 'auth_source' => 'default-sp', 121 | ], 122 | ]; 123 | -------------------------------------------------------------------------------- /default-enable: -------------------------------------------------------------------------------- 1 | This file indicates that the default state of this module 2 | is disabled. To enable, create a file named enable in the 3 | same directory as this file. 4 | -------------------------------------------------------------------------------- /docs/tested_tokens.md: -------------------------------------------------------------------------------- 1 | # The following tokens were tested against the implementation and found to work 2 | 3 | ## Attestation modes (None, Indirect) 4 | 5 | - [Yubikey 5 NFC](https://www.yubico.com/product/yubikey-5-nfc/) 6 | - [Yubikey 5C](https://www.yubico.com/product/yubikey-5c/) 7 | - [Security Key by Yubico](https://support.yubico.com/support/solutions/articles/15000006900-security-key-by-yubico) 8 | - [Security Key NFC by Yubico](https://support.yubico.com/support/solutions/articles/15000019469-security-key-nfc) 9 | - [Feitian BioPass FIDO2](https://www.ftsafe.com/Products/FIDO/Bio) 10 | - [Solo - FIDO2 security key (USB only)](https://solokeys.com/collections/all/products/solo) 11 | - [Solo Tap - FIDO2 security key (USB + NFC)](https://solokeys.com/collections/all/products/solo-tap) 12 | - TouchID (tested on Macbook Pro 2019, macOS 10.15.3, Google Chrome) - AAGUID 'adce000235bcc60a648b0b25f1f05503' not in database yet 13 | - FaceID (tested on an iPhone with iOS 14) 14 | - Android 13 (tested on a Murena Fairphone 5, "Samsung Internet" browser) 15 | 16 | ## Attestation mode None 17 | 18 | - Android 7 (Samsung Galaxy S6, Fingerprint Sensor) - when requesting 19 | indirect/direct, none is delivered instead 20 | - Windows Hello - when requesting indirect/direct, throws Exception because of unimplemented TPM attestation mode 21 | -------------------------------------------------------------------------------- /locales/de/LC_MESSAGES/webauthn.po: -------------------------------------------------------------------------------- 1 | 2 | #, fuzzy 3 | msgid "" 4 | msgstr "" 5 | "Project-Id-Version: SimpleSAMLphp 1.15\n" 6 | "Report-Msgid-Bugs-To: simplesamlphp-translation@googlegroups.com\n" 7 | "POT-Creation-Date: 2016-10-12 09:23+0200\n" 8 | "PO-Revision-Date: 2016-10-14 12:14+0200\n" 9 | "Last-Translator: \n" 10 | "Language: de\n" 11 | "Language-Team: \n" 12 | "Plural-Forms: nplurals=2; plural=(n != 1)\n" 13 | "MIME-Version: 1.0\n" 14 | "Content-Type: text/plain; charset=utf-8\n" 15 | "Content-Transfer-Encoding: 8bit\n" 16 | "Generated-By: Babel 2.3.4\n" 17 | 18 | msgid "{webauthn.webauthn:passwordlessCaption}" 19 | msgstr "Passwortlose Authentifikation" 20 | 21 | msgid "{webauthn.webauthn:passwordlessProse}" 22 | msgstr "Haben Sie bereits ein biometrisches oder PIN-geschütztes FIDO2 Token registriert? Loggen Sie sich hier ohne Benutzernamen oder Passwort ein!" 23 | 24 | msgid "{webauthn.webauthn:superchargeChoice}" 25 | msgstr "- oder -" 26 | 27 | msgid "{webauthn.webauthn:dedicatedManagementPageHeading}" 28 | msgstr "Schlüsselverwaltung" 29 | 30 | msgid "{webauthn.webauthn:dedicatedManagementPageHint}" 31 | msgstr "Wenn Sie Schlüssel hinzufügen oder löschen möchten, gehen Sie bitte zur" 32 | 33 | msgid "{webauthn.webauthn:dedicatedManagementPageText}" 34 | msgstr "Verwaltungsseite" 35 | 36 | msgid "{webauthn:webauthn:heading1}" 37 | msgstr "Zwei-Faktor-Authentifizierung" 38 | 39 | msgid "{webauthn:webauthn:page_title}" 40 | msgstr "Zwei-Faktor-Authentifizierung mit FIDO2" 41 | 42 | msgid "{webauthn:webauthn:accountEnabled}" 43 | msgstr "Für Ihr Benutzerkonto ist der Zugang nur mit einem FIDO2/WebAuthn Schlüssel möglich." 44 | 45 | msgid "{webauthn:webauthn:tokenList}" 46 | msgstr "Bei Ihrem Benutzerkonto sind die folgenden Schlüssel registriert:" 47 | 48 | msgid "{webauthn:webauthn:newTokenButton}" 49 | msgstr "Neuen Schlüssel registrieren" 50 | 51 | msgid "{webauthn:webauthn:newTokenName}" 52 | msgstr "Name für den neuen Schlüssel:" 53 | 54 | msgid "{webauthn:webauthn:newTokenDefaultName}" 55 | msgstr "Schlüssel vom" 56 | 57 | msgid "{webauthn:webauthn:authTokenButton}" 58 | msgstr "Authentifizieren" 59 | 60 | msgid "{webauthn:webauthn:wantsAdd}" 61 | msgstr "Nach der Anmeldung möchte ich einen Schlüssel hinzufügen." 62 | 63 | msgid "{webauthn:webauthn:wantsModification}" 64 | msgstr "Nach der Anmeldung möchte ich Schlüssel hinzufügen oder löschen." 65 | 66 | msgid "{webauthn:webauthn:noChange}" 67 | msgstr "Keine Änderungen durchführen." 68 | 69 | msgid "{webauthn:webauthn:removePrefix}" 70 | msgstr "Löschen von" 71 | 72 | msgid "{webauthn:webauthn:currentToken}" 73 | msgstr "(mit diesem Schlüssel sind Sie angemeldet)" 74 | 75 | msgid "title_FIDO_CERTIFICATION_TOO_LOW" 76 | msgstr "FIDO Schlüssel inakzeptabel" 77 | 78 | msgid "descr_FIDO_CERTIFICATION_TOO_LOW" 79 | msgstr "Sie haben versucht, einen FIDO Schlüssel zu registrieren der für die Firma nicht akzeptabel ist. Sie brauchen vielleicht einen anderen Schlüssel." 80 | 81 | msgid "{webauthn:webauthn:registerPasswordless}" 82 | msgstr "Für passwortlose Anmeldung registrieren?" 83 | 84 | msgid "{webauthn:webauthn:registerPasswordlessExplanations}" 85 | msgstr "Im passwortlosen Modus wird der Schlüssel mit einem biometrischen " 86 | "Merkmal order einer PIN geschützt. Dieser Schutz kann dann nicht mehr " 87 | "entfernt werden ohne alle Login-Daten für alle Webseiten zu löschen." 88 | 89 | msgid "{webauthn:webauthn:tokenRegisterBox}" 90 | msgstr "Registrierung eines neuen Schlüssels" 91 | -------------------------------------------------------------------------------- /locales/en/LC_MESSAGES/webauthn.po: -------------------------------------------------------------------------------- 1 | 2 | #, fuzzy 3 | msgid "" 4 | msgstr "" 5 | "Project-Id-Version: SimpleSAMLphp 1.15\n" 6 | "Report-Msgid-Bugs-To: simplesamlphp-translation@googlegroups.com\n" 7 | "POT-Creation-Date: 2016-10-12 09:23+0200\n" 8 | "PO-Revision-Date: 2016-10-14 12:14+0200\n" 9 | "Last-Translator: \n" 10 | "Language: de\n" 11 | "Language-Team: \n" 12 | "Plural-Forms: nplurals=2; plural=(n != 1)\n" 13 | "MIME-Version: 1.0\n" 14 | "Content-Type: text/plain; charset=utf-8\n" 15 | "Content-Transfer-Encoding: 8bit\n" 16 | "Generated-By: Babel 2.3.4\n" 17 | 18 | msgid "{webauthn.webauthn:passwordlessCaption}" 19 | msgstr "Passwordless Authentication" 20 | 21 | msgid "{webauthn.webauthn:passwordlessProse}" 22 | msgstr "Did you register a biometric or PIN-protected WebAuthN token already? Log in now without username or password!" 23 | 24 | msgid "{webauthn.webauthn:dedicatedManagementPageHeading}" 25 | msgstr "Managing your tokens" 26 | 27 | msgid "{webauthn.webauthn:dedicatedManagementPageHint}" 28 | msgstr "If you need to add or delete tokens, please visit" 29 | 30 | msgid "{webauthn.webauthn:dedicatedManagementPageText}" 31 | msgstr "Token Management" 32 | 33 | msgid "{webauthn.webauthn:superchargeChoice}" 34 | msgstr "- or -" 35 | 36 | msgid "{webauthn:webauthn:heading1}" 37 | msgstr "Two Factor Authentication" 38 | 39 | msgid "{webauthn:webauthn:page_title}" 40 | msgstr "Two factor authentication with FIDO2" 41 | 42 | msgid "{webauthn:webauthn:accountEnabled}" 43 | msgstr "For your account, authentication with a FIDO2/WebAuthn token is required." 44 | 45 | msgid "{webauthn:webauthn:tokenList}" 46 | msgstr "The following tokens are associated with your account:" 47 | 48 | msgid "{webauthn:webauthn:newTokenButton}" 49 | msgstr "Enroll new token" 50 | 51 | msgid "{webauthn:webauthn:newTokenName}" 52 | msgstr "Name for the new token:" 53 | 54 | msgid "{webauthn:webauthn:newTokenDefaultName}" 55 | msgstr "Token registered at" 56 | 57 | msgid "{webauthn:webauthn:authTokenButton}" 58 | msgstr "Authenticate" 59 | 60 | msgid "{webauthn:webauthn:wantsAdd}" 61 | msgstr "After authenticating, I want to register a new token." 62 | 63 | msgid "{webauthn:webauthn:wantsModification}" 64 | msgstr "After authenticating, I want to register a new token or delete an existing one." 65 | 66 | msgid "{webauthn:webauthn:noChange}" 67 | msgstr "Do not change anything." 68 | 69 | msgid "{webauthn:webauthn:removePrefix}" 70 | msgstr "Remove" 71 | 72 | msgid "{webauthn:webauthn:currentToken}" 73 | msgstr "(you authenticated with this token)" 74 | 75 | msgid "title_FIDO_CERTIFICATION_TOO_LOW" 76 | msgstr "FIDO Token not Acceptable" 77 | 78 | msgid "descr_FIDO_CERTIFICATION_TOO_LOW" 79 | msgstr "You attempted to register a FIDO token that does not match company policy. You may need to use a different token." 80 | 81 | msgid "{webauthn:webauthn:registerPasswordless}" 82 | msgstr "Register for Passwordless?" 83 | 84 | msgid "{webauthn:webauthn:registerPasswordlessExplanations}" 85 | msgstr "In Passwordless mode, the token will be protected with a biometric or " 86 | "PIN. From then on, this protection cannot be removed without deleting all " 87 | "login information for all websites." 88 | 89 | msgid "{webauthn:webauthn:tokenRegisterBox}" 90 | msgstr "New Token Registration" -------------------------------------------------------------------------------- /locales/fr/LC_MESSAGES/webauthn.po: -------------------------------------------------------------------------------- 1 | 2 | #, fuzzy 3 | msgid "" 4 | msgstr "" 5 | "Project-Id-Version: SimpleSAMLphp 1.15\n" 6 | "Report-Msgid-Bugs-To: simplesamlphp-translation@googlegroups.com\n" 7 | "POT-Creation-Date: 2016-10-12 09:23+0200\n" 8 | "PO-Revision-Date: 2016-10-14 12:14+0200\n" 9 | "Last-Translator: \n" 10 | "Language: de\n" 11 | "Language-Team: \n" 12 | "Plural-Forms: nplurals=2; plural=(n != 1)\n" 13 | "MIME-Version: 1.0\n" 14 | "Content-Type: text/plain; charset=utf-8\n" 15 | "Content-Transfer-Encoding: 8bit\n" 16 | "Generated-By: Babel 2.3.4\n" 17 | 18 | msgid "{webauthn.webauthn:passwordlessCaption}" 19 | msgstr "Authentification sans mot de passe" 20 | 21 | msgid "{webauthn.webauthn:passwordlessProse}" 22 | msgstr "Vous avez déjà enregistré un token WebAuthN biométrique ou protégé par un code PIN ? Connectez-vous sans nom d'utilisateur ni mot de passe !" 23 | 24 | msgid "{webauthn.webauthn:dedicatedManagementPageHint}" 25 | msgstr "Pour ajouter ou supprimer des tokens, veuillez consulter" 26 | 27 | msgid "{webauthn.webauthn:dedicatedManagementPageText}" 28 | msgstr "Gestion des tokens" 29 | 30 | msgid "{webauthn.webauthn:superchargeChoice}" 31 | msgstr "- ou -" 32 | 33 | msgid "{webauthn:webauthn:heading1}" 34 | msgstr "Authentification à deux facteurs" 35 | 36 | msgid "{webauthn:webauthn:page_title}" 37 | msgstr "Authentification à deux facteurs avec FIDO2" 38 | 39 | msgid "{webauthn:webauthn:accountEnabled}" 40 | msgstr "Pour votre compte, une authentification avec un token FIDO2/WebAuthn est requise." 41 | 42 | msgid "{webauthn:webauthn:tokenList}" 43 | msgstr "Les tokens suivants sont associés à votre compte :" 44 | 45 | msgid "{webauthn:webauthn:newTokenButton}" 46 | msgstr "Enregistrer un nouveau token" 47 | 48 | msgid "{webauthn:webauthn:newTokenName}" 49 | msgstr "Nom du nouveau token:" 50 | 51 | msgid "{webauthn:webauthn:newTokenDefaultName}" 52 | msgstr "Token enregistré à" 53 | 54 | msgid "{webauthn:webauthn:authTokenButton}" 55 | msgstr "Authentifier" 56 | 57 | msgid "{webauthn:webauthn:wantsAdd}" 58 | msgstr "Après authentification, je souhaite enregistrer un nouveau token." 59 | 60 | msgid "{webauthn:webauthn:wantsModification}" 61 | msgstr "Après authentification, je souhaite enregistrer un nouveau token ou en supprimer un." 62 | 63 | msgid "{webauthn:webauthn:noChange}" 64 | msgstr "Ne rien modifier." 65 | 66 | msgid "{webauthn:webauthn:removePrefix}" 67 | msgstr "Supprimer" 68 | 69 | msgid "{webauthn:webauthn:currentToken}" 70 | msgstr "(vous êtes authentifié-e avec ce token)" 71 | 72 | msgid "title_FIDO_CERTIFICATION_TOO_LOW" 73 | msgstr "Token FIDO non accepté" 74 | 75 | msgid "descr_FIDO_CERTIFICATION_TOO_LOW" 76 | msgstr "Vous tentez d'enregistrer un token FIDO qui ne correspond pas à la politique de l'entreprise. Vous devriez utiliser un autre token. 77 | 78 | msgid "{webauthn:webauthn:registerPasswordless}" 79 | msgstr "Enregistrer sans mot de passe ?" 80 | 81 | msgid "{webauthn:webauthn:registerPasswordlessExplanations}" 82 | msgstr "Sans mot de passe, le token est protégé par biométrie ou " 83 | "PIN. Une telle protection ne peut être supprimée qu'en supprimant simultanément la totalité " 84 | " des informations de connexion de tous les sites Web." 85 | 86 | msgid "{webauthn:webauthn:tokenRegisterBox}" 87 | msgstr "Enregistrement d'un nouveau token" 88 | 89 | msgid "{webauthn.webauthn:dedicatedManagementPageHeading}" 90 | msgstr "Gérer ses tokens" 91 | -------------------------------------------------------------------------------- /locales/lb/LC_MESSAGES/webauthn.po: -------------------------------------------------------------------------------- 1 | 2 | #, fuzzy 3 | msgid "" 4 | msgstr "" 5 | "Project-Id-Version: SimpleSAMLphp 2.0\n" 6 | "Report-Msgid-Bugs-To: simplesamlphp-translation@googlegroups.com\n" 7 | "POT-Creation-Date: 2023-04-19 09:23+0200\n" 8 | "PO-Revision-Date: 2023-04-19 12:14+0200\n" 9 | "Last-Translator: Stefan Winter\n" 10 | "Language: lb\n" 11 | "Language-Team: \n" 12 | "Plural-Forms: nplurals=2; plural=(n != 1)\n" 13 | "MIME-Version: 1.0\n" 14 | "Content-Type: text/plain; charset=utf-8\n" 15 | "Content-Transfer-Encoding: 8bit\n" 16 | "Generated-By: Babel 2.3.4\n" 17 | 18 | msgid "{webauthn.webauthn:passwordlessCaption}" 19 | msgstr "Authentificatioun ouni Passwuert" 20 | 21 | msgid "{webauthn.webauthn:passwordlessProse}" 22 | msgstr "Huet dir schons eng biometresch oder PIN-protegéiert WebAuthN token enregistréiert? Loggt iech elo domat an, ouni Benotzernumm oder Passwuert!" 23 | 24 | msgid "{webauthn.webauthn:superchargeChoice}" 25 | msgstr "- oder -" 26 | 27 | msgid "{webauthn.webauthn:dedicatedManagementPageHeading}" 28 | msgstr "Administratioun vun Schlesselen" 29 | 30 | msgid "{webauthn.webauthn:dedicatedManagementPageHint}" 31 | msgstr "Fir Schlesselen bäizepraffen oder ze läschen, besicht w.e.g. de" 32 | 33 | msgid "{webauthn.webauthn:dedicatedManagementPageText}" 34 | msgstr "Schlessel Administratioun" 35 | 36 | msgid "{webauthn:webauthn:heading1}" 37 | msgstr "Authentificatioun mat zwee Fakteuren" 38 | 39 | msgid "{webauthn:webauthn:page_title}" 40 | msgstr "Authentificatioun mat zwee Fakteueren, iwwert FIDO2" 41 | 42 | msgid "{webauthn:webauthn:accountEnabled}" 43 | msgstr "Fir ären Compte ass agestallt, dass dir iech mat engem FIDO2/WebAuthn token aloggen misst." 44 | 45 | msgid "{webauthn:webauthn:tokenList}" 46 | msgstr "Die folgend Tokens sin fir iech enregistréiert:" 47 | 48 | msgid "{webauthn:webauthn:newTokenButton}" 49 | msgstr "Neien token enregistréiern" 50 | 51 | msgid "{webauthn:webauthn:newTokenName}" 52 | msgstr "Numm fir den neien token:" 53 | 54 | msgid "{webauthn:webauthn:newTokenDefaultName}" 55 | msgstr "Token enregistréiert den " 56 | 57 | msgid "{webauthn:webauthn:authTokenButton}" 58 | msgstr "Umellen" 59 | 60 | msgid "{webauthn:webauthn:wantsAdd}" 61 | msgstr "No dem Umellen well ech gären eng neien Token bäipraffen." 62 | 63 | msgid "{webauthn:webauthn:wantsModification}" 64 | msgstr "No dem Umellen well ech gären meng Tokens managen." 65 | 66 | msgid "{webauthn:webauthn:noChange}" 67 | msgstr "Et ass gudd. Näischt änneren w.e.g." 68 | 69 | msgid "{webauthn:webauthn:removePrefix}" 70 | msgstr "Läschen" 71 | 72 | msgid "{webauthn:webauthn:currentToken}" 73 | msgstr "(mat desem Token huet dir iech ugemellt)" 74 | 75 | msgid "title_FIDO_CERTIFICATION_TOO_LOW" 76 | msgstr "FIDO Token ass net akzeptabel" 77 | 78 | msgid "descr_FIDO_CERTIFICATION_TOO_LOW" 79 | msgstr "Dir huet versicht en Token ze benotzen den d'Firmenpolitik net erlaabt. Dir musst vläit en aaneren benotzen." 80 | 81 | msgid "{webauthn:webauthn:registerPasswordless}" 82 | msgstr "Registréieren für Login ouni Passwuert?" 83 | 84 | msgid "{webauthn:webauthn:registerPasswordlessExplanations}" 85 | msgstr "Am Modus ouni Passwuert gett de Schlessel mat engem biometrischen " 86 | "trait oder enger PIN protégéiert. Des Protectioun kann hanno net mei " 87 | "reckgängeg gemaach gin ouni dass all Login Informatiounen fir all Websäit " 88 | "geläscht gin." 89 | 90 | msgid "{webauthn:webauthn:tokenRegisterBox}" 91 | msgstr "Enregistrement vun engem neien Schlessel" -------------------------------------------------------------------------------- /phpstan-baseline.neon: -------------------------------------------------------------------------------- 1 | parameters: 2 | ignoreErrors: 3 | - 4 | message: "#^Offset 'FIDO2PasswordlessAu…' does not exist on array\\{FIDO2AuthSuccessful\\: mixed, FIDO2WantsRegister\\: bool\\}\\.$#" 5 | count: 1 6 | path: src/Controller/AuthProcess.php 7 | -------------------------------------------------------------------------------- /phpstan-dev.neon: -------------------------------------------------------------------------------- 1 | parameters: 2 | level: 5 3 | paths: 4 | - tests 5 | -------------------------------------------------------------------------------- /phpstan.neon: -------------------------------------------------------------------------------- 1 | parameters: 2 | level: 3 3 | paths: 4 | - src 5 | bootstrapFiles: 6 | - tests/bootstrap.php 7 | includes: 8 | - phpstan-baseline.neon 9 | -------------------------------------------------------------------------------- /public/assets/base/icons/2nd.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simplesamlphp/simplesamlphp-module-webauthn/f0461a89272432fe7054020d727cd6b0120f3b56/public/assets/base/icons/2nd.png -------------------------------------------------------------------------------- /public/assets/base/icons/face.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simplesamlphp/simplesamlphp-module-webauthn/f0461a89272432fe7054020d727cd6b0120f3b56/public/assets/base/icons/face.png -------------------------------------------------------------------------------- /public/assets/base/icons/fingerprint.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simplesamlphp/simplesamlphp-module-webauthn/f0461a89272432fe7054020d727cd6b0120f3b56/public/assets/base/icons/fingerprint.png -------------------------------------------------------------------------------- /public/assets/base/icons/nothing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simplesamlphp/simplesamlphp-module-webauthn/f0461a89272432fe7054020d727cd6b0120f3b56/public/assets/base/icons/nothing.png -------------------------------------------------------------------------------- /public/assets/base/icons/pwless.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simplesamlphp/simplesamlphp-module-webauthn/f0461a89272432fe7054020d727cd6b0120f3b56/public/assets/base/icons/pwless.png -------------------------------------------------------------------------------- /public/assets/css/webauthn.css: -------------------------------------------------------------------------------- 1 | div.bounding-tokens { 2 | border: 1px; 3 | border-style: dotted; 4 | margin-bottom: 20px; 5 | padding: 10px; 6 | } 7 | 8 | div.space { 9 | margin: 10px; 10 | } 11 | 12 | li.currenttoken { 13 | font-weight: bold; 14 | color: blue; 15 | } 16 | 17 | li.othertoken { 18 | display: flex; 19 | } 20 | 21 | img.factorlogo { 22 | height: 2em; 23 | padding: 2px; 24 | } 25 | 26 | span.tokencaption { 27 | font-weight: bold; 28 | } 29 | 30 | #containerbase { 31 | display: grid; 32 | grid-template-columns: repeat(3, 45% 10% 45%); 33 | gap: 20px; 34 | } 35 | 36 | #container-1-1 { 37 | grid-column: 1; 38 | grid-row: 1; 39 | } 40 | 41 | #container-1-2 { 42 | grid-column: 1; 43 | grid-row: 2; 44 | } 45 | 46 | #container-1-3 { 47 | grid-column: 1; 48 | grid-row: 3; 49 | align-self: end; 50 | } 51 | 52 | #container-1-4 { 53 | grid-column: 1; 54 | grid-row: 4; 55 | align-self: end; 56 | } 57 | 58 | #container-2 { 59 | grid-column: 2; 60 | grid-row: 1 / 4; 61 | align-self: center; 62 | min-width: 20px; 63 | min-height: 100px; 64 | } 65 | 66 | #container-3-1 { 67 | grid-column: 3; 68 | grid-row: 1; 69 | } 70 | 71 | #container-3-2 { 72 | grid-column: 3; 73 | grid-row: 2; 74 | } 75 | 76 | #container-3-3 { 77 | grid-column: 3; 78 | grid-row: 3; 79 | } 80 | 81 | #container-3-4 { 82 | grid-column: 3; 83 | grid-row: 4; 84 | } 85 | 86 | #label-passwordless { 87 | display: flex; 88 | } 89 | 90 | #span-passwordless { 91 | font-size: small; 92 | display: contents; 93 | } 94 | 95 | #fingerprint { 96 | padding-bottom: 30px; 97 | padding-right: 50px; 98 | } 99 | 100 | #face { 101 | padding-bottom: 30px; 102 | } 103 | 104 | #submit-button { 105 | margin-top: 80px; 106 | } 107 | 108 | #passwordblock { 109 | display: block; 110 | } 111 | -------------------------------------------------------------------------------- /public/assets/js/authentication.js: -------------------------------------------------------------------------------- 1 | function authenticate() { 2 | setTimeout(function() {document.getElementById("authformSubmit").click();}, 500) 3 | } 4 | 5 | window.addEventListener('DOMContentLoaded', authenticate); 6 | -------------------------------------------------------------------------------- /public/assets/js/webauthn.js: -------------------------------------------------------------------------------- 1 | // the following two functions are taken from https://stackoverflow.com/questions/16363419/how-to-get-binary-string-from-arraybuffer 2 | 3 | function BinaryToString(binary) 4 | { 5 | var error; 6 | 7 | try { 8 | return decodeURIComponent(escape(binary)); 9 | } catch (_error) { 10 | error = _error; 11 | if (error instanceof URIError) { 12 | return binary; 13 | } else { 14 | throw error; 15 | } 16 | } 17 | } 18 | 19 | function ArrayBufferToString(buffer) 20 | { 21 | return BinaryToString(String.fromCharCode.apply(null, Array.prototype.slice.apply(new Uint8Array(buffer)))); 22 | } 23 | 24 | function registrationButtonClick() 25 | { 26 | // alert("In normal registration mode."); 27 | navigator.credentials.create(publicKeyCredentialCreationOptions) 28 | .then((cred) => { 29 | console.log('NEW CREDENTIAL', cred); 30 | document.getElementById('resp').value = cred.id; 31 | var enc = new TextDecoder('utf-8'); 32 | document.getElementById('data').value = enc.decode(cred.response.clientDataJSON); 33 | document.getElementById('attobj').value = btoa(ArrayBufferToString(cred.response.attestationObject)); 34 | document.getElementById('type').value = cred.response.type; 35 | document.getElementById('clientext').value = JSON.stringify(cred.getClientExtensionResults()); 36 | document.forms['regform'].submit(); 37 | }) 38 | .then((assertion) => { 39 | console.log('ASSERTION', assertion); 40 | }) 41 | .catch((err) => { 42 | alert("Something went wrong. It is possible that you are trying to use an invalid token.") 43 | console.log('ERROR', err); 44 | }); 45 | } 46 | 47 | function passwordlessRegistrationButtonClick() 48 | { 49 | // alert("In passwordless registration mode."); 50 | navigator.credentials.create(passwordlessPublicKeyCredentialCreationOptions) 51 | .then((cred) => { 52 | console.log('NEW CREDENTIAL', cred); 53 | document.getElementById('resp').value = cred.id; 54 | var enc = new TextDecoder('utf-8'); 55 | document.getElementById('data').value = enc.decode(cred.response.clientDataJSON); 56 | document.getElementById('attobj').value = btoa(ArrayBufferToString(cred.response.attestationObject)); 57 | document.getElementById('type').value = cred.response.type; 58 | document.getElementById('clientext').value = JSON.stringify(cred.getClientExtensionResults()); 59 | document.forms['regform'].submit(); 60 | }) 61 | .then((assertion) => { 62 | console.log('ASSERTION', assertion); 63 | }) 64 | .catch((err) => { 65 | alert("Something went wrong. It is possible that you are trying to use an invalid token.") 66 | console.log('ERROR', err); 67 | }); 68 | } 69 | 70 | function authButtonClick() 71 | { 72 | navigator.credentials.get(publicKeyCredentialRequestOptions) 73 | .then((cred) => { 74 | console.log('AUTH', cred); 75 | document.getElementById('resp').value = cred.id; 76 | var enc = new TextDecoder('utf-8'); 77 | document.getElementById('data_raw_b64').value = btoa(ArrayBufferToString(cred.response.clientDataJSON)); 78 | document.getElementById('data').value = enc.decode(cred.response.clientDataJSON); 79 | document.getElementById('authdata').value = btoa(ArrayBufferToString(cred.response.authenticatorData)); 80 | document.getElementById('sigdata').value = btoa(ArrayBufferToString(cred.response.signature)); 81 | document.getElementById('type').value = cred.response.type; 82 | document.getElementById('clientext').value = JSON.stringify(cred.getClientExtensionResults()); 83 | document.forms['authform'].submit(); 84 | }) 85 | .then((assertion) => { 86 | console.log('ASSERTION', assertion); 87 | }) 88 | .catch((err) => { 89 | console.log('ERROR', err); 90 | }); 91 | } 92 | 93 | function passwordlessAuthButtonClick() 94 | { 95 | navigator.credentials.get(passwordlessPublicKeyCredentialRequestOptions) 96 | .then((cred) => { 97 | console.log('AUTH', cred); 98 | document.getElementById('resp').value = cred.id; 99 | var enc = new TextDecoder('utf-8'); 100 | document.getElementById('data_raw_b64').value = btoa(ArrayBufferToString(cred.response.clientDataJSON)); 101 | document.getElementById('data').value = enc.decode(cred.response.clientDataJSON); 102 | document.getElementById('authdata').value = btoa(ArrayBufferToString(cred.response.authenticatorData)); 103 | document.getElementById('sigdata').value = btoa(ArrayBufferToString(cred.response.signature)); 104 | document.getElementById('userHandle').value = btoa(ArrayBufferToString(cred.response.userHandle)); 105 | document.getElementById('type').value = cred.response.type; 106 | document.getElementById('clientext').value = JSON.stringify(cred.getClientExtensionResults()); 107 | document.forms['authform'].submit(); 108 | }) 109 | .then((assertion) => { 110 | console.log('ASSERTION', assertion); 111 | }) 112 | .catch((err) => { 113 | console.log('ERROR', err); 114 | }); 115 | } 116 | 117 | var frontendData = JSON.parse(document.getElementById('frontendData').getAttribute('content')); 118 | 119 | var publicKeyCredentialCreationOptions = { 120 | publicKey: { 121 | challenge: new Uint8Array(frontendData['challengeEncoded']).buffer, 122 | rp: { 123 | name: "Restena DEV", 124 | id: frontendData['state']['FIDO2Scope'], 125 | }, 126 | user: { 127 | id: new Uint8Array(frontendData['usernameEncoded']).buffer, 128 | name: frontendData['state']['FIDO2Username'], 129 | displayName: frontendData['state']['FIDO2Displayname'], 130 | }, 131 | pubKeyCredParams: [{alg: -7, type: 'public-key'},{alg: -257, type: 'public-key'}], 132 | authenticatorSelection: { 133 | userVerification: "discouraged" 134 | }, 135 | timeout: 60000, 136 | attestation: frontendData['attestation'], 137 | } 138 | }; 139 | 140 | var passwordlessPublicKeyCredentialCreationOptions = { 141 | publicKey: { 142 | challenge: new Uint8Array(frontendData['challengeEncoded']).buffer, 143 | rp: { 144 | name: "Restena DEV", 145 | id: frontendData['state']['FIDO2Scope'], 146 | }, 147 | user: { 148 | id: new Uint8Array(frontendData['usernameEncoded']).buffer, 149 | name: frontendData['state']['FIDO2Username'], 150 | displayName: frontendData['state']['FIDO2Displayname'], 151 | }, 152 | pubKeyCredParams: [{alg: -7, type: 'public-key'},{alg: -257, type: 'public-key'}], 153 | authenticatorSelection: { 154 | requireResidentKey: true, 155 | residentKey: "required", 156 | userVerification: "required", 157 | credProtect: "userVerificationRequired", 158 | }, 159 | timeout: 60000, 160 | attestation: 'direct', 161 | extensions: { 162 | credProps: true, 163 | credProtect: { 164 | credentialProtectionPolicy: "userVerificationRequired", 165 | enforceCredentialProtectionPolicy: true 166 | } 167 | } 168 | } 169 | }; 170 | 171 | const publicKeyCredentialRequestOptions = { 172 | publicKey: { 173 | challenge: new Uint8Array(frontendData['challengeEncoded']).buffer, 174 | rpId: frontendData['state']['FIDO2Scope'], 175 | timeout: 60000, 176 | allowCredentials: frontendData['credentialIdEncoded'].map((oneId) => { 177 | return {id: new Uint8Array(oneId).buffer, type: 'public-key'}; 178 | }), 179 | userVerification: "discouraged" 180 | } 181 | }; 182 | 183 | const passwordlessPublicKeyCredentialRequestOptions = { 184 | publicKey: { 185 | challenge: new Uint8Array(frontendData['challengeEncoded']).buffer, 186 | rpId: frontendData['state']['FIDO2Scope'], 187 | timeout: 60000, 188 | userVerification: "required" 189 | } 190 | }; 191 | 192 | 193 | window.addEventListener('DOMContentLoaded', () => { 194 | let regform = document.getElementById('regform'); 195 | if (regform !== null) { 196 | document.getElementById('regformSubmit').addEventListener('click', registrationButtonClick); 197 | regform.addEventListener('submit', () => false); 198 | document.getElementById('tokenname').addEventListener('keydown', (event) => { 199 | if (event.keyCode == 13) { 200 | return false; 201 | } 202 | }); 203 | document.getElementById('passwordless').addEventListener('click', () => { 204 | if (document.getElementById('passwordless').checked) { 205 | document.getElementById('regformSubmit').removeEventListener('click', registrationButtonClick); 206 | document.getElementById('regformSubmit').addEventListener('click', passwordlessRegistrationButtonClick); 207 | } else { 208 | document.getElementById('regformSubmit').removeEventListener('click', passwordlessRegistrationButtonClick); 209 | document.getElementById('regformSubmit').addEventListener('click', registrationButtonClick); 210 | } 211 | }); 212 | } 213 | let authform = document.getElementById('authform'); 214 | if (authform !== null) { 215 | if (frontendData['FIDO2PasswordlessAuthMode'] === false) { 216 | document.getElementById('authformSubmit').addEventListener('click', authButtonClick); 217 | } else { 218 | document.getElementById('authformSubmit').addEventListener('click', passwordlessAuthButtonClick); 219 | } 220 | authform.addEventListener('submit', () => false); 221 | } 222 | const collection = document.getElementsByClassName('form-discoverable-credential'); 223 | for (let i = 0; i < collection.length; i++) { 224 | collection[i].onsubmit = function() { return confirm('Information about this website is also stored on the device itself. Remember to delete it from the device.'); }; 225 | } 226 | }); 227 | -------------------------------------------------------------------------------- /resources/icons.odp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simplesamlphp/simplesamlphp-module-webauthn/f0461a89272432fe7054020d727cd6b0120f3b56/resources/icons.odp -------------------------------------------------------------------------------- /routing/routes/routes.yaml: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | webauthn-registration: 4 | path: /registration 5 | defaults: { 6 | _controller: 'SimpleSAML\Module\webauthn\Controller\Registration::main' 7 | } 8 | methods: [GET, POST] 9 | 10 | webauthn-authprocess: 11 | path: /authprocess 12 | defaults: { 13 | _controller: 'SimpleSAML\Module\webauthn\Controller\AuthProcess::main' 14 | } 15 | methods: [GET, POST] 16 | 17 | webauthn-webauthn: 18 | path: /webauthn 19 | defaults: { 20 | _controller: 'SimpleSAML\Module\webauthn\Controller\WebAuthn::main' 21 | } 22 | methods: [GET, POST] 23 | 24 | webauthn-supercharged: 25 | path: /supercharged 26 | defaults: { 27 | _controller: 'SimpleSAML\Module\webauthn\Controller\Supercharged::main' 28 | } 29 | methods: [GET, POST] 30 | 31 | webauthn-pushbackuserpass: 32 | path: /pushbackuserpass 33 | defaults: { 34 | _controller: 'SimpleSAML\Module\webauthn\Controller\PushbackUserPass::main' 35 | } 36 | methods: [GET, POST] 37 | 38 | webauthn-regprocess: 39 | path: /regprocess 40 | defaults: { 41 | _controller: 'SimpleSAML\Module\webauthn\Controller\RegProcess::main' 42 | } 43 | methods: [GET, POST] 44 | 45 | webauthn-managetoken: 46 | path: /managetoken 47 | defaults: { 48 | _controller: 'SimpleSAML\Module\webauthn\Controller\ManageToken::main' 49 | } 50 | methods: [GET, POST] 51 | -------------------------------------------------------------------------------- /src/Auth/Process/WebAuthn.php: -------------------------------------------------------------------------------- 1 | 10 | * @package SimpleSAMLphp 11 | */ 12 | 13 | declare(strict_types=1); 14 | 15 | namespace SimpleSAML\Module\webauthn\Auth\Process; 16 | 17 | use SimpleSAML\Auth; 18 | use SimpleSAML\Configuration; 19 | use SimpleSAML\Logger; 20 | use SimpleSAML\Module; 21 | use SimpleSAML\Module\webauthn\WebAuthn\StateData; 22 | use SimpleSAML\Module\webauthn\WebAuthn\StaticProcessHelper; 23 | use SimpleSAML\Session; 24 | 25 | class WebAuthn extends Auth\ProcessingFilter 26 | { 27 | /** 28 | * @var boolean should new users be considered as enabled by default? 29 | */ 30 | private bool $defaultEnabled; 31 | 32 | /** 33 | * @var boolean switch that determines how 'toggle' will be used, if true then value of 'toggle' 34 | * will mean whether to trigger (true) or not (false) the webauthn authentication, 35 | * if false then $toggle means whether to switch the value of $defaultEnabled and then use that 36 | */ 37 | private bool $force; 38 | 39 | /** 40 | * @var string an attribute which is associated with 'force' because it determines its meaning, 41 | * it either simply means whether to trigger webauthn authentication or switch the default settings, 42 | * if null (was not sent as attribute) then the information from database is used 43 | */ 44 | private string $toggleAttrib; 45 | 46 | /** 47 | * @var bool a bool that determines whether to use local database or not 48 | */ 49 | private bool $useDatabase; 50 | 51 | /** 52 | * @var string|null AuthnContextClassRef 53 | */ 54 | private ?string $authnContextClassRef = null; 55 | 56 | /** 57 | * An object with all the parameters that will be needed in the process 58 | * 59 | * @var Module\webauthn\WebAuthn\StateData 60 | */ 61 | private StateData $stateData; 62 | 63 | /** 64 | * Maximum age of second-factor authentication in authproc 65 | */ 66 | private int $SecondFactorMaxAge; 67 | 68 | /** 69 | * Initialize filter. 70 | * 71 | * Validates and parses the configuration. 72 | * 73 | * @param array $config Configuration information. 74 | * @param mixed $reserved For future use. 75 | * 76 | * @throws \SimpleSAML\Error\Exception if the configuration is not valid. 77 | */ 78 | public function __construct(array $config, $reserved) 79 | { 80 | parent::__construct($config, $reserved); 81 | 82 | $moduleConfig = Configuration::getOptionalConfig('module_webauthn.php')->toArray(); 83 | 84 | $initialStateData = new Module\webauthn\WebAuthn\StateData(); 85 | Module\webauthn\Controller\WebAuthn::loadModuleConfig($moduleConfig, $initialStateData); 86 | $this->stateData = $initialStateData; 87 | 88 | $this->force = $config['force'] ?? true; 89 | $this->toggleAttrib = $config['attrib_toggle'] ?? 'toggle'; 90 | $this->useDatabase = $config['use_database'] ?? true; 91 | $this->defaultEnabled = $config['default_enable'] ?? false; 92 | $this->authnContextClassRef = $config['authncontextclassref'] ?? null; 93 | $this->SecondFactorMaxAge = $config['secondfactormaxage'] ?? -1; 94 | 95 | if (array_key_exists('use_inflow_registration', $moduleConfig['registration'])) { 96 | $this->stateData->useInflowRegistration = $moduleConfig['registration']['use_inflow_registration']; 97 | } else { 98 | $this->stateData->useInflowRegistration = true; 99 | } 100 | } 101 | 102 | /** 103 | * Process a authentication response 104 | * 105 | * This function saves the state, and redirects the user to the page where 106 | * the user can register or authenticate with his token. 107 | * 108 | * @param array &$state The state of the response. 109 | * 110 | * @return void 111 | */ 112 | public function process(array &$state): void 113 | { 114 | if (!array_key_exists($this->stateData->usernameAttrib, $state['Attributes'])) { 115 | Logger::warning('webauthn: cannot determine if user needs second factor, missing attribute "' . 116 | $this->stateData->usernameAttrib . '".'); 117 | return; 118 | } 119 | 120 | $state['saml:AuthnContextClassRef'] = $this->authnContextClassRef ?? 121 | 'urn:rsa:names:tc:SAML:2.0:ac:classes:FIDO'; 122 | Logger::debug('webauthn: userid: ' . $state['Attributes'][$this->stateData->usernameAttrib][0]); 123 | 124 | $localToggle = !empty($state['Attributes'][$this->toggleAttrib]) && 125 | !empty($state['Attributes'][$this->toggleAttrib][0]); 126 | 127 | if ( 128 | $this->stateData->store->is2FAEnabled( 129 | $state['Attributes'][$this->stateData->usernameAttrib][0], 130 | $this->defaultEnabled, 131 | $this->useDatabase, 132 | $localToggle, 133 | $this->force, 134 | ) === false 135 | ) { 136 | // nothing to be done here, end authprocfilter processing 137 | return; 138 | } 139 | 140 | if // did we do Passwordless mode successfully before? 141 | ( 142 | isset($state['Attributes']['internal:FIDO2PasswordlessAuthentication']) && 143 | // phpcs:ignore Generic.Files.LineLength.TooLong 144 | $state['Attributes']['internal:FIDO2PasswordlessAuthentication'][0] == $state['Attributes'][$this->stateData->usernameAttrib][0] 145 | ) { 146 | // then no need to trigger a second 2-Factor via authproc 147 | // just delete the internal attribute then 148 | unset($state['Attributes']['internal:FIDO2PasswordlessAuthentication']); 149 | return; 150 | } 151 | $session = Session::getSessionFromRequest(); 152 | $lastSecondFactor = $session->getData("DateTime", 'LastSuccessfulSecondFactor'); 153 | if // do we need to do secondFactor in interval, or even every time? 154 | // we skip only if an interval is configured AND we did successfully authenticate, 155 | // AND are within the interval 156 | ( 157 | $this->SecondFactorMaxAge >= 0 && $lastSecondFactor instanceof \DateTime 158 | ) { 159 | $interval = $lastSecondFactor->diff(new \DateTime()); 160 | if ($interval->invert == 1) { 161 | throw new \Exception("We are talking to a future self. Amazing."); 162 | } 163 | // phpcs:ignore Generic.Files.LineLength.TooLong 164 | $totalAge = $interval->s + 60 * $interval->i + 3600 * $interval->h + 86400 * $interval->d + 86400 * 30 * $interval->m + 86400 * 365 * $interval->y; 165 | if ($totalAge < $this->SecondFactorMaxAge) { // we are within the interval indeed, skip calling the AuthProc 166 | return; 167 | } 168 | } 169 | StaticProcessHelper::prepareState($this->stateData, $state); 170 | StaticProcessHelper::saveStateAndRedirect($state); 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /src/Auth/Source/Passwordless.php: -------------------------------------------------------------------------------- 1 | authSourceConfig = Configuration::loadFromArray( 44 | $config, 45 | 'authsources[' . var_export($this->authId, true) . ']', 46 | ); 47 | $this->authnContextClassRef = $this->authSourceConfig->getOptionalString( 48 | "authncontextclassref", 49 | 'urn:rsa:names:tc:SAML:2.0:ac:classes:FIDO', 50 | ); 51 | $moduleConfig = Configuration::getOptionalConfig('module_webauthn.php')->toArray(); 52 | 53 | $initialStateData = new StateData(); 54 | WebAuthn::loadModuleConfig($moduleConfig, $initialStateData); 55 | $this->stateData = $initialStateData; 56 | } 57 | 58 | public function authenticate(array &$state): void 59 | { 60 | $state['saml:AuthnContextClassRef'] = $this->authnContextClassRef; 61 | 62 | StaticProcessHelper::prepareStatePasswordlessAuth($this->stateData, $state); 63 | StaticProcessHelper::saveStateAndRedirect($state); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/Auth/Source/Supercharged.php: -------------------------------------------------------------------------------- 1 | pushbackAuthsource = $this->authSourceConfig->getString("password_authsource"); 29 | } 30 | 31 | public function authenticate(array &$state): void 32 | { 33 | $state['saml:AuthnContextClassRef'] = $this->authnContextClassRef; 34 | $state['pushbackAuthsource'] = $this->pushbackAuthsource; 35 | 36 | StaticProcessHelper::prepareStatePasswordlessAuth($this->stateData, $state); 37 | StaticProcessHelper::saveStateAndRedirectSupercharged($state); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Controller/AuthProcess.php: -------------------------------------------------------------------------------- 1 | authState = $authState; 62 | } 63 | 64 | /** 65 | * Inject the \SimpleSAML\Logger dependency. 66 | * 67 | * @param \SimpleSAML\Logger $logger 68 | */ 69 | public function setLogger(Logger $logger): void 70 | { 71 | $this->logger = $logger; 72 | } 73 | 74 | /** 75 | * @param \Symfony\Component\HttpFoundation\Request $request 76 | * @return ( 77 | * \Symfony\Component\HttpFoundation\RedirectResponse| 78 | * \SimpleSAML\HTTP\RunnableResponse 79 | * ) A Symfony Response-object. 80 | */ 81 | public function main(Request $request): Response 82 | { 83 | $this->logger::info('FIDO2 - Accessing WebAuthn enrollment validation'); 84 | 85 | $stateId = $request->query->get('StateId'); 86 | if ($stateId === null) { 87 | throw new Error\BadRequest('Missing required StateId query parameter.'); 88 | } 89 | 90 | $moduleConfig = Configuration::getOptionalConfig('module_webauthn.php'); 91 | $debugEnabled = $moduleConfig->getOptionalBoolean('debug', false); 92 | 93 | $state = $this->authState::loadState($stateId, 'webauthn:request'); 94 | 95 | $incomingID = bin2hex(WebAuthnAbstractEvent::base64urlDecode($request->request->get('response_id'))); 96 | 97 | /** 98 | * For passwordless auth, extract the userid from the response of the 99 | * discoverable credential, look up whether the credential used is one 100 | * that belongs to the claimed username 101 | * 102 | * Fail auth if not found, otherwise treat this auth like any other 103 | * (but check later whether UV was set during auth for the token at hand) 104 | */ 105 | if ($state['FIDO2PasswordlessAuthMode'] === true) { 106 | $usernameBuffer = ""; 107 | foreach (str_split(base64_decode($request->request->get('userHandle'))) as $oneChar) { 108 | $usernameBuffer .= bin2hex($oneChar); 109 | } 110 | $store = $state['webauthn:store']; 111 | $userForToken = $store->getUsernameByHashedId($usernameBuffer); 112 | if ($userForToken !== "") { 113 | $tokensForUser = $store->getTokenData($userForToken); 114 | $state['FIDO2Username'] = $userForToken; 115 | $state['FIDO2Tokens'] = $tokensForUser; 116 | } else { 117 | throw new Exception("Credential ID cannot be associated to any user!"); 118 | } 119 | } 120 | 121 | /** 122 | * §7.2 STEP 2 - 4 : check that the credential is one of those the particular user owns 123 | */ 124 | $publicKey = false; 125 | $previousCounter = -1; 126 | $oneToken = []; 127 | 128 | foreach ($state['FIDO2Tokens'] as $oneToken) { 129 | if ($oneToken[0] == $incomingID) { 130 | // Credential ID is eligible for user $state['FIDO2Username']; 131 | // using publicKey $oneToken[1] with current counter value $oneToken[2] 132 | $publicKey = $oneToken[1]; 133 | $previousCounter = $oneToken[2]; 134 | break; 135 | } 136 | } 137 | 138 | if ($publicKey === false || sizeof($oneToken) === 0) { 139 | throw new Exception( 140 | // phpcs:ignore Generic.Files.LineLength.TooLong 141 | "User attempted to authenticate with an unknown credential ID. This should already have been prevented by the browser!", 142 | ); 143 | } 144 | 145 | if (!is_string($oneToken[1])) { 146 | $oneToken[1] = stream_get_contents($oneToken[1]); 147 | } 148 | 149 | $authObject = new WebAuthnAuthenticationEvent( 150 | $request->request->get('type'), 151 | ($state['FIDO2Scope'] === null ? $state['FIDO2DerivedScope'] : $state['FIDO2Scope']), 152 | $state['FIDO2SignupChallenge'], 153 | base64_decode($request->request->get('authenticator_data')), 154 | base64_decode($request->request->get('client_data_raw')), 155 | $oneToken[0], 156 | $oneToken[1], 157 | (int)$oneToken[4], // algo 158 | base64_decode($request->request->get('signature')), 159 | $debugEnabled, 160 | ); 161 | 162 | /** Custom check: if the token was initially registered with UV, but now 163 | * authenticates only UP, we don't allow this downgrade. 164 | * 165 | * This is not typically allowed by authenticator implementations anyway 166 | * (they typically require a full reset of the key to remove UV 167 | * protections) but to be safe: find out and tell user to re-enroll with 168 | * the lower security level. (level upgrades are of course OK.) 169 | */ 170 | if ($oneToken[5] > $authObject->getPresenceLevel()) { 171 | // phpcs:ignore Generic.Files.LineLength.TooLong 172 | throw new Exception("Token was initially registered with higher identification guarantees than now authenticated with (was: " . $oneToken[5] . " now " . $authObject->getPresenceLevel() . "!"); 173 | } 174 | 175 | // no matter what: if we are passwordless it MUST be presence-verified 176 | if ( 177 | $state['FIDO2PasswordlessAuthMode'] === true && 178 | $oneToken[5] !== WebAuthnAbstractEvent::PRESENCE_LEVEL_VERIFIED 179 | ) { 180 | throw new Exception("Attempt to authenticate without User Verification in passwordless mode!"); 181 | } 182 | 183 | // if we didn't register the key as resident, do not allow its use in 184 | // passwordless mode 185 | if ($state['FIDO2PasswordlessAuthMode'] === true && $oneToken[6] !== 1) { 186 | throw new Exception("Attempt to authenticate with a token that is not registered for passwordless mode!"); 187 | } 188 | 189 | /** 190 | * §7.2 STEP 18 : detect physical object cloning on the token 191 | */ 192 | $counter = $authObject->getCounter(); 193 | if ($previousCounter === 0 && $counter === 0) { 194 | // no cloning check, it is a brand new token 195 | } elseif ($counter > $previousCounter) { 196 | // Signature counter was incremented compared to last time, good 197 | $store = $state['webauthn:store']; 198 | $store->updateSignCount($oneToken[0], $counter); 199 | } else { 200 | throw new Exception( 201 | // phpcs:ignore Generic.Files.LineLength.TooLong 202 | "Signature counter less or equal to a previous authentication! Token cloning likely (old: $previousCounter, new: $counter).", 203 | ); 204 | } 205 | 206 | // THAT'S IT. The user authenticated successfully. Remember the credential ID that was used. 207 | $state['FIDO2AuthSuccessful'] = $oneToken[0]; 208 | 209 | // See if he wants to hang around for token management operations 210 | if ($request->request->get('credentialChange') === 'on') { 211 | $state['FIDO2WantsRegister'] = true; 212 | } else { 213 | $state['FIDO2WantsRegister'] = false; 214 | } 215 | 216 | $this->authState::saveState($state, 'webauthn:request'); 217 | 218 | if ($debugEnabled) { 219 | $response = new RunnableResponse( 220 | function (WebAuthnAuthenticationEvent $authObject, array $state) { 221 | echo $authObject->getDebugBuffer(); 222 | echo $authObject->getValidateBuffer(); 223 | echo "Debug mode, not continuing to " . ($state['FIDO2WantsRegister'] ? 224 | "credential registration page." : "destination."); 225 | }, 226 | [$authObject, $state], 227 | ); 228 | } else { 229 | if ($state['FIDO2WantsRegister']) { 230 | $response = new RedirectResponse( 231 | Module::getModuleURL('webauthn/webauthn?StateId=' . urlencode($stateId)), 232 | ); 233 | } else { 234 | $response = new RunnableResponse([Auth\ProcessingChain::class, 'resumeProcessing'], [$state]); 235 | } 236 | } 237 | if ($state['FIDO2PasswordlessAuthMode'] === false) { 238 | // take note of the current timestamp so we know 239 | // a) that second-factor was done successfully in the current sesssion 240 | // b) when that event occured, so as to make regular re-auths configurable 241 | $this->session->setData("DateTime", 'LastSuccessfulSecondFactor', new \DateTime()); 242 | $this->authState::saveState($state, 'webauthn:request'); 243 | } 244 | if ($state['FIDO2PasswordlessAuthMode'] === true) { 245 | /** 246 | * But what about SAML attributes? As an authproc, those came in by the 247 | * first-factor authentication. 248 | * In passwordless, we're on our own. The one thing we know is the 249 | * username. 250 | */ 251 | $state['Attributes'][$state['FIDO2AttributeStoringUsername']] = [ $state['FIDO2Username'] ]; 252 | // in case this authentication happened in the Supercharged context 253 | // it may be that there is an authprocfilter for WebAuthN, too. 254 | 255 | // If so, remove it from $state as it is stupid to touch the token 256 | // twice; once in the Passwordless auth source and once as an 257 | // authprocfilter 258 | 259 | // this didn't actually work; authprocfilter self-removes instead 260 | // if it found Passwordless to be successful in the same session 261 | 262 | foreach ($state['IdPMetadata']['authproc'] as $index => $content) { 263 | if ($content['class'] == "webauthn:WebAuthn") { 264 | unset($state['IdPMetadata']['authproc'][$index]); 265 | } 266 | } 267 | // set an internal "authenticated passwordless" hint somewhere else 268 | // in $state, which the authproc can react upon 269 | $state['Attributes']['internal:FIDO2PasswordlessAuthentication'] = [ $state['FIDO2Username'] ]; 270 | 271 | $this->authState::saveState($state, 'webauthn:request'); 272 | 273 | // set a cookie to remember that the user has successfully used 274 | // Passwordless - on the Supercharged AuthSource, this can be used 275 | // to auto-trigger the FIDO2 authentication step next time 276 | setcookie("SuccessfullyUsedPasswordlessBefore", "YES", time() + (3600 * 24 * 90), '/', "", true, true); 277 | 278 | // now properly return our final state to the framework 279 | Source::completeAuth($state); 280 | } 281 | 282 | $response->setExpires(new DateTime('Thu, 19 Nov 1981 08:52:00 GMT')); 283 | $response->setCache([ 284 | 'must_revalidate' => true, 285 | 'no_cache' => true, 286 | 'no_store' => true, 287 | 'no_transform' => false, 288 | 'public' => false, 289 | 'private' => false, 290 | ]); 291 | 292 | return $response; 293 | } 294 | } 295 | -------------------------------------------------------------------------------- /src/Controller/ManageToken.php: -------------------------------------------------------------------------------- 1 | authState = $authState; 59 | } 60 | 61 | 62 | /** 63 | * Inject the \SimpleSAML\Logger dependency. 64 | * 65 | * @param \SimpleSAML\Logger $logger 66 | */ 67 | public function setLogger(Logger $logger): void 68 | { 69 | $this->logger = $logger; 70 | } 71 | 72 | 73 | /** 74 | * @param \Symfony\Component\HttpFoundation\Request $request 75 | * @return \SimpleSAML\HTTP\RunnableResponse A Symfony Response-object. 76 | */ 77 | public function main(Request $request): RunnableResponse 78 | { 79 | $this->logger::info('FIDO2 - Accessing WebAuthn token management'); 80 | 81 | $stateId = $request->query->get('StateId'); 82 | if ($stateId === null) { 83 | throw new Error\BadRequest('Missing required StateId query parameter.'); 84 | } 85 | 86 | $state = $this->authState::loadState($stateId, 'webauthn:request'); 87 | 88 | $ourState = WebAuthn::workflowStateMachine($state); 89 | if ($ourState !== WebAuthn::STATE_MGMT) { 90 | throw new Exception("Attempt to access the token management page unauthenticated."); 91 | } 92 | 93 | switch ($request->request->get('submit')) { 94 | case "NEVERMIND": 95 | $response = new RunnableResponse([Auth\ProcessingChain::class, 'resumeProcessing'], [$state]); 96 | break; 97 | case "DELETE": 98 | $credId = $request->request->get('credId'); 99 | if ($state['FIDO2AuthSuccessful'] == $credId) { 100 | throw new Exception("Attempt to delete the currently used credential despite UI preventing this."); 101 | } 102 | 103 | $store = $state['webauthn:store']; 104 | $store->deleteTokenData($credId); 105 | 106 | if (array_key_exists('Registration', $state)) { 107 | foreach ($state['FIDO2Tokens'] as $key => $value) { 108 | if ($state['FIDO2Tokens'][$key][0] == $credId) { 109 | unset($state['FIDO2Tokens'][$key]); 110 | break; 111 | } 112 | } 113 | 114 | $response = new RunnableResponse([StaticProcessHelper::class, 'saveStateAndRedirect'], [&$state]); 115 | } else { 116 | $response = new RunnableResponse([Auth\ProcessingChain::class, 'resumeProcessing'], [$state]); 117 | } 118 | break; 119 | default: 120 | throw new Exception("Unknown submit button state."); 121 | } 122 | 123 | $response->setExpires(new DateTime('Thu, 19 Nov 1981 08:52:00 GMT')); 124 | $response->setCache([ 125 | 'must_revalidate' => true, 126 | 'no_cache' => true, 127 | 'no_store' => true, 128 | 'no_transform' => false, 129 | 'public' => false, 130 | 'private' => false, 131 | ]); 132 | 133 | return $response; 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/Controller/PushbackUserPass.php: -------------------------------------------------------------------------------- 1 | authState = $authState; 56 | } 57 | 58 | /** 59 | * Inject the \SimpleSAML\Logger dependency. 60 | * 61 | * @param \SimpleSAML\Logger $logger 62 | */ 63 | public function setLogger(Logger $logger): void 64 | { 65 | $this->logger = $logger; 66 | } 67 | 68 | /** 69 | * @param \Symfony\Component\HttpFoundation\Request $request 70 | * @return ( 71 | * \Symfony\Component\HttpFoundation\RedirectResponse| 72 | * \SimpleSAML\HTTP\RunnableResponse 73 | * ) A Symfony Response-object. 74 | */ 75 | public function main(Request $request): Response 76 | { 77 | $this->logger::info('FIDO2 Supercharged - Redirecting to username/password validation'); 78 | 79 | $stateId = $request->query->get('StateId'); 80 | if ($stateId === null) { 81 | throw new Error\BadRequest('Missing required StateId query parameter.'); 82 | } 83 | 84 | $state = $this->authState::loadState($stateId, 'webauthn:request'); 85 | 86 | $authsources = Configuration::getConfig('authsources.php')->toArray(); 87 | $authsourceString = $state['pushbackAuthsource']; 88 | $authsourceClass = Auth\Source::getById($authsourceString); 89 | if (is_null($authsourceClass)) { 90 | throw new Exception("password authsource not found"); 91 | } 92 | $classname = get_class($authsourceClass); 93 | class_alias($classname, '\SimpleSAML\Module\webauthn\Auth\Source\AuthSourceOverloader'); 94 | $overrideSource = new class ( 95 | ['AuthId' => $authsourceString], 96 | $authsources[$authsourceString], 97 | ) extends AuthSourceOverloader 98 | { 99 | public function loginOverload(string $username, string $password): array 100 | { 101 | return $this->login($username, $password); 102 | } 103 | }; 104 | 105 | $attribs = $overrideSource->loginOverload( 106 | $request->request->get("username"), 107 | $request->request->get("password"), 108 | ); 109 | 110 | // this is the confirmed username, we store it just like the Passwordless 111 | // one would have been 112 | $state['Attributes'][$state['FIDO2AttributeStoringUsername']] = [ $request->request->get("username") ]; 113 | 114 | // we deliberately do not store any additional attributes - these have 115 | // to be retrieved from the same authproc that would retrieve them 116 | // in Passwordless mode 117 | unset($attribs); 118 | 119 | // now properly return our final state to the framework 120 | return new RunnableResponse([Auth\Source::class, 'completeAuth'], [&$state]); 121 | } 122 | 123 | public function login(string $username, string $password): array 124 | { 125 | throw new Exception("Ugh ($username, $password)."); 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /src/Controller/RegProcess.php: -------------------------------------------------------------------------------- 1 | authState = $authState; 65 | } 66 | 67 | 68 | /** 69 | * Inject the \SimpleSAML\Logger dependency. 70 | * 71 | * @param \SimpleSAML\Logger $logger 72 | */ 73 | public function setLogger(Logger $logger): void 74 | { 75 | $this->logger = $logger; 76 | } 77 | 78 | 79 | /** 80 | * @param \Symfony\Component\HttpFoundation\Request $request 81 | * @return \Symfony\Component\HttpFoundation\RedirectResponse|\SimpleSAML\HTTP\RunnableResponse 82 | * A Symfony Response-object. 83 | */ 84 | public function main(Request $request): Response 85 | { 86 | $this->logger::info('FIDO2 - Accessing WebAuthn enrollment validation'); 87 | 88 | $stateId = $request->query->get('StateId'); 89 | if ($stateId === null) { 90 | throw new Error\BadRequest('Missing required StateId query parameter.'); 91 | } 92 | 93 | $moduleConfig = Configuration::getOptionalConfig('module_webauthn.php'); 94 | $debugEnabled = $moduleConfig->getOptionalBoolean('debug', false); 95 | 96 | $state = $this->authState::loadState($stateId, 'webauthn:request'); 97 | 98 | // registering a credential is only allowed for new users or after being authenticated 99 | if (WebAuthn::workflowStateMachine($state) !== WebAuthn::STATE_MGMT) { 100 | throw new Exception("Attempt to register new token in unacceptable context."); 101 | } 102 | 103 | $fido2Scope = ($state['FIDO2Scope'] === null ? $state['FIDO2DerivedScope'] : $state['FIDO2Scope']); 104 | if ($fido2Scope === null) { 105 | throw new Exception("FIDO2Scope cannot be null!"); 106 | } 107 | 108 | $regObject = new WebAuthnRegistrationEvent( 109 | $request->request->get('type'), 110 | $fido2Scope, 111 | $state['FIDO2SignupChallenge'], 112 | base64_decode($request->request->get('attestation_object')), 113 | $request->request->get('response_id'), 114 | $request->request->get('attestation_client_data_json'), 115 | ($request->request->get('passwordless') == "on" ? 116 | $state['authenticatorAcceptabilityPasswordless'] : $state['authenticatorAcceptability2FA']), 117 | $debugEnabled, 118 | ); 119 | // at this point, we need to talk to the DB 120 | /** 121 | * STEP 19 of the validation procedure in § 7.1 of the spec: see if this credential is already registered 122 | */ 123 | $store = $state['webauthn:store']; 124 | if ($store->doesCredentialExist(bin2hex($regObject->getCredentialId())) === false) { 125 | // credential does not exist yet in database, good. 126 | } else { 127 | throw new Exception("The credential with ID " . $regObject->getCredentialId() . " already exists."); 128 | } 129 | 130 | // THAT'S IT. This is a valid credential and can be enrolled to the user. 131 | $friendlyName = $request->request->get('tokenname'); 132 | 133 | // if we know the token model, add it to the name 134 | $model = Translate::noop('unknown model'); 135 | $aaguiddict = AAGUID::getInstance(); 136 | if ($aaguiddict->hasToken($regObject->getAAGUID())) { 137 | $token = $aaguiddict->get($regObject->getAAGUID()); 138 | $model = $token['metadataStatement']['description']; 139 | } 140 | $friendlyName .= " ($model)"; 141 | 142 | /** 143 | * STEP 20 of the validation procedure in § 7.1 of the spec: store credentialId, credential, 144 | * signCount and associate with user 145 | */ 146 | 147 | /* 148 | * Observed with YubiKey 5: the transaction counter is 0 if the key has NEVER been used, but 149 | * the first transaction is also transaction #0. 150 | * i.e. 0 means "before first transaction OR the very first transaction has already taken place" 151 | * 152 | * The very first use of a key should not trigger the physical object cloning alert, so a 153 | * transaction counter == 0 should be allowed for the first authentication of a new key. 154 | * The best way to do this is to set the current counter value to -1 when registering a key 155 | * with a transaction counter of 0. 156 | */ 157 | $currentCounterValue = -1; 158 | if ($regObject->getCounter() > 0) { 159 | $currentCounterValue = $regObject->getCounter(); 160 | } 161 | 162 | // did we get any client extensions? 163 | $isResidentKey = 0; 164 | if ( 165 | strlen($request->request->get('clientext')) > 0 && 166 | count(json_decode($request->request->get('clientext'), true)) > 0 167 | ) { 168 | $extensions = json_decode($request->request->get('clientext'), true); 169 | if (isset($extensions['credProps']['rk']) && $extensions['credProps']['rk'] === true) { 170 | $isResidentKey = 1; 171 | } 172 | } 173 | 174 | // we also need to store the hased user_id in case we need to retrieve 175 | // tokens in passwordless mode 176 | // use identical hashing as in JS generation step 177 | $configUtils = new Utils\Config(); 178 | $username = hash('sha512', $state['FIDO2Username'] . '|' . $configUtils->getSecretSalt()); 179 | $store->storeTokenData( 180 | $state['FIDO2Username'], 181 | $regObject->getCredentialId(), 182 | $regObject->getCredential(), 183 | $regObject->getAlgo(), 184 | $regObject->getPresenceLevel(), 185 | // we deny saving resident key properties if Passwordless mode 186 | // was not requested 187 | ($request->request->get('passwordless') == "on" ? $isResidentKey : 0), 188 | $currentCounterValue, 189 | $friendlyName, 190 | $username, 191 | $regObject->getAAGUID(), 192 | $regObject->getAttestationLevel(), 193 | ); 194 | 195 | // make sure $state gets the news, the token is to be displayed to the user on the next page 196 | $state['FIDO2Tokens'][] = [ 197 | 0 => $regObject->getCredentialId(), 198 | 1 => $regObject->getCredential(), 199 | 2 => $currentCounterValue, 200 | 3 => $friendlyName, 201 | 4 => $regObject->getAlgo(), 202 | 5 => $regObject->getPresenceLevel(), 203 | 6 => $isResidentKey, 204 | ]; 205 | 206 | $id = $this->authState::saveState($state, 'webauthn:request'); 207 | if ($debugEnabled === true) { 208 | $response = new RunnableResponse( 209 | function (WebAuthnRegistrationEvent $regObject, string $id) { 210 | echo $regObject->getDebugBuffer(); 211 | echo $regObject->getValidateBuffer(); 212 | echo "
"; 214 | echo ""; 215 | }, 216 | [$regObject, $id], 217 | ); 218 | } elseif (array_key_exists('Registration', $state)) { 219 | $response = new RedirectResponse(Module::getModuleURL('webauthn/webauthn?StateId=' . urlencode($id))); 220 | } else { 221 | $response = new RunnableResponse([Auth\ProcessingChain::class, 'resumeProcessing'], [$state]); 222 | } 223 | 224 | $response->setExpires(new DateTime('Thu, 19 Nov 1981 08:52:00 GMT')); 225 | $response->setCache([ 226 | 'must_revalidate' => true, 227 | 'no_cache' => true, 228 | 'no_store' => true, 229 | 'no_transform' => false, 230 | 'public' => false, 231 | 'private' => false, 232 | ]); 233 | 234 | return $response; 235 | } 236 | } 237 | -------------------------------------------------------------------------------- /src/Controller/Registration.php: -------------------------------------------------------------------------------- 1 | authState = $authState; 65 | } 66 | 67 | 68 | /** 69 | * Inject the \SimpleSAML\Auth\Simple dependency. 70 | * 71 | * @param \SimpleSAML\Auth\Simple $authSimple 72 | */ 73 | public function setAuthSimple(Auth\Simple $authSimple): void 74 | { 75 | $this->authSimple = $authSimple; 76 | } 77 | 78 | 79 | /** 80 | * Inject the \SimpleSAML\Logger dependency. 81 | * 82 | * @param \SimpleSAML\Logger $logger 83 | */ 84 | public function setLogger(Logger $logger): void 85 | { 86 | $this->logger = $logger; 87 | } 88 | 89 | 90 | /** 91 | * @param \Symfony\Component\HttpFoundation\Request $request 92 | * @return \SimpleSAML\HTTP\RunnableResponse A Symfony Response-object. 93 | */ 94 | public function main(/** @scrutinizer ignore-unused */ Request $request): RunnableResponse 95 | { 96 | $moduleConfig = Configuration::getOptionalConfig('module_webauthn.php'); 97 | $registrationConfig = $moduleConfig->getArray('registration'); 98 | $registrationAuthSource = $registrationConfig['auth_source'] ?? 'default-sp'; 99 | 100 | $state = []; 101 | $state['SPMetadata']['entityid'] = "WEBAUTHN-SP-REGISTRATION"; 102 | 103 | $authSimple = $this->authSimple; 104 | $as = new $authSimple($registrationAuthSource); 105 | $as->requireAuth(); 106 | $attrs = $as->getAttributes(); 107 | 108 | $state['Attributes'] = $attrs; 109 | 110 | $stateData = new StateData(); 111 | // phpcs:disable Generic.Files.LineLength.TooLong 112 | $stateData->requestTokenModel = ($registrationConfig['policy_2fa']['minimum_certification_level'] == WebAuthnRegistrationEvent::CERTIFICATION_NOT_REQUIRED ? false : true); 113 | $stateData->minCertLevel2FA = $registrationConfig['policy_2fa']['minimum_certification_level']; 114 | $stateData->aaguidWhitelist2FA = $registrationConfig['policy_2fa']['aaguid_whitelist'] ?? []; 115 | $stateData->attFmtWhitelist2FA = $registrationConfig['policy_2fa']['attestation_format_whitelist'] ?? []; 116 | $stateData->minCertLevelPasswordless = $registrationConfig['policy_passwordless']['minimum_certification_level']; 117 | $stateData->aaguidWhitelistPasswordless = $registrationConfig['policy_passwordless']['aaguid_whitelist'] ?? []; 118 | $stateData->attFmtWhitelistPasswordless = $registrationConfig['policy_passwordless']['attestation_format_whitelist'] ?? []; 119 | // phpcs:enable Generic.Files.LineLength.TooLong 120 | 121 | try { 122 | $stateData->store = Store::parseStoreConfig($moduleConfig->getArray('store')); 123 | } catch (Exception $e) { 124 | $this->logger::error( 125 | 'webauthn: Could not create storage: ' . $e->getMessage(), 126 | ); 127 | } 128 | 129 | $stateData->scope = $moduleConfig->getOptionalString('scope', null); 130 | $httpUtils = new Utils\HTTP(); 131 | $baseurl = $httpUtils->getSelfHost(); 132 | $hostname = parse_url($baseurl, PHP_URL_HOST); 133 | if ($hostname !== null) { 134 | $stateData->derivedScope = $hostname; 135 | } 136 | $stateData->usernameAttrib = $moduleConfig->getString('identifyingAttribute'); 137 | $stateData->displaynameAttrib = $moduleConfig->getString('attrib_displayname'); 138 | 139 | StaticProcessHelper::prepareState($stateData, $state); 140 | 141 | $metadataHandler = MetaDataStorageHandler::getMetadataHandler(); 142 | $metadata = $metadataHandler->getMetaDataCurrent('saml20-idp-hosted'); 143 | $state['Source'] = $metadata; 144 | $state['IdPMetadata'] = $metadata; 145 | // inflow users are not allowed to enter the Registration page. If they 146 | // did, kill the session 147 | $moduleConfig = Configuration::getOptionalConfig('module_webauthn.php')->toArray(); 148 | 149 | if ($moduleConfig['registration']['use_inflow_registration']) { 150 | throw new Exception("Attempt to access the stand-alone registration page in inflow mode!"); 151 | } 152 | 153 | $state['Registration'] = true; 154 | $state['FIDO2WantsRegister'] = true; 155 | 156 | return new RunnableResponse([StaticProcessHelper::class, 'saveStateAndRedirect'], [&$state]); 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /src/Controller/Supercharged.php: -------------------------------------------------------------------------------- 1 | logger::info('FIDO2 - Accessing Supercharged interface'); 29 | 30 | $stateId = $request->query->get('StateId'); 31 | if ($stateId === null) { 32 | throw new Error\BadRequest('Missing required StateId query parameter.'); 33 | } 34 | 35 | $state = $this->authState::loadState($stateId, 'webauthn:request'); 36 | 37 | $templateFile = 'webauthn:supercharged.twig'; 38 | 39 | // Make, populate and layout consent form 40 | $t = new Template($this->config, $templateFile); 41 | $t->data['UserID'] = $state['FIDO2Username']; 42 | $t->data['FIDO2Tokens'] = $state['FIDO2Tokens']; 43 | // in case IdPs want to override UI and display SP-specific content 44 | $t->data['entityid'] = $state['SPMetadata']['entityid'] ?? 'WEBAUTHN-SP-NONE'; 45 | 46 | $challenge = str_split($state['FIDO2SignupChallenge'], 2); 47 | $configUtils = new Utils\Config(); 48 | $username = str_split( 49 | hash('sha512', $state['FIDO2Username'] . '|' . $configUtils->getSecretSalt()), 50 | 2, 51 | ); 52 | 53 | $challengeEncoded = []; 54 | foreach ($challenge as $oneChar) { 55 | $challengeEncoded[] = hexdec($oneChar); 56 | } 57 | 58 | $credentialIdEncoded = []; 59 | foreach ($state['FIDO2Tokens'] as $number => $token) { 60 | $idSplit = str_split($token[0], 2); 61 | $credentialIdEncoded[$number] = []; 62 | foreach ($idSplit as $credIdBlock) { 63 | $credentialIdEncoded[$number][] = hexdec($credIdBlock); 64 | } 65 | } 66 | 67 | $usernameEncoded = []; 68 | foreach ($username as $oneChar) { 69 | $usernameEncoded[] = hexdec($oneChar); 70 | } 71 | 72 | $frontendData = []; 73 | $frontendData['challengeEncoded'] = $challengeEncoded; 74 | $frontendData['state'] = []; 75 | foreach (['FIDO2Scope','FIDO2Username','FIDO2Displayname','requestTokenModel'] as $stateItem) { 76 | $frontendData['state'][$stateItem] = $state[$stateItem]; 77 | } 78 | 79 | $t->data['showExitButton'] = !array_key_exists('Registration', $state); 80 | $frontendData['usernameEncoded'] = $usernameEncoded; 81 | $frontendData['attestation'] = $state['requestTokenModel'] ? "indirect" : "none"; 82 | $frontendData['credentialIdEncoded'] = $credentialIdEncoded; 83 | $frontendData['FIDO2PasswordlessAuthMode'] = $state['FIDO2PasswordlessAuthMode']; 84 | $t->data['hasPreviouslyDonePasswordless'] = $_COOKIE['SuccessfullyUsedPasswordlessBefore'] ?? "NO"; 85 | $t->data['frontendData'] = json_encode($frontendData); 86 | 87 | $t->data['authForm'] = ""; 88 | $t->data['authURL'] = Module::getModuleURL('webauthn/authprocess?StateId=' . urlencode($stateId)); 89 | $t->data['pushbackURL'] = Module::getModuleURL('webauthn/pushbackuserpass?StateId=' . urlencode($stateId)); 90 | 91 | // dynamically generate the JS code needed for token registration 92 | return $t; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/Controller/WebAuthn.php: -------------------------------------------------------------------------------- 1 | authState = $authState; 64 | } 65 | 66 | 67 | /** 68 | * Inject the \SimpleSAML\Logger dependency. 69 | * 70 | * @param \SimpleSAML\Logger $logger 71 | */ 72 | public function setLogger(Logger $logger): void 73 | { 74 | $this->logger = $logger; 75 | } 76 | 77 | public static function workflowStateMachine(array $state) 78 | { 79 | // if we don't have any credentials yet, allow user to register 80 | // regardless if in inflow or standalone (redirect to standalone if need 81 | // be) 82 | // OTOH, if we are invoked for passwordless auth, we don't know the 83 | // username nor whether the user has any credentials. The only thing 84 | // we can do is authenticate -> final else 85 | if ( 86 | $state['FIDO2PasswordlessAuthMode'] != true && 87 | (!isset($state['FIDO2Tokens']) || count($state['FIDO2Tokens']) == 0) 88 | ) { 89 | return self::STATE_MGMT; 90 | } 91 | // from here on we do have a credential to work with 92 | // 93 | // user indicated he wants to manage tokens. He did so either by 94 | // visiting the Registration page, or by checking the box during 95 | // inflow. 96 | // If coming from inflow, allow management only if user is 97 | // properly authenticated, otherwise send to auth page 98 | if ($state['FIDO2WantsRegister']) { 99 | if ($state['FIDO2AuthSuccessful'] || $state['Registration']) { 100 | return self::STATE_MGMT; 101 | } 102 | return self::STATE_AUTH_ALLOWMGMT; 103 | } else { // in inflow, allow to check the management box; otherwise, 104 | // only auth 105 | $moduleConfig = Configuration::getOptionalConfig('module_webauthn.php')->toArray(); 106 | return $moduleConfig['registration']['use_inflow_registration'] ? 107 | self::STATE_AUTH_ALLOWMGMT : self::STATE_AUTH_NOMGMT; 108 | } 109 | } 110 | 111 | public static function loadModuleConfig(array $moduleConfig, StateData &$stateData): void 112 | { 113 | $stateData->store = Store::parseStoreConfig($moduleConfig['store']); 114 | 115 | // Set the optional scope if set by configuration 116 | if (array_key_exists('scope', $moduleConfig)) { 117 | $stateData->scope = $moduleConfig['scope']; 118 | } 119 | 120 | // Set the derived scope so we can compare it to the sent host at a later point 121 | $httpUtils = new Utils\HTTP(); 122 | $baseurl = $httpUtils->getSelfHost(); 123 | $hostname = parse_url($baseurl, PHP_URL_HOST); 124 | if ($hostname !== null) { 125 | $stateData->derivedScope = $hostname; 126 | } 127 | 128 | if (array_key_exists('identifyingAttribute', $moduleConfig)) { 129 | $stateData->usernameAttrib = $moduleConfig['identifyingAttribute']; 130 | } else { 131 | throw new Error\CriticalConfigurationError( 132 | 'webauthn: it is required to set identifyingAttribute in config.', 133 | ); 134 | } 135 | 136 | if (array_key_exists('attrib_displayname', $moduleConfig)) { 137 | $stateData->displaynameAttrib = $moduleConfig['attrib_displayname']; 138 | } else { 139 | throw new Error\CriticalConfigurationError( 140 | 'webauthn: it is required to set attrib_displayname in config.', 141 | ); 142 | } 143 | 144 | if (array_key_exists('minimum_certification_level', $moduleConfig['registration']['policy_2fa'])) { 145 | // phpcs:disable Generic.Files.LineLength.TooLong 146 | $stateData->requestTokenModel = ($moduleConfig['registration']['policy_2fa']['minimum_certification_level'] == Module\webauthn\WebAuthn\WebAuthnRegistrationEvent::CERTIFICATION_NOT_REQUIRED ? false : true); 147 | $stateData->minCertLevel2FA = $moduleConfig['registration']['policy_2fa']['minimum_certification_level']; 148 | $stateData->aaguidWhitelist2FA = $moduleConfig['registration']['policy_2fa']['aaguid_whitelist'] ?? []; 149 | $stateData->attFmtWhitelist2FA = $moduleConfig['registration']['policy_2fa']['attestation_format_whitelist'] ?? []; 150 | $stateData->minCertLevelPasswordless = $moduleConfig['registration']['policy_passwordless']['minimum_certification_level']; 151 | $stateData->aaguidWhitelistPasswordless = $moduleConfig['registration']['policy_passwordless']['aaguid_whitelist'] ?? []; 152 | $stateData->attFmtWhitelistPasswordless = $moduleConfig['registration']['policy_passwordless']['attestation_format_whitelist'] ?? []; 153 | // phpcs:enable Generic.Files.LineLength.TooLong 154 | } else { 155 | $stateData->requestTokenModel = false; 156 | } 157 | } 158 | 159 | 160 | /** 161 | * @param \Symfony\Component\HttpFoundation\Request $request 162 | * @return \SimpleSAML\XHTML\Template A Symfony Response-object. 163 | */ 164 | public function main(Request $request): Template 165 | { 166 | $this->logger::info('FIDO2 - Accessing WebAuthn interface'); 167 | 168 | $stateId = $request->query->get('StateId'); 169 | if ($stateId === null) { 170 | throw new Error\BadRequest('Missing required StateId query parameter.'); 171 | } 172 | 173 | $state = $this->authState::loadState($stateId, 'webauthn:request'); 174 | 175 | if ($this->workflowStateMachine($state) != self::STATE_AUTH_NOMGMT) { 176 | $templateFile = 'webauthn:webauthn.twig'; 177 | } else { 178 | $templateFile = 'webauthn:authentication.twig'; 179 | } 180 | 181 | // Make, populate and layout consent form 182 | $t = new Template($this->config, $templateFile); 183 | $t->data['UserID'] = $state['FIDO2Username']; 184 | $t->data['FIDO2Tokens'] = $state['FIDO2Tokens']; 185 | // in case IdPs want to override UI and display SP-specific content 186 | $t->data['entityid'] = $state['SPMetadata']['entityid'] ?? 'WEBAUTHN-SP-NONE'; 187 | 188 | $challenge = str_split($state['FIDO2SignupChallenge'], 2); 189 | $configUtils = new Utils\Config(); 190 | $username = str_split( 191 | hash('sha512', $state['FIDO2Username'] . '|' . $configUtils->getSecretSalt()), 192 | 2, 193 | ); 194 | 195 | $challengeEncoded = []; 196 | foreach ($challenge as $oneChar) { 197 | $challengeEncoded[] = hexdec($oneChar); 198 | } 199 | 200 | $credentialIdEncoded = []; 201 | foreach ($state['FIDO2Tokens'] as $number => $token) { 202 | $idSplit = str_split($token[0], 2); 203 | $credentialIdEncoded[$number] = []; 204 | foreach ($idSplit as $credIdBlock) { 205 | $credentialIdEncoded[$number][] = hexdec($credIdBlock); 206 | } 207 | } 208 | 209 | $usernameEncoded = []; 210 | foreach ($username as $oneChar) { 211 | $usernameEncoded[] = hexdec($oneChar); 212 | } 213 | 214 | $frontendData = []; 215 | $frontendData['challengeEncoded'] = $challengeEncoded; 216 | $frontendData['state'] = []; 217 | foreach (['FIDO2Scope','FIDO2Username','FIDO2Displayname','requestTokenModel'] as $stateItem) { 218 | $frontendData['state'][$stateItem] = $state[$stateItem]; 219 | } 220 | 221 | $t->data['showExitButton'] = !array_key_exists('Registration', $state); 222 | $frontendData['usernameEncoded'] = $usernameEncoded; 223 | $frontendData['attestation'] = $state['requestTokenModel'] ? "indirect" : "none"; 224 | $frontendData['credentialIdEncoded'] = $credentialIdEncoded; 225 | $frontendData['FIDO2PasswordlessAuthMode'] = $state['FIDO2PasswordlessAuthMode']; 226 | $t->data['frontendData'] = json_encode($frontendData); 227 | 228 | $t->data['FIDO2AuthSuccessful'] = $state['FIDO2AuthSuccessful']; 229 | if ($this->workflowStateMachine($state) == self::STATE_MGMT) { 230 | $t->data['regURL'] = Module::getModuleURL('webauthn/regprocess?StateId=' . urlencode($stateId)); 231 | $t->data['delURL'] = Module::getModuleURL('webauthn/managetoken?StateId=' . urlencode($stateId)); 232 | } 233 | 234 | $t->data['authForm'] = ""; 235 | if ( 236 | $this->workflowStateMachine($state) == self::STATE_AUTH_ALLOWMGMT || 237 | $this->workflowStateMachine($state) == self::STATE_AUTH_NOMGMT 238 | ) { 239 | $t->data['authURL'] = Module::getModuleURL('webauthn/authprocess?StateId=' . urlencode($stateId)); 240 | $t->data['delURL'] = Module::getModuleURL('webauthn/managetoken?StateId=' . urlencode($stateId)); 241 | } 242 | 243 | // dynamically generate the JS code needed for token registration 244 | return $t; 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /src/Store.php: -------------------------------------------------------------------------------- 1 | 17 | * @author JAcob Christiansen 18 | */ 19 | 20 | abstract class Store 21 | { 22 | /** 23 | * Constructor for the base class. 24 | * 25 | * This constructor should always be called first in any class which implements this class. 26 | * 27 | * @param array &$config The configuration for this storage handler. 28 | * @phpstan-ignore constructor.unusedParameter 29 | */ 30 | protected function __construct(array &$config) 31 | { 32 | } 33 | 34 | /** 35 | * is the user subject to 2nd factor at all? 36 | * 37 | * This function checks whether a given user has been enabled for WebAuthn. 38 | * 39 | * @param string $userId The hash identifying the user at an IdP. 40 | * @param bool $defaultIfNx if not found in the DB, should the user be considered enabled (true) 41 | * or disabled(false) 42 | * @param bool $useDatabase a bool that determines whether to use local database or not 43 | * @param bool $toggle variable which is associated with $force because it determines its meaning, it either 44 | * simply means whether to trigger webauthn authentication or switch the default settings, 45 | * @param bool $force switch that determines how $toggle will be used, if true then value of $toggle 46 | * will mean whether to trigger (true) or not (false) the webauthn authentication, 47 | * if false then $toggle means whether to switch the value of $defaultEnabled and then use that 48 | * 49 | * @return bool True if the user is enabled for 2FA, false if not 50 | */ 51 | abstract public function is2FAEnabled( 52 | string $userId, 53 | bool $defaultIfNx, 54 | bool $useDatabase = true, 55 | bool $toggle = false, 56 | bool $force = true, 57 | ): bool; 58 | 59 | /** 60 | * does a given credentialID already exist? 61 | * 62 | * This function checks whether a given credential ID already exists in the database 63 | * 64 | * @param string $credIdHex The hex representation of the credentialID to look for. 65 | * 66 | * @return bool True if the credential exists, false if not 67 | */ 68 | abstract public function doesCredentialExist(string $credIdHex): bool; 69 | 70 | /** 71 | * store newly enrolled token data 72 | * 73 | * @param string $userId The user. 74 | * @param string $credentialId The id identifying the credential. 75 | * @param string $credential The credential. 76 | * @param int $algo The algorithm used. 77 | * @param int $presenceLevel UV or UP? 78 | * @param int $signCounter The signature counter for this credential. 79 | * @param string $friendlyName A user-supplied name for this token. 80 | * @param string $hashedId hashed ID of the user 81 | * 82 | * @return bool 83 | */ 84 | abstract public function storeTokenData( 85 | string $userId, 86 | string $credentialId, 87 | string $credential, 88 | int $algo, 89 | int $presenceLevel, 90 | int $isResidentKey, 91 | int $signCounter, 92 | string $friendlyName, 93 | string $hashedId, 94 | string $aaguid, 95 | string $attLevel, 96 | ): bool; 97 | 98 | /** 99 | * remove an existing credential from the database 100 | * 101 | * @param string $credentialId the credential 102 | * @return true 103 | */ 104 | abstract public function deleteTokenData(string $credentialId): bool; 105 | 106 | /** 107 | * increment the signature counter after a successful authentication 108 | * 109 | * @param string $credentialId the credential 110 | * @param int $signCounter the new counter value 111 | * @return true 112 | */ 113 | abstract public function updateSignCount(string $credentialId, int $signCounter): bool; 114 | 115 | /** 116 | * Retrieve existing token data 117 | * 118 | * @param string $userId the username 119 | * @return array Array of all crypto data we have on file. 120 | */ 121 | abstract public function getTokenData(string $userId): array; 122 | 123 | /** 124 | * Retrieve username, given a credential ID 125 | * 126 | * @param string $hashedId the credential ID 127 | * @return string the username, if found (otherwise, empty string) 128 | */ 129 | abstract public function getUsernameByHashedId(string $hashedId): string; 130 | 131 | /** 132 | * Get statistics for all consent given in the consent store 133 | * 134 | * @return mixed Statistics from the consent store 135 | * 136 | * @throws \Exception 137 | */ 138 | public function getStatistics() 139 | { 140 | throw new Exception('Not implemented: getStatistics()'); 141 | } 142 | 143 | 144 | /** 145 | * Parse consent storage configuration. 146 | * 147 | * This function parses the configuration for a consent storage method. An exception will be thrown if 148 | * configuration parsing fails. 149 | * 150 | * @param string|array $config The configuration. 151 | * 152 | * @return \SimpleSAML\Module\webauthn\Store An object which implements the \SimpleSAML\Module\webauthn\Store class. 153 | * 154 | * @throws \Exception if the configuration is invalid. 155 | */ 156 | public static function parseStoreConfig(string|array $config): Store 157 | { 158 | if (is_string($config)) { 159 | $arrayUtils = new Utils\Arrays(); 160 | $config = $arrayUtils->arrayize($config); 161 | } 162 | 163 | Assert::isArray($config, 'Invalid configuration for consent store option: ' . var_export($config, true)); 164 | Assert::keyExists($config, 0, 'Consent store without name given.'); 165 | 166 | $className = Module::resolveClass( 167 | $config[0], 168 | 'WebAuthn\Store', 169 | '\SimpleSAML\Module\webauthn\Store', 170 | ); 171 | 172 | /** @var \SimpleSAML\Module\webauthn\Store */ 173 | return new $className($config); 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /src/WebAuthn/AAGUID.php: -------------------------------------------------------------------------------- 1 | getConfigDir() . '/' . self::AAGUID_CONFIG_FILE; 46 | if (!file_exists($path)) { 47 | Logger::warning("Missing AAGUID configuration file ($path). No device will be recognized."); 48 | return; 49 | } 50 | 51 | $data = file_get_contents($path); 52 | $json = json_decode($data, true); 53 | if (!is_array($json)) { 54 | // there was probably an error decoding the config, log the error and pray for the best 55 | Logger::warning('Broken configuration file "' . $path . '": could not JSON-decode it.'); 56 | } else { 57 | $this->dictionary = $json; 58 | } 59 | } 60 | 61 | 62 | /** 63 | * Get the singleton instance of the AAGUID dictionary. 64 | * 65 | * @return self 66 | */ 67 | public static function getInstance(): self 68 | { 69 | if (!isset(self::$instance)) { 70 | self::$instance = new self(); 71 | } 72 | return self::$instance; 73 | } 74 | 75 | 76 | /** 77 | * Determine if an AAGUID is known 78 | * 79 | * @param string $aaguid The AAGUID that we want to check. 80 | * 81 | * @return bool True if we know about this token, false otherwise. 82 | */ 83 | public function hasToken(string $aaguid): bool 84 | { 85 | $lowerAaguid = strtolower($aaguid); 86 | if (array_key_exists($lowerAaguid, $this->dictionary)) { 87 | return true; 88 | } else { 89 | Logger::info("AAGUID $lowerAaguid not found in dictionary, device is unknown."); 90 | return false; 91 | } 92 | } 93 | 94 | 95 | /** 96 | * Get the information for a given AAGUID. 97 | * 98 | * @param string $aaguid The AAGUID we want to get. 99 | * 100 | * @return array An array containing information about the given AAGUID, or an empty array if that AAGUID is 101 | * unknown. 102 | */ 103 | public function get(string $aaguid): array 104 | { 105 | if (!$this->hasToken($aaguid)) { 106 | return []; 107 | } 108 | return $this->dictionary[$aaguid]; 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /src/WebAuthn/StateData.php: -------------------------------------------------------------------------------- 1 | standalone registration page, if true => inflow registration. 64 | * Defaults to true. 65 | */ 66 | public bool $useInflowRegistration; 67 | } 68 | -------------------------------------------------------------------------------- /src/WebAuthn/StaticProcessHelper.php: -------------------------------------------------------------------------------- 1 | redirectTrustedURL($url, ['StateId' => $id]); 20 | } 21 | 22 | public static function saveStateAndRedirectSupercharged(array &$state): void 23 | { 24 | $id = Auth\State::saveState($state, 'webauthn:request'); 25 | $url = Module::getModuleURL('webauthn/supercharged'); 26 | $httpUtils = new Utils\HTTP(); 27 | $httpUtils->redirectTrustedURL($url, ['StateId' => $id]); 28 | } 29 | 30 | public static function prepareState(StateData $stateData, array &$state): void 31 | { 32 | $state['requestTokenModel'] = $stateData->requestTokenModel; 33 | $state['authenticatorAcceptability2FA'] = [ 34 | 'minCertLevel' => $stateData->minCertLevel2FA, 35 | 'aaguidWhitelist' => $stateData->aaguidWhitelist2FA, 36 | 'attFmtWhitelist' => $stateData->attFmtWhitelist2FA, 37 | ]; 38 | $state['authenticatorAcceptabilityPasswordless'] = [ 39 | 'minCertLevel' => $stateData->minCertLevelPasswordless, 40 | 'aaguidWhitelist' => $stateData->aaguidWhitelistPasswordless, 41 | 'attFmtWhitelist' => $stateData->attFmtWhitelistPasswordless, 42 | ]; 43 | $state['webauthn:store'] = $stateData->store; 44 | $state['FIDO2Tokens'] = $stateData->store->getTokenData($state['Attributes'][$stateData->usernameAttrib][0]); 45 | $state['FIDO2Scope'] = $stateData->scope; 46 | $state['FIDO2DerivedScope'] = $stateData->derivedScope; 47 | $state['FIDO2AttributeStoringUsername'] = $stateData->usernameAttrib; 48 | $state['FIDO2Username'] = $state['Attributes'][$stateData->usernameAttrib][0]; 49 | $state['FIDO2Displayname'] = $state['Attributes'][$stateData->displaynameAttrib][0]; 50 | $state['FIDO2SignupChallenge'] = hash('sha512', random_bytes(64)); 51 | $state['FIDO2WantsRegister'] = false; 52 | $state['FIDO2AuthSuccessful'] = false; 53 | $state['FIDO2PasswordlessAuthMode'] = false; 54 | } 55 | 56 | public static function prepareStatePasswordlessAuth(StateData $stateData, array &$state): void 57 | { 58 | $state['requestTokenModel'] = $stateData->requestTokenModel; 59 | $state['webauthn:store'] = $stateData->store; 60 | $state['FIDO2Scope'] = $stateData->scope; 61 | $state['FIDO2DerivedScope'] = $stateData->derivedScope; 62 | $state['FIDO2AttributeStoringUsername'] = $stateData->usernameAttrib; 63 | $state['FIDO2SignupChallenge'] = hash('sha512', random_bytes(64)); 64 | $state['FIDO2PasswordlessAuthMode'] = true; 65 | $state['FIDO2AuthSuccessful'] = false; 66 | $state['FIDO2Tokens'] = []; // we don't know which token comes in. 67 | $state['FIDO2Username'] = 'notauthenticated'; 68 | $state['FIDO2Displayname'] = 'User Not Authenticated Yet'; 69 | $state['FIDO2WantsRegister'] = false; 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/WebAuthn/Store/Database.php: -------------------------------------------------------------------------------- 1 | 26 | * @package SimpleSAMLphp 27 | */ 28 | 29 | class Database extends Store 30 | { 31 | /** 32 | * Database handle. 33 | * 34 | * This variable can't be serialized. 35 | */ 36 | private SSP_Database $db; 37 | 38 | 39 | /** 40 | * The configuration for our database store. 41 | * 42 | * @var array 43 | */ 44 | private array $config; 45 | 46 | 47 | /** 48 | * Parse configuration. 49 | * 50 | * This constructor parses the configuration. 51 | * 52 | * @param array $config Configuration for database consent store. 53 | * 54 | * @throws \Exception in case of a configuration error. 55 | */ 56 | public function __construct(array $config) 57 | { 58 | parent::__construct($config); 59 | $this->config = $config; 60 | $this->db = SSP_Database::getInstance(Configuration::loadFromArray($config)); 61 | $driver = $this->db->getDriver(); 62 | // phpcs:disable Generic.Files.LineLength.TooLong 63 | try { 64 | $this->db->read("SELECT COUNT(*) FROM credentials"); 65 | } catch (\Exception $e) { 66 | $this->db->write(" 67 | CREATE TABLE IF NOT EXISTS credentials ( 68 | creation_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, 69 | user_id VARCHAR(80) NOT NULL, 70 | credentialId VARCHAR(1024) " . ($driver === 'mysql' ? "CHARACTER SET 'binary'" : '') . " NOT NULL, 71 | credential " . ($driver === 'pgsql' ? 'BYTEA' : 'MEDIUMBLOB') . " NOT NULL, 72 | algo INT DEFAULT NULL, 73 | presenceLevel INT DEFAULT NULL, 74 | isResidentKey BOOLEAN DEFAULT NULL, 75 | signCounter INT NOT NULL, 76 | friendlyName VARCHAR(100) DEFAULT 'Unnamed Token', 77 | hashedId VARCHAR(128) DEFAULT '---', 78 | aaguid VARCHAR(64) DEFAULT NULL, 79 | " . ($driver === 'pgsql' 80 | ? "attLevel VARCHAR(6) NOT NULL DEFAULT 'None' CHECK (attLevel IN ('None','Basic','Self','AttCA'))," 81 | : "attLevel ENUM('None','Basic','Self','AttCA') NOT NULL DEFAULT 'None',") 82 | . " 83 | lastUsedTime TIMESTAMP DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(), 84 | lastUsedIp VARCHAR(64) DEFAULT NULL, 85 | CONSTRAINT credentials_user_id_credentialId_key UNIQUE (user_id, credentialId) 86 | ) 87 | "); 88 | } 89 | try { 90 | $this->db->read("SELECT COUNT(*) FROM userstatus"); 91 | } catch (\Exception $e) { 92 | $this->db->write("CREATE TABLE IF NOT EXISTS userstatus ( 93 | user_id VARCHAR(80) NOT NULL, 94 | " . ($driver === 'pgsql' 95 | ? "fido2Status VARCHAR(14) NOT NULL DEFAULT 'FIDO2Disabled' CHECK (fido2Status IN ('FIDO2Disabled', 'FIDO2Enabled'))," 96 | : "fido2Status ENUM('FIDO2Disabled','FIDO2Enabled') NOT NULL DEFAULT 'FIDO2Disabled',") 97 | . " 98 | CONSTRAINT userstatus_user_id_key UNIQUE (user_id) 99 | )"); 100 | } 101 | // phpcs:enable Generic.Files.LineLength.TooLong 102 | } 103 | 104 | /** 105 | * Called before serialization. 106 | * 107 | * @return array The variables which should be serialized. 108 | */ 109 | public function __sleep(): array 110 | { 111 | return [ 112 | 'config', 113 | ]; 114 | } 115 | 116 | 117 | /** 118 | * Called after unserialization. 119 | * @return void 120 | */ 121 | public function __wakeup(): void 122 | { 123 | $this->db = SSP_Database::getInstance(Configuration::loadFromArray($this->config)); 124 | } 125 | 126 | 127 | /** 128 | * is the user subject to 2nd factor at all? 129 | * 130 | * This function checks whether a given user has been enabled for WebAuthn. 131 | * 132 | * @param string $userId The hash identifying the user at an IdP. 133 | * @param bool $defaultIfNx if not found in the DB, should the user be considered enabled (true) 134 | * or disabled(false) 135 | * @param bool $useDatabase a bool that determines whether to use local database or not 136 | * @param bool $toggle variable which is associated with $force because it determines its meaning, it either 137 | * simply means whether to trigger webauthn authentication or switch the default settings, 138 | * @param bool $force switch that determines how $toggle will be used, if true then value of $toggle 139 | * will mean whether to trigger (true) or not (false) the webauthn authentication, 140 | * if false then $toggle means whether to switch the value of $defaultEnabled and then use that 141 | * 142 | * @return bool True if the user is enabled for 2FA, false if not 143 | */ 144 | public function is2FAEnabled( 145 | string $userId, 146 | bool $defaultIfNx, 147 | bool $useDatabase = true, 148 | bool $toggle = false, 149 | bool $force = true, 150 | ): bool { 151 | if (!$useDatabase) { 152 | if ($force) { 153 | return $toggle; 154 | } else { 155 | return $toggle ? !$defaultIfNx : $defaultIfNx; 156 | } 157 | } 158 | $st = $this->db->read('SELECT COUNT(*) FROM userstatus WHERE user_id = :userId', ['userId' => $userId]); 159 | 160 | $c = $st->fetchColumn(); 161 | if ($c == 0) { 162 | Logger::debug('User does not exist in DB, returning desired default.'); 163 | return $defaultIfNx; 164 | } else { 165 | $st2 = $this->db->read( 166 | "SELECT COUNT(*) FROM userstatus WHERE user_id = :userId AND fido2Status = 'FIDO2Disabled'", 167 | ['userId' => $userId], 168 | ); 169 | $rowCount2 = $st2->fetchColumn(); 170 | if ($rowCount2 === 1 /* explicitly disabled user in DB */) { 171 | return false; 172 | } 173 | Logger::debug('User exists and is not disabled -> enabled.'); 174 | return true; 175 | } 176 | } 177 | 178 | 179 | /** 180 | * does a given credentialID already exist? 181 | * 182 | * This function checks whether a given credential ID already exists in the database 183 | * 184 | * @param string $credIdHex The hex representation of the credentialID to look for. 185 | * 186 | * @return bool True if the credential exists, false if not 187 | */ 188 | public function doesCredentialExist(string $credIdHex): bool 189 | { 190 | $st = $this->db->read( 191 | 'SELECT COUNT(*) FROM credentials WHERE credentialId = :credentialId', 192 | ['credentialId' => $credIdHex], 193 | ); 194 | 195 | $rowCount = $st->fetchColumn(); 196 | if (!$rowCount) { 197 | Logger::debug('Credential does not exist yet.'); 198 | return false; 199 | } else { 200 | Logger::debug('Credential exists.'); 201 | return true; 202 | } 203 | } 204 | 205 | 206 | /** 207 | * store newly enrolled token data 208 | * 209 | * @param string $userId The user. 210 | * @param string $credentialId The id identifying the credential. 211 | * @param string $credential The credential. 212 | * @param int $algo The algorithm used. 213 | * @param int $presenceLevel UV or UP? 214 | * @param int $signCounter The signature counter for this credential. 215 | * @param string $friendlyName A user-supplied name for this token. 216 | * @param string $hashedId hashed user ID 217 | * 218 | * @return true 219 | */ 220 | public function storeTokenData( 221 | string $userId, 222 | string $credentialId, 223 | string $credential, 224 | int $algo, 225 | int $presenceLevel, 226 | int $isResidentKey, 227 | int $signCounter, 228 | string $friendlyName, 229 | string $hashedId, 230 | string $aaguid, 231 | string $attLevel, 232 | ): bool { 233 | // phpcs:disable Generic.Files.LineLength.TooLong 234 | $this->db->write( 235 | 'INSERT INTO credentials ' . 236 | '(user_id, credentialId, credential, algo, presenceLevel, isResidentKey, signCounter, friendlyName, hashedId, aaguid, attLevel) VALUES ' . 237 | '(:userId,:credentialId,:credential,:algo,:presenceLevel,:isResidentKey,:signCounter,:friendlyName,:hashedId,:aaguid,:attLevel)', 238 | [ 239 | 'userId' => $userId, 240 | 'credentialId' => $credentialId, 241 | 'credential' => $credential, 242 | 'algo' => $algo, 243 | 'presenceLevel' => $presenceLevel, 244 | 'isResidentKey' => $isResidentKey, 245 | 'signCounter' => $signCounter, 246 | 'friendlyName' => $friendlyName, 247 | 'hashedId' => $hashedId, 248 | 'aaguid' => $aaguid, 249 | 'attLevel' => $attLevel, 250 | ], 251 | ); 252 | // phpcs:enable Generic.Files.LineLength.TooLong 253 | 254 | return true; 255 | } 256 | 257 | 258 | /** 259 | * remove an existing credential from the database 260 | * 261 | * @param string $credentialId the credential 262 | * @return true 263 | */ 264 | public function deleteTokenData(string $credentialId): bool 265 | { 266 | $this->db->write( 267 | 'DELETE FROM credentials WHERE credentialId = :credentialId', 268 | ['credentialId' => $credentialId], 269 | ); 270 | 271 | Logger::debug('webauthn:Database - DELETED credential.'); 272 | 273 | return true; 274 | } 275 | 276 | 277 | /** 278 | * increment the signature counter after a successful authentication 279 | * 280 | * @param string $credentialId the credential 281 | * @param int $signCounter the new counter value 282 | * @return true 283 | */ 284 | public function updateSignCount(string $credentialId, int $signCounter): bool 285 | { 286 | $this->db->write( 287 | 'UPDATE credentials SET signCounter = :signCounter WHERE credentialId = :credentialId', 288 | ['signCounter' => $signCounter, 'credentialId' => $credentialId], 289 | ); 290 | 291 | Logger::debug('webauthn:Database - UPDATED signature counter.'); 292 | 293 | return true; 294 | } 295 | 296 | 297 | /** 298 | * Retrieve existing token data 299 | * 300 | * @param string $userId the username 301 | * @return array Array of all crypto data we have on file. 302 | */ 303 | public function getTokenData(string $userId): array 304 | { 305 | $ret = []; 306 | 307 | $st = $this->db->read( 308 | // phpcs:ignore Generic.Files.LineLength.TooLong 309 | 'SELECT credentialId, credential, signCounter, friendlyName, algo, presenceLevel, isResidentKey FROM credentials WHERE user_id = :userId', 310 | ['userId' => $userId], 311 | ); 312 | 313 | while ($row = $st->fetch(PDO::FETCH_NUM)) { 314 | if (is_resource($row[1])) { 315 | $row[1] = stream_get_contents($row[1]); 316 | } 317 | $ret[] = $row; 318 | } 319 | 320 | return $ret; 321 | } 322 | 323 | /** 324 | * Retrieve username, given a credential ID 325 | * 326 | * @param string $hashedId the credential ID 327 | * @return string the username, if found (otherwise, empty string) 328 | */ 329 | public function getUsernameByHashedId(string $hashedId): string 330 | { 331 | $st = $this->db->read( 332 | 'SELECT user_id FROM credentials WHERE hashedId = :hashId', 333 | ['hashId' => $hashedId], 334 | ); 335 | 336 | // return on first match, credential IDs are unique 337 | while ($row = $st->fetch(PDO::FETCH_NUM)) { 338 | return $row[0]; 339 | } 340 | 341 | return ""; 342 | } 343 | } 344 | -------------------------------------------------------------------------------- /src/WebAuthn/WebAuthnAbstractEvent.php: -------------------------------------------------------------------------------- 1 | 21 | * @package SimpleSAMLphp 22 | */ 23 | abstract class WebAuthnAbstractEvent 24 | { 25 | public const PRESENCE_LEVEL_PRESENT = 1; 26 | public const PRESENCE_LEVEL_VERIFIED = 4; 27 | public const PRESENCE_LEVEL_NONE = 0; 28 | 29 | /** 30 | * The SHA256 hash of the clientDataJSON 31 | * 32 | * @var string 33 | */ 34 | protected string $clientDataHash; 35 | 36 | /** 37 | * the authenticator's signature counter 38 | * 39 | * @var int 40 | */ 41 | protected int $counter; 42 | 43 | /** 44 | * the authenticator's signature algorithm 45 | * 46 | * @var int 47 | */ 48 | protected int $algo; 49 | 50 | /** 51 | * UV or UP bit? 52 | */ 53 | protected int $presenceLevel; 54 | 55 | /** 56 | * A string buffer to hold debug information in case we need it. 57 | * 58 | * @var string 59 | */ 60 | protected string $debugBuffer = ''; 61 | 62 | /** 63 | * A string buffer to hold raw validation data in case we want to look at it. 64 | * 65 | * @var string 66 | */ 67 | protected string $validateBuffer = ''; 68 | 69 | /** 70 | * the type of event requested. This is to be set in child class constructors 71 | * before calling the parent's. 72 | * 73 | * @var string 74 | */ 75 | protected string $eventType; 76 | 77 | /** 78 | * The rpIdHash, available once validated during constructor of base class 79 | */ 80 | protected string $rpIdHash; 81 | 82 | /** 83 | * the credential ID for this event (either the one that gets registered, or 84 | * the one that gets used to authenticate) 85 | * 86 | * To be set by the constructors of the child classes. 87 | * 88 | * @var string 89 | */ 90 | protected string $credentialId; 91 | 92 | /** 93 | * the credential binary data for this event (either the one that gets 94 | * registered, or the one that gets used to authenticate) 95 | * 96 | * To be set by the constructors of the child classes. 97 | * 98 | * @var string 99 | */ 100 | protected string $credential; 101 | 102 | 103 | /** 104 | * Initialize the event object. 105 | * 106 | * Validates and parses the configuration. 107 | * 108 | * @param string $pubkeyCredType PublicKeyCredential.type 109 | * @param string $scope the scope of the event 110 | * @param string $challenge the challenge which was used to trigger this event 111 | * @param string $authData the authData / authenticatorData structure which is present in all types of events 112 | * @param string $clientDataJSON the client data JSON string which is present in all types of events 113 | * @param bool $debugMode shall we collect and output some extensive debugging information along the way? 114 | */ 115 | public function __construct( 116 | string $pubkeyCredType, 117 | protected string $scope, 118 | protected string $challenge, 119 | string $authData, 120 | string $clientDataJSON, 121 | protected bool $debugMode = false, 122 | ) { 123 | $this->presenceLevel = self::PRESENCE_LEVEL_NONE; 124 | $this->debugBuffer .= "PublicKeyCredential.type: $pubkeyCredType
"; 125 | /** 126 | * This is not a required validation as per spec. Still odd that Firefox returns 127 | * "undefined" even though its own API spec says it will send "public-key". 128 | */ 129 | switch ($pubkeyCredType) { 130 | case "public-key": 131 | $this->pass("Key Type OK"); 132 | break; 133 | case "undefined": 134 | $this->warn("Key Type 'undefined' - Firefox or Yubikey issue?"); 135 | break; 136 | default: 137 | $this->fail("Unknown Key Type: " . $_POST['type']); 138 | break; 139 | } 140 | 141 | /** 142 | * eventType is already set by child constructor, otherwise the function 143 | * will fail because of the missing type) 144 | */ 145 | $this->clientDataHash = $this->verifyClientDataJSON($clientDataJSON); 146 | $this->counter = $this->validateAuthData($authData); 147 | } 148 | 149 | /** 150 | * @return int 151 | */ 152 | public function getCounter(): int 153 | { 154 | return $this->counter; 155 | } 156 | 157 | /** 158 | * @return string 159 | */ 160 | public function getCredential(): string 161 | { 162 | return $this->credential; 163 | } 164 | 165 | /** 166 | * @return int 167 | */ 168 | public function getAlgo(): int 169 | { 170 | return $this->algo; 171 | } 172 | 173 | /** 174 | * @return int 175 | */ 176 | public function getPresenceLevel(): int 177 | { 178 | return $this->presenceLevel; 179 | } 180 | 181 | /** 182 | * @return string 183 | */ 184 | public function getCredentialId(): string 185 | { 186 | return $this->credentialId; 187 | } 188 | 189 | /** 190 | * @return string 191 | */ 192 | public function getDebugBuffer(): string 193 | { 194 | return $this->debugBuffer; 195 | } 196 | 197 | /** 198 | * @return string 199 | */ 200 | public function getValidateBuffer(): string 201 | { 202 | return $this->validateBuffer; 203 | } 204 | 205 | /** 206 | * The base64url decode function differs slightly from base64. Thanks. 207 | * 208 | * taken from https://gist.github.com/nathggns/6652997 209 | * 210 | * @param string $data the base64url-encoded source string 211 | * @return string the decoded string 212 | */ 213 | public static function base64urlDecode(string $data): string 214 | { 215 | return base64_decode(strtr($data, '-_', '+/')); 216 | } 217 | 218 | /** 219 | * this function validates the content of clientDataJSON. 220 | * I.e. it performs 221 | * - for a REGistration session 222 | * - the validation steps 2 through 8 of the validation 223 | * - the parts of step 14 that relate to clientDataJSON 224 | * - for a AUTHentication session 225 | * - the validation steps 6 through 11 of the validation 226 | * - the parts of step 15 that relate to clientDataJSON 227 | * 228 | * @param string $clientDataJSON the incoming data 229 | * 230 | * @return string 231 | */ 232 | private function verifyClientDataJSON(string $clientDataJSON): string 233 | { 234 | /** 235 | * §7.1 STEP 2 + 3 : convert to JSON and dissect JSON into PHP associative array 236 | * §7.2 STEP 6 + 7 : convert to JSON and dissect JSON into PHP associative array 237 | */ 238 | $this->debugBuffer .= "ClientDataJSON hash: " . hash("sha256", $clientDataJSON) . "
"; 239 | $clientData = json_decode($clientDataJSON, true); 240 | $this->debugBuffer .= "
" . /** @scrutinizer ignore-type */ print_r($clientData, true) . "
"; 241 | switch ($this->eventType) { 242 | case "REG": 243 | if ($clientData['type'] == "webauthn.create") { 244 | /** 245 | * §7.1 STEP 4 wheck for webauthn.create 246 | */ 247 | $this->pass("Registration requested; type has expected value"); 248 | } else { 249 | $this->fail("REG requested, but did not receive webauthn.create."); 250 | } 251 | break; 252 | case "AUTH": 253 | if ($clientData['type'] == "webauthn.get") { 254 | /** 255 | * §7.2 STEP 8: check for webauthn.get 256 | */ 257 | $this->pass("Authentication requested; type has expected value"); 258 | } else { 259 | $this->fail("AUTH requested, but did not receive webauthn.get."); 260 | } 261 | break; 262 | default: 263 | $this->fail("Unexpected operation " . $this->eventType); 264 | break; 265 | } 266 | 267 | /** 268 | * §7.1 STEP 5 : check if incoming challenge matches issued challenge 269 | * §7.2 STEP 9 : check if incoming challenge matches issued challenge 270 | */ 271 | if ($this->challenge == bin2hex(WebAuthnAbstractEvent::base64urlDecode($clientData['challenge']))) { 272 | $this->pass("Challenge matches"); 273 | } else { 274 | $this->fail("Challenge does not match"); 275 | } 276 | 277 | /** 278 | * §7.1 STEP 6 : check if incoming origin matches our hostname (taken from IdP metadata prefix) 279 | * §7.2 STEP 10: check if incoming origin matches our hostname (taken from IdP metadata prefix) 280 | */ 281 | $httpHeler = new HTTPHelper(); 282 | $slash = strpos($httpHeler->getBaseURL(), '/', 8); 283 | $expectedOrigin = ($slash !== false) ? substr($httpHeler->getBaseURL(), 0, $slash) : $slash; 284 | if ($clientData['origin'] === $expectedOrigin) { 285 | $this->pass("Origin matches"); 286 | } else { 287 | $this->fail("Origin does not match: " . $expectedOrigin); 288 | } 289 | 290 | /** 291 | * §7.1 STEP 7 : optional tokenBinding check. The Yubikey does not make use of that option. 292 | * §7.2 STEP 11: optional tokenBinding check. The Yubikey does not make use of that option. 293 | */ 294 | if (!isset($clientData['tokenBinding'])) { 295 | $this->pass("No optional token binding data to validate."); 296 | } else { 297 | $this->warn("Validation of the present token binding data not implemented, continuing without!"); 298 | } 299 | 300 | /** 301 | * §7.1 STEP 8 : SHA-256 hashing the clientData 302 | * §7.2 STEP 16: SHA-256 hashing the clientData 303 | */ 304 | return hash("sha256", $clientDataJSON, true); 305 | } 306 | 307 | /** 308 | * This function performs the required checks on the authData (REG) or authenticatorData (AUTH) structure 309 | * 310 | * I.e. it performs 311 | * - for a REGistration session 312 | * - the validation steps 10-12 of the validation 313 | * - the parts of step 14 that relate to authData 314 | * - for a AUTHentication session 315 | * - the validation steps 12-14 of the validation 316 | * - the parts of step 15 that relate to authData 317 | * 318 | * @param string $authData the authData / authenticatorData binary blob 319 | * 320 | * @return int the current counter value of the authenticator 321 | */ 322 | private function validateAuthData(string $authData): int 323 | { 324 | $this->debugBuffer .= "AuthData:
";
325 |         $this->debugBuffer .= print_r($authData, true);
326 |         $this->debugBuffer .= "
"; 327 | 328 | /** 329 | * §7.1 STEP 10: compare incoming RpId hash with expected value 330 | * §7.2 STEP 12: compare incoming RpId hash with expected value 331 | */ 332 | if (bin2hex(substr($authData, 0, 32)) == hash("sha256", $this->scope)) { 333 | $this->pass("Relying Party hash correct."); 334 | $this->rpIdHash = hash("sha256", $this->scope); 335 | } else { 336 | $this->fail("Mismatching Relying Party hash."); 337 | } 338 | $bitfield = substr($authData, 32, 1); 339 | 340 | /** 341 | * §7.1 STEP 14 (authData part): no extensions were requested, so none are allowed to be present 342 | * §7.2 STEP 15 (authData part): no extensions were requested, so none are allowed to be present 343 | */ 344 | if ((128 & ord($bitfield)) > 0) { 345 | // so we get Extensions. We typically ignore all, but the 346 | // "credProtect" one may be interesting in the future. 347 | $this->pass("ED: Extension Data included. Interesting bits may be extracted later."); 348 | } else { 349 | $this->pass("ED: Extension Data not present."); 350 | } 351 | 352 | switch ($this->eventType) { 353 | case "REG": 354 | if ((64 & ord($bitfield)) > 0) { 355 | $this->pass("AT: Attested Credential Data Included."); 356 | } else { 357 | $this->fail("AT: not present, but required during registration."); 358 | } 359 | // REG events parse their registration-related Extensions, if 360 | // any, in the WebAuthnRegistrationEvent subclass 361 | break; 362 | case "AUTH": 363 | if ((64 & ord($bitfield)) > 0) { 364 | $this->fail("AT: Attested Credential Data Included."); 365 | } else { 366 | $this->pass("AT: not present, like it should be during an authentication."); 367 | } 368 | // AUTH events can also have extensions. Extensions, if any, 369 | // would follow after the counter. We allow them to be present 370 | // but don't currently do anything with them, so let's 371 | // just make a useless extraction here as a reminder. 372 | $extensionBytes = substr($authData, 37); 373 | if (strlen($extensionBytes) > 0) { 374 | // assign into variable and process if needed 375 | $this->cborDecode($extensionBytes); 376 | } 377 | break; 378 | default: 379 | $this->fail("unknown type of operation!"); 380 | break; 381 | } 382 | 383 | /** 384 | * §7.1 STEP 11 + 12 : check user presence (this implementation does not insist on verification currently) 385 | * §7.2 STEP 13 + 14 : check user presence (this implementation does not insist on verification currently) 386 | */ 387 | if ((4 & ord($bitfield)) > 0) { 388 | $this->presenceLevel = self::PRESENCE_LEVEL_VERIFIED; 389 | $this->pass("UV indicated: User is personally identified by the token."); 390 | } elseif ((1 & ord($bitfield)) > 0) { 391 | $this->presenceLevel = self::PRESENCE_LEVEL_PRESENT; 392 | $this->pass("UP indicated: someone is present and triggered the token."); 393 | } else { 394 | $this->fail("Neither UV nor UP asserted: user is possibly not present at computer."); 395 | } 396 | $counterBin = substr($authData, 33, 4); 397 | 398 | $counterDec = intval(bin2hex($counterBin), 16); 399 | $this->debugBuffer .= "Signature Counter: $counterDec
"; 400 | return $counterDec; 401 | } 402 | 403 | /** 404 | * this function takes a binary CBOR blob and decodes it into an associative PHP array. 405 | * 406 | * @param string $rawData the binary CBOR blob 407 | * @return array the decoded CBOR data 408 | */ 409 | protected function cborDecode(string $rawData): array 410 | { 411 | $otherObjectManager = new OtherObject\OtherObjectManager(); 412 | $otherObjectManager->add(OtherObject\SimpleObject::class); 413 | $otherObjectManager->add(OtherObject\FalseObject::class); 414 | $otherObjectManager->add(OtherObject\TrueObject::class); 415 | $otherObjectManager->add(OtherObject\NullObject::class); 416 | $otherObjectManager->add(OtherObject\UndefinedObject::class); 417 | $otherObjectManager->add(OtherObject\HalfPrecisionFloatObject::class); 418 | $otherObjectManager->add(OtherObject\SinglePrecisionFloatObject::class); 419 | $otherObjectManager->add(OtherObject\DoublePrecisionFloatObject::class); 420 | 421 | $tagManager = new Tag\TagManager(); 422 | $tagManager->add(Tag\DatetimeTag::class); 423 | $tagManager->add(Tag\TimestampTag::class); 424 | $tagManager->add(Tag\UnsignedBigIntegerTag::class); 425 | $tagManager->add(Tag\NegativeBigIntegerTag::class); 426 | $tagManager->add(Tag\DecimalFractionTag::class); 427 | $tagManager->add(Tag\BigFloatTag::class); 428 | $tagManager->add(Tag\Base64UrlEncodingTag::class); 429 | $tagManager->add(Tag\Base64EncodingTag::class); 430 | $tagManager->add(Tag\Base16EncodingTag::class); 431 | 432 | $decoder = new Decoder($tagManager, $otherObjectManager); 433 | $stream = new StringStream($rawData); 434 | 435 | $finalData = $decoder->decode($stream); 436 | if ($finalData instanceof Normalizable) { 437 | $finalData = $finalData->normalize(); 438 | } else { 439 | $this->fail("CBOR normalization failed."); 440 | } 441 | 442 | if ($finalData === null) { 443 | $this->fail("CBOR data decoding failed."); 444 | } 445 | return $finalData; 446 | } 447 | 448 | /** 449 | * @param string $text 450 | * @return void 451 | */ 452 | protected function warn(string $text): void 453 | { 454 | $this->validateBuffer .= "WARN: $text
"; 455 | } 456 | 457 | /** 458 | * @param string $text 459 | * @throws \Exception 460 | * @return void 461 | */ 462 | protected function fail(string $text): void 463 | { 464 | $this->validateBuffer .= "FAIL: $text
"; 465 | if ($this->debugMode === true) { 466 | echo $this->debugBuffer; 467 | echo $this->validateBuffer; 468 | } 469 | throw new \Exception($text); 470 | } 471 | 472 | /** 473 | * @param string $text 474 | * @return void 475 | */ 476 | protected function pass(string $text): void 477 | { 478 | $this->validateBuffer .= "PASS: $text
"; 479 | } 480 | 481 | /** 482 | * @param string $text 483 | * @return void 484 | */ 485 | protected function ignore(string $text): void 486 | { 487 | $this->validateBuffer .= "IGNORE: $text
"; 488 | } 489 | } 490 | -------------------------------------------------------------------------------- /src/WebAuthn/WebAuthnAuthenticationEvent.php: -------------------------------------------------------------------------------- 1 | 17 | * @package SimpleSAMLphp 18 | */ 19 | class WebAuthnAuthenticationEvent extends WebAuthnAbstractEvent 20 | { 21 | /** 22 | * Initialize the event object. 23 | * 24 | * Validates and parses the configuration. 25 | * 26 | * @param string $pubkeyCredType PublicKeyCredential.type 27 | * @param string $scope the scope of the event 28 | * @param string $challenge the challenge which was used to trigger this event 29 | * @param string $authData the authData binary string 30 | * @param string $clientDataJSON the client data JSON string which is present in all types of events 31 | * @param string $credentialId the credential ID 32 | * @param string $publicKey the public key which is supposed to validate the sig 33 | * (COSE format, still needs to be converted to PEM!) 34 | * @param string $signature the signature value to verify 35 | * @param bool $debugMode print debugging statements? 36 | */ 37 | public function __construct( 38 | string $pubkeyCredType, 39 | string $scope, 40 | string $challenge, 41 | string $authData, 42 | string $clientDataJSON, 43 | string $credentialId, 44 | string $publicKey, 45 | int $algo, 46 | string $signature, 47 | bool $debugMode = false, 48 | ) { 49 | $this->eventType = "AUTH"; 50 | $this->credential = $publicKey; 51 | $this->algo = $algo; 52 | $this->credentialId = $credentialId; 53 | parent::__construct($pubkeyCredType, $scope, $challenge, $authData, $clientDataJSON, $debugMode); 54 | $this->validateSignature($authData . $this->clientDataHash, $signature); 55 | } 56 | 57 | /** 58 | * @param string $sigData 59 | * @param string $signature 60 | * @return void 61 | */ 62 | private function validateSignature(string $sigData, string $signature): void 63 | { 64 | $keyArray = $this->cborDecode(hex2bin($this->credential)); 65 | $keyObject = null; 66 | switch ($this->algo) { 67 | case WebAuthnRegistrationEvent::PK_ALGORITHM_ECDSA: 68 | $keyObject = new Ec2Key($keyArray); 69 | break; 70 | case WebAuthnRegistrationEvent::PK_ALGORITHM_RSA: 71 | $keyObject = new RsaKey($keyArray); 72 | break; 73 | default: 74 | $this->fail("Incoming public key algorithm unknown and not supported!"); 75 | } 76 | $keyResource = openssl_pkey_get_public($keyObject->asPEM()); 77 | if ($keyResource === false) { 78 | $this->fail("Unable to construct public key resource from PEM (was algo type " . $this->algo . ")."); 79 | } 80 | /** 81 | * §7.2 STEP 17: validate signature 82 | */ 83 | $sigcheck = openssl_verify($sigData, $signature, $keyResource, OPENSSL_ALGO_SHA256); 84 | switch ($sigcheck) { 85 | case 1: 86 | $this->pass("Signature validation succeeded!"); 87 | break; 88 | case 0: 89 | $this->fail("Signature validation failed (sigdata = $sigData) (signature = $signature) !"); 90 | break; 91 | default: 92 | $this->fail("There was an error executing the signature check."); 93 | break; 94 | } 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /templates/authentication.twig: -------------------------------------------------------------------------------- 1 | {% set pagetitle = '{webauthn:webauthn:page_title}'|trans %} 2 | {% extends "base.twig" %} 3 | 4 | {% block preload %} 5 | 6 | 7 | {% endblock %} 8 | 9 | {% block content %} 10 |

{{ '{webauthn:webauthn:heading1}'|trans }}

11 | {% if authURL is defined and authURL|length > 0 %} 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | {% else %} 25 |

Please first register your token on the token management page before continuing. 26 | {% endif %} 27 | 28 | 29 | {% endblock %} 30 | -------------------------------------------------------------------------------- /templates/supercharged.twig: -------------------------------------------------------------------------------- 1 | {% set pagetitle = 'Passwordless future or username and password?'|trans %} 2 | 3 | {% extends "@core/base.twig" %} 4 | 5 | {% block preload %} 6 | 7 | 8 | {% endblock %} 9 | 10 | {% block postload %} 11 | 12 | 13 | {% if hasPreviouslyDonePasswordless == "YES" %}{% endif %} 14 | {% endblock %} 15 | 16 | {% block content %} 17 | {%- if not isProduction %} 18 | 19 |

20 | {% trans %}You are now accessing a pre-production system. This authentication setup is for testing and pre-production verification only. If someone sent you a link that pointed you here, and you are not a tester you probably got the wrong link, and should not be here.{% endtrans %} 21 |
22 | {% endif -%} 23 |
24 |
25 |

{{ '{webauthn.webauthn:passwordlessCaption}'|trans }}

26 |
27 |
28 |

{{ '{webauthn.webauthn:passwordlessProse}'|trans }}

29 |
30 |
31 | fingerprintface recognition 32 | {% if authURL is defined and authURL|length > 0 %} 33 |
34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 |
45 | {%- endif %} 46 |
47 |
48 | {{ '{webauthn.webauthn:dedicatedManagementPageHeading}'|trans }} 49 |

{{ '{webauthn.webauthn:dedicatedManagementPageHint}'|trans }} {{ '{webauthn.webauthn:dedicatedManagementPageText}'|trans }}

50 |
51 |
52 | {{ '{webauthn.webauthn:superchargeChoice}'|trans }} 53 |
54 |
55 |

{{ 'Enter your username and password'|trans }}

56 |
57 |
58 |

{{ 'A service has requested you to authenticate yourself. Please enter your username and password in the form below.'|trans }}

59 |
60 |
61 |
62 | 73 | 80 |
81 |
82 |
83 | {% if loginpage_links is defined -%} 84 | 89 | {%- endif %} 90 | 91 |

92 |
93 | {{ 'Help! I don\'t remember my password.'|trans }} 94 |

{{ 'Without your username and password you cannot authenticate yourself for access to the service. There may be someone that can help you. Consult the help desk at your organization!'|trans }}

95 |
96 |
97 |
98 | 99 | {% endblock %} 100 | -------------------------------------------------------------------------------- /templates/webauthn.twig: -------------------------------------------------------------------------------- 1 | {% set pagetitle = '{webauthn:webauthn:page_title}'|trans %} 2 | {% extends "base.twig" %} 3 | 4 | {% block preload %} 5 | 6 | 7 | {% endblock %} 8 | 9 | {% block content %} 10 |

{{ '{webauthn:webauthn:heading1}'|trans }}

11 |

{{ '{webauthn:webauthn:accountEnabled}'|trans }}

12 | {% if FIDO2Tokens|length > 0 %} 13 |
14 | {{ '{webauthn:webauthn:tokenList}'|trans }} 15 |
    16 | {% for token in FIDO2Tokens %} 17 | {% if FIDO2AuthSuccessful == false or FIDO2AuthSuccessful != token.0 %} 18 |
  • {% if token.5 == 4 and token.6 == true %}{% else %}{% endif %}{{ token.3|e }}  19 | {% if FIDO2AuthSuccessful == true %} 20 |
    21 | 22 | 25 |
    26 | {% endif %} 27 |
  • 28 | {% else %} 29 |
  • {{ token.3|e }}{% if token.5 == 4 and token.6 == true %} PasswordlessCapable {% endif %} {{ '{webauthn:webauthn:currentToken}'|trans }}
  • 30 | {% endif %} 31 | {% endfor %} 32 |
33 |
34 | {% endif %} 35 | {% if regURL is defined and regURL|length > 0 %} 36 |
37 | {{ '{webauthn:webauthn:tokenRegisterBox}'|trans }} 38 |
39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 |
48 | 49 | 50 | 52 | 53 |
54 |
55 |
56 | {% if FIDO2Tokens|length > 0 %} 57 | {% if showExitButton %} 58 |
59 |
60 | 63 |
64 | {% endif %} 65 | {% endif %} 66 | {% endif %} 67 | {% if authURL is defined and authURL|length > 0 %} 68 |
69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 |
86 | 87 |
88 | {% endif %} 89 | 90 | {% endblock %} 91 | --------------------------------------------------------------------------------