├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── app
├── build.gradle
└── src
│ └── main
│ ├── AndroidManifest.xml
│ ├── java
│ └── com
│ │ └── android
│ │ └── example
│ │ ├── FakeFileProvider.kt
│ │ └── MainActivity.kt
│ └── res
│ ├── layout
│ └── tapjacking.xml
│ └── xml
│ ├── file_paths.xml
│ ├── network_security_config.xml
│ └── strings.xml
├── build.gradle
├── checks
├── build.gradle
└── src
│ ├── main
│ ├── java
│ │ └── com
│ │ │ └── example
│ │ │ └── lint
│ │ │ └── checks
│ │ │ ├── BadCryptographyUsageDetector.kt
│ │ │ ├── BluetoothAdapterDetector.kt
│ │ │ ├── CustomSchemeDetector.kt
│ │ │ ├── DnsConfigDetector.kt
│ │ │ ├── InsecureStorageDetector.kt
│ │ │ ├── IssueRegistry.kt
│ │ │ ├── LogcatDetector.kt
│ │ │ ├── MisconfiguredFileProviderDetector.kt
│ │ │ ├── MissingNetworkSecurityConfigDetector.kt
│ │ │ ├── PermissionDetector.kt
│ │ │ ├── SafeBrowsingDetector.kt
│ │ │ ├── StickyBroadcastsDetector.kt
│ │ │ ├── StrandhoggDetector.kt
│ │ │ ├── TapjackingDetector.kt
│ │ │ ├── UnintendedExposedUrlDetector.kt
│ │ │ └── WeakPrngDetector.kt
│ └── resources
│ │ └── META-INF
│ │ └── services
│ │ └── com.android.tools.lint.client.api.IssueRegistry
│ └── test
│ └── java
│ └── com
│ └── example
│ └── lint
│ └── checks
│ ├── BadCryptographyUsageDetectorTest.kt
│ ├── BluetoothAdapterDetectorTest.kt
│ ├── CustomSchemeDetectorTest.kt
│ ├── DnsConfigDetectorTest.kt
│ ├── InsecureStorageDetectorTest.kt
│ ├── LogcatDetectorTest.kt
│ ├── MisconfiguredFileProviderDetectorTest.kt
│ ├── MissingNetworkSecurityConfigDetectorTest.kt
│ ├── PermissionDetectorTest.kt
│ ├── SafeBrowsingDetectorTest.kt
│ ├── StickyBroadcastsDetectorTest.kt
│ ├── StrandhoggDetectorTest.kt
│ ├── TapjackingDetectorTest.kt
│ ├── UnintendedExposedUrlDetectorTest.kt
│ └── WeakPrngDetectorTest.kt
├── docs
├── code-of-conduct.md
└── contributing.md
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | .gradle
3 | app/build
4 | build
5 | checks/build
6 | checks/lint-report.html
7 | local.properties
8 | .github/
9 | lint-results.sarif
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # How to become a contributor and submit your own code
2 |
3 | ## Contributor License Agreements
4 |
5 | We'd love to accept your sample apps and patches! Before we can take them, we
6 | have to jump a couple of legal hurdles.
7 |
8 | Please fill out either the individual or corporate Contributor License Agreement
9 | (CLA).
10 |
11 | * If you are an individual writing original source code and you're sure you
12 | own the intellectual property, then you'll need to sign an
13 | [individual CLA](https://developers.google.com/open-source/cla/individual).
14 | * If you work for a company that wants to allow you to contribute your work,
15 | then you'll need to sign a
16 | [corporate CLA](https://developers.google.com/open-source/cla/corporate).
17 |
18 | Follow either of the two links above to access the appropriate CLA and
19 | instructions for how to sign and return it. Once we receive it, we'll be able to
20 | accept your pull requests.
21 |
22 | ## Contributing A Patch
23 |
24 | 1. Submit an issue describing your proposed change to the repo in question.
25 | 1. The repo owner will respond to your issue promptly.
26 | 1. If your proposed change is accepted, and you haven't already done so, sign a
27 | Contributor License Agreement (see details above).
28 | 1. Fork the desired repo, develop and test your code changes.
29 | 1. Ensure that your code adheres to the existing style in the sample to which
30 | you are contributing. Refer to the
31 | [Google Cloud Platform Samples Style Guide](https://github.com/GoogleCloudPlatform/Template/wiki/style.html)
32 | for the recommended coding standards for this organization.
33 | 1. Ensure that your code has an appropriate set of unit tests which all pass.
34 | 1. Submit a pull request.
35 |
36 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | plugins {
17 | id 'com.android.application'
18 | id 'kotlin-android'
19 | }
20 |
21 | android {
22 | compileSdkVersion 33
23 |
24 | defaultConfig {
25 | applicationId "com.android.example.lint_usage"
26 | minSdkVersion 21
27 | versionCode 1
28 | versionName "1.0"
29 | }
30 |
31 | compileOptions {
32 | sourceCompatibility JavaVersion.VERSION_17
33 | targetCompatibility JavaVersion.VERSION_17
34 | }
35 | kotlinOptions {
36 | jvmTarget = '17'
37 | }
38 | namespace 'com.android.example'
39 | lint {
40 | checkDependencies true
41 | // Produce report for CI:
42 | // https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/sarif-support-for-code-scanning
43 | sarifOutput file('../lint-results.sarif')
44 | textReport true
45 | }
46 | }
47 |
48 | dependencies {
49 | lintChecks project(':checks')
50 | }
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
19 |
20 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
36 |
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/app/src/main/java/com/android/example/FakeFileProvider.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.android.example
17 |
18 | import android.content.ContentProvider
19 | import android.content.ContentValues
20 | import android.database.Cursor
21 | import android.net.Uri
22 |
23 | class FakeFileProvider : ContentProvider() {
24 | override fun onCreate(): Boolean {
25 | TODO("Not yet implemented")
26 | }
27 |
28 | override fun query(p0: Uri, p1: Array?, p2: String?, p3: Array?, p4: String?): Cursor? {
29 | TODO("Not yet implemented")
30 | }
31 |
32 | override fun getType(p0: Uri): String? {
33 | TODO("Not yet implemented")
34 | }
35 |
36 | override fun insert(p0: Uri, p1: ContentValues?): Uri? {
37 | TODO("Not yet implemented")
38 | }
39 |
40 | override fun delete(p0: Uri, p1: String?, p2: Array?): Int {
41 | TODO("Not yet implemented")
42 | }
43 |
44 | override fun update(p0: Uri, p1: ContentValues?, p2: String?, p3: Array?): Int {
45 | TODO("Not yet implemented")
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/app/src/main/java/com/android/example/MainActivity.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.android.example
17 |
18 | import android.app.Activity
19 | import android.bluetooth.BluetoothAdapter
20 | import android.content.Intent
21 | import android.util.Log
22 | import java.lang.Math
23 | import javax.crypto.Cipher
24 |
25 | class MainActivity: Activity() {
26 | private fun triggerVulnerableCryptoAlgorithm() {
27 | Cipher.getInstance("RC4")
28 | }
29 |
30 | private fun triggerUnsafeCryptoAlgorithmUsage() {
31 | val algo = "AES"
32 | val mode = "CBC"
33 | val padding = "PKCS1Padding"
34 |
35 | Cipher.getInstance("$algo/$mode/$padding")
36 | }
37 |
38 | private fun triggerWeakPrng() {
39 | val random = Math.random() * 100
40 | }
41 |
42 | private fun triggerInsecureStickyBroadcastMethod() {
43 | val intent = Intent()
44 | this.sendStickyBroadcast(intent)
45 | }
46 |
47 | private fun triggerExtendedBluetoothDiscoveryDuration() {
48 | val discoverableIntent: Intent = Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).apply {
49 | putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 121)
50 | }
51 | }
52 |
53 | private fun triggerZeroBluetoothDiscoveryDuration() {
54 | val discoverableIntent: Intent = Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).apply {
55 | putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0)
56 | }
57 | }
58 |
59 | private fun triggerLogInfoDisclosure() {
60 | Log.wtf("testpasswordtest", "test")
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/tapjacking.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
21 |
23 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/file_paths.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/network_security_config.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 |
20 |
21 | http://staging-app.com
22 | https://www.fakepreprodenvt.co.uk
23 | http://4.8.15.16
24 |
25 |
--------------------------------------------------------------------------------
/app/src/main/res/xml/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 | http://102.1.0.4/hello
19 | http://www.preprod-website.com
20 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | buildscript {
17 | ext {
18 | kotlinVersion = '1.9.20'
19 | gradlePluginVersion = '8.3.0'
20 | lintVersion = '31.5.1'
21 | }
22 |
23 | repositories {
24 | google()
25 | mavenCentral()
26 | }
27 | dependencies {
28 | classpath "com.android.tools.build:gradle:$gradlePluginVersion"
29 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
30 | }
31 | }
32 |
33 | allprojects {
34 | repositories {
35 | google()
36 | mavenCentral()
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/checks/build.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | apply plugin: 'java-library'
17 | apply plugin: 'kotlin'
18 | apply plugin: 'com.android.lint'
19 | apply plugin: 'maven-publish'
20 |
21 | lintOptions {
22 | htmlReport true
23 | htmlOutput file("lint-report.html")
24 | textReport true
25 | absolutePaths false
26 | ignoreTestSources true
27 | }
28 |
29 | java {
30 | withSourcesJar()
31 | withJavadocJar()
32 |
33 | sourceCompatibility = JavaVersion.VERSION_17
34 | targetCompatibility = JavaVersion.VERSION_17
35 | }
36 |
37 | dependencies {
38 | // For a description of the below dependencies, see the main project README
39 | compileOnly "com.android.tools.lint:lint-api:$lintVersion"
40 | // You typically don't need this one:
41 | compileOnly "com.android.tools.lint:lint-checks:$lintVersion"
42 | compileOnly "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
43 |
44 | testImplementation "junit:junit:4.13.2"
45 | testImplementation "com.android.tools.lint:lint:$lintVersion"
46 | testImplementation "com.android.tools.lint:lint-tests:$lintVersion"
47 | }
48 |
49 | publishing {
50 | publications {
51 | maven(MavenPublication) {
52 | groupId = 'com.android.security.lint'
53 | artifactId = 'lint'
54 | version = '1.0.3'
55 |
56 | from components.kotlin
57 |
58 | artifact sourcesJar
59 | artifact javadocJar
60 |
61 | pom {
62 | name = 'Android Security Lints'
63 | description = 'Custom security-focused experimental lint checks for Android development'
64 | url = 'https://github.com/google/android-security-lints'
65 | licenses {
66 | license {
67 | name = 'The Apache Software License, Version 2.0'
68 | url = 'http://www.apache.org/licenses/LICENSE-2.0.txt'
69 | distribution = 'repo'
70 | }
71 | }
72 |
73 | developers {
74 | developer {
75 | id = 'com.android.security.lint'
76 | name = 'Android Security Lint Contributors'
77 | url = 'https://github.com/google/android-security-lints'
78 | organization = 'Google - Android 3P Vulnerability Research'
79 | organizationUrl = 'https://www.google.com'
80 | }
81 | }
82 |
83 | scm {
84 | connection = 'scm:git:https://github.com/google/android-security-lints.git'
85 | developerConnection = 'scm:git:git@github.com:google/android-security-lints.git'
86 | url = 'https://github.com/google/android-security-lints'
87 | }
88 | }
89 | }
90 | }
91 |
92 | repositories {
93 | maven {
94 | url = layout.buildDirectory.dir('androidsecuritylints_m2repo')
95 | }
96 | }
97 | }
--------------------------------------------------------------------------------
/checks/src/main/java/com/example/lint/checks/BadCryptographyUsageDetector.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.tools.lint.detector.api.Category
19 | import com.android.tools.lint.detector.api.ConstantEvaluator
20 | import com.android.tools.lint.detector.api.Detector
21 | import com.android.tools.lint.detector.api.Implementation
22 | import com.android.tools.lint.detector.api.Incident
23 | import com.android.tools.lint.detector.api.Issue
24 | import com.android.tools.lint.detector.api.JavaContext
25 | import com.android.tools.lint.detector.api.Scope
26 | import com.android.tools.lint.detector.api.Severity
27 | import com.android.tools.lint.detector.api.SourceCodeScanner
28 | import com.intellij.psi.PsiMethod
29 | import org.jetbrains.uast.UCallExpression
30 |
31 | /**
32 | * Detector flagging whether the application uses weak or unsafe cryptographic algorithms.
33 | */
34 | class BadCryptographyUsageDetector: Detector(), SourceCodeScanner {
35 |
36 | override fun getApplicableMethodNames(): List = listOf(GET_INSTANCE)
37 |
38 | override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
39 | if (!context.evaluator.isMemberInSubClassOf(method, CRYPTO_CIPHER, false)) return
40 |
41 | val args = node.valueArguments
42 | // Currently only checking unsafe algorithms being passed in as an argument
43 | if (args.isEmpty()) return
44 | val transformation = ConstantEvaluator.evaluate(context, args[0])
45 |
46 | if (!handleVulnerableAlgorithmReporting(transformation.toString(), context, node)) {
47 | // If we haven't already warned about a vulnerable crypto algorithm being used
48 | // Check if we should warn about unsafe crypto algorithm usage
49 | handleUnsafeAlgorithmUsage(transformation.toString(), context, node)
50 | }
51 | }
52 |
53 | /**
54 | * Returns whether there was a reported VulnerableCryptoAlgorithm issue.
55 | *
56 | * This is needed so we don't accidentally also report that the algorithm is being used unsafely.
57 | */
58 | private fun handleVulnerableAlgorithmReporting(
59 | value: String, context: JavaContext, node: UCallExpression) : Boolean {
60 | val incident = Incident(
61 | VULNERABLE_ALGORITHM_ISSUE,
62 | node,
63 | context.getLocation(node),
64 | "Using vulnerable cryptographic algorithms puts the original input at risk of discovery"
65 | )
66 |
67 | if (VULNERABLE_BLOCK_CIPHER_ALGORITHMS.map{ value.startsWith(it) }.any{ it }) {
68 | incident.fix = fix().replace().range(context.getLocation(node))
69 | .with("Cipher.getInstance(\"$SAFE_BLOCK_CIPHER\")").build()
70 | context.report(incident)
71 | return true
72 | }
73 |
74 | if (VULNERABLE_STREAM_CIPHER_ALGORITHMS.map{ value.startsWith(it) }.any{ it }) {
75 | incident.fix = fix().replace().range(context.getLocation(node))
76 | .with("Cipher.getInstance(\"$SAFE_STREAM_CIPHER\")").build()
77 | context.report(incident)
78 | return true
79 | }
80 |
81 | return false
82 | }
83 |
84 | private fun handleUnsafeAlgorithmUsage(value: String, context: JavaContext, node: UCallExpression) {
85 | val setup = value.split('/')
86 | // If algorithm/mode/padding are not all specified, return
87 | if (setup.size != 3) return
88 | val algorithm = setup[0]
89 | val mode = setup[1]
90 | val padding = setup[2]
91 |
92 | val incident = Incident(
93 | UNSAFE_ALGORITHM_USAGE_ISSUE,
94 | node,
95 | context.getLocation(node),
96 | "Using insecure modes and paddings with cryptographic algorithms is unsafe and vulnerable to " +
97 | "attacks"
98 | )
99 |
100 | // Unsafe Cipher Padding
101 | // Acceptable for RSA to use CBC cipher mode with OAEPWithSHA-256AndMGF1Padding
102 | if (algorithm == "RSA" && padding == "PKCS1Padding") {
103 | incident.fix = fix().replace().range(context.getLocation(node))
104 | .with("Cipher.getInstance(\"RSA/$mode/OAEPWithSHA-256AndMGF1Padding\")").build()
105 | context.report(incident)
106 | }
107 |
108 | // Unsafe Cipher Mode
109 | else if (mode == "CBC") {
110 | if (padding == "NoPadding") {
111 | // This is a more serious issue, and should be an error instead of a warning
112 | incident.severity = Severity.ERROR
113 | } else if (algorithm == "RSA" && padding.startsWith("OAEP")) {
114 | // This is an acceptable combination of algorithm / mode / padding and does not need to be warned
115 | return
116 | }
117 | incident.fix = fix().replace().range(context.getLocation(node))
118 | .with("Cipher.getInstance(\"$algorithm/GCM/NoPadding\")").build()
119 | context.report(incident)
120 | }
121 | }
122 |
123 | companion object {
124 | // Classes
125 | private const val CRYPTO_CIPHER = "javax.crypto.Cipher"
126 |
127 | // Methods
128 | private const val GET_INSTANCE = "getInstance"
129 |
130 | // Argument values
131 | private val VULNERABLE_STREAM_CIPHER_ALGORITHMS = setOf("RC4", "ARCFOUR")
132 | private const val SAFE_STREAM_CIPHER = "ChaCha20"
133 | private val VULNERABLE_BLOCK_CIPHER_ALGORITHMS = setOf("Blowfish", "DES", "RC2", "RC5")
134 | private const val SAFE_BLOCK_CIPHER = "AES/GCM/NoPadding"
135 |
136 | private val IMPLEMENTATION = Implementation(BadCryptographyUsageDetector::class.java, Scope.JAVA_FILE_SCOPE)
137 |
138 | @JvmField
139 | val VULNERABLE_ALGORITHM_ISSUE: Issue =
140 | Issue.create(
141 | id = "VulnerableCryptoAlgorithm",
142 | briefDescription = "Application uses vulnerable cryptography algorithms",
143 | explanation =
144 | """
145 | Using weak or broken cryptographic hash functions may allow an attacker to reasonably determine \
146 | the original input or produce multiple inputs with the same hash value.
147 | """,
148 | category = Category.SECURITY,
149 | priority = 9,
150 | severity = Severity.ERROR,
151 | moreInfo = "https://goo.gle/VulnerableCryptoAlgorithm",
152 | implementation = IMPLEMENTATION
153 | )
154 |
155 | @JvmField
156 | val UNSAFE_ALGORITHM_USAGE_ISSUE: Issue =
157 | Issue.create(
158 | id = "UnsafeCryptoAlgorithmUsage",
159 | briefDescription = "Application uses unsafe cipher modes or paddings with cryptographic algorithms",
160 | explanation =
161 | """
162 | Using unsafe cipher modes or paddings with safe cryptographic algorithms is insecure, and \
163 | makes the code vulnerable to issues like padding oracle attacks.
164 | """,
165 | category = Category.SECURITY,
166 | priority = 8,
167 | severity = Severity.WARNING,
168 | moreInfo = "https://goo.gle/UnsafeCryptoAlgorithmUsage",
169 | implementation = IMPLEMENTATION
170 | )
171 | }
172 | }
--------------------------------------------------------------------------------
/checks/src/main/java/com/example/lint/checks/BluetoothAdapterDetector.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2024 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.tools.lint.detector.api.Category
19 | import com.android.tools.lint.detector.api.ConstantEvaluator
20 | import com.android.tools.lint.detector.api.Detector
21 | import com.android.tools.lint.detector.api.Implementation
22 | import com.android.tools.lint.detector.api.Incident
23 | import com.android.tools.lint.detector.api.Issue
24 | import com.android.tools.lint.detector.api.JavaContext
25 | import com.android.tools.lint.detector.api.Scope
26 | import com.android.tools.lint.detector.api.Severity
27 | import com.android.tools.lint.detector.api.SourceCodeScanner
28 | import com.intellij.psi.PsiMethod
29 | import org.jetbrains.uast.UCallExpression
30 |
31 | class BluetoothAdapterDetector : Detector(), SourceCodeScanner {
32 |
33 | override fun getApplicableMethodNames(): List = listOf(PUT_EXTRA_METHOD)
34 |
35 | override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
36 | if (!context.evaluator.isMemberInClass(method, INTENT_CLASS)) return
37 |
38 | val args = node.valueArguments
39 |
40 | if (args.isEmpty()) return
41 | val firstParam = ConstantEvaluator.evaluate(context, args[0])
42 | val secondParam = ConstantEvaluator.evaluate(context, args[1]) as? Int
43 |
44 | if (firstParam == "android.bluetooth.adapter.extra.DISCOVERABLE_DURATION" && (secondParam ?: 0) == 0) {
45 | val incident =
46 | Incident(
47 | ZERO_BLUETOOTH_DISCOVERY_DURATION_ISSUE,
48 | node,
49 | context.getLocation(node),
50 | "The EXTRA_DISCOVERABLE_DURATION time should never be set to zero",
51 | fix().replace().text((secondParam).toString()).with(RECOMMENDED_MAX_DISCOVERY_DURATION.toString()).build()
52 | )
53 | context.report(incident)
54 | }
55 |
56 | if (firstParam == "android.bluetooth.adapter.extra.DISCOVERABLE_DURATION" && (secondParam ?: 0) > 120) {
57 | val incident =
58 | Incident(
59 | EXTENDED_BLUETOOTH_DISCOVERY_DURATION_ISSUE,
60 | node,
61 | context.getLocation(node),
62 | "The EXTRA_DISCOVERABLE_DURATION time should be set to a shorter amount of time",
63 | fix().replace().text((secondParam).toString()).with(RECOMMENDED_MAX_DISCOVERY_DURATION.toString()).build()
64 | )
65 | context.report(incident)
66 | }
67 |
68 | }
69 |
70 | companion object {
71 | private const val INTENT_CLASS = "android.content.Intent"
72 | private const val PUT_EXTRA_METHOD = "putExtra"
73 | private const val RECOMMENDED_MAX_DISCOVERY_DURATION = 120
74 |
75 | @JvmField
76 | val ZERO_BLUETOOTH_DISCOVERY_DURATION_ISSUE: Issue =
77 | Issue.create(
78 | id = "ZeroBluetoothDiscoveryDuration",
79 | briefDescription = "The EXTRA_DISCOVERABLE_DURATION parameter is set to zero",
80 | explanation = """Setting the EXTRA_DISCOVERABLE_DURATION parameter to zero \
81 | will cause the device to be discoverable as long as the application is running \
82 | in the background or foreground.""",
83 | category = Category.SECURITY,
84 | priority = 9,
85 | severity = Severity.ERROR,
86 | moreInfo = "https://goo.gle/ZeroBluetoothDiscoveryDuration",
87 | implementation = Implementation(
88 | BluetoothAdapterDetector::class.java,
89 | Scope.JAVA_FILE_SCOPE
90 | )
91 | )
92 |
93 | @JvmField
94 | val EXTENDED_BLUETOOTH_DISCOVERY_DURATION_ISSUE: Issue =
95 | Issue.create(
96 | id = "ExtendedBluetoothDiscoveryDuration",
97 | briefDescription = "The EXTRA_DISCOVERABLE_DURATION parameter is unsafely high",
98 | explanation = """Setting the EXTRA_DISCOVERABLE_DURATION parameter to more than \
99 | 120 seconds can cause the device to be discoverable for an unsafe amount of time. \
100 | This could increase the timeframe in which attackers can conduct Bluetooth attacks.""",
101 | category = Category.SECURITY,
102 | priority = 7,
103 | severity = Severity.WARNING,
104 | moreInfo = "https://goo.gle/ExtendedBluetoothDiscoveryDuration",
105 | implementation = Implementation(
106 | BluetoothAdapterDetector::class.java,
107 | Scope.JAVA_FILE_SCOPE
108 | )
109 | )
110 |
111 | }
112 | }
--------------------------------------------------------------------------------
/checks/src/main/java/com/example/lint/checks/CustomSchemeDetector.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2024 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.SdkConstants.ANDROID_URI
19 | import com.android.SdkConstants.ATTR_AUTO_VERIFY
20 | import com.android.SdkConstants.TAG_DATA
21 | import com.android.SdkConstants.TAG_INTENT_FILTER
22 | import com.android.tools.lint.detector.api.Category
23 | import com.android.tools.lint.detector.api.Detector
24 | import com.android.tools.lint.detector.api.Implementation
25 | import com.android.tools.lint.detector.api.Incident
26 | import com.android.tools.lint.detector.api.Issue
27 | import com.android.tools.lint.detector.api.Scope
28 | import com.android.tools.lint.detector.api.Severity
29 | import com.android.tools.lint.detector.api.XmlContext
30 | import com.android.tools.lint.detector.api.XmlScanner
31 | import com.android.utils.childrenIterator
32 | import org.w3c.dom.Element
33 |
34 | /**
35 | * Detector flagging whether the application has issues verifying custom schemes (i.e. not http/https/file/ftp/ftps).
36 | */
37 | class CustomSchemeDetector : Detector(), XmlScanner {
38 | override fun getApplicableElements() = setOf(TAG_INTENT_FILTER)
39 |
40 | override fun visitElement(context: XmlContext, element: Element) {
41 | val autoVerifyAttribute = element.getAttributeNS(ANDROID_URI, ATTR_AUTO_VERIFY)
42 |
43 | if (autoVerifyAttribute != "true") {
44 | val incident =
45 | Incident(
46 | AUTOVERIFY_ATTRIBUTE_ISSUE,
47 | element,
48 | context.getLocation(element),
49 | "Custom scheme intent filters should explicitly set the `autoVerify` attribute to true",
50 | fix().set().android().attribute(ATTR_AUTO_VERIFY).value("true").build()
51 | )
52 |
53 | if (hasCustomSchemes(element)) {
54 | // Only have the lint check fire if there are custom schemes present
55 | context.report(incident)
56 | }
57 | }
58 | }
59 |
60 | private fun hasCustomSchemes(element: Element): Boolean {
61 | for (child in element.childrenIterator()) {
62 | if (child.nodeName == TAG_DATA && child.hasAttributes()) {
63 | for (i in 0 until child.attributes.length) {
64 | val attribute = child.attributes.item(i)
65 | val name = attribute.localName ?: continue
66 | val value = attribute.nodeValue
67 |
68 | if (value !in REGULAR_SCHEMES) {
69 | return true
70 | }
71 | }
72 | }
73 | }
74 | return false
75 | }
76 |
77 | companion object {
78 | private val REGULAR_SCHEMES = listOf("http", "https", "file", "ftp", "ftps")
79 |
80 | private const val EXPLANATION = """
81 | Intent filters should contain the `autoVerify` attribute and explicitly set it to true, in order \
82 | to signal to the system to automatically verify the associated hosts in your app's intent filters.
83 | """
84 |
85 | /** Issue describing the problem and pointing to the detector implementation. */
86 | @JvmField
87 | val AUTOVERIFY_ATTRIBUTE_ISSUE: Issue =
88 | Issue.create(
89 | // ID: used in @SuppressLint warnings etc
90 | id = "MissingAutoVerifyAttribute",
91 | // Title -- shown in the IDE's preference dialog, as category headers in the
92 | // Analysis results window, etc
93 | briefDescription = "Application has custom scheme intent filters with missing `autoVerify` attributes",
94 | // Full explanation of the issue; you can use some markdown markup such as
95 | // `monospace`, *italic*, and **bold**.
96 | explanation = EXPLANATION,
97 | category = Category.SECURITY,
98 | priority = 6,
99 | severity = Severity.WARNING,
100 | moreInfo = "https://goo.gle/MissingAutoVerifyAttribute",
101 | implementation =
102 | Implementation(CustomSchemeDetector::class.java, Scope.MANIFEST_SCOPE)
103 | )
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/checks/src/main/java/com/example/lint/checks/DnsConfigDetector.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2024 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.SdkConstants.ANDROID_URI
19 | import com.android.SdkConstants.ATTR_TARGET_SDK_VERSION
20 | import com.android.SdkConstants.TAG_USES_SDK
21 | import com.android.tools.lint.detector.api.Category
22 | import com.android.tools.lint.detector.api.Detector
23 | import com.android.tools.lint.detector.api.Implementation
24 | import com.android.tools.lint.detector.api.Incident
25 | import com.android.tools.lint.detector.api.Issue
26 | import com.android.tools.lint.detector.api.Severity
27 | import com.android.tools.lint.detector.api.Scope
28 | import com.android.tools.lint.detector.api.XmlContext
29 | import com.android.tools.lint.detector.api.XmlScanner
30 | import com.android.tools.lint.detector.api.targetSdkLessThan
31 | import org.w3c.dom.Element
32 |
33 | /**
34 | * Detector flagging whether the application has insecure DNS configurations.
35 | */
36 | class DnsConfigDetector : Detector(), XmlScanner {
37 | override fun getApplicableElements() = setOf(TAG_USES_SDK)
38 |
39 | override fun visitElement(context: XmlContext, element: Element) {
40 | val attribute = element.getAttributeNodeNS(ANDROID_URI, ATTR_TARGET_SDK_VERSION) ?: return
41 |
42 | val incident =
43 | Incident(
44 | SDK_LEVEL_ISSUE,
45 | element,
46 | context.getValueLocation(attribute),
47 | "Update your application's target SDK version to 28 and above to make use of the Android " +
48 | "OS's built-in transport security features",
49 | fix().set().android().attribute(ATTR_TARGET_SDK_VERSION).value(PATCHED_SDK_LEVEL.toString()).build()
50 | )
51 |
52 | context.report(incident, constraint = targetSdkLessThan(PATCHED_SDK_LEVEL))
53 | }
54 |
55 | companion object {
56 | const val PATCHED_SDK_LEVEL = 28
57 |
58 | /** Issue describing the problem and pointing to the detector implementation. */
59 | @JvmField
60 | val SDK_LEVEL_ISSUE: Issue =
61 | Issue.create(
62 | // ID: used in @SuppressLint warnings etc
63 | id = "InsecureDnsSdkLevel",
64 | // Title -- shown in the IDE's preference dialog, as category headers in the
65 | // Analysis results window, etc
66 | briefDescription = "Application vulnerable to DNS spoofing attacks",
67 | // Full explanation of the issue; you can use some markdown markup such as
68 | // `monospace`, *italic*, and **bold**.
69 | explanation =
70 | """
71 | Apps targeting SDK versions earlier than 28 are susceptible to DNS attacks like DNS spoofing or \
72 | cache poisoning
73 | """, // no need to .trimIndent(), lint does that automatically
74 | category = Category.SECURITY,
75 | priority = 8,
76 | severity = Severity.WARNING,
77 | moreInfo = "https://goo.gle/InsecureDnsSdkLevel",
78 | implementation =
79 | Implementation(DnsConfigDetector::class.java, Scope.MANIFEST_SCOPE)
80 | )
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/checks/src/main/java/com/example/lint/checks/InsecureStorageDetector.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2024 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.SdkConstants.ANDROID_URI
19 | import com.android.SdkConstants.TAG_APPLICATION
20 | import com.android.tools.lint.detector.api.Category
21 | import com.android.tools.lint.detector.api.Detector
22 | import com.android.tools.lint.detector.api.Implementation
23 | import com.android.tools.lint.detector.api.Incident
24 | import com.android.tools.lint.detector.api.Issue
25 | import com.android.tools.lint.detector.api.Scope
26 | import com.android.tools.lint.detector.api.Severity
27 | import com.android.tools.lint.detector.api.XmlContext
28 | import com.android.tools.lint.detector.api.XmlScanner
29 | import com.android.tools.lint.detector.api.targetSdkLessThan
30 | import org.w3c.dom.Element
31 |
32 |
33 | class InsecureStorageDetector : Detector(), XmlScanner {
34 | override fun getApplicableElements() = setOf(TAG_APPLICATION)
35 |
36 | override fun visitElement(context: XmlContext, element: Element) {
37 | val attrRequestLegacyStorage =
38 | element.getAttributeNodeNS(ANDROID_URI, ATTR_REQUEST_LEGACY_STORAGE) ?: return
39 |
40 | if (attrRequestLegacyStorage.value.toBoolean()) {
41 | val incident =
42 | Incident(
43 | LEGACY_EXTERNAL_STORAGE_ISSUE,
44 | attrRequestLegacyStorage,
45 | context.getLocation(attrRequestLegacyStorage),
46 | "Setting `requestLegacyExternalStorage` to `true` will disable Android Scoped Storage",
47 | fix().set().android().attribute(ATTR_REQUEST_LEGACY_STORAGE).value("false")
48 | .build(),
49 | )
50 | context.report(incident, constraint = targetSdkLessThan(PATCHED_SDK_LEVEL))
51 | }
52 | }
53 |
54 | companion object {
55 | private const val PATCHED_SDK_LEVEL = 30
56 | private const val ATTR_REQUEST_LEGACY_STORAGE = "requestLegacyExternalStorage"
57 |
58 | /** Issue describing the problem and pointing to the detector implementation. */
59 | @JvmField
60 | val LEGACY_EXTERNAL_STORAGE_ISSUE: Issue =
61 | Issue.create(
62 | id = "InsecureLegacyExternalStorage",
63 | briefDescription = "The `requestLegacyExternalStorage` attribute is set to true, opting the app out of scoped storage",
64 | explanation =
65 | """
66 | Applications targeting Android 10 can set the `requestLegacyExternalStorage` flag to \
67 | `true`, but this configuration opts the app out of Android Scoped Storage, making \
68 | application-related files in external storage accessible to other applications.
69 | """,
70 | category = Category.SECURITY,
71 | priority = 5,
72 | severity = Severity.WARNING,
73 | moreInfo = "https://goo.gle/InsecureLegacyExternalStorage",
74 | implementation =
75 | Implementation(
76 | InsecureStorageDetector::class.java,
77 | Scope.MANIFEST_SCOPE
78 | )
79 | )
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/checks/src/main/java/com/example/lint/checks/IssueRegistry.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.tools.lint.client.api.IssueRegistry
19 | import com.android.tools.lint.client.api.Vendor
20 | import com.android.tools.lint.detector.api.CURRENT_API
21 |
22 | /*
23 | * The list of issues that will be checked when running lint
.
24 | */
25 | class IssueRegistry : IssueRegistry() {
26 | override val issues = listOf(
27 | BadCryptographyUsageDetector.VULNERABLE_ALGORITHM_ISSUE,
28 | BadCryptographyUsageDetector.UNSAFE_ALGORITHM_USAGE_ISSUE,
29 | CustomSchemeDetector.AUTOVERIFY_ATTRIBUTE_ISSUE,
30 | DnsConfigDetector.SDK_LEVEL_ISSUE,
31 | StrandhoggDetector.ISSUE,
32 | TapjackingDetector.ISSUE,
33 | MissingNetworkSecurityConfigDetector.CLEARTEXT_TRAFFIC_ISSUE,
34 | MissingNetworkSecurityConfigDetector.TRUSTED_USER_CERTS_ISSUE,
35 | UnintendedExposedUrlDetector.EXPOSED_URL_ISSUE,
36 | UnintendedExposedUrlDetector.PRIVATE_IP_ADDRESS_ISSUE,
37 | MisconfiguredFileProviderDetector.ROOT_PATH_ISSUE,
38 | MisconfiguredFileProviderDetector.EXTERNAL_PATH_ISSUE,
39 | MisconfiguredFileProviderDetector.DOT_PATH_ISSUE,
40 | MisconfiguredFileProviderDetector.SLASH_PATH_ISSUE,
41 | MisconfiguredFileProviderDetector.ABSOLUTE_PATH_ISSUE,
42 | WeakPrngDetector.ISSUE,
43 | SafeBrowsingDetector.MANIFEST_ISSUE,
44 | PermissionDetector.PROTECTION_LEVEL_ISSUE,
45 | StickyBroadcastsDetector.STICKY_METHOD_ISSUE,
46 | StickyBroadcastsDetector.STICKY_PERMISSION_ISSUE,
47 | BluetoothAdapterDetector.ZERO_BLUETOOTH_DISCOVERY_DURATION_ISSUE,
48 | BluetoothAdapterDetector.EXTENDED_BLUETOOTH_DISCOVERY_DURATION_ISSUE,
49 | LogcatDetector.LOG_INFO_DISCLOSURE_ISSUE,
50 | InsecureStorageDetector.LEGACY_EXTERNAL_STORAGE_ISSUE
51 | )
52 |
53 | override val api: Int
54 | get() = CURRENT_API
55 |
56 | override val minApi: Int
57 | get() = 8 // works with Studio 4.1 or later; see com.android.tools.lint.detector.api.Api / ApiKt
58 |
59 | // Requires lint API 30.0+; if you're still building for something
60 | // older, just remove this property.
61 | override val vendor: Vendor =
62 | Vendor(
63 | vendorName = "Google - Android 3P Vulnerability Research",
64 | feedbackUrl = "https://github.com/google/android-security-lints/issues",
65 | contact = "https://github.com/google/android-security-lints"
66 | )
67 | }
68 |
--------------------------------------------------------------------------------
/checks/src/main/java/com/example/lint/checks/LogcatDetector.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2024 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.tools.lint.detector.api.Category
19 | import com.android.tools.lint.detector.api.ConstantEvaluator
20 | import com.android.tools.lint.detector.api.Detector
21 | import com.android.tools.lint.detector.api.Implementation
22 | import com.android.tools.lint.detector.api.Incident
23 | import com.android.tools.lint.detector.api.Issue
24 | import com.android.tools.lint.detector.api.JavaContext
25 | import com.android.tools.lint.detector.api.Scope
26 | import com.android.tools.lint.detector.api.Severity
27 | import com.android.tools.lint.detector.api.SourceCodeScanner
28 | import com.intellij.psi.PsiMethod
29 | import org.jetbrains.uast.UCallExpression
30 |
31 |
32 | class LogcatDetector : Detector(), SourceCodeScanner {
33 |
34 | override fun getApplicableMethodNames(): List = LOGCAT_METHODS
35 |
36 | override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
37 | if (!context.evaluator.isMemberInClass(method, LOGCAT_CLASS)) return
38 |
39 | val args = node.valueArguments
40 | if (args.isEmpty()) return
41 |
42 | for (element in args) {
43 | val transformation = ConstantEvaluator.evaluate(context, element)
44 |
45 | if (hasSuspiciousLogArguments(transformation.toString())) {
46 | val incident =
47 | Incident(
48 | LOG_INFO_DISCLOSURE_ISSUE,
49 | node,
50 | context.getLocation(node),
51 | "Sensitive data should never be logged to `logcat`",
52 | fix().replace().build()
53 | )
54 | context.report(incident)
55 | return
56 | }
57 | }
58 | }
59 |
60 | private fun hasSuspiciousLogArguments(value: CharSequence): Boolean {
61 | return SUSPICIOUS_LOG_ARGUMENTS.map { it.containsMatchIn(value) }.any { it }
62 | }
63 |
64 | companion object {
65 | private const val LOGCAT_CLASS = "android.util.Log"
66 | private val LOGCAT_METHODS = listOf(
67 | "d",
68 | "e",
69 | "i",
70 | "v",
71 | "w",
72 | "wtf"
73 | )
74 |
75 | private const val EXPLANATION = """
76 | Sensitive information such as application secrets should never be logged to logcat. \
77 | Any sensitive data should therefore be removed from logcat logs. Ensure all logging \
78 | to logcat is sanitized in non-debug versions of your application.
79 | """
80 |
81 | private val SUSPICIOUS_LOG_ARGUMENTS = setOf(
82 | Regex("(?i).*pwd.*"),
83 | Regex("(?i).*password.*"),
84 | Regex("(?i).*credential.*"),
85 | Regex("(?i).*cred.*"),
86 | Regex("(?i).*key.*"),
87 | Regex("(?i).*secret.*"),
88 | Regex("(?i).*token.*"),
89 | Regex("(?i).*passwd.*"),
90 | )
91 |
92 | // A more resource-intensive lint check, feel free to disable after running it
93 | // on your application's codebase.
94 | @JvmField
95 | val LOG_INFO_DISCLOSURE_ISSUE: Issue =
96 | Issue.create(
97 | id = "LogInfoDisclosure",
98 | briefDescription = "Potentially sensitive information logged to Logcat",
99 | explanation = EXPLANATION,
100 | category = Category.SECURITY,
101 | priority = 6,
102 | severity = Severity.WARNING,
103 | moreInfo = "https://goo.gle/LogInfoDisclosure",
104 | implementation = Implementation(
105 | LogcatDetector::class.java,
106 | Scope.JAVA_FILE_SCOPE
107 | )
108 | )
109 | }
110 | }
--------------------------------------------------------------------------------
/checks/src/main/java/com/example/lint/checks/MisconfiguredFileProviderDetector.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.resources.ResourceFolderType
19 | import com.android.tools.lint.detector.api.Category
20 | import com.android.tools.lint.detector.api.Implementation
21 | import com.android.tools.lint.detector.api.Incident
22 | import com.android.tools.lint.detector.api.Issue
23 | import com.android.tools.lint.detector.api.ResourceXmlDetector
24 | import com.android.tools.lint.detector.api.Scope
25 | import com.android.tools.lint.detector.api.Severity
26 | import com.android.tools.lint.detector.api.XmlContext
27 | import com.android.utils.XmlUtils
28 | import org.w3c.dom.Document
29 | import org.w3c.dom.Element
30 |
31 | /**
32 | * Detector flagging whether the application has an improperly configured `FileProvider`.
33 | */
34 | class MisconfiguredFileProviderDetector: ResourceXmlDetector() {
35 |
36 | override fun appliesTo(folderType: ResourceFolderType): Boolean {
37 | return folderType == ResourceFolderType.XML
38 | }
39 |
40 | override fun visitDocument(context: XmlContext, document: Document) {
41 | val root = document.documentElement ?: return
42 |
43 | if (root.tagName != TAG_PATHS) return
44 |
45 | for (child in XmlUtils.getSubTags(root)) {
46 | val tagName = child.tagName
47 |
48 | when(tagName) {
49 | TAG_ROOT_PATH -> handleRootPathReporting(context, child)
50 | TAG_EXTERNAL_PATH -> handleExternalPathReporting(context, child)
51 | in PATH_SUBTAGS -> {
52 | val path = child.getAttributeNode(PATH_ATTR)?.value ?: return
53 |
54 | when (path) {
55 | "." -> handleDotPathReporting(context, child)
56 | "/" -> handleSlashPathReporting(context, child)
57 | else -> {
58 | if (path.startsWith("/")) handleAbsolutePathReporting(context, child)
59 | }
60 | }
61 | }
62 | }
63 | }
64 | }
65 |
66 | private fun handleRootPathReporting(context: XmlContext, element: Element) {
67 | val incident =
68 | Incident(
69 | ROOT_PATH_ISSUE,
70 | element,
71 | context.getElementLocation(element),
72 | "Do not use `` as it provides arbitrary access to device files and folders",
73 | fix().replace().build()
74 | )
75 | context.report(incident)
76 | }
77 |
78 | private fun handleExternalPathReporting(context: XmlContext, element: Element) {
79 | val incident =
80 | Incident(
81 | EXTERNAL_PATH_ISSUE,
82 | element,
83 | context.getElementLocation(element),
84 | "Sensitive info like PII should not be stored or shared via ``",
85 | fix().replace().build()
86 | )
87 | context.report(incident)
88 | }
89 |
90 | private fun handleDotPathReporting(context: XmlContext, element: Element) {
91 | val incident =
92 | Incident(
93 | DOT_PATH_ISSUE,
94 | element,
95 | context.getElementLocation(element),
96 | """The "path" attribute should not be set to "."""",
97 | fix().replace().build()
98 | )
99 | context.report(incident)
100 | }
101 |
102 | private fun handleSlashPathReporting(context: XmlContext, element: Element) {
103 | val incident =
104 | Incident(
105 | SLASH_PATH_ISSUE,
106 | element,
107 | context.getElementLocation(element),
108 | """The "path" attribute should not be set to "/" """,
109 | fix().replace().build()
110 | )
111 | context.report(incident)
112 | }
113 |
114 | private fun handleAbsolutePathReporting(context: XmlContext, element: Element) {
115 | val incident =
116 | Incident(
117 | ABSOLUTE_PATH_ISSUE,
118 | element,
119 | context.getElementLocation(element),
120 | """The "path" attribute should not be an absolute path""",
121 | fix().replace().build()
122 | )
123 | context.report(incident)
124 | }
125 |
126 | companion object {
127 | private val IMPLEMENTATION = Implementation(MisconfiguredFileProviderDetector::class.java, Scope.RESOURCE_FILE_SCOPE)
128 | private const val TAG_PATHS = "paths"
129 | private const val TAG_ROOT_PATH = "root-path"
130 | private const val TAG_EXTERNAL_PATH = "external-path"
131 | private const val PATH_ATTR = "path"
132 | private val PATH_SUBTAGS = setOf(
133 | "files-path",
134 | "cache-path",
135 | "external-files-path",
136 | "external-cache-path",
137 | "external-media-path"
138 | )
139 |
140 | @JvmField
141 | val ROOT_PATH_ISSUE: Issue =
142 | Issue.create(
143 | id = "ExposedRootPath",
144 | briefDescription = "Application specifies the device root directory ",
145 | explanation =
146 | """
147 | Allowing the device root directory in the `FileProvider` configuration provides arbitrary access \
148 | to files and folders for attackers, thereby increasing the attack surface.
149 | """,
150 | category = Category.SECURITY,
151 | priority = 8,
152 | severity = Severity.WARNING,
153 | moreInfo = "https://goo.gle/ExposedRootPath",
154 | implementation = IMPLEMENTATION
155 | )
156 |
157 | @JvmField
158 | val EXTERNAL_PATH_ISSUE: Issue =
159 | Issue.create(
160 | id = "SensitiveExternalPath",
161 | briefDescription = "Application may expose sensitive info like PII by storing it in external storage",
162 | explanation =
163 | """
164 | Sensitive information like PII should not be stored outside of the application container or system \
165 | credential storage facilities
166 | """,
167 | category = Category.SECURITY,
168 | priority = 4,
169 | severity = Severity.WARNING,
170 | moreInfo = "https://goo.gle/SensitiveExternalPath",
171 | implementation = IMPLEMENTATION
172 | )
173 |
174 | @JvmField
175 | val DOT_PATH_ISSUE: Issue =
176 | Issue.create(
177 | id = "DotPathAttribute",
178 | briefDescription = """The "path" attribute should not be set to "." as a path.""",
179 | explanation =
180 | """
181 | Using a broad path range like "." can lead to the accidental exposure of sensitive files. \
182 | Ensure that a specific, narrow and limited path is shared to prevent mistakenly exposing sensitive data.
183 | """,
184 | category = Category.SECURITY,
185 | priority = 6,
186 | severity = Severity.WARNING,
187 | moreInfo = "https://goo.gle/DotPathAttribute",
188 | implementation = IMPLEMENTATION
189 | )
190 |
191 | @JvmField
192 | val SLASH_PATH_ISSUE: Issue =
193 | Issue.create(
194 | id = "SlashPathAttribute",
195 | briefDescription = """The "path" attribute should not be set to "/" as a path.""",
196 | explanation =
197 | """
198 | Using a broad path range like "/" can lead to the accidental exposure of sensitive files. \
199 | Ensure that a specific, narrow and limited path is shared to prevent mistakenly exposing sensitive data.
200 | """,
201 | category = Category.SECURITY,
202 | priority = 6,
203 | severity = Severity.WARNING,
204 | moreInfo = "https://goo.gle/SlashPathAttribute",
205 | implementation = IMPLEMENTATION
206 | )
207 |
208 | @JvmField
209 | val ABSOLUTE_PATH_ISSUE: Issue =
210 | Issue.create(
211 | id = "HardcodedAbsolutePath",
212 | briefDescription = """The "path" attribute should not be an absolute path.""",
213 | explanation =
214 | """
215 | Avoid hardcoding absolute paths into your app. Ensure that a specific, \
216 | narrow and limited path is shared to prevent mistakenly exposing sensitive data.
217 | """,
218 | category = Category.SECURITY,
219 | priority = 3,
220 | severity = Severity.WARNING,
221 | moreInfo = "https://goo.gle/HardcodedAbsolutePath",
222 | implementation = IMPLEMENTATION
223 | )
224 | }
225 | }
--------------------------------------------------------------------------------
/checks/src/main/java/com/example/lint/checks/MissingNetworkSecurityConfigDetector.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.SdkConstants
19 | import com.android.SdkConstants.ANDROID_URI
20 | import com.android.resources.ResourceFolderType
21 | import com.android.tools.lint.detector.api.Category
22 | import com.android.tools.lint.detector.api.Context
23 | import com.android.tools.lint.detector.api.Implementation
24 | import com.android.tools.lint.detector.api.Incident
25 | import com.android.tools.lint.detector.api.Issue
26 | import com.android.tools.lint.detector.api.LintFix
27 | import com.android.tools.lint.detector.api.ResourceXmlDetector
28 | import com.android.tools.lint.detector.api.Scope
29 | import com.android.tools.lint.detector.api.Severity
30 | import com.android.tools.lint.detector.api.XmlContext
31 | import com.android.tools.lint.detector.api.XmlScanner
32 | import com.android.tools.lint.detector.api.targetSdkLessThan
33 | import java.io.File
34 | import org.w3c.dom.Element
35 |
36 | /**
37 | * Detector flagging whether the application has default insecure network connections behavior by forgetting to include
38 | * a network security config file.
39 | */
40 | class MissingNetworkSecurityConfigDetector : ResourceXmlDetector(), XmlScanner {
41 | override fun getApplicableElements() = setOf(SdkConstants.TAG_APPLICATION)
42 | override fun appliesTo(folderType: ResourceFolderType): Boolean {
43 | return folderType == ResourceFolderType.XML
44 | }
45 |
46 | override fun visitElement(context: XmlContext, element: Element) {
47 | val networkSecurityConfigAttr = element.getAttributeNodeNS(ANDROID_URI, ATTR_NETWORK_SECURITY_CONFIG)
48 | // NetworkSecurityConfig file is already specified in the Manifest, no need to add one
49 | if (networkSecurityConfigAttr != null) return
50 |
51 | val cleartextTrafficIncident =
52 | Incident(
53 | CLEARTEXT_TRAFFIC_ISSUE,
54 | element,
55 | context.getElementLocation(element),
56 | "On SDK versions below 28, the application by default trusts cleartext traffic. Add a " +
57 | "Network Security Config file to opt out of these insecure connections.",
58 | createNetworkSecurityConfigFix(context, CLEARTEXT_TRAFFIC_CONFIG)
59 | )
60 |
61 | val userCertsIncident =
62 | Incident(
63 | TRUSTED_USER_CERTS_ISSUE,
64 | element,
65 | context.getElementLocation(element),
66 | "On SDK versions below 24, the application by default trusts user-added CA certificates. Add " +
67 | "a Network Security Config file to opt out of this insecure behavior.",
68 | createNetworkSecurityConfigFix(context, USER_CERTS_CONFIG)
69 | )
70 |
71 | val target = context.project.targetSdk
72 | // Check the Target SDK version so we don't accidentally display two lint warnings at the same time
73 | if (target in USER_CERTS_SDK_LEVEL until CLEARTEXT_TRAFFIC_SDK_LEVEL) {
74 | context.report(cleartextTrafficIncident, targetSdkLessThan(CLEARTEXT_TRAFFIC_SDK_LEVEL))
75 | } else if (target < USER_CERTS_SDK_LEVEL) {
76 | context.report(userCertsIncident, targetSdkLessThan(USER_CERTS_SDK_LEVEL))
77 | }
78 | }
79 |
80 | private fun createNetworkSecurityConfigFix(context: Context, config: String): LintFix? {
81 | val addConfigToManifestFix = fix().set().android().attribute(ATTR_NETWORK_SECURITY_CONFIG).value(NETWORK_SECURITY_CONFIG_LOCATION).build()
82 | val project = context.project
83 | val folder = project.resourceFolders.firstOrNull() ?: return null
84 | val file = File(folder, "xml/$NETWORK_SECURITY_CONFIG_FILE_NAME.xml")
85 |
86 | // NetworkSecurityConfig already exists, no need to create one
87 | if (file.exists()) return null
88 |
89 | val createConfigFileFix = fix().newFile(file, config).build()
90 | return fix().name("Create network security config").composite(addConfigToManifestFix, createConfigFileFix)
91 | }
92 |
93 | companion object {
94 | const val ATTR_NETWORK_SECURITY_CONFIG = "networkSecurityConfig"
95 | const val NETWORK_SECURITY_CONFIG_FILE_NAME = "network_security_config"
96 | const val NETWORK_SECURITY_CONFIG_LOCATION = "@xml/$NETWORK_SECURITY_CONFIG_FILE_NAME"
97 | const val CLEARTEXT_TRAFFIC_SDK_LEVEL = 28
98 | const val USER_CERTS_SDK_LEVEL = 24
99 | val CLEARTEXT_TRAFFIC_CONFIG =
100 | """
101 |
102 |
103 |
104 |
105 | """.trimIndent()
106 | val USER_CERTS_CONFIG =
107 | """
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 | """.trimIndent()
117 |
118 | @JvmField
119 | val IMPLEMENTATION =
120 | Implementation(MissingNetworkSecurityConfigDetector::class.java, Scope.MANIFEST_SCOPE)
121 |
122 | @JvmField
123 | val CLEARTEXT_TRAFFIC_ISSUE: Issue =
124 | Issue.create(
125 | id = "DefaultCleartextTraffic",
126 | briefDescription = "Application by default permits cleartext traffic",
127 | explanation =
128 | """
129 | Apps targeting SDK versions earlier than 28 trust cleartext traffic by default. \
130 | The application must explicitly opt out of this in order to only use secure connections.
131 | """,
132 | category = Category.SECURITY,
133 | priority = 5,
134 | severity = Severity.WARNING,
135 | moreInfo = "https://goo.gle/DefaultCleartextTraffic",
136 | implementation = IMPLEMENTATION
137 | )
138 |
139 | @JvmField
140 | val TRUSTED_USER_CERTS_ISSUE: Issue =
141 | Issue.create(
142 | id = "DefaultTrustedUserCerts",
143 | briefDescription = "Application by default trusts user-added CA certificates",
144 | explanation =
145 | """
146 | Apps targeting SDK versions earlier than 24 trust user-added CA certificates by default. \
147 | In practice, it is better to limit the set of trusted CAs so only trusted CAs are used for an app's secure \
148 | connections.
149 | """,
150 | category = Category.SECURITY,
151 | priority = 3,
152 | severity = Severity.WARNING,
153 | moreInfo = "https://goo.gle/DefaultTrustedUserCerts",
154 | implementation = IMPLEMENTATION
155 | )
156 | }
157 | }
--------------------------------------------------------------------------------
/checks/src/main/java/com/example/lint/checks/PermissionDetector.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2024 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.SdkConstants.ANDROID_URI
19 | import com.android.SdkConstants.TAG_PERMISSION
20 | import com.android.tools.lint.detector.api.Category
21 | import com.android.tools.lint.detector.api.Detector
22 | import com.android.tools.lint.detector.api.Implementation
23 | import com.android.tools.lint.detector.api.Incident
24 | import com.android.tools.lint.detector.api.Issue
25 | import com.android.tools.lint.detector.api.Scope
26 | import com.android.tools.lint.detector.api.Severity
27 | import com.android.tools.lint.detector.api.XmlContext
28 | import com.android.tools.lint.detector.api.XmlScanner
29 | import org.w3c.dom.Element
30 |
31 | /**
32 | * Detector flagging whether there are issues with the application's permissions.
33 | */
34 | class PermissionDetector : Detector(), XmlScanner {
35 | override fun getApplicableElements() = setOf(TAG_PERMISSION)
36 |
37 | override fun visitElement(context: XmlContext, element: Element) {
38 | val attrProtectionLevel = element.getAttributeNS(ANDROID_URI, ATTR_PROTECTION_LEVEL)
39 |
40 | if (attrProtectionLevel.isEmpty() or (attrProtectionLevel in INSECURE_PROTECTION_LEVELS)) {
41 | val incident =
42 | Incident(
43 | PROTECTION_LEVEL_ISSUE,
44 | element,
45 | context.getLocation(element),
46 | "Custom permissions should have a `signature` protectionLevel or higher",
47 | fix().set().android().attribute(ATTR_PROTECTION_LEVEL).value("signature").build()
48 | )
49 |
50 | context.report(incident)
51 | }
52 | }
53 |
54 | companion object {
55 | private const val ATTR_PROTECTION_LEVEL = "protectionLevel"
56 | // TODO: Decide whether to expand this to other protectionLevels beyond normal and/or check for flags
57 | private val INSECURE_PROTECTION_LEVELS = setOf("normal")
58 |
59 | private const val EXPLANATION = """
60 | Custom permissions are designed for sharing resources and capabilities with other apps. However, typos and \
61 | insufficient protection levels can negate the usage of these custom permissions altogether. In general, use \
62 | `signature` or higher protection levels whenever possible, as this ensures only other apps signed with the \
63 | same certificate can access these protected features.
64 | """
65 |
66 | /** Issue describing the problem and pointing to the detector implementation. */
67 | @JvmField
68 | val PROTECTION_LEVEL_ISSUE: Issue =
69 | Issue.create(
70 | // ID: used in @SuppressLint warnings etc
71 | id = "InsecurePermissionProtectionLevel",
72 | // Title -- shown in the IDE's preference dialog, as category headers in the
73 | // Analysis results window, etc
74 | briefDescription = "Custom permission created with a normal `protectionLevel`",
75 | // Full explanation of the issue; you can use some markdown markup such as
76 | // `monospace`, *italic*, and **bold**.
77 | explanation = EXPLANATION,
78 | category = Category.SECURITY,
79 | priority = 9,
80 | severity = Severity.WARNING,
81 | moreInfo = "https://goo.gle/InsecurePermissionProtectionLevel",
82 | implementation =
83 | Implementation(PermissionDetector::class.java, Scope.MANIFEST_SCOPE)
84 | )
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/checks/src/main/java/com/example/lint/checks/SafeBrowsingDetector.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2024 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.SdkConstants.ANDROID_URI
19 | import com.android.SdkConstants.ATTR_NAME
20 | import com.android.SdkConstants.ATTR_VALUE
21 | import com.android.SdkConstants.TAG_META_DATA
22 | import com.android.tools.lint.detector.api.Category
23 | import com.android.tools.lint.detector.api.Detector
24 | import com.android.tools.lint.detector.api.Implementation
25 | import com.android.tools.lint.detector.api.Incident
26 | import com.android.tools.lint.detector.api.Issue
27 | import com.android.tools.lint.detector.api.Scope
28 | import com.android.tools.lint.detector.api.Severity
29 | import com.android.tools.lint.detector.api.XmlContext
30 | import com.android.tools.lint.detector.api.XmlScanner
31 | import org.w3c.dom.Element
32 |
33 | /**
34 | * Detector flagging whether the application has disabled safe browsing.
35 | */
36 | class SafeBrowsingDetector : Detector(), XmlScanner {
37 | override fun getApplicableElements() = setOf(TAG_META_DATA)
38 |
39 | override fun visitElement(context: XmlContext, element: Element) {
40 | val attributeName = element.getAttributeNS(ANDROID_URI, ATTR_NAME)
41 | val attributeValue = element.getAttributeNS(ANDROID_URI, ATTR_VALUE)
42 |
43 | if (attributeName == ENABLE_SAFE_BROWSING_MANIFEST_VALUE && attributeValue == "false") {
44 | val incident =
45 | Incident(
46 | MANIFEST_ISSUE,
47 | element,
48 | context.getLocation(element),
49 | "Safe Browsing should be kept enabled at all times, as it aims to keep users from unsafe URLs",
50 | fix().set().android().attribute(ENABLE_SAFE_BROWSING_MANIFEST_VALUE).value("true").build()
51 | )
52 |
53 | context.report(incident)
54 | }
55 | }
56 |
57 | companion object {
58 | private const val ENABLE_SAFE_BROWSING_MANIFEST_VALUE = "android.webkit.WebView.EnableSafeBrowsing"
59 |
60 | private const val EXPLANATION = """
61 | Safe Browsing is a service to help applications check URLs against a known list of unsafe web \
62 | resources. We recommend keeping Safe Browsing enabled at all times and designing your app around \
63 | any constraints this causes.
64 | """
65 |
66 | @JvmField
67 | val MANIFEST_ISSUE: Issue =
68 | Issue.create(
69 | id = "DisabledAllSafeBrowsing",
70 | briefDescription = "Application has disabled safe browsing for all WebView objects",
71 | explanation = EXPLANATION,
72 | category = Category.SECURITY,
73 | priority = 8,
74 | severity = Severity.WARNING,
75 | moreInfo = "https://goo.gle/DisabledAllSafeBrowsing",
76 | implementation =
77 | Implementation(SafeBrowsingDetector::class.java, Scope.MANIFEST_SCOPE)
78 | )
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/checks/src/main/java/com/example/lint/checks/StickyBroadcastsDetector.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2024 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.SdkConstants.ANDROID_URI
19 | import com.android.SdkConstants.ATTR_NAME
20 | import com.android.SdkConstants.CLASS_CONTEXT
21 | import com.android.SdkConstants.TAG_USES_PERMISSION
22 | import com.android.tools.lint.detector.api.Category
23 | import com.android.tools.lint.detector.api.Detector
24 | import com.android.tools.lint.detector.api.Implementation
25 | import com.android.tools.lint.detector.api.Incident
26 | import com.android.tools.lint.detector.api.Issue
27 | import com.android.tools.lint.detector.api.JavaContext
28 | import com.android.tools.lint.detector.api.Scope
29 | import com.android.tools.lint.detector.api.Severity
30 | import com.android.tools.lint.detector.api.SourceCodeScanner
31 | import com.android.tools.lint.detector.api.XmlContext
32 | import com.android.tools.lint.detector.api.XmlScanner
33 | import com.intellij.psi.PsiMethod
34 | import org.jetbrains.uast.UCallExpression
35 | import org.jetbrains.uast.getOutermostQualified
36 | import org.jetbrains.uast.getQualifiedChain
37 | import org.w3c.dom.Element
38 |
39 | class StickyBroadcastsDetector : Detector(), XmlScanner, SourceCodeScanner {
40 |
41 | override fun getApplicableElements() = setOf(TAG_USES_PERMISSION)
42 | override fun getApplicableMethodNames(): List = listOf(STICKY_ORDERED_METHOD)
43 |
44 | override fun visitElement(context: XmlContext, element: Element) {
45 | val attrPermissionName = element.getAttributeNS(ANDROID_URI, ATTR_NAME)
46 | if (attrPermissionName in DANGEROUS_PERMISSIONS) {
47 | val incident =
48 | Incident(
49 | STICKY_PERMISSION_ISSUE,
50 | element,
51 | context.getLocation(element),
52 | "Sticky broadcasts can be accessed, sent or modified by anyone. Use non-sticky broadcasts instead.",
53 | fix().replace().build()
54 | )
55 |
56 | context.report(incident)
57 | }
58 | }
59 |
60 | override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
61 | if (!context.evaluator.isMemberInSubClassOf(method, CLASS_CONTEXT, false)) return
62 |
63 | val incident =
64 | Incident(
65 | STICKY_METHOD_ISSUE,
66 | node,
67 | context.getLocation(node),
68 | "Sticky broadcasts can be accessed, sent or modified by anyone. Use non-sticky broadcasts instead.",
69 | fix().replace().build()
70 | )
71 |
72 | context.report(incident)
73 | }
74 |
75 | companion object {
76 | private val DANGEROUS_PERMISSIONS = setOf("android.permission.BROADCAST_STICKY")
77 | private const val STICKY_ORDERED_METHOD = "sendStickyOrderedBroadcast"
78 |
79 | private const val EXPLANATION = """
80 | Sticky broadcasts can be accessed, sent, or modified by anyone, resulting in potential security issues. \
81 | For this reason, it was deprecated in API level 21 and other mechanisms such as databases or non-sticky \
82 | broadcasts should be used instead.
83 | """
84 |
85 | @JvmField
86 | val STICKY_PERMISSION_ISSUE: Issue =
87 | Issue.create(
88 | id = "InsecureStickyBroadcastsPermission",
89 | briefDescription = "Usage of insecure sticky broadcasts",
90 | explanation = EXPLANATION,
91 | category = Category.SECURITY,
92 | priority = 6,
93 | severity = Severity.WARNING,
94 | moreInfo = "https://goo.gle/InsecureStickyBroadcastsPermission",
95 | implementation = Implementation(StickyBroadcastsDetector::class.java, Scope.MANIFEST_SCOPE)
96 | )
97 |
98 | @JvmField
99 | val STICKY_METHOD_ISSUE: Issue =
100 | Issue.create(
101 | id = "InsecureStickyBroadcastsMethod",
102 | briefDescription = "Usage of insecure sticky broadcasts",
103 | explanation = EXPLANATION,
104 | category = Category.SECURITY,
105 | priority = 6,
106 | severity = Severity.WARNING,
107 | moreInfo = "https://goo.gle/InsecureStickyBroadcastsMethod",
108 | implementation = Implementation(StickyBroadcastsDetector::class.java, Scope.JAVA_FILE_SCOPE)
109 | )
110 | }
111 | }
--------------------------------------------------------------------------------
/checks/src/main/java/com/example/lint/checks/StrandhoggDetector.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.SdkConstants.ANDROID_URI
19 | import com.android.SdkConstants.ATTR_TARGET_SDK_VERSION
20 | import com.android.SdkConstants.TAG_USES_SDK
21 | import com.android.tools.lint.detector.api.Category
22 | import com.android.tools.lint.detector.api.Detector
23 | import com.android.tools.lint.detector.api.Implementation
24 | import com.android.tools.lint.detector.api.Incident
25 | import com.android.tools.lint.detector.api.Issue
26 | import com.android.tools.lint.detector.api.Severity
27 | import com.android.tools.lint.detector.api.Scope
28 | import com.android.tools.lint.detector.api.XmlContext
29 | import com.android.tools.lint.detector.api.XmlScanner
30 | import com.android.tools.lint.detector.api.targetSdkLessThan
31 | import org.w3c.dom.Element
32 |
33 | /**
34 | * Detector flagging whether the application is vulnerable to Strandhogg / Task Affinity attacks.
35 | */
36 | class StrandhoggDetector : Detector(), XmlScanner {
37 | override fun getApplicableElements() = setOf(TAG_USES_SDK)
38 |
39 | override fun visitElement(context: XmlContext, element: Element) {
40 | val attribute = element.getAttributeNodeNS(ANDROID_URI, ATTR_TARGET_SDK_VERSION) ?: return
41 |
42 | val incident =
43 | Incident(
44 | ISSUE,
45 | element,
46 | context.getValueLocation(attribute),
47 | "Update your application's target SDK version to 28 and above to protect it from " +
48 | "Strandhogg attacks",
49 | fix().set().android().attribute(ATTR_TARGET_SDK_VERSION).value(PATCHED_SDK_LEVEL.toString()).build()
50 | )
51 |
52 | context.report(incident, constraint = targetSdkLessThan(PATCHED_SDK_LEVEL))
53 | }
54 |
55 | companion object {
56 | const val PATCHED_SDK_LEVEL = 28
57 |
58 | /** Issue describing the problem and pointing to the detector implementation. */
59 | @JvmField
60 | val ISSUE: Issue =
61 | Issue.create(
62 | // ID: used in @SuppressLint warnings etc
63 | id = "StrandhoggVulnerable",
64 | // Title -- shown in the IDE's preference dialog, as category headers in the
65 | // Analysis results window, etc
66 | briefDescription = "Application vulnerable to Strandhogg attacks",
67 | // Full explanation of the issue; you can use some markdown markup such as
68 | // `monospace`, *italic*, and **bold**.
69 | explanation =
70 | """
71 | Apps targeting SDK versions earlier than 28 are susceptible to Strandhogg / \
72 | Task Affinity attacks.
73 | """, // no need to .trimIndent(), lint does that automatically
74 | category = Category.SECURITY,
75 | priority = 6,
76 | severity = Severity.WARNING,
77 | moreInfo = "https://goo.gle/StrandhoggVulnerable",
78 | implementation =
79 | Implementation(StrandhoggDetector::class.java, Scope.MANIFEST_SCOPE)
80 | )
81 | }
82 | }
83 |
--------------------------------------------------------------------------------
/checks/src/main/java/com/example/lint/checks/TapjackingDetector.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.SdkConstants.ANDROID_URI
19 | import com.android.SdkConstants.ATTR_ID
20 | import com.android.SdkConstants.CHECK_BOX
21 | import com.android.SdkConstants.COMPOUND_BUTTON
22 | import com.android.SdkConstants.SWITCH
23 | import com.android.SdkConstants.TOGGLE_BUTTON
24 | import com.android.SdkConstants.VALUE_TRUE
25 | import com.android.tools.lint.detector.api.Category
26 | import com.android.tools.lint.detector.api.Implementation
27 | import com.android.tools.lint.detector.api.Incident
28 | import com.android.tools.lint.detector.api.Issue
29 | import com.android.tools.lint.detector.api.ResourceXmlDetector
30 | import com.android.tools.lint.detector.api.Severity
31 | import com.android.tools.lint.detector.api.Scope
32 | import com.android.tools.lint.detector.api.XmlContext
33 | import org.w3c.dom.Element
34 |
35 | /**
36 | * Detector flagging whether the application has UI elements susceptible to tapjacking / overlay attacks.
37 | */
38 | class TapjackingDetector : ResourceXmlDetector() {
39 | // Pick out specifically UI elements with two states as it is more likely to govern whether a setting is enabled
40 | override fun getApplicableElements() = setOf(TOGGLE_BUTTON, COMPOUND_BUTTON, CHECK_BOX, SWITCH)
41 |
42 | override fun visitElement(context: XmlContext, element: Element) {
43 | val name = element.getAttributeNodeNS(ANDROID_URI, ATTR_ID)?.value ?: return
44 |
45 | if (ENABLE_NAME in name || DISABLE_NAME in name) {
46 | val incident =
47 | Incident(
48 | ISSUE,
49 | element,
50 | context.getElementLocation(element),
51 | "Add the `android:filterTouchesWhenObscured` attribute to protect this UI element from " +
52 | "tapjacking / overlay attacks",
53 | fix().set().android().attribute(ATTR_FILTER_TOUCHES_OBSCURED).value(VALUE_TRUE).build()
54 | )
55 |
56 | context.report(incident)
57 | }
58 | }
59 |
60 | companion object {
61 | const val ATTR_FILTER_TOUCHES_OBSCURED = "filterTouchesWhenObscured"
62 | const val ENABLE_NAME = "enable"
63 | const val DISABLE_NAME = "disable"
64 |
65 | @JvmField
66 | val ISSUE: Issue =
67 | Issue.create(
68 | id = "TapjackingVulnerable",
69 | briefDescription = "Application's UI is vulnerable to tapjacking attacks",
70 | explanation =
71 | """
72 | Apps with sensitive UI elements should add the `filterTouchesWithObscured` attribute \
73 | to protect it from tapjacking / overlay attacks.
74 | """,
75 | category = Category.SECURITY,
76 | priority = 3,
77 | severity = Severity.WARNING,
78 | moreInfo = "https://goo.gle/TapjackingVulnerable",
79 | implementation =
80 | Implementation(TapjackingDetector::class.java, Scope.RESOURCE_FILE_SCOPE)
81 | )
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/checks/src/main/java/com/example/lint/checks/UnintendedExposedUrlDetector.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.SdkConstants
19 | import com.android.resources.ResourceFolderType
20 | import com.android.tools.lint.detector.api.Category
21 | import com.android.tools.lint.detector.api.Implementation
22 | import com.android.tools.lint.detector.api.Incident
23 | import com.android.tools.lint.detector.api.Issue
24 | import com.android.tools.lint.detector.api.ResourceXmlDetector
25 | import com.android.tools.lint.detector.api.Severity
26 | import com.android.tools.lint.detector.api.Scope
27 | import com.android.tools.lint.detector.api.XmlContext
28 | import com.android.utils.XmlUtils
29 | import org.w3c.dom.Document
30 | import org.w3c.dom.Element
31 |
32 | /**
33 | * Detector flagging whether the application has potentially unintended exposed URLs and private IP addresses
34 | * in strings.xml and Network Security Config files.
35 | */
36 | class UnintendedExposedUrlDetector: ResourceXmlDetector() {
37 |
38 | override fun appliesTo(folderType: ResourceFolderType): Boolean {
39 | return folderType == ResourceFolderType.XML
40 | }
41 |
42 | override fun visitDocument(context: XmlContext, document: Document) {
43 | val root = document.documentElement ?: return
44 |
45 | if (root.tagName != TAG_NETWORK_SECURITY_CONFIG && root.tagName != SdkConstants.TAG_RESOURCES) return
46 |
47 | for (child in XmlUtils.getSubTags(root)) {
48 | val tagName = child.tagName
49 |
50 | if (TAG_DOMAIN_CONFIG == tagName) {
51 | XmlUtils.getSubTags(child).filter { TAG_DOMAIN == it.tagName }.forEach {
52 | val domainName = it.textContent.trim()
53 | handlePrivateIpReporting(domainName, context, it)
54 | handleExposedUrlReporting(domainName, context, it)
55 | }
56 | }
57 |
58 | else if (SdkConstants.TAG_STRING == tagName) {
59 | val stringValue = child.textContent.trim()
60 | handlePrivateIpReporting(stringValue, context, child)
61 | handleExposedUrlReporting(stringValue, context, child)
62 | }
63 | }
64 | }
65 |
66 | private fun hasExposedUrl(value: String): Boolean {
67 | return value.matches(STAGING_URL_REGEX) ||
68 | value.matches(DEBUG_URL_REGEX) ||
69 | value.matches(PREPROD_URL_REGEX)
70 | }
71 |
72 | private fun handlePrivateIpReporting(value: String, context: XmlContext, element: Element) {
73 | if (!IPV4_REGEX.containsMatchIn(value)) return
74 |
75 | val ipAddress = IPV4_REGEX.find(value)
76 | val isPublicIp = PUBLIC_IP_PREFIXES.map {
77 | ipAddress?.value?.split(".")?.get(0) == it.toString() }.any {it}
78 |
79 | val incident =
80 | Incident(
81 | PRIVATE_IP_ADDRESS_ISSUE,
82 | element,
83 | context.getElementLocation(element),
84 | "Exposing private IP addresses puts the application and its resources at unnecessary risk",
85 | fix().replace().build()
86 | )
87 | if (!isPublicIp) context.report(incident)
88 | }
89 |
90 | private fun handleExposedUrlReporting(value: String, context: XmlContext, element: Element) {
91 | if (!hasExposedUrl(value)) return
92 |
93 | val incident =
94 | Incident(
95 | EXPOSED_URL_ISSUE,
96 | element,
97 | context.getElementLocation(element),
98 | "Exposing development / debugging URLs allows attackers to gain unintended access to the " +
99 | "application and its resources",
100 | fix().replace().build()
101 | )
102 | context.report(incident)
103 | }
104 |
105 | companion object {
106 | private val IMPLEMENTATION = Implementation(UnintendedExposedUrlDetector::class.java, Scope.RESOURCE_FILE_SCOPE)
107 |
108 | const val TAG_NETWORK_SECURITY_CONFIG = "network-security-config"
109 | const val TAG_DOMAIN_CONFIG = "domain-config"
110 | const val TAG_DOMAIN = "domain"
111 |
112 | val IPV4_REGEX = Regex("(?:[0-9]{1,3}\\.){3}[0-9]{1,3}")
113 | val PUBLIC_IP_PREFIXES = setOf(10, 172, 192)
114 |
115 | private const val URL_PREFIX =
116 | "^(https:\\/\\/www\\.|http:\\/\\/www\\.|https:\\/\\/|http:\\/\\/)?\\p{Graph}*"
117 | private const val URL_SUFFIX = "\\p{Graph}*(.[a-zA-Z0-9]{2,})(.[a-zA-Z0-9]{2,})?"
118 |
119 | val STAGING_URL_REGEX = Regex("${URL_PREFIX}(staging|STAGING)${URL_SUFFIX}")
120 | val DEBUG_URL_REGEX = Regex("${URL_PREFIX}(debug|DEBUG)${URL_SUFFIX}")
121 | val PREPROD_URL_REGEX = Regex("$URL_PREFIX(preprod|PREPROD)$URL_SUFFIX")
122 |
123 | @JvmField
124 | val EXPOSED_URL_ISSUE: Issue =
125 | Issue.create(
126 | id = "UnintendedExposedUrl",
127 | briefDescription = "Application may have a debugging or development URL publicly exposed",
128 | explanation =
129 | """
130 | URLs that look intended for debugging and development purposes only are exposed in the application, \
131 | allowing attackers to gain access to parts of the application and server that should be kept secure.
132 | """,
133 | category = Category.SECURITY,
134 | priority = 3,
135 | severity = Severity.WARNING,
136 | moreInfo = "https://goo.gle/UnintendedExposedUrl",
137 | implementation = IMPLEMENTATION
138 | )
139 |
140 | @JvmField
141 | val PRIVATE_IP_ADDRESS_ISSUE: Issue =
142 | Issue.create(
143 | id = "UnintendedPrivateIpAddress",
144 | briefDescription = "Application may have a private IP address publicly exposed",
145 | explanation =
146 | """
147 | Private IP addresses are referenced that may have been intended only for debugging and development. \
148 | These should not be exposed publicly, as it may permit attackers to gain unintended access to the \
149 | application and its resources.
150 | """,
151 | category = Category.SECURITY,
152 | priority = 4,
153 | severity = Severity.WARNING,
154 | moreInfo = "https://goo.gle/UnintendedPrivateIpAddress",
155 | implementation = IMPLEMENTATION
156 | )
157 | }
158 | }
--------------------------------------------------------------------------------
/checks/src/main/java/com/example/lint/checks/WeakPrngDetector.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.tools.lint.detector.api.Category
19 | import com.android.tools.lint.detector.api.Detector
20 | import com.android.tools.lint.detector.api.Implementation
21 | import com.android.tools.lint.detector.api.Incident
22 | import com.android.tools.lint.detector.api.Issue
23 | import com.android.tools.lint.detector.api.JavaContext
24 | import com.android.tools.lint.detector.api.Scope
25 | import com.android.tools.lint.detector.api.Severity
26 | import com.android.tools.lint.detector.api.SourceCodeScanner
27 | import com.intellij.psi.PsiMethod
28 | import org.jetbrains.uast.UCallExpression
29 |
30 | /**
31 | * Detector flagging whether the application uses a weak PRNG (pseudorandom number generator).
32 | */
33 | class WeakPrngDetector: Detector(), SourceCodeScanner {
34 |
35 | override fun getApplicableMethodNames(): List = listOf(RANDOM)
36 |
37 | override fun getApplicableConstructorTypes(): List = listOf(UTIL_RANDOM)
38 |
39 | override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
40 | // If static java.lang.Math.random method is called
41 | if (!context.evaluator.isMemberInSubClassOf(method, LANG_MATH, false)) return
42 |
43 | val incident = Incident(
44 | ISSUE,
45 | node,
46 | context.getLocation(node),
47 | "Math.random relies on a weak PRNG, use `$UTIL_RANDOM` for non-security contexts and " +
48 | "`$SECURE_RANDOM` for security / authentication purposes",
49 | fix().replace().range(context.getLocation(node)).with("Random().nextDouble()")
50 | .imports(UTIL_RANDOM).build()
51 | )
52 | context.report(incident)
53 | }
54 |
55 | override fun visitConstructor(context: JavaContext, node: UCallExpression, constructor: PsiMethod) {
56 | // If java.util.Random constructor is called
57 | val incident = Incident(
58 | ISSUE,
59 | node,
60 | context.getLocation(node),
61 | "`$UTIL_RANDOM` should only be used for non-security contexts as it is not a cryptographically " +
62 | "secure PRNG",
63 | fix().replace().range(context.getLocation(node)).with("SecureRandom()").imports(
64 | SECURE_RANDOM).build()
65 | )
66 | context.report(incident)
67 | }
68 |
69 | companion object {
70 | // Classes
71 | private const val LANG_MATH = "java.lang.Math"
72 | private const val UTIL_RANDOM = "java.util.Random"
73 | private const val SECURE_RANDOM = "java.security.SecureRandom"
74 |
75 | // Methods
76 | private const val RANDOM = "random"
77 |
78 | @JvmField
79 | val ISSUE: Issue =
80 | Issue.create(
81 | id = "WeakPrng",
82 | briefDescription = "Application uses non-cryptographically secure pseudorandom number generators",
83 | explanation =
84 | """
85 | If a non-cryptographically secure pseudorandom number generator (PRNG) is used in a security context \
86 | like authentication, an attacker may be able to guess the randomly-generated numbers and gain access \
87 | to privileged data or functionality.
88 | """,
89 | category = Category.SECURITY,
90 | priority = 4,
91 | severity = Severity.WARNING,
92 | moreInfo = "https://goo.gle/WeakPrng",
93 | implementation = Implementation(WeakPrngDetector::class.java, Scope.JAVA_FILE_SCOPE)
94 | )
95 | }
96 | }
--------------------------------------------------------------------------------
/checks/src/main/resources/META-INF/services/com.android.tools.lint.client.api.IssueRegistry:
--------------------------------------------------------------------------------
1 | com.example.lint.checks.IssueRegistry
2 |
--------------------------------------------------------------------------------
/checks/src/test/java/com/example/lint/checks/BluetoothAdapterDetectorTest.kt:
--------------------------------------------------------------------------------
1 | package com.example.lint.checks
2 |
3 | import com.android.tools.lint.checks.infrastructure.LintDetectorTest
4 | import com.android.tools.lint.detector.api.Detector
5 | import org.junit.Test
6 | import org.junit.runner.RunWith
7 | import org.junit.runners.JUnit4
8 |
9 | @RunWith(JUnit4::class)
10 | class BluetoothAdapterDetectorTest : LintDetectorTest() {
11 | override fun getIssues() =
12 | mutableListOf(
13 | BluetoothAdapterDetector.ZERO_BLUETOOTH_DISCOVERY_DURATION_ISSUE,
14 | BluetoothAdapterDetector.EXTENDED_BLUETOOTH_DISCOVERY_DURATION_ISSUE
15 | )
16 |
17 | override fun getDetector(): Detector = BluetoothAdapterDetector()
18 |
19 | @Test
20 | fun extraDiscoverableDurationIsZero_showsWarning() {
21 | lint().files(
22 | java(
23 | """import android.app.Activity;
24 | import android.bluetooth.BluetoothAdapter;
25 | import android.content.Intent;
26 |
27 | public class MainActivity extends Activity {
28 | private Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
29 | }"""
30 | ).indented()
31 | ).run().expect(
32 | """src/MainActivity.java:6: Error: The EXTRA_DISCOVERABLE_DURATION time should never be set to zero [ZeroBluetoothDiscoveryDuration]
33 | private Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
34 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
35 | 1 errors, 0 warnings""".trimIndent()
36 | )
37 | }
38 |
39 | @Test
40 | fun extraDiscoverableDurationIsZero_showsQuickFix() {
41 | lint().files(
42 | java(
43 | """import android.app.Activity;
44 | import android.bluetooth.BluetoothAdapter;
45 | import android.content.Intent;
46 |
47 | public class MainActivity extends Activity {
48 | private Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
49 | }"""
50 | ).indented()
51 | ).run().expectFixDiffs(
52 | // Unfortunately, the semi-colon will be left behind due to limitations with the lint API
53 | // needing to also account for chained calls, and it being impossible to fully detect the
54 | // entire relevant code block to delete.
55 | """Fix for src/MainActivity.java line 6: Replace with 120:
56 | @@ -6 +6
57 | - private Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
58 | + private Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120);"""
59 | )
60 | }
61 |
62 | @Test
63 | fun extraDiscoverableDurationIsNonZero_showsNoWarning() {
64 | lint().files(
65 | java(
66 | """import android.app.Activity;
67 | import android.bluetooth.BluetoothAdapter;
68 | import android.content.Intent;
69 |
70 | public class MainActivity extends Activity {
71 | private Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 1);
72 | }"""
73 | ).indented()
74 | ).run().expectClean()
75 | }
76 |
77 | @Test
78 | fun extraDiscoverableDurationMoreThan120Seconds_showsWarning() {
79 | lint().files(
80 | java(
81 | """import android.app.Activity;
82 | import android.bluetooth.BluetoothAdapter;
83 | import android.content.Intent;
84 |
85 | public class MainActivity extends Activity {
86 | private Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 121);
87 | }"""
88 | ).indented()
89 | ).run().expect(
90 | """src/MainActivity.java:6: Warning: The EXTRA_DISCOVERABLE_DURATION time should be set to a shorter amount of time [ExtendedBluetoothDiscoveryDuration]
91 | private Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 121);
92 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
93 | 0 errors, 1 warnings""".trimIndent()
94 | )
95 | }
96 |
97 | @Test
98 | fun extraDiscoverableDurationMoreThan120Seconds_showsQuickFix() {
99 | lint().files(
100 | java(
101 | """import android.app.Activity;
102 | import android.bluetooth.BluetoothAdapter;
103 | import android.content.Intent;
104 |
105 | public class MainActivity extends Activity {
106 | private Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 121);
107 | }"""
108 | ).indented()
109 | ).run().expectFixDiffs(
110 | // Unfortunately, the semi-colon will be left behind due to limitations with the lint API
111 | // needing to also account for chained calls, and it being impossible to fully detect the
112 | // entire relevant code block to delete.
113 | """Fix for src/MainActivity.java line 6: Replace with 120:
114 | @@ -6 +6
115 | - private Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 121);
116 | + private Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120);"""
117 | )
118 | }
119 |
120 | @Test
121 | fun extraDiscoverableDurationIs120Seconds_showsNoWarning() {
122 | lint().files(
123 | java(
124 | """import android.app.Activity;
125 | import android.bluetooth.BluetoothAdapter;
126 | import android.content.Intent;
127 |
128 | public class MainActivity extends Activity {
129 | private Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE).putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120);
130 | }"""
131 | ).indented()
132 | ).run().expectClean()
133 | }
134 |
135 | }
--------------------------------------------------------------------------------
/checks/src/test/java/com/example/lint/checks/CustomSchemeDetectorTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2024 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.tools.lint.checks.infrastructure.LintDetectorTest
19 | import com.android.tools.lint.detector.api.Detector
20 |
21 | import org.junit.Test
22 | import org.junit.runner.RunWith
23 | import org.junit.runners.JUnit4
24 |
25 | @RunWith(JUnit4::class)
26 | class CustomSchemeDetectorTest : LintDetectorTest() {
27 | override fun getIssues() = mutableListOf(CustomSchemeDetector.AUTOVERIFY_ATTRIBUTE_ISSUE)
28 |
29 | override fun getDetector(): Detector = CustomSchemeDetector()
30 |
31 | @Test
32 | fun testWhenNoIntentFilterSpecifiedInManifest_showsNoWarning() {
33 | lint()
34 | .files(
35 | manifest("""
36 |
37 |
38 |
39 |
40 |
41 | """
42 | ).indented()
43 | ).run().expectClean()
44 | }
45 |
46 | @Test
47 | fun testWhenAutoVerifyAttributeSpecifiedOnCustomSchemeIntentFilter_noWarning() {
48 | lint()
49 | .files(
50 | manifest("""
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 | """
63 | ).indented()
64 | ).run().expectClean()
65 | }
66 |
67 | @Test
68 | fun testWhenNoAutoVerifyAttributeSpecifiedOnRegularSchemeIntentFilter_noWarning() {
69 | lint()
70 | .files(
71 | manifest("""
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 | """
85 | ).indented()
86 | ).run().expectClean()
87 | }
88 |
89 | @Test
90 | fun testWhenFalseAutoVerifyAttributeSpecifiedOnCustomSchemeIntentFilter_showsWarning() {
91 | lint().files(
92 | manifest("""
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 | """
105 | ).indented()
106 | ).run().expect(
107 | """
108 | AndroidManifest.xml:5: Warning: Custom scheme intent filters should explicitly set the autoVerify attribute to true [MissingAutoVerifyAttribute]
109 |
110 | ^
111 | 0 errors, 1 warnings
112 | """
113 | )
114 | }
115 |
116 | @Test
117 | fun testWhenNoAutoVerifyAttributeSpecifiedOnCustomSchemeIntentFilter_showsWarning() {
118 | lint().files(
119 | manifest("""
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 | """
132 | ).indented()
133 | ).run().expect(
134 | """
135 | AndroidManifest.xml:5: Warning: Custom scheme intent filters should explicitly set the autoVerify attribute to true [MissingAutoVerifyAttribute]
136 |
137 | ^
138 | 0 errors, 1 warnings
139 | """
140 | )
141 | }
142 |
143 | @Test
144 | fun testWhenNoAutoVerifyAttributeSpecifiedOnCustomSchemeIntentFilter_showsQuickFix() {
145 | lint().files(
146 | manifest("""
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 | """
159 | ).indented()
160 | ).run().expectFixDiffs(
161 | """
162 | Fix for AndroidManifest.xml line 5: Set autoVerify="true":
163 | @@ -9 +9
164 | -
165 | +
166 | """
167 | )
168 | }
169 |
170 | @Test
171 | fun testWhenFalseAutoVerifyAttributeSpecifiedOnCustomSchemeIntentFilter_showsQuickFix() {
172 | lint().files(
173 | manifest("""
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 | """
186 | ).indented()
187 | ).run().expectFixDiffs(
188 | """
189 | Fix for AndroidManifest.xml line 5: Set autoVerify="true":
190 | @@ -9 +9
191 | -
192 | +
193 | """
194 | )
195 | }
196 | }
197 |
--------------------------------------------------------------------------------
/checks/src/test/java/com/example/lint/checks/DnsConfigDetectorTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2024 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.tools.lint.checks.infrastructure.LintDetectorTest
19 | import com.android.tools.lint.detector.api.Detector
20 |
21 | import org.junit.Test
22 | import org.junit.runner.RunWith
23 | import org.junit.runners.JUnit4
24 |
25 | @RunWith(JUnit4::class)
26 | class DnsConfigDetectorTest : LintDetectorTest() {
27 | override fun getIssues() = mutableListOf(DnsConfigDetector.SDK_LEVEL_ISSUE)
28 |
29 | override fun getDetector(): Detector = DnsConfigDetector()
30 |
31 | @Test
32 | fun testWhenNoTargetSdkVersionSpecified_showsNoWarning() {
33 | lint()
34 | .files(
35 | manifest("""
36 |
37 |
38 |
39 |
40 |
41 |
42 | """
43 | ).indented()
44 | ).run().expectClean()
45 | }
46 |
47 | @Test
48 | fun testWhenTargetSdkBelowSecureDnsTransportPatch_showsWarning() {
49 | lint().files(
50 | manifest("""
51 |
52 |
53 |
54 |
55 |
56 |
57 | """
58 | ).indented()
59 | ).run().expect(
60 | """
61 | AndroidManifest.xml:2: Warning: Update your application's target SDK version to 28 and above to make use of the Android OS's built-in transport security features [InsecureDnsSdkLevel]
62 |
63 | ~~
64 | 0 errors, 1 warnings
65 | """
66 | )
67 | }
68 |
69 | @Test
70 | fun testWhenTargetSdkBelowSecureDnsTransportPatch_showsQuickFix() {
71 | lint().files(
72 | manifest("""
73 |
74 |
75 |
76 |
77 |
78 |
79 | """
80 | ).indented()
81 | ).run().expectFixDiffs(
82 | """
83 | Fix for AndroidManifest.xml line 2: Set targetSdkVersion="28":
84 | @@ -5 +5
85 | -
86 | +
87 | """
88 | )
89 | }
90 |
91 | @Test
92 | fun testWhenTargetSdkAtSecureDnsTransportPatchLevel_noWarning() {
93 | lint()
94 | .files(
95 | manifest("""
96 |
97 |
98 |
99 |
100 |
101 |
102 | """
103 | ).indented()
104 | ).run().expectClean()
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/checks/src/test/java/com/example/lint/checks/InsecureStorageDetectorTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2024 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.tools.lint.checks.infrastructure.LintDetectorTest
19 | import com.android.tools.lint.detector.api.Detector
20 |
21 | import org.junit.Test
22 | import org.junit.runner.RunWith
23 | import org.junit.runners.JUnit4
24 |
25 | @RunWith(JUnit4::class)
26 | class InsecureExternalDataStorageDetectorTest : LintDetectorTest() {
27 | override fun getIssues() =
28 | mutableListOf(InsecureStorageDetector.LEGACY_EXTERNAL_STORAGE_ISSUE)
29 |
30 | override fun getDetector(): Detector = InsecureStorageDetector()
31 |
32 | @Test
33 | fun testWhenNoRequestLegacyExternalStorageDeclared_showsNoWarning() {
34 | lint()
35 | .files(
36 | manifest(
37 | """
38 |
39 |
40 |
41 |
42 |
43 | """
44 | ).indented()
45 | ).run().expectClean()
46 | }
47 |
48 | @Test
49 | fun testWhenRequestLegacyExternalStorageDeclared_whenPatchedSdkLevel_showsNoWarning() {
50 | lint()
51 | .files(
52 | manifest(
53 | """
54 |
55 |
56 |
57 |
58 |
59 |
60 | """
61 | ).indented()
62 | ).run().expectClean()
63 | }
64 |
65 | @Test
66 | fun testWhenRequestLegacyExternalStorageDeclared_whenBelowPatchedSdkLevel_showsWarning() {
67 | lint().files(
68 | manifest(
69 | """
70 |
71 |
72 |
73 |
74 |
75 |
76 | """
77 | ).indented()
78 | ).run().expect(
79 | """AndroidManifest.xml:3: Warning: Setting requestLegacyExternalStorage to true will disable Android Scoped Storage [InsecureLegacyExternalStorage]
80 |
81 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
82 | 0 errors, 1 warnings"""
83 | )
84 | }
85 |
86 | @Test
87 | fun testWhenRequestLegacyExternalStorageDeclared_whenBelowPatchedSdkLevel_showsQuickFix() {
88 | lint().files(
89 | manifest(
90 | """
91 |
92 |
93 |
94 |
95 |
96 |
97 | """
98 | ).indented()
99 | ).run().expectFixDiffs(
100 | """Fix for AndroidManifest.xml line 3: Set requestLegacyExternalStorage="false":
101 | @@ -7 +7
102 | -
103 | + """
104 | )
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/checks/src/test/java/com/example/lint/checks/LogcatDetectorTest.kt:
--------------------------------------------------------------------------------
1 | package com.example.lint.checks
2 |
3 | import com.android.tools.lint.checks.infrastructure.LintDetectorTest
4 | import com.android.tools.lint.detector.api.Detector
5 | import org.junit.Test
6 | import org.junit.runner.RunWith
7 | import org.junit.runners.JUnit4
8 |
9 | @RunWith(JUnit4::class)
10 | class LogInfoDisclosureDetectorTest : LintDetectorTest() {
11 | override fun getIssues() = listOf(LogcatDetector.LOG_INFO_DISCLOSURE_ISSUE)
12 |
13 | override fun getDetector(): Detector = LogcatDetector()
14 |
15 | @Test
16 | fun logInfoDisclosureMethod_whenSuspiciousStringPresent_showsWarning() {
17 | lint().files(
18 | java(
19 | """
20 | import android.app.Activity;
21 | import android.util.Log;
22 |
23 | public class MainActivity extends Activity {
24 |
25 | private void testLogs() {
26 | Log.wtf("testpasswdtest", "test");
27 | }
28 | }
29 | """
30 | ).indented()
31 | ).run().expect(
32 | """
33 | src/MainActivity.java:7: Warning: Sensitive data should never be logged to logcat [LogInfoDisclosure]
34 | Log.wtf("testpasswdtest", "test");
35 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
36 | 0 errors, 1 warnings
37 | """
38 | )
39 | }
40 |
41 | @Test
42 | fun logInfoDisclosureMethod_whenSuspiciousStringPresent_showsQuickFix() {
43 | lint().files(
44 | kotlin(
45 | """
46 | import android.app.Activity
47 | import android.util.Log
48 |
49 | class MainActivity: Activity {
50 |
51 | private fun testLogs() {
52 | Log.v("hiddenkeyinstring", "test")
53 | }
54 | }
55 | """
56 | ).indented()
57 | ).run().expectFixDiffs(
58 | """
59 | Fix for src/MainActivity.kt line 7: Delete:
60 | @@ -7 +7
61 | - Log.v("hiddenkeyinstring", "test")
62 | """
63 | )
64 | }
65 |
66 | @Test
67 | fun logInfoDisclosureMethod_whenDifferentCasing_showsWarning() {
68 | lint().files(
69 | kotlin(
70 | """
71 | import android.app.Activity
72 | import android.util.Log
73 |
74 | class MainActivity: Activity {
75 |
76 | private fun testLogs() {
77 | Log.e("creDenTiAlblahblah", "test")
78 | }
79 | }
80 | """
81 | ).indented()
82 | ).run().expect(
83 | """
84 | src/MainActivity.kt:7: Warning: Sensitive data should never be logged to logcat [LogInfoDisclosure]
85 | Log.e("creDenTiAlblahblah", "test")
86 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
87 | 0 errors, 1 warnings
88 | """
89 | )
90 | }
91 |
92 | @Test
93 | fun logInfoDisclosureMethod_whenDifferentCasing_showsQuickFix() {
94 | lint().files(
95 | kotlin(
96 | """
97 | import android.app.Activity
98 | import android.util.Log
99 |
100 | class MainActivity: Activity {
101 |
102 | private fun testLogs() {
103 | Log.v("passWORD", "test")
104 | }
105 | }
106 | """
107 | ).indented()
108 | ).run().expectFixDiffs(
109 | """
110 | Fix for src/MainActivity.kt line 7: Delete:
111 | @@ -7 +7
112 | - Log.v("passWORD", "test")
113 | """
114 | )
115 | }
116 |
117 | @Test
118 | fun logInfoDisclosureMethod_whenNoSuspiciousStrings_showsNoWarning() {
119 | lint().files(
120 | java(
121 | """
122 | import android.app.Activity;
123 | import android.util.Log;
124 |
125 | public class MainActivity extends Activity {
126 |
127 | private void testLogs() {
128 | Log.d("testtesttest", "test");
129 | }
130 | }
131 | """
132 | ).indented()
133 | ).run().expectClean()
134 | }
135 |
136 | }
--------------------------------------------------------------------------------
/checks/src/test/java/com/example/lint/checks/MisconfiguredFileProviderDetectorTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.tools.lint.checks.infrastructure.LintDetectorTest
19 | import com.android.tools.lint.detector.api.Detector
20 |
21 | import org.junit.Test
22 | import org.junit.runner.RunWith
23 | import org.junit.runners.JUnit4
24 |
25 | @RunWith(JUnit4::class)
26 | class MisconfiguredFileProviderDetectorTest : LintDetectorTest() {
27 | override fun getIssues() = mutableListOf(
28 | MisconfiguredFileProviderDetector.ROOT_PATH_ISSUE,
29 | MisconfiguredFileProviderDetector.EXTERNAL_PATH_ISSUE,
30 | MisconfiguredFileProviderDetector.DOT_PATH_ISSUE,
31 | MisconfiguredFileProviderDetector.SLASH_PATH_ISSUE,
32 | MisconfiguredFileProviderDetector.ABSOLUTE_PATH_ISSUE
33 | )
34 |
35 | override fun getDetector(): Detector = MisconfiguredFileProviderDetector()
36 |
37 | @Test
38 | fun testWhenRootPathUsedInConfig_showsWarningAndQuickFix() {
39 | lint()
40 | .files(
41 | xml("res/xml/file_paths.xml",
42 | """
43 |
44 |
45 |
46 |
47 |
48 | """
49 | ).indented()
50 | ).run().expect(
51 | """
52 | res/xml/file_paths.xml:5: Warning: Do not use as it provides arbitrary access to device files and folders [ExposedRootPath]
53 |
54 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
55 | 0 errors, 1 warnings
56 | """
57 | ).expectFixDiffs("""
58 | Fix for res/xml/file_paths.xml line 5: Delete:
59 | @@ -5 +5
60 | -
61 | """
62 | )
63 | }
64 |
65 | @Test
66 | fun testWhenExternalPathUsedInConfig_showsWarningAndQuickFix() {
67 | lint()
68 | .files(
69 | xml("res/xml/file_paths.xml",
70 | """
71 |
72 |
73 |
74 |
75 |
76 | """
77 | ).indented()
78 | ).run().expect(
79 | """
80 | res/xml/file_paths.xml:5: Warning: Sensitive info like PII should not be stored or shared via [SensitiveExternalPath]
81 |
82 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
83 | 0 errors, 1 warnings
84 | """
85 | ).expectFixDiffs("""
86 | Fix for res/xml/file_paths.xml line 5: Delete:
87 | @@ -5 +5
88 | -
89 | """)
90 | }
91 |
92 | @Test
93 | fun testWhenDotPathUsedInConfig_showsWarningAndQuickFix() {
94 | lint()
95 | .files(
96 | xml("res/xml/file_paths.xml",
97 | """
98 |
99 |
100 |
101 |
102 |
103 | """
104 | ).indented()
105 | ).run().expect(
106 | """
107 | res/xml/file_paths.xml:5: Warning: The "path" attribute should not be set to "." [DotPathAttribute]
108 |
109 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
110 | 0 errors, 1 warnings
111 | """
112 | ).expectFixDiffs("""
113 | Fix for res/xml/file_paths.xml line 5: Delete:
114 | @@ -5 +5
115 | -
116 | """)
117 | }
118 |
119 | @Test
120 | fun testWhenSlashPathUsedInConfig_showsWarningAndQuickFix() {
121 | lint()
122 | .files(
123 | xml("res/xml/file_paths.xml",
124 | """
125 |
126 |
127 |
128 |
129 |
130 | """
131 | ).indented()
132 | ).run().expect(
133 | """
134 | res/xml/file_paths.xml:5: Warning: The "path" attribute should not be set to "/" [SlashPathAttribute]
135 |
136 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
137 | 0 errors, 1 warnings
138 | """
139 | ).expectFixDiffs("""
140 | Fix for res/xml/file_paths.xml line 5: Delete:
141 | @@ -5 +5
142 | -
143 | """)
144 | }
145 |
146 | @Test
147 | fun testWhenAbsolutePathUsedInConfig_showsWarningAndQuickFix() {
148 | lint()
149 | .files(
150 | xml("res/xml/file_paths.xml",
151 | """
152 |
153 |
154 |
155 |
156 |
157 | """
158 | ).indented()
159 | ).run().expect(
160 | """
161 | res/xml/file_paths.xml:5: Warning: The "path" attribute should not be an absolute path [HardcodedAbsolutePath]
162 |
163 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
164 | 0 errors, 1 warnings
165 | """
166 | ).expectFixDiffs("""
167 | Fix for res/xml/file_paths.xml line 5: Delete:
168 | @@ -5 +5
169 | -
170 | """)
171 | }
172 |
173 | @Test
174 | fun testWhenNoRootOrExternalPathUsedInConfig_noWarning() {
175 | lint()
176 | .files(
177 | xml("res/xml/file_paths.xml",
178 | """
179 |
180 |
181 |
182 |
183 | """
184 | ).indented()
185 | ).run().expectClean()
186 | }
187 |
188 | @Test
189 | fun testWhenNoSpecialCharPathsUsedInConfig_noWarning() {
190 | lint()
191 | .files(
192 | xml("res/xml/file_paths.xml",
193 | """
194 |
195 |
196 |
197 |
198 |
199 | """
200 | ).indented()
201 | ).run().expectClean()
202 | }
203 | }
204 |
--------------------------------------------------------------------------------
/checks/src/test/java/com/example/lint/checks/MissingNetworkSecurityConfigDetectorTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.tools.lint.checks.infrastructure.LintDetectorTest
19 | import com.android.tools.lint.checks.infrastructure.TestFile
20 | import com.android.tools.lint.detector.api.Detector
21 |
22 | import org.junit.Test
23 | import org.junit.runner.RunWith
24 | import org.junit.runners.JUnit4
25 |
26 | @RunWith(JUnit4::class)
27 | class MissingNetworkSecurityConfigDetectorTest : LintDetectorTest() {
28 | override fun getIssues() = mutableListOf(
29 | MissingNetworkSecurityConfigDetector.CLEARTEXT_TRAFFIC_ISSUE,
30 | MissingNetworkSecurityConfigDetector.TRUSTED_USER_CERTS_ISSUE
31 | )
32 |
33 | override fun getDetector(): Detector = MissingNetworkSecurityConfigDetector()
34 |
35 | @Test
36 | fun testWhenNoNetworkSecurityConfig_sdkLevelAboveDefaultCleartextTraffic_noWarning() {
37 | lint()
38 | .files(
39 | manifest("""
40 |
41 |
42 |
43 |
44 |
45 |
46 | """
47 | ).indented()
48 | ).run().expectClean()
49 | }
50 |
51 | @Test
52 | fun testWhenHasNetworkSecurityConfig_noWarning() {
53 | lint()
54 | .files(
55 | manifest("""
56 |
57 |
58 |
59 |
60 |
61 |
62 | """
63 | ).indented()
64 | ).run().expectClean()
65 | }
66 |
67 | @Test
68 | fun testWhenNoNetworkSecurityConfig_defaultCleartextTrafficSdkLevel_showsWarning() {
69 | lint()
70 | .files(
71 | manifest("""
72 |
73 |
74 |
75 |
76 |
77 |
78 | """
79 | ).indented()
80 | ).run().expect(
81 | """
82 | AndroidManifest.xml:3: Warning: On SDK versions below 28, the application by default trusts cleartext traffic. Add a Network Security Config file to opt out of these insecure connections. [DefaultCleartextTraffic]
83 |
84 | ~~~~~~~~~~~
85 | 0 errors, 1 warnings
86 | """
87 | )
88 | }
89 |
90 | @Test
91 | fun testWhenNoNetworkSecurityConfig_defaultUserCerts_showsWarning() {
92 | lint()
93 | .files(
94 | manifest("""
95 |
96 |
97 |
98 |
99 |
100 |
101 | """
102 | ).indented()
103 | ).run().expect(
104 | """
105 | AndroidManifest.xml:3: Warning: On SDK versions below 24, the application by default trusts user-added CA certificates. Add a Network Security Config file to opt out of this insecure behavior. [DefaultTrustedUserCerts]
106 |
107 | ~~~~~~~~~~~
108 | 0 errors, 1 warnings
109 | """
110 | )
111 | }
112 |
113 | @Test
114 | fun testWhenNoNetworkSecurityConfig_defaultCleartextTrafficSdkLevel_showsQuickFix() {
115 | lint().files(
116 | manifest("""
117 |
118 |
119 |
120 |
121 |
122 |
123 | """
124 | ).indented(),
125 | emptyXmlFile
126 | ).run().expectFixDiffs(
127 | """
128 | Fix for AndroidManifest.xml line 3: Create network security config:
129 | @@ -7 +7
130 | -
131 | +
132 | res/xml/network_security_config.xml:
133 | @@ -1 +1
134 | +
135 | +
136 | +
137 | +
138 | """
139 | )
140 | }
141 |
142 | @Test
143 | fun testWhenNoNetworkSecurityConfig_defaultUserCerts_showsQuickFix() {
144 | // TODO: fix why quick fix is re
145 | lint().files(
146 | manifest("""
147 |
148 |
149 |
150 |
151 |
152 |
153 | """
154 | ).indented(),
155 | emptyXmlFile
156 | ).run().expectFixDiffs(
157 | """
158 | Fix for AndroidManifest.xml line 3: Create network security config:
159 | @@ -7 +7
160 | -
161 | +
162 | res/xml/network_security_config.xml:
163 | @@ -1 +1
164 | +
165 | +
166 | +
167 | +
168 | +
169 | +
170 | +
171 | +
172 | """
173 | )
174 | }
175 |
176 | companion object {
177 | // It's necessary to add an empty XML File in order for the unit test to recognize that a resources folder
178 | // exists
179 | val emptyXmlFile: TestFile = xml(
180 | "res/xml/strings.xml",
181 | """
182 |
183 | """
184 | ).indented()
185 | }
186 | }
187 |
--------------------------------------------------------------------------------
/checks/src/test/java/com/example/lint/checks/PermissionDetectorTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2024 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.tools.lint.checks.infrastructure.LintDetectorTest
19 | import com.android.tools.lint.detector.api.Detector
20 |
21 | import org.junit.Test
22 | import org.junit.runner.RunWith
23 | import org.junit.runners.JUnit4
24 |
25 | @RunWith(JUnit4::class)
26 | class PermissionDetectorTest : LintDetectorTest() {
27 | override fun getIssues() = mutableListOf(PermissionDetector.PROTECTION_LEVEL_ISSUE)
28 |
29 | override fun getDetector(): Detector = PermissionDetector()
30 |
31 | @Test
32 | fun testWhenNoCustomPermissionsInManifest_showsNoWarning() {
33 | lint()
34 | .files(
35 | manifest("""
36 |
37 |
38 |
39 |
40 |
41 | """
42 | ).indented()
43 | ).run().expectClean()
44 | }
45 |
46 | @Test
47 | fun testWhenCustomPermissionSignatureProtectionLevel_noWarning() {
48 | lint()
49 | .files(
50 | manifest("""
51 |
52 |
54 |
55 |
56 |
57 |
58 | """
59 | ).indented()
60 | ).run().expectClean()
61 | }
62 |
63 | @Test
64 | fun testWhenCustomPermissionDangerousProtectionLevel_noWarning() {
65 | lint()
66 | .files(
67 | manifest("""
68 |
69 |
71 |
72 |
73 |
74 |
75 | """
76 | ).indented()
77 | ).run().expectClean()
78 | }
79 |
80 | @Test
81 | /** Custom permissions have a default normal protectionLevel. */
82 | fun testWhenCustomPermissionNoSpecifiedProtectionLevel_showsWarning() {
83 | lint().files(
84 | manifest("""
85 |
86 |
87 |
88 |
89 |
90 |
91 | """
92 | ).indented()
93 | ).run().expect(
94 | """
95 | AndroidManifest.xml:2: Warning: Custom permissions should have a signature protectionLevel or higher [InsecurePermissionProtectionLevel]
96 |
97 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
98 | 0 errors, 1 warnings
99 | """
100 | )
101 | }
102 |
103 | @Test
104 | fun testWhenCustomPermissionNormalProtectionLevel_showsWarning() {
105 | lint().files(
106 | manifest("""
107 |
108 |
110 |
111 |
112 |
113 |
114 | """
115 | ).indented()
116 | ).run().expect(
117 | """
118 | AndroidManifest.xml:2: Warning: Custom permissions should have a signature protectionLevel or higher [InsecurePermissionProtectionLevel]
119 |
131 |
133 |
134 |
135 |
136 |
137 | """
138 | ).indented()
139 | ).run().expectFixDiffs(
140 | """
141 | Fix for AndroidManifest.xml line 2: Set protectionLevel="signature":
142 | @@ -7 +7
143 | - android:protectionLevel="normal" />
144 | + android:protectionLevel="signature" />
145 | """
146 | )
147 | }
148 | }
149 |
--------------------------------------------------------------------------------
/checks/src/test/java/com/example/lint/checks/SafeBrowsingDetectorTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2024 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.tools.lint.checks.infrastructure.LintDetectorTest
19 | import com.android.tools.lint.detector.api.Detector
20 |
21 | import org.junit.Test
22 | import org.junit.runner.RunWith
23 | import org.junit.runners.JUnit4
24 |
25 | @RunWith(JUnit4::class)
26 | class SafeBrowsingDetectorTest : LintDetectorTest() {
27 | override fun getIssues() = mutableListOf(SafeBrowsingDetector.MANIFEST_ISSUE)
28 |
29 | override fun getDetector(): Detector = SafeBrowsingDetector()
30 |
31 | @Test
32 | fun testWhenNoSafeBrowsingSpecifiedInManifest_showsNoWarning() {
33 | lint()
34 | .files(
35 | manifest("""
36 |
37 |
38 |
39 |
40 |
41 | """
42 | ).indented()
43 | ).run().expectClean()
44 | }
45 |
46 | @Test
47 | /** Safe Browsing is enabled by default, so if no value is specified, it will be true. */
48 | fun testWhenSafeBrowsingEnabled_noWarning() {
49 | lint()
50 | .files(
51 | manifest("""
52 |
53 |
54 |
55 |
56 |
57 |
58 | """
59 | ).indented()
60 | ).run().expectClean()
61 | }
62 |
63 | @Test
64 | fun testWhenSafeBrowsingDisabledInManifest_showsWarning() {
65 | lint().files(
66 | manifest("""
67 |
68 |
69 |
70 |
71 |
72 |
73 | """
74 | ).indented()
75 | ).run().expect(
76 | """
77 | AndroidManifest.xml:3: Warning: Safe Browsing should be kept enabled at all times, as it aims to keep users from unsafe URLs [DisabledAllSafeBrowsing]
78 |
79 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
80 | 0 errors, 1 warnings
81 | """
82 | )
83 | }
84 |
85 | @Test
86 | fun testWhenSafeBrowsingDisabledInManifest_showsQuickFix() {
87 | lint().files(
88 | manifest("""
89 |
90 |
91 |
92 |
93 |
94 |
95 | """
96 | ).indented()
97 | ).run().expectFixDiffs(
98 | """
99 | Fix for AndroidManifest.xml line 3: Set android.webkit.WebView.EnableSafeBrowsing="true":
100 | @@ -8 +8
101 | + android:android.webkit.WebView.EnableSafeBrowsing="true"
102 | """
103 | )
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/checks/src/test/java/com/example/lint/checks/StickyBroadcastsDetectorTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2024 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.tools.lint.checks.infrastructure.LintDetectorTest
19 | import com.android.tools.lint.detector.api.Detector
20 | import org.junit.Test
21 | import org.junit.runner.RunWith
22 | import org.junit.runners.JUnit4
23 |
24 | @RunWith(JUnit4::class)
25 | class StickyBroadcastsDetectorTest : LintDetectorTest() {
26 | override fun getIssues() =
27 | mutableListOf(StickyBroadcastsDetector.STICKY_PERMISSION_ISSUE, StickyBroadcastsDetector.STICKY_METHOD_ISSUE)
28 |
29 | override fun getDetector(): Detector = StickyBroadcastsDetector()
30 |
31 | @Test
32 | fun stickyBroadcastPermissionInManifest_showsWarning() {
33 | lint().files(
34 | manifest(
35 | """
36 |
37 |
38 |
39 |
40 | """
41 | ).indented()
42 | ).run().expect(
43 | """
44 | AndroidManifest.xml:2: Warning: Sticky broadcasts can be accessed, sent or modified by anyone. Use non-sticky broadcasts instead. [InsecureStickyBroadcastsPermission]
45 |
46 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
47 | 0 errors, 1 warnings
48 | """
49 | )
50 | }
51 |
52 | @Test
53 | fun stickyBroadcastPermissionInManifest_showsQuickFix() {
54 | lint().files(
55 | manifest(
56 | """
57 |
58 |
59 |
60 |
61 | """
62 | ).indented()
63 | ).run().expectFixDiffs(
64 | """
65 | Fix for AndroidManifest.xml line 2: Delete:
66 | @@ -2 +2
67 | -
68 | """
69 | )
70 | }
71 |
72 | @Test
73 | fun differentBroadcastPermissionInManifest_showsNoWarning() {
74 | lint().files(
75 | manifest(
76 | """
77 |
78 |
79 |
80 |
81 | """
82 | ).indented()
83 | ).run().expectClean()
84 | }
85 |
86 | @Test
87 | fun stickyBroadcastMethodCall_showsWarning() {
88 | lint().files(
89 | java(
90 | """
91 | package fake.pkg;
92 |
93 | import android.app.Activity;
94 | import android.os.Bundle;
95 |
96 | @Suppress("DEPRECATION")
97 | public class MainActivity extends Activity {
98 |
99 | @Override
100 | protected void onCreate(Bundle savedInstanceState) {
101 | super.onCreate(savedInstanceState);
102 | sendStickyOrderedBroadcast();
103 | }
104 | }"""
105 | ).indented()
106 | ).run().expect(
107 | """
108 | src/fake/pkg/MainActivity.java:12: Warning: Sticky broadcasts can be accessed, sent or modified by anyone. Use non-sticky broadcasts instead. [InsecureStickyBroadcastsMethod]
109 | sendStickyOrderedBroadcast();
110 | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
111 | 0 errors, 1 warnings
112 | """
113 | )
114 | }
115 |
116 | @Test
117 | fun stickyBroadcastMethodCall_showsQuickFix() {
118 | lint().files(
119 | java(
120 | """
121 | package fake.pkg;
122 |
123 | import android.app.Activity;
124 | import android.os.Bundle;
125 |
126 | @Suppress("DEPRECATION")
127 | public class MainActivity extends Activity {
128 |
129 | @Override
130 | protected void onCreate(Bundle savedInstanceState) {
131 | super.onCreate(savedInstanceState);
132 | Intent intent = new Intent();
133 | sendStickyOrderedBroadcast(intent);
134 | }
135 | }"""
136 | ).indented()
137 | ).run().expectFixDiffs(
138 | // Unfortunately, the semi-colon will be left behind due to limitations with the lint API
139 | // needing to also account for chained calls, and it being impossible to fully detect the
140 | // entire relevant code block to delete.
141 | """
142 | Fix for src/fake/pkg/MainActivity.java line 13: Delete:
143 | @@ -13 +13
144 | - sendStickyOrderedBroadcast(intent);
145 | + ;
146 | """
147 | )
148 | }
149 |
150 | @Test
151 | fun regularBroadcastMethodCall_showsNoWarning() {
152 | lint().files(
153 | java(
154 | """
155 | package fake.pkg;
156 |
157 | import android.app.Activity;
158 | import android.os.Bundle;
159 |
160 | @Suppress("DEPRECATION")
161 | public class MainActivity extends Activity {
162 |
163 | @Override
164 | protected void onCreate(Bundle savedInstanceState) {
165 | super.onCreate(savedInstanceState);
166 | sendBroadcast();
167 | }
168 | }"""
169 | ).indented()
170 | ).run().expectClean()
171 | }
172 | }
--------------------------------------------------------------------------------
/checks/src/test/java/com/example/lint/checks/StrandhoggDetectorTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.tools.lint.checks.infrastructure.LintDetectorTest
19 | import com.android.tools.lint.detector.api.Detector
20 |
21 | import org.junit.Test
22 | import org.junit.runner.RunWith
23 | import org.junit.runners.JUnit4
24 |
25 | @RunWith(JUnit4::class)
26 | class StrandhoggDetectorTest : LintDetectorTest() {
27 | override fun getIssues() = mutableListOf(StrandhoggDetector.ISSUE)
28 |
29 | override fun getDetector(): Detector = StrandhoggDetector()
30 |
31 | @Test
32 | fun testWhenNoTargetSdkVersionSpecified_showsNoWarning() {
33 | lint()
34 | .files(
35 | manifest("""
36 |
37 |
38 |
39 |
40 |
41 |
42 | """
43 | ).indented()
44 | ).run().expectClean()
45 | }
46 |
47 | @Test
48 | fun testWhenTargetSdkBelowStrandhoggPatch_showsWarning() {
49 | lint().files(
50 | manifest("""
51 |
52 |
53 |
54 |
55 |
56 |
57 | """
58 | ).indented()
59 | ).run().expect(
60 | """
61 | AndroidManifest.xml:2: Warning: Update your application's target SDK version to 28 and above to protect it from Strandhogg attacks [StrandhoggVulnerable]
62 |
63 | ~~
64 | 0 errors, 1 warnings
65 | """
66 | )
67 | }
68 |
69 | @Test
70 | fun testWhenTargetSdkBelowStrandhoggPatch_showsQuickFix() {
71 | lint().files(
72 | manifest("""
73 |
74 |
75 |
76 |
77 |
78 |
79 | """
80 | ).indented()
81 | ).run().expectFixDiffs(
82 | """
83 | Fix for AndroidManifest.xml line 2: Set targetSdkVersion="28":
84 | @@ -5 +5
85 | -
86 | +
87 | """
88 | )
89 | }
90 |
91 | @Test
92 | fun testWhenTargetSdkAtStrandhoggPatch_noWarning() {
93 | lint()
94 | .files(
95 | manifest("""
96 |
97 |
98 |
99 |
100 |
101 |
102 | """
103 | ).indented()
104 | ).run().expectClean()
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/checks/src/test/java/com/example/lint/checks/TapjackingDetectorTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.tools.lint.checks.infrastructure.LintDetectorTest
19 | import com.android.tools.lint.detector.api.Detector
20 |
21 | import org.junit.Test
22 | import org.junit.runner.RunWith
23 | import org.junit.runners.JUnit4
24 |
25 | @RunWith(JUnit4::class)
26 | class TapjackingDetectorTest : LintDetectorTest() {
27 | override fun getIssues() = mutableListOf(TapjackingDetector.ISSUE)
28 |
29 | override fun getDetector(): Detector = TapjackingDetector()
30 |
31 | @Test
32 | fun testWhenNamedEnableUiElement_showsWarning() {
33 | lint().files(
34 | xml(
35 | "res/xml/switch.xml",
36 | """
37 |
38 |
39 |
40 |
41 |
42 | """
43 | ).indented()
44 | ).run().expect(
45 | """
46 | res/xml/switch.xml:3: Warning: Add the android:filterTouchesWhenObscured attribute to protect this UI element from tapjacking / overlay attacks [TapjackingVulnerable]
47 |
48 | ~~~~~~
49 | 0 errors, 1 warnings
50 | """
51 | )
52 | }
53 |
54 | @Test
55 | fun testWhenNamedDisableUiElement_showsWarning() {
56 | lint().files(
57 | xml(
58 | "res/xml/checkbox.xml",
59 | """
60 |
61 |
62 |
64 |
65 |
66 | """
67 | ).indented()
68 | ).run().expect(
69 | """
70 | res/xml/checkbox.xml:3: Warning: Add the android:filterTouchesWhenObscured attribute to protect this UI element from tapjacking / overlay attacks [TapjackingVulnerable]
71 |
85 |
86 |
87 |
88 |
89 | """
90 | ).indented()
91 | ).run().expectFixDiffs(
92 | """
93 | Fix for res/xml/button.xml line 3: Set filterTouchesWhenObscured="true":
94 | @@ -4 +4
95 | -
96 | +
99 | """
100 | )
101 | }
102 |
103 | @Test
104 | fun testWhenNamedDisableUiElement_showsQuickFix() {
105 | lint().files(
106 | xml(
107 | "res/xml/button.xml",
108 | """
109 |
110 |
111 |
112 |
113 |
114 | """
115 | ).indented()
116 | ).run().expectFixDiffs(
117 | """
118 | Fix for res/xml/button.xml line 3: Set filterTouchesWhenObscured="true":
119 | @@ -4 +4
120 | -
121 | +
124 | """
125 | )
126 | }
127 |
128 | @Test
129 | fun testWhenNoRelevantUiElement_noWarning() {
130 | lint()
131 | .files(
132 | xml(
133 | "res/xml/button.xml",
134 | """
135 |
136 |
137 |
138 |
139 | """
140 | ).indented()
141 | ).run().expectClean()
142 | }
143 |
144 | @Test
145 | fun testWhenNoInterestingNamedUiElement_noWarning() {
146 | lint()
147 | .files(
148 | xml(
149 | "res/xml/button.xml",
150 | """
151 |
152 |
153 |
154 |
155 | """
156 | ).indented()
157 | ).run().expectClean()
158 | }
159 | }
160 |
--------------------------------------------------------------------------------
/checks/src/test/java/com/example/lint/checks/WeakPrngDetectorTest.kt:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.example.lint.checks
17 |
18 | import com.android.tools.lint.checks.infrastructure.LintDetectorTest
19 | import com.android.tools.lint.detector.api.Detector
20 |
21 | import org.junit.Test
22 | import org.junit.runner.RunWith
23 | import org.junit.runners.JUnit4
24 |
25 |
26 | @RunWith(JUnit4::class)
27 | class WeakPrngDetectorTest : LintDetectorTest() {
28 |
29 | override fun getIssues() = listOf(WeakPrngDetector.ISSUE)
30 |
31 | override fun getDetector(): Detector = WeakPrngDetector()
32 |
33 | @Test
34 | fun testWhenMathRandomUsed_showsWarningAndQuickFix() {
35 | lint()
36 | .files(
37 | java(
38 | """
39 | package fake.pkg;
40 |
41 | import java.lang.Math;
42 |
43 | public class TestWeakPrngDetector {
44 | private void foo() {
45 | int random = Math.random() * 100;
46 | }
47 | }
48 | """
49 | ).indented()
50 | ).run().expect(
51 | """
52 | src/fake/pkg/TestWeakPrngDetector.java:7: Warning: Math.random relies on a weak PRNG, use java.util.Random for non-security contexts and java.security.SecureRandom for security / authentication purposes [WeakPrng]
53 | int random = Math.random() * 100;
54 | ~~~~~~~~~~~~~
55 | 0 errors, 1 warnings
56 | """
57 | ).expectFixDiffs("""
58 | Fix for src/fake/pkg/TestWeakPrngDetector.java line 7: Replace with Random().nextDouble():
59 | @@ -3 +3
60 | + import java.util.Random;
61 | @@ -7 +8
62 | - int random = Math.random() * 100;
63 | + int random = Random().nextDouble() * 100;
64 | """)
65 |
66 | }
67 |
68 | @Test
69 | fun testWhenUtilRandomUsed_showsWarningAndQuickFix() {
70 | lint()
71 | .files(
72 | kotlin(
73 | """
74 | package fake.pkg
75 |
76 | import java.util.Random
77 |
78 | class TestWeakPrngDetector {
79 | private fun foo() {
80 | val random = Random()
81 | val randomDouble = random.nextDouble()
82 | }
83 | }
84 | """
85 | ).indented()
86 | ).run().expect(
87 | """
88 | src/fake/pkg/TestWeakPrngDetector.kt:7: Warning: java.util.Random should only be used for non-security contexts as it is not a cryptographically secure PRNG [WeakPrng]
89 | val random = Random()
90 | ~~~~~~~~
91 | 0 errors, 1 warnings
92 | """
93 | ).expectFixDiffs("""
94 | Fix for src/fake/pkg/TestWeakPrngDetector.kt line 7: Replace with SecureRandom():
95 | @@ -3 +3
96 | + import java.security.SecureRandom
97 | @@ -7 +8
98 | - val random = Random()
99 | + val random = SecureRandom()
100 | """)
101 | }
102 |
103 | @Test
104 | fun testWhenNoWeakPrngUsed_noWarning() {
105 | lint()
106 | .files(
107 | java(
108 | """
109 | package fake.pkg;
110 |
111 | import java.security.SecureRandom;
112 |
113 | public class TestWeakPrngDetector {
114 | private void foo() {
115 | int randomInt = SecureRandom().nextInt(1000);
116 | }
117 | }
118 | """
119 | ).indented()
120 | ).run().expectClean()
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/docs/code-of-conduct.md:
--------------------------------------------------------------------------------
1 | # Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, gender identity and expression, level of
9 | experience, education, socio-economic status, nationality, personal appearance,
10 | race, religion, or sexual identity and orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or reject
41 | comments, commits, code, wiki edits, issues, and other contributions that are
42 | not aligned to this Code of Conduct, or to ban temporarily or permanently any
43 | contributor for other behaviors that they deem inappropriate, threatening,
44 | offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | This Code of Conduct also applies outside the project spaces when the Project
56 | Steward has a reasonable belief that an individual's behavior may have a
57 | negative impact on the project or its community.
58 |
59 | ## Conflict Resolution
60 |
61 | We do not believe that all conflict is bad; healthy debate and disagreement
62 | often yield positive results. However, it is never okay to be disrespectful or
63 | to engage in behavior that violates the project’s code of conduct.
64 |
65 | If you see someone violating the code of conduct, you are encouraged to address
66 | the behavior directly with those involved. Many issues can be resolved quickly
67 | and easily, and this gives people more control over the outcome of their
68 | dispute. If you are unable to resolve the matter for any reason, or if the
69 | behavior is threatening or harassing, report it. We are dedicated to providing
70 | an environment where participants feel welcome and safe.
71 |
72 | Reports should be directed to *[PROJECT STEWARD NAME(s) AND EMAIL(s)]*, the
73 | Project Steward(s) for *[PROJECT NAME]*. It is the Project Steward’s duty to
74 | receive and address reported violations of the code of conduct. They will then
75 | work with a committee consisting of representatives from the Open Source
76 | Programs Office and the Google Open Source Strategy team. If for any reason you
77 | are uncomfortable reaching out to the Project Steward, please email
78 | opensource@google.com.
79 |
80 | We will investigate every complaint, but you may not receive a direct response.
81 | We will use our discretion in determining when and how to follow up on reported
82 | incidents, which may range from not taking action to permanent expulsion from
83 | the project and project-sponsored spaces. We will notify the accused of the
84 | report and provide them an opportunity to discuss it before any action is taken.
85 | The identity of the reporter will be omitted from the details of the report
86 | supplied to the accused. In potentially harmful situations, such as ongoing
87 | harassment or threats to anyone's safety, we may take action without notice.
88 |
89 | ## Attribution
90 |
91 | This Code of Conduct is adapted from the Contributor Covenant, version 1.4,
92 | available at
93 | https://www.contributor-covenant.org/version/1/4/code-of-conduct/
94 |
--------------------------------------------------------------------------------
/docs/contributing.md:
--------------------------------------------------------------------------------
1 | # How to Contribute
2 |
3 | We would love to accept your patches and contributions to this project.
4 |
5 | ## Before you begin
6 |
7 | ### Sign our Contributor License Agreement
8 |
9 | Contributions to this project must be accompanied by a
10 | [Contributor License Agreement](https://cla.developers.google.com/about) (CLA).
11 | You (or your employer) retain the copyright to your contribution; this simply
12 | gives us permission to use and redistribute your contributions as part of the
13 | project.
14 |
15 | If you or your current employer have already signed the Google CLA (even if it
16 | was for a different project), you probably don't need to do it again.
17 |
18 | Visit to see your current agreements or to
19 | sign a new one.
20 |
21 | ### Review our Community Guidelines
22 |
23 | This project follows [Google's Open Source Community
24 | Guidelines](https://opensource.google/conduct/).
25 |
26 | ## Contribution process
27 |
28 | ### Code Reviews
29 |
30 | All submissions, including submissions by project members, require review. We
31 | use [GitHub pull requests](https://docs.github.com/articles/about-pull-requests)
32 | for this purpose.
33 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | android.nonFinalResIds=false
13 | android.nonTransitiveRClass=true
14 | org.gradle.jvmargs=-Xmx1536m
15 | kotlin.jvm.target.validation.mode=IGNORE
16 |
17 | # When configured, Gradle will run in incubating parallel mode.
18 | # This option should only be used with decoupled projects. More details, visit
19 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
20 | # org.gradle.parallel=true
21 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/google/android-security-lints/089c9bf8ca5f5bd605e8140b487f941e22a294f3/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sun Jul 14 14:58:49 PDT 2024
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.7-bin.zip
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/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 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
84 |
85 | APP_NAME="Gradle"
86 | APP_BASE_NAME=${0##*/}
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | MAX_FD=$( ulimit -H -n ) ||
147 | warn "Could not query maximum file descriptor limit"
148 | esac
149 | case $MAX_FD in #(
150 | '' | soft) :;; #(
151 | *)
152 | ulimit -n "$MAX_FD" ||
153 | warn "Could not set maximum file descriptor limit to $MAX_FD"
154 | esac
155 | fi
156 |
157 | # Collect all arguments for the java command, stacking in reverse order:
158 | # * args from the command line
159 | # * the main class name
160 | # * -classpath
161 | # * -D...appname settings
162 | # * --module-path (only if needed)
163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
164 |
165 | # For Cygwin or MSYS, switch paths to Windows format before running java
166 | if "$cygwin" || "$msys" ; then
167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
169 |
170 | JAVACMD=$( cygpath --unix "$JAVACMD" )
171 |
172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
173 | for arg do
174 | if
175 | case $arg in #(
176 | -*) false ;; # don't mess with options #(
177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
178 | [ -e "$t" ] ;; #(
179 | *) false ;;
180 | esac
181 | then
182 | arg=$( cygpath --path --ignore --mixed "$arg" )
183 | fi
184 | # Roll the args list around exactly as many times as the number of
185 | # args, so each arg winds up back in the position where it started, but
186 | # possibly modified.
187 | #
188 | # NB: a `for` loop captures its iteration list before it begins, so
189 | # changing the positional parameters here affects neither the number of
190 | # iterations, nor the values presented in `arg`.
191 | shift # remove old arg
192 | set -- "$@" "$arg" # push replacement arg
193 | done
194 | fi
195 |
196 | # Collect all arguments for the java command;
197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
198 | # shell script including quotes and variable substitutions, so put them in
199 | # double quotes to make sure that they get re-expanded; and
200 | # * put everything else in single quotes, so that it's not re-expanded.
201 |
202 | set -- \
203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
204 | -classpath "$CLASSPATH" \
205 | org.gradle.wrapper.GradleWrapperMain \
206 | "$@"
207 |
208 | # Use "xargs" to parse quoted args.
209 | #
210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
211 | #
212 | # In Bash we could simply go:
213 | #
214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
215 | # set -- "${ARGS[@]}" "$@"
216 | #
217 | # but POSIX shell has neither arrays nor command substitution, so instead we
218 | # post-process each arg (as a line of input to sed) to backslash-escape any
219 | # character that might be a shell metacharacter, then use eval to reverse
220 | # that process (while maintaining the separation between arguments), and wrap
221 | # the whole thing up as a single "set" statement.
222 | #
223 | # This will of course break if any of these variables contains a newline or
224 | # an unmatched quote.
225 | #
226 |
227 | eval "set -- $(
228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
229 | xargs -n1 |
230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
231 | tr '\n' ' '
232 | )" '"$@"'
233 |
234 | exec "$JAVACMD" "$@"
235 |
--------------------------------------------------------------------------------
/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 |
17 | @if "%DEBUG%" == "" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%" == "" set DIRNAME=.
29 | set APP_BASE_NAME=%~n0
30 | set APP_HOME=%DIRNAME%
31 |
32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
34 |
35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
37 |
38 | @rem Find java.exe
39 | if defined JAVA_HOME goto findJavaFromJavaHome
40 |
41 | set JAVA_EXE=java.exe
42 | %JAVA_EXE% -version >NUL 2>&1
43 | if "%ERRORLEVEL%" == "0" goto execute
44 |
45 | echo.
46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
47 | echo.
48 | echo Please set the JAVA_HOME variable in your environment to match the
49 | echo location of your Java installation.
50 |
51 | goto fail
52 |
53 | :findJavaFromJavaHome
54 | set JAVA_HOME=%JAVA_HOME:"=%
55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
56 |
57 | if exist "%JAVA_EXE%" goto execute
58 |
59 | echo.
60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
61 | echo.
62 | echo Please set the JAVA_HOME variable in your environment to match the
63 | echo location of your Java installation.
64 |
65 | goto fail
66 |
67 | :execute
68 | @rem Setup the command line
69 |
70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
71 |
72 |
73 | @rem Execute Gradle
74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
75 |
76 | :end
77 | @rem End local scope for the variables with windows NT shell
78 | if "%ERRORLEVEL%"=="0" goto mainEnd
79 |
80 | :fail
81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
82 | rem the _cmd.exe /c_ return code!
83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
84 | exit /b 1
85 |
86 | :mainEnd
87 | if "%OS%"=="Windows_NT" endlocal
88 |
89 | :omega
90 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (C) 2023 The Android Open Source Project
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | include ':checks', ':app'
17 |
--------------------------------------------------------------------------------