-
Notifications
You must be signed in to change notification settings - Fork 421
Add permission security snippets and region tags #1074
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
strzyzkat
wants to merge
3
commits into
main
Choose a base branch
from
strzyzkat/permissions-security-snippets
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
95 changes: 95 additions & 0 deletions
95
security/src/main/java/com/example/snippets/security/permissions/CallerVerifier.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,95 @@ | ||
| /* | ||
| * Copyright 2026 The Android Open Source Project | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package com.example.snippets.security.permissions | ||
|
|
||
| import android.content.Context | ||
| import android.content.pm.PackageManager | ||
| import android.os.Binder | ||
| import android.os.Build | ||
|
|
||
| // [START android_security_caller_verifier] | ||
| // [START android_security_caller_signature_verification] | ||
| object CallerVerifier { | ||
| private const val TRUSTED_PARTNER_SHA256 = | ||
| "A1B2C3D4E5F60708090A0B0C0D0E0F1011121314151617181920212223242526" | ||
|
|
||
| fun isCallerAuthorized(context: Context): Boolean { | ||
| val callingUid = Binder.getCallingUid() | ||
| if (callingUid == android.os.Process.myUid()) return true | ||
|
|
||
| val pm = context.packageManager | ||
| // Modern API 28+ check by UID: | ||
| if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { | ||
| val certBytes = hexStringToByteArray(TRUSTED_PARTNER_SHA256) | ||
| if (pm.hasSigningCertificate(callingUid, certBytes, PackageManager.CERT_INPUT_SHA256)) { | ||
| return true | ||
| } | ||
| } | ||
|
|
||
| // Fallback for legacy APIs: | ||
| val callingPackages = pm.getPackagesForUid(callingUid) ?: return false | ||
| for (pkg in callingPackages) { | ||
| if (verifyPackageSignature(pm, pkg)) { | ||
| return true | ||
| } | ||
| } | ||
| return false | ||
| } | ||
|
|
||
| @Suppress("DEPRECATION") | ||
| private fun verifyPackageSignature(pm: PackageManager, packageName: String): Boolean { | ||
| return try { | ||
| val packageInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES) | ||
| val signatures = packageInfo.signatures ?: return false | ||
| for (sig in signatures) { | ||
| val digest = java.security.MessageDigest.getInstance("SHA-256").digest(sig.toByteArray()) | ||
| val hex = digest.joinToString("") { "%02X".format(it) } | ||
| if (hex.equals(TRUSTED_PARTNER_SHA256, ignoreCase = true)) return true | ||
| } | ||
| false | ||
| } catch (e: PackageManager.NameNotFoundException) { | ||
| false | ||
| } | ||
| } | ||
|
|
||
| private fun hexStringToByteArray(s: String): ByteArray { | ||
| val len = s.length | ||
| val data = ByteArray(len / 2) | ||
| for (i in 0 until len step 2) { | ||
| data[i / 2] = ((Character.digit(s[i], 16) shl 4) + Character.digit(s[i + 1], 16)).toByte() | ||
| } | ||
| return data | ||
| } | ||
| } | ||
| // [END android_security_caller_signature_verification] | ||
| // [END android_security_caller_verifier] | ||
|
|
||
| // Placeholder helper for compilation of vulnerable anti-pattern snippet | ||
| object SignatureUtils { | ||
| fun verifyPartnerPackage(context: Context, packageName: String): Boolean = true | ||
| } | ||
|
|
||
| fun Context.vulnerableCallerCheck(intent: android.content.Intent?) { | ||
| // [START android_security_caller_spoofing_vulnerable] | ||
| // VULNERABLE PATTERN: DO NOT DO THIS | ||
| val callingPackage = intent?.getStringExtra("calling_package") | ||
| if (callingPackage != null && SignatureUtils.verifyPartnerPackage(this, callingPackage)) { | ||
| // A malicious app passes "com.example.partner" in the extra. | ||
| // The signature check verifies the installed partner on disk, but the CALLER was malicious! | ||
| } | ||
| // [END android_security_caller_spoofing_vulnerable] | ||
| } |
62 changes: 62 additions & 0 deletions
62
security/src/main/java/com/example/snippets/security/permissions/FineGrainedBoundService.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| /* | ||
| * Copyright 2026 The Android Open Source Project | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package com.example.snippets.security.permissions | ||
|
|
||
| import android.app.Service | ||
| import android.content.Intent | ||
| import android.os.Binder | ||
| import android.os.IBinder | ||
| import android.util.Log | ||
|
|
||
| // Stub interface representing AIDL generated interface | ||
| interface IMyService { | ||
| fun getData(): String | ||
| fun modifyData(newData: String) | ||
|
|
||
| abstract class Stub : Binder(), IMyService | ||
| } | ||
|
|
||
| // [START android_security_service_enforce_calling_permission] | ||
| class SecureBoundService : Service() { | ||
|
|
||
| private val binder = object : IMyService.Stub() { | ||
| override fun getData(): String { | ||
| // Read-only operation guarded by manifest-level permission | ||
| return "Confidential Data" | ||
| } | ||
|
|
||
| override fun modifyData(newData: String) { | ||
| // MUST use enforceCallingPermission or checkCallingPermission. | ||
| // NEVER use checkCallingOrSelfPermission or enforceCallingOrSelfPermission. | ||
| this@SecureBoundService.enforceCallingPermission( | ||
| "com.example.snippets.permission.WRITE_DATA", | ||
| "Caller lacks WRITE_DATA permission" | ||
| ) | ||
| updateInternalState(newData) | ||
| Log.d("SecureBoundService", "Data modified to: $newData with proper WRITE_DATA permission check") | ||
| } | ||
| } | ||
|
|
||
| override fun onBind(intent: Intent?): IBinder = binder | ||
|
|
||
| private fun updateInternalState(data: String) { | ||
| // Internal state update logic | ||
| } | ||
| } | ||
| // [END android_security_service_enforce_calling_permission] | ||
|
|
||
| typealias FineGrainedBoundService = SecureBoundService | ||
64 changes: 64 additions & 0 deletions
64
...ity/src/main/java/com/example/snippets/security/permissions/LocationPermissionSnippets.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| /* | ||
| * Copyright 2026 The Android Open Source Project | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package com.example.snippets.security.permissions | ||
|
|
||
| import android.Manifest | ||
| import androidx.activity.ComponentActivity | ||
| import androidx.activity.result.contract.ActivityResultContracts | ||
|
|
||
| class LocationPermissionActivity : ComponentActivity() { | ||
|
|
||
| // [START android_security_sequential_location_permission] | ||
| private val foregroundLocationLauncher = | ||
| registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions -> | ||
| val fineGranted = permissions[Manifest.permission.ACCESS_FINE_LOCATION] ?: false | ||
| val coarseGranted = permissions[Manifest.permission.ACCESS_COARSE_LOCATION] ?: false | ||
| if (fineGranted || coarseGranted) { | ||
| startForegroundLocationUpdates() | ||
| } | ||
| } | ||
|
|
||
| fun requestForegroundLocation() { | ||
| foregroundLocationLauncher.launch( | ||
| arrayOf( | ||
| Manifest.permission.ACCESS_FINE_LOCATION, | ||
| Manifest.permission.ACCESS_COARSE_LOCATION | ||
| ) | ||
| ) | ||
| } | ||
|
|
||
| // Background location requested only AFTER foreground is granted and user explicitly opts in: | ||
| private val backgroundLocationLauncher = | ||
| registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted -> | ||
| if (isGranted) { | ||
| startBackgroundTracking() | ||
| } | ||
| } | ||
| // [END android_security_sequential_location_permission] | ||
|
|
||
| fun requestBackgroundLocation() { | ||
| backgroundLocationLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION) | ||
| } | ||
|
|
||
| private fun startForegroundLocationUpdates() { | ||
| // Start foreground location updates | ||
| } | ||
|
|
||
| private fun startBackgroundTracking() { | ||
| // Start background location updates | ||
| } | ||
| } |
44 changes: 44 additions & 0 deletions
44
security/src/main/java/com/example/snippets/security/permissions/MediaPickerSnippets.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| /* | ||
| * Copyright 2026 The Android Open Source Project | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| package com.example.snippets.security.permissions | ||
|
|
||
| import android.net.Uri | ||
| import androidx.activity.ComponentActivity | ||
| import androidx.activity.result.PickVisualMediaRequest | ||
| import androidx.activity.result.contract.ActivityResultContracts | ||
|
|
||
| class MediaPickerActivity : ComponentActivity() { | ||
|
|
||
| // [START android_security_photo_picker_request] | ||
| private val photoPickerLauncher = | ||
| registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> | ||
| if (uri != null) { | ||
| handleImageUri(uri) | ||
| } | ||
| } | ||
|
|
||
| fun selectPhoto() { | ||
| photoPickerLauncher.launch( | ||
| PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) | ||
| ) | ||
| } | ||
| // [END android_security_photo_picker_request] | ||
|
|
||
| private fun handleImageUri(uri: Uri) { | ||
| // Direct URI access without requesting storage permissions | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nit: if you rename the file
SecureBoundService.ktyou wouldn't need this alias