├── .github └── workflows │ ├── build-kdoc.yml │ ├── codeql.yml │ ├── dependent-issues.yml │ └── test-dev.yml ├── .gitignore ├── .tx └── config ├── AUTHORS ├── LICENSE ├── README.md ├── build.gradle.kts ├── gradle.properties ├── gradle ├── libs.versions.toml └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── jitpack.yml ├── lib ├── .gitignore ├── build.gradle.kts └── src │ ├── androidTest │ ├── AndroidManifest.xml │ └── java │ │ └── at │ │ └── bitfire │ │ └── cert4android │ │ ├── ConscryptTest.kt │ │ ├── CustomCertManagerTest.kt │ │ ├── CustomCertStoreTest.kt │ │ ├── TestCertificates.kt │ │ └── UserDecisionRegistryTest.kt │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── at │ │ │ └── bitfire │ │ │ └── cert4android │ │ │ ├── Cert4Android.kt │ │ │ ├── CertUtils.kt │ │ │ ├── ConscryptIntegration.kt │ │ │ ├── CustomCertManager.kt │ │ │ ├── CustomCertStore.kt │ │ │ ├── NotificationUtils.kt │ │ │ ├── TrustCertificateActivity.kt │ │ │ └── UserDecisionRegistry.kt │ └── res │ │ ├── drawable │ │ └── ic_lock_open_white.xml │ │ ├── values-ar │ │ └── strings.xml │ │ ├── values-bg │ │ └── strings.xml │ │ ├── values-ca │ │ └── strings.xml │ │ ├── values-cs │ │ └── strings.xml │ │ ├── values-da │ │ └── strings.xml │ │ ├── values-de │ │ └── strings.xml │ │ ├── values-el │ │ └── strings.xml │ │ ├── values-es │ │ └── strings.xml │ │ ├── values-eu │ │ └── strings.xml │ │ ├── values-fa │ │ └── strings.xml │ │ ├── values-fi │ │ └── strings.xml │ │ ├── values-fr │ │ └── strings.xml │ │ ├── values-gl │ │ └── strings.xml │ │ ├── values-hu │ │ └── strings.xml │ │ ├── values-it │ │ └── strings.xml │ │ ├── values-ja │ │ └── strings.xml │ │ ├── values-nb-rNO │ │ └── strings.xml │ │ ├── values-nl │ │ └── strings.xml │ │ ├── values-pl │ │ └── strings.xml │ │ ├── values-pt │ │ └── strings.xml │ │ ├── values-ru │ │ └── strings.xml │ │ ├── values-sk │ │ └── strings.xml │ │ ├── values-sl-rSI │ │ └── strings.xml │ │ ├── values-sr │ │ └── strings.xml │ │ ├── values-szl │ │ └── strings.xml │ │ ├── values-tr │ │ └── strings.xml │ │ ├── values-uk │ │ └── strings.xml │ │ ├── values-vi │ │ └── strings.xml │ │ ├── values-zh-rTW │ │ └── strings.xml │ │ ├── values-zh │ │ └── strings.xml │ │ └── values │ │ ├── about_strings.xml │ │ └── strings.xml │ └── test │ ├── java │ └── at │ │ └── bitfire │ │ └── cert4android │ │ └── CertUtilsTest.kt │ └── resources │ └── davdroid-web.crt ├── run-tests.sh ├── sample-app ├── .gitignore ├── build.gradle.kts └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── at │ │ └── bitfire │ │ └── cert4android │ │ └── demo │ │ └── MainActivity.kt │ └── res │ ├── drawable-v24 │ └── ic_launcher_foreground.xml │ ├── drawable │ └── ic_launcher_background.xml │ ├── mipmap-anydpi-v26 │ ├── ic_launcher.xml │ └── ic_launcher_round.xml │ ├── mipmap-hdpi │ ├── ic_launcher.webp │ └── ic_launcher_round.webp │ ├── mipmap-mdpi │ ├── ic_launcher.webp │ └── ic_launcher_round.webp │ ├── mipmap-xhdpi │ ├── ic_launcher.webp │ └── ic_launcher_round.webp │ ├── mipmap-xxhdpi │ ├── ic_launcher.webp │ └── ic_launcher_round.webp │ ├── mipmap-xxxhdpi │ ├── ic_launcher.webp │ └── ic_launcher_round.webp │ └── values │ └── strings.xml └── settings.gradle /.github/workflows/build-kdoc.yml: -------------------------------------------------------------------------------- 1 | name: Build KDoc 2 | on: 3 | push: 4 | branches: [main] 5 | 6 | # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages 7 | permissions: 8 | contents: read 9 | pages: write 10 | id-token: write 11 | 12 | jobs: 13 | build: 14 | name: Build and publish KDoc 15 | runs-on: ubuntu-latest 16 | steps: 17 | - uses: actions/checkout@v4 18 | - uses: actions/setup-java@v4 19 | with: 20 | distribution: temurin 21 | java-version: 21 22 | cache: gradle 23 | - uses: gradle/actions/setup-gradle@v3 24 | 25 | - name: Build KDoc 26 | run: ./gradlew --no-daemon --no-configuration-cache cert4android:dokkaHtml 27 | 28 | - name: Publish KDoc 29 | if: success() 30 | uses: actions/upload-pages-artifact@v3 31 | with: 32 | path: lib/build/dokka/html 33 | 34 | deploy: 35 | environment: 36 | name: github-pages 37 | url: ${{ steps.deployment.outputs.page_url }} 38 | runs-on: ubuntu-latest 39 | needs: build 40 | steps: 41 | - name: Deploy to GitHub Pages 42 | id: deployment 43 | uses: actions/deploy-pages@v4 44 | -------------------------------------------------------------------------------- /.github/workflows/codeql.yml: -------------------------------------------------------------------------------- 1 | name: "CodeQL" 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | # The branches below must be a subset of the branches above 8 | branches: [ "main" ] 9 | schedule: 10 | - cron: '30 8 * * 6' 11 | 12 | jobs: 13 | analyze: 14 | name: Analyze 15 | runs-on: ubuntu-latest 16 | permissions: 17 | actions: read 18 | contents: read 19 | security-events: write 20 | 21 | strategy: 22 | fail-fast: false 23 | matrix: 24 | language: [ 'java' ] 25 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 26 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support 27 | 28 | steps: 29 | - name: Checkout repository 30 | uses: actions/checkout@v4 31 | - uses: actions/setup-java@v4 32 | with: 33 | distribution: temurin 34 | java-version: 21 35 | cache: gradle 36 | - uses: gradle/actions/setup-gradle@v3 37 | 38 | # Initializes the CodeQL tools for scanning. 39 | - name: Initialize CodeQL 40 | uses: github/codeql-action/init@v3 41 | with: 42 | languages: ${{ matrix.language }} 43 | # If you wish to specify custom queries, you can do so here or in a config file. 44 | # By default, queries listed here will override any specified in a config file. 45 | # Prefix the list here with "+" to use these queries and those in the config file. 46 | 47 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs 48 | # queries: security-extended,security-and-quality 49 | 50 | # Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java). 51 | # If this step fails, then you should remove it and run the build manually (see below) 52 | # - name: Autobuild 53 | # uses: github/codeql-action/autobuild@v2 54 | 55 | - name: Build 56 | run: ./gradlew --no-daemon cert4android:assemble 57 | 58 | - name: Perform CodeQL Analysis 59 | uses: github/codeql-action/analyze@v3 60 | with: 61 | category: "/language:${{matrix.language}}" -------------------------------------------------------------------------------- /.github/workflows/dependent-issues.yml: -------------------------------------------------------------------------------- 1 | name: Dependent Issues 2 | 3 | on: 4 | issues: 5 | types: 6 | - opened 7 | - edited 8 | - closed 9 | - reopened 10 | pull_request_target: 11 | types: 12 | - opened 13 | - edited 14 | - closed 15 | - reopened 16 | # Makes sure we always add status check for PRs. Useful only if 17 | # this action is required to pass before merging. Otherwise, it 18 | # can be removed. 19 | - synchronize 20 | 21 | # Schedule a daily check. Useful if you reference cross-repository 22 | # issues or pull requests. Otherwise, it can be removed. 23 | schedule: 24 | - cron: '12 9 * * *' 25 | 26 | permissions: write-all 27 | 28 | jobs: 29 | check: 30 | runs-on: ubuntu-latest 31 | steps: 32 | - uses: z0al/dependent-issues@v1 33 | env: 34 | # (Required) The token to use to make API calls to GitHub. 35 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 36 | # (Optional) The token to use to make API calls to GitHub for remote repos. 37 | GITHUB_READ_TOKEN: ${{ secrets.DEPENDENT_ISSUES_READ_TOKEN }} 38 | 39 | with: 40 | # (Optional) The label to use to mark dependent issues 41 | # label: dependent 42 | 43 | # (Optional) Enable checking for dependencies in issues. 44 | # Enable by setting the value to "on". Default "off" 45 | check_issues: on 46 | 47 | # (Optional) A comma-separated list of keywords. Default 48 | # "depends on, blocked by" 49 | keywords: depends on, blocked by 50 | 51 | # (Optional) A custom comment body. It supports `{{ dependencies }}` token. 52 | comment: > 53 | This PR/issue depends on: 54 | 55 | {{ dependencies }} 56 | -------------------------------------------------------------------------------- /.github/workflows/test-dev.yml: -------------------------------------------------------------------------------- 1 | name: Development tests 2 | on: push 3 | concurrency: 4 | group: ${{ github.workflow }}-${{ github.ref }} 5 | cancel-in-progress: true 6 | jobs: 7 | 8 | test: 9 | name: Tests without emulator 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v4 13 | - uses: actions/setup-java@v4 14 | with: 15 | distribution: temurin 16 | java-version: 21 17 | cache: gradle 18 | - uses: gradle/actions/setup-gradle@v3 19 | 20 | - name: Check 21 | run: ./gradlew cert4android:check 22 | 23 | test_on_emulator: 24 | name: Tests with emulator 25 | runs-on: ubuntu-latest 26 | steps: 27 | - uses: actions/checkout@v4 28 | - uses: actions/setup-java@v4 29 | with: 30 | distribution: temurin 31 | java-version: 21 32 | cache: gradle 33 | - uses: gradle/actions/setup-gradle@v3 34 | 35 | - name: Enable KVM group perms 36 | run: | 37 | echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules 38 | sudo udevadm control --reload-rules 39 | sudo udevadm trigger --name-match=kvm 40 | 41 | - name: Cache AVD 42 | uses: actions/cache@v4 43 | with: 44 | path: ~/.config/.android/avd 45 | key: avd-${{ hashFiles('lib/build.gradle.kts') }} # gradle-managed devices are defined there 46 | 47 | - name: Run device tests 48 | run: ./gradlew --no-daemon virtualCheck 49 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .gradle 3 | /.idea/ 4 | /build 5 | /captures 6 | /.kotlin 7 | /local.properties 8 | -------------------------------------------------------------------------------- /.tx/config: -------------------------------------------------------------------------------- 1 | [main] 2 | host = https://www.transifex.com 3 | 4 | [davx5.cert4android] 5 | file_filter = src/main/res/values-/strings.xml 6 | minimum_perc = 0 7 | source_file = src/main/res/values/strings.xml 8 | source_lang = en 9 | trans.tr_TR = src/main/res/values-tr/strings.xml 10 | trans.zh_CN = src/main/res/values-zh/strings.xml 11 | type = ANDROID 12 | 13 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | 2 | Initial contributor: 3 | Ricki Hirner (bitfire.at) 4 | -------------------------------------------------------------------------------- /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 | 2 | [![License](https://img.shields.io/github/license/bitfireAT/cert4android)](https://github.com/bitfireAT/cert4android/blob/main/LICENSE) 3 | [![Tests](https://github.com/bitfireAT/cert4android/actions/workflows/test-dev.yml/badge.svg)](https://github.com/bitfireAT/cert4android/actions/workflows/test-dev.yml) 4 | [![KDoc](https://img.shields.io/badge/documentation-KDoc-informational)](https://bitfireat.github.io/cert4android/) 5 | [![Latest Version](https://img.shields.io/jitpack/version/com.github.bitfireAT/cert4android)](https://jitpack.io/#bitfireAT/cert4android) 6 | 7 | 8 | _This software is not affiliated to, nor has it been authorized, sponsored or otherwise approved 9 | by Google LLC. Android is a trademark of Google LLC._ 10 | 11 | 12 | # cert4android 13 | 14 | cert4android is a library for Android to manage custom certificates which has 15 | been developed for [DAVx⁵](https://www.davx5.com). Feel free to use 16 | it in your own open-source app. 17 | 18 | Generated KDoc: https://bitfireat.github.io/cert4android/ 19 | 20 | For questions, suggestions etc. use [Github discussions](https://github.com/bitfireAT/cert4android/discussions). 21 | We're happy about contributions! In case of bigger changes, please let us know in the discussions before. 22 | Then make the changes in your own repository and send a pull request. 23 | 24 | 25 | # Features 26 | 27 | * uses a service to manage custom certificates 28 | * supports multiple threads and multiple processes (for instance, if you have an UI 29 | and a separate `:sync` process which should share the certificate information) 30 | 31 | 32 | # How to use 33 | 34 | 1. Add the [jitpack.io](https://jitpack.io) repository to your project's level `build.gradle`: 35 | ```groovy 36 | allprojects { 37 | repositories { 38 | // ... more repos 39 | maven { url "https://jitpack.io" } 40 | } 41 | } 42 | ``` 43 | or if you are using `settings.gradle`: 44 | ```groovy 45 | dependencyResolutionManagement { 46 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 47 | repositories { 48 | // ... more repos 49 | maven { url "https://jitpack.io" } 50 | } 51 | } 52 | ``` 53 | 2. Add the dependency to your module's `build.gradle` file: 54 | ```groovy 55 | dependencies { 56 | implementation 'com.github.bitfireAT:cert4android:' 57 | } 58 | ``` 59 | 3. Create an instance of `CustomCertManager` (`Context` is required to connect to the 60 | `CustomCertService`, which manages the custom certificates). 61 | 4. Use this instance as `X509TrustManager` in your calls (for instance, when setting up your HTTP client). 62 | Don't forget to get and use the `hostnameVerifier()`, too. 63 | 5. Close the instance when it's not required anymore (will disconnect from the 64 | `CustomCertService`, thus allowing it to be destroyed). 65 | 66 | Example of initialzing an okhttp client: 67 | 68 | val keyManager = ... 69 | CustomCertManager(...).use { trustManager -> 70 | val sslContext = SSLContext.getInstance("TLS") 71 | sslContext.init( 72 | if (keyManager != null) arrayOf(keyManager) else null, 73 | arrayOf(trustManager), 74 | null 75 | ) 76 | val builder = OkHttpClient.Builder() 77 | builder.sslSocketFactory(sslContext.socketFactory, trustManager) 78 | .hostnameVerifier(hostnameVerifier) 79 | val httpClient = builder.build() 80 | // use httpClient 81 | } 82 | 83 | 84 | You can overwrite resources when you want, just have a look at the `res/strings` 85 | directory. Especially `certificate_notification_connection_security` and 86 | `trust_certificate_unknown_certificate_found` should contain your app name. 87 | 88 | To view the available gradle tasks for the library: `./gradlew cert4android:tasks` 89 | (the `cert4android` module is defined in `settings.gradle`). 90 | 91 | 92 | # License 93 | 94 | Copyright (C) Ricki Hirner and [contributors](https://github.com/bitfireAT/cert4android/graphs/contributors). 95 | 96 | This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome 97 | to redistribute it under the conditions of the [GNU GPL v3](LICENSE). 98 | 99 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | plugins { 3 | alias(libs.plugins.android.application) apply false 4 | alias(libs.plugins.android.library) apply false 5 | alias(libs.plugins.compose.compiler) apply false 6 | alias(libs.plugins.dokka) apply false 7 | alias(libs.plugins.kotlin.android) apply false 8 | } 9 | 10 | group = "at.bitfire" 11 | version = System.getenv("GIT_COMMIT") 12 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # [https://developer.android.com/build/optimize-your-build#optimize] 2 | org.gradle.daemon=true 3 | org.gradle.jvmargs=-Xmx4g -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 -XX:+UseParallelGC -XX:MaxMetaspaceSize=512m 4 | org.gradle.parallel=true 5 | 6 | # configuration cache [https://developer.android.com/build/optimize-your-build#use-the-configuration-cache-experimental] 7 | org.gradle.unsafe.configuration-cache=true 8 | org.gradle.unsafe.configuration-cache-problems=warn 9 | 10 | # Android 11 | android.useAndroidX=true 12 | -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | agp = "8.9.1" 3 | androidx-activityCompose = "1.10.1" 4 | androidx-appcompat = "1.7.0" 5 | androidx-core = "1.16.0" 6 | androidx-lifecycle = "2.8.7" 7 | androidx-test-core = "1.6.1" 8 | androidx-test-runner = "1.6.2" 9 | androidx-test-rules = "1.6.1" 10 | # don't update to 2.5.3 / until https://github.com/google/conscrypt/issues/1268 is fixed 11 | #noinspection GradleDependency 12 | conscrypt = "2.5.2" 13 | compose-bom = "2025.04.00" 14 | dokka = "1.9.20" 15 | junit = "4.13.2" 16 | kotlin = "2.1.20" 17 | mockk = "1.14.0" 18 | okhttp3 = "4.12.0" 19 | 20 | [libraries] 21 | androidx-activityCompose = { module = "androidx.activity:activity-compose", version.ref = "androidx-activityCompose" } 22 | androidx-appcompat = { module = "androidx.appcompat:appcompat", version.ref = "androidx-appcompat" } 23 | androidx-core = { module = "androidx.core:core-ktx", version.ref = "androidx-core" } 24 | androidx-lifecycle-livedata = { module = "androidx.lifecycle:lifecycle-livedata-ktx", version.ref = "androidx-lifecycle" } 25 | androidx-lifecycle-runtime = { module = "androidx.lifecycle:lifecycle-runtime-ktx", version.ref = "androidx-lifecycle" } 26 | androidx-lifecycle-viewmodel = { module = "androidx.lifecycle:lifecycle-viewmodel-ktx", version.ref = "androidx-lifecycle" } 27 | androidx-test-core = { module = "androidx.test:core-ktx", version.ref = "androidx-test-core" } 28 | androidx-test-runner = { module = "androidx.test:runner", version.ref = "androidx-test-runner" } 29 | androidx-test-rules = { module = "androidx.test:rules", version.ref = "androidx-test-rules" } 30 | compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "compose-bom" } 31 | compose-material3 = { module = "androidx.compose.material3:material3" } 32 | compose-runtime-livedata = { module = "androidx.compose.runtime:runtime-livedata" } 33 | compose-ui-base = { module = "androidx.compose.ui:ui" } 34 | compose-ui-graphics = { module = "androidx.compose.ui:ui-graphics" } 35 | compose-ui-tooling = { module = "androidx.compose.ui:ui-tooling" } 36 | compose-ui-toolingPreview = { module = "androidx.compose.ui:ui-tooling-preview" } 37 | conscrypt = { module = "org.conscrypt:conscrypt-android", version.ref = "conscrypt" } 38 | junit = { module = "junit:junit", version.ref = "junit" } 39 | kotlin-stdlib = { module = "org.jetbrains.kotlin:kotlin-stdlib", version.ref = "kotlin" } 40 | mockk-android = { module = "io.mockk:mockk-android", version.ref = "mockk" } 41 | okttp3-mockwebserver = { module = "com.squareup.okhttp3:mockwebserver", version.ref = "okhttp3" } 42 | 43 | [plugins] 44 | android-application = { id = "com.android.application", version.ref = "agp" } 45 | android-library = { id = "com.android.library", version.ref = "agp" } 46 | compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } 47 | kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } 48 | dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitfireAT/cert4android/b67ba86d313ceb622d7717ad7b587abc74a2caa9/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | # SPDX-License-Identifier: Apache-2.0 19 | # 20 | 21 | ############################################################################## 22 | # 23 | # Gradle start up script for POSIX generated by Gradle. 24 | # 25 | # Important for running: 26 | # 27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 28 | # noncompliant, but you have some other compliant shell such as ksh or 29 | # bash, then to run this script, type that shell name before the whole 30 | # command line, like: 31 | # 32 | # ksh Gradle 33 | # 34 | # Busybox and similar reduced shells will NOT work, because this script 35 | # requires all of these POSIX shell features: 36 | # * functions; 37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 39 | # * compound commands having a testable exit status, especially «case»; 40 | # * various built-in commands including «command», «set», and «ulimit». 41 | # 42 | # Important for patching: 43 | # 44 | # (2) This script targets any POSIX shell, so it avoids extensions provided 45 | # by Bash, Ksh, etc; in particular arrays are avoided. 46 | # 47 | # The "traditional" practice of packing multiple parameters into a 48 | # space-separated string is a well documented source of bugs and security 49 | # problems, so this is (mostly) avoided, by progressively accumulating 50 | # options in "$@", and eventually passing that to Java. 51 | # 52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 54 | # see the in-line comments for details. 55 | # 56 | # There are tweaks for specific operating systems such as AIX, CygWin, 57 | # Darwin, MinGW, and NonStop. 58 | # 59 | # (3) This script is generated from the Groovy template 60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 61 | # within the Gradle project. 62 | # 63 | # You can find Gradle at https://github.com/gradle/gradle/. 64 | # 65 | ############################################################################## 66 | 67 | # Attempt to set APP_HOME 68 | 69 | # Resolve links: $0 may be a link 70 | app_path=$0 71 | 72 | # Need this for daisy-chained symlinks. 73 | while 74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 75 | [ -h "$app_path" ] 76 | do 77 | ls=$( ls -ld "$app_path" ) 78 | link=${ls#*' -> '} 79 | case $link in #( 80 | /*) app_path=$link ;; #( 81 | *) app_path=$APP_HOME$link ;; 82 | esac 83 | done 84 | 85 | # This is normally unused 86 | # shellcheck disable=SC2034 87 | APP_BASE_NAME=${0##*/} 88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s 90 | ' "$PWD" ) || exit 91 | 92 | # Use the maximum available, or set MAX_FD != -1 to use that value. 93 | MAX_FD=maximum 94 | 95 | warn () { 96 | echo "$*" 97 | } >&2 98 | 99 | die () { 100 | echo 101 | echo "$*" 102 | echo 103 | exit 1 104 | } >&2 105 | 106 | # OS specific support (must be 'true' or 'false'). 107 | cygwin=false 108 | msys=false 109 | darwin=false 110 | nonstop=false 111 | case "$( uname )" in #( 112 | CYGWIN* ) cygwin=true ;; #( 113 | Darwin* ) darwin=true ;; #( 114 | MSYS* | MINGW* ) msys=true ;; #( 115 | NONSTOP* ) nonstop=true ;; 116 | esac 117 | 118 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 119 | 120 | 121 | # Determine the Java command to use to start the JVM. 122 | if [ -n "$JAVA_HOME" ] ; then 123 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 124 | # IBM's JDK on AIX uses strange locations for the executables 125 | JAVACMD=$JAVA_HOME/jre/sh/java 126 | else 127 | JAVACMD=$JAVA_HOME/bin/java 128 | fi 129 | if [ ! -x "$JAVACMD" ] ; then 130 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 131 | 132 | Please set the JAVA_HOME variable in your environment to match the 133 | location of your Java installation." 134 | fi 135 | else 136 | JAVACMD=java 137 | if ! command -v java >/dev/null 2>&1 138 | then 139 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 140 | 141 | Please set the JAVA_HOME variable in your environment to match the 142 | location of your Java installation." 143 | fi 144 | fi 145 | 146 | # Increase the maximum file descriptors if we can. 147 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 148 | case $MAX_FD in #( 149 | max*) 150 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 151 | # shellcheck disable=SC2039,SC3045 152 | MAX_FD=$( ulimit -H -n ) || 153 | warn "Could not query maximum file descriptor limit" 154 | esac 155 | case $MAX_FD in #( 156 | '' | soft) :;; #( 157 | *) 158 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 159 | # shellcheck disable=SC2039,SC3045 160 | ulimit -n "$MAX_FD" || 161 | warn "Could not set maximum file descriptor limit to $MAX_FD" 162 | esac 163 | fi 164 | 165 | # Collect all arguments for the java command, stacking in reverse order: 166 | # * args from the command line 167 | # * the main class name 168 | # * -classpath 169 | # * -D...appname settings 170 | # * --module-path (only if needed) 171 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 172 | 173 | # For Cygwin or MSYS, switch paths to Windows format before running java 174 | if "$cygwin" || "$msys" ; then 175 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 176 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 177 | 178 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 179 | 180 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 181 | for arg do 182 | if 183 | case $arg in #( 184 | -*) false ;; # don't mess with options #( 185 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 186 | [ -e "$t" ] ;; #( 187 | *) false ;; 188 | esac 189 | then 190 | arg=$( cygpath --path --ignore --mixed "$arg" ) 191 | fi 192 | # Roll the args list around exactly as many times as the number of 193 | # args, so each arg winds up back in the position where it started, but 194 | # possibly modified. 195 | # 196 | # NB: a `for` loop captures its iteration list before it begins, so 197 | # changing the positional parameters here affects neither the number of 198 | # iterations, nor the values presented in `arg`. 199 | shift # remove old arg 200 | set -- "$@" "$arg" # push replacement arg 201 | done 202 | fi 203 | 204 | 205 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 206 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 207 | 208 | # Collect all arguments for the java command: 209 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 210 | # and any embedded shellness will be escaped. 211 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 212 | # treated as '${Hostname}' itself on the command line. 213 | 214 | set -- \ 215 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 216 | -classpath "$CLASSPATH" \ 217 | org.gradle.wrapper.GradleWrapperMain \ 218 | "$@" 219 | 220 | # Stop when "xargs" is not available. 221 | if ! command -v xargs >/dev/null 2>&1 222 | then 223 | die "xargs is not available" 224 | fi 225 | 226 | # Use "xargs" to parse quoted args. 227 | # 228 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 229 | # 230 | # In Bash we could simply go: 231 | # 232 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 233 | # set -- "${ARGS[@]}" "$@" 234 | # 235 | # but POSIX shell has neither arrays nor command substitution, so instead we 236 | # post-process each arg (as a line of input to sed) to backslash-escape any 237 | # character that might be a shell metacharacter, then use eval to reverse 238 | # that process (while maintaining the separation between arguments), and wrap 239 | # the whole thing up as a single "set" statement. 240 | # 241 | # This will of course break if any of these variables contains a newline or 242 | # an unmatched quote. 243 | # 244 | 245 | eval "set -- $( 246 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 247 | xargs -n1 | 248 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 249 | tr '\n' ' ' 250 | )" '"$@"' 251 | 252 | exec "$JAVACMD" "$@" 253 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | @rem SPDX-License-Identifier: Apache-2.0 17 | @rem 18 | 19 | @if "%DEBUG%"=="" @echo off 20 | @rem ########################################################################## 21 | @rem 22 | @rem Gradle startup script for Windows 23 | @rem 24 | @rem ########################################################################## 25 | 26 | @rem Set local scope for the variables with windows NT shell 27 | if "%OS%"=="Windows_NT" setlocal 28 | 29 | set DIRNAME=%~dp0 30 | if "%DIRNAME%"=="" set DIRNAME=. 31 | @rem This is normally unused 32 | set APP_BASE_NAME=%~n0 33 | set APP_HOME=%DIRNAME% 34 | 35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 37 | 38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 40 | 41 | @rem Find java.exe 42 | if defined JAVA_HOME goto findJavaFromJavaHome 43 | 44 | set JAVA_EXE=java.exe 45 | %JAVA_EXE% -version >NUL 2>&1 46 | if %ERRORLEVEL% equ 0 goto execute 47 | 48 | echo. 1>&2 49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 50 | echo. 1>&2 51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 52 | echo location of your Java installation. 1>&2 53 | 54 | goto fail 55 | 56 | :findJavaFromJavaHome 57 | set JAVA_HOME=%JAVA_HOME:"=% 58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 59 | 60 | if exist "%JAVA_EXE%" goto execute 61 | 62 | echo. 1>&2 63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 64 | echo. 1>&2 65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 66 | echo location of your Java installation. 1>&2 67 | 68 | goto fail 69 | 70 | :execute 71 | @rem Setup the command line 72 | 73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 74 | 75 | 76 | @rem Execute Gradle 77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 78 | 79 | :end 80 | @rem End local scope for the variables with windows NT shell 81 | if %ERRORLEVEL% equ 0 goto mainEnd 82 | 83 | :fail 84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 85 | rem the _cmd.exe /c_ return code! 86 | set EXIT_CODE=%ERRORLEVEL% 87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 89 | exit /b %EXIT_CODE% 90 | 91 | :mainEnd 92 | if "%OS%"=="Windows_NT" endlocal 93 | 94 | :omega 95 | -------------------------------------------------------------------------------- /jitpack.yml: -------------------------------------------------------------------------------- 1 | jdk: 2 | - openjdk21 3 | before_install: 4 | - sdk install java 21.0.2-open 5 | - sdk use java 21.0.2-open -------------------------------------------------------------------------------- /lib/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /lib/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | alias(libs.plugins.android.library) 3 | alias(libs.plugins.compose.compiler) 4 | alias(libs.plugins.dokka) 5 | alias(libs.plugins.kotlin.android) 6 | `maven-publish` 7 | } 8 | 9 | android { 10 | namespace = "at.bitfire.cert4android" 11 | 12 | compileSdk = 35 13 | 14 | defaultConfig { 15 | minSdk = 21 // Android 5 16 | 17 | aarMetadata { 18 | minCompileSdk = 29 19 | } 20 | 21 | testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" 22 | } 23 | 24 | compileOptions { 25 | sourceCompatibility = JavaVersion.VERSION_21 26 | targetCompatibility = JavaVersion.VERSION_21 27 | } 28 | kotlin { 29 | jvmToolchain(21) 30 | } 31 | 32 | buildFeatures { 33 | compose = true 34 | } 35 | 36 | buildTypes { 37 | release { 38 | // Android libraries shouldn't be minified: 39 | // https://developer.android.com/studio/projects/android-library#Considerations 40 | isMinifyEnabled = false 41 | proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt")) 42 | } 43 | } 44 | 45 | lint { 46 | disable += listOf("MissingTranslation", "ExtraTranslation") 47 | } 48 | 49 | @Suppress("UnstableApiUsage") 50 | testOptions { 51 | managedDevices { 52 | localDevices { 53 | create("virtual") { 54 | device = "Pixel 3" 55 | apiLevel = 33 56 | systemImageSource = "aosp-atd" 57 | } 58 | } 59 | } 60 | } 61 | 62 | testFixtures { 63 | enable = true 64 | } 65 | 66 | packaging { 67 | resources { 68 | excludes.add("META-INF/*.md") 69 | } 70 | } 71 | 72 | publishing { 73 | // Configure publish variant 74 | singleVariant("release") { 75 | withSourcesJar() 76 | } 77 | } 78 | } 79 | 80 | publishing { 81 | // Configure publishing data 82 | publications { 83 | register("release", MavenPublication::class.java) { 84 | groupId = "com.github.bitfireAT" 85 | artifactId = "cert4android" 86 | version = System.getenv("GIT_COMMIT") 87 | 88 | afterEvaluate { 89 | from(components["release"]) 90 | } 91 | } 92 | } 93 | } 94 | 95 | dependencies { 96 | implementation(libs.kotlin.stdlib) 97 | 98 | implementation(libs.androidx.appcompat) 99 | implementation(libs.androidx.lifecycle.livedata) 100 | implementation(libs.androidx.lifecycle.viewmodel) 101 | implementation(libs.conscrypt) 102 | 103 | // Jetpack Compose 104 | implementation(libs.androidx.activityCompose) 105 | implementation(platform(libs.compose.bom)) 106 | implementation(libs.compose.material3) 107 | implementation(libs.compose.runtime.livedata) 108 | debugImplementation(libs.compose.ui.tooling) 109 | implementation(libs.compose.ui.toolingPreview) 110 | 111 | androidTestImplementation(libs.androidx.test.core) 112 | androidTestImplementation(libs.androidx.test.runner) 113 | androidTestImplementation(libs.androidx.test.rules) 114 | androidTestImplementation(libs.okttp3.mockwebserver) 115 | androidTestImplementation(libs.mockk.android) 116 | 117 | testImplementation(libs.junit) 118 | } -------------------------------------------------------------------------------- /lib/src/androidTest/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /lib/src/androidTest/java/at/bitfire/cert4android/ConscryptTest.kt: -------------------------------------------------------------------------------- 1 | package at.bitfire.cert4android 2 | 3 | import org.junit.Before 4 | import org.junit.Test 5 | import java.security.cert.CertificateFactory 6 | import java.security.cert.X509Certificate 7 | 8 | class ConscryptTest { 9 | 10 | @Before 11 | fun setUp() { 12 | ConscryptIntegration.initialize() 13 | } 14 | 15 | 16 | @Test 17 | fun test_X509Certificate_toString() { 18 | val certFactory = CertificateFactory.getInstance("X.509") 19 | val testCert = certFactory.generateCertificate(RAW_EXPIRED_CERT.byteInputStream()) as X509Certificate 20 | 21 | // Crashes with Conscrypt 2.5.3 22 | System.err.println(testCert.toString()) 23 | } 24 | 25 | 26 | companion object { 27 | 28 | const val RAW_EXPIRED_CERT = "-----BEGIN CERTIFICATE-----\n" + 29 | "MIIFdDCCBFygAwIBAgIQJ2buVutJ846r13Ci/ITeIjANBgkqhkiG9w0BAQwFADBv\n" + 30 | "MQswCQYDVQQGEwJTRTEUMBIGA1UEChMLQWRkVHJ1c3QgQUIxJjAkBgNVBAsTHUFk\n" + 31 | "ZFRydXN0IEV4dGVybmFsIFRUUCBOZXR3b3JrMSIwIAYDVQQDExlBZGRUcnVzdCBF\n" + 32 | "eHRlcm5hbCBDQSBSb290MB4XDTAwMDUzMDEwNDgzOFoXDTIwMDUzMDEwNDgzOFow\n" + 33 | "gYUxCzAJBgNVBAYTAkdCMRswGQYDVQQIExJHcmVhdGVyIE1hbmNoZXN0ZXIxEDAO\n" + 34 | "BgNVBAcTB1NhbGZvcmQxGjAYBgNVBAoTEUNPTU9ETyBDQSBMaW1pdGVkMSswKQYD\n" + 35 | "VQQDEyJDT01PRE8gUlNBIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkq\n" + 36 | "hkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAkehUktIKVrGsDSTdxc9EZ3SZKzejfSNw\n" + 37 | "AHG8U9/E+ioSj0t/EFa9n3Byt2F/yUsPF6c947AEYe7/EZfH9IY+Cvo+XPmT5jR6\n" + 38 | "2RRr55yzhaCCenavcZDX7P0N+pxs+t+wgvQUfvm+xKYvT3+Zf7X8Z0NyvQwA1onr\n" + 39 | "ayzT7Y+YHBSrfuXjbvzYqOSSJNpDa2K4Vf3qwbxstovzDo2a5JtsaZn4eEgwRdWt\n" + 40 | "4Q08RWD8MpZRJ7xnw8outmvqRsfHIKCxH2XeSAi6pE6p8oNGN4Tr6MyBSENnTnIq\n" + 41 | "m1y9TBsoilwie7SrmNnu4FGDwwlGTm0+mfqVF9p8M1dBPI1R7Qu2XK8sYxrfV8g/\n" + 42 | "vOldxJuvRZnio1oktLqpVj3Pb6r/SVi+8Kj/9Lit6Tf7urj0Czr56ENCHonYhMsT\n" + 43 | "8dm74YlguIwoVqwUHZwK53Hrzw7dPamWoUi9PPevtQ0iTMARgexWO/bTouJbt7IE\n" + 44 | "IlKVgJNp6I5MZfGRAy1wdALqi2cVKWlSArvX31BqVUa/oKMoYX9w0MOiqiwhqkfO\n" + 45 | "KJwGRXa/ghgntNWutMtQ5mv0TIZxMOmm3xaG4Nj/QN370EKIf6MzOi5cHkERgWPO\n" + 46 | "GHFrK+ymircxXDpqR+DDeVnWIBqv8mqYqnK8V0rSS527EPywTEHl7R09XiidnMy/\n" + 47 | "s1Hap0flhFMCAwEAAaOB9DCB8TAfBgNVHSMEGDAWgBStvZh6NLQm9/rEJlTvA73g\n" + 48 | "JMtUGjAdBgNVHQ4EFgQUu69+Aj36pvE8hI6t7jiY7NkyMtQwDgYDVR0PAQH/BAQD\n" + 49 | "AgGGMA8GA1UdEwEB/wQFMAMBAf8wEQYDVR0gBAowCDAGBgRVHSAAMEQGA1UdHwQ9\n" + 50 | "MDswOaA3oDWGM2h0dHA6Ly9jcmwudXNlcnRydXN0LmNvbS9BZGRUcnVzdEV4dGVy\n" + 51 | "bmFsQ0FSb290LmNybDA1BggrBgEFBQcBAQQpMCcwJQYIKwYBBQUHMAGGGWh0dHA6\n" + 52 | "Ly9vY3NwLnVzZXJ0cnVzdC5jb20wDQYJKoZIhvcNAQEMBQADggEBAGS/g/FfmoXQ\n" + 53 | "zbihKVcN6Fr30ek+8nYEbvFScLsePP9NDXRqzIGCJdPDoCpdTPW6i6FtxFQJdcfj\n" + 54 | "Jw5dhHk3QBN39bSsHNA7qxcS1u80GH4r6XnTq1dFDK8o+tDb5VCViLvfhVdpfZLY\n" + 55 | "Uspzgb8c8+a4bmYRBbMelC1/kZWSWfFMzqORcUx8Rww7Cxn2obFshj5cqsQugsv5\n" + 56 | "B5a6SE2Q8pTIqXOi6wZ7I53eovNNVZ96YUWYGGjHXkBrI/V5eu+MtWuLt29G9Hvx\n" + 57 | "PUsE2JOAWVrgQSQdso8VYFhH2+9uRv0V9dlfmrPb2LjkQLPNlzmuhbsdjrzch5vR\n" + 58 | "pu/xO28QOG8=\n" + 59 | "-----END CERTIFICATE-----\n" 60 | 61 | } 62 | 63 | } -------------------------------------------------------------------------------- /lib/src/androidTest/java/at/bitfire/cert4android/CustomCertManagerTest.kt: -------------------------------------------------------------------------------- 1 | /*************************************************************************************************** 2 | * Copyright © All Contributors. See LICENSE and AUTHORS in the root directory for details. 3 | **************************************************************************************************/ 4 | 5 | package at.bitfire.cert4android 6 | 7 | import androidx.test.platform.app.InstrumentationRegistry 8 | import org.junit.Assume.assumeNotNull 9 | import org.junit.Before 10 | import org.junit.Test 11 | import java.io.IOException 12 | import java.net.URL 13 | import java.security.cert.CertificateException 14 | import java.security.cert.X509Certificate 15 | 16 | class CustomCertManagerTest { 17 | 18 | private val context by lazy { InstrumentationRegistry.getInstrumentation().targetContext } 19 | 20 | private lateinit var certManager: CustomCertManager 21 | private lateinit var paranoidCertManager: CustomCertManager 22 | 23 | private var siteCerts: List? = 24 | try { 25 | TestCertificates.getSiteCertificates(URL("https://www.davx5.com")) 26 | } catch(_: IOException) { 27 | null 28 | } 29 | init { 30 | assumeNotNull("Couldn't load certificate from Web", siteCerts) 31 | } 32 | 33 | @Before 34 | fun createCertManager() { 35 | certManager = CustomCertManager(context, true, null) 36 | paranoidCertManager = CustomCertManager(context, false, null) 37 | } 38 | 39 | 40 | @Test(expected = CertificateException::class) 41 | fun testCheckClientCertificate() { 42 | certManager.checkClientTrusted(null, null) 43 | } 44 | 45 | @Test 46 | fun testTrustedCertificate() { 47 | certManager.checkServerTrusted(siteCerts!!.toTypedArray(), "RSA") 48 | } 49 | 50 | @Test(expected = CertificateException::class) 51 | fun testParanoidCertificate() { 52 | paranoidCertManager.checkServerTrusted(siteCerts!!.toTypedArray(), "RSA") 53 | } 54 | 55 | @Test 56 | fun testAddCustomCertificate() { 57 | addTrustedCertificate() 58 | paranoidCertManager.checkServerTrusted(siteCerts!!.toTypedArray(), "RSA") 59 | } 60 | 61 | @Test(expected = CertificateException::class) 62 | fun testRemoveCustomCertificate() { 63 | addTrustedCertificate() 64 | 65 | // remove certificate again 66 | // should now be rejected for the whole session 67 | addUntrustedCertificate() 68 | 69 | paranoidCertManager.checkServerTrusted(siteCerts!!.toTypedArray(), "RSA") 70 | } 71 | 72 | 73 | // helpers 74 | 75 | private fun addTrustedCertificate() { 76 | CustomCertStore.getInstance(context).setTrustedByUser(siteCerts!!.first()) 77 | } 78 | 79 | private fun addUntrustedCertificate() { 80 | CustomCertStore.getInstance(context).setUntrustedByUser(siteCerts!!.first()) 81 | } 82 | 83 | } -------------------------------------------------------------------------------- /lib/src/androidTest/java/at/bitfire/cert4android/CustomCertStoreTest.kt: -------------------------------------------------------------------------------- 1 | /*************************************************************************************************** 2 | * Copyright © All Contributors. See LICENSE and AUTHORS in the root directory for details. 3 | **************************************************************************************************/ 4 | 5 | package at.bitfire.cert4android 6 | 7 | import androidx.test.platform.app.InstrumentationRegistry 8 | import org.junit.Assert.* 9 | import org.junit.Before 10 | import org.junit.Test 11 | 12 | class CustomCertStoreTest { 13 | 14 | val context = InstrumentationRegistry.getInstrumentation().targetContext 15 | val certStore = CustomCertStore.getInstance(context) 16 | 17 | val testCert = TestCertificates.testCert 18 | 19 | @Before 20 | fun clearKeys() { 21 | certStore.clearUserDecisions() 22 | assertFalse(certStore.userKeyStore.aliases().hasMoreElements()) 23 | } 24 | 25 | 26 | @Test 27 | fun testSetTrustedByUser() { 28 | // set it to untrustd before to test whether setTrustedByUser removes the cert from untrustedCerts, too 29 | certStore.setUntrustedByUser(testCert) 30 | assertEquals(testCert, certStore.untrustedCerts.first()) 31 | 32 | // set to trusted, should save to disk 33 | certStore.setTrustedByUser(testCert) 34 | 35 | assertTrue(certStore.isTrustedByUser(testCert)) 36 | assertTrue(certStore.untrustedCerts.isEmpty()) 37 | 38 | // test whether cert was stored to disk: 39 | // create another cert store to make sure data is loaded from disk again 40 | val anotherCertStore = CustomCertStore(context) 41 | assertTrue(anotherCertStore.userKeyStore.aliases().toList().any { alias -> 42 | anotherCertStore.isTrustedByUser(testCert) 43 | }) 44 | } 45 | 46 | @Test 47 | fun testSetUnTrustedByUser() { 48 | // set to trusted before to test whether setUntrustedByUser removes the cert from trusted key store, too 49 | certStore.setTrustedByUser(testCert) // saves trust to disk 50 | 51 | certStore.setUntrustedByUser(testCert) 52 | assertEquals(testCert, certStore.untrustedCerts.first()) 53 | 54 | // test whether now empts key store was saved to disk: 55 | // create another cert store to make sure data is loaded from disk again 56 | val anotherCertStore = CustomCertStore(context) 57 | assertFalse(anotherCertStore.isTrustedByUser(testCert)) 58 | } 59 | 60 | } -------------------------------------------------------------------------------- /lib/src/androidTest/java/at/bitfire/cert4android/TestCertificates.kt: -------------------------------------------------------------------------------- 1 | package at.bitfire.cert4android 2 | 3 | import android.net.SSLCertificateSocketFactory 4 | import org.apache.http.conn.ssl.AllowAllHostnameVerifier 5 | import java.net.URL 6 | import java.security.cert.CertificateFactory 7 | import java.security.cert.X509Certificate 8 | import javax.net.ssl.HttpsURLConnection 9 | import javax.net.ssl.X509TrustManager 10 | 11 | /** 12 | * Provides certificates for testing. 13 | */ 14 | object TestCertificates { 15 | 16 | init { 17 | ConscryptIntegration.initialize() 18 | } 19 | 20 | val certFactory = CertificateFactory.getInstance("X.509") 21 | 22 | const val RAW_TEST_CERT = "-----BEGIN CERTIFICATE-----\n" + 23 | "MIICxzCCAa+gAwIBAgIUe7x8TfMqQlJ+qTF/L+n6NqRqKAwwDQYJKoZIhvcNAQEL\n" + 24 | "BQAwDjEMMAoGA1UEAwwDdG50MB4XDTIwMDIxODE5NTYyMFoXDTMwMDIxNTE5NTYy\n" + 25 | "MFowDjEMMAoGA1UEAwwDdG50MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC\n" + 26 | "AQEAzqBnVAWwIp8oOrcEJzplOLzd8ZKscmrJ0oxMf7oiYUE5+D3I1IjsCIeUdwfH\n" + 27 | "9zDKmNo3lwyFUTjw2WotssawmEH0LGfabi6h/1bbFG4QOQC7KYMtD8tqzR6F0WVe\n" + 28 | "oZ5uM5VvQB+dRvlq2CdWb8NcBkyd2pQ8RvJsft3fWY5ix3CL+OZ8lXOGqkxN780m\n" + 29 | "RkrxdYog3fvWC1CMSix8Y28q4JwRRAMP0JhBGIdFpnEPLowh6HhhPRiwAn+ksSey\n" + 30 | "Rz39AsUErUUCD7soCsDSzu80uieF9enEVweqnn/ayPhJlX0Drw7UwrC88UqdLqRD\n" + 31 | "Da/ucJYzKkMgHZJ7EXNh2WZpbwIDAQABox0wGzAJBgNVHRMEAjAAMA4GA1UdEQQH\n" + 32 | "MAWCA3RudDANBgkqhkiG9w0BAQsFAAOCAQEARpS40Z7hsIeiGqI4Pd33vIK69PwZ\n" + 33 | "yhfGwGT61Fo3CFyEBAc8y+93NkI3l6bd/En8UAkG87nE6qsBxc9LedFhabdcgsgf\n" + 34 | "rEN8vqNhhucuLyHPPzCi+C2sAJHgAGoKEgrfrmvdjCYUa1TJng59n5W5q8SmmYf/\n" + 35 | "AEokes8tF8DuZ3TOTXt2MwPFIbaZiDyn6J1+PYmEPMxoqbG5TDYkox4U4+zODDt0\n" + 36 | "0GFBlln9186eAbdKPSIkS8slAlB5ylBg/TlG/LmzQ/5ESqITyXSTJo5RSLCQ32iG\n" + 37 | "46rF2aPRcVr71DWqbV+YdwkI3N7EwZOIIEl6a9srF+q01LrIukWkScuU9Q==\n" + 38 | "-----END CERTIFICATE-----\n" 39 | 40 | /** some test certificate (untrusted Snakeoil certificate generated by Debian) */ 41 | val testCert = certFactory.generateCertificate(RAW_TEST_CERT.byteInputStream()) as X509Certificate 42 | 43 | 44 | /** 45 | * Get the certificates of a site (bypassing all trusted checks). 46 | * 47 | * @param url the URL to get the certificates from 48 | * @return the certificates of the site 49 | */ 50 | fun getSiteCertificates(url: URL): List { 51 | val conn = url.openConnection() as HttpsURLConnection 52 | try { 53 | conn.hostnameVerifier = AllowAllHostnameVerifier() 54 | conn.sslSocketFactory = object : SSLCertificateSocketFactory(1000) { 55 | init { 56 | setTrustManagers(arrayOf(object : X509TrustManager { 57 | override fun checkClientTrusted( 58 | chain: Array?, 59 | authType: String? 60 | ) { /* OK */ } 61 | override fun checkServerTrusted( 62 | chain: Array?, 63 | authType: String? 64 | ) { /* OK */ } 65 | override fun getAcceptedIssuers(): Array? = emptyArray() 66 | })) 67 | } 68 | } 69 | conn.inputStream.read() 70 | val certs = mutableListOf() 71 | conn.serverCertificates.forEach { certs += it as X509Certificate } 72 | return certs 73 | } finally { 74 | conn.disconnect() 75 | } 76 | } 77 | 78 | } -------------------------------------------------------------------------------- /lib/src/androidTest/java/at/bitfire/cert4android/UserDecisionRegistryTest.kt: -------------------------------------------------------------------------------- 1 | package at.bitfire.cert4android 2 | 3 | import androidx.core.app.NotificationManagerCompat 4 | import androidx.test.platform.app.InstrumentationRegistry 5 | import io.mockk.every 6 | import io.mockk.just 7 | import io.mockk.mockk 8 | import io.mockk.mockkObject 9 | import io.mockk.runs 10 | import io.mockk.unmockkAll 11 | import io.mockk.verify 12 | import kotlinx.coroutines.Dispatchers 13 | import kotlinx.coroutines.delay 14 | import kotlinx.coroutines.launch 15 | import kotlinx.coroutines.runBlocking 16 | import org.junit.After 17 | import org.junit.Assert.assertEquals 18 | import org.junit.Assert.assertFalse 19 | import org.junit.Assert.assertTrue 20 | import org.junit.Before 21 | import org.junit.Test 22 | import java.util.Collections 23 | import java.util.concurrent.Semaphore 24 | import kotlin.concurrent.thread 25 | 26 | class UserDecisionRegistryTest { 27 | 28 | private val context = InstrumentationRegistry.getInstrumentation().targetContext 29 | private val certStore = CustomCertStore.getInstance(context) 30 | private val registry = UserDecisionRegistry.getInstance(context) 31 | 32 | private val testCert = TestCertificates.testCert 33 | 34 | 35 | @Before 36 | fun setUp() { 37 | mockkObject(NotificationUtils) 38 | mockkObject(registry) 39 | every { registry.requestDecision(any(), any(), any()) } returns Unit 40 | } 41 | 42 | @After 43 | fun cleanUp() { 44 | unmockkAll() 45 | certStore.clearUserDecisions() 46 | } 47 | 48 | 49 | @Test 50 | fun testCheck_FirstDecision_Negative() { 51 | every { registry.requestDecision(testCert, any(), any()) } answers { 52 | registry.onUserDecision(testCert, false) 53 | } 54 | assertFalse(runBlocking { 55 | registry.check(testCert, true) 56 | }) 57 | } 58 | 59 | @Test 60 | fun testCheck_FirstDecision_Positive() { 61 | every { registry.requestDecision(testCert, any(), any()) } answers { 62 | registry.onUserDecision(testCert, true) 63 | } 64 | assertTrue(runBlocking { 65 | registry.check(testCert, true) 66 | }) 67 | } 68 | 69 | @Test 70 | fun testCheck_MultipleDecisionsForSameCert_Negative() { 71 | val canSendFeedback = Semaphore(0) 72 | every { registry.requestDecision(testCert, any(), any()) } answers { 73 | thread { 74 | canSendFeedback.acquire() 75 | registry.onUserDecision(testCert, false) 76 | } 77 | } 78 | val results = Collections.synchronizedList(mutableListOf()) 79 | runBlocking { 80 | repeat(5) { 81 | launch(Dispatchers.Default) { 82 | results += registry.check(testCert, true) 83 | } 84 | } 85 | canSendFeedback.release() 86 | } 87 | synchronized(registry.pendingDecisions) { 88 | assertFalse(registry.pendingDecisions.containsKey(testCert)) 89 | } 90 | assertEquals(5, results.size) 91 | assertTrue(results.all { !it }) 92 | verify(exactly = 1) { registry.requestDecision(any(), any(), any()) } 93 | } 94 | 95 | @Test 96 | fun testCheck_MultipleDecisionsForSameCert_Positive() { 97 | val canSendFeedback = Semaphore(0) 98 | every { registry.requestDecision(testCert, any(), any()) } answers { 99 | thread { 100 | canSendFeedback.acquire() 101 | registry.onUserDecision(testCert, true) 102 | } 103 | } 104 | val results = Collections.synchronizedList(mutableListOf()) 105 | runBlocking { 106 | repeat(5) { 107 | launch(Dispatchers.Default) { 108 | results += registry.check(testCert, true) 109 | } 110 | } 111 | canSendFeedback.release() 112 | } 113 | synchronized(registry.pendingDecisions) { 114 | assertFalse(registry.pendingDecisions.containsKey(testCert)) 115 | } 116 | assertEquals(5, results.size) 117 | assertTrue(results.all { it }) 118 | verify(exactly = 1) { registry.requestDecision(any(), any(), any()) } 119 | } 120 | 121 | @Test 122 | fun testCheck_MultipleDecisionsForSameCert_cancel() { 123 | val canSendFeedback = Semaphore(0) 124 | val nm = mockk() 125 | every { nm.cancel(any(), any()) } just runs 126 | every { NotificationUtils.createChannels(any()) } returns nm 127 | every { registry.requestDecision(testCert, any(), any()) } answers { 128 | thread { 129 | canSendFeedback.acquire() 130 | registry.onUserDecision(testCert, false) 131 | } 132 | } 133 | val results = Collections.synchronizedList(mutableListOf()) 134 | runBlocking { 135 | repeat(5) { 136 | val job = launch(Dispatchers.Default) { 137 | results += registry.check(testCert, true) 138 | } 139 | delay(1000) 140 | job.cancel() // Cancel the job 141 | delay(1000) 142 | } 143 | canSendFeedback.release() 144 | } 145 | synchronized(registry.pendingDecisions) { 146 | assertFalse(registry.pendingDecisions.containsKey(testCert)) 147 | } 148 | assertEquals(0, results.size) 149 | verify(exactly = 5) { registry.requestDecision(any(), any(), any()) } 150 | } 151 | 152 | @Test 153 | fun testCheck_UserDecisionImpossible() { 154 | every { NotificationUtils.notificationsPermitted(any()) } returns false 155 | assertFalse(runBlocking { 156 | // should return instantly 157 | registry.check(testCert, false) 158 | }) 159 | verify(inverse = true) { 160 | registry.requestDecision(any(), any(), any()) 161 | } 162 | } 163 | 164 | } -------------------------------------------------------------------------------- /lib/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /lib/src/main/java/at/bitfire/cert4android/Cert4Android.kt: -------------------------------------------------------------------------------- 1 | /*************************************************************************************************** 2 | * Copyright © All Contributors. See LICENSE and AUTHORS in the root directory for details. 3 | **************************************************************************************************/ 4 | 5 | package at.bitfire.cert4android 6 | 7 | import android.util.Log 8 | import androidx.compose.foundation.layout.Box 9 | import androidx.compose.foundation.layout.safeDrawingPadding 10 | import androidx.compose.material3.MaterialTheme 11 | import androidx.compose.runtime.Composable 12 | import androidx.compose.ui.Modifier 13 | import java.util.logging.Level 14 | import java.util.logging.Logger 15 | 16 | object Cert4Android { 17 | 18 | // logging 19 | 20 | const val TAG = "cert4android" 21 | 22 | var log: Logger = Logger.getLogger(TAG) 23 | init { 24 | log.level = if (Log.isLoggable(TAG, Log.VERBOSE)) 25 | Level.ALL 26 | else 27 | Level.INFO 28 | } 29 | 30 | 31 | // theme 32 | 33 | var theme: @Composable (content: @Composable () -> Unit) -> Unit = { content -> 34 | MaterialTheme { 35 | Box(Modifier.safeDrawingPadding()) { 36 | content() 37 | } 38 | } 39 | } 40 | 41 | } -------------------------------------------------------------------------------- /lib/src/main/java/at/bitfire/cert4android/CertUtils.kt: -------------------------------------------------------------------------------- 1 | /*************************************************************************************************** 2 | * Copyright © All Contributors. See LICENSE and AUTHORS in the root directory for details. 3 | **************************************************************************************************/ 4 | 5 | package at.bitfire.cert4android 6 | 7 | import java.security.GeneralSecurityException 8 | import java.security.KeyStore 9 | import java.security.MessageDigest 10 | import java.security.cert.X509Certificate 11 | import java.util.Locale 12 | import java.util.logging.Level 13 | import javax.net.ssl.TrustManagerFactory 14 | import javax.net.ssl.X509TrustManager 15 | 16 | object CertUtils { 17 | 18 | fun getTrustManager(keyStore: KeyStore?): X509TrustManager? { 19 | try { 20 | val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()) 21 | tmf.init(keyStore) 22 | tmf.trustManagers 23 | .filterIsInstance() 24 | .forEach { return it } 25 | } catch(e: GeneralSecurityException) { 26 | Cert4Android.log.log(Level.SEVERE, "Couldn't initialize trust manager", e) 27 | } 28 | return null 29 | } 30 | 31 | 32 | fun getTag(cert: X509Certificate) = 33 | fingerprint(cert, "SHA-512", separator = null) 34 | 35 | fun fingerprint(cert: X509Certificate, algorithm: String, separator: Char? = ':'): String { 36 | val md = MessageDigest.getInstance(algorithm) 37 | return hexString(md.digest(cert.encoded), separator) 38 | } 39 | 40 | fun hexString(data: ByteArray, separator: Char? = ':'): String { 41 | val str = StringBuilder() 42 | for ((idx, b) in data.withIndex()) { 43 | if (idx != 0 && separator != null) 44 | str.append(separator) 45 | str.append(String.format("%02x", b).uppercase(Locale.ROOT)) 46 | } 47 | return str.toString() 48 | } 49 | 50 | } -------------------------------------------------------------------------------- /lib/src/main/java/at/bitfire/cert4android/ConscryptIntegration.kt: -------------------------------------------------------------------------------- 1 | package at.bitfire.cert4android 2 | 3 | import org.conscrypt.Conscrypt 4 | import java.security.Security 5 | import javax.net.ssl.SSLContext 6 | 7 | object ConscryptIntegration { 8 | 9 | private var initialized = false 10 | 11 | @Synchronized 12 | fun initialize() { 13 | if (initialized) 14 | return 15 | 16 | // initialize Conscrypt 17 | Security.insertProviderAt(Conscrypt.newProvider(), 1) 18 | 19 | val version = Conscrypt.version() 20 | Cert4Android.log.info("Using Conscrypt/${version.major()}.${version.minor()}.${version.patch()} for TLS") 21 | 22 | val engine = SSLContext.getDefault().createSSLEngine() 23 | Cert4Android.log.info("Enabled protocols: ${engine.enabledProtocols.joinToString(", ")}") 24 | Cert4Android.log.info("Enabled ciphers: ${engine.enabledCipherSuites.joinToString(", ")}") 25 | 26 | initialized = true 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /lib/src/main/java/at/bitfire/cert4android/CustomCertManager.kt: -------------------------------------------------------------------------------- 1 | /*************************************************************************************************** 2 | * Copyright © All Contributors. See LICENSE and AUTHORS in the root directory for details. 3 | **************************************************************************************************/ 4 | 5 | package at.bitfire.cert4android 6 | 7 | import android.annotation.SuppressLint 8 | import android.content.Context 9 | import kotlinx.coroutines.flow.StateFlow 10 | import java.security.cert.CertificateException 11 | import java.security.cert.X509Certificate 12 | import javax.net.ssl.SSLSession 13 | import javax.net.ssl.X509TrustManager 14 | 15 | /** 16 | * TrustManager to handle custom certificates. 17 | * 18 | * Initializes Conscrypt when it is first loaded. 19 | * 20 | * @param trustSystemCerts whether system certificates will be trusted 21 | * @param appInForeground - `true`: if needed, directly launches [TrustCertificateActivity] and shows notification (if possible) 22 | * - `false`: if needed, shows notification (if possible) 23 | * - `null`: non-interactive mode: does not show notification or launch activity 24 | */ 25 | @SuppressLint("CustomX509TrustManager") 26 | class CustomCertManager @JvmOverloads constructor( 27 | context: Context, 28 | val trustSystemCerts: Boolean = true, 29 | var appInForeground: StateFlow? 30 | ): X509TrustManager { 31 | 32 | val certStore = CustomCertStore.getInstance(context) 33 | 34 | 35 | @Throws(CertificateException::class) 36 | override fun checkClientTrusted(chain: Array?, authType: String?) { 37 | throw CertificateException("cert4android doesn't validate client certificates") 38 | } 39 | 40 | /** 41 | * Checks whether a certificate is trusted. Allows user to explicitly accept untrusted certificates. 42 | * 43 | * @param chain certificate chain to check 44 | * @param authType authentication type (ignored) 45 | * 46 | * @throws CertificateException in case of an untrusted or questionable certificate 47 | */ 48 | @Throws(CertificateException::class) 49 | override fun checkServerTrusted(chain: Array, authType: String) { 50 | if (!certStore.isTrusted(chain, authType, trustSystemCerts, appInForeground)) 51 | throw CertificateException("Certificate chain not trusted") 52 | } 53 | 54 | override fun getAcceptedIssuers() = arrayOf() 55 | 56 | 57 | /** 58 | * A HostnameVerifier that allows users to explicitly accept untrusted and 59 | * non-matching (bad hostname) certificates. 60 | */ 61 | inner class HostnameVerifier( 62 | private val defaultHostnameVerifier: javax.net.ssl.HostnameVerifier? = null 63 | ): javax.net.ssl.HostnameVerifier { 64 | 65 | override fun verify(hostname: String, session: SSLSession): Boolean { 66 | if (defaultHostnameVerifier != null && defaultHostnameVerifier.verify(hostname, session)) 67 | // default HostnameVerifier says trusted → OK 68 | return true 69 | 70 | Cert4Android.log.warning("Host name \"$hostname\" not verified, checking whether certificate is explicitly trusted") 71 | // Allow users to explicitly accept certificates that have a bad hostname here 72 | (session.peerCertificates.firstOrNull() as? X509Certificate)?.let { cert -> 73 | // Check without trusting system certificates so that the user will be asked even for system-trusted certificates 74 | if (certStore.isTrusted(arrayOf(cert), "RSA", false, appInForeground)) 75 | return true 76 | } 77 | 78 | return false 79 | } 80 | 81 | } 82 | 83 | 84 | companion object { 85 | 86 | init { 87 | // On first load of this class, initialize Conscrypt. 88 | ConscryptIntegration.initialize() 89 | } 90 | 91 | } 92 | 93 | } -------------------------------------------------------------------------------- /lib/src/main/java/at/bitfire/cert4android/CustomCertStore.kt: -------------------------------------------------------------------------------- 1 | /*************************************************************************************************** 2 | * Copyright © All Contributors. See LICENSE and AUTHORS in the root directory for details. 3 | **************************************************************************************************/ 4 | 5 | package at.bitfire.cert4android 6 | 7 | import android.annotation.SuppressLint 8 | import android.content.Context 9 | import androidx.annotation.VisibleForTesting 10 | import kotlinx.coroutines.TimeoutCancellationException 11 | import kotlinx.coroutines.flow.StateFlow 12 | import kotlinx.coroutines.runBlocking 13 | import kotlinx.coroutines.withTimeout 14 | import org.conscrypt.Conscrypt 15 | import java.io.File 16 | import java.io.FileInputStream 17 | import java.io.FileOutputStream 18 | import java.security.KeyStore 19 | import java.security.cert.CertificateException 20 | import java.security.cert.X509Certificate 21 | import java.util.logging.Level 22 | 23 | class CustomCertStore internal constructor( 24 | private val context: Context, 25 | private val userTimeout: Long = 60000L 26 | ) { 27 | 28 | companion object { 29 | 30 | private const val KEYSTORE_DIR = "KeyStore" 31 | private const val KEYSTORE_NAME = "KeyStore.bks" 32 | 33 | @SuppressLint("StaticFieldLeak") // we only store the applicationContext, so this is safe 34 | private var instance: CustomCertStore? = null 35 | 36 | @Synchronized 37 | fun getInstance(context: Context): CustomCertStore { 38 | instance?.let { 39 | return it 40 | } 41 | 42 | val newInstance = CustomCertStore(context.applicationContext) 43 | instance = newInstance 44 | return newInstance 45 | } 46 | 47 | } 48 | 49 | /** system default TrustStore */ 50 | private val systemKeyStore by lazy { Conscrypt.getDefaultX509TrustManager() } 51 | 52 | /** custom TrustStore */ 53 | @VisibleForTesting 54 | internal val userKeyStore = KeyStore.getInstance(KeyStore.getDefaultType())!! 55 | private val userKeyStoreFile = File(context.getDir(KEYSTORE_DIR, Context.MODE_PRIVATE), KEYSTORE_NAME) 56 | 57 | /** in-memory store for untrusted certs */ 58 | @VisibleForTesting 59 | internal var untrustedCerts = HashSet() 60 | 61 | init { 62 | loadUserKeyStore() 63 | } 64 | 65 | @Synchronized 66 | fun clearUserDecisions() { 67 | Cert4Android.log.info("Clearing user-(dis)trusted certificates") 68 | 69 | for (alias in userKeyStore.aliases()) 70 | userKeyStore.deleteEntry(alias) 71 | saveUserKeyStore() 72 | 73 | // clear untrusted certs 74 | untrustedCerts.clear() 75 | } 76 | 77 | /** 78 | * Determines whether a certificate chain is trusted. 79 | */ 80 | fun isTrusted(chain: Array, authType: String, trustSystemCerts: Boolean, appInForeground: StateFlow?): Boolean { 81 | if (chain.isEmpty()) 82 | throw IllegalArgumentException("Certificate chain must not be empty") 83 | val cert = chain[0] 84 | 85 | synchronized(this) { 86 | if (isTrustedByUser(cert)) 87 | // explicitly accepted by user 88 | return true 89 | 90 | // explicitly rejected by user 91 | if (untrustedCerts.contains(cert)) 92 | return false 93 | 94 | // check system certs, if applicable 95 | if (trustSystemCerts) 96 | try { 97 | systemKeyStore.checkServerTrusted(chain, authType) 98 | 99 | // trusted by system 100 | return true 101 | } catch (_: CertificateException) { 102 | // not trusted by system, ask user 103 | } 104 | } 105 | 106 | if (appInForeground == null) { 107 | Cert4Android.log.log(Level.INFO, "Certificate not known and running in non-interactive mode, rejecting") 108 | return false 109 | } 110 | 111 | return runBlocking { 112 | val ui = UserDecisionRegistry.getInstance(context) 113 | 114 | try { 115 | withTimeout(userTimeout) { 116 | ui.check(cert, appInForeground.value) 117 | } 118 | } catch (_: TimeoutCancellationException) { 119 | Cert4Android.log.log(Level.WARNING, "User timeout while waiting for certificate decision, rejecting") 120 | false 121 | } 122 | } 123 | } 124 | 125 | /** 126 | * Determines whether a certificate has been explicitly accepted by the user. In this case, 127 | * we can ignore an invalid host name for that certificate. 128 | */ 129 | @Synchronized 130 | fun isTrustedByUser(cert: X509Certificate): Boolean = 131 | userKeyStore.getCertificateAlias(cert) != null 132 | 133 | @Synchronized 134 | fun setTrustedByUser(cert: X509Certificate) { 135 | val alias = CertUtils.getTag(cert) 136 | Cert4Android.log.info("Trusted by user: ${cert.subjectDN.name} ($alias)") 137 | 138 | userKeyStore.setCertificateEntry(alias, cert) 139 | saveUserKeyStore() 140 | 141 | untrustedCerts -= cert 142 | } 143 | 144 | @Synchronized 145 | fun setUntrustedByUser(cert: X509Certificate) { 146 | Cert4Android.log.info("Distrusted by user: ${cert.subjectDN.name}") 147 | 148 | // find certificate 149 | val alias = userKeyStore.getCertificateAlias(cert) 150 | if (alias != null) { 151 | // and delete, if applicable 152 | userKeyStore.deleteEntry(alias) 153 | saveUserKeyStore() 154 | } 155 | 156 | untrustedCerts += cert 157 | } 158 | 159 | 160 | @Synchronized 161 | private fun loadUserKeyStore() { 162 | try { 163 | FileInputStream(userKeyStoreFile).use { 164 | userKeyStore.load(it, null) 165 | Cert4Android.log.fine("Loaded ${userKeyStore.size()} trusted certificate(s)") 166 | } 167 | } catch(_: Exception) { 168 | Cert4Android.log.fine("No key store for trusted certificates (yet); creating in-memory key store.") 169 | try { 170 | userKeyStore.load(null, null) 171 | } catch(e: Exception) { 172 | Cert4Android.log.log(Level.SEVERE, "Couldn't initialize in-memory key store", e) 173 | } 174 | } 175 | } 176 | 177 | @Synchronized 178 | private fun saveUserKeyStore() { 179 | try { 180 | FileOutputStream(userKeyStoreFile).use { userKeyStore.store(it, null) } 181 | } catch(e: Exception) { 182 | Cert4Android.log.log(Level.SEVERE, "Couldn't save custom certificate key store", e) 183 | } 184 | } 185 | 186 | } -------------------------------------------------------------------------------- /lib/src/main/java/at/bitfire/cert4android/NotificationUtils.kt: -------------------------------------------------------------------------------- 1 | /*************************************************************************************************** 2 | * Copyright © All Contributors. See LICENSE and AUTHORS in the root directory for details. 3 | **************************************************************************************************/ 4 | 5 | package at.bitfire.cert4android 6 | 7 | import android.Manifest 8 | import android.app.NotificationChannel 9 | import android.app.NotificationManager 10 | import android.content.Context 11 | import android.content.pm.PackageManager 12 | import android.os.Build 13 | import androidx.core.app.ActivityCompat 14 | import androidx.core.app.NotificationManagerCompat 15 | 16 | object NotificationUtils { 17 | 18 | const val CHANNEL_CERTIFICATES = "cert4android" 19 | 20 | const val ID_CERT_DECISION = 88809 21 | 22 | 23 | /** 24 | * Checks whether the notifications permission is granted. 25 | */ 26 | fun notificationsPermitted(context: Context) = 27 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { 28 | ActivityCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED 29 | } else 30 | true 31 | 32 | 33 | fun createChannels(context: Context): NotificationManagerCompat { 34 | val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager 35 | 36 | if (Build.VERSION.SDK_INT >= 26) 37 | nm.createNotificationChannel(NotificationChannel(CHANNEL_CERTIFICATES, 38 | context.getString(R.string.certificate_notification_connection_security), NotificationManager.IMPORTANCE_HIGH)) 39 | 40 | return NotificationManagerCompat.from(context) 41 | } 42 | 43 | } -------------------------------------------------------------------------------- /lib/src/main/java/at/bitfire/cert4android/TrustCertificateActivity.kt: -------------------------------------------------------------------------------- 1 | /*************************************************************************************************** 2 | * Copyright © All Contributors. See LICENSE and AUTHORS in the root directory for details. 3 | **************************************************************************************************/ 4 | 5 | package at.bitfire.cert4android 6 | 7 | import android.app.Application 8 | import android.content.Intent 9 | import android.os.Bundle 10 | import androidx.activity.ComponentActivity 11 | import androidx.activity.compose.BackHandler 12 | import androidx.activity.compose.setContent 13 | import androidx.activity.enableEdgeToEdge 14 | import androidx.activity.viewModels 15 | import androidx.annotation.StringRes 16 | import androidx.compose.foundation.clickable 17 | import androidx.compose.foundation.layout.Column 18 | import androidx.compose.foundation.layout.Row 19 | import androidx.compose.foundation.layout.fillMaxWidth 20 | import androidx.compose.foundation.layout.padding 21 | import androidx.compose.foundation.rememberScrollState 22 | import androidx.compose.foundation.verticalScroll 23 | import androidx.compose.material3.Card 24 | import androidx.compose.material3.Checkbox 25 | import androidx.compose.material3.MaterialTheme 26 | import androidx.compose.material3.Scaffold 27 | import androidx.compose.material3.SnackbarHost 28 | import androidx.compose.material3.SnackbarHostState 29 | import androidx.compose.material3.Text 30 | import androidx.compose.material3.TextButton 31 | import androidx.compose.runtime.Composable 32 | import androidx.compose.runtime.LaunchedEffect 33 | import androidx.compose.runtime.getValue 34 | import androidx.compose.runtime.mutableIntStateOf 35 | import androidx.compose.runtime.mutableStateOf 36 | import androidx.compose.runtime.remember 37 | import androidx.compose.runtime.rememberCoroutineScope 38 | import androidx.compose.runtime.setValue 39 | import androidx.compose.runtime.snapshots.Snapshot 40 | import androidx.compose.ui.Modifier 41 | import androidx.compose.ui.res.stringResource 42 | import androidx.compose.ui.tooling.preview.Preview 43 | import androidx.compose.ui.unit.dp 44 | import androidx.lifecycle.AndroidViewModel 45 | import androidx.lifecycle.viewModelScope 46 | import kotlinx.coroutines.Dispatchers 47 | import kotlinx.coroutines.launch 48 | import java.io.ByteArrayInputStream 49 | import java.security.cert.CertificateFactory 50 | import java.security.cert.CertificateParsingException 51 | import java.security.cert.X509Certificate 52 | import java.security.spec.MGF1ParameterSpec.SHA1 53 | import java.security.spec.MGF1ParameterSpec.SHA256 54 | import java.text.DateFormat 55 | import java.util.logging.Level 56 | 57 | class TrustCertificateActivity : ComponentActivity() { 58 | 59 | companion object { 60 | const val EXTRA_CERTIFICATE = "certificate" 61 | const val EXTRA_TRUSTED = "trusted" 62 | 63 | fun rawCertFromIntent(intent: Intent): ByteArray = 64 | intent.getByteArrayExtra(EXTRA_CERTIFICATE) ?: throw IllegalArgumentException("EXTRA_CERTIFICATE required") 65 | } 66 | 67 | private val model by viewModels() 68 | 69 | 70 | override fun onCreate(savedInstanceState: Bundle?) { 71 | super.onCreate(savedInstanceState) 72 | 73 | processIntent(intent) 74 | addOnNewIntentListener { newIntent -> 75 | processIntent(newIntent) 76 | } 77 | 78 | enableEdgeToEdge() 79 | 80 | setContent { 81 | Cert4Android.theme { 82 | MainLayout( 83 | onRegisterDecision = { trusted -> model.registerDecision(trusted) }, 84 | onFinish = { finish() } 85 | ) 86 | } 87 | } 88 | } 89 | 90 | private fun processIntent(intent: Intent) { 91 | // process certificate 92 | model.parseCertificate(rawCertFromIntent(intent)) 93 | 94 | // process EXTRA_TRUSTED, if available 95 | if (intent.hasExtra(EXTRA_TRUSTED)) { 96 | val trusted = intent.getBooleanExtra(EXTRA_TRUSTED, false) 97 | model.registerDecision(trusted) 98 | } 99 | } 100 | 101 | 102 | @Composable 103 | @Preview 104 | fun MainLayout( 105 | onRegisterDecision: (Boolean) -> Unit = {}, 106 | onFinish: () -> Unit = {} 107 | ) { 108 | val snackbarHostState = remember { SnackbarHostState() } 109 | val scope = rememberCoroutineScope() 110 | 111 | val uiState = model.uiState 112 | LaunchedEffect(uiState.decided) { 113 | if (uiState.decided) 114 | onFinish() 115 | } 116 | 117 | var backPressedCounter by remember { mutableIntStateOf(0) } 118 | BackHandler { 119 | val newBackPressedCounter = backPressedCounter + 1 120 | when (newBackPressedCounter) { 121 | 0 -> { /* back button not pressed yet */ } 122 | 1 -> 123 | scope.launch { 124 | snackbarHostState.showSnackbar(getString(R.string.trust_certificate_press_back_to_reject)) 125 | } 126 | else -> 127 | onRegisterDecision(false) 128 | } 129 | backPressedCounter = newBackPressedCounter 130 | } 131 | 132 | Scaffold( 133 | snackbarHost = { SnackbarHost(snackbarHostState) }, 134 | modifier = Modifier.padding(16.dp) 135 | ) { paddingValues -> 136 | Column( 137 | modifier = Modifier 138 | .padding(paddingValues) 139 | .verticalScroll(rememberScrollState()), 140 | ) { 141 | Text( 142 | text = stringResource(R.string.trust_certificate_unknown_certificate_found), 143 | style = MaterialTheme.typography.bodySmall, 144 | modifier = Modifier 145 | .fillMaxWidth() 146 | .padding(bottom = 16.dp) 147 | ) 148 | 149 | CertificateCard( 150 | uiState = uiState, 151 | onRegisterDecision = onRegisterDecision 152 | ) 153 | 154 | Text( 155 | text = stringResource(R.string.trust_certificate_reset_info), 156 | style = MaterialTheme.typography.bodySmall, 157 | modifier = Modifier 158 | .fillMaxWidth() 159 | .padding(top = 16.dp), 160 | ) 161 | } 162 | } 163 | } 164 | 165 | @Composable 166 | fun CertificateCard( 167 | uiState: UiState, 168 | onRegisterDecision: (Boolean) -> Unit 169 | ) { 170 | Card( 171 | modifier = Modifier 172 | .fillMaxWidth(), 173 | ) { 174 | Column( 175 | modifier = Modifier 176 | .padding(16.dp), 177 | ) { 178 | Text( 179 | text = stringResource(R.string.trust_certificate_x509_certificate_details), 180 | style = MaterialTheme.typography.titleMedium, 181 | modifier = Modifier 182 | .fillMaxWidth() 183 | .padding(bottom = 16.dp), 184 | ) 185 | if (uiState.issuedFor != null) 186 | InfoPack(R.string.trust_certificate_issued_for, uiState.issuedFor) 187 | if (uiState.issuedBy != null) 188 | InfoPack(R.string.trust_certificate_issued_by, uiState.issuedBy) 189 | 190 | val validFrom = uiState.validFrom 191 | val validTo = uiState.validTo 192 | if (validFrom != null && validTo != null) 193 | InfoPack( 194 | R.string.trust_certificate_validity_period, 195 | stringResource( 196 | R.string.trust_certificate_validity_period_value, 197 | validFrom, 198 | validTo 199 | ) 200 | ) 201 | 202 | val sha1 = uiState.sha1 203 | val sha256 = uiState.sha256 204 | if (sha1 != null || sha256 != null) { 205 | Text( 206 | text = stringResource(R.string.trust_certificate_fingerprints).uppercase(), 207 | style = MaterialTheme.typography.bodyMedium, 208 | modifier = Modifier.fillMaxWidth(), 209 | ) 210 | 211 | if (sha1 != null) 212 | Text( 213 | text = sha1, 214 | style = MaterialTheme.typography.bodyMedium, 215 | modifier = Modifier 216 | .fillMaxWidth() 217 | .padding(bottom = 16.dp, top = 4.dp), 218 | ) 219 | 220 | if (sha256 != null) 221 | Text( 222 | text = sha256, 223 | style = MaterialTheme.typography.bodyMedium, 224 | modifier = Modifier 225 | .fillMaxWidth() 226 | .padding(bottom = 16.dp, top = 4.dp), 227 | ) 228 | } 229 | 230 | var fingerprintVerified by remember { mutableStateOf(false) } 231 | Row( 232 | modifier = Modifier 233 | .fillMaxWidth() 234 | .padding(8.dp), 235 | ) { 236 | Checkbox( 237 | checked = fingerprintVerified, 238 | onCheckedChange = { fingerprintVerified = it } 239 | ) 240 | Text( 241 | text = stringResource(R.string.trust_certificate_fingerprint_verified), 242 | modifier = Modifier 243 | .clickable { 244 | fingerprintVerified = !fingerprintVerified 245 | } 246 | .weight(1f) 247 | .padding(bottom = 8.dp), 248 | style = MaterialTheme.typography.bodyMedium 249 | ) 250 | } 251 | 252 | Row( 253 | modifier = Modifier.fillMaxWidth(), 254 | ) { 255 | TextButton( 256 | enabled = fingerprintVerified, 257 | onClick = { 258 | onRegisterDecision(true) 259 | }, 260 | modifier = Modifier 261 | .weight(1f) 262 | .padding(end = 16.dp) 263 | ) { Text(stringResource(R.string.trust_certificate_accept).uppercase()) } 264 | TextButton( 265 | onClick = { 266 | onRegisterDecision(false) 267 | }, 268 | modifier = Modifier 269 | .weight(1f) 270 | ) { Text(stringResource(R.string.trust_certificate_reject).uppercase()) } 271 | } 272 | } 273 | } 274 | } 275 | 276 | @Composable 277 | fun InfoPack(@StringRes labelStringRes: Int, text: String) { 278 | Text( 279 | text = stringResource(labelStringRes).uppercase(), 280 | style = MaterialTheme.typography.bodyMedium, 281 | modifier = Modifier 282 | .fillMaxWidth(), 283 | ) 284 | Text( 285 | text = text, 286 | style = MaterialTheme.typography.bodySmall, 287 | modifier = Modifier 288 | .fillMaxWidth() 289 | .padding(bottom = 16.dp), 290 | ) 291 | } 292 | 293 | 294 | data class UiState( 295 | val issuedFor: String? = null, 296 | val issuedBy: String? = null, 297 | val validFrom: String? = null, 298 | val validTo: String? = null, 299 | val sha1: String? = null, 300 | val sha256: String? = null, 301 | 302 | val decided: Boolean = false 303 | ) 304 | 305 | class Model(application: Application) : AndroidViewModel(application) { 306 | 307 | private var cert: X509Certificate? = null 308 | 309 | var uiState by mutableStateOf(UiState()) 310 | private set 311 | 312 | fun parseCertificate(rawCert: ByteArray) = viewModelScope.launch(Dispatchers.Default) { 313 | val certFactory = CertificateFactory.getInstance("X.509")!! 314 | (certFactory.generateCertificate(ByteArrayInputStream(rawCert)) as? X509Certificate)?.let { cert -> 315 | this@Model.cert = cert 316 | 317 | try { 318 | val subject = cert.subjectAlternativeNames?.let { altNames -> 319 | val sb = StringBuilder() 320 | for (altName in altNames) { 321 | val name = altName[1] 322 | if (name is String) 323 | sb.append("[").append(altName[0]).append("]").append(name).append(" ") 324 | } 325 | sb.toString() 326 | } ?: /* use CN if alternative names are not available */ cert.subjectDN.name 327 | 328 | val timeFormatter = DateFormat.getDateInstance(DateFormat.LONG) 329 | Snapshot.withMutableSnapshot { // thread-safe update of UI state 330 | uiState = uiState.copy( 331 | issuedFor = subject, 332 | issuedBy = cert.issuerDN.toString(), 333 | validFrom = timeFormatter.format(cert.notBefore), 334 | validTo = timeFormatter.format(cert.notAfter), 335 | sha1 = "SHA1: " + CertUtils.fingerprint(cert, SHA1.digestAlgorithm), 336 | sha256 = "SHA256: " + CertUtils.fingerprint(cert, SHA256.digestAlgorithm) 337 | ) 338 | } 339 | } catch (e: CertificateParsingException) { 340 | Cert4Android.log.log(Level.WARNING, "Couldn't parse certificate", e) 341 | } 342 | } 343 | } 344 | 345 | fun registerDecision(trusted: Boolean) { 346 | // notify user decision registry 347 | cert?.let { 348 | UserDecisionRegistry.getInstance(getApplication()).onUserDecision(it, trusted) 349 | 350 | // notify UI that the case has been decided (causes Activity to finish) 351 | uiState = uiState.copy(decided = true) 352 | } 353 | } 354 | 355 | } 356 | 357 | } -------------------------------------------------------------------------------- /lib/src/main/java/at/bitfire/cert4android/UserDecisionRegistry.kt: -------------------------------------------------------------------------------- 1 | package at.bitfire.cert4android 2 | 3 | import android.annotation.SuppressLint 4 | import android.app.PendingIntent 5 | import android.content.Context 6 | import android.content.Intent 7 | import androidx.core.app.NotificationCompat 8 | import androidx.core.app.TaskStackBuilder 9 | import kotlinx.coroutines.suspendCancellableCoroutine 10 | import java.security.cert.X509Certificate 11 | import kotlin.coroutines.Continuation 12 | import kotlin.coroutines.resume 13 | 14 | class UserDecisionRegistry private constructor( 15 | private val context: Context 16 | ) { 17 | 18 | companion object { 19 | 20 | @SuppressLint("StaticFieldLeak") 21 | private var instance: UserDecisionRegistry? = null 22 | 23 | @Synchronized 24 | fun getInstance(context: Context): UserDecisionRegistry { 25 | instance?.let { 26 | return it 27 | } 28 | 29 | val newInstance = UserDecisionRegistry(context.applicationContext) 30 | instance = newInstance 31 | return newInstance 32 | } 33 | 34 | } 35 | 36 | internal val pendingDecisions = mutableMapOf>>() 37 | 38 | /** 39 | * Tries to retrieve a trust decision from the user about a given certificate. 40 | * 41 | * Thread-safe, can handle multiple requests for various certificates and/or the same certificate at once. 42 | * 43 | * @param cert certificate to ask user about 44 | * @param appInForeground whether the app is currently in foreground = whether it can directly launch an Activity 45 | * @return *true* if the user explicitly trusts the certificate, *false* if unknown or untrusted 46 | */ 47 | suspend fun check(cert: X509Certificate, appInForeground: Boolean): Boolean = suspendCancellableCoroutine { cont -> 48 | // check whether we're able to retrieve user feedback (= start an Activity and/or show a notification) 49 | val notificationsPermitted = NotificationUtils.notificationsPermitted(context) 50 | val userDecisionPossible = appInForeground || notificationsPermitted 51 | 52 | if (userDecisionPossible) { 53 | // User decision possible → remember request in pendingDecisions so that a later decision will be applied to this request 54 | 55 | cont.invokeOnCancellation { 56 | synchronized(pendingDecisions) { 57 | val decisionsList = pendingDecisions[cert] 58 | 59 | // remove from pending decisions on cancellation 60 | decisionsList?.remove(cont) 61 | 62 | // Remove decisions list if empty 63 | if (decisionsList?.isEmpty() == true) 64 | pendingDecisions -= cert 65 | } 66 | 67 | val nm = NotificationUtils.createChannels(context) 68 | nm.cancel(CertUtils.getTag(cert), NotificationUtils.ID_CERT_DECISION) 69 | } 70 | 71 | val requestDecision: Boolean 72 | synchronized(pendingDecisions) { 73 | if (pendingDecisions.containsKey(cert)) { 74 | // There are already pending decisions for this request, just add our request 75 | pendingDecisions[cert]!! += cont 76 | requestDecision = false 77 | } else { 78 | // First decision for this certificate, show UI 79 | pendingDecisions[cert] = mutableListOf(cont) 80 | requestDecision = true 81 | } 82 | } 83 | 84 | if (requestDecision) 85 | requestDecision(cert, launchActivity = appInForeground, showNotification = notificationsPermitted) 86 | 87 | } else { 88 | // We're not able to retrieve user feedback, directly reject request 89 | Cert4Android.log.warning("App not in foreground and missing notification permission, rejecting certificate") 90 | cont.resume(false) 91 | } 92 | } 93 | 94 | /** 95 | * Starts UI for retrieving feedback (accept/reject) for a certificate from the user. 96 | * 97 | * Ensure that required permissions are granted/conditions are met before setting [launchActivity] 98 | * or [showNotification]. 99 | * 100 | * @param cert certificate to ask user about 101 | * @param launchActivity whether to launch a [TrustCertificateActivity] 102 | * @param showNotification whether to show a certificate notification (caller must check notification permissions before passing *true*) 103 | * 104 | * @throws IllegalArgumentException when both [launchActivity] and [showNotification] are *false* 105 | */ 106 | @SuppressLint("MissingPermission") 107 | internal fun requestDecision(cert: X509Certificate, launchActivity: Boolean, showNotification: Boolean) { 108 | if (!launchActivity && !showNotification) 109 | throw IllegalArgumentException("User decision requires certificate Activity and/or notification") 110 | 111 | val rawCert = cert.encoded 112 | val decisionIntent = Intent(context, TrustCertificateActivity::class.java).apply { 113 | putExtra(TrustCertificateActivity.EXTRA_CERTIFICATE, rawCert) 114 | } 115 | 116 | if (showNotification) { 117 | val rejectIntent = Intent(context, TrustCertificateActivity::class.java).apply { 118 | putExtra(TrustCertificateActivity.EXTRA_CERTIFICATE, rawCert) 119 | putExtra(TrustCertificateActivity.EXTRA_TRUSTED, false) 120 | } 121 | 122 | val id = rawCert.contentHashCode() 123 | val notify = NotificationCompat.Builder(context, NotificationUtils.CHANNEL_CERTIFICATES) 124 | .setPriority(NotificationCompat.PRIORITY_HIGH) 125 | .setSmallIcon(R.drawable.ic_lock_open_white) 126 | .setContentTitle(context.getString(R.string.certificate_notification_connection_security)) 127 | .setContentText(context.getString(R.string.certificate_notification_user_interaction)) 128 | .setSubText(cert.subjectDN.name) 129 | .setCategory(NotificationCompat.CATEGORY_SERVICE) 130 | .setContentIntent( 131 | TaskStackBuilder.create(context) 132 | .addNextIntent(decisionIntent) 133 | .getPendingIntent(id, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) 134 | ) 135 | .setDeleteIntent( 136 | TaskStackBuilder.create(context) 137 | .addNextIntent(rejectIntent) 138 | .getPendingIntent(id + 1, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE) 139 | ) 140 | .build() 141 | 142 | val nm = NotificationUtils.createChannels(context) 143 | nm.notify(CertUtils.getTag(cert), NotificationUtils.ID_CERT_DECISION, notify) 144 | } 145 | 146 | if (launchActivity) { 147 | decisionIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) 148 | context.startActivity(decisionIntent) 149 | } 150 | } 151 | 152 | fun onUserDecision(cert: X509Certificate, trusted: Boolean) { 153 | // cancel notification 154 | val nm = NotificationUtils.createChannels(context) 155 | nm.cancel(CertUtils.getTag(cert), NotificationUtils.ID_CERT_DECISION) 156 | 157 | // save decision 158 | val customCertStore = CustomCertStore.getInstance(context) 159 | if (trusted) 160 | customCertStore.setTrustedByUser(cert) 161 | else 162 | customCertStore.setUntrustedByUser(cert) 163 | 164 | // continue work that's waiting for decisions 165 | synchronized(pendingDecisions) { 166 | pendingDecisions[cert]?.iterator()?.let { iter -> 167 | while (iter.hasNext()) { 168 | iter.next().resume(trusted) 169 | iter.remove() 170 | } 171 | } 172 | 173 | // remove certificate from pendingDecisions so UI can be shown again in future 174 | pendingDecisions.remove(cert) 175 | } 176 | } 177 | 178 | } -------------------------------------------------------------------------------- /lib/src/main/res/drawable/ic_lock_open_white.xml: -------------------------------------------------------------------------------- 1 | 8 | 9 | 14 | 17 | 18 | -------------------------------------------------------------------------------- /lib/src/main/res/values-ar/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | أمن الاتصال 5 | فضلاً راجع الشهادة 6 | 7 | الشهادة مرفوضة مؤقتاً 8 | 9 | عثر cert4android على شهادة غير معروفة. هل تريد الوثوق بها؟ 10 | تفاصيل شهادة X509 11 | صادرة لـ 12 | جهة الإصدار 13 | مدة الصلاحية 14 | %1$s - %2$s (لن يتم تنفيذها) 15 | البصمات 16 | لقد قمت بالتحقق يدوياً من كامل البصمة. 17 | موافق 18 | أرفض 19 | يمكنك إعادة ضبط كل الشهادات المخصصة في إعدادات التطبيق. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-bg/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Защита на връзката 5 | Прегледайте сертификата 6 | 7 | Сертификатът е временно отхвърлен 8 | 9 | cert4android се натъкна на непознат сертификат. Желаете ли да му се доверите? 10 | Подробности за сертификата на X509 11 | Издаден за 12 | Издаден от 13 | Период на годност 14 | %1$s – %2$s (няма да се прилага) 15 | Отпечатъци 16 | Ръчно проверих целия отпечатък 17 | Приемане 18 | Отхвърляне 19 | Можеш да нулираш всички допълнително вкарани сертификати в настройките на приложението. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-ca/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Seguretat de la connexió 5 | Si us plau, comprova el certificat 6 | 7 | Certificat temporalment rebutjat 8 | 9 | cert4android ha trobat un certificat desconegut. Vols confiar-hi? 10 | Detalls del certificat X509 11 | Emès per a 12 | Emès per 13 | Període de validesa 14 | Empremtes 15 | He verificat les l\'empremta sencera manualment. 16 | Acceptar 17 | Rebutjar 18 | Pots reinicialitzar els certificats personalitzats als ajustaments de l\'aplicació. 19 | 20 | -------------------------------------------------------------------------------- /lib/src/main/res/values-cs/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Zabezpečení připojení 5 | Zkontrolujte certifikát 6 | 7 | Certifikát dočasně odmítnut 8 | 9 | cert4android nalezl neznámý certifikát. Chcete mu důvěřovat? 10 | podrobnosti X509 certifikátu 11 | Vystaven pro 12 | Vystavil 13 | Období platnosti 14 | %1$s – %2$s (nebude vynuceno) 15 | Otisky 16 | Celý otisk byl mnou ručně ověřen. 17 | Přijmout 18 | Zamítnout 19 | Všechny vlastní certifikáty lze resetovat v nastavení aplikace. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-da/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Forbindelses sikkerhed 5 | Gennemse certifikat 6 | 7 | Certifikat midlertidigt afvist 8 | 9 | cert4android er stødt på et ukendt certifikat. Skal det godkendes? 10 | Detaljer for X509-certifikat 11 | Udstedt til 12 | Udstedt af 13 | Gyldighedsperiode 14 | %1$s – %2$s (vil ikke blive håndhævet) 15 | Fingeraftryk 16 | Jeg har manuelt godkendt hele fingeraftrykket. 17 | Godkend 18 | Afvis 19 | Alle brugertilpasset certifikater kan nulstilles i programmets indstillinger. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-de/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Verbindungssicherheit 5 | Bitte Zertifikat überprüfen 6 | 7 | Zertifikat vorübergehend abgelehnt 8 | 9 | cert4android ist auf ein unbekanntes Zertifikat gestoßen. Wollen Sie diesem vertrauen? 10 | X509-Zertifikat 11 | Ausgestellt für 12 | Ausgestellt von 13 | Gültigkeitszeitraum 14 | %1$s – %2$s (wird nicht erzwungen) 15 | Prüfsummen 16 | Ich habe die vollständige Prüfsumme händisch überprüft. 17 | Akzeptieren 18 | Ablehnen 19 | Alle akzeptierten/abgelehnten Zertifikate können in den App-Einstellungen zurückgesetzt werden. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-el/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Ασφάλεια σύνδεσης 5 | Παρακαλώ ελέγξτε το πιστοποιητικό 6 | 7 | Το πιστοποιητικό απορρίφθηκε προσωρινά 8 | 9 | Το cert4android εντόπισε ένα άγνωστο πιστοποιητικό. Θέλετε να το εμπιστεύεστε; 10 | Λεπτομέρειες πιστοποιητικού X509 11 | Εκδόθηκε για 12 | Εκδόθηκε από 13 | Περίοδος ισχύος 14 | %1$s – %2$s (δεν θα εφαρμοστεί) 15 | Αποτυπώματα 16 | Έχω πιστοποιήσει χειροκίνητα το δακτυλικό αποτύπωμα. 17 | Αποδοχή 18 | Απόρριψη 19 | Μπορείτε να επαναφέρετε όλα τα προσαρμοσμένα πιστοποιητικά στις ρυθμίσεις της εφαρμογής. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-es/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Seguridad de conexión 5 | Por favor, revisa el certificado 6 | 7 | Certificado rechazado temporalmente 8 | 9 | cert4android ha encontrado un certificado desconocido. ¿Quieres que sea válido? 10 | Detalles del certificado X509 11 | Expedido para 12 | Expedido por 13 | Periodo de validez 14 | %1$s – %2$s (no será aplicado) 15 | Huellas 16 | He verificado manualmente la huella entera. 17 | Aceptar 18 | Rechazar 19 | Puedes reiniciar todos los certificados particulares en los ajustes de la app. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-eu/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Konexio segurtasuna 5 | Mesedez egiaztatu ziurtagiria 6 | 7 | Ziurtagiria aldi baterako baztertuta 8 | 9 | cert4android ziurtagiri ezezagun bat aurkitu du. Fidagarritzat jo nahi duzu? 10 | X509 ziurtagiri xehetasunak 11 | Igortuta: 12 | Igorlea: 13 | Balio-epea 14 | %1$s – %2$s (ez da aplikatuko) 15 | Hatz-markak 16 | Hatz-marka osoa eskuz egiaztatu dut. 17 | Onartu 18 | Baztertu 19 | Ziurtagiri pertsonalizatu guztiak berrezarri ditzakezu aplikazioaren ezarpenetan. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-fa/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | امنیت اتصال 5 | لطفا گواهی‌نامه‌ی خود را بازبینی کنید 6 | 7 | گواهی‌نامه موقتاً رد شده‌است 8 | 9 | cert4android با یک گواهی‌نامه‌ی ناشناخته مواجه‌شده‌است. آیا به آن اعتماد می‌کنید؟ 10 | جزئیات گواهی‌نامه‌ی X509 11 | مشکل برای 12 | مشکل از 13 | دوره‌ی اعتبار 14 | اثر انگشت‌ها 15 | به صورت دستی تمام اثر انگشت را تایید می‌کنم 16 | قبول 17 | رد 18 | شما می‌توانید تمام گواهی‌نامه‌های سفارشی را در تنظیمات برنامه مجدداً تنظیم کنید. 19 | 20 | -------------------------------------------------------------------------------- /lib/src/main/res/values-fi/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Yhteyden suojaus 5 | Ole hyvä ja tarkista sertifikaatti 6 | 7 | Sertifikaatti hylätty väliaikaisesti 8 | 9 | cert4android on havainnut tuntemattoman sertifikaatin. Luotetaanko siihen? 10 | X509 sertifikaatin tiedot 11 | Myönnetty 12 | Myöntäjä 13 | Voimassaoloaika 14 | %1$s - %2$s (ei pakoteta) 15 | Sormenjäljet 16 | Olen manuaalisesti vahvistanut koko sormenjäljen. 17 | Hyväksy 18 | Hylkää 19 | Voit resetoida kaikki mukautetut sertifikaatit ohjelman asetuksista. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-fr/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Sécurité de la connexion 5 | Veuillez relire et vérifier le certificat 6 | 7 | Certificat provisoirement rejeté 8 | 9 | Ce certificat n\'est pas déjà référencé. 10 | Lui faites vous confiance? 11 | X509 détails du certificat 12 | Délivré pour 13 | Délivré par 14 | Période de validité 15 | %1$s – %2$s (ne sera pas appliquée) 16 | Empreinte 17 | J\'ai vérifié manuellement la totalité de l\'empreinte 18 | Accepter 19 | Refuser 20 | Vous pouvez réinitialiser tous les certificats personnalisés dans les paramètres de l\'application. 21 | 22 | -------------------------------------------------------------------------------- /lib/src/main/res/values-gl/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Seguridade da conexión 5 | Por favor revise o certificado 6 | 7 | Certificado temporalmente rexeitado 8 | 9 | cert4android atopou un certificado descoñecido. Quere confiar nel? 10 | Detalles do certificado X509 11 | Proporcionado para 12 | Proporcionado por 13 | Válido por 14 | %1$s – %2$s (non será imposto) 15 | Impresións dixitais 16 | Verifiquei manualmente a impresión dixital. 17 | Aceptar 18 | Rexeitar 19 | Pode restablecer os certificados personalizados nos axustes da app. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-hu/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Kapcsolat biztonsága 5 | Kérjük ellenőrizze a tanúsítványt. 6 | 7 | Tanúsítvány ideglenesen elutasítva 8 | 9 | Egy eddig ismeretlen tanúsítvány érkezett. Megbízik benne? 10 | X509 tanúsítvány részletei 11 | Tulajdonos 12 | Kibocsátó 13 | Érvényesség 14 | %1$s – %2$s (nem lesz kikényszerítve) 15 | Ujjlenyomatok 16 | Az ujjlenyomatokat ellenőriztem. 17 | Elfogadás 18 | Elutasítás 19 | Az alkalmazásbeállításoknál lehetőség van a korábban elfogadott tanúsítványok törlésére 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-it/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Sicurezza della connessione 5 | Si prega di controllare il certificato 6 | 7 | Certificato temporaneamente rifiutato 8 | 9 | cert4android ha trovato un certificato sconosciuto. Ritenerlo affidabile? 10 | X509 dettagli certificato 11 | Emesso per 12 | Emesso da 13 | Periodo di validità 14 | %1$s – %2$s (non sarà applicato) 15 | Impronte digitali 16 | Ho verificato manualmente l\'intera impronta digitale. 17 | Accetta 18 | Rifiuta 19 | È possibile azzerare tutti i certificati personalizzati nelle impostazioni dell\'app. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-ja/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 接続セキュリティ 5 | 証明書を確認してください 6 | 7 | 証明書は一時的に拒否されました 8 | 9 | cert4androidは、未知の証明書を検出しました。それを信頼しますか? 10 | X509 証明書の詳細 11 | 発行先 12 | 発行者 13 | 有効期間 14 | %1$s – %2$s (強制ではありません) 15 | フィンガープリント 16 | 私は手動でフィンガープリント全体を確認しました。 17 | 同意 18 | 拒否 19 | アプリの設定ですべてのカスタム証明書をリセットすることができます。 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-nb-rNO/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Tilkoblingssikkerhet 5 | Gransk sertifikatet 6 | 7 | Sertifikat midlertidig avvist 8 | 9 | cert4android har støtt på et ukjent sertifikat. Har du tiltro til det? 10 | X509-sertifikatsdetaljer 11 | Utstedt for 12 | Utstedt av 13 | Gyldighetsperiode 14 | %1$s – %2$s (vil ikke utøves) 15 | Fingeravtrykk 16 | Jeg har manuelt bekreftet hele fingeravtrykket. 17 | Godta 18 | Avslå 19 | Du kan tilbakestille alle egendefinerte sertifikater i programinnstillingene. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-nl/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Verbinding beveiliging 5 | Controleer de certificaten 6 | 7 | Certificaat tijdelijk afgewezen 8 | 9 | cert4android is benaderd door een onbekend certificaat. Wilt u dit vertrouwen? 10 | X509 certificaat details 11 | afgegeven voor 12 | afgegeven door 13 | Geldigheidsduur 14 | %1$s – %2$s (worden niet afgedwongen) 15 | Vingerafdruken 16 | Ik heb handmatig de gehele vingerafdruk gecontroleerd. 17 | Accepteren 18 | Afwijzen 19 | U can de bewerkte certificaten bij de app instellingen herstellen. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-pl/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Bezpieczeństwo połączenia 5 | Proszę zapoznać się z certyfikatem 6 | 7 | Certyfikat tymczasowo odrzucony 8 | 9 | cert4Android napotkał nieznany certyfikat. Czy chcesz go dodać? 10 | Szczegóły certyfikatu X509 11 | Wydane dla 12 | Wydane przez 13 | Okres ważności 14 | %1$s – %2$s (nie będzie egzekwowane) 15 | Odciski palców 16 | Muszę ręcznie zweryfikowane cały odcisk palca. 17 | Akceptuj 18 | Odrzuć 19 | Można przywrócić wszystkie niestandardowe certyfikaty w ustawieniach aplikacji. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-pt/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Segurança da conexão 5 | Por favor, verifique o certificado 6 | 7 | Certificado rejeitado temporariamente 8 | 9 | O cert4android encontrou um certificado desconhecido. Deseja torná-lo confiável? 10 | Detalhes do certificado X509 11 | Emitido para 12 | Emitido por 13 | Período de validade 14 | %1$s – %2$s (não será aplicado) 15 | Impressões digitais 16 | Verifiquei manualmente toda a impressão digital. 17 | Aceitar 18 | Rejeitar 19 | Você pode redefinir todos os certificados personalizados nas configurações do aplicativo. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-ru/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Безопасность подключения 5 | Просмотрите сертификат 6 | 7 | Сертификат временно отклонен 8 | 9 | cert4android обнаружил неизвестный сертификат. Вы хотите доверять ему? 10 | Данные сертификата X509 11 | Выдан 12 | Кем выдан 13 | Срок действия 14 | %1$s – %2$s (не будет применяться) 15 | Отпечатки 16 | Я вручную проверил весь отпечаток. 17 | Принять 18 | Отклонить 19 | Вы можете сбросить все пользовательские сертификаты в настройках приложения. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-sk/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Zabezpečenie spojenia 5 | Skontrolujte, prosím, certifikát 6 | 7 | Certifikát bol dočasne odmietnutý 8 | 9 | cert4android zistil neznámy certifikát. Prajete si dôverovať mu? 10 | Detaily X509 certifikátu 11 | Vydaný pre 12 | Vydaný 13 | Obdobie platnosti 14 | %1$s – %2$s (nebude sa vynucovať) 15 | Odtlačky 16 | Manuálne som skontroloval celý odtlačok. 17 | Prijať 18 | Odmietnuť 19 | V nastavení aplikácie môžete vynulovať všetky používateľské certifikáty 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-sl-rSI/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Varnost povezave 5 | Prosim preverite certifikat 6 | 7 | Certifikat je začasno onemogočen 8 | 9 | Cert4android ne prepozna certifikata. Ali vi zaupate certifikatu? 10 | X509 podrobnosti certifikata 11 | Izdano za 12 | Izdano od 13 | Obdobje veljave 14 | %1$s - %2$s (ne bo prisilno uporabljeno) 15 | Prstni odtisi 16 | Sem ročno preveril celoten prstni odtis. 17 | Sprejmi 18 | Zavrni 19 | V nastavitvah aplikacije lahko ponastavite vse certifikate. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-sr/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Безбедност везе 5 | Прегледајте сертификат 6 | 7 | Сертификат привремено одбијен 8 | 9 | серт-за-Андроид је наишао на непознат сертификат. Желите ли да се поуздате у њега? 10 | Детаљи X509 сертификата 11 | Издат за 12 | Издавач 13 | Период важења 14 | %1$s – %2$s (неће бити спроведен) 15 | Отисци 16 | Ручно сам проверио читав отисак. 17 | Прихвати 18 | Одбиј 19 | Можете да ресетујете све прилагођене сертификате у поставкама апликације. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-szl/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Bezpieczyństwo połōnczynio 5 | Przejzdrzij certyfikat 6 | 7 | Certyfikat tymczasowo ôdciepniynty 8 | 9 | cert4android trefiōł niyznōmy certyfikat. Chcesz mu zaufać? 10 | Informacyje ô certyfikacie X509 11 | Wydane dlo 12 | Wydane ôd 13 | Ôkres ważności 14 | %1$s – %2$s (niy bydzie wymuszany) 15 | Ôdciski palcōw 16 | Cołki ôdcisk palca bōł ryncznie zweryfikowany. 17 | Akceptuj 18 | Ôdciep 19 | We sztelōnkach aplikacyje możesz zresetować wszyjske włosne certyfikaty. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-tr/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /lib/src/main/res/values-uk/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Безпека з\'єднання 5 | Будь ласка, огляньте сертифікат 6 | 7 | Сертифікат тимчасово відхилено 8 | 9 | cert4android зіткнувся з невідомим сертифікатом. Чи довіряти йому? 10 | Подробиці сертифікату X509 11 | Видано для 12 | Видано 13 | Термін дії 14 | %1$s – %2$s (не буде виконано) 15 | Відбитки 16 | Я вручну перевірив весь відбиток. 17 | Прийняти 18 | Відхилити 19 | Ви можете скинути всі сертифікати користувача в налаштуваннях додатку. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-vi/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Sự bảo mật của kết nối 5 | Vui lòng xem xét chứng chỉ 6 | 7 | Đã tạm thời từ chối chứng chỉ 8 | 9 | cert4android đã gặp một chứng chỉ không xác định. Bạn có muốn tin tưởng nó không? 10 | Chi tiết chứng chỉ X509 11 | Được cấp cho 12 | Được cấp bởi 13 | Thời gian hợp lệ 14 | %1$s – %2$s (sẽ không được thi hành) 15 | Mã kiểm tra 16 | Tôi đã xác minh toàn bộ mã kiểm tra theo cách thủ công. 17 | Chấp nhận 18 | Từ chối 19 | Bạn có thể đặt lại tất cả chứng chỉ tuỳ chỉnh trong cài đặt ứng dụng. 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-zh-rTW/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 連線安全性 5 | 請檢視憑證 6 | 7 | 憑證被臨時拒絕 8 | 9 | cert4android 收到不認識的憑證,您要信賴它嗎? 10 | X509 憑證細節 11 | 發行給 12 | 發行人 13 | 有效期限 14 | %1$s – %2$s (將不會執行) 15 | 指紋 16 | 我以手動驗證過整個指紋 17 | 接受 18 | 拒絕 19 | 您可以在程式的設定裡重設所有自訂的憑證 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values-zh/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 连接安全性 5 | 请检查证书 6 | 7 | 证书被临时拒绝 8 | 9 | cert4android 遇到了未知证书。你是否要信任该证书? 10 | X509 证书信息 11 | 签发给 12 | 签发者 13 | 有效期 14 | %1$s – %2$s(过期后仍会信任) 15 | 指纹 16 | 我已经检查了整个指纹 17 | 接受 18 | 拒绝 19 | 你可以在应用内的设置中重设证书信任状态。 20 | 21 | -------------------------------------------------------------------------------- /lib/src/main/res/values/about_strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Ricki Hirner 6 | https://www.bitfire.at 7 | cert4android 8 | Library for managing custom certificates in an app-private key store 9 | https://github.com/bitfireAT/cert4android 10 | gpl_3_0 11 | true 12 | 13 | -------------------------------------------------------------------------------- /lib/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Connection security 5 | Please review the certificate 6 | 7 | Certificate temporarily rejected 8 | 9 | 10 | cert4android has encountered an unknown certificate. Do you want to trust it? 11 | X509 certificate details 12 | Issued for 13 | Issued by 14 | Validity period 15 | %1$s – %2$s (will not be enforced) 16 | Fingerprints 17 | I have manually verified the whole fingerprint. 18 | Accept 19 | Reject 20 | You can reset all custom certificates in the app settings. 21 | Press Back again to reject certificate 22 | 23 | -------------------------------------------------------------------------------- /lib/src/test/java/at/bitfire/cert4android/CertUtilsTest.kt: -------------------------------------------------------------------------------- 1 | /*************************************************************************************************** 2 | * Copyright © All Contributors. See LICENSE and AUTHORS in the root directory for details. 3 | **************************************************************************************************/ 4 | 5 | package at.bitfire.cert4android 6 | 7 | import org.junit.Assert.assertEquals 8 | import org.junit.Assert.assertNotNull 9 | import org.junit.Test 10 | import java.security.cert.CertificateFactory 11 | import java.security.cert.X509Certificate 12 | import java.security.spec.MGF1ParameterSpec 13 | 14 | class CertUtilsTest { 15 | 16 | private val certFactory = CertificateFactory.getInstance("X.509")!! 17 | 18 | 19 | @Test 20 | fun testGetTrustManagerSystem() { 21 | assertNotNull(CertUtils.getTrustManager(null)) 22 | } 23 | 24 | @Test 25 | fun testFingerprint() { 26 | javaClass.classLoader!!.getResourceAsStream("davdroid-web.crt").use { stream -> 27 | val cert = certFactory.generateCertificate(stream) as X509Certificate 28 | assertEquals("8D:E5:74:B2:AA:3E:5C:EE:62:84:4A:3B:78:71:B6:C3", CertUtils.fingerprint(cert, "MD5")) 29 | assertEquals("6C:83:A0:12:1A:F5:55:BF:C2:BC:23:DA:78:E4:5F:88:6E:01:0A:BC", CertUtils.fingerprint(cert, MGF1ParameterSpec.SHA1.digestAlgorithm)) 30 | } 31 | } 32 | 33 | @Test 34 | fun testGetTag() { 35 | javaClass.classLoader!!.getResourceAsStream("davdroid-web.crt").use { stream -> 36 | val cert = certFactory.generateCertificate(stream) as X509Certificate 37 | assertNotNull(cert) 38 | 39 | assertEquals( 40 | "4F91DE498B026C600389A9F40D37CBC6A74DBCA060CA0F927556A88B67CC6C8B15D2F7B93B3FA1407AD49994CB3DEA6FA72851A5B680B283E449CEB25B6559A2", 41 | CertUtils.getTag(cert) 42 | ) 43 | } 44 | } 45 | 46 | @Test 47 | fun testHexString() { 48 | assertEquals("", CertUtils.hexString(ByteArray(0))) 49 | assertEquals("00:01:02:03:04:05:06:07:08:09:0A:0B:0C:0D:0E:0F:10", CertUtils.hexString(ByteArray(17) { i -> i.toByte() })) 50 | } 51 | 52 | } -------------------------------------------------------------------------------- /lib/src/test/resources/davdroid-web.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIGHzCCBQegAwIBAgISA3zwINiFuH0OAMuSPAZYiT10MA0GCSqGSIb3DQEBCwUA 3 | MEoxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MSMwIQYDVQQD 4 | ExpMZXQncyBFbmNyeXB0IEF1dGhvcml0eSBYMzAeFw0xNjA5MTQxMzE3MDBaFw0x 5 | NjEyMTMxMzE3MDBaMB4xHDAaBgNVBAMTE2RhdmRyb2lkLmJpdGZpcmUuYXQwggIi 6 | MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQC165XMJbQURgWtYYGz5R95LEsg 7 | GzRtVXA5zR4dw3UrK0GD93nEJKHsa1a4c22nzPZDfMkYk3/oPpglg/Zx8ZgDaGDn 8 | OCVbApYNPpPNQ7+15utpFfJqAEo5BR+kWWk3MYB8LtUupZBzO2crmfQn9qMgI/AV 9 | OzrHnrecFqPr1QgMn3tIYtTd2Yp9fKG4qYVRAuyVeR8pL+GDvyeb5NLQ6O/UgKMY 10 | Qn2n+ayIowfLtRgT/kCVb0E0WTn2sZQ5sjxSsglsQGCx0p8yf9m3WJz4RtWR55lH 11 | Vpo2Q3QDYSMjeK2gYuRmdjtolgwLbv0T79pLBCqzI5ZbQhofym/aYdG2igeSylvc 12 | 5uQ+TXvbnIuLpF5JeSpR4UQIc6aFvNZHW8ed3sK3BTTSsE319XIJNhNo4qrBifzw 13 | nLBU4RMGl9ut+aCAauFgGt5kEw0CMTy//OQPgfoMeEIt7yPIm/tJ7kUFd5YLxvZY 14 | gvmT8F0SZPw+fAvfBbWGiocxw7jAx7Sx/xUBsfWYZavU0cM/KXntBkgNr5byXdAk 15 | iPhKzf4OKdsjzZ/PL/hKB31hoQOASLoCx4CKhNOdqCZmUuP88x0tdMYsBB2kYBmi 16 | D516Zr9Kldvyb4ve8KAuZwzyGy/lC/+AImtafq5IpyLLiLhWfrXTGDd+Zv1I54lG 17 | SX+vpfE9VktGgiTjwwIDAQABo4ICKTCCAiUwDgYDVR0PAQH/BAQDAgWgMB0GA1Ud 18 | JQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAMBgNVHRMBAf8EAjAAMB0GA1UdDgQW 19 | BBQu2Cdd5cy2Oe/68ppKQNEK+tNofjAfBgNVHSMEGDAWgBSoSmpjBH3duubRObem 20 | RWXv86jsoTBwBggrBgEFBQcBAQRkMGIwLwYIKwYBBQUHMAGGI2h0dHA6Ly9vY3Nw 21 | LmludC14My5sZXRzZW5jcnlwdC5vcmcvMC8GCCsGAQUFBzAChiNodHRwOi8vY2Vy 22 | dC5pbnQteDMubGV0c2VuY3J5cHQub3JnLzAzBgNVHREELDAqghNkYXZkcm9pZC5i 23 | aXRmaXJlLmF0ghNpY3Nkcm9pZC5iaXRmaXJlLmF0MIH+BgNVHSAEgfYwgfMwCAYG 24 | Z4EMAQIBMIHmBgsrBgEEAYLfEwEBATCB1jAmBggrBgEFBQcCARYaaHR0cDovL2Nw 25 | cy5sZXRzZW5jcnlwdC5vcmcwgasGCCsGAQUFBwICMIGeDIGbVGhpcyBDZXJ0aWZp 26 | Y2F0ZSBtYXkgb25seSBiZSByZWxpZWQgdXBvbiBieSBSZWx5aW5nIFBhcnRpZXMg 27 | YW5kIG9ubHkgaW4gYWNjb3JkYW5jZSB3aXRoIHRoZSBDZXJ0aWZpY2F0ZSBQb2xp 28 | Y3kgZm91bmQgYXQgaHR0cHM6Ly9sZXRzZW5jcnlwdC5vcmcvcmVwb3NpdG9yeS8w 29 | DQYJKoZIhvcNAQELBQADggEBACdhJqgHg+4WuEgR4elul3oFrA+YDFhsyXhNlagE 30 | Jgxt3eoRciZvIQ7y2UY/7mCv54dSdL3GW5GDj2W6VmpR5V4UPnxAlI618xTSU9Nq 31 | aVI1xt94Lnc/hFVDHpBdZdXUiaTor8/cLc64ul9wb3HHUQbKro1N5WcNNyHHIt8R 32 | oPN3sTrKRSU5mVTDFBTctUScvjtERZWzGVK7V4Kv8H0NT/P+7+q+gzKn/vR9ZPKV 33 | RqEn5GHtly5dG74OvKkW7Q+wO4HsTGAZrC8BufbCLfv0+2kFZIdNyOfuOsKsDyly 34 | LKNTF4ZeHKw8Sh+5eA+v0ch2PhtIVNYwZ7kezgKYM+lQa3U= 35 | -----END CERTIFICATE----- 36 | -------------------------------------------------------------------------------- /run-tests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ./gradlew -i check connectedCheck 4 | 5 | echo 6 | echo View lint report: 7 | echo -n file:// 8 | realpath build/outputs/lint-results-debug.html 9 | 10 | echo 11 | echo View local unit test reports: 12 | echo -n file:// 13 | realpath build/reports/tests/testDebugUnitTest/debug/index.html 14 | echo -n file:// 15 | realpath build/reports/tests/testReleaseUnitTest/release/index.html 16 | 17 | echo 18 | echo "View connected unit test reports (debug):" 19 | echo -n file:// 20 | realpath build/reports/androidTests/connected/index.html 21 | -------------------------------------------------------------------------------- /sample-app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /sample-app/build.gradle.kts: -------------------------------------------------------------------------------- 1 | plugins { 2 | alias(libs.plugins.android.application) 3 | alias(libs.plugins.compose.compiler) 4 | alias(libs.plugins.kotlin.android) 5 | } 6 | 7 | android { 8 | namespace = "at.bitfire.cert4android.demo" 9 | compileSdk = 35 10 | 11 | defaultConfig { 12 | applicationId = "at.bitfire.cert4android.demo" 13 | versionCode = 1 14 | versionName = "1.0.0" 15 | 16 | minSdk = 21 17 | targetSdk = 35 18 | 19 | vectorDrawables { 20 | useSupportLibrary = true 21 | } 22 | } 23 | 24 | compileOptions { 25 | sourceCompatibility = JavaVersion.VERSION_21 26 | targetCompatibility = JavaVersion.VERSION_21 27 | } 28 | kotlin { 29 | jvmToolchain(21) 30 | } 31 | 32 | buildTypes { 33 | release { 34 | proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt")) 35 | } 36 | } 37 | 38 | buildFeatures { 39 | compose = true 40 | } 41 | } 42 | 43 | dependencies { 44 | implementation(libs.androidx.core) 45 | implementation(libs.androidx.lifecycle.runtime) 46 | 47 | implementation(libs.androidx.appcompat) 48 | 49 | implementation(libs.androidx.activityCompose) 50 | implementation(platform(libs.compose.bom)) 51 | implementation(libs.compose.material3) 52 | implementation(libs.compose.ui.base) 53 | implementation(libs.compose.ui.graphics) 54 | debugImplementation(libs.compose.ui.toolingPreview) 55 | implementation(libs.compose.runtime.livedata) 56 | 57 | implementation(project(":cert4android")) 58 | } -------------------------------------------------------------------------------- /sample-app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 15 | 16 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /sample-app/src/main/java/at/bitfire/cert4android/demo/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package at.bitfire.cert4android.demo 2 | 3 | import android.Manifest 4 | import android.annotation.SuppressLint 5 | import android.app.Application 6 | import android.content.pm.PackageManager 7 | import android.net.SSLCertificateSocketFactory 8 | import android.os.Build 9 | import android.os.Bundle 10 | import android.util.Log 11 | import androidx.activity.ComponentActivity 12 | import androidx.activity.compose.setContent 13 | import androidx.activity.viewModels 14 | import androidx.compose.foundation.layout.Column 15 | import androidx.compose.foundation.layout.Row 16 | import androidx.compose.foundation.layout.padding 17 | import androidx.compose.foundation.rememberScrollState 18 | import androidx.compose.foundation.verticalScroll 19 | import androidx.compose.material3.Button 20 | import androidx.compose.material3.Checkbox 21 | import androidx.compose.material3.SnackbarHost 22 | import androidx.compose.material3.SnackbarHostState 23 | import androidx.compose.material3.Text 24 | import androidx.compose.runtime.LaunchedEffect 25 | import androidx.compose.runtime.collectAsState 26 | import androidx.compose.runtime.livedata.observeAsState 27 | import androidx.compose.runtime.remember 28 | import androidx.compose.ui.Modifier 29 | import androidx.compose.ui.unit.dp 30 | import androidx.core.app.ActivityCompat 31 | import androidx.lifecycle.AndroidViewModel 32 | import androidx.lifecycle.MutableLiveData 33 | import androidx.lifecycle.viewModelScope 34 | import at.bitfire.cert4android.Cert4Android 35 | import at.bitfire.cert4android.CustomCertManager 36 | import at.bitfire.cert4android.CustomCertStore 37 | import kotlinx.coroutines.Dispatchers 38 | import kotlinx.coroutines.flow.MutableStateFlow 39 | import kotlinx.coroutines.launch 40 | import org.apache.http.conn.ssl.AllowAllHostnameVerifier 41 | import org.apache.http.conn.ssl.StrictHostnameVerifier 42 | import java.net.URL 43 | import javax.net.ssl.HttpsURLConnection 44 | 45 | class MainActivity : ComponentActivity() { 46 | 47 | private val model by viewModels() 48 | 49 | 50 | override fun onCreate(savedInstanceState: Bundle?) { 51 | super.onCreate(savedInstanceState) 52 | 53 | if (Build.VERSION.SDK_INT >= 33 && ActivityCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) 54 | ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.POST_NOTIFICATIONS), 0) 55 | 56 | setContent { 57 | Cert4Android.theme { 58 | Column(Modifier 59 | .padding(8.dp) 60 | .verticalScroll(rememberScrollState())) { 61 | Row { 62 | Checkbox(model.appInForeground.collectAsState().value, onCheckedChange = { foreground -> 63 | model.setInForeground(foreground) 64 | }) 65 | Text("App in foreground") 66 | } 67 | 68 | Button(onClick = { 69 | model.testAccess("https://www.github.com") 70 | }, modifier = Modifier.padding(top = 16.dp)) { 71 | Text("Access normal URL with trusted system certs") 72 | } 73 | 74 | Button(onClick = { 75 | model.testAccess("https://www.github.com", trustSystemCerts = false) 76 | }, modifier = Modifier.padding(top = 16.dp)) { 77 | Text("Access normal URL with distrusted system certs") 78 | } 79 | 80 | Button(onClick = { 81 | model.testAccess("https://expired.badssl.com/") 82 | }, modifier = Modifier.padding(top = 16.dp)) { 83 | Text("Access URL with expired certificate") 84 | } 85 | 86 | Button(onClick = { 87 | model.testAccess("https://self-signed.badssl.com/") 88 | }, modifier = Modifier.padding(top = 16.dp)) { 89 | Text("Access URL with self-signed certificate") 90 | } 91 | 92 | Button(onClick = { 93 | model.testAccess("https://wrong.host.badssl.com/") 94 | }, modifier = Modifier.padding(top = 16.dp)) { 95 | Text("Access URL with certificate for wrong host name") 96 | } 97 | 98 | Button(onClick = { 99 | model.testAccess("https://wrong.host.badssl.com/", trustSystemCerts = false) 100 | }, modifier = Modifier.padding(top = 16.dp)) { 101 | Text("Access URL with certificate for wrong host name with distrusted system certs") 102 | } 103 | 104 | Button(onClick = { 105 | model.reset() 106 | }, modifier = Modifier.padding(top = 16.dp)) { 107 | Text("Clear trusted certs") 108 | } 109 | 110 | val snackBarHostState = remember { SnackbarHostState() } 111 | val result = model.resultMessage.observeAsState() 112 | result.value?.let { msg -> 113 | if (msg.isNotEmpty()) 114 | LaunchedEffect(snackBarHostState) { 115 | snackBarHostState.showSnackbar(msg) 116 | model.resultMessage.value = null 117 | } 118 | } 119 | SnackbarHost(snackBarHostState) 120 | } 121 | } 122 | } 123 | } 124 | 125 | 126 | class Model(application: Application): AndroidViewModel(application) { 127 | 128 | val appInForeground = MutableStateFlow(true) 129 | val resultMessage = MutableLiveData() 130 | 131 | init { 132 | // The default HostnameVerifier is called before our per-connection HostnameVerifier. 133 | @SuppressLint("AllowAllHostnameVerifier") 134 | HttpsURLConnection.setDefaultHostnameVerifier(AllowAllHostnameVerifier()) 135 | } 136 | 137 | fun reset() = viewModelScope.launch(Dispatchers.IO) { 138 | CustomCertStore.getInstance(getApplication()).clearUserDecisions() 139 | } 140 | 141 | fun setInForeground(foreground: Boolean) { 142 | appInForeground.value = foreground 143 | } 144 | 145 | fun testAccess(url: String, trustSystemCerts: Boolean = true) = viewModelScope.launch(Dispatchers.IO) { 146 | try { 147 | val urlConn = URL(url).openConnection() as HttpsURLConnection 148 | 149 | // set cert4android TrustManager and HostnameVerifier 150 | val certMgr = CustomCertManager( 151 | getApplication(), 152 | trustSystemCerts = trustSystemCerts, 153 | appInForeground = appInForeground 154 | ) 155 | urlConn.hostnameVerifier = certMgr.HostnameVerifier(StrictHostnameVerifier()) 156 | urlConn.sslSocketFactory = object : SSLCertificateSocketFactory(/* handshakeTimeoutMillis = */ 1000) { 157 | init { 158 | setTrustManagers(arrayOf(certMgr)) 159 | } 160 | } 161 | 162 | // access sample URL 163 | Log.i(Cert4Android.TAG, "testAccess(): HTTP ${urlConn.responseCode}") 164 | resultMessage.postValue("${urlConn.responseCode} ${urlConn.responseMessage}") 165 | urlConn.inputStream.close() 166 | } catch (e: Exception) { 167 | resultMessage.postValue("testAccess() ERROR: ${e.message}") 168 | Log.w(Cert4Android.TAG, "testAccess(): ERROR: ${e.message}") 169 | } 170 | } 171 | 172 | } 173 | 174 | } -------------------------------------------------------------------------------- /sample-app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /sample-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 | -------------------------------------------------------------------------------- /sample-app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /sample-app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /sample-app/src/main/res/mipmap-hdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitfireAT/cert4android/b67ba86d313ceb622d7717ad7b587abc74a2caa9/sample-app/src/main/res/mipmap-hdpi/ic_launcher.webp -------------------------------------------------------------------------------- /sample-app/src/main/res/mipmap-hdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitfireAT/cert4android/b67ba86d313ceb622d7717ad7b587abc74a2caa9/sample-app/src/main/res/mipmap-hdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /sample-app/src/main/res/mipmap-mdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitfireAT/cert4android/b67ba86d313ceb622d7717ad7b587abc74a2caa9/sample-app/src/main/res/mipmap-mdpi/ic_launcher.webp -------------------------------------------------------------------------------- /sample-app/src/main/res/mipmap-mdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitfireAT/cert4android/b67ba86d313ceb622d7717ad7b587abc74a2caa9/sample-app/src/main/res/mipmap-mdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /sample-app/src/main/res/mipmap-xhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitfireAT/cert4android/b67ba86d313ceb622d7717ad7b587abc74a2caa9/sample-app/src/main/res/mipmap-xhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /sample-app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitfireAT/cert4android/b67ba86d313ceb622d7717ad7b587abc74a2caa9/sample-app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /sample-app/src/main/res/mipmap-xxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitfireAT/cert4android/b67ba86d313ceb622d7717ad7b587abc74a2caa9/sample-app/src/main/res/mipmap-xxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /sample-app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitfireAT/cert4android/b67ba86d313ceb622d7717ad7b587abc74a2caa9/sample-app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /sample-app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitfireAT/cert4android/b67ba86d313ceb622d7717ad7b587abc74a2caa9/sample-app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp -------------------------------------------------------------------------------- /sample-app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bitfireAT/cert4android/b67ba86d313ceb622d7717ad7b587abc74a2caa9/sample-app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp -------------------------------------------------------------------------------- /sample-app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | cert4android Demo 3 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | google() 4 | mavenCentral() 5 | gradlePluginPortal() 6 | } 7 | } 8 | dependencyResolutionManagement { 9 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 10 | repositories { 11 | google() 12 | mavenCentral() 13 | } 14 | } 15 | rootProject.name = "root" 16 | include ':sample-app' 17 | include ':lib' 18 | project(':lib').name = 'cert4android' 19 | --------------------------------------------------------------------------------