From f237d9fd15d8c5c421f735831820e6a7857abcdd Mon Sep 17 00:00:00 2001 From: Yuxiang Cao Date: Mon, 4 Sep 2023 17:28:31 -0700 Subject: [PATCH 01/12] chore: add java example --- LICENSE | 201 ------------- LICENSE-APACHE | 201 +++++++++++++ LICENSE-GPL | 278 ++++++++++++++++++ key-attestation/java-example/.editorconfig | 17 ++ key-attestation/java-example/.gitignore | 19 ++ key-attestation/java-example/LICENSE-APACHE | 1 + key-attestation/java-example/LICENSE-GPL | 1 + key-attestation/java-example/README.md | 25 ++ key-attestation/java-example/pom.xml | 95 ++++++ .../Common.java | 233 +++++++++++++++ ...eyAttestationStatementVerifyException.java | 7 + .../Verify.java | 225 ++++++++++++++ .../certchecker/CertChecker.java | 196 ++++++++++++ ...DsmKeyAttestationAuthorityCertChecker.java | 137 +++++++++ .../certchecker/FortanixRootCertChecker.java | 78 +++++ .../KeyAttestationCaCertChecker.java | 101 +++++++ .../KeyAttestationStatementCertChecker.java | 95 ++++++ .../types/ClusterNodeEnrollmentPolicy.java | 104 +++++++ .../types/KeyUsage.java | 68 +++++ .../types/NodeEnrollmentPolicyItem.java | 85 ++++++ .../VerifyTest.java | 72 +++++ .../resources/key-attestation-statement.pem | 129 ++++++++ 22 files changed, 2167 insertions(+), 201 deletions(-) delete mode 100644 LICENSE create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-GPL create mode 100644 key-attestation/java-example/.editorconfig create mode 100644 key-attestation/java-example/.gitignore create mode 120000 key-attestation/java-example/LICENSE-APACHE create mode 120000 key-attestation/java-example/LICENSE-GPL create mode 100644 key-attestation/java-example/README.md create mode 100644 key-attestation/java-example/pom.xml create mode 100644 key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Common.java create mode 100644 key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/KeyAttestationStatementVerifyException.java create mode 100644 key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Verify.java create mode 100644 key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/CertChecker.java create mode 100644 key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/DsmKeyAttestationAuthorityCertChecker.java create mode 100644 key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/FortanixRootCertChecker.java create mode 100644 key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationCaCertChecker.java create mode 100644 key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationStatementCertChecker.java create mode 100644 key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/ClusterNodeEnrollmentPolicy.java create mode 100644 key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/KeyUsage.java create mode 100644 key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/NodeEnrollmentPolicyItem.java create mode 100644 key-attestation/java-example/src/test/java/com/fortanix/key_attestation_statement_verification/VerifyTest.java create mode 100644 key-attestation/java-example/src/test/resources/key-attestation-statement.pem diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 261eeb9..0000000 --- a/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..11069ed --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/LICENSE-GPL b/LICENSE-GPL new file mode 100644 index 0000000..7ac7fbf --- /dev/null +++ b/LICENSE-GPL @@ -0,0 +1,278 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., [http://fsf.org/] + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. diff --git a/key-attestation/java-example/.editorconfig b/key-attestation/java-example/.editorconfig new file mode 100644 index 0000000..1f494b0 --- /dev/null +++ b/key-attestation/java-example/.editorconfig @@ -0,0 +1,17 @@ +# Editor configuration, see http://editorconfig.org +root = true + +[*] +charset = utf-8 +indent_style = space +indent_size = 2 +insert_final_newline = true +trim_trailing_whitespace = true +max_line_length = 80 + +[*.sh] +end_of_line = lf + +[*.java] +indent_size = 4 +max_line_length = 120 diff --git a/key-attestation/java-example/.gitignore b/key-attestation/java-example/.gitignore new file mode 100644 index 0000000..e94ed57 --- /dev/null +++ b/key-attestation/java-example/.gitignore @@ -0,0 +1,19 @@ +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +# https://github.com/takari/maven-wrapper#usage-without-binary-jar +.mvn/wrapper/maven-wrapper.jar + +# Eclipse m2e generated files +# Eclipse Core +.project +# JDT-specific (Eclipse Java Development Tools) +.classpath + +/.vscode \ No newline at end of file diff --git a/key-attestation/java-example/LICENSE-APACHE b/key-attestation/java-example/LICENSE-APACHE new file mode 120000 index 0000000..1cd601d --- /dev/null +++ b/key-attestation/java-example/LICENSE-APACHE @@ -0,0 +1 @@ +../../LICENSE-APACHE \ No newline at end of file diff --git a/key-attestation/java-example/LICENSE-GPL b/key-attestation/java-example/LICENSE-GPL new file mode 120000 index 0000000..89e542f --- /dev/null +++ b/key-attestation/java-example/LICENSE-GPL @@ -0,0 +1 @@ +../../LICENSE-GPL \ No newline at end of file diff --git a/key-attestation/java-example/README.md b/key-attestation/java-example/README.md new file mode 100644 index 0000000..66a41e3 --- /dev/null +++ b/key-attestation/java-example/README.md @@ -0,0 +1,25 @@ +# Java example code for how to verify Fortanix DSM Key Attestation Statement + +This is a example java of how to verify **Fortanix DSM Key Attestation Statement** properly. + +## Building + +`mvn compile` + +## Testing + +`mvn test` + +## Explanation + +The test code under [VerifyTest.java](src/test/java/com/fortanix/key_attestation_statement_verification/VerifyTest.java) +shows how to properly verify the **Fortanix DSM Key Attestation Statement** certificate: +- `verifyStatementWithoutCrlCheck` for offline verification +- `verifyStatementFullCheck` for online verification + +# License + +This project is primarily distributed under the terms of the Apache License +version 2.0 and the GNU General Public License version 2, see +[LICENSE-APACHE](./LICENSE-APACHE) and [LICENSE-GPL](./LICENSE-GPL) for +details. \ No newline at end of file diff --git a/key-attestation/java-example/pom.xml b/key-attestation/java-example/pom.xml new file mode 100644 index 0000000..6bb3f18 --- /dev/null +++ b/key-attestation/java-example/pom.xml @@ -0,0 +1,95 @@ + + 4.0.0 + com.fortanix.key_attestation_statement_verification + key-attestation-statement-verification + 0.0.1 + + 1.8 + 1.8 + UTF-8 + 4.13.2 + 3.0.0-M3 + 8.45.1 + 3.0.0-M5 + 3.0.0 + + + + org.eclipse + yasson + 2.0.4 + + + jakarta.json.bind + jakarta.json.bind-api + 2.0.0 + + + org.glassfish + jakarta.json + 2.0.1 + + + jakarta.json + jakarta.json-api + 2.1.2 + + + org.bouncycastle + bcpkix-jdk18on + 1.76 + + + junit + junit + ${junit.version} + test + + + + + + src/test/resources + true + + + + + org.apache.maven.plugins + maven-enforcer-plugin + ${maven-enforcer-plugin.version} + + + + enforce + + + + + 3.6.3 + + + true + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${maven-surefire-plugin.version} + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + ${maven-javadoc-plugin.version} + + + + \ No newline at end of file diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Common.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Common.java new file mode 100644 index 0000000..070216d --- /dev/null +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Common.java @@ -0,0 +1,233 @@ +package com.fortanix.key_attestation_statement_verification; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.StringReader; +import java.net.URL; +import java.net.URLConnection; +import java.nio.charset.StandardCharsets; +import java.security.cert.X509Certificate; +import java.util.List; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.x500.RDN; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x500.X500NameBuilder; +import org.bouncycastle.asn1.x500.style.BCStyle; + +public class Common { + public static final String FORTANIX_PKI_DOMAIN = "pki.fortanix.com"; + public static final String FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CERT_URL = String + .format("https://%s/Fortanix_Attestation_and_Provisioning_Root_CA.crt", FORTANIX_PKI_DOMAIN); + public static final String FORTANIX_KEY_ATTESTATION_CA_CRL_URL = String + .format("https://%s/Fortanix_Key_Attestation_CA.crl", FORTANIX_PKI_DOMAIN); + public static final String FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CRL_URL = String + .format("https://%s/Fortanix_Attestation_and_Provisioning_Root_CA.crl", FORTANIX_PKI_DOMAIN); + + public static final String ID_KP_FORTANIX_KEY_ATTESTATION = "1.3.6.1.4.1.49690.8.1"; + public static final String CLUSTER_NODE_ENROLLMENT_POLICY_OID = "1.3.6.1.4.1.49690.2.5"; + /** + * Node enrollment policy item: Minimum protection profile + */ + public static final String NODE_ENROLLMENT_POLICY_ITEM_MINIMUM_PROTECTION_PROFILE_OID = "1.3.6.1.4.1.49690.2.5.1"; + /** + * One of qualifiers of 'Node enrollment policy item: Minimum protection + * profile': Well-known protection profile: Fortanix FX2200 + */ + public static final String NODE_ENROLLMENT_POLICY_ITEM_WELL_KNOWN_PROTECTION_PROFILE_FORTANIX_FX2200_OID = "1.3.6.1.4.1.49690.2.5.1.1"; + /** + * Node enrollment policy item: Site operator approval required + */ + public static final String NODE_ENROLLMENT_POLICY_ITEM_SITE_OPERATOR_APPROVAL_REQUIRED_OID = "1.3.6.1.4.1.49690.2.5.2"; + public static final String FORTANIX_KEY_ATTESTATION_CERTIFICATE_POLICY_OID = "1.3.6.1.4.1.49690.6.1.2"; + + public static final int VALID_AUTHORITY_CERT_CHAIN_NUM = 3; + public static final String FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CN = "Fortanix Attestation and Provisioning Root CA"; + public static final String FORTANIX_KEY_ATTESTATION_CA_CN = "Fortanix Key Attestation CA"; + public static final String DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN = "Fortanix DSM SaaS Key Attestation Authority"; + public static final String KEY_ATTESTATION_STATEMENT_CN = "Fortanix DSM Key Attestation"; + public static final String FORTANIX_SUBJECT_C = "US"; + public static final String FORTANIX_SUBJECT_ST = "California"; + public static final String FORTANIX_SUBJECT_L = "Santa Clara"; + public static final String FORTANIX_SUBJECT_O = "Fortanix, Inc."; + public static X500Name FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_NAME; + public static X500Name FORTANIX_KEY_ATTESTATION_CA_NAME; + public static X500Name DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_NAME; + public static X500Name KEY_ATTESTATION_STATEMENT_NAME; + + static { + Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_NAME = buildX500Name( + Common.FORTANIX_SUBJECT_C, + Common.FORTANIX_SUBJECT_ST, + Common.FORTANIX_SUBJECT_L, + Common.FORTANIX_SUBJECT_O, + Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CN); + Common.FORTANIX_KEY_ATTESTATION_CA_NAME = buildX500Name( + Common.FORTANIX_SUBJECT_C, + Common.FORTANIX_SUBJECT_ST, + Common.FORTANIX_SUBJECT_L, + Common.FORTANIX_SUBJECT_O, + Common.FORTANIX_KEY_ATTESTATION_CA_CN); + Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_NAME = buildX500Name( + "", "", "", "", + Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN); + Common.KEY_ATTESTATION_STATEMENT_NAME = buildX500Name( + "", "", "", "", + Common.KEY_ATTESTATION_STATEMENT_CN); + + } + + /** + * Helper function to build expected Name + * + * @param c Country + * @param st State or province + * @param l Locality + * @param o Organization name + * @param cn Common name + * @return + */ + private static X500Name buildX500Name(String c, String st, String l, String o, String cn) { + X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE); + // Set the values for county, stateOrProvince, locality, organization and + // commonName + if (!c.isEmpty()) { + builder.addRDN(BCStyle.C, c); + } + ; + if (!st.isEmpty()) { + builder.addRDN(BCStyle.ST, st); + } + ; + if (!l.isEmpty()) { + builder.addRDN(BCStyle.L, l); + } + ; + if (!o.isEmpty()) { + builder.addRDN(BCStyle.O, o); + } + ; + builder.addRDN(BCStyle.CN, cn); + + return builder.build(); + } + + /** + * Check if given Name contains all expected Name + * + * @param actual Actual Name + * @param expected Expected Name + * @return + * @throws Exception + */ + public static boolean checkNameMatch(X500Name actual, X500Name expected) throws Exception { + ASN1ObjectIdentifier[] styles = { BCStyle.C, BCStyle.ST, BCStyle.L, BCStyle.O, BCStyle.CN }; + + for (ASN1ObjectIdentifier style : styles) { + if (!checkRDNsMatch(actual, expected, style)) { + return false; + } + } + + return true; + } + + /** + * Helper function to check if specific Subject Name is matched. This is needed + * for get rid of difference between UTF8String and PrintableString + * + * @param actual Actual Name + * @param expected Expected Name + * @param style Specific RDN type + * @return + * @throws Exception + */ + private static boolean checkRDNsMatch(X500Name actual, X500Name expected, ASN1ObjectIdentifier style) + throws Exception { + RDN[] actualRDNs = actual.getRDNs(style); + RDN[] expectedRDNs = expected.getRDNs(style); + + if (expectedRDNs.length != 0) { + if (actualRDNs.length != 0) { + String actualValue = actualRDNs[0].getFirst().getValue().toString(); + String expectedValue = expectedRDNs[0].getFirst().getValue().toString(); + + if (!actualValue.equals(expectedValue)) { + return false; + } + } else { + return false; + } + } + + return true; + } + + /** + * Helper function to check if given URL is a valid URL to Fortanix PKI + * + * @param urlString URL to be checked + * @throws Exception Will throw KeyAttestationStatementVerifyException if URL is + * invalid + */ + public static void isValidCrlUrl(String urlString) throws Exception { + URL url = new URL(urlString); + if (!url.getProtocol().equals("https")) { + throw new KeyAttestationStatementVerifyException("invalid CRL URL: invalid domain"); + } + if (!url.getHost().equalsIgnoreCase(FORTANIX_PKI_DOMAIN)) { + throw new KeyAttestationStatementVerifyException("invalid CRL URL: should be https"); + } + if (!url.getPath().endsWith(".crl")) { + throw new KeyAttestationStatementVerifyException("invalid CRL URL: should be end with '.crl'"); + } + } + + /** + * Helper function to retrieve remote content from URL into a String + * + * @param url URL to get content from + * @return Data in type of sting + * @throws Exception + */ + public static String getUrlContentsInString(URL url) throws Exception { + // create a URLConnection object + URLConnection urlConnection = url.openConnection(); + + // wrap the URLConnection in a BufferedReader + BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader(urlConnection.getInputStream(), StandardCharsets.UTF_8)); + + StringBuilder content = new StringBuilder(); + String line; + // read from the URLConnection via the BufferedReader + while ((line = bufferedReader.readLine()) != null) { + content.append(line + "\n"); + } + bufferedReader.close(); + + return content.toString(); + } + + /** + * Get FortanixRootCaCert from given remote URL + * + * @param rootCertUrlStr Given remote URL to FortanixRootCaCert + * @return Decoded Certificate from remote + * @throws Exception + */ + public static X509Certificate getFortanixRootCaCertRemote(String rootCertUrlStr) throws Exception { + URL url = new URL(rootCertUrlStr); + if (!url.getProtocol().equals("https")) { + throw new KeyAttestationStatementVerifyException("Fortanix Root CA certificate URL must use HTTPS"); + } + String pem = getUrlContentsInString(url); + List certs = Verify.readPemCertsFromReader(new StringReader(pem)); + if (certs.size() != 1) { + throw new KeyAttestationStatementVerifyException( + "Fortanix Root CA certificate pem data should only contains one certificate"); + } + return certs.get(0); + } + +} diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/KeyAttestationStatementVerifyException.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/KeyAttestationStatementVerifyException.java new file mode 100644 index 0000000..e583c3c --- /dev/null +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/KeyAttestationStatementVerifyException.java @@ -0,0 +1,7 @@ +package com.fortanix.key_attestation_statement_verification; + +public class KeyAttestationStatementVerifyException extends Exception { + public KeyAttestationStatementVerifyException(String msg) { + super(msg); + } +} diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Verify.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Verify.java new file mode 100644 index 0000000..7036b44 --- /dev/null +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Verify.java @@ -0,0 +1,225 @@ +package com.fortanix.key_attestation_statement_verification; + +import java.io.FileReader; +import java.io.Reader; +import java.security.PublicKey; +import java.security.Security; +import java.security.cert.CertPath; +import java.security.cert.CertPathValidator; +import java.security.cert.CertPathValidatorException; +import java.security.cert.CertificateFactory; +import java.security.cert.PKIXParameters; +import java.security.cert.TrustAnchor; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; +import org.bouncycastle.jce.provider.BouncyCastleProvider; +import org.bouncycastle.openssl.PEMParser; + +import com.fortanix.key_attestation_statement_verification.certchecker.CertChecker; +import com.fortanix.key_attestation_statement_verification.certchecker.DsmKeyAttestationAuthorityCertChecker; +import com.fortanix.key_attestation_statement_verification.certchecker.FortanixRootCertChecker; +import com.fortanix.key_attestation_statement_verification.certchecker.KeyAttestationCaCertChecker; +import com.fortanix.key_attestation_statement_verification.certchecker.KeyAttestationStatementCertChecker; + +public final class Verify { + + static { + Security.addProvider(new BouncyCastleProvider()); + } + + /** + * Verify given `attestationStatement`, `authorityChain` by using `trustRootCa` + * + * @param authorityChain Certificate chain of all certificates expect + * `Fortanix Key Attestation Statement` certificate + * @param attestationStatement `Fortanix Key Attestation Statement` certificate + * @param trustRootCa Trusted root CA, you need to get the certificate + * from Fortanix PKI website + * @param verifyCrl If check the CRL, need network access + * @throws Exception + */ + public static void verify(List authorityChain, X509Certificate attestationStatement, + X509Certificate trustRootCa, boolean verifyCrl) throws Exception { + checkAuthorityChainLength(authorityChain); + + check_root_cert_match(authorityChain.get(authorityChain.size() - 1), trustRootCa); + // verify each signature on authority certificate chain is correctly signed by + // it's parent + try { + verify_cert_chain_signature(authorityChain, trustRootCa, verifyCrl); + System.out.println("The signature in 'Fortanix DSM Key Attestation' certificate is valid."); + } catch (Exception e) { + throw new KeyAttestationStatementVerifyException( + "The signature in 'Fortanix DSM Key Attestation' certificate is valid, " + e.toString()); + } + // because 'Fortanix DSM SaaS Key Attestation Authority' is not a CA + // certificate, so we need to manually check 'Fortanix DSM Key Attestation' is + // correctly singed by 'Fortanix DSM SaaS Key Attestation Authority' certificate + CertChecker statementChecker = new KeyAttestationStatementCertChecker(); + CertChecker authorityChecker = new DsmKeyAttestationAuthorityCertChecker(); + CertChecker caChecker = new KeyAttestationCaCertChecker(); + CertChecker rooCertChecker = new FortanixRootCertChecker(); + statementChecker.check(attestationStatement, authorityChain.get(0)); + // 1st certificate in the chain should be 'Fortanix DSM SaaS Key Attestation + // Authority' certificate + authorityChecker.check(authorityChain.get(0), authorityChain.get(1)); + // 2nd certificate in the chain should be 'Fortanix Key Attestation CA' + // certificate + caChecker.check(authorityChain.get(1), authorityChain.get(2)); + // 3rd certificate in the chain should be 'Fortanix Attestation and Provisioning + // Root CA' certificate + rooCertChecker.check(authorityChain.get(2), authorityChain.get(2)); + } + + /** + * Verify the signature in given certificate chain from leaf node to trusted CA + * certificate + * + * @param chain Certificate chain to verify + * @param trust_ca The trusted CA certificate + * @throws Exception + */ + public static void verify_cert_chain_signature(List chain, X509Certificate trust_ca, + boolean verifyCrl) + throws Exception { + if (chain.isEmpty()) { + throw new KeyAttestationStatementVerifyException("Empty certificate chain"); + } + // Create CertPath + CertificateFactory factory = CertificateFactory.getInstance("X.509", "BC"); + CertPath certPath = factory.generateCertPath(chain); + + // Set up TrustAnchor using the last certificate as the root certificate + TrustAnchor trustAnchor = new TrustAnchor(trust_ca, null); + Set trustAnchors = Collections.singleton(trustAnchor); + + // Set up PKIXParameters + PKIXParameters params = new PKIXParameters(trustAnchors); + params.setRevocationEnabled(verifyCrl); + + // Validate CertPath + CertPathValidator validator = CertPathValidator.getInstance("PKIX", "BC"); + try { + validator.validate(certPath, params); + } catch (CertPathValidatorException e) { + // Handle validation exception + throw new KeyAttestationStatementVerifyException("Certificate chain validation failed" + e.toString()); + } + } + + /** + * Helper function to check if given trusted Root CA certificate matches the + * final parent CA certificate in the `authorityChain` + * + * @param root_cert The final parent CA certificate in the `authorityChain` + * @param trust_ca Trusted Root CA certificate + * @throws Exception + */ + public static void check_root_cert_match(X509Certificate root_cert, X509Certificate trust_ca) throws Exception { + if (!root_cert.equals(trust_ca)) { + throw new KeyAttestationStatementVerifyException( + "Root CA certificate in chain does not match trust ca certificate"); + } + } + + /** + * Helper function to read a certificate chain from the path to a PEM formatted + * file + * + * @param pemFilePath The path to a PEM formatted file + * @return A list of X509Certificate + * @throws Exception + */ + public static List readPemCertsFromPath(String pemFilePath) throws Exception { + Reader reader = new FileReader(pemFilePath); + return readPemCertsFromReader(reader); + } + + /** + * Helper function to read a certificate chain from a Reader + * + * @param reader java Reader of the data of certificate chain + * @return A list of X509Certificate + * @throws Exception + */ + public static List readPemCertsFromReader(Reader reader) throws Exception { + List certChain = new ArrayList<>(); + try (PEMParser pemParser = new PEMParser(reader)) { + Object object = pemParser.readObject(); + while (object != null) { + if (object instanceof X509CertificateHolder) { + X509CertificateHolder cert = (X509CertificateHolder) object; + if (!certChain.add(cert)) { + throw new KeyAttestationStatementVerifyException("Failed to add new Certificate"); + } + } else { + throw new KeyAttestationStatementVerifyException( + "Found a non Certificate PEM object: " + object.toString()); + } + object = pemParser.readObject(); + } + pemParser.close(); + } + if (certChain.isEmpty()) { + throw new KeyAttestationStatementVerifyException("No valid Certificate in given file"); + } + return convertX509CertificateHolders(certChain); + } + + /** + * Helper function to convert a List of + * org.bouncycastle.cert.X509CertificateHolder to a List of + * java.security.cert.X509Certificate + * + * @param cert_chain List of certificate to be converted + * @return A List of java.security.cert.X509Certificate + * @throws Exception + */ + public static List convertX509CertificateHolders(List cert_chain) + throws Exception { + // Convert X509CertificateHolder to Certificate for CertPath + JcaX509CertificateConverter converter = new JcaX509CertificateConverter() + .setProvider(BouncyCastleProvider.PROVIDER_NAME); + List chain = new ArrayList<>(); + for (X509CertificateHolder holder : cert_chain) { + chain.add(converter.getCertificate(holder)); + } + return chain; + } + + /** + * Helper function to check the length of authority certificate chain. + * + * @param authorityCertChain Certificate chain to be checked + * @throws KeyAttestationStatementVerifyException + */ + private static void checkAuthorityChainLength(List authorityCertChain) + throws KeyAttestationStatementVerifyException { + if (authorityCertChain.size() != Common.VALID_AUTHORITY_CERT_CHAIN_NUM) { + throw new KeyAttestationStatementVerifyException( + String.format( + "A valid authority certificates chain should contain %d certificate", + Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN)); + } + } + + /** + * Helper function to check if given child certificate is correctly signed by + * it's issuer + * + * @param child Certificate to be validated + * @param parent The certificate of issuer + * @throws Exception + */ + public static void verify_cert_chain_signature(X509Certificate child, X509Certificate parent) + throws Exception { + PublicKey parentPublicKey = parent.getPublicKey(); + child.verify(parentPublicKey); + } +} diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/CertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/CertChecker.java new file mode 100644 index 0000000..3320887 --- /dev/null +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/CertChecker.java @@ -0,0 +1,196 @@ +package com.fortanix.key_attestation_statement_verification.certchecker; + +import java.security.MessageDigest; +import java.security.cert.X509Certificate; + +import org.bouncycastle.asn1.ASN1InputStream; +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.ASN1OctetString; +import org.bouncycastle.asn1.x509.CRLDistPoint; +import org.bouncycastle.asn1.x509.DistributionPoint; +import org.bouncycastle.asn1.x509.DistributionPointName; +import org.bouncycastle.asn1.x509.GeneralName; +import org.bouncycastle.asn1.x509.GeneralNames; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.asn1.x509.PolicyInformation; +import org.bouncycastle.asn1.x509.SubjectKeyIdentifier; +import org.bouncycastle.asn1.x509.AuthorityKeyIdentifier; +import org.bouncycastle.asn1.x509.CertificatePolicies; +import org.bouncycastle.asn1.x509.ExtendedKeyUsage; +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; + +import com.fortanix.key_attestation_statement_verification.KeyAttestationStatementVerifyException; +import com.fortanix.key_attestation_statement_verification.types.ClusterNodeEnrollmentPolicy; + +/** + * This abstract class represents custom certificate checker + */ +public abstract class CertChecker { + /** + * This function should check all details in given certificate `cert` + * + * @param cert Certificate to be checked + * @param issuerCert Issuer's certificate + * @throws Exception + */ + abstract public void check(X509Certificate cert, X509Certificate issuerCert) throws Exception; + + protected void verifyDistPoint(String errStrPrefix, X509Certificate cert, String expectedCrl) throws Exception { + byte[] crlDistPointExtOctetBytes = cert.getExtensionValue("2.5.29.31"); + if (crlDistPointExtOctetBytes == null) { + throw new KeyAttestationStatementVerifyException( + errStrPrefix + + " certificate should contains cRLDistributionPoints extension"); + } + ASN1OctetString crlDistPointExtOctet = ASN1OctetString.getInstance(crlDistPointExtOctetBytes); + ASN1InputStream asnInStream = new ASN1InputStream(crlDistPointExtOctet.getOctets()); + CRLDistPoint crlDistPoint = CRLDistPoint.getInstance(asnInStream.readObject()); + + DistributionPoint[] distPoints = crlDistPoint.getDistributionPoints(); + if (distPoints.length != 1) { + throw new KeyAttestationStatementVerifyException( + errStrPrefix + + " certificate cRLDistributionPoints extension should contains 1 point"); + } + DistributionPointName actualName = distPoints[0].getDistributionPoint(); + if (actualName.getType() != DistributionPointName.FULL_NAME) { + throw new KeyAttestationStatementVerifyException( + errStrPrefix + + " certificate cRLDistributionPoints extension's DistributionPointName should be type of FULL_NAME"); + } + DistributionPointName expectedName = new DistributionPointName(new GeneralNames( + new GeneralName(GeneralName.uniformResourceIdentifier, expectedCrl))); + if (!actualName.equals(expectedName)) { + throw new KeyAttestationStatementVerifyException( + errStrPrefix + + " certificate cRLDistributionPoints extension wrong Name"); + } + } + + /** + * Check given certificate's SubjectKeyIdentifier extension matches its Public + * Subject Key info + * + * @param errStrPrefix + * @param cert Certificate to be checked + * @param digestAlgo Hash algorithm name used for creating + * SubjectKeyIdentifier + * @throws Exception + */ + protected void checkSubjectKeyIdentifier(String errStrPrefix, X509Certificate cert, String digestAlgo) + throws Exception { + byte[] computedSkiVal = getComputedSkiVal(cert, digestAlgo); + byte[] skiVal = getExtSkiVal(cert); + // Compare both SKIs + if (!java.util.Arrays.equals(skiVal, computedSkiVal)) { + throw new KeyAttestationStatementVerifyException( + errStrPrefix + + " certificate Subject Key Identifier content not match with Subject Public Key"); + } + } + + /** + * Get Subject Key Identifier value from certificate extension + * + * @param certHolder Source certificate + * @return Byte array format of Subject Key Identifier value + * @throws Exception + */ + protected byte[] getExtSkiVal(X509Certificate cert) throws Exception { + X509CertificateHolder certHolder = new JcaX509CertificateHolder(cert); + SubjectKeyIdentifier ski = SubjectKeyIdentifier.fromExtensions(certHolder.getExtensions()); + if (ski == null) { + throw new KeyAttestationStatementVerifyException("SubjectKeyIdentifier extension not found"); + } + return ski.getKeyIdentifier(); + } + + /** + * Get Authority Key Identifier value from certificate extension + * + * @param certHolder Source certificate + * @return Byte array format of Authority Key Identifier value value + * @throws Exception Will throw `KeyAttestationStatementVerifyException` if no + * Authority Key Identifier extension found + */ + protected byte[] getExtAkiVal(X509Certificate cert) throws Exception { + X509CertificateHolder certHolder = new JcaX509CertificateHolder(cert); + AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.fromExtensions(certHolder.getExtensions()); + if (aki == null) { + throw new KeyAttestationStatementVerifyException("AuthorityKeyIdentifier extension not found"); + } + return aki.getKeyIdentifier(); + } + + /** + * Compute Subject Key Identifier value from certificate's Public Subject Key + * Info + * + * @param cert Source certificate + * @param digestAlgo Hash algorithm name used for creating SubjectKeyIdentifier + * @return + * @throws Exception + */ + protected byte[] getComputedSkiVal(X509Certificate cert, String digestAlgo) throws Exception { + byte[] certPkVal = cert.getPublicKey().getEncoded(); + MessageDigest md = MessageDigest.getInstance(digestAlgo); + byte[] computedSkiVal = md.digest(certPkVal); + return computedSkiVal; + } + + /** + * Get specific CertificatePolicyInfo from CertificatePolicies extension + * + * @param cert Source certificate + * @param policyIdentifier Specific OID of CertificatePolicyInfo + * @return PolicyInformation that matches given OID + * @throws Exception Will throw `KeyAttestationStatementVerifyException` if no + * specific PolicyInformation found + */ + protected PolicyInformation getCertificatePolicyInfoByOID(X509Certificate cert, + ASN1ObjectIdentifier policyIdentifier) throws Exception { + X509CertificateHolder certHolder = new JcaX509CertificateHolder(cert); + CertificatePolicies certificatePolicies = CertificatePolicies.fromExtensions(certHolder.getExtensions()); + if (certificatePolicies == null) { + throw new KeyAttestationStatementVerifyException("CertificatePolicies extension not found"); + } + return certificatePolicies.getPolicyInformation(policyIdentifier); + } + + /** + * Check if ExtendedKeyUsage extension contains specific KeyPurposeId + * + * @param cert Source certificate + * @param keyPurposeId Specific KeyPurposeId, which is type of OID + * @return If ExtendedKeyUsage has specific KeyPurposeId + * @throws Exception Will throw `KeyAttestationStatementVerifyException` if no + * ExtendedKeyUsage extension found + */ + protected boolean checkExtendedKeyUsage(X509Certificate cert, KeyPurposeId keyPurposeId) throws Exception { + X509CertificateHolder certHolder = new JcaX509CertificateHolder(cert); + ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.fromExtensions(certHolder.getExtensions()); + if (extendedKeyUsage == null) { + throw new KeyAttestationStatementVerifyException("ExtendedKeyUsage extension not found"); + } + return extendedKeyUsage.hasKeyPurposeId(keyPurposeId); + } + + /** + * Get ClusterNodeEnrollmentPolicy extension + * + * @param cert Source certificate + * @return ClusterNodeEnrollmentPolicy + * @throws Exception Will throw `KeyAttestationStatementVerifyException` if no + * ClusterNodeEnrollmentPolicy extension found + */ + protected ClusterNodeEnrollmentPolicy getClusterNodeEnrollmentPolicy(X509Certificate cert) throws Exception { + X509CertificateHolder certHolder = new JcaX509CertificateHolder(cert); + ClusterNodeEnrollmentPolicy clusterNodeEnrollmentPolicy = ClusterNodeEnrollmentPolicy + .fromExtensions(certHolder.getExtensions()); + if (clusterNodeEnrollmentPolicy == null) { + throw new KeyAttestationStatementVerifyException("ClusterNodeEnrollmentPolicy extension not found"); + } + return clusterNodeEnrollmentPolicy; + } +} diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/DsmKeyAttestationAuthorityCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/DsmKeyAttestationAuthorityCertChecker.java new file mode 100644 index 0000000..4fd5486 --- /dev/null +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/DsmKeyAttestationAuthorityCertChecker.java @@ -0,0 +1,137 @@ +package com.fortanix.key_attestation_statement_verification.certchecker; + +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import java.security.interfaces.RSAPublicKey; +import java.util.Arrays; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.KeyPurposeId; +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; + +import com.fortanix.key_attestation_statement_verification.Common; +import com.fortanix.key_attestation_statement_verification.KeyAttestationStatementVerifyException; +import com.fortanix.key_attestation_statement_verification.types.ClusterNodeEnrollmentPolicy; +import com.fortanix.key_attestation_statement_verification.types.KeyUsage; +import com.fortanix.key_attestation_statement_verification.types.NodeEnrollmentPolicyItem; + +public class DsmKeyAttestationAuthorityCertChecker extends CertChecker { + @Override + public void check(X509Certificate cert, X509Certificate issuerCert) throws Exception { + cert.checkValidity(); + check_subject_and_issuer(cert); + check_public_key(cert); + check_extensions(cert, issuerCert); + } + + private void check_subject_and_issuer(X509Certificate cert) throws Exception { + X509CertificateHolder certHolder = new JcaX509CertificateHolder(cert); + // check subject + X500Name authorityCertSubject = certHolder.getSubject(); + if (!Common.checkNameMatch(authorityCertSubject, Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_NAME)) { + throw new KeyAttestationStatementVerifyException( + Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN + " certificate subject is invalid:\n" + + authorityCertSubject.toString()); + } + // check issuer + X500Name authorityCertIssuer = certHolder.getIssuer(); + if (!Common.checkNameMatch(authorityCertIssuer, Common.FORTANIX_KEY_ATTESTATION_CA_NAME)) { + throw new KeyAttestationStatementVerifyException( + Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN + " certificate issuer is invalid:\n" + + authorityCertIssuer.toString() + "\n!=\n" + + Common.FORTANIX_KEY_ATTESTATION_CA_NAME.toString()); + } + } + + private void check_public_key(X509Certificate cert) throws Exception { + PublicKey authorityPk = cert.getPublicKey(); + if (authorityPk instanceof RSAPublicKey) { + RSAPublicKey authorityRsaPk = (RSAPublicKey) authorityPk; + assert (authorityRsaPk.getModulus().bitLength() >= 3072); + } else { + throw new KeyAttestationStatementVerifyException( + Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN + " certificate invalid public key type"); + } + + } + + private void check_extensions(X509Certificate cert, X509Certificate issuerCert) throws Exception { + // check extension: Key Usage + KeyUsage[] authorityCertExpectedKeyUsage = { KeyUsage.DIGITAL_SIGNATURE }; + KeyUsage.checkKeyUsageHelper(Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, cert.getKeyUsage(), + authorityCertExpectedKeyUsage); + // check extension: Basic Constraints + int pathLenConstraint = cert.getBasicConstraints(); + if (pathLenConstraint != -1) { + throw new KeyAttestationStatementVerifyException( + Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN + + " certificate has invalid BasicConstraints extension, it should not be a CA"); + + } + // check extension: CRL Distribution Points + verifyDistPoint(Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, cert, + Common.FORTANIX_KEY_ATTESTATION_CA_CRL_URL); + // check extension: Subject Key Identifier + checkSubjectKeyIdentifier(Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, cert, "SHA-1"); + // check extension: Authority Key Identifier + if (!Arrays.equals(getExtAkiVal(cert), getExtSkiVal(issuerCert))) { + throw new KeyAttestationStatementVerifyException( + Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN + + " certificate Authority Key Identifier extension has wrong value"); + } + // check extension: Certificate Policies + if (getCertificatePolicyInfoByOID(cert, + new ASN1ObjectIdentifier(Common.FORTANIX_KEY_ATTESTATION_CERTIFICATE_POLICY_OID)) == null) { + throw new KeyAttestationStatementVerifyException(String.format( + "%s certificate Extended Key Usage extension should contain: Fortanix Key Attestation Certificate Policy (%s)", + Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, + Common.FORTANIX_KEY_ATTESTATION_CERTIFICATE_POLICY_OID)); + } + // check extension: Extended Key Usage + if (!checkExtendedKeyUsage(cert, + KeyPurposeId.getInstance(new ASN1ObjectIdentifier(Common.ID_KP_FORTANIX_KEY_ATTESTATION)))) { + throw new KeyAttestationStatementVerifyException(String.format( + "%s certificate Extended Key Usage extension should contain KeyPurposeId: id-kp-fortanix-key-attestation (%s)", + Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, Common.ID_KP_FORTANIX_KEY_ATTESTATION)); + } + // check extension: Cluster node enrollment policy + ClusterNodeEnrollmentPolicy clusterNodeEnrollmentPolicy = getClusterNodeEnrollmentPolicy(cert); + NodeEnrollmentPolicyItem[] nodeEnrollmentPolicyItem = clusterNodeEnrollmentPolicy + .getNodeEnrollmentPolicyItems(); + if (nodeEnrollmentPolicyItem.length < 2) { + throw new KeyAttestationStatementVerifyException(Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN + + " certificate 'Cluster node enrollment policy' extension should at least contain 2 policy items, but get: " + + nodeEnrollmentPolicyItem.length); + } + ASN1ObjectIdentifier policyItem1 = nodeEnrollmentPolicyItem[0].getPolicyItem(); + if (!policyItem1.getId().equals(Common.NODE_ENROLLMENT_POLICY_ITEM_MINIMUM_PROTECTION_PROFILE_OID)) { + throw new KeyAttestationStatementVerifyException(String.format( + "%s certificate 'Cluster node enrollment policy' extension should contain policy item 'Node enrollment policy item: Minimum protection profile' (%s), but get: %s", + Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, + Common.NODE_ENROLLMENT_POLICY_ITEM_MINIMUM_PROTECTION_PROFILE_OID, + policyItem1.getId())); + } + + ASN1ObjectIdentifier policyItem1Qualifier = ASN1ObjectIdentifier + .getInstance(nodeEnrollmentPolicyItem[0].getQualifiers()); + if (!policyItem1Qualifier.getId() + .equals(Common.NODE_ENROLLMENT_POLICY_ITEM_WELL_KNOWN_PROTECTION_PROFILE_FORTANIX_FX2200_OID)) { + throw new KeyAttestationStatementVerifyException(String.format( + "%s certificate 'Cluster node enrollment policy' extension policy item 'Node enrollment policy item: Minimum protection profile' should contain qualifier: 'Well-known protection profile: Fortanix FX2200' (%s), but get: %s", + Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, + Common.NODE_ENROLLMENT_POLICY_ITEM_WELL_KNOWN_PROTECTION_PROFILE_FORTANIX_FX2200_OID, + policyItem1.getId())); + } + ASN1ObjectIdentifier policyItem2 = nodeEnrollmentPolicyItem[1].getPolicyItem(); + if (!policyItem2.getId().equals(Common.NODE_ENROLLMENT_POLICY_ITEM_SITE_OPERATOR_APPROVAL_REQUIRED_OID)) { + throw new KeyAttestationStatementVerifyException(String.format( + "%s certificate 'Cluster node enrollment policy' extension should contain policy item 'Node enrollment policy item: Site operator approval required' (%s), but get: %s", + Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, + Common.NODE_ENROLLMENT_POLICY_ITEM_SITE_OPERATOR_APPROVAL_REQUIRED_OID, + policyItem1.getId())); + } + } + +} diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/FortanixRootCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/FortanixRootCertChecker.java new file mode 100644 index 0000000..51e6f87 --- /dev/null +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/FortanixRootCertChecker.java @@ -0,0 +1,78 @@ +package com.fortanix.key_attestation_statement_verification.certchecker; + +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import java.security.interfaces.RSAPublicKey; + +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; + +import com.fortanix.key_attestation_statement_verification.Common; +import com.fortanix.key_attestation_statement_verification.KeyAttestationStatementVerifyException; +import com.fortanix.key_attestation_statement_verification.types.KeyUsage; + +public class FortanixRootCertChecker extends CertChecker { + + @Override + public void check(X509Certificate cert, X509Certificate issuerCert) throws Exception { + cert.checkValidity(); + check_subject_and_issuer(cert); + check_public_key(cert); + check_extensions(cert); + } + + private void check_subject_and_issuer(X509Certificate cert) throws Exception { + X509CertificateHolder certHolder = new JcaX509CertificateHolder(cert); + + // check subject + X500Name rootCertSubject = certHolder.getSubject(); + if (!Common.checkNameMatch(rootCertSubject, Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_NAME)) { + throw new KeyAttestationStatementVerifyException( + Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CN + " certificate subject is invalid " + + rootCertSubject.toString()); + } + + // check issuer + X500Name rootCertIssuer = certHolder.getIssuer(); + if (!Common.checkNameMatch(rootCertIssuer, Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_NAME)) { + throw new KeyAttestationStatementVerifyException( + Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CN + " certificate issuer is invalid " + + rootCertIssuer.toString()); + } + } + + private void check_public_key(X509Certificate cert) throws Exception { + PublicKey rootPk = cert.getPublicKey(); + if (rootPk instanceof RSAPublicKey) { + RSAPublicKey rootRsaPk = (RSAPublicKey) rootPk; + assert (rootRsaPk.getModulus().bitLength() >= 3072); + } else { + throw new KeyAttestationStatementVerifyException( + Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CN + + " certificate invalid public key type"); + } + } + + private void check_extensions(X509Certificate cert) throws Exception { + // check extension: Key Usage + KeyUsage[] rootCertExpectedKeyUsage = { KeyUsage.DIGITAL_SIGNATURE, KeyUsage.KEY_CERT_SIGN, KeyUsage.CRL_SIGN }; + KeyUsage.checkKeyUsageHelper(Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CN, cert.getKeyUsage(), + rootCertExpectedKeyUsage); + int pathLenConstraint = cert.getBasicConstraints(); + // check extension: Basic Constraints + if (pathLenConstraint < 0) { + throw new KeyAttestationStatementVerifyException( + Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CN + + " certificate has invalid BasicConstraints extension, it should be a CA"); + + } + if (pathLenConstraint != Integer.MAX_VALUE) { + throw new KeyAttestationStatementVerifyException( + Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CN + + " certificate has invalid BasicConstraints extension, it'a CA but pathLenConstraint should be absent"); + } + checkSubjectKeyIdentifier(Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CN, cert, "SHA-1"); + } + +} diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationCaCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationCaCertChecker.java new file mode 100644 index 0000000..5051af2 --- /dev/null +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationCaCertChecker.java @@ -0,0 +1,101 @@ +package com.fortanix.key_attestation_statement_verification.certchecker; + +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import java.security.interfaces.RSAPublicKey; +import java.util.Arrays; + +import org.bouncycastle.asn1.ASN1ObjectIdentifier; +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; + +import com.fortanix.key_attestation_statement_verification.Common; +import com.fortanix.key_attestation_statement_verification.KeyAttestationStatementVerifyException; +import com.fortanix.key_attestation_statement_verification.types.KeyUsage; + +public class KeyAttestationCaCertChecker extends CertChecker { + + @Override + public void check(X509Certificate cert, X509Certificate issuerCert) throws Exception { + cert.checkValidity(); + check_subject_and_issuer(cert); + check_public_key(cert); + check_extensions(cert, issuerCert); + } + + private void check_subject_and_issuer(X509Certificate cert) throws Exception { + X509CertificateHolder certHolder = new JcaX509CertificateHolder(cert); + // check subject + X500Name caCertSubject = certHolder.getSubject(); + + if (!Common.checkNameMatch(caCertSubject, Common.FORTANIX_KEY_ATTESTATION_CA_NAME)) { + throw new KeyAttestationStatementVerifyException( + Common.FORTANIX_KEY_ATTESTATION_CA_CN + " certificate subject is invalid " + + caCertSubject.toString()); + } + + // check issuer + X500Name caCertIssuer = certHolder.getIssuer(); + if (!Common.checkNameMatch(caCertIssuer, Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_NAME)) { + throw new KeyAttestationStatementVerifyException( + Common.FORTANIX_KEY_ATTESTATION_CA_CN + " certificate issuer is invalid " + + caCertIssuer.toString()); + } + + } + + private void check_public_key(X509Certificate cert) throws Exception { + PublicKey caPk = cert.getPublicKey(); + if (caPk instanceof RSAPublicKey) { + RSAPublicKey caRsaPk = (RSAPublicKey) caPk; + assert (caRsaPk.getModulus().bitLength() >= 3072); + } else { + throw new KeyAttestationStatementVerifyException( + Common.FORTANIX_KEY_ATTESTATION_CA_CN + " certificate invalid public key type"); + } + + } + + private void check_extensions(X509Certificate cert, X509Certificate issuerCert) throws Exception { + // check extension: Key Usage + KeyUsage[] caCertExpectedKeyUsage = { KeyUsage.DIGITAL_SIGNATURE, KeyUsage.KEY_CERT_SIGN, KeyUsage.CRL_SIGN }; + KeyUsage.checkKeyUsageHelper(Common.FORTANIX_KEY_ATTESTATION_CA_CN, cert.getKeyUsage(), + caCertExpectedKeyUsage); + // check extension: Basic Constraints + int pathLenConstraint = cert.getBasicConstraints(); + if (pathLenConstraint < 0) { + throw new KeyAttestationStatementVerifyException( + Common.FORTANIX_KEY_ATTESTATION_CA_CN + + " certificate has invalid BasicConstraints extension, it should be a CA"); + + } + if (pathLenConstraint != Integer.MAX_VALUE) { + throw new KeyAttestationStatementVerifyException( + Common.FORTANIX_KEY_ATTESTATION_CA_CN + + " certificate has invalid BasicConstraints extension, it'a CA but pathLenConstraint should be absent"); + } + // check extension: CRL Distribution Points + verifyDistPoint(Common.FORTANIX_KEY_ATTESTATION_CA_CN, cert, + Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CRL_URL); + + // check extension: Subject Key Identifier + checkSubjectKeyIdentifier(Common.FORTANIX_KEY_ATTESTATION_CA_CN, cert, "SHA-1"); + // check extension: Authority Key Identifier + if (!Arrays.equals(getExtAkiVal(cert), getExtSkiVal(issuerCert))) { + throw new KeyAttestationStatementVerifyException( + Common.FORTANIX_KEY_ATTESTATION_CA_CN + + " certificate Authority Key Identifier extension has wrong value"); + } + + // check extension: Certificate Policies + if (getCertificatePolicyInfoByOID(cert, + new ASN1ObjectIdentifier(Common.FORTANIX_KEY_ATTESTATION_CERTIFICATE_POLICY_OID)) == null) { + throw new KeyAttestationStatementVerifyException(String.format( + "%s certificate Extended Key Usage extension should contain: Fortanix Key Attestation Certificate Policy (%s)", + Common.FORTANIX_KEY_ATTESTATION_CA_CN, + Common.FORTANIX_KEY_ATTESTATION_CERTIFICATE_POLICY_OID)); + } + } + +} diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationStatementCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationStatementCertChecker.java new file mode 100644 index 0000000..a49ebe3 --- /dev/null +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationStatementCertChecker.java @@ -0,0 +1,95 @@ +package com.fortanix.key_attestation_statement_verification.certchecker; + +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import java.security.interfaces.RSAPublicKey; +import java.util.Arrays; +import java.util.Set; +import java.util.stream.Collectors; + +import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.cert.X509CertificateHolder; +import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; + +import com.fortanix.key_attestation_statement_verification.Common; +import com.fortanix.key_attestation_statement_verification.KeyAttestationStatementVerifyException; +import com.fortanix.key_attestation_statement_verification.types.KeyUsage; + +public class KeyAttestationStatementCertChecker extends CertChecker { + @Override + public void check(X509Certificate cert, X509Certificate issuerCert) throws Exception { + cert.checkValidity(); + check_subject_and_issuer(cert); + check_public_key(cert); + check_extensions(cert, issuerCert); + } + + private void check_subject_and_issuer(X509Certificate cert) throws Exception { + X509CertificateHolder statementCert = new JcaX509CertificateHolder(cert); + // check subject + X500Name statementCertSubject = statementCert.getSubject(); + if (!Common.checkNameMatch(statementCertSubject, Common.KEY_ATTESTATION_STATEMENT_NAME)) { + throw new KeyAttestationStatementVerifyException( + Common.KEY_ATTESTATION_STATEMENT_CN + " certificate subject is invalid " + + statementCertSubject.toString()); + } + // check issuer + + X500Name statementCertIssuer = statementCert.getIssuer(); + if (!Common.checkNameMatch(statementCertIssuer, Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_NAME)) { + throw new KeyAttestationStatementVerifyException( + Common.KEY_ATTESTATION_STATEMENT_CN + " certificate issuer is invalid " + + statementCertIssuer.toString()); + } + } + + private void check_public_key(X509Certificate cert) throws Exception { + PublicKey statementPk = cert.getPublicKey(); + if (statementPk instanceof RSAPublicKey) { + RSAPublicKey statementRsaPk = (RSAPublicKey) statementPk; + assert (statementRsaPk.getModulus().bitLength() >= 2048); + } else { + throw new KeyAttestationStatementVerifyException( + Common.KEY_ATTESTATION_STATEMENT_CN + " certificate invalid public key type"); + } + + } + + private void check_extensions(X509Certificate cert, X509Certificate issuerCert) throws Exception { + checkCertKeyUsages(cert); + // check extension: Authority Key Identifier + if (!Arrays.equals(getExtAkiVal(cert), getExtSkiVal(issuerCert))) { + throw new KeyAttestationStatementVerifyException( + Common.KEY_ATTESTATION_STATEMENT_CN + + " certificate Authority Key Identifier extension has wrong value"); + } + } + + private void checkCertKeyUsages(X509Certificate cert) throws KeyAttestationStatementVerifyException { + boolean[] certKeyUsagesBooleans = cert.getKeyUsage(); + if (certKeyUsagesBooleans != null && certKeyUsagesBooleans.length == 9) { + KeyUsage[] allowedKeyUsages = { + KeyUsage.DIGITAL_SIGNATURE, + KeyUsage.KEY_ENCIPHERMENT, + KeyUsage.DATA_ENCIPHERMENT, + KeyUsage.KEY_AGREEMENT, + }; + Set allowedKeyUsagesSet = Arrays.stream(allowedKeyUsages).collect(Collectors.toSet()); + + KeyUsage[] disallowedKeyUsages = Arrays.stream(KeyUsage.values()) + .filter(keyUsage -> !allowedKeyUsagesSet.contains(keyUsage)) + .toArray(KeyUsage[]::new); + for (KeyUsage ku : disallowedKeyUsages) { + if (certKeyUsagesBooleans[ku.getBitIndex()]) { + throw new KeyAttestationStatementVerifyException( + Common.KEY_ATTESTATION_STATEMENT_CN + " keyUsage extension should not contain: " + + ku.toString()); + } + } + } else { + throw new KeyAttestationStatementVerifyException( + Common.KEY_ATTESTATION_STATEMENT_CN + " invalid keyUsage extension"); + } + } + +} diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/ClusterNodeEnrollmentPolicy.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/ClusterNodeEnrollmentPolicy.java new file mode 100644 index 0000000..a83a428 --- /dev/null +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/ClusterNodeEnrollmentPolicy.java @@ -0,0 +1,104 @@ +package com.fortanix.key_attestation_statement_verification.types; + +import org.bouncycastle.asn1.*; +import org.bouncycastle.asn1.x509.Extensions; + +import com.fortanix.key_attestation_statement_verification.Common; + +/** + * Java class for representing Fortanix defined ASN1 type: + * ClusterNodeEnrollmentPolicy + * + *
+ *   ClusterNodeEnrollmentPolicy ::= SEQUENCE SIZE (1..MAX) OF NodeEnrollmentPolicyItem
+ * 
+ */ +public class ClusterNodeEnrollmentPolicy extends ASN1Object { + private NodeEnrollmentPolicyItem[] nodeEnrollmentPolicyItems; + + public NodeEnrollmentPolicyItem[] getNodeEnrollmentPolicyItems() { + return copy(nodeEnrollmentPolicyItems); + } + + private static NodeEnrollmentPolicyItem[] copy(NodeEnrollmentPolicyItem[] items) { + NodeEnrollmentPolicyItem[] result = new NodeEnrollmentPolicyItem[items.length]; + System.arraycopy(items, 0, result, 0, items.length); + return result; + } + + public ClusterNodeEnrollmentPolicy(ASN1Sequence seq) { + this.nodeEnrollmentPolicyItems = new NodeEnrollmentPolicyItem[seq.size()]; + + for (int i = 0; i != seq.size(); i++) { + nodeEnrollmentPolicyItems[i] = NodeEnrollmentPolicyItem.getInstance(seq.getObjectAt(i)); + } + } + + public ClusterNodeEnrollmentPolicy(NodeEnrollmentPolicyItem item) { + this.nodeEnrollmentPolicyItems = new NodeEnrollmentPolicyItem[] { item }; + } + + public ClusterNodeEnrollmentPolicy(NodeEnrollmentPolicyItem[] items) { + this.nodeEnrollmentPolicyItems = copy(items); + } + + /** + * Produce an object suitable for an ASN1OutputStream. + * + *
+     * ClusterNodeEnrollmentPolicy ::= SEQUENCE SIZE (1..MAX) OF NodeEnrollmentPolicyItem
+     * 
+ */ + public ASN1Primitive toASN1Primitive() { + return new DERSequence(nodeEnrollmentPolicyItems); + } + + /** + * Return an ClusterNodeEnrollmentPolicy from the passed in object. + * + * @param obj an ClusterNodeEnrollmentPolicy, some form or encoding of one, or + * null. + * @return an ClusterNodeEnrollmentPolicy object, or null if null is passed in. + */ + public static ClusterNodeEnrollmentPolicy getInstance( + Object obj) { + if (obj instanceof ClusterNodeEnrollmentPolicy) { + return (ClusterNodeEnrollmentPolicy) obj; + } else if (obj != null) { + return new ClusterNodeEnrollmentPolicy(ASN1Sequence.getInstance(obj)); + } + + return null; + } + + public static ClusterNodeEnrollmentPolicy getInstance( + ASN1TaggedObject obj, + boolean explicit) { + return getInstance(ASN1Sequence.getInstance(obj, explicit)); + } + + /** + * Retrieve an ClusterNodeEnrollmentPolicy for a passed in Extensions object, if + * present. + * + * @param extensions the extensions object to be examined. + * @return the ClusterNodeEnrollmentPolicy, null if the extension is not + * present. + */ + public static ClusterNodeEnrollmentPolicy fromExtensions(Extensions extensions) { + return getInstance(Extensions.getExtensionParsedValue(extensions, + new ASN1ObjectIdentifier(Common.CLUSTER_NODE_ENROLLMENT_POLICY_OID))); + } + + public String toString() { + StringBuffer p = new StringBuffer(); + for (int i = 0; i < nodeEnrollmentPolicyItems.length; i++) { + if (p.length() != 0) { + p.append(", "); + } + p.append(nodeEnrollmentPolicyItems[i]); + } + + return "ClusterNodeEnrollmentPolicy: [" + p + "]"; + } +} diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/KeyUsage.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/KeyUsage.java new file mode 100644 index 0000000..99d9ad4 --- /dev/null +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/KeyUsage.java @@ -0,0 +1,68 @@ +package com.fortanix.key_attestation_statement_verification.types; + +import com.fortanix.key_attestation_statement_verification.KeyAttestationStatementVerifyException; + +/** + * The helper type for checking X509 KeyUsage extension + */ +public enum KeyUsage { + DIGITAL_SIGNATURE(0), + NON_REPUDIATION(1), + KEY_ENCIPHERMENT(2), + DATA_ENCIPHERMENT(3), + KEY_AGREEMENT(4), + KEY_CERT_SIGN(5), + CRL_SIGN(6), + ENCIPHER_ONLY(7), + DECIPHER_ONLY(8); + + final int bitIndex; + + KeyUsage(int bitIndex) { + this.bitIndex = bitIndex; + } + + public int getBitIndex() { + return this.bitIndex; + } + + @Override + public String toString() { + switch (this) { + case DIGITAL_SIGNATURE: + return "Digital Signature"; + case NON_REPUDIATION: + return "Non-Repudiation"; + case KEY_ENCIPHERMENT: + return "Key Encipherment"; + case DATA_ENCIPHERMENT: + return "Data Encipherment"; + case KEY_AGREEMENT: + return "Key Agreement"; + case KEY_CERT_SIGN: + return "Key Certificate Sign"; + case CRL_SIGN: + return "CRL Sign"; + case ENCIPHER_ONLY: + return "Encipher Only"; + case DECIPHER_ONLY: + return "Decipher Only"; + default: + throw new IllegalArgumentException(); + } + } + + public static void checkKeyUsageHelper(String errStrPrefix, boolean[] keyUsage, KeyUsage[] expectedEnabledBits) + throws KeyAttestationStatementVerifyException { + if (keyUsage != null && keyUsage.length == 9) { + for (KeyUsage ku : expectedEnabledBits) { + if (!keyUsage[ku.bitIndex]) { + throw new KeyAttestationStatementVerifyException( + errStrPrefix + " keyUsage extension does not contains: " + ku.toString()); + } + } + } else { + throw new KeyAttestationStatementVerifyException(errStrPrefix + " invalid keyUsage extension"); + } + } +} \ No newline at end of file diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/NodeEnrollmentPolicyItem.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/NodeEnrollmentPolicyItem.java new file mode 100644 index 0000000..f0d1514 --- /dev/null +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/NodeEnrollmentPolicyItem.java @@ -0,0 +1,85 @@ +package com.fortanix.key_attestation_statement_verification.types; + +import org.bouncycastle.asn1.*; + +/** + * Java class for representing Fortanix defined ASN1 type: + * NodeEnrollmentPolicyItem + * + *
+ *   NodeEnrollmentPolicyItem ::= SEQUENCE {
+ *   policyItem OBJECT IDENTIFIER,
+ *   qualifiers ANY DEFINED BY policyItem OPTIONAL }
+ * 
+ */ +public class NodeEnrollmentPolicyItem extends ASN1Object { + private ASN1ObjectIdentifier policyItem; + private ASN1Encodable qualifiers; + + private NodeEnrollmentPolicyItem(ASN1Sequence seq) { + if (seq.size() < 1 || seq.size() > 2) { + throw new IllegalArgumentException("Bad sequence size: " + + seq.size()); + } + + policyItem = ASN1ObjectIdentifier.getInstance(seq.getObjectAt(0)); + + if (seq.size() > 1) { + qualifiers = seq.getObjectAt(1); + } + } + + public NodeEnrollmentPolicyItem(ASN1ObjectIdentifier policyItem) { + this.policyItem = policyItem; + } + + public NodeEnrollmentPolicyItem(ASN1ObjectIdentifier policyItem, ASN1Encodable qualifiers) { + this.policyItem = policyItem; + this.qualifiers = qualifiers; + } + + public static NodeEnrollmentPolicyItem getInstance(Object obj) { + if (obj == null || obj instanceof NodeEnrollmentPolicyItem) { + return (NodeEnrollmentPolicyItem) obj; + } + + return new NodeEnrollmentPolicyItem(ASN1Sequence.getInstance(obj)); + } + + public ASN1ObjectIdentifier getPolicyItem() { + return policyItem; + } + + public ASN1Encodable getQualifiers() { + return qualifiers; + } + + /* + *
+     * NodeEnrollmentPolicyItem ::= SEQUENCE {
+     * policyItem OBJECT IDENTIFIER,
+     * qualifiers ANY DEFINED BY policyItem OPTIONAL }
+     * 
+ */ + public ASN1Primitive toASN1Primitive() { + ASN1EncodableVector vec = new ASN1EncodableVector(2); + vec.add(policyItem); + if (qualifiers != null) { + vec.add(qualifiers); + } + return new DERSequence(vec); + } + + public String toString() { + StringBuffer sb = new StringBuffer(); + + sb.append("NodeEnrollmentPolicyItem: "); + sb.append(policyItem); + + if (qualifiers != null) { + sb.append(qualifiers); + } + + return sb.toString(); + } +} \ No newline at end of file diff --git a/key-attestation/java-example/src/test/java/com/fortanix/key_attestation_statement_verification/VerifyTest.java b/key-attestation/java-example/src/test/java/com/fortanix/key_attestation_statement_verification/VerifyTest.java new file mode 100644 index 0000000..05f91a1 --- /dev/null +++ b/key-attestation/java-example/src/test/java/com/fortanix/key_attestation_statement_verification/VerifyTest.java @@ -0,0 +1,72 @@ +package com.fortanix.key_attestation_statement_verification; + +import org.junit.Ignore; +import org.junit.Test; +import static org.junit.Assert.*; + +import java.net.URL; +import java.security.cert.X509Certificate; +import java.util.List; + +public class VerifyTest { + private static final String VALID_STATEMENT_CERT_PEM = "key-attestation-statement.pem"; + + private URL getTestFileUrl(String fileName) throws Exception { + URL resUrl = getClass().getClassLoader().getResource(fileName); + if (resUrl == null) { + throw new IllegalArgumentException("Test resource file not found!"); + } else { + return resUrl; + } + } + + /** + * This test tests the verification logic expect CRL verification and Root CA + * download + * + * @throws Exception + */ + @Test + public void verifyStatementWithoutCrlCheck() throws Exception { + URL url = getTestFileUrl(VALID_STATEMENT_CERT_PEM); + List cert_chain = Verify.readPemCertsFromPath(url.getPath()); + assertEquals(4, cert_chain.size()); + List authorityChain = cert_chain.subList(1, cert_chain.size()); + // Last certificate is Root CA cert, since the test certificate is using a fake + // root CA, so we assume root ca cert is correct by using last certificate as + // trust CA certificate + // NOTE: please replace with Root CA certificate if you already downloaded it + // somewhere + X509Certificate trusted = cert_chain.get(cert_chain.size() - 1); + // because at time this code is written, CRL server is not setup, we turn of the + // CRL check + Verify.verify(authorityChain, cert_chain.get(0), trusted, false); + } + + /** + * This test is ignored because it's an example code for showing how to verify a + * real 'Fortanix DSM Key Attestation' + * + * @throws Exception + */ + @Ignore + @Test + public void verifyStatementFullCheck() throws Exception { + // Note, the certificate in the file should be in order of: + // 1. Fortanix DSM Key Attestation + // 2. Fortanix DSM SaaS Key Attestation Authority + // 3. Fortanix Key Attestation CA + // 4. Fortanix Attestation and Provisioning Root CA + String certChainPath = "Path to the certificate chain file"; + List cert_chain = Verify.readPemCertsFromPath(certChainPath); + assertEquals(4, cert_chain.size()); + List authorityChain = cert_chain.subList(1, cert_chain.size()); + + System.out.println("Downloading Fortanix Attestation and Provisioning Root CA certificate form: " + + Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CERT_URL); + X509Certificate trustedRootCert = Common.getFortanixRootCaCertRemote( + Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CERT_URL); + + Verify.verify(authorityChain, cert_chain.get(0), trustedRootCert, true); + } +} diff --git a/key-attestation/java-example/src/test/resources/key-attestation-statement.pem b/key-attestation/java-example/src/test/resources/key-attestation-statement.pem new file mode 100644 index 0000000..3946974 --- /dev/null +++ b/key-attestation/java-example/src/test/resources/key-attestation-statement.pem @@ -0,0 +1,129 @@ +-----BEGIN CERTIFICATE----- +MIID/zCCAmegAwIBAgIUCVQHdgKkQdO34cZVHfE5cO1rQwUwDQYJKoZIhvcNAQEL +BQAwNjE0MDIGA1UEAwwrRm9ydGFuaXggRFNNIFNhYVMgS2V5IEF0dGVzdGF0aW9u +IEF1dGhvcml0eTAgFw0yMzA5MDEwMDM2MDZaGA85OTk5MTIzMTIzNTk1OVowXjEl +MCMGA1UEAwwcRm9ydGFuaXggRFNNIEtleSBBdHRlc3RhdGlvbjE1MDMGCysGAQQB +g4QaAQICDCRiMmI4N2Y4NC04MGQyLTRjNGMtYmE0MS03ZmExMmZiNGVmZjUwggEi +MA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDJnG/Pwu6ElZ7ySoMWwleMK0Z6 +fbKKUeqIuTGMSLfqoFVH+JeEVNSh1dYzpA18vm7/7kjc11CaABgzzA42tH8QUkq2 +atVFvUKIJcNhueuu1mMBeeujOarbeOTfypVtoj200ITgYdcCXuNMefNplvamEb6R +bSPYMVfWxblNhZqTw8FFPHWIMNjoiNKOlXL7/uirMS8Av0saMhJ1dWXtX44F06ts +OYIdkx2AogMmj+Op+uOt2RwMzMnofsitapREPGhr8nmJqK/i5jJSgt38NZs/hn1x +wRXCnCj4OpMudjiK9q3+5EddTTYXXMukGRtQ2OIb3e9ViUncpTzyCZ1+VLyRAgMB +AAGjWzBZMA4GA1UdDwEB/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lZTuX +TD/H5gy/Zv8zDTe/1Zj+KY7Q+BiTJSrUsi8y1M3loePYwO4bWZbnVR6+PzZTPDhR +45m9wTsAcrQTNSZn3khxJ6pMcFsGucM8oyVYwOtBB3QZOmI3D0SkITtAnkcunT9s +D8nCO8Bw0BOkYKOJBIWBSWuruRCrZDxIbjgeykcAAPj47nPpoAYmI5vwF8LkLJNc +hugoUHmw3aC7/rJtJoP2AlLMe3aK7f7o8Y+jZZPEBcD37iu5TNekU17WlH+Q22n5 +/4hGYGGMQ5uK2971wifIc3QqvUczB/3cu8BTLFlAxCxic359Rb6u5AS5RJE7sYKI +EeS4TnykL05RW11u1A/mkVsuBaOYHEeAN28Hz4xMffoWtPTM1oCfEAv7eYH/ZdJ7 +5xeLVJjEyY2/55NKoAIMsK91iPwWHE7DZSQMAuRLtrYtrkyHHNBRGru2ikdpvy1g +9qajKqHV7Dnp9sTMixqq15OgLnUKwmQffGfzhCbcSj9K1mkGO2nTSOAZJaDvfxWf +yGypNrVAJI78/0/5zY+qkEivgh9xpnoAKHK4UT/cKhuLDCNQIEhB4fhnwhOuX1/1 +DFOz4Vdzshx2KL0eanblKF2i0ekR8tzv97a41mzM3Q/TXe0l9xVINzDynbePYHrs +WBYyPcMCau5v4vFxobX+622kIrXllaU+gQ== +-----END CERTIFICATE----- \ No newline at end of file From ef17bb6587d62ce359addd7d83d6adac7e1c049a Mon Sep 17 00:00:00 2001 From: Yuxiang Cao Date: Mon, 4 Sep 2023 18:03:22 -0700 Subject: [PATCH 02/12] ci: add CI for java-example --- .github/workflows/java-example-ci.yml | 48 +++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 .github/workflows/java-example-ci.yml diff --git a/.github/workflows/java-example-ci.yml b/.github/workflows/java-example-ci.yml new file mode 100644 index 0000000..57ca016 --- /dev/null +++ b/.github/workflows/java-example-ci.yml @@ -0,0 +1,48 @@ +# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-java-with-maven + +name: Java CI with Maven for java-example + +on: + push: + branches: [ "main" ] + paths: + - 'key-attestation/java-example/**' + pull_request: + branches: [ "main" ] + paths: + - 'key-attestation/java-example/**' + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Set up JDK 8 + uses: actions/setup-java@v3 + with: + java-version: '8' + distribution: 'temurin' + cache: maven + - name: Check and Install Maven + run: | + if ! command -v mvn --version &> /dev/null + then + echo "Maven could not be found" + echo "Installing Maven..." + sudo apt update + sudo apt install -y maven + mvn --version + else + echo "Maven is already installed" + fi + - name: Build with Maven + run: mvn -B package --file key-attestation/java-example/pom.xml + + # Optional: Uploads the full dependency graph to GitHub to improve the quality of Dependabot alerts this repository can receive + - name: Update dependency graph + uses: advanced-security/maven-dependency-submission-action@571e99aab1055c2e71a1e2309b9691de18d6b7d6 + with: + directory: key-attestation/java-example From 34dd72047154fbb7604ff9b90c151d4cedfbf1b4 Mon Sep 17 00:00:00 2001 From: Yuxiang Cao Date: Tue, 5 Sep 2023 11:11:45 -0700 Subject: [PATCH 03/12] fix: add missing check on statement cert signature --- .../fortanix/key_attestation_statement_verification/Verify.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Verify.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Verify.java index 7036b44..ba7fe68 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Verify.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Verify.java @@ -61,6 +61,8 @@ public static void verify(List authorityChain, X509Certificate // because 'Fortanix DSM SaaS Key Attestation Authority' is not a CA // certificate, so we need to manually check 'Fortanix DSM Key Attestation' is // correctly singed by 'Fortanix DSM SaaS Key Attestation Authority' certificate + verify_cert_signature(attestationStatement, authorityChain.get(0)); + CertChecker statementChecker = new KeyAttestationStatementCertChecker(); CertChecker authorityChecker = new DsmKeyAttestationAuthorityCertChecker(); CertChecker caChecker = new KeyAttestationCaCertChecker(); From d9f96acd8ea0b42df4b7028caa8854eff2de600f Mon Sep 17 00:00:00 2001 From: Yuxiang Cao Date: Tue, 5 Sep 2023 12:09:47 -0700 Subject: [PATCH 04/12] refactor: add logging --- .../Common.java | 11 +++++ .../Verify.java | 22 +++++++-- .../certchecker/CertChecker.java | 49 ++++++++++++++++--- ...DsmKeyAttestationAuthorityCertChecker.java | 20 +++++++- .../certchecker/FortanixRootCertChecker.java | 19 ++++++- .../KeyAttestationCaCertChecker.java | 19 ++++++- .../KeyAttestationStatementCertChecker.java | 18 +++++++ 7 files changed, 145 insertions(+), 13 deletions(-) diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Common.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Common.java index 070216d..73417aa 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Common.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Common.java @@ -14,6 +14,7 @@ import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.asn1.x500.X500NameBuilder; import org.bouncycastle.asn1.x500.style.BCStyle; +import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; public class Common { public static final String FORTANIX_PKI_DOMAIN = "pki.fortanix.com"; @@ -230,4 +231,14 @@ public static X509Certificate getFortanixRootCaCertRemote(String rootCertUrlStr) return certs.get(0); } + /** + * Helper function to get CN string from a certificate + * @param cert Source certificate + * @return Common Name (CN) of the given certificate + * @throws Exception + */ + public static String getCommonName(X509Certificate cert) throws Exception { + X500Name x500name = new JcaX509CertificateHolder(cert).getSubject(); + return x500name.getRDNs(BCStyle.CN)[0].getFirst().getValue().toString(); + } } diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Verify.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Verify.java index ba7fe68..18d3c0d 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Verify.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Verify.java @@ -15,6 +15,7 @@ import java.util.Collections; import java.util.List; import java.util.Set; +import java.util.logging.Logger; import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; @@ -28,6 +29,7 @@ import com.fortanix.key_attestation_statement_verification.certchecker.KeyAttestationStatementCertChecker; public final class Verify { + private static final Logger LOGGER = Logger.getLogger(Verify.class.getName()); static { Security.addProvider(new BouncyCastleProvider()); @@ -48,6 +50,7 @@ public static void verify(List authorityChain, X509Certificate X509Certificate trustRootCa, boolean verifyCrl) throws Exception { checkAuthorityChainLength(authorityChain); + LOGGER.info("Checking if root certificate in `authorityChain` matches given trusted root certificate"); check_root_cert_match(authorityChain.get(authorityChain.size() - 1), trustRootCa); // verify each signature on authority certificate chain is correctly signed by // it's parent @@ -58,6 +61,8 @@ public static void verify(List authorityChain, X509Certificate throw new KeyAttestationStatementVerifyException( "The signature in 'Fortanix DSM Key Attestation' certificate is valid, " + e.toString()); } + LOGGER.info(String.format("Checking if '%s' certificate is correctly signed by '%s' certificate", + Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, Common.KEY_ATTESTATION_STATEMENT_CN)); // because 'Fortanix DSM SaaS Key Attestation Authority' is not a CA // certificate, so we need to manually check 'Fortanix DSM Key Attestation' is // correctly singed by 'Fortanix DSM SaaS Key Attestation Authority' certificate @@ -90,6 +95,7 @@ public static void verify(List authorityChain, X509Certificate public static void verify_cert_chain_signature(List chain, X509Certificate trust_ca, boolean verifyCrl) throws Exception { + LOGGER.info("Checking if root certificate in `authorityChain` matches given trusted root certificate"); if (chain.isEmpty()) { throw new KeyAttestationStatementVerifyException("Empty certificate chain"); } @@ -125,6 +131,8 @@ public static void verify_cert_chain_signature(List chain, X509 */ public static void check_root_cert_match(X509Certificate root_cert, X509Certificate trust_ca) throws Exception { if (!root_cert.equals(trust_ca)) { + LOGGER.warning("Actual root cert:\n" + root_cert.toString()); + LOGGER.warning("Expected root cert:\n" + trust_ca.toString()); throw new KeyAttestationStatementVerifyException( "Root CA certificate in chain does not match trust ca certificate"); } @@ -139,6 +147,7 @@ public static void check_root_cert_match(X509Certificate root_cert, X509Certific * @throws Exception */ public static List readPemCertsFromPath(String pemFilePath) throws Exception { + LOGGER.info(String.format("Reading PEM certificates from %s ...", pemFilePath)); Reader reader = new FileReader(pemFilePath); return readPemCertsFromReader(reader); } @@ -151,6 +160,7 @@ public static List readPemCertsFromPath(String pemFilePath) thr * @throws Exception */ public static List readPemCertsFromReader(Reader reader) throws Exception { + LOGGER.info(String.format("Reading PEM certificates from %s ...", reader.toString())); List certChain = new ArrayList<>(); try (PEMParser pemParser = new PEMParser(reader)) { Object object = pemParser.readObject(); @@ -185,12 +195,15 @@ public static List readPemCertsFromReader(Reader reader) throws */ public static List convertX509CertificateHolders(List cert_chain) throws Exception { + LOGGER.info("Converting List to List ..."); // Convert X509CertificateHolder to Certificate for CertPath JcaX509CertificateConverter converter = new JcaX509CertificateConverter() .setProvider(BouncyCastleProvider.PROVIDER_NAME); List chain = new ArrayList<>(); for (X509CertificateHolder holder : cert_chain) { - chain.add(converter.getCertificate(holder)); + X509Certificate cert = converter.getCertificate(holder); + LOGGER.fine("Converted cert:\n" + cert.toString()); + chain.add(cert); } return chain; } @@ -203,7 +216,10 @@ public static List convertX509CertificateHolders(List authorityCertChain) throws KeyAttestationStatementVerifyException { - if (authorityCertChain.size() != Common.VALID_AUTHORITY_CERT_CHAIN_NUM) { + int authorityCertChainSize = authorityCertChain.size(); + LOGGER.info(String.format("Checking authorityCertChain size: %d == %d ?", authorityCertChainSize, + Common.VALID_AUTHORITY_CERT_CHAIN_NUM)); + if (authorityCertChainSize != Common.VALID_AUTHORITY_CERT_CHAIN_NUM) { throw new KeyAttestationStatementVerifyException( String.format( "A valid authority certificates chain should contain %d certificate", @@ -219,7 +235,7 @@ private static void checkAuthorityChainLength(List authorityCer * @param parent The certificate of issuer * @throws Exception */ - public static void verify_cert_chain_signature(X509Certificate child, X509Certificate parent) + public static void verify_cert_signature(X509Certificate child, X509Certificate parent) throws Exception { PublicKey parentPublicKey = parent.getPublicKey(); child.verify(parentPublicKey); diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/CertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/CertChecker.java index 3320887..c34a1c3 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/CertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/CertChecker.java @@ -2,6 +2,7 @@ import java.security.MessageDigest; import java.security.cert.X509Certificate; +import java.util.logging.Logger; import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1ObjectIdentifier; @@ -20,6 +21,7 @@ import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; +import com.fortanix.key_attestation_statement_verification.Common; import com.fortanix.key_attestation_statement_verification.KeyAttestationStatementVerifyException; import com.fortanix.key_attestation_statement_verification.types.ClusterNodeEnrollmentPolicy; @@ -27,6 +29,8 @@ * This abstract class represents custom certificate checker */ public abstract class CertChecker { + private static Logger LOGGER = Logger.getLogger(CertChecker.class.getName()); + /** * This function should check all details in given certificate `cert` * @@ -36,7 +40,17 @@ public abstract class CertChecker { */ abstract public void check(X509Certificate cert, X509Certificate issuerCert) throws Exception; + /** + * Verify the CrlDistPoint extension in given certificate contains expected URL + * + * @param errStrPrefix + * @param cert Source certificate + * @param expectedCrl Expected CRL URL + * @throws Exception + */ protected void verifyDistPoint(String errStrPrefix, X509Certificate cert, String expectedCrl) throws Exception { + LOGGER.info(String.format("Checking if '%s' certificate's CrlDistPoint contains: %s", + Common.getCommonName(cert), expectedCrl)); byte[] crlDistPointExtOctetBytes = cert.getExtensionValue("2.5.29.31"); if (crlDistPointExtOctetBytes == null) { throw new KeyAttestationStatementVerifyException( @@ -72,20 +86,23 @@ protected void verifyDistPoint(String errStrPrefix, X509Certificate cert, String * Check given certificate's SubjectKeyIdentifier extension matches its Public * Subject Key info * - * @param errStrPrefix - * @param cert Certificate to be checked - * @param digestAlgo Hash algorithm name used for creating - * SubjectKeyIdentifier + * @param cert Certificate to be checked + * @param digestAlgo Hash algorithm name used for creating + * SubjectKeyIdentifier + * * @throws Exception */ - protected void checkSubjectKeyIdentifier(String errStrPrefix, X509Certificate cert, String digestAlgo) + protected void checkSubjectKeyIdentifier(X509Certificate cert, String digestAlgo) throws Exception { + LOGGER.info(String.format( + "Checking if '%s' certificate's SubjectKeyIdentifier extension matches its Public Subject Key info", + Common.getCommonName(cert))); byte[] computedSkiVal = getComputedSkiVal(cert, digestAlgo); byte[] skiVal = getExtSkiVal(cert); // Compare both SKIs if (!java.util.Arrays.equals(skiVal, computedSkiVal)) { throw new KeyAttestationStatementVerifyException( - errStrPrefix + Common.getCommonName(cert) + " certificate Subject Key Identifier content not match with Subject Public Key"); } } @@ -98,6 +115,9 @@ protected void checkSubjectKeyIdentifier(String errStrPrefix, X509Certificate ce * @throws Exception */ protected byte[] getExtSkiVal(X509Certificate cert) throws Exception { + LOGGER.info(String.format( + "Getting '%s' certificate's SubjectKeyIdentifier extension", + Common.getCommonName(cert))); X509CertificateHolder certHolder = new JcaX509CertificateHolder(cert); SubjectKeyIdentifier ski = SubjectKeyIdentifier.fromExtensions(certHolder.getExtensions()); if (ski == null) { @@ -115,6 +135,9 @@ protected byte[] getExtSkiVal(X509Certificate cert) throws Exception { * Authority Key Identifier extension found */ protected byte[] getExtAkiVal(X509Certificate cert) throws Exception { + LOGGER.info(String.format( + "Getting '%s' certificate's AuthorityKeyIdentifier extension", + Common.getCommonName(cert))); X509CertificateHolder certHolder = new JcaX509CertificateHolder(cert); AuthorityKeyIdentifier aki = AuthorityKeyIdentifier.fromExtensions(certHolder.getExtensions()); if (aki == null) { @@ -133,6 +156,9 @@ protected byte[] getExtAkiVal(X509Certificate cert) throws Exception { * @throws Exception */ protected byte[] getComputedSkiVal(X509Certificate cert, String digestAlgo) throws Exception { + LOGGER.info(String.format( + "Computing '%s' certificate's Subject Key Identifier value from certificate's Public Subject Key", + Common.getCommonName(cert))); byte[] certPkVal = cert.getPublicKey().getEncoded(); MessageDigest md = MessageDigest.getInstance(digestAlgo); byte[] computedSkiVal = md.digest(certPkVal); @@ -141,7 +167,7 @@ protected byte[] getComputedSkiVal(X509Certificate cert, String digestAlgo) thro /** * Get specific CertificatePolicyInfo from CertificatePolicies extension - * + * * @param cert Source certificate * @param policyIdentifier Specific OID of CertificatePolicyInfo * @return PolicyInformation that matches given OID @@ -150,6 +176,9 @@ protected byte[] getComputedSkiVal(X509Certificate cert, String digestAlgo) thro */ protected PolicyInformation getCertificatePolicyInfoByOID(X509Certificate cert, ASN1ObjectIdentifier policyIdentifier) throws Exception { + LOGGER.info(String.format( + "Getting '%s' certificate's CertificatePolicyInfo with OID: %s from CertificatePolicies extension", + Common.getCommonName(cert), policyIdentifier.toString())); X509CertificateHolder certHolder = new JcaX509CertificateHolder(cert); CertificatePolicies certificatePolicies = CertificatePolicies.fromExtensions(certHolder.getExtensions()); if (certificatePolicies == null) { @@ -168,6 +197,9 @@ protected PolicyInformation getCertificatePolicyInfoByOID(X509Certificate cert, * ExtendedKeyUsage extension found */ protected boolean checkExtendedKeyUsage(X509Certificate cert, KeyPurposeId keyPurposeId) throws Exception { + LOGGER.info(String.format( + "Checking '%s' certificate has extended key usage with OID: %s from ExtendedKeyUsage extension", + Common.getCommonName(cert), keyPurposeId.toString())); X509CertificateHolder certHolder = new JcaX509CertificateHolder(cert); ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage.fromExtensions(certHolder.getExtensions()); if (extendedKeyUsage == null) { @@ -185,6 +217,9 @@ protected boolean checkExtendedKeyUsage(X509Certificate cert, KeyPurposeId keyPu * ClusterNodeEnrollmentPolicy extension found */ protected ClusterNodeEnrollmentPolicy getClusterNodeEnrollmentPolicy(X509Certificate cert) throws Exception { + LOGGER.info(String.format( + "Getting '%s' certificate's ClusterNodeEnrollmentPolicy extension (OID: %s)", + Common.getCommonName(cert), Common.CLUSTER_NODE_ENROLLMENT_POLICY_OID)); X509CertificateHolder certHolder = new JcaX509CertificateHolder(cert); ClusterNodeEnrollmentPolicy clusterNodeEnrollmentPolicy = ClusterNodeEnrollmentPolicy .fromExtensions(certHolder.getExtensions()); diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/DsmKeyAttestationAuthorityCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/DsmKeyAttestationAuthorityCertChecker.java index 4fd5486..13c2773 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/DsmKeyAttestationAuthorityCertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/DsmKeyAttestationAuthorityCertChecker.java @@ -4,6 +4,7 @@ import java.security.cert.X509Certificate; import java.security.interfaces.RSAPublicKey; import java.util.Arrays; +import java.util.logging.Logger; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.x500.X500Name; @@ -18,11 +19,24 @@ import com.fortanix.key_attestation_statement_verification.types.NodeEnrollmentPolicyItem; public class DsmKeyAttestationAuthorityCertChecker extends CertChecker { + private static final Logger LOGGER = Logger.getLogger(DsmKeyAttestationAuthorityCertChecker.class.getName()); + private String certCN; + @Override public void check(X509Certificate cert, X509Certificate issuerCert) throws Exception { + LOGGER.info("Checking certificate content:\n" + cert.toString()); + certCN = Common.getCommonName(cert); + LOGGER.info(String.format( + "Checking '%s' certificate's Validity", certCN)); cert.checkValidity(); + LOGGER.info(String.format( + "Checking '%s' certificate's Subject & Issuer", certCN)); check_subject_and_issuer(cert); + LOGGER.info(String.format( + "Checking '%s' certificate's Public key length & type", certCN)); check_public_key(cert); + LOGGER.info(String.format( + "Checking '%s' certificate's extensions", certCN)); check_extensions(cert, issuerCert); } @@ -59,10 +73,14 @@ private void check_public_key(X509Certificate cert) throws Exception { private void check_extensions(X509Certificate cert, X509Certificate issuerCert) throws Exception { // check extension: Key Usage + LOGGER.info(String.format( + "Checking '%s' certificate's KeyUsages extension", certCN)); KeyUsage[] authorityCertExpectedKeyUsage = { KeyUsage.DIGITAL_SIGNATURE }; KeyUsage.checkKeyUsageHelper(Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, cert.getKeyUsage(), authorityCertExpectedKeyUsage); // check extension: Basic Constraints + LOGGER.info(String.format( + "Checking '%s' certificate's BasicConstraints extension", certCN)); int pathLenConstraint = cert.getBasicConstraints(); if (pathLenConstraint != -1) { throw new KeyAttestationStatementVerifyException( @@ -74,7 +92,7 @@ private void check_extensions(X509Certificate cert, X509Certificate issuerCert) verifyDistPoint(Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, cert, Common.FORTANIX_KEY_ATTESTATION_CA_CRL_URL); // check extension: Subject Key Identifier - checkSubjectKeyIdentifier(Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, cert, "SHA-1"); + checkSubjectKeyIdentifier(cert, "SHA-1"); // check extension: Authority Key Identifier if (!Arrays.equals(getExtAkiVal(cert), getExtSkiVal(issuerCert))) { throw new KeyAttestationStatementVerifyException( diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/FortanixRootCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/FortanixRootCertChecker.java index 51e6f87..8893eda 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/FortanixRootCertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/FortanixRootCertChecker.java @@ -3,6 +3,7 @@ import java.security.PublicKey; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPublicKey; +import java.util.logging.Logger; import org.bouncycastle.asn1.x500.X500Name; import org.bouncycastle.cert.X509CertificateHolder; @@ -13,12 +14,24 @@ import com.fortanix.key_attestation_statement_verification.types.KeyUsage; public class FortanixRootCertChecker extends CertChecker { + private static final Logger LOGGER = Logger.getLogger(FortanixRootCertChecker.class.getName()); + private String certCN; @Override public void check(X509Certificate cert, X509Certificate issuerCert) throws Exception { + LOGGER.info("Checking certificate content:\n" + cert.toString()); + certCN = Common.getCommonName(cert); + LOGGER.info(String.format( + "Checking '%s' certificate's Validity", certCN)); cert.checkValidity(); + LOGGER.info(String.format( + "Checking '%s' certificate's Subject & Issuer", certCN)); check_subject_and_issuer(cert); + LOGGER.info(String.format( + "Checking '%s' certificate's Public key length & type", certCN)); check_public_key(cert); + LOGGER.info(String.format( + "Checking '%s' certificate's extensions", certCN)); check_extensions(cert); } @@ -56,11 +69,15 @@ private void check_public_key(X509Certificate cert) throws Exception { private void check_extensions(X509Certificate cert) throws Exception { // check extension: Key Usage + LOGGER.info(String.format( + "Checking '%s' certificate's KeyUsages extension", certCN)); KeyUsage[] rootCertExpectedKeyUsage = { KeyUsage.DIGITAL_SIGNATURE, KeyUsage.KEY_CERT_SIGN, KeyUsage.CRL_SIGN }; KeyUsage.checkKeyUsageHelper(Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CN, cert.getKeyUsage(), rootCertExpectedKeyUsage); int pathLenConstraint = cert.getBasicConstraints(); // check extension: Basic Constraints + LOGGER.info(String.format( + "Checking '%s' certificate's BasicConstraints extension", certCN)); if (pathLenConstraint < 0) { throw new KeyAttestationStatementVerifyException( Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CN @@ -72,7 +89,7 @@ private void check_extensions(X509Certificate cert) throws Exception { Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CN + " certificate has invalid BasicConstraints extension, it'a CA but pathLenConstraint should be absent"); } - checkSubjectKeyIdentifier(Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CN, cert, "SHA-1"); + checkSubjectKeyIdentifier(cert, "SHA-1"); } } diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationCaCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationCaCertChecker.java index 5051af2..4be9a36 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationCaCertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationCaCertChecker.java @@ -4,6 +4,7 @@ import java.security.cert.X509Certificate; import java.security.interfaces.RSAPublicKey; import java.util.Arrays; +import java.util.logging.Logger; import org.bouncycastle.asn1.ASN1ObjectIdentifier; import org.bouncycastle.asn1.x500.X500Name; @@ -15,12 +16,24 @@ import com.fortanix.key_attestation_statement_verification.types.KeyUsage; public class KeyAttestationCaCertChecker extends CertChecker { + private static final Logger LOGGER = Logger.getLogger(KeyAttestationCaCertChecker.class.getName()); + private String certCN; @Override public void check(X509Certificate cert, X509Certificate issuerCert) throws Exception { + LOGGER.info("Checking certificate content:\n" + cert.toString()); + certCN = Common.getCommonName(cert); + LOGGER.info(String.format( + "Checking '%s' certificate's Validity", certCN)); cert.checkValidity(); + LOGGER.info(String.format( + "Checking '%s' certificate's Subject & Issuer", certCN)); check_subject_and_issuer(cert); + LOGGER.info(String.format( + "Checking '%s' certificate's Public key length & type", certCN)); check_public_key(cert); + LOGGER.info(String.format( + "Checking '%s' certificate's extensions", certCN)); check_extensions(cert, issuerCert); } @@ -59,10 +72,14 @@ private void check_public_key(X509Certificate cert) throws Exception { private void check_extensions(X509Certificate cert, X509Certificate issuerCert) throws Exception { // check extension: Key Usage + LOGGER.info(String.format( + "Checking '%s' certificate's KeyUsages extension", certCN)); KeyUsage[] caCertExpectedKeyUsage = { KeyUsage.DIGITAL_SIGNATURE, KeyUsage.KEY_CERT_SIGN, KeyUsage.CRL_SIGN }; KeyUsage.checkKeyUsageHelper(Common.FORTANIX_KEY_ATTESTATION_CA_CN, cert.getKeyUsage(), caCertExpectedKeyUsage); // check extension: Basic Constraints + LOGGER.info(String.format( + "Checking '%s' certificate's BasicConstraints extension", certCN)); int pathLenConstraint = cert.getBasicConstraints(); if (pathLenConstraint < 0) { throw new KeyAttestationStatementVerifyException( @@ -80,7 +97,7 @@ private void check_extensions(X509Certificate cert, X509Certificate issuerCert) Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CRL_URL); // check extension: Subject Key Identifier - checkSubjectKeyIdentifier(Common.FORTANIX_KEY_ATTESTATION_CA_CN, cert, "SHA-1"); + checkSubjectKeyIdentifier(cert, "SHA-1"); // check extension: Authority Key Identifier if (!Arrays.equals(getExtAkiVal(cert), getExtSkiVal(issuerCert))) { throw new KeyAttestationStatementVerifyException( diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationStatementCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationStatementCertChecker.java index a49ebe3..c3a67a1 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationStatementCertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationStatementCertChecker.java @@ -5,6 +5,7 @@ import java.security.interfaces.RSAPublicKey; import java.util.Arrays; import java.util.Set; +import java.util.logging.Logger; import java.util.stream.Collectors; import org.bouncycastle.asn1.x500.X500Name; @@ -16,11 +17,24 @@ import com.fortanix.key_attestation_statement_verification.types.KeyUsage; public class KeyAttestationStatementCertChecker extends CertChecker { + private static final Logger LOGGER = Logger.getLogger(KeyAttestationStatementCertChecker.class.getName()); + private String certCN; + @Override public void check(X509Certificate cert, X509Certificate issuerCert) throws Exception { + LOGGER.info("Checking certificate content:\n" + cert.toString()); + certCN = Common.getCommonName(cert); + LOGGER.info(String.format( + "Checking '%s' certificate's Validity", certCN)); cert.checkValidity(); + LOGGER.info(String.format( + "Checking '%s' certificate's Subject & Issuer", certCN)); check_subject_and_issuer(cert); + LOGGER.info(String.format( + "Checking '%s' certificate's Public key length & type", certCN)); check_public_key(cert); + LOGGER.info(String.format( + "Checking '%s' certificate's extensions", certCN)); check_extensions(cert, issuerCert); } @@ -58,6 +72,8 @@ private void check_public_key(X509Certificate cert) throws Exception { private void check_extensions(X509Certificate cert, X509Certificate issuerCert) throws Exception { checkCertKeyUsages(cert); // check extension: Authority Key Identifier + LOGGER.info(String.format( + "Checking '%s' certificate's AuthorityKeyIdentifier extension", certCN)); if (!Arrays.equals(getExtAkiVal(cert), getExtSkiVal(issuerCert))) { throw new KeyAttestationStatementVerifyException( Common.KEY_ATTESTATION_STATEMENT_CN @@ -66,6 +82,8 @@ private void check_extensions(X509Certificate cert, X509Certificate issuerCert) } private void checkCertKeyUsages(X509Certificate cert) throws KeyAttestationStatementVerifyException { + LOGGER.info(String.format( + "Checking '%s' certificate's KeyUsages extension", certCN)); boolean[] certKeyUsagesBooleans = cert.getKeyUsage(); if (certKeyUsagesBooleans != null && certKeyUsagesBooleans.length == 9) { KeyUsage[] allowedKeyUsages = { From 361e6d501acecc0d51ad4b6e10efdbc23144a1ac Mon Sep 17 00:00:00 2001 From: Yuxiang Cao Date: Tue, 5 Sep 2023 13:50:41 -0700 Subject: [PATCH 05/12] build: remove unused dependencies --- key-attestation/java-example/pom.xml | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/key-attestation/java-example/pom.xml b/key-attestation/java-example/pom.xml index 6bb3f18..3593dd4 100644 --- a/key-attestation/java-example/pom.xml +++ b/key-attestation/java-example/pom.xml @@ -16,26 +16,6 @@ 3.0.0 - - org.eclipse - yasson - 2.0.4 - - - jakarta.json.bind - jakarta.json.bind-api - 2.0.0 - - - org.glassfish - jakarta.json - 2.0.1 - - - jakarta.json - jakarta.json-api - 2.1.2 - org.bouncycastle bcpkix-jdk18on From c47f1e290e6a54d255bcfebe2857ad8193313d72 Mon Sep 17 00:00:00 2001 From: Yuxiang Cao Date: Tue, 5 Sep 2023 14:44:00 -0700 Subject: [PATCH 06/12] refactor: use better package name --- key-attestation/java-example/README.md | 2 +- key-attestation/java-example/pom.xml | 4 ++-- .../Common.java | 2 +- .../KeyAttestationStatementVerifyException.java | 2 +- .../Verify.java | 14 ++++++-------- .../certchecker/CertChecker.java | 8 ++++---- .../DsmKeyAttestationAuthorityCertChecker.java | 12 ++++++------ .../certchecker/FortanixRootCertChecker.java | 8 ++++---- .../certchecker/KeyAttestationCaCertChecker.java | 8 ++++---- .../KeyAttestationStatementCertChecker.java | 8 ++++---- .../package-info.java | 6 ++++++ .../types/asn1}/ClusterNodeEnrollmentPolicy.java | 4 ++-- .../types/asn1}/KeyUsage.java | 4 ++-- .../types/asn1}/NodeEnrollmentPolicyItem.java | 2 +- .../types/json/KeyAttestationResponse.java | 5 +++++ .../types/json/KeyAttestationStatement.java | 5 +++++ .../types/json/KeyAttestationStatementFormat.java | 5 +++++ .../VerifyTest.java | 2 +- .../package-info.java | 6 ++++++ 19 files changed, 66 insertions(+), 41 deletions(-) rename key-attestation/java-example/src/main/java/com/fortanix/{key_attestation_statement_verification => keyattestationstatementverifier}/Common.java (99%) rename key-attestation/java-example/src/main/java/com/fortanix/{key_attestation_statement_verification => keyattestationstatementverifier}/KeyAttestationStatementVerifyException.java (73%) rename key-attestation/java-example/src/main/java/com/fortanix/{key_attestation_statement_verification => keyattestationstatementverifier}/Verify.java (95%) rename key-attestation/java-example/src/main/java/com/fortanix/{key_attestation_statement_verification => keyattestationstatementverifier}/certchecker/CertChecker.java (97%) rename key-attestation/java-example/src/main/java/com/fortanix/{key_attestation_statement_verification => keyattestationstatementverifier}/certchecker/DsmKeyAttestationAuthorityCertChecker.java (94%) rename key-attestation/java-example/src/main/java/com/fortanix/{key_attestation_statement_verification => keyattestationstatementverifier}/certchecker/FortanixRootCertChecker.java (93%) rename key-attestation/java-example/src/main/java/com/fortanix/{key_attestation_statement_verification => keyattestationstatementverifier}/certchecker/KeyAttestationCaCertChecker.java (94%) rename key-attestation/java-example/src/main/java/com/fortanix/{key_attestation_statement_verification => keyattestationstatementverifier}/certchecker/KeyAttestationStatementCertChecker.java (94%) create mode 100644 key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/package-info.java rename key-attestation/java-example/src/main/java/com/fortanix/{key_attestation_statement_verification/types => keyattestationstatementverifier/types/asn1}/ClusterNodeEnrollmentPolicy.java (96%) rename key-attestation/java-example/src/main/java/com/fortanix/{key_attestation_statement_verification/types => keyattestationstatementverifier/types/asn1}/KeyUsage.java (92%) rename key-attestation/java-example/src/main/java/com/fortanix/{key_attestation_statement_verification/types => keyattestationstatementverifier/types/asn1}/NodeEnrollmentPolicyItem.java (97%) create mode 100644 key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationResponse.java create mode 100644 key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatement.java create mode 100644 key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatementFormat.java rename key-attestation/java-example/src/test/java/com/fortanix/{key_attestation_statement_verification => keyattestationstatementverifier}/VerifyTest.java (97%) create mode 100644 key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/package-info.java diff --git a/key-attestation/java-example/README.md b/key-attestation/java-example/README.md index 66a41e3..90c5cde 100644 --- a/key-attestation/java-example/README.md +++ b/key-attestation/java-example/README.md @@ -12,7 +12,7 @@ This is a example java of how to verify **Fortanix DSM Key Attestation Statement ## Explanation -The test code under [VerifyTest.java](src/test/java/com/fortanix/key_attestation_statement_verification/VerifyTest.java) +The test code under [VerifyTest.java](src/test/java/com/fortanix/keyattestationstatementverifier/VerifyTest.java) shows how to properly verify the **Fortanix DSM Key Attestation Statement** certificate: - `verifyStatementWithoutCrlCheck` for offline verification - `verifyStatementFullCheck` for online verification diff --git a/key-attestation/java-example/pom.xml b/key-attestation/java-example/pom.xml index 3593dd4..2c26587 100644 --- a/key-attestation/java-example/pom.xml +++ b/key-attestation/java-example/pom.xml @@ -2,8 +2,8 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 - com.fortanix.key_attestation_statement_verification - key-attestation-statement-verification + com.fortanix.keyattestationstatementverifier + key-attestation-statement-verifier 0.0.1 1.8 diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Common.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Common.java similarity index 99% rename from key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Common.java rename to key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Common.java index 73417aa..aae22bc 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Common.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Common.java @@ -1,4 +1,4 @@ -package com.fortanix.key_attestation_statement_verification; +package com.fortanix.keyattestationstatementverifier; import java.io.BufferedReader; import java.io.InputStreamReader; diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/KeyAttestationStatementVerifyException.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/KeyAttestationStatementVerifyException.java similarity index 73% rename from key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/KeyAttestationStatementVerifyException.java rename to key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/KeyAttestationStatementVerifyException.java index e583c3c..86e14a2 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/KeyAttestationStatementVerifyException.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/KeyAttestationStatementVerifyException.java @@ -1,4 +1,4 @@ -package com.fortanix.key_attestation_statement_verification; +package com.fortanix.keyattestationstatementverifier; public class KeyAttestationStatementVerifyException extends Exception { public KeyAttestationStatementVerifyException(String msg) { diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Verify.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java similarity index 95% rename from key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Verify.java rename to key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java index 18d3c0d..4eb88db 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/Verify.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java @@ -1,5 +1,10 @@ -package com.fortanix.key_attestation_statement_verification; +package com.fortanix.keyattestationstatementverifier; +import com.fortanix.keyattestationstatementverifier.certchecker.CertChecker; +import com.fortanix.keyattestationstatementverifier.certchecker.DsmKeyAttestationAuthorityCertChecker; +import com.fortanix.keyattestationstatementverifier.certchecker.FortanixRootCertChecker; +import com.fortanix.keyattestationstatementverifier.certchecker.KeyAttestationCaCertChecker; +import com.fortanix.keyattestationstatementverifier.certchecker.KeyAttestationStatementCertChecker; import java.io.FileReader; import java.io.Reader; import java.security.PublicKey; @@ -16,18 +21,11 @@ import java.util.List; import java.util.Set; import java.util.logging.Logger; - import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.openssl.PEMParser; -import com.fortanix.key_attestation_statement_verification.certchecker.CertChecker; -import com.fortanix.key_attestation_statement_verification.certchecker.DsmKeyAttestationAuthorityCertChecker; -import com.fortanix.key_attestation_statement_verification.certchecker.FortanixRootCertChecker; -import com.fortanix.key_attestation_statement_verification.certchecker.KeyAttestationCaCertChecker; -import com.fortanix.key_attestation_statement_verification.certchecker.KeyAttestationStatementCertChecker; - public final class Verify { private static final Logger LOGGER = Logger.getLogger(Verify.class.getName()); diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/CertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/CertChecker.java similarity index 97% rename from key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/CertChecker.java rename to key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/CertChecker.java index c34a1c3..71719dd 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/CertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/CertChecker.java @@ -1,4 +1,4 @@ -package com.fortanix.key_attestation_statement_verification.certchecker; +package com.fortanix.keyattestationstatementverifier.certchecker; import java.security.MessageDigest; import java.security.cert.X509Certificate; @@ -21,9 +21,9 @@ import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; -import com.fortanix.key_attestation_statement_verification.Common; -import com.fortanix.key_attestation_statement_verification.KeyAttestationStatementVerifyException; -import com.fortanix.key_attestation_statement_verification.types.ClusterNodeEnrollmentPolicy; +import com.fortanix.keyattestationstatementverifier.Common; +import com.fortanix.keyattestationstatementverifier.KeyAttestationStatementVerifyException; +import com.fortanix.keyattestationstatementverifier.types.asn1.ClusterNodeEnrollmentPolicy; /** * This abstract class represents custom certificate checker diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/DsmKeyAttestationAuthorityCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/DsmKeyAttestationAuthorityCertChecker.java similarity index 94% rename from key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/DsmKeyAttestationAuthorityCertChecker.java rename to key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/DsmKeyAttestationAuthorityCertChecker.java index 13c2773..947b0a4 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/DsmKeyAttestationAuthorityCertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/DsmKeyAttestationAuthorityCertChecker.java @@ -1,4 +1,4 @@ -package com.fortanix.key_attestation_statement_verification.certchecker; +package com.fortanix.keyattestationstatementverifier.certchecker; import java.security.PublicKey; import java.security.cert.X509Certificate; @@ -12,11 +12,11 @@ import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; -import com.fortanix.key_attestation_statement_verification.Common; -import com.fortanix.key_attestation_statement_verification.KeyAttestationStatementVerifyException; -import com.fortanix.key_attestation_statement_verification.types.ClusterNodeEnrollmentPolicy; -import com.fortanix.key_attestation_statement_verification.types.KeyUsage; -import com.fortanix.key_attestation_statement_verification.types.NodeEnrollmentPolicyItem; +import com.fortanix.keyattestationstatementverifier.Common; +import com.fortanix.keyattestationstatementverifier.KeyAttestationStatementVerifyException; +import com.fortanix.keyattestationstatementverifier.types.asn1.ClusterNodeEnrollmentPolicy; +import com.fortanix.keyattestationstatementverifier.types.asn1.KeyUsage; +import com.fortanix.keyattestationstatementverifier.types.asn1.NodeEnrollmentPolicyItem; public class DsmKeyAttestationAuthorityCertChecker extends CertChecker { private static final Logger LOGGER = Logger.getLogger(DsmKeyAttestationAuthorityCertChecker.class.getName()); diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/FortanixRootCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/FortanixRootCertChecker.java similarity index 93% rename from key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/FortanixRootCertChecker.java rename to key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/FortanixRootCertChecker.java index 8893eda..af4cb78 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/FortanixRootCertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/FortanixRootCertChecker.java @@ -1,4 +1,4 @@ -package com.fortanix.key_attestation_statement_verification.certchecker; +package com.fortanix.keyattestationstatementverifier.certchecker; import java.security.PublicKey; import java.security.cert.X509Certificate; @@ -9,9 +9,9 @@ import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; -import com.fortanix.key_attestation_statement_verification.Common; -import com.fortanix.key_attestation_statement_verification.KeyAttestationStatementVerifyException; -import com.fortanix.key_attestation_statement_verification.types.KeyUsage; +import com.fortanix.keyattestationstatementverifier.Common; +import com.fortanix.keyattestationstatementverifier.KeyAttestationStatementVerifyException; +import com.fortanix.keyattestationstatementverifier.types.asn1.KeyUsage; public class FortanixRootCertChecker extends CertChecker { private static final Logger LOGGER = Logger.getLogger(FortanixRootCertChecker.class.getName()); diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationCaCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationCaCertChecker.java similarity index 94% rename from key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationCaCertChecker.java rename to key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationCaCertChecker.java index 4be9a36..6015e5e 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationCaCertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationCaCertChecker.java @@ -1,4 +1,4 @@ -package com.fortanix.key_attestation_statement_verification.certchecker; +package com.fortanix.keyattestationstatementverifier.certchecker; import java.security.PublicKey; import java.security.cert.X509Certificate; @@ -11,9 +11,9 @@ import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; -import com.fortanix.key_attestation_statement_verification.Common; -import com.fortanix.key_attestation_statement_verification.KeyAttestationStatementVerifyException; -import com.fortanix.key_attestation_statement_verification.types.KeyUsage; +import com.fortanix.keyattestationstatementverifier.Common; +import com.fortanix.keyattestationstatementverifier.KeyAttestationStatementVerifyException; +import com.fortanix.keyattestationstatementverifier.types.asn1.KeyUsage; public class KeyAttestationCaCertChecker extends CertChecker { private static final Logger LOGGER = Logger.getLogger(KeyAttestationCaCertChecker.class.getName()); diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationStatementCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationStatementCertChecker.java similarity index 94% rename from key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationStatementCertChecker.java rename to key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationStatementCertChecker.java index c3a67a1..9923402 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/certchecker/KeyAttestationStatementCertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationStatementCertChecker.java @@ -1,4 +1,4 @@ -package com.fortanix.key_attestation_statement_verification.certchecker; +package com.fortanix.keyattestationstatementverifier.certchecker; import java.security.PublicKey; import java.security.cert.X509Certificate; @@ -12,9 +12,9 @@ import org.bouncycastle.cert.X509CertificateHolder; import org.bouncycastle.cert.jcajce.JcaX509CertificateHolder; -import com.fortanix.key_attestation_statement_verification.Common; -import com.fortanix.key_attestation_statement_verification.KeyAttestationStatementVerifyException; -import com.fortanix.key_attestation_statement_verification.types.KeyUsage; +import com.fortanix.keyattestationstatementverifier.Common; +import com.fortanix.keyattestationstatementverifier.KeyAttestationStatementVerifyException; +import com.fortanix.keyattestationstatementverifier.types.asn1.KeyUsage; public class KeyAttestationStatementCertChecker extends CertChecker { private static final Logger LOGGER = Logger.getLogger(KeyAttestationStatementCertChecker.class.getName()); diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/package-info.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/package-info.java new file mode 100644 index 0000000..da47630 --- /dev/null +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/package-info.java @@ -0,0 +1,6 @@ +/** + * This module is a example for showing how to verify Fortanix Key Attestation + * Statement. + * + */ +package com.fortanix.keyattestationstatementverifier; diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/ClusterNodeEnrollmentPolicy.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/ClusterNodeEnrollmentPolicy.java similarity index 96% rename from key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/ClusterNodeEnrollmentPolicy.java rename to key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/ClusterNodeEnrollmentPolicy.java index a83a428..5519a5c 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/ClusterNodeEnrollmentPolicy.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/ClusterNodeEnrollmentPolicy.java @@ -1,9 +1,9 @@ -package com.fortanix.key_attestation_statement_verification.types; +package com.fortanix.keyattestationstatementverifier.types.asn1; import org.bouncycastle.asn1.*; import org.bouncycastle.asn1.x509.Extensions; -import com.fortanix.key_attestation_statement_verification.Common; +import com.fortanix.keyattestationstatementverifier.Common; /** * Java class for representing Fortanix defined ASN1 type: diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/KeyUsage.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/KeyUsage.java similarity index 92% rename from key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/KeyUsage.java rename to key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/KeyUsage.java index 99d9ad4..50c4321 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/KeyUsage.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/KeyUsage.java @@ -1,6 +1,6 @@ -package com.fortanix.key_attestation_statement_verification.types; +package com.fortanix.keyattestationstatementverifier.types.asn1; -import com.fortanix.key_attestation_statement_verification.KeyAttestationStatementVerifyException; +import com.fortanix.keyattestationstatementverifier.KeyAttestationStatementVerifyException; /** * The helper type for checking X509 KeyUsage extension diff --git a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/NodeEnrollmentPolicyItem.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/NodeEnrollmentPolicyItem.java similarity index 97% rename from key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/NodeEnrollmentPolicyItem.java rename to key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/NodeEnrollmentPolicyItem.java index f0d1514..9f3fedf 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/key_attestation_statement_verification/types/NodeEnrollmentPolicyItem.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/NodeEnrollmentPolicyItem.java @@ -1,4 +1,4 @@ -package com.fortanix.key_attestation_statement_verification.types; +package com.fortanix.keyattestationstatementverifier.types.asn1; import org.bouncycastle.asn1.*; diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationResponse.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationResponse.java new file mode 100644 index 0000000..fc4569e --- /dev/null +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationResponse.java @@ -0,0 +1,5 @@ +package com.fortanix.keyattestationstatementverifier.types.json; + +public class KeyAttestationResponse { + +} diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatement.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatement.java new file mode 100644 index 0000000..ab6d845 --- /dev/null +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatement.java @@ -0,0 +1,5 @@ +package com.fortanix.keyattestationstatementverifier.types.json; + +public class KeyAttestationStatement { + +} diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatementFormat.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatementFormat.java new file mode 100644 index 0000000..20046fa --- /dev/null +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatementFormat.java @@ -0,0 +1,5 @@ +package com.fortanix.keyattestationstatementverifier.types.json; + +public class KeyAttestationStatementFormat { + +} diff --git a/key-attestation/java-example/src/test/java/com/fortanix/key_attestation_statement_verification/VerifyTest.java b/key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/VerifyTest.java similarity index 97% rename from key-attestation/java-example/src/test/java/com/fortanix/key_attestation_statement_verification/VerifyTest.java rename to key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/VerifyTest.java index 05f91a1..c8dc3a8 100644 --- a/key-attestation/java-example/src/test/java/com/fortanix/key_attestation_statement_verification/VerifyTest.java +++ b/key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/VerifyTest.java @@ -1,4 +1,4 @@ -package com.fortanix.key_attestation_statement_verification; +package com.fortanix.keyattestationstatementverifier; import org.junit.Ignore; import org.junit.Test; diff --git a/key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/package-info.java b/key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/package-info.java new file mode 100644 index 0000000..694112b --- /dev/null +++ b/key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/package-info.java @@ -0,0 +1,6 @@ +/** + * This module is a example for showing how to verify Fortanix Key Attestation + * Statement through testing. + * + */ +package com.fortanix.keyattestationstatementverifier; From cda6c69edb6eed99120e65608b1652442a2c73f8 Mon Sep 17 00:00:00 2001 From: Yuxiang Cao Date: Tue, 5 Sep 2023 15:51:42 -0700 Subject: [PATCH 07/12] feat: add functionality to decode and verify json data --- key-attestation/java-example/README.md | 6 +- key-attestation/java-example/pom.xml | 15 ++++ .../Verify.java | 67 +++++++++++++++- .../types/json/KeyAttestationResponse.java | 76 ++++++++++++++++++- .../types/json/KeyAttestationStatement.java | 75 +++++++++++++++++- .../json/KeyAttestationStatementFormat.java | 11 ++- .../JsonTest.java | 43 +++++++++++ .../VerifyTest.java | 64 ++++++++++++---- .../package-info.java | 6 -- .../resources/key-attestation-response.json | 11 +++ 10 files changed, 344 insertions(+), 30 deletions(-) create mode 100644 key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/JsonTest.java delete mode 100644 key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/package-info.java create mode 100644 key-attestation/java-example/src/test/resources/key-attestation-response.json diff --git a/key-attestation/java-example/README.md b/key-attestation/java-example/README.md index 90c5cde..e49b890 100644 --- a/key-attestation/java-example/README.md +++ b/key-attestation/java-example/README.md @@ -14,8 +14,10 @@ This is a example java of how to verify **Fortanix DSM Key Attestation Statement The test code under [VerifyTest.java](src/test/java/com/fortanix/keyattestationstatementverifier/VerifyTest.java) shows how to properly verify the **Fortanix DSM Key Attestation Statement** certificate: -- `verifyStatementWithoutCrlCheck` for offline verification -- `verifyStatementFullCheck` for online verification + +- `verifyStatementFromJsonWithoutCrlCheck`: Verify given `KeyAttestationResponse` in a JSON file, assuming the last certificate in authority chain is correct ROOT certificate and skipping CRL checks. +- `verifyStatementFullCheck`: Verify given `KeyAttestationResponse` in a JSON file, the `Fortanix Attestation and Provisioning Root CA` is downloaded from https://pki.fortanix.com in runtime. +- `verifyStatementFromPemWithoutCrlCheck`: Verify given statement and authority chain in a PEM file, the `Fortanix Attestation and Provisioning Root CA` is downloaded from https://pki.fortanix.com in runtime. # License diff --git a/key-attestation/java-example/pom.xml b/key-attestation/java-example/pom.xml index 2c26587..33fbc46 100644 --- a/key-attestation/java-example/pom.xml +++ b/key-attestation/java-example/pom.xml @@ -27,6 +27,21 @@ ${junit.version} test + + com.fasterxml.jackson.core + jackson-core + 2.15.2 + + + com.fasterxml.jackson.core + jackson-annotations + 2.15.2 + + + com.fasterxml.jackson.core + jackson-databind + 2.15.2 + diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java index 4eb88db..2ee7248 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java @@ -5,8 +5,12 @@ import com.fortanix.keyattestationstatementverifier.certchecker.FortanixRootCertChecker; import com.fortanix.keyattestationstatementverifier.certchecker.KeyAttestationCaCertChecker; import com.fortanix.keyattestationstatementverifier.certchecker.KeyAttestationStatementCertChecker; +import com.fortanix.keyattestationstatementverifier.types.json.KeyAttestationResponse; + +import java.io.ByteArrayInputStream; import java.io.FileReader; import java.io.Reader; +import java.io.StringReader; import java.security.PublicKey; import java.security.Security; import java.security.cert.CertPath; @@ -17,6 +21,7 @@ import java.security.cert.TrustAnchor; import java.security.cert.X509Certificate; import java.util.ArrayList; +import java.util.Base64; import java.util.Collections; import java.util.List; import java.util.Set; @@ -33,6 +38,34 @@ public final class Verify { Security.addProvider(new BouncyCastleProvider()); } + /** + * Verify given `KeyAttestationResponse` by using `trustRootCa` + * + * @param keyAttestationResponse Json object in format of + * `KeyAttestationResponse`, it should contains + * base64 encoded Authority Certificate chain and + * Attestation Statement + * @param trustRootCa Trusted root CA, you need to get the + * certificate + * from Fortanix PKI website + * @param verifyCrl If check the CRL, need network access + * @throws Exception + */ + public static void verify(KeyAttestationResponse keyAttestationResponse, + X509Certificate trustRootCa, boolean verifyCrl) throws Exception { + LOGGER.info(String.format("Verifying KeyAttestationResponse: %s", keyAttestationResponse.toString())); + // skip verifying attestationStatement.format since it's been covered by json + // decoding + String attestationStatementStr = keyAttestationResponse.getAttestationStatement().getStatement(); + List authorityChain = keyAttestationResponse.getAuthorityChain(); + LOGGER.info( + String.format("Decoding Attestation Statement Certificate: %s", attestationStatementStr.toString())); + X509Certificate attestationStatementCert = readBase64EncodedCertificate(attestationStatementStr); + LOGGER.info(String.format("Decoding Attestation Statement Certificate: %s", authorityChain.toString())); + List authorityChainCerts = readBase64EncodedCertificates(authorityChain); + verify(authorityChainCerts, attestationStatementCert, trustRootCa, verifyCrl); + } + /** * Verify given `attestationStatement`, `authorityChain` by using `trustRootCa` * @@ -177,7 +210,7 @@ public static List readPemCertsFromReader(Reader reader) throws pemParser.close(); } if (certChain.isEmpty()) { - throw new KeyAttestationStatementVerifyException("No valid Certificate in given file"); + throw new KeyAttestationStatementVerifyException("No valid Certificate in given reader"); } return convertX509CertificateHolders(certChain); } @@ -238,4 +271,36 @@ public static void verify_cert_signature(X509Certificate child, X509Certificate PublicKey parentPublicKey = parent.getPublicKey(); child.verify(parentPublicKey); } + + /** + * Helper function to decode base64 encoded x509 certificate into + * X509Certificate + * + * @param base64Certificate Source base64 string + * @return + * @throws Exception + */ + public static X509Certificate readBase64EncodedCertificate(String base64Certificate) throws Exception { + byte[] certificateBytes = Base64.getDecoder().decode(base64Certificate); + + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes)); + } + + /** + * Helper function to decode base64 encoded list of x509 certificate into list + * of X509Certificate + * + * @param base64CertificateList Source base64 string list + * @return + * @throws Exception + */ + public static List readBase64EncodedCertificates(List base64CertificateList) + throws Exception { + List chain = new ArrayList<>(); + for (String certStr : base64CertificateList) { + chain.add(readBase64EncodedCertificate(certStr)); + } + return chain; + } } diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationResponse.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationResponse.java index fc4569e..4198c5b 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationResponse.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationResponse.java @@ -1,5 +1,79 @@ package com.fortanix.keyattestationstatementverifier.types.json; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.List; + public class KeyAttestationResponse { - + + /** + * The DER-encoded certificate chain for the authority issuing the key + * attestation statement, encoded in Base64 String. + */ + @JsonProperty("authority_chain") + private List authorityChain; // Blob as + + /** + * The key attestation statement. + */ + @JsonProperty("attestation_statement") + private KeyAttestationStatement attestationStatement; + + public KeyAttestationResponse() { + } + + public List getAuthorityChain() { + return authorityChain; + } + + public void setAuthorityChain(List authorityChain) { + this.authorityChain = authorityChain; + } + + public KeyAttestationResponse(List authorityChain, KeyAttestationStatement attestationStatement) { + this.authorityChain = authorityChain; + this.attestationStatement = attestationStatement; + } + + public KeyAttestationStatement getAttestationStatement() { + return attestationStatement; + } + + public void setAttestationStatement(KeyAttestationStatement attestationStatement) { + this.attestationStatement = attestationStatement; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + KeyAttestationResponse other = (KeyAttestationResponse) obj; + if (authorityChain == null) { + if (other.authorityChain != null) + return false; + } else if (!authorityChain.equals(other.authorityChain)) + return false; + if (attestationStatement == null) { + if (other.attestationStatement != null) + return false; + } else if (!attestationStatement.equals(other.attestationStatement)) + return false; + return true; + } + + @Override + public String toString() { + ObjectMapper objectMapper = new ObjectMapper(); + try { + return objectMapper.writeValueAsString(this); + } catch (JsonProcessingException e) { + e.printStackTrace(); + return super.toString(); + } + } } diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatement.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatement.java index ab6d845..e572150 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatement.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatement.java @@ -1,5 +1,76 @@ package com.fortanix.keyattestationstatementverifier.types.json; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + public class KeyAttestationStatement { - -} + + /** + * The format of the `statement` field. + */ + @JsonProperty("format") + private KeyAttestationStatementFormat format; + + /** + * The key attestation statement formatted according to `format`, encoded in + * Base64 String. + */ + @JsonProperty("statement") + private String statement; // Blob as + + public KeyAttestationStatement() { + } + + public KeyAttestationStatement(KeyAttestationStatementFormat format, String statement) { + this.format = format; + this.statement = statement; + } + + public KeyAttestationStatementFormat getFormat() { + return format; + } + + public void setFormat(KeyAttestationStatementFormat format) { + this.format = format; + } + + public String getStatement() { + return statement; + } + + public void setStatement(String statement) { + this.statement = statement; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + KeyAttestationStatement other = (KeyAttestationStatement) obj; + if (format != other.format) + return false; + if (statement == null) { + if (other.statement != null) + return false; + } else if (!statement.equals(other.statement)) + return false; + return true; + } + + @Override + public String toString() { + ObjectMapper objectMapper = new ObjectMapper(); + try { + return objectMapper.writeValueAsString(this); + } catch (JsonProcessingException e) { + e.printStackTrace(); + return super.toString(); + } + } + +} \ No newline at end of file diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatementFormat.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatementFormat.java index 20046fa..45cd724 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatementFormat.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatementFormat.java @@ -1,5 +1,12 @@ package com.fortanix.keyattestationstatementverifier.types.json; -public class KeyAttestationStatementFormat { - +import com.fasterxml.jackson.annotation.JsonProperty; + +public enum KeyAttestationStatementFormat { + + /** + * The attestation statement is formatted as a DER-encoded X.509 certificate. + */ + @JsonProperty("x509_certificate") + X509_CERTIFICATE } diff --git a/key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/JsonTest.java b/key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/JsonTest.java new file mode 100644 index 0000000..3bf3d4e --- /dev/null +++ b/key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/JsonTest.java @@ -0,0 +1,43 @@ +package com.fortanix.keyattestationstatementverifier; + +import org.junit.Test; + +import com.fortanix.keyattestationstatementverifier.types.json.KeyAttestationResponse; +import com.fortanix.keyattestationstatementverifier.types.json.KeyAttestationStatement; +import com.fortanix.keyattestationstatementverifier.types.json.KeyAttestationStatementFormat; +import com.fasterxml.jackson.databind.ObjectMapper; + +import static org.junit.Assert.*; + +import java.util.Arrays; +import java.util.List; + +public class JsonTest { + private final ObjectMapper objectMapper = new ObjectMapper(); + + @Test + public void testKeyAttestationResponseJsonEncodingDecoding() throws Exception { + // Create sample data + List authorityChain = Arrays.asList("certChain1", "certChain2"); + String statementString = "statement1"; + KeyAttestationStatement keyAttestationStatement = new KeyAttestationStatement( + KeyAttestationStatementFormat.X509_CERTIFICATE, statementString); + + // Encode to JSON + KeyAttestationResponse response = new KeyAttestationResponse(authorityChain, keyAttestationStatement); + String jsonString = objectMapper.writeValueAsString(response); + + // Expected JSON + String expectedJson = "{\"authority_chain\":[\"certChain1\",\"certChain2\"],\"attestation_statement\":{\"format\":\"x509_certificate\",\"statement\":\"statement1\"}}"; + + // Assert that the encoded JSON string matches the expected JSON + assertEquals(expectedJson, jsonString); + + // Decode from JSON + KeyAttestationResponse decodedResponse = objectMapper.readValue(jsonString, KeyAttestationResponse.class); + + // Assert that the original and decoded objects are equal + assertEquals(response.getAuthorityChain(), decodedResponse.getAuthorityChain()); + assertEquals(response.getAttestationStatement(), decodedResponse.getAttestationStatement()); + } +} diff --git a/key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/VerifyTest.java b/key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/VerifyTest.java index c8dc3a8..17b92e4 100644 --- a/key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/VerifyTest.java +++ b/key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/VerifyTest.java @@ -2,14 +2,21 @@ import org.junit.Ignore; import org.junit.Test; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fortanix.keyattestationstatementverifier.types.json.KeyAttestationResponse; + import static org.junit.Assert.*; +import java.io.FileReader; +import java.io.Reader; import java.net.URL; import java.security.cert.X509Certificate; import java.util.List; public class VerifyTest { private static final String VALID_STATEMENT_CERT_PEM = "key-attestation-statement.pem"; + private static final String VALID_RESPONSE_JSON = "key-attestation-response.json"; private URL getTestFileUrl(String fileName) throws Exception { URL resUrl = getClass().getClassLoader().getResource(fileName); @@ -22,27 +29,57 @@ private URL getTestFileUrl(String fileName) throws Exception { /** * This test tests the verification logic expect CRL verification and Root CA - * download + * download, reading test data from a PEM file * * @throws Exception */ @Test - public void verifyStatementWithoutCrlCheck() throws Exception { + public void verifyStatementFromPemWithoutCrlCheck() throws Exception { + // Note, the certificate in the file is in order of: + // 1. Fortanix DSM Key Attestation + // 2. Fortanix DSM SaaS Key Attestation Authority + // 3. Fortanix Key Attestation CA + // 4. Fortanix Attestation and Provisioning Root CA URL url = getTestFileUrl(VALID_STATEMENT_CERT_PEM); List cert_chain = Verify.readPemCertsFromPath(url.getPath()); assertEquals(4, cert_chain.size()); List authorityChain = cert_chain.subList(1, cert_chain.size()); - // Last certificate is Root CA cert, since the test certificate is using a fake - // root CA, so we assume root ca cert is correct by using last certificate as - // trust CA certificate + // Last certificate of Authority Chain is Root CA cert, since the test + // certificate is using a fake root CA, so we assume root ca cert is correct by + // using last certificate as trust CA certificate. // NOTE: please replace with Root CA certificate if you already downloaded it - // somewhere + // somewhere. X509Certificate trusted = cert_chain.get(cert_chain.size() - 1); // because at time this code is written, CRL server is not setup, we turn of the // CRL check Verify.verify(authorityChain, cert_chain.get(0), trusted, false); } + /** + * This test tests the verification logic expect CRL verification and Root CA + * downloading, reading test data from a Json file storing a + * KeyAttestationResponse + * + * @throws Exception + */ + @Test + public void verifyStatementFromJsonWithoutCrlCheck() throws Exception { + URL url = getTestFileUrl(VALID_RESPONSE_JSON); + Reader reader = new FileReader(url.getPath()); + ObjectMapper objectMapper = new ObjectMapper(); + KeyAttestationResponse decodedResponse = objectMapper.readValue(reader, KeyAttestationResponse.class); + // Last certificate of Authority Chain is Root CA cert, since the test + // certificate is using a fake root CA, so we assume root ca cert is correct by + // using last certificate as trust CA certificate. + // NOTE: please replace with Root CA certificate if you already downloaded it + // somewhere. + List authorityChain = decodedResponse.getAuthorityChain(); + X509Certificate trusted = Verify.readBase64EncodedCertificate(authorityChain.get(authorityChain.size() - 1)); + // because at time this code is written, CRL server is not setup, we turn of the + // CRL check + Verify.verify(decodedResponse, trusted, false); + } + /** * This test is ignored because it's an example code for showing how to verify a * real 'Fortanix DSM Key Attestation' @@ -52,21 +89,16 @@ public void verifyStatementWithoutCrlCheck() throws Exception { @Ignore @Test public void verifyStatementFullCheck() throws Exception { - // Note, the certificate in the file should be in order of: - // 1. Fortanix DSM Key Attestation - // 2. Fortanix DSM SaaS Key Attestation Authority - // 3. Fortanix Key Attestation CA - // 4. Fortanix Attestation and Provisioning Root CA - String certChainPath = "Path to the certificate chain file"; - List cert_chain = Verify.readPemCertsFromPath(certChainPath); - assertEquals(4, cert_chain.size()); - List authorityChain = cert_chain.subList(1, cert_chain.size()); + String jsonPath = "Path to the KeyAttestationResponse json file"; + Reader reader = new FileReader(jsonPath); + ObjectMapper objectMapper = new ObjectMapper(); + KeyAttestationResponse decodedResponse = objectMapper.readValue(reader, KeyAttestationResponse.class); System.out.println("Downloading Fortanix Attestation and Provisioning Root CA certificate form: " + Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CERT_URL); X509Certificate trustedRootCert = Common.getFortanixRootCaCertRemote( Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CERT_URL); - Verify.verify(authorityChain, cert_chain.get(0), trustedRootCert, true); + Verify.verify(decodedResponse, trustedRootCert, true); } } diff --git a/key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/package-info.java b/key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/package-info.java deleted file mode 100644 index 694112b..0000000 --- a/key-attestation/java-example/src/test/java/com/fortanix/keyattestationstatementverifier/package-info.java +++ /dev/null @@ -1,6 +0,0 @@ -/** - * This module is a example for showing how to verify Fortanix Key Attestation - * Statement through testing. - * - */ -package com.fortanix.keyattestationstatementverifier; diff --git a/key-attestation/java-example/src/test/resources/key-attestation-response.json b/key-attestation/java-example/src/test/resources/key-attestation-response.json new file mode 100644 index 0000000..e332979 --- /dev/null +++ b/key-attestation/java-example/src/test/resources/key-attestation-response.json @@ -0,0 +1,11 @@ +{ + "authority_chain": [ + "MIIF3DCCA8SgAwIBAgIUQkEZAtXgNJBW1Z8ayC/xC/00ar8wDQYJKoZIhvcNAQELBQAwdzELMAkGA1UEBgwCVVMxEzARBgNVBAgMCkNhbGlmb3JuaWExFDASBgNVBAcMC1NhbnRhIENsYXJhMRcwFQYDVQQKDA5Gb3J0YW5peCwgSW5jLjEkMCIGA1UEAwwbRm9ydGFuaXggS2V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H5gy/Zv8zDTe/1Zj+KY7Q+BiTJSrUsi8y1M3loePYwO4bWZbnVR6+PzZTPDhR45m9wTsAcrQTNSZn3khxJ6pMcFsGucM8oyVYwOtBB3QZOmI3D0SkITtAnkcunT9sD8nCO8Bw0BOkYKOJBIWBSWuruRCrZDxIbjgeykcAAPj47nPpoAYmI5vwF8LkLJNchugoUHmw3aC7/rJtJoP2AlLMe3aK7f7o8Y+jZZPEBcD37iu5TNekU17WlH+Q22n5/4hGYGGMQ5uK2971wifIc3QqvUczB/3cu8BTLFlAxCxic359Rb6u5AS5RJE7sYKIEeS4TnykL05RW11u1A/mkVsuBaOYHEeAN28Hz4xMffoWtPTM1oCfEAv7eYH/ZdJ75xeLVJjEyY2/55NKoAIMsK91iPwWHE7DZSQMAuRLtrYtrkyHHNBRGru2ikdpvy1g9qajKqHV7Dnp9sTMixqq15OgLnUKwmQffGfzhCbcSj9K1mkGO2nTSOAZJaDvfxWfyGypNrVAJI78/0/5zY+qkEivgh9xpnoAKHK4UT/cKhuLDCNQIEhB4fhnwhOuX1/1DFOz4Vdzshx2KL0eanblKF2i0ekR8tzv97a41mzM3Q/TXe0l9xVINzDynbePYHrsWBYyPcMCau5v4vFxobX+622kIrXllaU+gQ==" + ], + "attestation_statement": { + "format": "x509_certificate", + "statement": "MIID/zCCAmegAwIBAgIUCVQHdgKkQdO34cZVHfE5cO1rQwUwDQYJKoZIhvcNAQELBQAwNjE0MDIGA1UEAwwrRm9ydGFuaXggRFNNIFNhYVMgS2V5IEF0dGVzdGF0aW9uIEF1dGhvcml0eTAgFw0yMzA5MDEwMDM2MDZaGA85OTk5MTIzMTIzNTk1OVowXjElMCMGA1UEAwwcRm9ydGFuaXggRFNNIEtleSBBdHRlc3RhdGlvbjE1MDMGCysGAQQBg4QaAQICDCRiMmI4N2Y4NC04MGQyLTRjNGMtYmE0MS03ZmExMmZiNGVmZjUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDJnG/Pwu6ElZ7ySoMWwleMK0Z6fbKKUeqIuTGMSLfqoFVH+JeEVNSh1dYzpA18vm7/7kjc11CaABgzzA42tH8QUkq2atVFvUKIJcNhueuu1mMBeeujOarbeOTfypVtoj200ITgYdcCXuNMefNplvamEb6RbSPYMVfWxblNhZqTw8FFPHWIMNjoiNKOlXL7/uirMS8Av0saMhJ1dWXtX44F06tsOYIdkx2AogMmj+Op+uOt2RwMzMnofsitapREPGhr8nmJqK/i5jJSgt38NZs/hn1xwRXCnCj4OpMudjiK9q3+5EddTTYXXMukGRtQ2OIb3e9ViUncpTzyCZ1+VLyRAgMBAAGjWzBZMA4GA1UdDwEB/wQEAwIEsDASBgwrBgEEAYOEGgIEAQEEAjAAMBIGDCsGAQQBg4QaAgQBAgQCMAAwHwYDVR0jBBgwFoAUcm3RwDxhP/S92lTKe5ylkY0F2UkwDQYJKoZIhvcNAQELBQADggGBADVTH2Ur3FPkAxY4cquGtHJmixVqRtNks5xvf0KAq+Rps1Bq9Al46y/cbCZAD/bCS/8VqqQyMNswW0H5gM0v7Qi+lT8Ao4xQI1HqDbd3UYH1VKwrhqgWfdNkeLp/cC/3dEUX5XTH4hnu9kEoMCiEWwkbrmflqOlwGUM8O28B7DsFP/qi+2a66HSU1C2MAWYF52krNZ/HGTI2QRbGHsApVBOsFms1eGKsDhHq24bG/0VUMQZXVtT64wbmvowQbFybKWV2M3ncpAiSJ8z2XLm6IpXR3FmuonjznoCmJg39oqelzvydyk8rBpifPma5sYV+LEN8PAGfKs/+UxfIQqSZRth3EprBELR9YWkx0MKQ2LysPGII9GexZU17/ycpIYOamvHCCcX90X35TmPx2L5nSWXvN2u/XzsQdtteK8ZFLPYZR4jlwED4lWKjyWqr1nyMSfuw7A6LItEswLI0Pk+333fXHxAs3HHbKXsyuwx4MZ9XreAqX7WmVlaN8LNca7tuEA==" + } +} \ No newline at end of file From 2efce34590f717ad4c78cc34da21742809c831f9 Mon Sep 17 00:00:00 2001 From: Yuxiang Cao Date: Tue, 5 Sep 2023 17:20:52 -0700 Subject: [PATCH 08/12] chore: fix style and comments --- key-attestation/java-example/.gitignore | 2 +- key-attestation/java-example/pom.xml | 2 +- .../fortanix/keyattestationstatementverifier/Common.java | 8 ++------ .../fortanix/keyattestationstatementverifier/Verify.java | 6 +++--- .../certchecker/FortanixRootCertChecker.java | 2 +- .../certchecker/KeyAttestationCaCertChecker.java | 2 +- 6 files changed, 9 insertions(+), 13 deletions(-) diff --git a/key-attestation/java-example/.gitignore b/key-attestation/java-example/.gitignore index e94ed57..ad3cf01 100644 --- a/key-attestation/java-example/.gitignore +++ b/key-attestation/java-example/.gitignore @@ -16,4 +16,4 @@ buildNumber.properties # JDT-specific (Eclipse Java Development Tools) .classpath -/.vscode \ No newline at end of file +/.vscode diff --git a/key-attestation/java-example/pom.xml b/key-attestation/java-example/pom.xml index 33fbc46..fdd1d17 100644 --- a/key-attestation/java-example/pom.xml +++ b/key-attestation/java-example/pom.xml @@ -87,4 +87,4 @@ - \ No newline at end of file + diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Common.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Common.java index aae22bc..4f7647f 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Common.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Common.java @@ -95,19 +95,15 @@ private static X500Name buildX500Name(String c, String st, String l, String o, S if (!c.isEmpty()) { builder.addRDN(BCStyle.C, c); } - ; if (!st.isEmpty()) { builder.addRDN(BCStyle.ST, st); } - ; if (!l.isEmpty()) { builder.addRDN(BCStyle.L, l); } - ; if (!o.isEmpty()) { builder.addRDN(BCStyle.O, o); } - ; builder.addRDN(BCStyle.CN, cn); return builder.build(); @@ -174,10 +170,10 @@ private static boolean checkRDNsMatch(X500Name actual, X500Name expected, ASN1Ob public static void isValidCrlUrl(String urlString) throws Exception { URL url = new URL(urlString); if (!url.getProtocol().equals("https")) { - throw new KeyAttestationStatementVerifyException("invalid CRL URL: invalid domain"); + throw new KeyAttestationStatementVerifyException("invalid CRL URL: should be https"); } if (!url.getHost().equalsIgnoreCase(FORTANIX_PKI_DOMAIN)) { - throw new KeyAttestationStatementVerifyException("invalid CRL URL: should be https"); + throw new KeyAttestationStatementVerifyException("invalid CRL URL: invalid domain"); } if (!url.getPath().endsWith(".crl")) { throw new KeyAttestationStatementVerifyException("invalid CRL URL: should be end with '.crl'"); diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java index 2ee7248..270c965 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java @@ -69,7 +69,7 @@ public static void verify(KeyAttestationResponse keyAttestationResponse, /** * Verify given `attestationStatement`, `authorityChain` by using `trustRootCa` * - * @param authorityChain Certificate chain of all certificates expect + * @param authorityChain Certificate chain of all certificates except * `Fortanix Key Attestation Statement` certificate * @param attestationStatement `Fortanix Key Attestation Statement` certificate * @param trustRootCa Trusted root CA, you need to get the certificate @@ -87,10 +87,10 @@ public static void verify(List authorityChain, X509Certificate // it's parent try { verify_cert_chain_signature(authorityChain, trustRootCa, verifyCrl); - System.out.println("The signature in 'Fortanix DSM Key Attestation' certificate is valid."); + System.out.println("The signature in 'Fortanix DSM Key Attestation' certificate is invalid."); } catch (Exception e) { throw new KeyAttestationStatementVerifyException( - "The signature in 'Fortanix DSM Key Attestation' certificate is valid, " + e.toString()); + "The signature in 'Fortanix DSM Key Attestation' certificate is invalid, " + e.toString()); } LOGGER.info(String.format("Checking if '%s' certificate is correctly signed by '%s' certificate", Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, Common.KEY_ATTESTATION_STATEMENT_CN)); diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/FortanixRootCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/FortanixRootCertChecker.java index af4cb78..c60c70d 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/FortanixRootCertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/FortanixRootCertChecker.java @@ -59,7 +59,7 @@ private void check_public_key(X509Certificate cert) throws Exception { PublicKey rootPk = cert.getPublicKey(); if (rootPk instanceof RSAPublicKey) { RSAPublicKey rootRsaPk = (RSAPublicKey) rootPk; - assert (rootRsaPk.getModulus().bitLength() >= 3072); + assert (rootRsaPk.getModulus().bitLength() >= 4096); } else { throw new KeyAttestationStatementVerifyException( Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CN diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationCaCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationCaCertChecker.java index 6015e5e..2456a13 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationCaCertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationCaCertChecker.java @@ -62,7 +62,7 @@ private void check_public_key(X509Certificate cert) throws Exception { PublicKey caPk = cert.getPublicKey(); if (caPk instanceof RSAPublicKey) { RSAPublicKey caRsaPk = (RSAPublicKey) caPk; - assert (caRsaPk.getModulus().bitLength() >= 3072); + assert (caRsaPk.getModulus().bitLength() >= 4096); } else { throw new KeyAttestationStatementVerifyException( Common.FORTANIX_KEY_ATTESTATION_CA_CN + " certificate invalid public key type"); From 24a7050819bd11dbbfaba0007d613638644e7e86 Mon Sep 17 00:00:00 2001 From: Yuxiang Cao Date: Wed, 6 Sep 2023 13:24:46 -0700 Subject: [PATCH 09/12] style: fix some nit picks --- .../keyattestationstatementverifier/Verify.java | 17 ++++++++--------- .../DsmKeyAttestationAuthorityCertChecker.java | 4 ++-- .../KeyAttestationStatementCertChecker.java | 1 - .../types/asn1/KeyUsage.java | 2 +- .../types/asn1/NodeEnrollmentPolicyItem.java | 2 +- .../types/json/KeyAttestationStatement.java | 2 +- .../resources/key-attestation-response.json | 2 +- .../resources/key-attestation-statement.pem | 2 +- 8 files changed, 15 insertions(+), 17 deletions(-) diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java index 270c965..f8f9188 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java @@ -10,7 +10,6 @@ import java.io.ByteArrayInputStream; import java.io.FileReader; import java.io.Reader; -import java.io.StringReader; import java.security.PublicKey; import java.security.Security; import java.security.cert.CertPath; @@ -61,7 +60,7 @@ public static void verify(KeyAttestationResponse keyAttestationResponse, LOGGER.info( String.format("Decoding Attestation Statement Certificate: %s", attestationStatementStr.toString())); X509Certificate attestationStatementCert = readBase64EncodedCertificate(attestationStatementStr); - LOGGER.info(String.format("Decoding Attestation Statement Certificate: %s", authorityChain.toString())); + LOGGER.info(String.format("Decoding Authority Chain: %s", authorityChain.toString())); List authorityChainCerts = readBase64EncodedCertificates(authorityChain); verify(authorityChainCerts, attestationStatementCert, trustRootCa, verifyCrl); } @@ -81,23 +80,23 @@ public static void verify(List authorityChain, X509Certificate X509Certificate trustRootCa, boolean verifyCrl) throws Exception { checkAuthorityChainLength(authorityChain); + LOGGER.info(String.format("Checking if '%s' certificate is correctly signed by '%s' certificate", + Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, Common.KEY_ATTESTATION_STATEMENT_CN)); + // because 'Fortanix DSM SaaS Key Attestation Authority' is not a CA + // certificate, so we need to manually check 'Fortanix DSM Key Attestation' is + // correctly singed by 'Fortanix DSM SaaS Key Attestation Authority' certificate + verify_cert_signature(attestationStatement, authorityChain.get(0)); + LOGGER.info("Checking if root certificate in `authorityChain` matches given trusted root certificate"); check_root_cert_match(authorityChain.get(authorityChain.size() - 1), trustRootCa); // verify each signature on authority certificate chain is correctly signed by // it's parent try { verify_cert_chain_signature(authorityChain, trustRootCa, verifyCrl); - System.out.println("The signature in 'Fortanix DSM Key Attestation' certificate is invalid."); } catch (Exception e) { throw new KeyAttestationStatementVerifyException( "The signature in 'Fortanix DSM Key Attestation' certificate is invalid, " + e.toString()); } - LOGGER.info(String.format("Checking if '%s' certificate is correctly signed by '%s' certificate", - Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, Common.KEY_ATTESTATION_STATEMENT_CN)); - // because 'Fortanix DSM SaaS Key Attestation Authority' is not a CA - // certificate, so we need to manually check 'Fortanix DSM Key Attestation' is - // correctly singed by 'Fortanix DSM SaaS Key Attestation Authority' certificate - verify_cert_signature(attestationStatement, authorityChain.get(0)); CertChecker statementChecker = new KeyAttestationStatementCertChecker(); CertChecker authorityChecker = new DsmKeyAttestationAuthorityCertChecker(); diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/DsmKeyAttestationAuthorityCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/DsmKeyAttestationAuthorityCertChecker.java index 947b0a4..7ac9dc6 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/DsmKeyAttestationAuthorityCertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/DsmKeyAttestationAuthorityCertChecker.java @@ -140,7 +140,7 @@ private void check_extensions(X509Certificate cert, X509Certificate issuerCert) "%s certificate 'Cluster node enrollment policy' extension policy item 'Node enrollment policy item: Minimum protection profile' should contain qualifier: 'Well-known protection profile: Fortanix FX2200' (%s), but get: %s", Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, Common.NODE_ENROLLMENT_POLICY_ITEM_WELL_KNOWN_PROTECTION_PROFILE_FORTANIX_FX2200_OID, - policyItem1.getId())); + policyItem1Qualifier.getId())); } ASN1ObjectIdentifier policyItem2 = nodeEnrollmentPolicyItem[1].getPolicyItem(); if (!policyItem2.getId().equals(Common.NODE_ENROLLMENT_POLICY_ITEM_SITE_OPERATOR_APPROVAL_REQUIRED_OID)) { @@ -148,7 +148,7 @@ private void check_extensions(X509Certificate cert, X509Certificate issuerCert) "%s certificate 'Cluster node enrollment policy' extension should contain policy item 'Node enrollment policy item: Site operator approval required' (%s), but get: %s", Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, Common.NODE_ENROLLMENT_POLICY_ITEM_SITE_OPERATOR_APPROVAL_REQUIRED_OID, - policyItem1.getId())); + policyItem2.getId())); } } diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationStatementCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationStatementCertChecker.java index 9923402..494c851 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationStatementCertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationStatementCertChecker.java @@ -109,5 +109,4 @@ private void checkCertKeyUsages(X509Certificate cert) throws KeyAttestationState Common.KEY_ATTESTATION_STATEMENT_CN + " invalid keyUsage extension"); } } - } diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/KeyUsage.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/KeyUsage.java index 50c4321..02f174e 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/KeyUsage.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/KeyUsage.java @@ -65,4 +65,4 @@ public static void checkKeyUsageHelper(String errStrPrefix, boolean[] keyUsage, throw new KeyAttestationStatementVerifyException(errStrPrefix + " invalid keyUsage extension"); } } -} \ No newline at end of file +} diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/NodeEnrollmentPolicyItem.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/NodeEnrollmentPolicyItem.java index 9f3fedf..c307d02 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/NodeEnrollmentPolicyItem.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/NodeEnrollmentPolicyItem.java @@ -82,4 +82,4 @@ public String toString() { return sb.toString(); } -} \ No newline at end of file +} diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatement.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatement.java index e572150..2195c78 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatement.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/json/KeyAttestationStatement.java @@ -73,4 +73,4 @@ public String toString() { } } -} \ No newline at end of file +} diff --git a/key-attestation/java-example/src/test/resources/key-attestation-response.json b/key-attestation/java-example/src/test/resources/key-attestation-response.json index e332979..7b8ebe3 100644 --- a/key-attestation/java-example/src/test/resources/key-attestation-response.json +++ b/key-attestation/java-example/src/test/resources/key-attestation-response.json @@ -8,4 +8,4 @@ "format": "x509_certificate", "statement": "MIID/zCCAmegAwIBAgIUCVQHdgKkQdO34cZVHfE5cO1rQwUwDQYJKoZIhvcNAQELBQAwNjE0MDIGA1UEAwwrRm9ydGFuaXggRFNNIFNhYVMgS2V5IEF0dGVzdGF0aW9uIEF1dGhvcml0eTAgFw0yMzA5MDEwMDM2MDZaGA85OTk5MTIzMTIzNTk1OV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K8ZFLPYZR4jlwED4lWKjyWqr1nyMSfuw7A6LItEswLI0Pk+333fXHxAs3HHbKXsyuwx4MZ9XreAqX7WmVlaN8LNca7tuEA==" } -} \ No newline at end of file +} diff --git a/key-attestation/java-example/src/test/resources/key-attestation-statement.pem b/key-attestation/java-example/src/test/resources/key-attestation-statement.pem index 3946974..3eb5e91 100644 --- a/key-attestation/java-example/src/test/resources/key-attestation-statement.pem +++ b/key-attestation/java-example/src/test/resources/key-attestation-statement.pem @@ -126,4 +126,4 @@ EeS4TnykL05RW11u1A/mkVsuBaOYHEeAN28Hz4xMffoWtPTM1oCfEAv7eYH/ZdJ7 yGypNrVAJI78/0/5zY+qkEivgh9xpnoAKHK4UT/cKhuLDCNQIEhB4fhnwhOuX1/1 DFOz4Vdzshx2KL0eanblKF2i0ekR8tzv97a41mzM3Q/TXe0l9xVINzDynbePYHrs WBYyPcMCau5v4vFxobX+622kIrXllaU+gQ== ------END CERTIFICATE----- \ No newline at end of file +-----END CERTIFICATE----- From ba8396bfb05e108ec5b3105dc183f5582f04a3d4 Mon Sep 17 00:00:00 2001 From: Yuxiang Cao Date: Wed, 6 Sep 2023 13:25:59 -0700 Subject: [PATCH 10/12] fix: skip public key check in statement Since we cannot expect what kind of asymmetric key will be in Key Attestation statement, we can skip the check of public key for now. --- .../KeyAttestationStatementCertChecker.java | 20 ++----------------- 1 file changed, 2 insertions(+), 18 deletions(-) diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationStatementCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationStatementCertChecker.java index 494c851..b4233b4 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationStatementCertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationStatementCertChecker.java @@ -1,8 +1,6 @@ package com.fortanix.keyattestationstatementverifier.certchecker; -import java.security.PublicKey; import java.security.cert.X509Certificate; -import java.security.interfaces.RSAPublicKey; import java.util.Arrays; import java.util.Set; import java.util.logging.Logger; @@ -30,9 +28,7 @@ public void check(X509Certificate cert, X509Certificate issuerCert) throws Excep LOGGER.info(String.format( "Checking '%s' certificate's Subject & Issuer", certCN)); check_subject_and_issuer(cert); - LOGGER.info(String.format( - "Checking '%s' certificate's Public key length & type", certCN)); - check_public_key(cert); + LOGGER.info(String.format( "Checking '%s' certificate's extensions", certCN)); check_extensions(cert, issuerCert); @@ -47,8 +43,8 @@ private void check_subject_and_issuer(X509Certificate cert) throws Exception { Common.KEY_ATTESTATION_STATEMENT_CN + " certificate subject is invalid " + statementCertSubject.toString()); } - // check issuer + // check issuer X500Name statementCertIssuer = statementCert.getIssuer(); if (!Common.checkNameMatch(statementCertIssuer, Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_NAME)) { throw new KeyAttestationStatementVerifyException( @@ -57,18 +53,6 @@ private void check_subject_and_issuer(X509Certificate cert) throws Exception { } } - private void check_public_key(X509Certificate cert) throws Exception { - PublicKey statementPk = cert.getPublicKey(); - if (statementPk instanceof RSAPublicKey) { - RSAPublicKey statementRsaPk = (RSAPublicKey) statementPk; - assert (statementRsaPk.getModulus().bitLength() >= 2048); - } else { - throw new KeyAttestationStatementVerifyException( - Common.KEY_ATTESTATION_STATEMENT_CN + " certificate invalid public key type"); - } - - } - private void check_extensions(X509Certificate cert, X509Certificate issuerCert) throws Exception { checkCertKeyUsages(cert); // check extension: Authority Key Identifier From 69b10c26139018669ddb897801e368928c208cd9 Mon Sep 17 00:00:00 2001 From: Yuxiang Cao Date: Wed, 6 Sep 2023 13:45:01 -0700 Subject: [PATCH 11/12] refactor: refactor KeyUsage to KeyUsageExt Refactor KeyUsageExt into a bitflags like type --- ...DsmKeyAttestationAuthorityCertChecker.java | 12 ++- .../certchecker/FortanixRootCertChecker.java | 12 ++- .../KeyAttestationCaCertChecker.java | 12 ++- .../KeyAttestationStatementCertChecker.java | 42 ++++----- .../types/asn1/KeyUsage.java | 68 --------------- .../types/asn1/KeyUsageExt.java | 87 +++++++++++++++++++ 6 files changed, 133 insertions(+), 100 deletions(-) delete mode 100644 key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/KeyUsage.java create mode 100644 key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/KeyUsageExt.java diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/DsmKeyAttestationAuthorityCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/DsmKeyAttestationAuthorityCertChecker.java index 7ac9dc6..81af2b8 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/DsmKeyAttestationAuthorityCertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/DsmKeyAttestationAuthorityCertChecker.java @@ -15,8 +15,9 @@ import com.fortanix.keyattestationstatementverifier.Common; import com.fortanix.keyattestationstatementverifier.KeyAttestationStatementVerifyException; import com.fortanix.keyattestationstatementverifier.types.asn1.ClusterNodeEnrollmentPolicy; -import com.fortanix.keyattestationstatementverifier.types.asn1.KeyUsage; +import com.fortanix.keyattestationstatementverifier.types.asn1.KeyUsageExt; import com.fortanix.keyattestationstatementverifier.types.asn1.NodeEnrollmentPolicyItem; +import com.fortanix.keyattestationstatementverifier.types.asn1.KeyUsageExt.KeyUsage; public class DsmKeyAttestationAuthorityCertChecker extends CertChecker { private static final Logger LOGGER = Logger.getLogger(DsmKeyAttestationAuthorityCertChecker.class.getName()); @@ -76,8 +77,13 @@ private void check_extensions(X509Certificate cert, X509Certificate issuerCert) LOGGER.info(String.format( "Checking '%s' certificate's KeyUsages extension", certCN)); KeyUsage[] authorityCertExpectedKeyUsage = { KeyUsage.DIGITAL_SIGNATURE }; - KeyUsage.checkKeyUsageHelper(Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, cert.getKeyUsage(), - authorityCertExpectedKeyUsage); + KeyUsageExt keyUsageExt = new KeyUsageExt(cert.getKeyUsage()); + if (!keyUsageExt.hasUsage(authorityCertExpectedKeyUsage)) { + throw new KeyAttestationStatementVerifyException( + Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN + + " certificate keyUsage extension should contains: " + + authorityCertExpectedKeyUsage.toString()); + } // check extension: Basic Constraints LOGGER.info(String.format( "Checking '%s' certificate's BasicConstraints extension", certCN)); diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/FortanixRootCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/FortanixRootCertChecker.java index c60c70d..ddfe54e 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/FortanixRootCertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/FortanixRootCertChecker.java @@ -11,7 +11,8 @@ import com.fortanix.keyattestationstatementverifier.Common; import com.fortanix.keyattestationstatementverifier.KeyAttestationStatementVerifyException; -import com.fortanix.keyattestationstatementverifier.types.asn1.KeyUsage; +import com.fortanix.keyattestationstatementverifier.types.asn1.KeyUsageExt; +import com.fortanix.keyattestationstatementverifier.types.asn1.KeyUsageExt.KeyUsage; public class FortanixRootCertChecker extends CertChecker { private static final Logger LOGGER = Logger.getLogger(FortanixRootCertChecker.class.getName()); @@ -72,8 +73,13 @@ private void check_extensions(X509Certificate cert) throws Exception { LOGGER.info(String.format( "Checking '%s' certificate's KeyUsages extension", certCN)); KeyUsage[] rootCertExpectedKeyUsage = { KeyUsage.DIGITAL_SIGNATURE, KeyUsage.KEY_CERT_SIGN, KeyUsage.CRL_SIGN }; - KeyUsage.checkKeyUsageHelper(Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CN, cert.getKeyUsage(), - rootCertExpectedKeyUsage); + KeyUsageExt keyUsageExt = new KeyUsageExt(cert.getKeyUsage()); + if (!keyUsageExt.hasUsage(rootCertExpectedKeyUsage)) { + throw new KeyAttestationStatementVerifyException( + Common.FORTANIX_ATTESTATION_AND_PROVISIONING_ROOT_CA_CN + + " certificate keyUsage extension should contains: " + + rootCertExpectedKeyUsage.toString()); + } int pathLenConstraint = cert.getBasicConstraints(); // check extension: Basic Constraints LOGGER.info(String.format( diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationCaCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationCaCertChecker.java index 2456a13..0f82760 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationCaCertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationCaCertChecker.java @@ -13,7 +13,8 @@ import com.fortanix.keyattestationstatementverifier.Common; import com.fortanix.keyattestationstatementverifier.KeyAttestationStatementVerifyException; -import com.fortanix.keyattestationstatementverifier.types.asn1.KeyUsage; +import com.fortanix.keyattestationstatementverifier.types.asn1.KeyUsageExt; +import com.fortanix.keyattestationstatementverifier.types.asn1.KeyUsageExt.KeyUsage; public class KeyAttestationCaCertChecker extends CertChecker { private static final Logger LOGGER = Logger.getLogger(KeyAttestationCaCertChecker.class.getName()); @@ -75,8 +76,13 @@ private void check_extensions(X509Certificate cert, X509Certificate issuerCert) LOGGER.info(String.format( "Checking '%s' certificate's KeyUsages extension", certCN)); KeyUsage[] caCertExpectedKeyUsage = { KeyUsage.DIGITAL_SIGNATURE, KeyUsage.KEY_CERT_SIGN, KeyUsage.CRL_SIGN }; - KeyUsage.checkKeyUsageHelper(Common.FORTANIX_KEY_ATTESTATION_CA_CN, cert.getKeyUsage(), - caCertExpectedKeyUsage); + KeyUsageExt keyUsageExt = new KeyUsageExt(cert.getKeyUsage()); + if (!keyUsageExt.hasUsage(caCertExpectedKeyUsage)) { + throw new KeyAttestationStatementVerifyException( + Common.FORTANIX_KEY_ATTESTATION_CA_CN + + " certificate keyUsage extension should contains: " + + caCertExpectedKeyUsage.toString()); + } // check extension: Basic Constraints LOGGER.info(String.format( "Checking '%s' certificate's BasicConstraints extension", certCN)); diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationStatementCertChecker.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationStatementCertChecker.java index b4233b4..32186a2 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationStatementCertChecker.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/certchecker/KeyAttestationStatementCertChecker.java @@ -12,7 +12,8 @@ import com.fortanix.keyattestationstatementverifier.Common; import com.fortanix.keyattestationstatementverifier.KeyAttestationStatementVerifyException; -import com.fortanix.keyattestationstatementverifier.types.asn1.KeyUsage; +import com.fortanix.keyattestationstatementverifier.types.asn1.KeyUsageExt; +import com.fortanix.keyattestationstatementverifier.types.asn1.KeyUsageExt.KeyUsage; public class KeyAttestationStatementCertChecker extends CertChecker { private static final Logger LOGGER = Logger.getLogger(KeyAttestationStatementCertChecker.class.getName()); @@ -57,7 +58,7 @@ private void check_extensions(X509Certificate cert, X509Certificate issuerCert) checkCertKeyUsages(cert); // check extension: Authority Key Identifier LOGGER.info(String.format( - "Checking '%s' certificate's AuthorityKeyIdentifier extension", certCN)); + "Checking '%s' certificate's AuthorityKeyIdentifier extension", certCN)); if (!Arrays.equals(getExtAkiVal(cert), getExtSkiVal(issuerCert))) { throw new KeyAttestationStatementVerifyException( Common.KEY_ATTESTATION_STATEMENT_CN @@ -68,29 +69,24 @@ private void check_extensions(X509Certificate cert, X509Certificate issuerCert) private void checkCertKeyUsages(X509Certificate cert) throws KeyAttestationStatementVerifyException { LOGGER.info(String.format( "Checking '%s' certificate's KeyUsages extension", certCN)); - boolean[] certKeyUsagesBooleans = cert.getKeyUsage(); - if (certKeyUsagesBooleans != null && certKeyUsagesBooleans.length == 9) { - KeyUsage[] allowedKeyUsages = { - KeyUsage.DIGITAL_SIGNATURE, - KeyUsage.KEY_ENCIPHERMENT, - KeyUsage.DATA_ENCIPHERMENT, - KeyUsage.KEY_AGREEMENT, - }; - Set allowedKeyUsagesSet = Arrays.stream(allowedKeyUsages).collect(Collectors.toSet()); + KeyUsageExt keyUsageExt = new KeyUsageExt(cert.getKeyUsage()); + KeyUsage[] allowedKeyUsages = { + KeyUsage.DIGITAL_SIGNATURE, + KeyUsage.KEY_ENCIPHERMENT, + KeyUsage.DATA_ENCIPHERMENT, + KeyUsage.KEY_AGREEMENT, + }; + Set allowedKeyUsagesSet = Arrays.stream(allowedKeyUsages).collect(Collectors.toSet()); - KeyUsage[] disallowedKeyUsages = Arrays.stream(KeyUsage.values()) - .filter(keyUsage -> !allowedKeyUsagesSet.contains(keyUsage)) - .toArray(KeyUsage[]::new); - for (KeyUsage ku : disallowedKeyUsages) { - if (certKeyUsagesBooleans[ku.getBitIndex()]) { - throw new KeyAttestationStatementVerifyException( - Common.KEY_ATTESTATION_STATEMENT_CN + " keyUsage extension should not contain: " - + ku.toString()); - } + KeyUsage[] disallowedKeyUsages = Arrays.stream(KeyUsage.values()) + .filter(keyUsage -> !allowedKeyUsagesSet.contains(keyUsage)) + .toArray(KeyUsage[]::new); + for (KeyUsage ku : disallowedKeyUsages) { + if (keyUsageExt.hasUsage(ku)) { + throw new KeyAttestationStatementVerifyException( + Common.KEY_ATTESTATION_STATEMENT_CN + " keyUsage extension should not contain: " + + ku.toString()); } - } else { - throw new KeyAttestationStatementVerifyException( - Common.KEY_ATTESTATION_STATEMENT_CN + " invalid keyUsage extension"); } } } diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/KeyUsage.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/KeyUsage.java deleted file mode 100644 index 02f174e..0000000 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/KeyUsage.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.fortanix.keyattestationstatementverifier.types.asn1; - -import com.fortanix.keyattestationstatementverifier.KeyAttestationStatementVerifyException; - -/** - * The helper type for checking X509 KeyUsage extension - */ -public enum KeyUsage { - DIGITAL_SIGNATURE(0), - NON_REPUDIATION(1), - KEY_ENCIPHERMENT(2), - DATA_ENCIPHERMENT(3), - KEY_AGREEMENT(4), - KEY_CERT_SIGN(5), - CRL_SIGN(6), - ENCIPHER_ONLY(7), - DECIPHER_ONLY(8); - - final int bitIndex; - - KeyUsage(int bitIndex) { - this.bitIndex = bitIndex; - } - - public int getBitIndex() { - return this.bitIndex; - } - - @Override - public String toString() { - switch (this) { - case DIGITAL_SIGNATURE: - return "Digital Signature"; - case NON_REPUDIATION: - return "Non-Repudiation"; - case KEY_ENCIPHERMENT: - return "Key Encipherment"; - case DATA_ENCIPHERMENT: - return "Data Encipherment"; - case KEY_AGREEMENT: - return "Key Agreement"; - case KEY_CERT_SIGN: - return "Key Certificate Sign"; - case CRL_SIGN: - return "CRL Sign"; - case ENCIPHER_ONLY: - return "Encipher Only"; - case DECIPHER_ONLY: - return "Decipher Only"; - default: - throw new IllegalArgumentException(); - } - } - - public static void checkKeyUsageHelper(String errStrPrefix, boolean[] keyUsage, KeyUsage[] expectedEnabledBits) - throws KeyAttestationStatementVerifyException { - if (keyUsage != null && keyUsage.length == 9) { - for (KeyUsage ku : expectedEnabledBits) { - if (!keyUsage[ku.bitIndex]) { - throw new KeyAttestationStatementVerifyException( - errStrPrefix + " keyUsage extension does not contains: " + ku.toString()); - } - } - } else { - throw new KeyAttestationStatementVerifyException(errStrPrefix + " invalid keyUsage extension"); - } - } -} diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/KeyUsageExt.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/KeyUsageExt.java new file mode 100644 index 0000000..76416ff --- /dev/null +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/types/asn1/KeyUsageExt.java @@ -0,0 +1,87 @@ +package com.fortanix.keyattestationstatementverifier.types.asn1; + +import java.util.Arrays; +import java.util.EnumSet; + +import com.fortanix.keyattestationstatementverifier.KeyAttestationStatementVerifyException; + +/** + * The helper type for checking X509 KeyUsage extension + */ +public class KeyUsageExt { + public enum KeyUsage { + DIGITAL_SIGNATURE(0), + NON_REPUDIATION(1), + KEY_ENCIPHERMENT(2), + DATA_ENCIPHERMENT(3), + KEY_AGREEMENT(4), + KEY_CERT_SIGN(5), + CRL_SIGN(6), + ENCIPHER_ONLY(7), + DECIPHER_ONLY(8); + + final int bitIndex; + + private KeyUsage(int bitIndex) { + this.bitIndex = bitIndex; + } + + public int getBitIndex() { + return this.bitIndex; + } + + @Override + public String toString() { + switch (this) { + case DIGITAL_SIGNATURE: + return "Digital Signature"; + case NON_REPUDIATION: + return "Non-Repudiation"; + case KEY_ENCIPHERMENT: + return "Key Encipherment"; + case DATA_ENCIPHERMENT: + return "Data Encipherment"; + case KEY_AGREEMENT: + return "Key Agreement"; + case KEY_CERT_SIGN: + return "Key Certificate Sign"; + case CRL_SIGN: + return "CRL Sign"; + case ENCIPHER_ONLY: + return "Encipher Only"; + case DECIPHER_ONLY: + return "Decipher Only"; + default: + throw new IllegalArgumentException(); + } + } + } + + private final EnumSet usages = EnumSet.noneOf(KeyUsage.class); + + public KeyUsageExt(boolean[] keyUsageBitArray) { + if (keyUsageBitArray.length != KeyUsage.values().length) { + throw new IllegalArgumentException("Invalid length of keyUsageBitArray"); + } + + KeyUsage[] usages = KeyUsage.values(); + for (int i = 0; i < keyUsageBitArray.length; i++) { + if (keyUsageBitArray[i]) { + this.usages.add(usages[i]); + } + } + } + + public boolean hasUsage(KeyUsage keyUsage) { + return usages.contains(keyUsage); + } + + public boolean hasUsage(KeyUsage[] keyUsageList) { + return usages.containsAll(Arrays.asList(keyUsageList)); + } + + @Override + public String toString() { + return "KeyUsageExt{" + usages + '}'; + } +} From c0ba284695a7d994da29e68e5c34899120a543bf Mon Sep 17 00:00:00 2001 From: Yuxiang Cao Date: Wed, 6 Sep 2023 13:47:25 -0700 Subject: [PATCH 12/12] fix: fix wrong logging --- .../com/fortanix/keyattestationstatementverifier/Verify.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java index f8f9188..64138ed 100644 --- a/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java +++ b/key-attestation/java-example/src/main/java/com/fortanix/keyattestationstatementverifier/Verify.java @@ -81,7 +81,7 @@ public static void verify(List authorityChain, X509Certificate checkAuthorityChainLength(authorityChain); LOGGER.info(String.format("Checking if '%s' certificate is correctly signed by '%s' certificate", - Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN, Common.KEY_ATTESTATION_STATEMENT_CN)); + Common.KEY_ATTESTATION_STATEMENT_CN, Common.DSM_CLUSTER_KEY_ATTESTATION_AUTHORITY_CN)); // because 'Fortanix DSM SaaS Key Attestation Authority' is not a CA // certificate, so we need to manually check 'Fortanix DSM Key Attestation' is // correctly singed by 'Fortanix DSM SaaS Key Attestation Authority' certificate