Anti-AIClone

Log date · Mon

Do Android keep rules affect security?

Published on · Updated

Yes. Broad rules can preserve unnecessary names and code: our sample kept three original class names versus one with a narrow rule.

Do keep rules affect security?

Yes. Keep rules constrain what R8 can remove or rename. An overly broad rule can leave unnecessary class and method names in a release. In our Java sample, keeping the whole package preserved all three original class names. Keeping only the entry point retained one original name, renamed one class and removed one unused class. Both programs printed total=90.

Those names can help someone understand code, but their count is not a security score. R8 primarily optimizes and shrinks code; narrowing a rule does not make client code or secrets inaccessible.

Measured results and interpretation
QuestionFinding
What did the broad rule retain?Three original class names, including unused Unused.
What changed with the narrow rule?Main stayed, Pricing was renamed, and Unused was removed.
Did behavior match?Both printed total=90 for the tested input.
Does this protect a secret?No; do not ship shared secrets in the client.

Sample and controls

We wrote three classes: Main calls Pricing.calculateTotal(100); Pricing also contains an uncalled method; Unused has no references. We compiled and ran them with OpenJDK 17.0.19 and R8 8.3.37. Both variants use -dontoptimize to isolate shrinking and naming. This is a Java classfile experiment, not an Android DEX, reflection test or a complete production app build.

The pricing class in our sample; a separate Unused class has no callers.
package demo;
public class Pricing {
  public static int calculateTotal(int amount) { return amount * 9 / 10; }
  public static int unusedDiscount(int amount) { return amount / 2; }
}

Keeping the input, tools and output format fixed while changing only the rule makes the difference easier to interpret. Passing one input proves that path only; it is not a substitute for an application regression suite.

Two rules and their results

The broad rule matches classes in demo and its subpackages and keeps their members. The narrow rule preserves Main and its main method, leaving other code eligible for removal or renaming. It works for this directly called sample; it is not a replacement for the entry rules in an Android project.

Broad rule: keep the whole package.
-dontoptimize
-keep class demo.** { *; }
Narrow rule: keep only the sample entry point.
-dontoptimize
-keep class demo.Main { public static void main(java.lang.String[]); }
Broad output files, copied from the transcript.
== broad ==
-- output class files --
demo/Main.class
demo/Pricing.class
demo/Unused.class
Narrow output files, copied from the transcript.
== narrow ==
-- output class files --
a/a.class
demo/Main.class

The narrow mapping maps demo.Pricing to a.a and calculateTotal to a; Unused is absent from the output file list. All three classes retain their original names under the broad rule. Our original-name count uses output class paths, excludes methods, and does not count names in the mapping file as names in the app.

This illustrates the difference between code surviving and its name surviving. Pricing is still needed for the calculation but has a new name; Unused is unreachable from this entry point and is removed under the narrow rule. Matching output for this run does not establish equivalent behavior for every input or feature.

Why some names must stay

R8 can analyze direct calls, but may not see indirect uses made through strings. Android documents reflection and JNI as examples: removing or renaming a class, field or method looked up by name can make the lookup fail at runtime. [1] Find the actual dynamic entry point and members before deciding what to preserve.

The rule options are not interchangeable. Android documents that -keep preserves matched classes and specified members, whereas -keepclassmembers preserves the specified members only if their class survives. allowobfuscation permits renaming and allowshrinking permits removal. [2] Choose according to the runtime contract, not the option name alone.

For example, when reflection constructs an object by its full class name, both the class name and the required constructor are part of the contract. Keeping members alone does not guarantee the class exists. Check serialization, plugin registration and native interfaces independently rather than assuming every library uses the same contract.

Recommendations by case

These are engineering recommendations, not security effects measured by our sample. Whenever you narrow a rule, verify both behavior and the release artifact.

Recommendations: start from the dependency
CaseRecommendation
Directly called internal codeFirst check whether a custom keep rule is needed at all.
Reflection loads by nameKeep only required classes, names and members; test lookup failures too.
A library contributes a broad ruleInspect merged configuration and library guidance; upgrade or ask its maintainer about a narrower rule.
Client contains a shared privileged secretMove it to a controlled server and rotate any already shipped key.

A smaller rule may permit more optimization, but may uncover a hidden compatibility dependency. Record the reason, owner and test covering the dynamic path next to each rule. Revisit it after library upgrades because both usage and supplied rules can change. Do not remove a necessary rule merely to increase the number of renamed items.

Distinguish build diagnostics from the artifact delivered to users. A mapping helps the team diagnose problems and normally associates original names with new ones, so restrict access and associate it with the correct release. Review the actual release artifact and its configuration instead of inferring the final result from a single rule in source. An unexplained preserved class is a prompt to investigate the effective configuration and dependency path, not proof that the class is sensitive.

Check your own release build

In your own project, build the release variant and run functional tests first, then inspect the merged R8 configuration. Android notes that rules can come from the app and its libraries, and recommends -whyareyoukeeping to explain retention paths. [3] Adjust the module and variant paths below; use the configuration.txt actually produced by your build.

Run from the project root; adjust paths and task names for your project.
./gradlew :app:assembleRelease
find app/build/outputs/mapping -name configuration.txt -print
find app/build/outputs/mapping -name mapping.txt -print

When looking for package-wide patterns and global options, record where each rule came from, then review it alongside tests for reflection, JNI, serialization and plugins. Keep a known-good baseline. Change one related set of rules at a time, compare artifacts and exercise affected features on devices, including error handling and upgrade paths.

Save the mapping file for each release so you can interpret crash traces; Android warns that later builds overwrite it. [3] Manage it as an internal build artifact. Counting surviving names helps find unexpectedly broad rules, but does not prove logic is confidential or replace credential inventory and permission design.

When comparing results, also hold the build variant, dependency versions and default rules constant. Otherwise a missing class could be the result of a dependency upgrade or another configuration change rather than the rule just edited. Save the configuration and artifact for each variant and record the differences. If a feature regresses, restore the baseline and narrow the investigation around the failing entry point. Do not check only the launch screen: dynamic loading may occur in sign-in, payment, error recovery or a rarely used settings screen.

Your checklist

  • Inspect merged R8 rules and their sources in the release build.
  • Document names and members required by reflection, JNI and other dynamic entry points.
  • Narrow rules incrementally and test affected features on devices.
  • Compare release artifacts and retain the mapping file for each release.
  • Remove shared privileged secrets from the client and rotate shipped values.

Primary sources

All sources and reproduction status ↗