├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── README.md ├── .github └── workflows │ ├── gradle.yml │ └── release.yml ├── src └── main │ ├── java │ ├── DefinitionsAnalysis.java │ ├── Rule.java │ ├── ValueSet.java │ ├── PrivacyDetectionTransformer.java │ └── PrivacyDog.java │ └── resources │ └── privacydog.json ├── gradlew.bat ├── gradlew └── LICENSE /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hluwa/PrivacyDog/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PrivacyDog 2 | 3 | 基于 Soot 框架的 Android 隐私问题静态代码扫描器 4 | 5 | ## 使用方法 6 | 7 | ``` 8 | PrivacyDog 9 | -t 输入文件/目录 10 | -r [可选] 规则文件地址, 默认使用内置规则 11 | -o [可选] JSON 输出目录, 默认仅输出 stdout 12 | ``` 13 | 14 | ## 扫描规则 15 | 16 | 可参考 [privacydog.json](src/main/resources/privacydog.json) 17 | 18 | 除了 `stringPattern` 是对所有指令进行匹配,其他均为对函数调用的匹配。 19 | 20 | 支持对调用参数具体值的匹配,比如匹配第一个参数为 `android_id` 的 `Settings.Secure.getString`: 21 | 22 | ``` 23 | { 24 | "className": "android.provider.Settings$Secure", 25 | "methodName": "getString", 26 | "arguments": { 27 | "1": "android_id" 28 | } 29 | } 30 | ``` 31 | 32 | 采用的是成本较低的过程内分析。 33 | -------------------------------------------------------------------------------- /.github/workflows/gradle.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Java project with Gradle 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-gradle 3 | 4 | name: Java CI with Gradle 5 | 6 | on: 7 | push: 8 | branches: [ master ] 9 | pull_request: 10 | branches: [ master ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Set up JDK 1.8 20 | uses: actions/setup-java@v1 21 | with: 22 | java-version: 1.8 23 | - name: Grant execute permission for gradlew 24 | run: chmod +x gradlew 25 | - name: Build with Gradle 26 | run: ./gradlew build 27 | -------------------------------------------------------------------------------- /src/main/java/DefinitionsAnalysis.java: -------------------------------------------------------------------------------- 1 | import soot.Unit; 2 | import soot.Value; 3 | import soot.jimple.DefinitionStmt; 4 | import soot.toolkits.graph.DirectedGraph; 5 | import soot.toolkits.scalar.ForwardFlowAnalysis; 6 | import soot.toolkits.scalar.Pair; 7 | 8 | import java.util.ArrayList; 9 | import java.util.HashMap; 10 | import java.util.List; 11 | 12 | public class DefinitionsAnalysis extends ForwardFlowAnalysis { 13 | 14 | 15 | ValueSet emptySet = new ValueSet(); 16 | 17 | 18 | /** 19 | * Construct the analysis from a DirectedGraph representation of a Body. 20 | * 21 | * @param graph 22 | */ 23 | public DefinitionsAnalysis(DirectedGraph graph) { 24 | super(graph); 25 | 26 | doAnalysis(); 27 | } 28 | 29 | @Override 30 | protected void flowThrough(ValueSet in, Unit d, ValueSet out) { 31 | in.copy(out); 32 | if (d instanceof DefinitionStmt) { 33 | DefinitionStmt defStmt = (DefinitionStmt) d; 34 | Value leftOp = defStmt.getLeftOp(); 35 | AbstractValue value = new AbstractValue(leftOp); 36 | value.values.add(new Pair<>(defStmt.getRightOp(), d)); 37 | if (out.contains(value)) { 38 | out.varToValues.remove(value.o); 39 | } 40 | out.add(value); 41 | 42 | } 43 | } 44 | 45 | public List> solveOf(Unit location, Object o) { 46 | return solveOf(location, o, false); 47 | } 48 | 49 | 50 | public List> solveOf(Unit location, Object o, boolean before) { 51 | ValueSet vs = before ? this.getFlowBefore(location) : this.getFlowAfter(location); 52 | if (vs.varToValues.containsKey(o)) { 53 | return vs.varToValues.get(o).values; 54 | } 55 | return new ArrayList<>(); 56 | } 57 | 58 | @Override 59 | protected ValueSet newInitialFlow() { 60 | return emptySet.clone(); 61 | } 62 | 63 | @Override 64 | protected void merge(ValueSet in1, ValueSet in2, ValueSet out) { 65 | in1.union(in2, out); 66 | } 67 | 68 | @Override 69 | protected void copy(ValueSet source, ValueSet dest) { 70 | dest.varToValues = new HashMap<>(); 71 | for (Object var : source.varToValues.keySet()) { 72 | dest.varToValues.put(var, source.varToValues.get(var).clone()); 73 | } 74 | } 75 | } 76 | 77 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Automation Upload Release 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | build: 9 | 10 | runs-on: ubuntu-latest 11 | 12 | steps: 13 | 14 | - uses: actions/checkout@v2 15 | - name: Set up JDK 1.8 16 | uses: actions/setup-java@v1 17 | with: 18 | java-version: 1.8 19 | 20 | - name: Grant execute permission for gradlew 21 | run: chmod +x gradlew 22 | 23 | - name: Build with Gradle 24 | run: ./gradlew build 25 | 26 | - name: Assemble distributions 27 | run: ./gradlew assembleDist 28 | 29 | - name: Get the version 30 | id: getVersion 31 | if: startsWith(github.ref, 'refs/tags/') 32 | run: echo ::set-output name=VERSION::${GITHUB_REF/refs\/tags\//} 33 | 34 | - name: Get Release Upload Url 35 | id: getReleaseUploadUrl 36 | uses: actions/github-script@v3.1.0 37 | with: 38 | github-token: ${{secrets.GITHUB_TOKEN}} 39 | script: | 40 | try { 41 | const releaseResponse = await github.repos.getReleaseByTag({ 42 | owner: '${{ github.repository_owner }}', 43 | repo: '${{ github.event.repository.name }}', 44 | tag: '${{ steps.getVersion.outputs.VERSION }}' 45 | }) 46 | const { 47 | data: { upload_url: uploadUrl } 48 | } = releaseResponse; 49 | core.setOutput('upload_url', uploadUrl); 50 | } catch (e) { 51 | core.setFailed(e.message); 52 | } 53 | 54 | - name: Upload Tar Release 55 | uses: actions/upload-release-asset@v1.0.2 56 | env: 57 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 58 | with: 59 | upload_url: '${{ steps.getReleaseUploadUrl.outputs.upload_url }}' 60 | asset_path: '${{ github.workspace }}/build/distributions/PrivacyDog.tar' 61 | asset_name: 'PrivacyDog-${{ steps.getVersion.outputs.VERSION }}-RELEASE.tar' 62 | asset_content_type: application/octet-stream 63 | 64 | 65 | - name: Upload Zip Release 66 | uses: actions/upload-release-asset@v1.0.2 67 | env: 68 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 69 | with: 70 | upload_url: '${{ steps.getReleaseUploadUrl.outputs.upload_url }}' 71 | asset_path: '${{ github.workspace }}/build/distributions/PrivacyDog.zip' 72 | asset_name: 'PrivacyDog-${{ steps.getVersion.outputs.VERSION }}-RELEASE.zip' 73 | asset_content_type: application/octet-stream 74 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /src/main/java/Rule.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.Map; 3 | 4 | public class Rule { 5 | private String name; 6 | private List conditions; 7 | 8 | public Rule() { 9 | } 10 | 11 | @Override 12 | public String toString() { 13 | return "Rule{" + 14 | "name='" + name + '\'' + 15 | ", conditions=" + conditions + 16 | '}'; 17 | } 18 | 19 | public String getName() { 20 | return name; 21 | } 22 | 23 | public void setName(String name) { 24 | this.name = name; 25 | } 26 | 27 | public List getConditions() { 28 | return conditions; 29 | } 30 | 31 | public void setConditions(List conditions) { 32 | this.conditions = conditions; 33 | } 34 | } 35 | 36 | 37 | class Condition { 38 | private String className; 39 | private String methodName; 40 | private String classPattern; 41 | private String methodPattern; 42 | private String stringPattern; 43 | private int paramsCount = -1; 44 | private Map arguments; 45 | 46 | public String getClassPattern() { 47 | return classPattern; 48 | } 49 | 50 | public void setClassPattern(String classPattern) { 51 | this.classPattern = classPattern; 52 | } 53 | 54 | public String getMethodPattern() { 55 | return methodPattern; 56 | } 57 | 58 | public void setMethodPattern(String methodPattern) { 59 | this.methodPattern = methodPattern; 60 | } 61 | 62 | public String getClassName() { 63 | return className; 64 | } 65 | 66 | public void setClassName(String className) { 67 | this.className = className; 68 | } 69 | 70 | public String getMethodName() { 71 | return methodName; 72 | } 73 | 74 | public void setMethodName(String methodName) { 75 | this.methodName = methodName; 76 | } 77 | 78 | public Map getArguments() { 79 | return arguments; 80 | } 81 | 82 | public void setArguments(Map arguments) { 83 | this.arguments = arguments; 84 | } 85 | 86 | public int getParamsCount() { 87 | return paramsCount; 88 | } 89 | 90 | public void setParamsCount(int paramsCount) { 91 | this.paramsCount = paramsCount; 92 | } 93 | 94 | public String getStringPattern() { 95 | return stringPattern; 96 | } 97 | 98 | public void setStringPattern(String stringPattern) { 99 | this.stringPattern = stringPattern; 100 | } 101 | 102 | 103 | public boolean isInvokeCondition() { 104 | return !conditionEmpty(className) || !conditionEmpty(classPattern) 105 | || !conditionEmpty(methodName) || !conditionEmpty(methodPattern) 106 | || !conditionEmpty(paramsCount) || !conditionEmpty(arguments); 107 | } 108 | 109 | private boolean conditionEmpty(String key) { 110 | return key == null || key.isEmpty(); 111 | } 112 | 113 | private boolean conditionEmpty(int key) { 114 | return key == -1; 115 | } 116 | 117 | 118 | private boolean conditionEmpty(Map key) { 119 | return key == null || key.size() == 0; 120 | } 121 | 122 | @Override 123 | public String toString() { 124 | return "Condition{" + 125 | "className='" + className + '\'' + 126 | ", methodName='" + methodName + '\'' + 127 | ", classPattern='" + classPattern + '\'' + 128 | ", methodPattern='" + methodPattern + '\'' + 129 | ", stringPattern='" + stringPattern + '\'' + 130 | ", paramsCount=" + paramsCount + 131 | ", arguments=" + arguments + 132 | '}'; 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /src/main/java/ValueSet.java: -------------------------------------------------------------------------------- 1 | import soot.Unit; 2 | import soot.toolkits.scalar.AbstractFlowSet; 3 | import soot.toolkits.scalar.Pair; 4 | 5 | import java.util.*; 6 | 7 | class AbstractValue { 8 | Object o; 9 | List> values = new ArrayList<>(); 10 | Map conditions = new TreeMap<>(); 11 | 12 | public AbstractValue() { 13 | } 14 | 15 | public AbstractValue(Object obj) { 16 | this.o = obj; 17 | } 18 | 19 | @Override 20 | public AbstractValue clone() { 21 | AbstractValue res = new AbstractValue(this.o); 22 | res.values = new ArrayList<>(values); 23 | res.conditions = new TreeMap<>(this.conditions); 24 | return res; 25 | } 26 | 27 | @Override 28 | public boolean equals(Object o) { 29 | return o != null && hashCode() == o.hashCode(); 30 | } 31 | 32 | @Override 33 | public int hashCode() { 34 | return Objects.hash(Arrays.hashCode(values.toArray()), Arrays.hashCode(conditions.values().toArray()), this.o); 35 | } 36 | } 37 | 38 | public class ValueSet extends AbstractFlowSet { 39 | 40 | public Map varToValues = new HashMap<>(); 41 | 42 | 43 | public ValueSet() { 44 | } 45 | 46 | @Override 47 | public ValueSet clone() { 48 | ValueSet res = new ValueSet(); 49 | res.varToValues = new HashMap<>(); 50 | for (Object var : this.varToValues.keySet()) { 51 | res.varToValues.put(var, this.varToValues.get(var).clone()); 52 | } 53 | return res; 54 | } 55 | 56 | @Override 57 | public boolean isEmpty() { 58 | return this.varToValues.isEmpty(); 59 | } 60 | 61 | @Override 62 | public int size() { 63 | return this.varToValues.size(); 64 | } 65 | 66 | @Override 67 | public void add(AbstractValue obj) { 68 | if (contains(obj)) { 69 | AbstractValue dest = this.varToValues.get(obj.o); 70 | for (Pair value : obj.values) { 71 | if (!dest.values.contains(value)) { 72 | dest.values.add(value); 73 | } 74 | } 75 | } else { 76 | this.varToValues.put(obj.o, obj); 77 | } 78 | } 79 | 80 | @Override 81 | public void remove(AbstractValue obj) { 82 | if (contains(obj)) { 83 | AbstractValue dest = this.varToValues.get(obj.o); 84 | for (Pair value : obj.values) { 85 | if (!dest.values.contains(value)) { 86 | dest.values.remove(value); 87 | } 88 | } 89 | if (dest.values.isEmpty()) { 90 | this.varToValues.remove(obj.o); 91 | } 92 | } 93 | } 94 | 95 | 96 | public void intersection(ValueSet other, ValueSet dest) { 97 | for (AbstractValue obj : this) { 98 | if (other.contains(obj)) { 99 | List> destValues = new ArrayList<>(); 100 | List> values1 = other.varToValues.get(obj.o).values; 101 | List> values2 = this.varToValues.get(obj.o).values; 102 | for (Pair value : values1) { 103 | if (values2.contains(value)) { 104 | destValues.add(value); 105 | } 106 | } 107 | 108 | if (!destValues.isEmpty()) { 109 | AbstractValue n = new AbstractValue(); 110 | n.o = obj.o; 111 | n.values = destValues; 112 | dest.add(n); 113 | } 114 | } 115 | } 116 | } 117 | 118 | @Override 119 | public boolean contains(AbstractValue obj) { 120 | for (Object o : this.varToValues.keySet()) { 121 | if (o.equals(obj.o)) { 122 | return true; 123 | } 124 | } 125 | return false; 126 | } 127 | 128 | @Override 129 | public Iterator iterator() { 130 | return this.varToValues.values().iterator(); 131 | } 132 | 133 | @Override 134 | public List toList() { 135 | return (List) this.varToValues.values(); 136 | } 137 | } 138 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or 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 UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /src/main/resources/privacydog.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "IMEI", 4 | "conditions": [ 5 | { 6 | "className": "android.telephony.TelephonyManager", 7 | "methodPattern": "getDeviceId" 8 | }, 9 | { 10 | "methodPattern": "getimei" 11 | } 12 | ] 13 | }, 14 | { 15 | "name": "IMSI", 16 | "conditions": [ 17 | { 18 | "className": "android.telephony.TelephonyManager", 19 | "methodPattern": "getSubscriberId" 20 | }, 21 | { 22 | "methodPattern": "getimsi" 23 | } 24 | ] 25 | }, 26 | { 27 | "name": "Sim SerialNumber(ICCID)", 28 | "conditions": [ 29 | { 30 | "className": "android.telephony.TelephonyManager", 31 | "methodName": "getSimSerialNumber" 32 | } 33 | ] 34 | }, 35 | { 36 | "name": "Mac Address", 37 | "conditions": [ 38 | { 39 | "stringPattern": "/sys/class/net/\\S+/address" 40 | }, 41 | { 42 | "className": "java.net.NetworkInterface", 43 | "methodName": "getHardwareAddress" 44 | }, 45 | { 46 | "className": "android.net.wifi.WifiInfo", 47 | "methodName": "getMacAddress" 48 | } 49 | ] 50 | }, 51 | { 52 | "name": "AndroidID", 53 | "conditions": [ 54 | { 55 | "className": "android.provider.Settings$Secure", 56 | "methodName": "getString", 57 | "arguments": { 58 | "1": "android_id" 59 | } 60 | } 61 | ] 62 | }, 63 | { 64 | "name": "SerialNo", 65 | "conditions": [ 66 | { 67 | "stringPattern": "" 68 | }, 69 | { 70 | "stringPattern": "ro.\\S*serialno" 71 | } 72 | ] 73 | }, 74 | { 75 | "name": "Phone Number", 76 | "conditions": [ 77 | { 78 | "className": "android.telephony.TelephonyManager", 79 | "methodPattern": "getLine.?Number" 80 | }, 81 | { 82 | "methodPattern": "getphonenumber" 83 | } 84 | ] 85 | }, 86 | { 87 | "name": "WiFi Info", 88 | "conditions": [ 89 | { 90 | "className": "android.net.wifi.WifiInfo", 91 | "methodPattern": "getMacAddress|getBSSID|getIpAddress|getSSID" 92 | }, 93 | { 94 | "className": "android.net.wifi.WifiManager", 95 | "methodPattern": "getScanResults|getConnectionInfo" 96 | } 97 | ] 98 | }, 99 | { 100 | "name": "Location Info", 101 | "conditions": [ 102 | { 103 | "className": "android.location.Location", 104 | "methodPattern": "getLatitude|getLongitude" 105 | }, 106 | { 107 | "className": "android.location.LocationManager", 108 | "methodPattern": "getLastKnownLocation|requestLocationUpdates|getLastLocation|getCellLocation" 109 | } 110 | ] 111 | }, 112 | { 113 | "name": "Sensor Data", 114 | "conditions": [ 115 | { 116 | "className": "android.hardware.SensorManager", 117 | "methodName": "registerListener" 118 | } 119 | ] 120 | }, 121 | { 122 | "name": "Package List", 123 | "conditions": [ 124 | { 125 | "className": "android.content.pm.PackageManager", 126 | "methodPattern": "getInstallerPackageName|getInstalledApplications|getInstalledModules|getInstalledPackages" 127 | }, 128 | { 129 | "className": "android.app.ApplicationPackageManager", 130 | "methodPattern": "getInstalledPackages" 131 | } 132 | ] 133 | }, 134 | { 135 | "name": "Device Admin", 136 | "conditions": [ 137 | { 138 | "stringPattern": "android.app.action.ADD_DEVICE_ADMIN" 139 | } 140 | ] 141 | }, 142 | { 143 | "name": "Media Record", 144 | "conditions": [ 145 | { 146 | "className": "android.media.MediaRecorder", 147 | "methodName": "start" 148 | }, 149 | { 150 | "className": "android.media.AudioRecord", 151 | "methodName": "start" 152 | } 153 | ] 154 | }, 155 | { 156 | "name": "Camera Access", 157 | "conditions": [ 158 | { 159 | "className": "android.hardware.Camera", 160 | "methodPattern": "open" 161 | } 162 | ] 163 | }, 164 | { 165 | "name": "SMS Send", 166 | "conditions": [ 167 | { 168 | "className": "android.telephony.SmsManager", 169 | "methodPattern": "send\\S*Message" 170 | } 171 | ] 172 | }, 173 | { 174 | "name": "SMS Access", 175 | "conditions": [ 176 | { 177 | "className": "android.content.ContentResolver", 178 | "methodPattern": "query", 179 | "arguments": { 180 | "0": "content://sms/" 181 | } 182 | }, 183 | { 184 | "className": "android.content.UriMatcher", 185 | "methodName": "addURI", 186 | "arguments": { 187 | "0": "sms" 188 | } 189 | }, 190 | { 191 | "stringPattern": "content://sms/" 192 | } 193 | ] 194 | }, 195 | { 196 | "name": "SMS Monitor", 197 | "conditions": [ 198 | { 199 | "className": "android.content.ContentResolver", 200 | "methodName": "registerContentObserver", 201 | "arguments": { 202 | "0": "content://sms" 203 | } 204 | } 205 | ] 206 | }, 207 | { 208 | "name": "Contacts Access", 209 | "conditions": [ 210 | { 211 | "className": "android.content.ContentResolver", 212 | "methodPattern": "query", 213 | "arguments": { 214 | "0": "content://com.android.contacts|" 215 | } 216 | }, 217 | { 218 | "className": "android.content.UriMatcher", 219 | "methodName": "addURI", 220 | "arguments": { 221 | "0": "com.android.contacts" 222 | } 223 | }, 224 | { 225 | "className": "android.provider.ContactsContract$Contacts" 226 | }, 227 | { 228 | "stringPattern": "content://com.android.contacts|" 229 | } 230 | ] 231 | }, 232 | { 233 | "name": "CallLog Access", 234 | "conditions": [ 235 | { 236 | "className": "android.content.ContentResolver", 237 | "methodPattern": "query", 238 | "arguments": { 239 | "0": "content://call_log|" 240 | } 241 | }, 242 | { 243 | "className": "android.content.UriMatcher", 244 | "methodName": "addURI", 245 | "arguments": { 246 | "0": "call_log" 247 | } 248 | }, 249 | { 250 | "stringPattern": "content://call_log|" 251 | } 252 | ] 253 | }, 254 | { 255 | "name": "Call Status Monitor", 256 | "conditions": [ 257 | { 258 | "className": "android.telephony.TelephonyManager", 259 | "methodName": "listen" 260 | } 261 | ] 262 | }, 263 | { 264 | "name": "Call Phone", 265 | "conditions": [ 266 | { 267 | "stringPattern": "android.intent.action.CALL" 268 | }, 269 | { 270 | "stringPattern": "" 271 | } 272 | ] 273 | } 274 | ] 275 | -------------------------------------------------------------------------------- /src/main/java/PrivacyDetectionTransformer.java: -------------------------------------------------------------------------------- 1 | import soot.Body; 2 | import soot.BodyTransformer; 3 | import soot.Unit; 4 | import soot.Value; 5 | import soot.jimple.*; 6 | import soot.toolkits.scalar.Pair; 7 | 8 | import java.util.ArrayList; 9 | import java.util.HashMap; 10 | import java.util.List; 11 | import java.util.Map; 12 | import java.util.regex.Matcher; 13 | import java.util.regex.Pattern; 14 | 15 | import static java.util.regex.Pattern.CASE_INSENSITIVE; 16 | import static soot.util.cfgcmd.CFGGraphType.EXCEPTIONAL_UNIT_GRAPH; 17 | 18 | public class PrivacyDetectionTransformer extends BodyTransformer { 19 | private Rule[] rules; 20 | private final List> result = new ArrayList<>(); 21 | private final Map> resultMap = new HashMap<>(); 22 | 23 | public PrivacyDetectionTransformer(Rule[] rules) { 24 | this.rules = rules; 25 | } 26 | 27 | @Override 28 | protected void internalTransform(Body b, String phaseName, Map options) { 29 | if (rules == null || rules.length == 0) { 30 | return; 31 | } 32 | DefinitionsAnalysis vsa = null; 33 | 34 | for (Unit unit : b.getUnits()) { 35 | if (unit == null) { 36 | continue; 37 | } 38 | StmtLocation stmtLocation = new StmtLocation((Stmt) unit, b); 39 | 40 | for (Rule rule : rules) { 41 | for (Condition condition : rule.getConditions()) { 42 | if (!verifyStringPattern((Stmt) unit, condition)) { 43 | continue; 44 | } 45 | if (condition.isInvokeCondition()) { 46 | if (!((Stmt) unit).containsInvokeExpr()) { 47 | continue; 48 | } 49 | InvokeExpr invokeExpr = ((Stmt) unit).getInvokeExpr(); 50 | if (!verifyClass(invokeExpr, condition) 51 | || !verifyMethod(invokeExpr, condition)) { 52 | continue; 53 | } 54 | if (vsa == null) { 55 | vsa = new DefinitionsAnalysis(EXCEPTIONAL_UNIT_GRAPH.buildGraph(b)); 56 | } 57 | if (!verifyArguments(invokeExpr, condition, (Stmt) unit, vsa)) { 58 | continue; 59 | } 60 | } 61 | 62 | result.add(new Pair<>(stmtLocation, rule)); 63 | if (!resultMap.containsKey(rule)) { 64 | resultMap.put(rule, new ArrayList<>()); 65 | } 66 | resultMap.get(rule).add(stmtLocation); 67 | break; 68 | } 69 | } 70 | } 71 | 72 | } 73 | 74 | private boolean verifyStringPattern(Stmt statement, Condition condition) { 75 | return condition.getStringPattern() == null || Pattern.compile(condition.getStringPattern()).matcher(statement.toString()).find(); 76 | } 77 | 78 | private boolean verifyClass(InvokeExpr invokeExpr, Condition condition) { 79 | String invokeClassName = invokeExpr.getMethod().getDeclaringClass().getName(); 80 | if (condition.getClassName() != null) { 81 | if (condition.getClassName().equals(invokeClassName)) { 82 | return true; 83 | } else if (condition.getClassPattern() == null) { 84 | return false; 85 | } 86 | } 87 | 88 | if (condition.getClassPattern() != null) { 89 | Pattern pattern = Pattern.compile(condition.getClassPattern(), CASE_INSENSITIVE); 90 | Matcher matcher = pattern.matcher(invokeClassName); 91 | return matcher.find(); 92 | } 93 | 94 | return true; 95 | } 96 | 97 | private boolean verifyMethod(InvokeExpr invokeExpr, Condition condition) { 98 | String invokeMethodName = invokeExpr.getMethod().getName(); 99 | if (condition.getMethodName() != null) { 100 | if (condition.getMethodName().equals(invokeMethodName)) { 101 | return true; 102 | } else if (condition.getMethodPattern() == null) { 103 | return false; 104 | } 105 | } 106 | 107 | if (condition.getMethodPattern() != null) { 108 | Pattern pattern = Pattern.compile(condition.getMethodPattern(), CASE_INSENSITIVE); 109 | Matcher matcher = pattern.matcher(invokeMethodName); 110 | return matcher.find(); 111 | } 112 | 113 | return true; 114 | } 115 | 116 | private boolean verifyArguments(InvokeExpr invokeExpr, Condition condition, Stmt stmt, DefinitionsAnalysis vsa) { 117 | if (condition.getParamsCount() != -1 && condition.getParamsCount() != invokeExpr.getArgCount()) { 118 | return false; 119 | } 120 | 121 | if (condition.getArguments() != null && condition.getArguments().size() != 0) { 122 | for (int argIndex : condition.getArguments().keySet()) { 123 | if (argIndex >= invokeExpr.getArgCount()) { 124 | return false; 125 | } 126 | boolean matches = false; 127 | Pattern pattern = Pattern.compile(condition.getArguments().get(argIndex)); 128 | 129 | Value value = invokeExpr.getArg(argIndex); 130 | if (value instanceof Constant) { 131 | Matcher matcher = pattern.matcher(value.toString()); 132 | if (matcher.find()) { 133 | continue; 134 | } 135 | } 136 | 137 | 138 | List> valuePairs = vsa.solveOf(stmt, value, true); 139 | 140 | for (Pair pair : valuePairs) { 141 | Object maybeValue = pair.getO1(); 142 | String maybeValueString; 143 | if (maybeValue instanceof StringConstant) { 144 | maybeValueString = ((StringConstant) maybeValue).value; 145 | } else if (maybeValue instanceof IntConstant) { 146 | maybeValueString = String.valueOf(((IntConstant) maybeValue).value); 147 | } else { 148 | maybeValueString = maybeValue.toString(); 149 | } 150 | 151 | Matcher matcher = pattern.matcher(maybeValueString); 152 | matches = matcher.find(); 153 | if (matches) { 154 | break; 155 | } 156 | } 157 | 158 | if (!matches) { 159 | return false; 160 | } 161 | } 162 | } 163 | 164 | return true; 165 | } 166 | 167 | public Rule[] getRules() { 168 | return rules; 169 | } 170 | 171 | public void setRules(Rule[] rules) { 172 | this.rules = rules; 173 | } 174 | 175 | public List> getResult() { 176 | return result; 177 | } 178 | 179 | public Map> getResultMap() { 180 | return resultMap; 181 | } 182 | 183 | } 184 | 185 | class StmtLocation { 186 | private Stmt stmt; 187 | private Body body; 188 | 189 | StmtLocation(Stmt stmt, Body body) { 190 | this.stmt = stmt; 191 | this.body = body; 192 | } 193 | 194 | public Stmt getStmt() { 195 | return stmt; 196 | } 197 | 198 | public void setStmt(Stmt stmt) { 199 | this.stmt = stmt; 200 | } 201 | 202 | public Body getBody() { 203 | return body; 204 | } 205 | 206 | public void setBody(Body body) { 207 | this.body = body; 208 | } 209 | 210 | public String getClassName() { 211 | try { 212 | return this.getBody().getMethod().getDeclaringClass().getName(); 213 | } catch (Exception e) { 214 | return ""; 215 | } 216 | } 217 | } 218 | -------------------------------------------------------------------------------- /src/main/java/PrivacyDog.java: -------------------------------------------------------------------------------- 1 | import com.google.gson.Gson; 2 | import com.google.gson.GsonBuilder; 3 | import net.lingala.zip4j.ZipFile; 4 | import org.apache.commons.cli.CommandLine; 5 | import org.apache.commons.cli.CommandLineParser; 6 | import org.apache.commons.cli.DefaultParser; 7 | import org.apache.commons.cli.ParseException; 8 | import soot.G; 9 | import soot.PackManager; 10 | import soot.Scene; 11 | import soot.Transform; 12 | import soot.options.Options; 13 | 14 | import java.io.*; 15 | import java.nio.file.Files; 16 | import java.nio.file.Path; 17 | import java.util.*; 18 | import java.util.logging.Logger; 19 | 20 | public class PrivacyDog { 21 | 22 | static String targetPath = ""; 23 | static String outputPath = null; 24 | static String ruleFilePath = "privacydog.json"; 25 | 26 | private static Rule[] rules; 27 | private static final Logger logger = Logger.getLogger("PrivacyDog"); 28 | 29 | private static void setupSoot(String taskPath) throws IOException { 30 | G.reset(); 31 | Options.v().set_wrong_staticness(Options.wrong_staticness_ignore); 32 | Options.v().set_allow_phantom_refs(true); 33 | Options.v().set_allow_phantom_elms(true); 34 | Options.v().set_ignore_resolving_levels(true); 35 | Options.v().set_ignore_resolution_errors(true); 36 | Options.v().set_no_bodies_for_excluded(true); 37 | Options.v().set_whole_program(false); 38 | Options.v().set_coffi(true); 39 | Options.v().set_throw_analysis(Options.throw_analysis_dalvik); 40 | Options.v().set_soot_classpath(Scene.defaultJavaClassPath()); 41 | Options.v().setPhaseOption("cg", "all-reachable:true"); 42 | Options.v().setPhaseOption("jb.dae", "enabled:false"); 43 | Options.v().setPhaseOption("jb.uce", "enabled:false"); 44 | Options.v().setPhaseOption("jj.dae", "enabled:false"); 45 | Options.v().setPhaseOption("jj.uce", "enabled:false"); 46 | Options.v().setPhaseOption("jtp.dae", "enabled:false"); 47 | Options.v().setPhaseOption("jtp.uce", "enabled:false"); 48 | if (taskPath.endsWith(".apk") || taskPath.endsWith(".dex")) { 49 | Options.v().set_src_prec(Options.src_prec_apk); 50 | Options.v().set_process_multiple_dex(true); 51 | } 52 | 53 | if (taskPath.endsWith(".aar")) { 54 | List processList = new ArrayList<>(); 55 | ZipFile zipFile = new ZipFile(taskPath); 56 | Path tempPath = Files.createTempDirectory(null); 57 | zipFile.extractAll(tempPath.toString()); 58 | for (File file : Objects.requireNonNull(new File(tempPath.toString()).listFiles())) { 59 | if (isCodeFile(file)) { 60 | processList.add(file.getPath()); 61 | } 62 | } 63 | Options.v().set_process_dir(processList); 64 | } else { 65 | Options.v().set_process_dir(Collections.singletonList(taskPath)); 66 | } 67 | Scene.v().loadNecessaryClasses(); 68 | } 69 | 70 | 71 | private static void setupRule() { 72 | File ruleFile = new File(ruleFilePath); 73 | if (!ruleFile.exists()) { 74 | logger.warning("Unable to found rule file,Using inner default rules."); 75 | try { 76 | InputStream assetStream = PrivacyDog.class.getClassLoader().getResourceAsStream("privacydog.json"); 77 | assert assetStream != null; 78 | rules = new Gson().fromJson(new InputStreamReader(assetStream), Rule[].class); 79 | } catch (Exception e) { 80 | logger.warning("Can't read rules from assets."); 81 | } 82 | return; 83 | } 84 | 85 | try { 86 | rules = new Gson().fromJson(new FileReader(ruleFile), Rule[].class); 87 | } catch (Exception e) { 88 | logger.warning("Parse rule fatal: " + e.toString()); 89 | } 90 | } 91 | 92 | public static boolean isCodeFile(File file) { 93 | return file.isFile() && (file.getName().endsWith(".jar") 94 | || file.getName().endsWith(".apk") 95 | || file.getName().endsWith(".dex") 96 | || file.getName().endsWith(".aar")); 97 | } 98 | 99 | public static void main(String[] args) { 100 | CommandLineParser parser = new DefaultParser(); 101 | org.apache.commons.cli.Options options = new org.apache.commons.cli.Options(); 102 | 103 | 104 | options.addOption("t", "target", true, "target file or folder path;"); 105 | options.addOption("r", "rule", true, "rule file path, default is 'privacydog.json';"); 106 | options.addOption("o", "output", true, "output json to folder;"); 107 | 108 | 109 | try { 110 | CommandLine commandLine = parser.parse(options, args); 111 | if (!commandLine.hasOption("t")) { 112 | System.err.println("Please input target path from '-t' option."); 113 | return; 114 | } 115 | targetPath = commandLine.getOptionValue("t"); 116 | 117 | if (commandLine.hasOption("r")) { 118 | ruleFilePath = commandLine.getOptionValue("r"); 119 | } 120 | 121 | if (commandLine.hasOption("o")) { 122 | String o = commandLine.getOptionValue("o"); 123 | if (!(new File(o).exists() && new File(o).isDirectory())) { 124 | System.err.println("Output need directory path;"); 125 | return; 126 | } 127 | outputPath = o; 128 | } 129 | } catch (ParseException e) { 130 | e.printStackTrace(); 131 | } 132 | 133 | setupRule(); 134 | if (rules == null || rules.length == 0) { 135 | logger.warning("The rule is empty"); 136 | return; 137 | } 138 | 139 | File targetPath = new File(PrivacyDog.targetPath); 140 | if (!targetPath.exists()) { 141 | logger.warning("The target path is not exists"); 142 | return; 143 | } 144 | List files = new ArrayList<>(); 145 | 146 | if (targetPath.isDirectory()) { 147 | for (File file : Objects.requireNonNull(new File(PrivacyDog.targetPath).listFiles())) { 148 | if (isCodeFile(file)) { 149 | files.add(file); 150 | } 151 | } 152 | } else if (isCodeFile(targetPath)) { 153 | files.add(targetPath); 154 | } 155 | for (File file : files) { 156 | System.out.println("\n" + file.getName()); 157 | 158 | try { 159 | setupSoot(file.getPath()); 160 | } catch (IOException e) { 161 | e.printStackTrace(); 162 | continue; 163 | } 164 | 165 | PrivacyDetectionTransformer transformer = new PrivacyDetectionTransformer(rules); 166 | PackManager.v().getPack("jtp").add(new Transform("jtp.privacy_detection", transformer)); 167 | PackManager.v().runPacks(); 168 | 169 | Map> resultMap = transformer.getResultMap(); 170 | Map>> jsonObject = new HashMap<>(); 171 | for (Rule rule : resultMap.keySet()) { 172 | System.out.println("\t" + rule.getName()); 173 | Map> locationMap = new HashMap<>(); 174 | jsonObject.put(rule.getName(), locationMap); 175 | List locations = resultMap.get(rule); 176 | locations.sort(Comparator.comparing(StmtLocation::getClassName)); 177 | for (StmtLocation location : locations) { 178 | System.out.printf("\t\t%s->%s :%s%n", 179 | location.getBody().getMethod().getDeclaringClass().getName(), 180 | location.getBody().getMethod().getName(), 181 | location.getStmt()); 182 | String locationSig = String.format("%s->%s", location.getBody().getMethod().getDeclaringClass().getName(), location.getBody().getMethod().getName()); 183 | if (!locationMap.containsKey(locationSig)) { 184 | locationMap.put(locationSig, new ArrayList<>()); 185 | } 186 | locationMap.get(locationSig).add(location.getStmt().toString()); 187 | 188 | } 189 | } 190 | String jsonData = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create().toJson(jsonObject); 191 | System.out.println(jsonData); 192 | if (outputPath != null) { 193 | try { 194 | FileWriter writer = new FileWriter(new File(outputPath, file.getName() + ".json")); 195 | writer.write(jsonData); 196 | writer.close(); 197 | } catch (IOException e) { 198 | e.printStackTrace(); 199 | } 200 | } 201 | } 202 | } 203 | } 204 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | --------------------------------------------------------------------------------