├── .gitignore ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── reveny │ │ └── nativekeyattestation │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── ic_launcher-playstore.png │ ├── java │ │ └── com │ │ │ └── reveny │ │ │ └── nativekeyattestation │ │ │ └── MainActivity.java │ ├── jni │ │ ├── Build │ │ │ ├── Android.mk │ │ │ └── Application.mk │ │ ├── Include │ │ │ ├── Logger.hpp │ │ │ └── SafeJNI.hpp │ │ ├── KeyAttestation │ │ │ ├── Asn1Utils.hpp │ │ │ ├── KeyAttestation.cpp │ │ │ ├── KeyAttestation.hpp │ │ │ └── RootOfTrust.hpp │ │ └── Main.cpp │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.webp │ │ ├── ic_launcher_foreground.webp │ │ └── ic_launcher_round.webp │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.webp │ │ ├── ic_launcher_foreground.webp │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.webp │ │ ├── ic_launcher_foreground.webp │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.webp │ │ ├── ic_launcher_foreground.webp │ │ └── ic_launcher_round.webp │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.webp │ │ ├── ic_launcher_foreground.webp │ │ └── ic_launcher_round.webp │ │ ├── values-night │ │ └── themes.xml │ │ ├── values │ │ ├── colors.xml │ │ ├── ic_launcher_background.xml │ │ ├── strings.xml │ │ └── themes.xml │ │ └── xml │ │ ├── backup_rules.xml │ │ └── data_extraction_rules.xml │ └── test │ └── java │ └── com │ └── reveny │ └── nativekeyattestation │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── images └── preview.png └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Gradle files 2 | .gradle/ 3 | build/ 4 | 5 | # Local configuration file (sdk path, etc) 6 | local.properties 7 | 8 | # Log/OS Files 9 | *.log 10 | 11 | # Android Studio generated files and folders 12 | captures/ 13 | .externalNativeBuild/ 14 | .cxx/ 15 | *.apk 16 | output.json 17 | 18 | # IntelliJ 19 | *.iml 20 | .idea/ 21 | misc.xml 22 | deploymentTargetDropDown.xml 23 | render.experimental.xml 24 | 25 | # Keystore files 26 | *.jks 27 | *.keystore 28 | 29 | # Google Services (e.g. APIs or Firebase) 30 | google-services.json 31 | 32 | # Android Profiling 33 | *.hprof 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Android-Native-KeyAttestation 2 | A c++ (jni) implementation of KeyAttestation for Android 3 | 4 | ## Disclaimer 5 | - This code is NOT written by me, it is simply just translated by me. Credit for KeyAttestation goes to vvb2060 6 | - I don't suggest using this code in any commercial software as it is not really stable and really only a POC. 7 | - To pass this app you can simply use bootloader spoofer by chiteroman. This is not intended to be used as a root detection app. 8 | - Don't expect much from this app as it is just a small project for me to see what's possible with the use of JavaNativeInterface. 9 | 10 | ## Features 11 | - [x] Support for Android 14 12 | - [x] Hardware-backed key generation and attestation 13 | - [x] Native code implementation for improved security 14 | - [x] Error handling and reporting 15 | 16 | ## Todo 17 | - [ ] Check whether certificate is expired 18 | - [ ] Maybe there is a way to do everything without JNI? 19 | - [ ] Adapt more checks from regular KeyAttestation 20 | - [ ] Remove some unnecessary error checks 21 | 22 | ## Build and Installation 23 | Building this project requires the Android NDK and CMake: https://developer.android.com/studio/projects/install-ndk 24 | Follow these steps to compile and install the application on your device: 25 | 26 | 1. Clone the repository to your local machine. 27 | 2. Open the project in Android Studio with NDK and CMake installed. 28 | 3. Build the project using the "Build" menu. 29 | 4. Connect your Android device and ensure USB debugging is enabled. 30 | 5. Install the app onto your device using Android Studio's "Run" function. 31 | 32 | ## Known Problems 33 | - Some devices may not support hardware-backed key attestation 34 | - Crashes may happen if TEE is broken 35 | 36 | ## Credits 37 | This project uses resources from following sources: 38 | - Original KeyAttestation project by vvb2060: https://github.com/vvb2060/KeyAttestation 39 | - Key Attestation sample by Google: https://developer.android.com/training/articles/security-key-attestation 40 | 41 | Special thanks to vvb2060 and contributors of KeyAttestation for their resources and knowledge. 42 | Contributions to this project are very welcome. 43 | 44 | ## Contact 45 | For questions, suggestions, or contributions, please reach out through: 46 | - Telegram Group: https://t.me/reveny1 47 | - Telegram Contact: https://t.me/revenyy 48 | 49 | ## Screenshots 50 | ![preview](https://github.com/reveny/Android-Native-KeyAttestation/blob/main/images/preview.png) 51 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.application' 3 | } 4 | 5 | android { 6 | namespace 'com.reveny.nativekeyattestation' 7 | compileSdk 34 8 | 9 | defaultConfig { 10 | applicationId "com.reveny.nativekeyattestation" 11 | minSdk 21 12 | targetSdk 34 13 | versionCode 1 14 | versionName "1.0" 15 | ndk { 16 | //noinspection ChromeOsAbiSupport 17 | abiFilters 'armeabi-v7a', 'arm64-v8a' 18 | } 19 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 20 | } 21 | 22 | buildTypes { 23 | release { 24 | minifyEnabled false 25 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 26 | } 27 | } 28 | compileOptions { 29 | sourceCompatibility JavaVersion.VERSION_1_8 30 | targetCompatibility JavaVersion.VERSION_1_8 31 | } 32 | externalNativeBuild { 33 | ndkBuild { 34 | path "src/main/jni/Build/Android.mk" 35 | } 36 | } 37 | ndkVersion = '26.1.10909125' 38 | } 39 | 40 | dependencies { 41 | implementation "org.bouncycastle:bcprov-jdk18on:1.76" 42 | 43 | implementation 'androidx.appcompat:appcompat:1.6.1' 44 | implementation 'com.google.android.material:material:1.11.0' 45 | implementation 'androidx.constraintlayout:constraintlayout:2.1.4' 46 | testImplementation 'junit:junit:4.13.2' 47 | androidTestImplementation 'androidx.test.ext:junit:1.1.5' 48 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' 49 | } -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /app/src/androidTest/java/com/reveny/nativekeyattestation/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.reveny.nativekeyattestation; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.test.platform.app.InstrumentationRegistry; 6 | import androidx.test.ext.junit.runners.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 24 | assertEquals("com.reveny.nativekeyattestation", appContext.getPackageName()); 25 | } 26 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 15 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /app/src/main/ic_launcher-playstore.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reveny/Android-Native-KeyAttestation/bddc054b667dff5d9457a4b2fd2c85aed87cce83/app/src/main/ic_launcher-playstore.png -------------------------------------------------------------------------------- /app/src/main/java/com/reveny/nativekeyattestation/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.reveny.nativekeyattestation; 2 | 3 | import androidx.appcompat.app.AppCompatActivity; 4 | 5 | import android.os.Bundle; 6 | import android.widget.TextView; 7 | 8 | public class MainActivity extends AppCompatActivity { 9 | public native String getAttestationResult(); 10 | 11 | @Override 12 | protected void onCreate(Bundle savedInstanceState) { 13 | super.onCreate(savedInstanceState); 14 | setContentView(R.layout.activity_main); 15 | System.loadLibrary("Attestation"); 16 | 17 | TextView view = findViewById(R.id.result_text); 18 | String result = getAttestationResult(); 19 | view.setText(result); 20 | } 21 | } -------------------------------------------------------------------------------- /app/src/main/jni/Build/Android.mk: -------------------------------------------------------------------------------- 1 | LOCAL_PATH := $(call my-dir)/.. 2 | 3 | include $(CLEAR_VARS) 4 | 5 | LOCAL_CPPFLAGS += -fexceptions -Werror -Wpedantic -s -std=c++20 -w 6 | 7 | LOCAL_C_INCLUDES := $(LOCAL_PATH)/Include \ 8 | 9 | LOCAL_MODULE := Attestation 10 | LOCAL_SRC_FILES := Main.cpp KeyAttestation/KeyAttestation.cpp 11 | LOCAL_LDLIBS := -llog -landroid 12 | 13 | include $(BUILD_SHARED_LIBRARY) 14 | -------------------------------------------------------------------------------- /app/src/main/jni/Build/Application.mk: -------------------------------------------------------------------------------- 1 | APP_ABI := arm64-v8a armeabi-v7a 2 | APP_STL := c++_static 3 | APP_OPTIM := release 4 | APP_THIN_ARCHIVE := true 5 | APP_PIE := true -------------------------------------------------------------------------------- /app/src/main/jni/Include/Logger.hpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by reveny on 26/10/2023. 3 | // 4 | #pragma once 5 | 6 | #include 7 | 8 | #define LOG_TAG "KeyAttestation" 9 | #define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)) 10 | #define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)) -------------------------------------------------------------------------------- /app/src/main/jni/Include/SafeJNI.hpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by reveny on 04/02/2024. 3 | // 4 | #pragma once 5 | 6 | #define THROW_JNI_EXCEPTIONS 1 7 | 8 | #define SAFE_FIND_CLASS(env, name) SafeJNI::FindClass(env, name); 9 | #define SAFE_GET_METHOD_ID(env, clazz, name, sig) SafeJNI::GetMethodID(env, clazz, name, sig); 10 | #define SAFE_GET_STATIC_METHOD_ID(env, clazz, name, sig) SafeJNI::GetStaticMethodID(env, clazz, name, sig); 11 | 12 | #define SAFE_THROW(env, clazz, info) SafeJNI::ThrowException(env, clazz, info); 13 | #define SAFE_FAILIURE_RETURN_VALUE(env, obj, ret) if (obj == nullptr || env->ExceptionCheck()) { env->ExceptionClear(); return ret; } 14 | #define SAFE_FAILIURE_RETURN_VOID(env, obj) if (obj == nullptr || env->ExceptionCheck()) { env->ExceptionClear(); return; } 15 | #define SAFE_JNI_CHECK(env) if (env->ExceptionCheck()) { env->ExceptionClear(); return; } 16 | #define SAFE_JNI_CHECK_VALUE(env, val) if (env->ExceptionCheck()) { env->ExceptionClear(); return val; } 17 | 18 | namespace SafeJNI { 19 | inline jclass FindClass(JNIEnv* env, const char* name) { 20 | jclass clazz = env->FindClass(name); 21 | if (!clazz) { 22 | if (THROW_JNI_EXCEPTIONS) env->ThrowNew(env->FindClass("java/lang/ClassNotFoundException"), name); 23 | return nullptr; 24 | } 25 | return clazz; 26 | } 27 | 28 | inline jmethodID GetMethodID(JNIEnv* env, jclass clazz, const char* name, const char* sig) { 29 | jmethodID mid = env->GetMethodID(clazz, name, sig); 30 | if (!mid) { 31 | if (THROW_JNI_EXCEPTIONS) env->ThrowNew(env->FindClass("java/lang/NoSuchMethodException"), name); 32 | return nullptr; 33 | } 34 | return mid; 35 | } 36 | 37 | inline jmethodID GetStaticMethodID(JNIEnv* env, jclass clazz, const char* name, const char* sig) { 38 | jmethodID mid = env->GetStaticMethodID(clazz, name, sig); 39 | if (!mid) { 40 | if (THROW_JNI_EXCEPTIONS) env->ThrowNew(env->FindClass("java/lang/NoSuchMethodException"), name); 41 | return nullptr; 42 | } 43 | return mid; 44 | } 45 | 46 | inline void ThrowException(JNIEnv* env, const char* clazz, const char* info) { 47 | if (THROW_JNI_EXCEPTIONS == 0) return; 48 | 49 | env->ThrowNew(env->FindClass(clazz), info); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /app/src/main/jni/KeyAttestation/Asn1Utils.hpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by reveny on 29/12/2023. 3 | // 4 | #pragma once 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | #include "Include/SafeJNI.hpp" 11 | 12 | namespace Asn1Utils { 13 | inline jbyteArray GetByteArrayFromAsn1(JNIEnv *env, jobject asn1Encodable) { 14 | jclass derOctetStringClass = SAFE_FIND_CLASS(env, "org/bouncycastle/asn1/DEROctetString"); 15 | if (asn1Encodable == nullptr || !env->IsInstanceOf(asn1Encodable, derOctetStringClass)) { 16 | SAFE_THROW(env, "java/lang/IllegalArgumentException", "Expected DEROctetString"); 17 | return nullptr; 18 | } 19 | jmethodID getOctetsMethod = SAFE_GET_METHOD_ID(env, derOctetStringClass, "getOctets", "()[B"); 20 | SAFE_FAILIURE_RETURN_VALUE(env, getOctetsMethod, nullptr); 21 | 22 | return (jbyteArray)env->CallObjectMethod(asn1Encodable, getOctetsMethod); 23 | } 24 | 25 | inline jobject GetAsn1SequenceFromStream(JNIEnv* env, jobject asn1InputStream) { 26 | jclass asn1InputStreamClass = SAFE_FIND_CLASS(env, "org/bouncycastle/asn1/ASN1InputStream"); 27 | jmethodID readObjectMethod = SAFE_GET_METHOD_ID(env, asn1InputStreamClass, "readObject", "()Lorg/bouncycastle/asn1/ASN1Primitive;"); 28 | SAFE_FAILIURE_RETURN_VALUE(env, readObjectMethod, nullptr); 29 | 30 | jobject asn1Primitive = env->CallObjectMethod(asn1InputStream, readObjectMethod); 31 | SAFE_FAILIURE_RETURN_VALUE(env, asn1Primitive, nullptr); 32 | 33 | jclass octetStringClass = SAFE_FIND_CLASS(env, "org/bouncycastle/asn1/ASN1OctetString"); 34 | if (!env->IsInstanceOf(asn1Primitive, octetStringClass)) { 35 | SAFE_THROW(env, "java/lang/IllegalArgumentException", "Expected octet stream"); 36 | return nullptr; 37 | } 38 | 39 | jmethodID getOctetsMethod = SAFE_GET_METHOD_ID(env, octetStringClass, "getOctets", "()[B"); 40 | SAFE_FAILIURE_RETURN_VALUE(env, getOctetsMethod, nullptr); 41 | 42 | jbyteArray octets = static_cast(env->CallObjectMethod(asn1Primitive, getOctetsMethod)); 43 | jmethodID inputStreamID = SAFE_GET_METHOD_ID(env, asn1InputStreamClass, "", "([B)V"); 44 | jobject seqInputStream = env->NewObject(asn1InputStreamClass, inputStreamID, octets); 45 | SAFE_FAILIURE_RETURN_VALUE(env, seqInputStream, nullptr); 46 | 47 | asn1Primitive = env->CallObjectMethod(seqInputStream, readObjectMethod); 48 | SAFE_FAILIURE_RETURN_VALUE(env, asn1Primitive, nullptr); 49 | 50 | jclass sequenceClass = SAFE_FIND_CLASS(env, "org/bouncycastle/asn1/ASN1Sequence"); 51 | if (!env->IsInstanceOf(asn1Primitive, sequenceClass)) { 52 | SAFE_THROW(env, "java/lang/IllegalArgumentException", "Expected sequence"); 53 | return nullptr; 54 | } 55 | 56 | return asn1Primitive; 57 | } 58 | 59 | inline jobject GetAsn1SequenceFromBytes(JNIEnv* env, jbyteArray bytes) { 60 | jclass asn1InputStreamClass = SAFE_FIND_CLASS(env, "org/bouncycastle/asn1/ASN1InputStream"); 61 | SAFE_FAILIURE_RETURN_VALUE(env, asn1InputStreamClass, nullptr); 62 | 63 | jmethodID asn1InputStreamConstructor = SAFE_GET_METHOD_ID(env, asn1InputStreamClass, "", "([B)V"); 64 | SAFE_FAILIURE_RETURN_VALUE(env, asn1InputStreamConstructor, nullptr); 65 | 66 | jobject asn1InputStream = env->NewObject(asn1InputStreamClass, asn1InputStreamConstructor, bytes); 67 | SAFE_FAILIURE_RETURN_VALUE(env, asn1InputStream, nullptr); 68 | 69 | return GetAsn1SequenceFromStream(env, asn1InputStream); 70 | } 71 | 72 | inline jboolean GetBooleanFromAsn1(JNIEnv *env, jobject value) { 73 | jclass booleanClass = SAFE_FIND_CLASS(env, "org/bouncycastle/asn1/ASN1Boolean"); 74 | if (!env->IsInstanceOf(value, booleanClass)) { 75 | SAFE_THROW(env, "java/lang/IllegalArgumentException", "Expected boolean"); 76 | return JNI_FALSE; 77 | } 78 | 79 | jmethodID equalsMethod = SAFE_GET_METHOD_ID(env, booleanClass, "equals", "(Ljava/lang/Object;)Z"); 80 | jobject trueValue = env->GetStaticObjectField(booleanClass, env->GetStaticFieldID(booleanClass, "TRUE", "Lorg/bouncycastle/asn1/ASN1Boolean;")); 81 | jobject falseValue = env->GetStaticObjectField(booleanClass, env->GetStaticFieldID(booleanClass, "FALSE", "Lorg/bouncycastle/asn1/ASN1Boolean;")); 82 | 83 | if (env->CallBooleanMethod(value, equalsMethod, trueValue)) { 84 | return JNI_TRUE; 85 | } 86 | else if (env->CallBooleanMethod(value, equalsMethod, falseValue)) { 87 | return JNI_FALSE; 88 | } else { 89 | SAFE_THROW(env, "java/lang/IllegalArgumentException", "Invalid boolean value"); 90 | return JNI_FALSE; 91 | } 92 | } 93 | 94 | inline jint BigIntegerToInt(JNIEnv *env, jobject bigInt) { 95 | jclass bigIntegerClass = SAFE_FIND_CLASS(env, "java/math/BigInteger"); 96 | SAFE_FAILIURE_RETURN_VALUE(env, bigIntegerClass, 0); 97 | 98 | jmethodID intValueMethod = SAFE_GET_METHOD_ID(env, bigIntegerClass, "intValue", "()I"); 99 | SAFE_FAILIURE_RETURN_VALUE(env, intValueMethod, 0); 100 | 101 | return env->CallIntMethod(bigInt, intValueMethod); 102 | } 103 | 104 | inline jint GetIntegerFromAsn1(JNIEnv *env, jobject asn1Value) { 105 | jclass integerClass = SAFE_FIND_CLASS(env, "org/bouncycastle/asn1/ASN1Integer"); 106 | jclass enumeratedClass = SAFE_FIND_CLASS(env, "org/bouncycastle/asn1/ASN1Enumerated"); 107 | SAFE_FAILIURE_RETURN_VALUE(env, enumeratedClass, 0); 108 | 109 | if (env->IsInstanceOf(asn1Value, integerClass)) { 110 | return BigIntegerToInt(env, env->CallObjectMethod(asn1Value, env->GetMethodID(integerClass, "getValue", "()Ljava/math/BigInteger;"))); 111 | } else if (env->IsInstanceOf(asn1Value, enumeratedClass)) { 112 | return BigIntegerToInt(env, env->CallObjectMethod(asn1Value, env->GetMethodID(enumeratedClass, "getValue", "()Ljava/math/BigInteger;"))); 113 | } else { 114 | SAFE_THROW(env, "java/lang/IllegalArgumentException", "Integer value expected"); 115 | return 0; 116 | } 117 | } 118 | 119 | inline std::set GetIntegersFromAsn1Set(JNIEnv* env, jobject set) { 120 | jclass setClass = SAFE_FIND_CLASS(env, "org/bouncycastle/asn1/ASN1Set"); 121 | if (!env->IsInstanceOf(set, setClass)) { 122 | SAFE_THROW(env, "java/lang/IllegalArgumentException", "Expected set"); 123 | return std::set(); // Return empty set to avoid further processing 124 | } 125 | 126 | std::set resultSet; 127 | jmethodID getObjectsMethod = SAFE_GET_METHOD_ID(env, setClass, "getObjects", "()Ljava/util/Enumeration;"); 128 | jobject enumeration = env->CallObjectMethod(set, getObjectsMethod); 129 | SAFE_FAILIURE_RETURN_VALUE(env, enumeration, std::set()); 130 | 131 | jclass enumerationClass = SAFE_FIND_CLASS(env, "java/util/Enumeration"); 132 | jmethodID hasMoreElementsMethod = SAFE_GET_METHOD_ID(env, enumerationClass, "hasMoreElements", "()Z"); 133 | jmethodID nextElementMethod = SAFE_GET_METHOD_ID(env, enumerationClass, "nextElement", "()Ljava/lang/Object;"); 134 | while (env->CallBooleanMethod(enumeration, hasMoreElementsMethod)) { 135 | jobject asn1Integer = env->CallObjectMethod(enumeration, nextElementMethod); 136 | if (env->ExceptionCheck()) break; 137 | 138 | resultSet.insert(GetIntegerFromAsn1(env, asn1Integer)); 139 | } 140 | 141 | return resultSet; 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /app/src/main/jni/KeyAttestation/KeyAttestation.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by reveny on 02/01/2024. 3 | // 4 | #include "KeyAttestation.hpp" 5 | #include "Include/Logger.hpp" 6 | #include 7 | 8 | namespace KeyAttestation { 9 | jbyteArray attestationChallenge = nullptr; 10 | std::string outData = {}; 11 | AttestationResult attestationResult = AttestationResult::CriticalError; 12 | 13 | std::unique_ptr softwareEnforced = nullptr; 14 | std::unique_ptr teeEnforced = nullptr; 15 | } 16 | 17 | jobject KeyAttestation::ParseAsn1Encodable(JNIEnv* env, jobject parser) { 18 | jclass parserClass = SAFE_FIND_CLASS(env, "org/bouncycastle/asn1/ASN1SequenceParser"); 19 | jmethodID readObjectMethod = SAFE_GET_METHOD_ID(env, parserClass, "readObject", "()Lorg/bouncycastle/asn1/ASN1Encodable;"); 20 | SAFE_FAILIURE_RETURN_VALUE(env, readObjectMethod, nullptr); 21 | 22 | return env->CallObjectMethod(parser, readObjectMethod); 23 | } 24 | 25 | std::string KeyAttestation::VerifiedBootStateToString(int verifiedBootState) { 26 | switch (verifiedBootState) { 27 | case RootOfTrust::KM_VERIFIED_BOOT_VERIFIED: return "Verified"; 28 | case RootOfTrust::KM_VERIFIED_BOOT_SELF_SIGNED: return "Self-signed"; 29 | case RootOfTrust::KM_VERIFIED_BOOT_UNVERIFIED: return "Unverified"; 30 | case RootOfTrust::KM_VERIFIED_BOOT_FAILED: return "Failed"; 31 | default: return "Unknown (" + std::to_string(verifiedBootState) + ")"; 32 | } 33 | } 34 | 35 | jobject KeyAttestation::ParseAsn1TaggedObject(JNIEnv* env, jobject parser) { 36 | jobject asn1Encodable = ParseAsn1Encodable(env, parser); 37 | SAFE_FAILIURE_RETURN_VALUE(env, asn1Encodable, nullptr); 38 | 39 | jclass taggedObjectClass = SAFE_FIND_CLASS(env, "org/bouncycastle/asn1/ASN1TaggedObject"); 40 | if (env->IsInstanceOf(asn1Encodable, taggedObjectClass)) { 41 | return asn1Encodable; 42 | } else { 43 | SAFE_THROW(env, "java/lang/IllegalArgumentException", "Expected ASN1TaggedObject"); 44 | return nullptr; 45 | } 46 | } 47 | 48 | jobject KeyAttestation::GetAttestationSequence(JNIEnv* env, jobject x509Cert) { 49 | jclass x509CertClass = SAFE_FIND_CLASS(env, "java/security/cert/X509Certificate"); 50 | jmethodID getExtensionValueMethod = SAFE_GET_METHOD_ID(env, x509CertClass, "getExtensionValue", "(Ljava/lang/String;)[B"); 51 | jstring asn1Oid = env->NewStringUTF(ASN1_OID.c_str()); 52 | 53 | jbyteArray attestationExtensionBytes = static_cast(env->CallObjectMethod(x509Cert, getExtensionValueMethod, asn1Oid)); 54 | SAFE_FAILIURE_RETURN_VALUE(env, attestationExtensionBytes, nullptr); 55 | 56 | jsize length = env->GetArrayLength(attestationExtensionBytes); 57 | if (length == 0) { 58 | SAFE_THROW(env, "java/lang/IllegalArgumentException", "Expected ASN1TaggedObject"); 59 | return nullptr; 60 | } 61 | 62 | return Asn1Utils::GetAsn1SequenceFromBytes(env, attestationExtensionBytes); 63 | } 64 | 65 | void KeyAttestation::Asn1Attestation(JNIEnv* env, jobject cert) { 66 | auto GetObjectAt = [env](jobject sequence, int index) -> jobject { 67 | jclass sequenceClass = env->FindClass("org/bouncycastle/asn1/ASN1Sequence"); 68 | jmethodID getObjectAtMethod = env->GetMethodID(sequenceClass, "getObjectAt", "(I)Lorg/bouncycastle/asn1/ASN1Encodable;"); 69 | return env->CallObjectMethod(sequence, getObjectAtMethod, index); 70 | }; 71 | 72 | jobject seq = GetAttestationSequence(env, cert); 73 | SAFE_FAILIURE_RETURN_VOID(env, seq); 74 | 75 | jobject challengeObj = GetObjectAt(seq, ATTESTATION_CHALLENGE_INDEX); 76 | SAFE_FAILIURE_RETURN_VOID(env, challengeObj); 77 | attestationChallenge = Asn1Utils::GetByteArrayFromAsn1(env, challengeObj); 78 | 79 | jobject softwareObj = GetObjectAt(seq, SW_ENFORCED_INDEX); 80 | SAFE_FAILIURE_RETURN_VOID(env, softwareObj); 81 | softwareEnforced = std::make_unique(env, softwareObj); 82 | 83 | jobject teeObj = GetObjectAt(seq, TEE_ENFORCED_INDEX); 84 | SAFE_FAILIURE_RETURN_VOID(env, teeObj); 85 | teeEnforced = std::make_unique(env, teeObj); 86 | } 87 | 88 | void KeyAttestation::LoadFromCert(JNIEnv* env, jobject cert) { 89 | jclass x509CertClass = SAFE_FIND_CLASS(env, "java/security/cert/X509Certificate"); 90 | SAFE_FAILIURE_RETURN_VOID(env, x509CertClass); 91 | 92 | jmethodID getExtensionValueMethod = SAFE_GET_METHOD_ID(env, x509CertClass, "getExtensionValue", "(Ljava/lang/String;)[B"); 93 | SAFE_FAILIURE_RETURN_VOID(env, getExtensionValueMethod); 94 | 95 | jstring asn1Oid = env->NewStringUTF(ASN1_OID.c_str()); 96 | jstring eatOid = env->NewStringUTF(EAT_OID.c_str()); 97 | jstring crlDpOid = env->NewStringUTF(CRL_DP_OID.c_str()); 98 | 99 | if (env->CallObjectMethod(cert, getExtensionValueMethod, asn1Oid) == NULL) { 100 | jmethodID getIssuerDNMethod = env->GetMethodID(x509CertClass, "getIssuerDN", "()Ljava/security/Principal;"); 101 | jobject issuerDN = env->CallObjectMethod(cert, getIssuerDNMethod); 102 | SAFE_FAILIURE_RETURN_VOID(env, issuerDN); 103 | 104 | jmethodID getNameMethod = env->GetMethodID(env->GetObjectClass(issuerDN), "getName", "()Ljava/lang/String;"); 105 | jstring name = (jstring)env->CallObjectMethod(issuerDN, getNameMethod); 106 | 107 | // Do not throw exception here because this is actually expected. 108 | // SAFE_THROW(env, "java/lang/IllegalArgumentException", "Invalid issuer"); 109 | throw std::runtime_error("Invalid issuer"); 110 | } 111 | 112 | if (env->CallObjectMethod(cert, getExtensionValueMethod, eatOid) != nullptr) { 113 | if (env->CallObjectMethod(cert, getExtensionValueMethod, asn1Oid) != nullptr) { 114 | SAFE_THROW(env, "java/lang/IllegalArgumentException", "Multiple attestation extensions found"); 115 | } 116 | } 117 | 118 | if (env->CallObjectMethod(cert, getExtensionValueMethod, crlDpOid) != nullptr) { 119 | LOGE("CRL Distribution Points extension found in leaf certificate."); 120 | } 121 | 122 | Asn1Attestation(env, cert); 123 | } 124 | 125 | bool KeyAttestation::CheckAttestation(JNIEnv* env, jobject certificate) { 126 | try { 127 | LoadFromCert(env, certificate); 128 | 129 | if (!softwareEnforced || !teeEnforced) { 130 | LOGE("CheckAttestation -> Tee or Software is null %p %p", softwareEnforced.get(), teeEnforced.get()); 131 | return false; 132 | } 133 | 134 | std::set purposes = !teeEnforced->purposes.empty() ? teeEnforced->purposes : softwareEnforced->purposes; 135 | return !(purposes.empty() || purposes.find(7) == purposes.end()); 136 | } catch (...) { 137 | return false; 138 | } 139 | } 140 | 141 | KeyAttestation::AttestationResult KeyAttestation::ParseCertificateChain(JNIEnv* env, jobjectArray certs) { 142 | SAFE_FAILIURE_RETURN_VALUE(env, certs, AttestationResult::Error); 143 | 144 | int size = env->GetArrayLength(certs); 145 | jobject parent = env->GetObjectArrayElement(certs, size - 1); 146 | for (int i = size - 1; i >= 0; i--) { 147 | jobject current = env->GetObjectArrayElement(certs, i); 148 | SAFE_FAILIURE_RETURN_VALUE(env, current, AttestationResult::Error); 149 | 150 | if (CheckAttestation(env, current)) { 151 | break; 152 | } 153 | } 154 | 155 | // Software and Tee broken, return error. 156 | if (softwareEnforced.get() == nullptr && teeEnforced.get() == nullptr) { 157 | return AttestationResult::Error; 158 | } 159 | 160 | if (teeEnforced.get() != nullptr && teeEnforced->rootOfTrust != nullptr) { 161 | attestationResult = (!teeEnforced->rootOfTrust->isDeviceLocked() || teeEnforced->rootOfTrust->getVerifiedBootState() != RootOfTrust::KM_VERIFIED_BOOT_VERIFIED) ? AttestationResult::Unlocked : AttestationResult::Locked; 162 | outData = "Verified Boot State: " + teeEnforced->rootOfTrust->getVerifiedBootStateString() + "\n" 163 | + "Is Device Locked: " + std::string(teeEnforced->rootOfTrust->isDeviceLocked() ? "true" : "false"); 164 | } 165 | 166 | // I assume that Software isn't as reliable as Tee so we only check that if tee returned locked. 167 | if (softwareEnforced.get() != nullptr && softwareEnforced->rootOfTrust != nullptr && attestationResult != AttestationResult::Unlocked) { 168 | attestationResult = (!softwareEnforced->rootOfTrust->isDeviceLocked() || softwareEnforced->rootOfTrust->getVerifiedBootState() != RootOfTrust::KM_VERIFIED_BOOT_VERIFIED) ? AttestationResult::Unlocked : AttestationResult::Locked; 169 | outData = "Verified Boot State: " + softwareEnforced->rootOfTrust->getVerifiedBootStateString() + "\n" 170 | + "Is Device Unlocked: " + std::string(softwareEnforced->rootOfTrust->isDeviceLocked() ? "true" : "false"); 171 | } 172 | 173 | // LOGI("ParseCertificateChain -> Result: %d", attestationResult); 174 | return attestationResult; 175 | } 176 | 177 | void KeyAttestation::GenerateKey(JNIEnv* env, jstring alias, jboolean useStrongBox, jboolean includeProps, jstring attestKeyAlias) { 178 | jclass dateClass = SAFE_FIND_CLASS(env, "java/util/Date"); 179 | jmethodID dateConstructor = SAFE_GET_METHOD_ID(env, dateClass, "", "()V"); 180 | jobject now = env->NewObject(dateClass, dateConstructor); 181 | SAFE_FAILIURE_RETURN_VOID(env, now); 182 | 183 | jmethodID attestKeyID = SAFE_GET_METHOD_ID(env, env->GetObjectClass(alias), "equals", "(Ljava/lang/Object;)Z") 184 | jboolean attestKey = env->CallBooleanMethod(alias, attestKeyID, attestKeyAlias); 185 | SAFE_JNI_CHECK(env); 186 | 187 | jint purposes = (android_get_device_api_level() >= 31 && attestKey) ? 128 : (4 | 8); 188 | 189 | jclass builderClass = SAFE_FIND_CLASS(env, "android/security/keystore/KeyGenParameterSpec$Builder"); 190 | jmethodID builderConstructor = SAFE_GET_METHOD_ID(env, builderClass, "", "(Ljava/lang/String;I)V"); 191 | jobject builder = env->NewObject(builderClass, builderConstructor, alias, purposes); 192 | SAFE_FAILIURE_RETURN_VOID(env, builder); 193 | 194 | jmethodID setAlgorithmParameterSpecMethod = SAFE_GET_METHOD_ID(env, builderClass, "setAlgorithmParameterSpec", "(Ljava/security/spec/AlgorithmParameterSpec;)Landroid/security/keystore/KeyGenParameterSpec$Builder;"); 195 | jclass ecGenParameterSpecClass = SAFE_FIND_CLASS(env, "java/security/spec/ECGenParameterSpec"); 196 | jmethodID ecGenParameterSpecConstructor = SAFE_GET_METHOD_ID(env, ecGenParameterSpecClass, "", "(Ljava/lang/String;)V"); 197 | jobject ecGenParameterSpec = env->NewObject(ecGenParameterSpecClass, ecGenParameterSpecConstructor, env->NewStringUTF("secp256r1")); 198 | SAFE_FAILIURE_RETURN_VOID(env, ecGenParameterSpec); 199 | 200 | env->CallObjectMethod(builder, setAlgorithmParameterSpecMethod, ecGenParameterSpec); 201 | 202 | jclass stringClass = SAFE_FIND_CLASS(env, "java/lang/String"); 203 | jobjectArray digests = env->NewObjectArray(1, stringClass, nullptr); 204 | SAFE_FAILIURE_RETURN_VOID(env, digests); 205 | env->SetObjectArrayElement(digests, 0, env->NewStringUTF("SHA-256")); 206 | 207 | jmethodID setDigestsMethod = env->GetMethodID(builderClass, "setDigests", "([Ljava/lang/String;)Landroid/security/keystore/KeyGenParameterSpec$Builder;"); 208 | env->CallObjectMethod(builder, setDigestsMethod, digests); 209 | 210 | jmethodID setKeyValidityStartMethod = env->GetMethodID(builderClass, "setKeyValidityStart", "(Ljava/util/Date;)Landroid/security/keystore/KeyGenParameterSpec$Builder;"); 211 | env->CallObjectMethod(builder, setKeyValidityStartMethod, now); 212 | 213 | jmethodID setAttestationChallengeMethod = env->GetMethodID(builderClass, "setAttestationChallenge", "([B)Landroid/security/keystore/KeyGenParameterSpec$Builder;"); 214 | jmethodID getBytesMethod = env->GetMethodID(env->FindClass("java/lang/String"), "getBytes", "()[B"); 215 | jmethodID toStringID = SAFE_GET_METHOD_ID(env, dateClass, "toString", "()Ljava/lang/String;"); 216 | jbyteArray challenge = (jbyteArray)env->CallObjectMethod(env->CallObjectMethod(now, toStringID), getBytesMethod); 217 | SAFE_FAILIURE_RETURN_VOID(env, challenge); 218 | env->CallObjectMethod(builder, setAttestationChallengeMethod, challenge); 219 | 220 | if (android_get_device_api_level() >= 28 && useStrongBox) { 221 | jmethodID setIsStrongBoxBackedMethod = SAFE_GET_METHOD_ID(env, builderClass, "setIsStrongBoxBacked", "(Z)Landroid/security/keystore/KeyGenParameterSpec$Builder;"); 222 | env->CallObjectMethod(builder, setIsStrongBoxBackedMethod, JNI_TRUE); 223 | } 224 | 225 | if (android_get_device_api_level() >= 31) { 226 | if (includeProps) { 227 | jmethodID setDevicePropertiesAttestationIncludedMethod = env->GetMethodID(builderClass, "setDevicePropertiesAttestationIncluded", "(Z)Landroid/security/keystore/KeyGenParameterSpec$Builder;"); 228 | env->CallObjectMethod(builder, setDevicePropertiesAttestationIncludedMethod, JNI_TRUE); 229 | } 230 | 231 | if (attestKeyAlias != NULL && !attestKey) { 232 | jmethodID setAttestKeyAliasMethod = env->GetMethodID(builderClass, "setAttestKeyAlias", "(Ljava/lang/String;)Landroid/security/keystore/KeyGenParameterSpec$Builder;"); 233 | env->CallObjectMethod(builder, setAttestKeyAliasMethod, attestKeyAlias); 234 | } 235 | 236 | if (attestKey) { 237 | jmethodID setCertificateSubjectMethod = env->GetMethodID(builderClass, "setCertificateSubject", "(Ljavax/security/auth/x500/X500Principal;)Landroid/security/keystore/KeyGenParameterSpec$Builder;"); 238 | jclass x500PrincipalClass = env->FindClass("javax/security/auth/x500/X500Principal"); 239 | jmethodID x500PrincipalConstructor = env->GetMethodID(x500PrincipalClass, "", "(Ljava/lang/String;)V"); 240 | jobject x500Principal = env->NewObject(x500PrincipalClass, x500PrincipalConstructor, env->NewStringUTF("CN=App Attest Key")); 241 | SAFE_FAILIURE_RETURN_VOID(env, x500Principal); 242 | env->CallObjectMethod(builder, setCertificateSubjectMethod, x500Principal); 243 | } 244 | } 245 | 246 | jclass keyPairGeneratorClass = SAFE_FIND_CLASS(env, "java/security/KeyPairGenerator"); 247 | jmethodID getInstanceMethod = SAFE_GET_STATIC_METHOD_ID(env, keyPairGeneratorClass, "getInstance", "(Ljava/lang/String;Ljava/lang/String;)Ljava/security/KeyPairGenerator;"); 248 | jobject keyPairGenerator = env->CallStaticObjectMethod(keyPairGeneratorClass, getInstanceMethod, env->NewStringUTF("EC"), env->NewStringUTF("AndroidKeyStore")); 249 | SAFE_FAILIURE_RETURN_VOID(env, keyPairGenerator); 250 | 251 | jmethodID initializeMethod = SAFE_GET_METHOD_ID(env, keyPairGeneratorClass, "initialize", "(Ljava/security/spec/AlgorithmParameterSpec;)V"); 252 | jmethodID buildMethod = SAFE_GET_METHOD_ID(env, builderClass, "build", "()Landroid/security/keystore/KeyGenParameterSpec;"); 253 | env->CallVoidMethod(keyPairGenerator, initializeMethod, env->CallObjectMethod(builder, buildMethod)); 254 | 255 | jmethodID generateKeyPairMethod = SAFE_GET_METHOD_ID(env, keyPairGeneratorClass, "generateKeyPair", "()Ljava/security/KeyPair;"); 256 | env->CallObjectMethod(keyPairGenerator, generateKeyPairMethod); 257 | } 258 | 259 | KeyAttestation::AttestationResult KeyAttestation::StartAttestation(JNIEnv* env, jboolean useStrongBox, jboolean includeProps, jboolean useAttestKey) { 260 | auto AddToArray = [env](jobjectArray array, jobject element) -> jobjectArray { 261 | jsize length = env->GetArrayLength(array); 262 | jobjectArray newArray = env->NewObjectArray(length + 1, env->GetObjectClass(element), NULL); 263 | 264 | for (jsize i = 0; i < length; i++) { 265 | env->SetObjectArrayElement(newArray, i, env->GetObjectArrayElement(array, i)); 266 | } 267 | 268 | env->SetObjectArrayElement(newArray, length, element); 269 | return newArray; 270 | }; 271 | 272 | jclass certClass = SAFE_FIND_CLASS(env, "java/security/cert/Certificate"); 273 | jobjectArray certs = env->NewObjectArray(0, certClass, nullptr); 274 | jstring alias = env->NewStringUTF("reveny"); 275 | jstring attestKeyAlias = useAttestKey ? env->NewStringUTF("reveny_persistent") : nullptr; 276 | 277 | jclass keyStoreClass = SAFE_FIND_CLASS(env, "java/security/KeyStore"); 278 | jmethodID getInstanceMethod = SAFE_GET_STATIC_METHOD_ID(env, keyStoreClass, "getInstance", "(Ljava/lang/String;)Ljava/security/KeyStore;"); 279 | jobject keyStore = env->CallStaticObjectMethod(keyStoreClass, getInstanceMethod, env->NewStringUTF("AndroidKeyStore")); 280 | SAFE_FAILIURE_RETURN_VALUE(env, keyStore, AttestationResult::Error); 281 | 282 | jmethodID loadMethod = SAFE_GET_METHOD_ID(env, keyStoreClass, "load", "(Ljava/security/KeyStore$LoadStoreParameter;)V"); 283 | env->CallVoidMethod(keyStore, loadMethod, nullptr); 284 | SAFE_JNI_CHECK_VALUE(env, AttestationResult::Error); 285 | 286 | if (useAttestKey) { 287 | jmethodID containsAliasMethod = SAFE_GET_METHOD_ID(env, keyStoreClass, "containsAlias", "(Ljava/lang/String;)Z"); 288 | jboolean hasAttestKey = env->CallBooleanMethod(keyStore, containsAliasMethod, attestKeyAlias); 289 | SAFE_JNI_CHECK_VALUE(env, AttestationResult::Error); 290 | 291 | if (!hasAttestKey) { 292 | GenerateKey(env, attestKeyAlias, useStrongBox, includeProps, attestKeyAlias); 293 | } 294 | } 295 | GenerateKey(env, alias, useStrongBox, includeProps, attestKeyAlias); 296 | 297 | jmethodID getCertificateChainMethod = SAFE_GET_METHOD_ID(env, keyStoreClass, "getCertificateChain", "(Ljava/lang/String;)[Ljava/security/cert/Certificate;"); 298 | jobjectArray certificateChain = static_cast(env->CallObjectMethod(keyStore, getCertificateChainMethod, useAttestKey ? attestKeyAlias : alias)); 299 | SAFE_FAILIURE_RETURN_VALUE(env, certificateChain, AttestationResult::Error); 300 | 301 | jclass certificateFactoryClass = SAFE_FIND_CLASS(env, "java/security/cert/CertificateFactory"); 302 | jmethodID getInstanceCFMethod = SAFE_GET_STATIC_METHOD_ID(env, certificateFactoryClass, "getInstance", "(Ljava/lang/String;)Ljava/security/cert/CertificateFactory;"); 303 | jobject cf = env->CallStaticObjectMethod(certificateFactoryClass, getInstanceCFMethod, env->NewStringUTF("X.509")); 304 | SAFE_FAILIURE_RETURN_VALUE(env, cf, AttestationResult::Error); 305 | 306 | jclass byteArrayInputStreamClass = SAFE_FIND_CLASS(env, "java/io/ByteArrayInputStream"); 307 | jmethodID byteArrayInputStreamConstructor = SAFE_GET_METHOD_ID(env, byteArrayInputStreamClass, "", "([B)V"); 308 | jmethodID generateCertificateMethod = SAFE_GET_METHOD_ID(env, certificateFactoryClass, "generateCertificate", "(Ljava/io/InputStream;)Ljava/security/cert/Certificate;"); 309 | 310 | jsize chainLength = env->GetArrayLength(certificateChain); 311 | for (jsize i = 0; i < chainLength; i++) { 312 | jobject cert = env->GetObjectArrayElement(certificateChain, i); 313 | jmethodID getEncodedMethod = SAFE_GET_METHOD_ID(env, certClass, "getEncoded", "()[B"); 314 | jbyteArray encodedCert = static_cast(env->CallObjectMethod(cert, getEncodedMethod)); 315 | SAFE_FAILIURE_RETURN_VALUE(env, encodedCert, AttestationResult::Error); 316 | 317 | jobject inputStream = env->NewObject(byteArrayInputStreamClass, byteArrayInputStreamConstructor, encodedCert); 318 | SAFE_FAILIURE_RETURN_VALUE(env, inputStream, AttestationResult::Error); 319 | 320 | jobject x509Cert = env->CallObjectMethod(cf, generateCertificateMethod, inputStream); 321 | SAFE_FAILIURE_RETURN_VALUE(env, x509Cert, AttestationResult::Error); 322 | 323 | certs = AddToArray(certs, x509Cert); 324 | } 325 | 326 | jobjectArray x509Certs = env->NewObjectArray(0, env->FindClass("java/security/cert/X509Certificate"), NULL); 327 | jsize length = env->GetArrayLength(certs); 328 | for (jsize i = 0; i < length; i++) { 329 | jobject cert = env->GetObjectArrayElement(certs, i); 330 | 331 | if (env->IsInstanceOf(cert, env->FindClass("java/security/cert/X509Certificate"))) { 332 | // Add the certificate to the x509Certs array. 333 | x509Certs = AddToArray(x509Certs, cert); 334 | } 335 | } 336 | 337 | // LOGI("StartAttestation -> Size: %d", env->GetArrayLength(x509Certs)); 338 | return ParseCertificateChain(env, x509Certs); 339 | } -------------------------------------------------------------------------------- /app/src/main/jni/KeyAttestation/KeyAttestation.hpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by reveny on 29/12/2023. 3 | // 4 | #pragma once 5 | 6 | #include 7 | #include 8 | 9 | #include "RootOfTrust.hpp" 10 | 11 | namespace KeyAttestation { 12 | constexpr const int KM_BYTES = 9 << 28; 13 | constexpr const int KM_ENUM_REP = 2 << 28; 14 | constexpr const int KM_TAG_ROOT_OF_TRUST = KM_BYTES | 704; 15 | constexpr const int KM_TAG_PURPOSE = KM_ENUM_REP | 1; 16 | constexpr const int KEYMASTER_TAG_TYPE_MASK = 0x0FFFFFFF; 17 | constexpr const int ATTESTATION_CHALLENGE_INDEX = 4; 18 | constexpr const int SW_ENFORCED_INDEX = 6; 19 | constexpr const int TEE_ENFORCED_INDEX = 7; 20 | 21 | const std::string EAT_OID = "1.3.6.1.4.1.11129.2.1.25"; 22 | const std::string ASN1_OID = "1.3.6.1.4.1.11129.2.1.17"; 23 | const std::string CRL_DP_OID = "2.5.29.31"; 24 | 25 | extern jbyteArray attestationChallenge; 26 | 27 | enum AttestationResult { 28 | Error = -1, 29 | CriticalError = -2, 30 | Locked = 1, 31 | Unlocked = 0, 32 | }; 33 | extern AttestationResult attestationResult; 34 | extern std::string outData; 35 | 36 | jobject ParseAsn1Encodable(JNIEnv* env, jobject parser); 37 | jobject ParseAsn1TaggedObject(JNIEnv* env, jobject parser); 38 | jobject GetAttestationSequence(JNIEnv* env, jobject x509Cert); 39 | 40 | class Attest { 41 | public: 42 | std::set purposes; 43 | RootOfTrust* rootOfTrust; 44 | 45 | Attest(JNIEnv* env, jobject sequence) : rootOfTrust(nullptr) { 46 | jclass sequenceClass = SAFE_FIND_CLASS(env, "org/bouncycastle/asn1/ASN1Sequence"); 47 | SAFE_FAILIURE_RETURN_VOID(env, sequenceClass); 48 | 49 | if (!env->IsInstanceOf(sequence, sequenceClass)) { 50 | SAFE_THROW(env, "java/lang/IllegalArgumentException", "Expected sequence for authorization list"); 51 | return; 52 | } 53 | 54 | jmethodID parserMethod = SAFE_GET_METHOD_ID(env, sequenceClass, "parser", "()Lorg/bouncycastle/asn1/ASN1SequenceParser;"); 55 | SAFE_FAILIURE_RETURN_VOID(env, parserMethod); 56 | 57 | jobject parser = env->CallObjectMethod(sequence, parserMethod); 58 | SAFE_FAILIURE_RETURN_VOID(env, parser); 59 | 60 | jobject entry = ParseAsn1TaggedObject(env, parser); 61 | while (entry != nullptr) { 62 | jclass taggedObjectClass = SAFE_FIND_CLASS(env, "org/bouncycastle/asn1/ASN1TaggedObject"); 63 | SAFE_FAILIURE_RETURN_VOID(env, taggedObjectClass); 64 | 65 | jmethodID getTagNoMethod = SAFE_GET_METHOD_ID(env, taggedObjectClass, "getTagNo", "()I"); 66 | SAFE_FAILIURE_RETURN_VOID(env, getTagNoMethod); 67 | 68 | jmethodID getBaseObjectMethod = SAFE_GET_METHOD_ID(env, taggedObjectClass, "getBaseObject", "()Lorg/bouncycastle/asn1/ASN1Object;"); 69 | SAFE_FAILIURE_RETURN_VOID(env, getBaseObjectMethod); 70 | 71 | int tag = env->CallIntMethod(entry, getTagNoMethod); 72 | SAFE_JNI_CHECK(env); 73 | 74 | jobject value = env->CallObjectMethod(entry, getBaseObjectMethod); 75 | SAFE_FAILIURE_RETURN_VOID(env, value); 76 | 77 | switch (tag) { 78 | case KM_TAG_PURPOSE & KEYMASTER_TAG_TYPE_MASK: 79 | purposes = Asn1Utils::GetIntegersFromAsn1Set(env, value); 80 | break; 81 | case KM_TAG_ROOT_OF_TRUST & KEYMASTER_TAG_TYPE_MASK: 82 | rootOfTrust = new RootOfTrust(env, value); 83 | break; 84 | } 85 | 86 | entry = ParseAsn1TaggedObject(env, parser); // Move to the next entry 87 | } 88 | } 89 | 90 | ~Attest() { 91 | delete rootOfTrust; // Ensure proper cleanup 92 | } 93 | }; 94 | 95 | extern std::unique_ptr softwareEnforced; 96 | extern std::unique_ptr teeEnforced; 97 | 98 | void Asn1Attestation(JNIEnv* env, jobject cert); 99 | void LoadFromCert(JNIEnv* env, jobject cert); 100 | std::string VerifiedBootStateToString(int verifiedBootState); 101 | 102 | void CheckStatus(JNIEnv* env, jobject cert, jobject parentKey); 103 | bool CheckAttestation(JNIEnv* env, jobject certificate); 104 | void GenerateKey(JNIEnv* env, jstring alias, jboolean useStrongBox, jboolean includeProps, jstring attestKeyAlias); 105 | 106 | AttestationResult ParseCertificateChain(JNIEnv* env, jobjectArray certs); 107 | AttestationResult StartAttestation(JNIEnv* env, jboolean useStrongBox, jboolean includeProps, jboolean useAttestKey); 108 | } 109 | -------------------------------------------------------------------------------- /app/src/main/jni/KeyAttestation/RootOfTrust.hpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by reveny on 29/12/2023. 3 | // 4 | #pragma once 5 | 6 | #include "Asn1Utils.hpp" 7 | #include 8 | #include 9 | 10 | class RootOfTrust { 11 | public: 12 | static const int VERIFIED_BOOT_KEY_INDEX = 0; 13 | static const int DEVICE_LOCKED_INDEX = 1; 14 | static const int VERIFIED_BOOT_STATE_INDEX = 2; 15 | 16 | enum VerifiedBootState { 17 | KM_VERIFIED_BOOT_VERIFIED = 0, 18 | KM_VERIFIED_BOOT_SELF_SIGNED = 1, 19 | KM_VERIFIED_BOOT_UNVERIFIED = 2, 20 | KM_VERIFIED_BOOT_FAILED = 3, 21 | }; 22 | 23 | jbyteArray verifiedBootKey; 24 | bool deviceLocked = true; 25 | VerifiedBootState verifiedBootState; 26 | 27 | RootOfTrust(JNIEnv *env, jobject asn1Encodable) { 28 | jclass sequenceClass = env->FindClass("org/bouncycastle/asn1/ASN1Sequence"); 29 | if (!env->IsInstanceOf(asn1Encodable, sequenceClass)) { 30 | SAFE_THROW(env, "java/lang/IllegalArgumentException", "Expected sequence for authorization list") 31 | } 32 | 33 | jmethodID getObjectAtMethod = env->GetMethodID(sequenceClass, "getObjectAt", "(I)Lorg/bouncycastle/asn1/ASN1Encodable;"); 34 | verifiedBootKey = Asn1Utils::GetByteArrayFromAsn1(env, env->CallObjectMethod(asn1Encodable, getObjectAtMethod, VERIFIED_BOOT_KEY_INDEX)); 35 | deviceLocked = Asn1Utils::GetBooleanFromAsn1(env, env->CallObjectMethod(asn1Encodable, getObjectAtMethod, DEVICE_LOCKED_INDEX)); 36 | verifiedBootState = (VerifiedBootState) Asn1Utils::GetIntegerFromAsn1(env, env->CallObjectMethod(asn1Encodable, getObjectAtMethod, VERIFIED_BOOT_STATE_INDEX)); 37 | } 38 | 39 | bool isDeviceLocked() { 40 | return deviceLocked; 41 | } 42 | 43 | int getVerifiedBootState() { 44 | return verifiedBootState; 45 | } 46 | 47 | std::string getVerifiedBootStateString() { 48 | switch (verifiedBootState) { 49 | case VerifiedBootState::KM_VERIFIED_BOOT_VERIFIED: return "Verified"; 50 | case VerifiedBootState::KM_VERIFIED_BOOT_SELF_SIGNED: return "Self Signed"; 51 | case VerifiedBootState::KM_VERIFIED_BOOT_UNVERIFIED: return "Unverified"; 52 | case VerifiedBootState::KM_VERIFIED_BOOT_FAILED: return "Failed"; 53 | } 54 | } 55 | }; -------------------------------------------------------------------------------- /app/src/main/jni/Main.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by reveny on 19/02/2024. 3 | // 4 | 5 | #include 6 | #include "KeyAttestation/KeyAttestation.hpp" 7 | 8 | extern "C" { 9 | JNIEXPORT jstring JNICALL 10 | Java_com_reveny_nativekeyattestation_MainActivity_getAttestationResult(JNIEnv *env, jobject thiz) 11 | { 12 | KeyAttestation::AttestationResult result = KeyAttestation::StartAttestation(env, false, false, false); 13 | 14 | if (result == KeyAttestation::AttestationResult::Error || result == KeyAttestation::AttestationResult::CriticalError) { 15 | return env->NewStringUTF("Could not run Attestation. See Log for reason."); 16 | } 17 | 18 | return env->NewStringUTF(KeyAttestation::outData.c_str()); 19 | } 20 | } -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 18 | 19 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reveny/Android-Native-KeyAttestation/bddc054b667dff5d9457a4b2fd2c85aed87cce83/app/src/main/res/mipmap-hdpi/ic_launcher.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reveny/Android-Native-KeyAttestation/bddc054b667dff5d9457a4b2fd2c85aed87cce83/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reveny/Android-Native-KeyAttestation/bddc054b667dff5d9457a4b2fd2c85aed87cce83/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reveny/Android-Native-KeyAttestation/bddc054b667dff5d9457a4b2fd2c85aed87cce83/app/src/main/res/mipmap-mdpi/ic_launcher.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reveny/Android-Native-KeyAttestation/bddc054b667dff5d9457a4b2fd2c85aed87cce83/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reveny/Android-Native-KeyAttestation/bddc054b667dff5d9457a4b2fd2c85aed87cce83/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reveny/Android-Native-KeyAttestation/bddc054b667dff5d9457a4b2fd2c85aed87cce83/app/src/main/res/mipmap-xhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reveny/Android-Native-KeyAttestation/bddc054b667dff5d9457a4b2fd2c85aed87cce83/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reveny/Android-Native-KeyAttestation/bddc054b667dff5d9457a4b2fd2c85aed87cce83/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reveny/Android-Native-KeyAttestation/bddc054b667dff5d9457a4b2fd2c85aed87cce83/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reveny/Android-Native-KeyAttestation/bddc054b667dff5d9457a4b2fd2c85aed87cce83/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reveny/Android-Native-KeyAttestation/bddc054b667dff5d9457a4b2fd2c85aed87cce83/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reveny/Android-Native-KeyAttestation/bddc054b667dff5d9457a4b2fd2c85aed87cce83/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reveny/Android-Native-KeyAttestation/bddc054b667dff5d9457a4b2fd2c85aed87cce83/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.webp -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/reveny/Android-Native-KeyAttestation/bddc054b667dff5d9457a4b2fd2c85aed87cce83/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /app/src/main/res/values-night/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #FF000000 4 | #FFFFFFFF 5 | -------------------------------------------------------------------------------- /app/src/main/res/values/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #CAD9E2 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | Native KeyAttestation 3 | -------------------------------------------------------------------------------- /app/src/main/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 8 |