commit aa6291eb3384c4d5b1d0911f4f929072fb86e003 Author: nitrogenoliquido <203537016+nitrogenoliquido@users.noreply.github.com> Date: Fri Nov 27 08:34:35 2026 -0500 added files. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..51358ec --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +.gradle/ +build/ +out/ +.idea/ +*.iml +.classpath +.project +.settings/ +*.log +*.BACKUP +out.jar +*-out.jar diff --git a/README.md b/README.md new file mode 100644 index 0000000..dc70952 --- /dev/null +++ b/README.md @@ -0,0 +1,70 @@ +

+ Skid Solutions Banner +

+ + Discord + + Version 9.1.15 + Java 17 + Gradle 8.14.3 +

+ +

+ https://discord.gg/skidsolutions +

+ +

+ +

+ +

+ jak + hack + deobf2 + deobf +

+ +

+ This is not a reconstruction nor a remake. +

+ +

+ +

+ +## How to build + +### Prerequisites +- **Java Development Kit**: JDK 17 (the Gradle wrapper 8.14.3 does not run on newer JDKs) + +### Building OpenStringer + +Run from this folder: + +```powershell +$env:JAVA_HOME = "C:\Program Files\Java\jdk-17" + +.\gradlew.bat clean build +``` + +Generated `build/libs/`: +- `OpenStringer-9.1.15.jar` +- `OpenStringer-9.1.15-sources.jar` + +### Running + +```powershell +java -jar build\libs\OpenStringer-9.1.15.jar [options] +``` + +No license file, activation code, or online check is required. + +Common options: +- `-configFile ` — load XML protection configuration +- `-verbose` — enable verbose logging +- `-optimize` — strip debug info (line numbers, local variables, source file) +- `-checkCaller` — enable caller-context string encryption +- `-integrityProtection` — enable bytecode and JAR integrity checks +- `-resourceEncryption` — enable resource encryption and stream wrappers +- `-target <1.5|1.6|1.7|1.8|9>` — force target bytecode version +- `-info` — display product information diff --git a/assets/deobf.jpg b/assets/deobf.jpg new file mode 100644 index 0000000..fa8dbde Binary files /dev/null and b/assets/deobf.jpg differ diff --git a/assets/deobf2.png b/assets/deobf2.png new file mode 100644 index 0000000..1d4014d Binary files /dev/null and b/assets/deobf2.png differ diff --git a/assets/divider.svg b/assets/divider.svg new file mode 100644 index 0000000..f473231 --- /dev/null +++ b/assets/divider.svg @@ -0,0 +1,26 @@ + diff --git a/assets/hack.jpg b/assets/hack.jpg new file mode 100644 index 0000000..c4252ef Binary files /dev/null and b/assets/hack.jpg differ diff --git a/assets/jak.jpg b/assets/jak.jpg new file mode 100644 index 0000000..162bfe5 Binary files /dev/null and b/assets/jak.jpg differ diff --git a/assets/ss.png b/assets/ss.png new file mode 100644 index 0000000..041b33a Binary files /dev/null and b/assets/ss.png differ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..dfaafa6 --- /dev/null +++ b/build.gradle @@ -0,0 +1,84 @@ +plugins { + id 'java' + id 'application' + id 'idea' + id 'eclipse' +} + +group = 'com.licel.stringer' +version = '9.1.15' + +def javaVersion = 17 + +repositories { + mavenCentral() +} + +dependencies { + implementation 'org.ow2.asm:asm:9.11.1' + implementation 'org.ow2.asm:asm-commons:9.11.1' + implementation 'org.apache.commons:commons-jexl3:3.3' + implementation 'commons-io:commons-io:2.18.0' + implementation 'org.zeroturnaround:zt-zip:1.17' + implementation 'org.slf4j:slf4j-simple:1.7.36' + implementation 'org.bouncycastle:bcprov-jdk18on:1.80' + implementation 'org.bouncycastle:bcpkix-jdk18on:1.80' + compileOnly 'org.apache.ant:ant:1.10.15' +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(javaVersion) + } + withSourcesJar() +} + +application { + applicationName = 'OpenStringer' + mainClass = 'com.licel.stringer.ConsoleTask' +} + +tasks.withType(JavaCompile).configureEach { + options.release = javaVersion + options.encoding = 'UTF-8' + options.compilerArgs += ['-parameters', '-Xlint:none', '-Xmaxerrs', '4096'] +} + +tasks.withType(JavaExec).configureEach { + javaLauncher = javaToolchains.launcherFor { + languageVersion = JavaLanguageVersion.of(javaVersion) + } +} + +tasks.withType(AbstractArchiveTask).configureEach { + preserveFileTimestamps = false + reproducibleFileOrder = true +} + +tasks.named('jar', Jar) { + duplicatesStrategy = DuplicatesStrategy.EXCLUDE + manifest { + attributes( + 'Main-Class': 'com.licel.stringer.ConsoleTask', + 'Implementation-Title': 'OpenStringer', + 'Implementation-Version': project.version) + } + exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/versions/**' + from { + configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } + } +} + +idea { + module { + downloadSources = true + downloadJavadoc = true + } +} + +eclipse { + classpath { + downloadSources = true + downloadJavadoc = true + } +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..a31b0e0 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8 +org.gradle.parallel=true +org.gradle.caching=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..9251069 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionSha256Sum=bd71102213493060956ec229d946beee57158dbd89d0e62b91bca0fa2c5f3531 diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..23d15a9 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..4e7b9fc --- /dev/null +++ b/settings.gradle @@ -0,0 +1,7 @@ +pluginManagement { + repositories { + mavenCentral() + gradlePluginPortal() + } +} +rootProject.name = 'OpenStringer' diff --git a/src/main/java/com/licel/stringer/AntTask.java b/src/main/java/com/licel/stringer/AntTask.java new file mode 100644 index 0000000..2b6f011 --- /dev/null +++ b/src/main/java/com/licel/stringer/AntTask.java @@ -0,0 +1,372 @@ +package com.licel.stringer; + +import java.io.File; +import java.lang.reflect.Method; +import org.apache.tools.ant.BuildException; +import org.apache.tools.ant.Project; +import org.apache.tools.ant.Task; +import org.apache.tools.ant.types.PatternSet; +import org.apache.tools.ant.types.PatternSet.NameEntry; + +public class AntTask extends Task { + private Config config = new Config(); + private final PatternSet patternSet; + + public AntTask() { + this.config.setCheckCaller(true); + this.config.setListener(new AntTaskWorkerListener(this, this)); + this.patternSet = new PatternSet(); + } + + @Override + public void execute() { + this.log("Mode: ANT"); + this.log(ProductInfo.getConsoleTitle()); + Project project = this.getProject(); + + String[] includes = this.patternSet.getIncludePatterns(project); + if (includes != null) { + for (String include : includes) { + this.config.addInclude(include); + } + } + + String[] excludes = this.patternSet.getExcludePatterns(project); + if (excludes != null) { + for (String exclude : excludes) { + this.config.addExclude(exclude); + } + } + + try { + Worker worker = new Worker(this.config); + worker.stringerIt(); + } catch (Throwable ex) { + ex.printStackTrace(); + throw new BuildException(ex.getMessage()); + } + } + + public void setSrcFile(File srcFile) { + this.config.setSrcFile(srcFile); + } + + public void setSrcDir(File srcDir) { + this.config.setSrcDir(srcDir); + } + + public void setDestFile(File destFile) { + this.config.setDestFile(destFile); + } + + public void setDestDir(File destDir) { + this.config.setDestDir(destDir); + } + + public void setVerbose(boolean verbose) { + this.config.setVerbose(verbose); + } + + public ParamsOptions createVerbose() { + return new ParamsOptions(this.config, "setVerbose", boolean.class); + } + + public void setOptimize(boolean optimize) { + this.config.setOptimize(optimize); + } + + public ParamsOptions createOptimize() { + return new ParamsOptions(this.config, "setOptimize", boolean.class); + } + + public void setIntegrityProtection(boolean integrityProtection) { + this.config.setIntegrityProtection(integrityProtection); + } + + public void setResourceEncryption(boolean resourceEncryption) { + this.config.setResourceEncryption(resourceEncryption); + } + + public void setOsgiCompatibility(boolean osgiCompatibility) { + this.config.setOsgiCompatibility(osgiCompatibility); + } + + public void setJ2EECompatibility(boolean j2eeCompatibility) { + this.config.setOsgiCompatibility(true); + } + + public void setNameGenMethod(String nameGenMethod) { + this.config.setNameGenMethod(nameGenMethod); + } + + public void setProguardMapFile(File proguardMapFile) { + this.config.setProguardMapFile(proguardMapFile); + } + + public ParamsOptions createProguardMapFile() { + return new ParamsOptions(this.config, "setProguardMapFile", String.class); + } + + public void setTarget(String target) { + this.config.setTarget(target); + } + + public ParamsOptions createTarget() { + return new ParamsOptions(this.config, "setTarget", String.class); + } + + public void setForceAndroid(boolean forceAndroid) { + this.config.setForceAndroid(forceAndroid); + } + + public void setTrialExpirationTimestamp(String trialExpirationTimestamp) { + this.config.setTrialExpirationTimestamp(trialExpirationTimestamp); + } + + public ParamsOptions createTrialExpirationTimestamp() { + return new ParamsOptions(this.config, "setTrialExpirationTimestamp", String.class); + } + + public void setTrialExpirationTimestampPattern(String trialExpirationTimestampPattern) { + this.config.setTrialExpirationTimestampPattern(trialExpirationTimestampPattern); + } + + public ParamsOptions createTrialExpirationTimestampPattern() { + return new ParamsOptions(this.config, "setTrialExpirationTimestampPattern", String.class); + } + + public void setSignMode(String signMode) { + this.config.setSignMode(signMode); + } + + public ParamsOptions createSignMode() { + return new ParamsOptions(this.config, "setSignMode", String.class); + } + + public void setKeystore(String keystore) { + this.config.setKeystore(keystore); + } + + public ParamsOptions createKeystore() { + return new ParamsOptions(this.config, "setKeystore", String.class); + } + + public void setAlias(String alias) { + this.config.setAlias(alias); + } + + public ParamsOptions createAlias() { + return new ParamsOptions(this.config, "setAlias", String.class); + } + + public void setStorepass(String storepass) { + this.config.setStorepass(storepass); + } + + public ParamsOptions createStorepass() { + return new ParamsOptions(this.config, "setStorepass", String.class); + } + + public void setKeypass(String keypass) { + this.config.setKeypass(keypass); + } + + public ParamsOptions createKeypass() { + return new ParamsOptions(this.config, "setKeypass", String.class); + } + + public void setStoretype(String storetype) { + this.config.setKeystoreType(storetype); + } + + public ParamsOptions createStoretype() { + return new ParamsOptions(this.config, "setKeystoreType", String.class); + } + + public void setConfigFile(File configFile) { + try { + FileConfig fileConfig = new FileConfig(configFile); + if (this.config.getDestFile() != null) { + fileConfig.setDestFile(this.config.getDestFile()); + } + if (this.config.getSrcFile() != null) { + fileConfig.setSrcFile(this.config.getSrcFile()); + } + this.config = fileConfig; + } catch (Exception ex) { + throw new BuildException(ex); + } + } + + public NameEntry createInclude() { + return this.patternSet.createInclude(); + } + + public NameEntry createExclude() { + return this.patternSet.createExclude(); + } + + public void setCheckCaller(boolean checkCaller) { + this.config.setCheckCaller(checkCaller); + } + + public void setCheckJar(boolean checkJar) { + this.config.setCheckJar(checkJar); + } + + public ProtectionElementsOptions createProtectionElements() { + return new ProtectionElementsOptions(this.config.getProtectionElements()); + } + + public class ParamsOptions { + protected Params container; + protected Method setMethod; + protected Method valueOfMethod; + + public ParamsOptions(Params container, String methodName, Class valueType) { + this.container = container; + try { + this.setMethod = container.getClass().getMethod(methodName, valueType); + Class boxedType = valueType.equals(boolean.class) ? Boolean.class : valueType; + Class valueOfArg = boxedType.equals(String.class) ? Object.class : String.class; + this.valueOfMethod = boxedType.getMethod("valueOf", valueOfArg); + } catch (Exception ex) { + throw new BuildException(ex); + } + } + + public void addText(String text) { + try { + Object parsedValue = this.valueOfMethod.invoke(null, text); + this.setMethod.invoke(this.container, parsedValue); + } catch (Exception ex) { + throw new BuildException(ex); + } + } + } + + public class FiltersOptions { + protected Params container; + + public FiltersOptions(Params container) { + this.container = container; + } + + public ParamsOptions createFilter() { + return new ParamsOptions(this.container, "addFilter", String.class); + } + } + + public class FilteredParamsOptions { + protected Params container; + + public FilteredParamsOptions(Params container) { + this.container = container; + container.setEnabled(true); + } + + public FiltersOptions createFilters() { + return new FiltersOptions(this.container); + } + + public ParamsOptions createMode() { + return new ParamsOptions(this.container, "setMode", String.class); + } + } + + public class StringEncryptonParamsOptions extends FilteredParamsOptions { + public StringEncryptonParamsOptions(Params params) { + super(params); + } + + public ParamsOptions createCheckCaller() { + return new ParamsOptions(this.container, "setCheckCaller", boolean.class); + } + + public ParamsOptions createEqualsIntrinsicEnabled() { + return new ParamsOptions(this.container, "setEqualsIntrinsicEnabled", boolean.class); + } + } + + public class IntegrityControlParamsOptions extends FilteredParamsOptions { + public IntegrityControlParamsOptions(Params params) { + super(params); + } + + public ParamsOptions createCheckBytecode() { + return new ParamsOptions(((IntegrityControlParams) this.container).checkBytecode(), "setEnabled", boolean.class); + } + + public ParamsOptions createCheckJar() { + return new ParamsOptions(((IntegrityControlParams) this.container).checkJar(), "setEnabled", boolean.class); + } + + public ParamsOptions createSealJar() { + return new ParamsOptions(((IntegrityControlParams) this.container).sealJar(), "setEnabled", boolean.class); + } + + public ParamsOptions createOsgiCompatibility() { + return new ParamsOptions(((IntegrityControlParams) this.container).osgiCompatibility(), "setEnabled", boolean.class); + } + } + + public class PathsOptions { + protected ProtectionElementParams container; + + public PathsOptions(ProtectionElementParams container) { + this.container = container; + } + + public ParamsOptions createPath() { + return new ParamsOptions(this.container, "addPath", String.class); + } + } + + public class ProtectionElementOptions { + protected ProtectionElementParams container; + + public ProtectionElementOptions(ProtectionElementParams container) { + this.container = container; + } + + public void setTarget(String target) { + this.container.setTarget(target); + } + + public ParamsOptions createTarget() { + return new ParamsOptions(this.container, "setTarget", String.class); + } + + public PathsOptions createPaths() { + return new PathsOptions(this.container); + } + + public StringEncryptonParamsOptions createStringEncryption() { + return new StringEncryptonParamsOptions(this.container.getStringEncryption()); + } + + public FilteredParamsOptions createHideAccess() { + return new FilteredParamsOptions(this.container.getHideAccess()); + } + + public FilteredParamsOptions createResourceEncryption() { + return new FilteredParamsOptions(this.container.getResourceEncryption()); + } + + public IntegrityControlParamsOptions createIntegrityControl() { + return new IntegrityControlParamsOptions(this.container.getIntegrityControl()); + } + } + + public class ProtectionElementsOptions { + protected ProtectionElementParamsContainer container; + + public ProtectionElementsOptions(ProtectionElementParamsContainer container) { + this.container = container; + } + + public ProtectionElementOptions createProtectionElement() { + return new ProtectionElementOptions(this.container.createElement()); + } + } +} diff --git a/src/main/java/com/licel/stringer/AntTaskWorkerListener.java b/src/main/java/com/licel/stringer/AntTaskWorkerListener.java new file mode 100644 index 0000000..261fa1e --- /dev/null +++ b/src/main/java/com/licel/stringer/AntTaskWorkerListener.java @@ -0,0 +1,23 @@ +package com.licel.stringer; + +import org.apache.tools.ant.Task; + +class AntTaskWorkerListener implements WorkerListener { + private final AntTask antTask; + private final Task task; + + AntTaskWorkerListener(AntTask antTask, Task task) { + this.antTask = antTask; + this.task = task; + } + + @Override + public void info(String message) { + this.task.log(message); + } + + @Override + public void verbose(String message) { + this.task.log(message); + } +} diff --git a/src/main/java/com/licel/stringer/Config.java b/src/main/java/com/licel/stringer/Config.java new file mode 100644 index 0000000..f99d0f0 --- /dev/null +++ b/src/main/java/com/licel/stringer/Config.java @@ -0,0 +1,503 @@ +package com.licel.stringer; + +import com.licel.stringer.model.ClassInfo; +import com.licel.stringer.util.StringerUtils; +import java.io.File; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Properties; + +public class Config extends ProtectionElementParams { + public static final String RELEASE_MODE = "release"; + public static final String DEFAULT_MODE = "default"; + public static final String NONE_MODE = "none"; + + protected boolean verbose = false; + protected boolean optimize = false; + protected String nameGenMethod = "utf"; + protected long trialExpirationTimestampSeconds = 0L; + protected String trialExpirationTimestamp = null; + protected String trialExpirationTimestampPattern = null; + protected List injectList; + protected File srcFile; + protected File destFile; + protected File proguardMapFile; + protected Properties proguardMap; + protected WorkerListener listener; + protected String keystore; + protected String keystoreType; + protected String storepass; + protected String alias; + protected String keypass; + protected String signMode = NONE_MODE; + protected File tmpDir; + protected ArrayList includeList; + protected ArrayList excludeList; + public boolean isLegacy = false; + protected PersonalizationProfile personalizationProfile = new PersonalizationProfile(); + protected ProtectionElementParamsContainer protectionElements = new ProtectionElementParamsContainer(); + protected boolean forceGenerateInternalLibPkg = false; + + public void validate() { + if (this.srcFile == null) { + throw new RuntimeException("Missing srcFile"); + } + if (!this.srcFile.exists()) { + throw new RuntimeException("Could not find srcFile " + this.srcFile.getAbsolutePath()); + } + if (this.destFile == null) { + throw new RuntimeException("Missing destFile"); + } + if (this.tmpDir != null && this.tmpDir.isFile()) { + throw new RuntimeException("The value of tmpDir must point to a valid and writable directory"); + } + + if (this.trialExpirationTimestamp != null) { + if (this.trialExpirationTimestampPattern == null) { + try { + this.trialExpirationTimestampSeconds = Long.parseLong(this.trialExpirationTimestamp); + if (this.trialExpirationTimestampSeconds <= 0L) { + throw new NumberFormatException(); + } + } catch (NumberFormatException ex) { + throw new RuntimeException("Incorrect format of trialExpirationTimestamp (positive integer > 0): " + this.trialExpirationTimestamp); + } + } else { + try { + SimpleDateFormat format = new SimpleDateFormat(this.trialExpirationTimestampPattern); + this.trialExpirationTimestampSeconds = format.parse(this.trialExpirationTimestamp).getTime() / 1000L; + } catch (IllegalArgumentException ex) { + throw new RuntimeException("Incorrect format of trialExpirationTimestampPattern: " + this.trialExpirationTimestampPattern); + } catch (ParseException ex) { + throw new RuntimeException("Incorrect format of trialExpirationTimestamp (" + this.trialExpirationTimestampPattern + "): " + this.trialExpirationTimestamp); + } + } + } + + if (!RELEASE_MODE.equalsIgnoreCase(this.signMode) + && !DEFAULT_MODE.equalsIgnoreCase(this.signMode) + && !NONE_MODE.equalsIgnoreCase(this.signMode)) { + throw new RuntimeException("Incorrect signMode:" + this.signMode); + } + + if (this.isReleaseMode()) { + if (this.keystore == null) { + throw new RuntimeException("In case of sign mode release it is necessary to set keystore path"); + } + if (this.alias == null) { + throw new RuntimeException("In case of sign mode release it is necessary to set key alias"); + } + if (this.storepass == null) { + throw new RuntimeException("In case of sign mode release it is necessary to set storepass"); + } + if (this.keypass == null) { + throw new RuntimeException("In case of sign mode release it is necessary to set keypass"); + } + } + + if (this.includeList != null && this.excludeList != null) { + this.stringEncryption.addFilter(new ClassInfo("glob:!**/**")); + this.integrityControl.addFilter(new ClassInfo("glob:!**/**")); + this.hideAccess.addFilter(new ClassInfo("glob:!**/**")); + this.resourceEncryption.addFilter(new ClassInfo("glob:!**/**")); + } + + if (this.includeList != null) { + this.stringEncryption.setFiltered(true); + this.stringEncryption.setEnabled(true); + this.integrityControl.setFiltered(true); + this.integrityControl.setEnabled(true); + this.hideAccess.setFiltered(true); + this.hideAccess.setEnabled(true); + this.resourceEncryption.setFiltered(true); + this.resourceEncryption.setEnabled(true); + + for (String include : this.includeList) { + this.stringEncryption.addFilter(new ClassInfo(include)); + this.integrityControl.addFilter(new ClassInfo(include)); + this.hideAccess.addFilter(new ClassInfo(include)); + this.resourceEncryption.addFilter(new ClassInfo(include)); + } + } + + if (this.excludeList != null) { + this.stringEncryption.setFiltered(true); + this.stringEncryption.setEnabled(true); + this.integrityControl.setFiltered(true); + this.integrityControl.setEnabled(true); + this.hideAccess.setFiltered(true); + this.hideAccess.setEnabled(true); + this.resourceEncryption.setFiltered(true); + this.resourceEncryption.setEnabled(true); + + for (String exclude : this.excludeList) { + this.stringEncryption.addFilter(new ClassInfo("glob:!" + exclude)); + this.integrityControl.addFilter(new ClassInfo("glob:!" + exclude)); + this.hideAccess.addFilter(new ClassInfo("glob:!" + exclude)); + this.resourceEncryption.addFilter(new ClassInfo("glob:!" + exclude)); + } + } + + if (this.proguardMapFile != null) { + if (!this.proguardMapFile.exists()) { + throw new RuntimeException("Could not find proguardMapFile: " + this.proguardMapFile.getAbsolutePath()); + } + try { + this.proguardMap = StringerUtils.loadProguardMap(this.proguardMapFile); + this.stringEncryption.setMap(this.proguardMap); + this.hideAccess.setMap(this.proguardMap); + this.resourceEncryption.setMap(this.proguardMap); + this.integrityControl.setMap(this.proguardMap); + } catch (Exception ex) { + throw new RuntimeException("Could not load proguardMapFile " + ex.getMessage()); + } + } else { + boolean hasNullPaths = false; + for (ProtectionElementParams element : this.protectionElements.getElements()) { + if (element.getPaths() == null) { + hasNullPaths = true; + break; + } + } + if (hasNullPaths && this.protectionElements.getElements().size() > 1) { + throw new RuntimeException("Protection elements w/ and w/o path tag cannot be used at the same time"); + } + } + } + + public ArrayList generateProtectionElementsConfigs() { + ArrayList configs = new ArrayList<>(); + if (this.protectionElements.getElements().isEmpty()) { + configs.add(this); + return configs; + } + + for (ProtectionElementParams element : this.protectionElements.getElements()) { + Config elementConfig = new Config(); + elementConfig.setAlias(this.alias); + elementConfig.setKeypass(this.keypass); + elementConfig.setKeystore(this.keystore); + elementConfig.setKeystoreType(this.keystoreType); + elementConfig.setOptimize(this.optimize); + elementConfig.setSignMode(this.signMode); + elementConfig.setStorepass(this.storepass); + elementConfig.setTrialExpirationTimestamp(this.trialExpirationTimestamp); + elementConfig.setTrialExpirationTimestampPattern(this.trialExpirationTimestampPattern); + elementConfig.setTrialExpirationTimestampSeconds(this.trialExpirationTimestampSeconds); + elementConfig.setVerbose(this.verbose); + elementConfig.setListener(this.listener); + elementConfig.setProguardMapFile(this.proguardMapFile); + elementConfig.setTarget(element.getTarget() != null ? element.getTarget() : this.target); + elementConfig.setPaths(element.getPaths()); + elementConfig.setStringEncryption(element.getStringEncryption()); + elementConfig.setHideAccess(element.getHideAccess()); + elementConfig.setIntegrityControl(element.getIntegrityControl()); + elementConfig.setResourceEncryption(element.getResourceEncryption()); + if (this.proguardMap != null) { + elementConfig.getStringEncryption().setMap(this.proguardMap); + elementConfig.getHideAccess().setMap(this.proguardMap); + elementConfig.getResourceEncryption().setMap(this.proguardMap); + elementConfig.getIntegrityControl().setMap(this.proguardMap); + } + elementConfig.setSrcFile(this.srcFile); + elementConfig.setDestFile(this.destFile); + configs.add(elementConfig); + } + + return configs; + } + + public void addInclude(String pattern) { + if (this.includeList == null) { + this.includeList = new ArrayList<>(); + } + this.includeList.add(pattern); + } + + public void addExclude(String pattern) { + if (this.excludeList == null) { + this.excludeList = new ArrayList<>(); + } + this.excludeList.add(pattern); + } + + public void addInject(String pattern) { + if (this.injectList == null) { + this.injectList = new ArrayList<>(); + } + this.injectList.add(pattern); + } + + public List getInjectList() { + return this.injectList; + } + + public void setCheckCaller(boolean checkCaller) { + this.stringEncryption.setEnabled(true); + this.stringEncryption.setCheckCaller(checkCaller); + } + + public boolean isVerbose() { + return this.verbose; + } + + public void setVerbose(boolean verbose) { + this.verbose = verbose; + } + + public void setIntegrityProtection(boolean integrityProtection) { + this.integrityControl.setEnabled(true); + this.integrityControl.checkBytecode().setEnabled(integrityProtection); + this.integrityControl.checkJar().setEnabled(integrityProtection); + } + + public void setResourceEncryption(boolean resourceEncryption) { + this.resourceEncryption.setEnabled(resourceEncryption); + } + + public boolean isOptimize() { + return this.optimize; + } + + public void setOptimize(boolean optimize) { + this.optimize = optimize; + } + + public boolean isJ2EECompatibility() { + return this.isOsgiCompatibility(); + } + + public void setJ2EECompatibility(boolean j2eeCompatibility) { + this.setOsgiCompatibility(j2eeCompatibility); + } + + public boolean isOsgiCompatibility() { + return this.integrityControl.osgiCompatibility().isEnabled(); + } + + public void setOsgiCompatibility(boolean osgiCompatibility) { + this.integrityControl.osgiCompatibility().setEnabled(osgiCompatibility); + } + + public String getNameGenMethod() { + return this.nameGenMethod; + } + + public void setNameGenMethod(String nameGenMethod) { + this.nameGenMethod = nameGenMethod; + } + + public File getDestFile() { + return this.destFile; + } + + public void setDestFile(File destFile) { + this.destFile = destFile; + } + + public File getSrcFile() { + return this.srcFile; + } + + public void setSrcFile(File srcFile) { + this.srcFile = srcFile; + } + + public void setDestDir(File destDir) { + this.destFile = destDir; + } + + public void setSrcDir(File srcDir) { + this.srcFile = srcDir; + } + + public String getKeystore() { + return this.keystore; + } + + public void setKeystore(String keystore) { + this.keystore = keystore; + } + + public String getKeystoreType() { + return this.keystoreType; + } + + public void setKeystoreType(String keystoreType) { + this.keystoreType = keystoreType; + } + + public String getStorepass() { + return this.storepass; + } + + public void setStorepass(String storepass) { + this.storepass = storepass; + } + + public String getAlias() { + return this.alias; + } + + public void setAlias(String alias) { + this.alias = alias; + } + + public String getKeypass() { + return this.keypass; + } + + public void setKeypass(String keypass) { + this.keypass = keypass; + } + + public String getSignMode() { + return this.signMode; + } + + public void setSignMode(String signMode) { + this.signMode = signMode; + } + + public boolean isReleaseMode() { + return RELEASE_MODE.equalsIgnoreCase(this.signMode); + } + + public boolean isDefaultMode() { + return DEFAULT_MODE.equalsIgnoreCase(this.signMode); + } + + public boolean isNoneMode() { + return NONE_MODE.equalsIgnoreCase(this.signMode); + } + + public File getProguardMapFile() { + return this.proguardMapFile; + } + + public void setProguardMapFile(File proguardMapFile) { + this.proguardMapFile = proguardMapFile; + } + + public void setProguardMapFile(String proguardMapFile) { + this.proguardMapFile = new File(proguardMapFile); + } + + public Properties getProguardMap() { + return this.proguardMap; + } + + public WorkerListener getListener() { + return this.listener != null ? this.listener : this.getDefaultListener(); + } + + public void setListener(WorkerListener listener) { + this.listener = listener; + } + + public boolean isForceAndroid() { + return false; + } + + public void setForceAndroid(boolean forceAndroid) { + } + + public String getTrialExpirationTimestamp() { + return this.trialExpirationTimestamp; + } + + public void setTrialExpirationTimestamp(String trialExpirationTimestamp) { + this.trialExpirationTimestamp = trialExpirationTimestamp; + } + + public long getTrialExpirationTimestampSeconds() { + return this.trialExpirationTimestampSeconds; + } + + public void setTrialExpirationTimestampSeconds(long trialExpirationTimestampSeconds) { + this.trialExpirationTimestampSeconds = trialExpirationTimestampSeconds; + } + + public String getTrialExpirationTimestampPattern() { + return this.trialExpirationTimestampPattern; + } + + public void setTrialExpirationTimestampPattern(String trialExpirationTimestampPattern) { + this.trialExpirationTimestampPattern = trialExpirationTimestampPattern; + } + + public void setCheckJar(boolean checkJar) { + this.integrityControl.checkJar().setEnabled(checkJar); + } + + public ProtectionElementParamsContainer getProtectionElements() { + return this.protectionElements; + } + + public PersonalizationProfile getPersonalizationProfile() { + return this.personalizationProfile; + } + + public void setPersonalizationProfile(PersonalizationProfile personalizationProfile) { + this.personalizationProfile = personalizationProfile; + } + + public File getTmpDir() { + return this.tmpDir; + } + + public void setTmpDir(File tmpDir) { + this.tmpDir = tmpDir; + } + + WorkerListener getDefaultListener() { + return new ConsoleWorkerListener(this); + } + + public boolean isForceGenerateInternalLibPkg() { + return this.forceGenerateInternalLibPkg; + } + + public void setForceGenerateInternalLibPkg(boolean forceGenerateInternalLibPkg) { + this.forceGenerateInternalLibPkg = forceGenerateInternalLibPkg; + } + + @Override + public void dump(WorkerListener listener) { + if (this.isLegacy) { + listener.verbose("A legacy format configuration file is set. See actual protection settings in verbose mode."); + } + + if (this.verbose) { + listener.verbose("[Configuration]"); + listener.verbose(" source: " + this.srcFile.getAbsolutePath()); + listener.verbose(" destination: " + this.destFile.getAbsolutePath()); + listener.verbose(" sign mode: " + this.signMode); + listener.verbose(" verbose: " + this.verbose); + listener.verbose(" optimize: " + this.optimize); + listener.verbose(" android library: " + this.isForceAndroid()); + if (this.getProguardMapFile() != null) { + listener.verbose(" proguard map file: " + this.getProguardMapFile()); + } + if (this.getTrialExpirationTimestampSeconds() > 0L) { + Date expirationDate = new Date(this.getTrialExpirationTimestampSeconds() * 1000L); + SimpleDateFormat format = new SimpleDateFormat(); + listener.verbose(" trialExpirationTimestamp: " + this.getTrialExpirationTimestampSeconds() + "(" + format.format(expirationDate) + ")"); + } + if (this.getTmpDir() != null) { + listener.verbose(" tmpDir: " + this.getTmpDir()); + } + + if (this.protectionElements.getElements().isEmpty()) { + super.dump(listener); + } else { + for (ProtectionElementParams element : this.protectionElements.getElements()) { + element.dump(listener); + } + } + } + } +} diff --git a/src/main/java/com/licel/stringer/ConsoleTask.java b/src/main/java/com/licel/stringer/ConsoleTask.java new file mode 100644 index 0000000..345691a --- /dev/null +++ b/src/main/java/com/licel/stringer/ConsoleTask.java @@ -0,0 +1,148 @@ +package com.licel.stringer; + +import java.io.File; + +public class ConsoleTask { + public static void main(String[] args) { + Config config = new Config(); + String configFilePath = null; + boolean repairMode = false; + int positionalIndex = 0; + + try { + for (int i = 0; i < args.length; i++) { + if (args[i].equalsIgnoreCase("-verbose")) { + config.setVerbose(true); + } else if (args[i].equalsIgnoreCase("-checkCaller")) { + config.setCheckCaller(true); + } else if (args[i].equalsIgnoreCase("-integrityProtection")) { + config.setIntegrityProtection(true); + } else if (args[i].equalsIgnoreCase("-optimize")) { + config.setOptimize(true); + } else if (args[i].equalsIgnoreCase("-resourceEncryption")) { + config.setResourceEncryption(true); + } else if (args[i].equalsIgnoreCase("-osgiCompatibility")) { + config.setOsgiCompatibility(true); + } else if (args[i].equalsIgnoreCase("-include")) { + if (i + 1 < args.length) { + config.addInclude(args[++i]); + } + } else if (args[i].equalsIgnoreCase("-exclude")) { + if (i + 1 < args.length) { + config.addExclude(args[++i]); + } + } else if (args[i].equalsIgnoreCase("-inject")) { + if (i + 1 < args.length) { + config.addInject(args[++i]); + } + } else if (args[i].equalsIgnoreCase("-configFile")) { + if (i + 1 < args.length) { + configFilePath = args[++i]; + } + } else if (args[i].equalsIgnoreCase("-proguardMapFile")) { + if (i + 1 < args.length) { + config.setProguardMapFile(new File(args[++i])); + } + } else if (args[i].equalsIgnoreCase("-nameGenMethod")) { + if (i + 1 < args.length) { + String method = args[++i]; + if ("utf".equalsIgnoreCase(method) || "latin".equalsIgnoreCase(method)) { + config.setNameGenMethod(method); + } + } + } else if (args[i].equalsIgnoreCase("-target")) { + if (i + 1 < args.length) { + config.setTarget(args[++i]); + } + } else if (args[i].equalsIgnoreCase("-outputType")) { + if (i + 1 < args.length) { + i++; + } + } else if (args[i].equalsIgnoreCase("-trialExpirationTimestamp")) { + if (i + 1 < args.length) { + config.setTrialExpirationTimestamp(args[++i]); + } + } else if (args[i].equalsIgnoreCase("-trialExpirationTimestampPattern")) { + if (i + 1 < args.length) { + config.setTrialExpirationTimestampPattern(args[++i]); + } + } else if (args[i].equalsIgnoreCase("-forceAndroid")) { + config.setForceAndroid(true); + } else if (args[i].equalsIgnoreCase("-noCheckJar")) { + config.setCheckJar(false); + } else if (args[i].equalsIgnoreCase("-equalsIntrinsicEnabled")) { + config.getStringEncryption().setEqualsIntrinsicEnabled(true); + } else if (args[i].equalsIgnoreCase("-repair")) { + repairMode = true; + } else if (args[i].equalsIgnoreCase("-info")) { + printProductInfo(); + } else { + positionalIndex = i; + break; + } + } + } catch (Exception ex) { + System.err.println("Error parsing config parameters : " + ex.getMessage()); + System.exit(-1); + } + + if (configFilePath != null) { + try { + FileConfig fileConfig = new FileConfig(new File(configFilePath)); + if (config.getDestFile() != null) { + fileConfig.setDestFile(config.getDestFile()); + } + if (config.getSrcFile() != null) { + fileConfig.setSrcFile(config.getSrcFile()); + } + if (config.getProguardMapFile() != null) { + fileConfig.setProguardMapFile(config.getProguardMapFile()); + } + config = fileConfig; + } catch (Exception ex) { + System.err.println("Error parsing config file : " + ex.getMessage()); + System.exit(-1); + } + } + + if (config.getSrcFile() == null && positionalIndex + 1 > args.length) { + System.err.println("Missing src parameter"); + System.err.println("Usage : java -jar stringer.jar [options] src dest"); + System.exit(-1); + } else if (positionalIndex < args.length) { + File src = new File(args[positionalIndex]); + if (src.isDirectory()) { + config.setSrcDir(src); + } else { + config.setSrcFile(src); + } + } + + if (config.getDestFile() == null && positionalIndex + 2 > args.length) { + System.err.println("Missing dest parameter"); + System.err.println("Usage : java -jar stringer.jar [options] src dest"); + System.exit(-1); + } else if (positionalIndex + 1 < args.length) { + config.setDestFile(new File(args[positionalIndex + 1])); + } + + try { + config.getListener().info("Mode: CLI"); + if (!repairMode) { + Worker worker = new Worker(config); + worker.stringerIt(); + } else { + Worker.repairArchive(config.getSrcFile(), config.getDestFile()); + } + } catch (Throwable ex) { + ex.printStackTrace(); + System.err.println("Failed to process due to: " + ex.getMessage()); + System.exit(-1); + } + } + + private static void printProductInfo() { + System.out.println(ProductInfo.getInfoText()); + System.exit(0); + } +} diff --git a/src/main/java/com/licel/stringer/ConsoleWorkerListener.java b/src/main/java/com/licel/stringer/ConsoleWorkerListener.java new file mode 100644 index 0000000..ef57d19 --- /dev/null +++ b/src/main/java/com/licel/stringer/ConsoleWorkerListener.java @@ -0,0 +1,19 @@ +package com.licel.stringer; + +class ConsoleWorkerListener implements WorkerListener { + private final Config config; + + ConsoleWorkerListener(Config config) { + this.config = config; + } + + @Override + public void info(String message) { + System.out.println(message); + } + + @Override + public void verbose(String message) { + System.out.println(message); + } +} diff --git a/src/main/java/com/licel/stringer/FileConfig.java b/src/main/java/com/licel/stringer/FileConfig.java new file mode 100644 index 0000000..30b86f2 --- /dev/null +++ b/src/main/java/com/licel/stringer/FileConfig.java @@ -0,0 +1,193 @@ +package com.licel.stringer; + +import com.licel.stringer.config.PathFilter; +import com.licel.stringer.config.ProtectionConfigHandler; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +public class FileConfig extends Config { + private SAXParserFactory saxParserFactory = null; + + public FileConfig() { + this.saxParserFactory = this.createSAXParserFactory(); + } + + public FileConfig(File file) throws IOException, ParserConfigurationException, SAXException { + this.saxParserFactory = this.createSAXParserFactory(); + this.parseXmlFile(file); + } + + private Document createXmlDoc() throws ParserConfigurationException { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + Document document = builder.newDocument(); + Element root = document.createElement("stringer-v3"); + root.appendChild(this.createTag(document, "signMode", this.signMode)); + root.appendChild(this.createTag(document, "verbose", Boolean.toString(this.verbose))); + root.appendChild(this.createTag(document, "optimize", Boolean.toString(this.optimize))); + + try { + if (this.proguardMapFile != null) { + root.appendChild(this.createTag(document, "proguardMapFile", this.proguardMapFile.getCanonicalPath())); + } + } catch (Exception ignored) { + } + + document.appendChild(root); + if (this.isReleaseMode()) { + if (this.keystore != null && !this.keystore.trim().isEmpty()) { + root.appendChild(this.createTag(document, "keystore", this.keystore)); + } + if (this.alias != null && !this.alias.trim().isEmpty()) { + root.appendChild(this.createTag(document, "alias", this.alias)); + } + if (this.storepass != null && !this.storepass.trim().isEmpty()) { + root.appendChild(this.createTag(document, "storepass", this.storepass)); + } + if (this.keystoreType != null && !this.keystoreType.trim().isEmpty()) { + root.appendChild(this.createTag(document, "storetype", this.keystoreType)); + } + if (this.keypass != null && !this.keypass.trim().isEmpty()) { + root.appendChild(this.createTag(document, "keypass", this.keypass)); + } + } + + try { + if (this.tmpDir != null) { + root.appendChild(this.createTag(document, "tmpDir", this.tmpDir.getCanonicalPath())); + } + } catch (Exception ignored) { + } + + ArrayList elementConfigs = this.generateProtectionElementsConfigs(); + Element protectionElementsNode = document.createElement("protectionElements"); + for (Config elementConfig : elementConfigs) { + protectionElementsNode.appendChild(this.createProtectionElementParams(document, elementConfig)); + } + + root.appendChild(protectionElementsNode); + return document; + } + + public void store(File file) { + try { + Document document = this.createXmlDoc(); + TransformerFactory transformerFactory = TransformerFactory.newInstance(); + Transformer transformer = transformerFactory.newTransformer(); + DOMSource source = new DOMSource(document); + transformer.setOutputProperty("indent", "yes"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); + StreamResult result = new StreamResult(file); + transformer.transform(source, result); + } catch (ParserConfigurationException | TransformerException ignored) { + } + } + + private Element createTag(Document document, String tagName, String value) { + Element element = document.createElement(tagName); + element.setTextContent(value); + return element; + } + + private Element createParams(Document document, String tagName, FilteredParams params) { + Element element = document.createElement(tagName); + Element modeElement = document.createElement("mode"); + modeElement.setTextContent(params.getMode()); + element.appendChild(modeElement); + if (params.filtered && params.filters != null && !params.filters.isEmpty()) { + Element filtersElement = document.createElement("filters"); + for (PathFilter filter : params.filters) { + Element filterElement = document.createElement("filter"); + filterElement.appendChild(document.createCDATASection(filter.toString())); + filtersElement.appendChild(filterElement); + } + element.appendChild(filtersElement); + } + return element; + } + + private Element createProtectionElementParams(Document document, ProtectionElementParams params) { + Element element = document.createElement("protectionElement"); + if (this.target != null) { + element.appendChild(this.createTag(document, "target", this.target)); + } + + if (params.getPaths() != null) { + Element pathsElement = document.createElement("paths"); + for (String path : params.getPaths()) { + Element pathElement = document.createElement("path"); + pathElement.appendChild(document.createCDATASection(path)); + pathsElement.appendChild(pathElement); + } + element.appendChild(pathsElement); + } + + if (params.getStringEncryption().isEnabled()) { + Element stringEnc = this.createParams(document, "stringEncryption", params.getStringEncryption()); + stringEnc.appendChild(this.createTag(document, "checkCaller", Boolean.toString(params.getStringEncryption().isCheckCaller()))); + stringEnc.appendChild(this.createTag(document, "equalsIntrinsicEnabled", Boolean.toString(params.getStringEncryption().isEqualsIntrinsicEnabled()))); + element.appendChild(stringEnc); + } + + if (params.getHideAccess().isEnabled()) { + element.appendChild(this.createParams(document, "hideAccess", params.getHideAccess())); + } + + if (params.getResourceEncryption().isEnabled()) { + element.appendChild(this.createParams(document, "resourceEncryption", params.getResourceEncryption())); + } + + if (params.getIntegrityControl().isEnabled()) { + Element integrity = this.createParams(document, "integrityControl", params.getIntegrityControl()); + integrity.appendChild(this.createTag(document, "checkBytecode", Boolean.toString(params.getIntegrityControl().checkBytecode().isEnabled()))); + integrity.appendChild(this.createTag(document, "checkJar", Boolean.toString(params.getIntegrityControl().checkJar().isEnabled()))); + integrity.appendChild(this.createTag(document, "sealJar", Boolean.toString(params.getIntegrityControl().sealJar().isEnabled()))); + integrity.appendChild(this.createTag(document, "osgiCompatibility", Boolean.toString(params.getIntegrityControl().osgiCompatibility().isEnabled()))); + element.appendChild(integrity); + } + + return element; + } + + private SAXParserFactory createSAXParserFactory() { + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setValidating(false); + try { + factory.setFeature("http://xml.org/sax/features/validation", false); + factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false); + factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); + factory.setFeature("http://xml.org/sax/features/external-general-entities", false); + factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + } catch (Exception ignored) { + } + return factory; + } + + private void parseXmlFile(File file) throws IOException, ParserConfigurationException, SAXException { + try (InputStreamReader reader = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8)) { + InputSource inputSource = new InputSource(); + inputSource.setCharacterStream(reader); + ProtectionConfigHandler handler = new ProtectionConfigHandler(this, this); + SAXParser parser = this.saxParserFactory.newSAXParser(); + parser.parse(inputSource, handler); + } + } +} diff --git a/src/main/java/com/licel/stringer/FilteredParams.java b/src/main/java/com/licel/stringer/FilteredParams.java new file mode 100644 index 0000000..2ee1f99 --- /dev/null +++ b/src/main/java/com/licel/stringer/FilteredParams.java @@ -0,0 +1,220 @@ +package com.licel.stringer; + +import com.licel.stringer.config.PathFilter; +import com.licel.stringer.model.ClassInfo; +import java.nio.file.FileSystems; +import java.nio.file.PathMatcher; +import java.nio.file.Paths; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +public class FilteredParams extends Params { + public static final String ANNOTATIONS_MODE = "annotations"; + public static final String FILTERED_MODE = "filter"; + public static final String OFF_MODE = "off"; + + protected boolean annotations = false; + protected boolean filtered = true; + protected List filters = new ArrayList<>(); + protected Properties map; + + public void setMode(String mode) throws ParseException { + if (mode != null) { + if (ANNOTATIONS_MODE.equals(mode)) { + this.annotations = true; + this.filtered = false; + this.enabled = true; + } else if (FILTERED_MODE.equals(mode)) { + this.annotations = false; + this.filtered = true; + this.enabled = true; + } else if (OFF_MODE.equals(mode)) { + this.annotations = false; + this.filtered = false; + this.enabled = false; + } else { + throw new ParseException("Illegal mode value: " + mode, 0); + } + } + } + + public String getMode() { + if (this.annotations) { + return ANNOTATIONS_MODE; + } + return this.filtered ? FILTERED_MODE : OFF_MODE; + } + + public void setMap(Properties map) { + this.map = map; + } + + public boolean isAnnotations() { + return this.annotations; + } + + public void setAnnotations(boolean annotations) { + this.annotations = annotations; + this.filtered = !annotations; + } + + public boolean isFiltered() { + return this.filtered; + } + + public void setFiltered(boolean filtered) { + this.filtered = filtered; + this.annotations = !filtered; + } + + public boolean isEmpty() { + return this.filters.isEmpty(); + } + + public List getFilters() { + return this.filters; + } + + public void addFilter(ClassInfo classInfo) { + this.addFilter(classInfo.name); + } + + public void addFilter(String filterPattern) { + this.filters.add(this.makeFilter(filterPattern)); + } + + protected PathFilter makeFilter(String filterPattern) { + PathMatcher pathMatcher = null; + String syntaxPrefix = ""; + boolean exclude = false; + boolean isRegex = filterPattern.startsWith("regex:"); + boolean isGlob = filterPattern.startsWith("glob:"); + if (isRegex) { + syntaxPrefix = "regex:"; + } + if (isGlob) { + syntaxPrefix = "glob:"; + } + + String expression = filterPattern; + if (isRegex || isGlob) { + int colonIndex = expression.indexOf(':'); + if (colonIndex + 1 >= expression.length()) { + throw new RuntimeException("Invalid filter: " + expression); + } + expression = filterPattern.substring(colonIndex + 1); + exclude = expression.charAt(0) == '!'; + if (exclude) { + expression = expression.substring(1); + filterPattern = syntaxPrefix.concat(expression); + } + pathMatcher = FileSystems.getDefault().getPathMatcher(filterPattern); + } + + return new PathFilter(pathMatcher, syntaxPrefix, expression, exclude); + } + + public String getFilterString(String delimiter) { + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < this.filters.size(); i++) { + builder.append(this.filters.get(i).toString()).append(delimiter); + } + if (builder.length() > 0 && builder.charAt(builder.length() - 1) == delimiter.charAt(0)) { + builder.deleteCharAt(builder.length() - 1); + } + return builder.toString(); + } + + public void setFilterString(String filterList, String delimiterRegex) { + this.filters = new ArrayList<>(); + String[] entries = filterList.split(delimiterRegex); + for (String entry : entries) { + if (!entry.trim().isEmpty()) { + this.addFilter(new ClassInfo(entry)); + } + } + } + + public boolean match(ClassInfo classInfo) { + return this.match(classInfo.name); + } + + public boolean match(String target) { + return this.match(target, true); + } + + public boolean match(String target, boolean resolveProguardName) { + if (!this.filtered) { + return false; + } + if (this.filters.isEmpty()) { + return true; + } + + boolean defaultResult = false; + for (int i = this.filters.size() - 1; i >= 0; i--) { + PathFilter filter = this.filters.get(i); + if (filter.pathMatcher != null) { + boolean matched = filter.pathMatcher.matches( + resolveProguardName ? Paths.get(this.resolveClassName(target)) : Paths.get(target)); + if (filter.exclude) { + defaultResult = true; + if (matched) { + return false; + } + } + if (matched) { + return true; + } + } else if (filter.pathExpression != null + && (resolveProguardName ? this.resolveClassName(target) : target).matches(this.wildcardToRegex(filter.pathExpression))) { + return true; + } + } + + return defaultResult; + } + + protected String resolveClassName(String className) { + String resolved = className; + if (this.map != null && this.map.containsKey(resolved)) { + resolved = this.map.getProperty(resolved).replace('.', '/'); + } + return resolved; + } + + protected String wildcardToRegex(String wildcard) { + StringBuilder regex = new StringBuilder(wildcard.length()); + regex.append('^'); + for (int i = 0; i < wildcard.length(); i++) { + char ch = wildcard.charAt(i); + switch (ch) { + case '$': + case '(': + case ')': + case '.': + case '[': + case '\\': + case ']': + case '^': + case '{': + case '|': + case '}': + regex.append("\\").append(ch); + break; + case '*': + regex.append(".*"); + break; + case '?': + regex.append("."); + break; + default: + regex.append(ch); + } + } + regex.append('$'); + return regex.toString(); + } +} diff --git a/src/main/java/com/licel/stringer/HideAccessParams.java b/src/main/java/com/licel/stringer/HideAccessParams.java new file mode 100644 index 0000000..e11f1e3 --- /dev/null +++ b/src/main/java/com/licel/stringer/HideAccessParams.java @@ -0,0 +1,114 @@ +package com.licel.stringer; + +import com.licel.stringer.config.MemberAccessFilter; +import com.licel.stringer.config.PathFilter; +import com.licel.stringer.util.StringerUtils; +import java.nio.file.FileSystems; +import java.nio.file.PathMatcher; +import java.nio.file.Paths; + +public class HideAccessParams extends FilteredParams { + public static final String ANNOTATION = "Lcom/stringer/annotations/HideAccess;"; + + public HideAccessParams() { + this.name = "hideAccess"; + } + + private boolean isSameClassElementName(MemberAccessFilter filter, String owner, String memberName, String descriptor) { + String dotOwner = owner.replace('/', '.'); + if (this.map != null && this.map.containsKey(dotOwner)) { + this.map.getProperty(dotOwner).replace('.', '/'); + } + + String argDescriptor = descriptor.substring(0, descriptor.indexOf(')') + 1); + String expectedArgs = StringerUtils.toJvmArgumentDescriptor(filter.parameterPattern, this.map); + if (!expectedArgs.equals(argDescriptor)) { + return false; + } + + String resolvedName = memberName; + if (this.map != null) { + String key = dotOwner + ':' + memberName + StringerUtils.toJvmArgumentDescriptor(filter.parameterPattern, null); + resolvedName = this.map.getProperty(key, memberName); + } + + return resolvedName.equals(filter.memberName); + } + + public boolean matchClassElement(String owner, String memberName, String descriptor) { + if (!this.filtered) { + return false; + } + if (this.filters.isEmpty()) { + return true; + } + + boolean defaultResult = false; + for (int i = this.filters.size() - 1; i >= 0; i--) { + MemberAccessFilter filter = (MemberAccessFilter) this.filters.get(i); + if (filter.pathMatcher != null) { + boolean matched = filter.pathMatcher.matches(Paths.get(this.resolveClassName(owner))) + && (filter.memberSignature == null || this.isSameClassElementName(filter, owner, memberName, descriptor)); + if (filter.exclude) { + defaultResult = true; + if (matched) { + return false; + } + } + if (matched) { + return true; + } + } else if (filter.pathExpression != null + && this.resolveClassName(owner).matches(this.wildcardToRegex(filter.pathExpression))) { + return true; + } + } + + return defaultResult; + } + + @Override + protected PathFilter makeFilter(String filterPattern) { + String rawPattern = filterPattern; + String memberSignature = null; + boolean exclude = false; + int hashIndex = filterPattern.indexOf('#'); + if (hashIndex > 0) { + filterPattern = filterPattern.substring(0, hashIndex); + memberSignature = rawPattern.substring(hashIndex + 1); + } + + PathMatcher pathMatcher = null; + String syntaxPrefix = ""; + boolean isRegex = filterPattern.startsWith("regex:"); + boolean isGlob = filterPattern.startsWith("glob:"); + if (isRegex) { + syntaxPrefix = "regex:"; + } + if (isGlob) { + syntaxPrefix = "glob:"; + } + + String expression = filterPattern; + if (isRegex || isGlob) { + int colonIndex = expression.indexOf(':'); + if (colonIndex + 1 >= expression.length()) { + throw new RuntimeException("Invalid filter: " + expression); + } + expression = filterPattern.substring(colonIndex + 1); + exclude = expression.charAt(0) == '!'; + if (exclude) { + expression = expression.substring(1); + filterPattern = syntaxPrefix.concat(expression); + } + pathMatcher = FileSystems.getDefault().getPathMatcher(filterPattern); + } + + return new MemberAccessFilter(pathMatcher, memberSignature, syntaxPrefix, expression, exclude); + } + + @Override + public boolean match(String target, boolean resolveProguardName) { + return this.matchClassElement(target, "", "()"); + } +} diff --git a/src/main/java/com/licel/stringer/IntegrityControlParams.java b/src/main/java/com/licel/stringer/IntegrityControlParams.java new file mode 100644 index 0000000..54b31fb --- /dev/null +++ b/src/main/java/com/licel/stringer/IntegrityControlParams.java @@ -0,0 +1,56 @@ +package com.licel.stringer; + +public class IntegrityControlParams extends FilteredParams { + private final CheckByteCodeParams checkBytecode = new CheckByteCodeParams(); + private final CheckJarParams checkJar = new CheckJarParams(); + private final SealJarParams sealJar = new SealJarParams(); + private final OsgiCompatibility osgiCompatibility = new OsgiCompatibility(); + + public IntegrityControlParams() { + this.name = "integrityControl"; + } + + public CheckByteCodeParams checkBytecode() { + return this.checkBytecode; + } + + public CheckJarParams checkJar() { + return this.checkJar; + } + + public SealJarParams sealJar() { + return this.sealJar; + } + + public OsgiCompatibility osgiCompatibility() { + return this.osgiCompatibility; + } + + public class CheckByteCodeParams extends Params { + CheckByteCodeParams() { + this.enabled = false; + this.name = "checkBytecode"; + } + } + + public class CheckJarParams extends Params { + CheckJarParams() { + this.enabled = true; + this.name = "checkJar"; + } + } + + public class SealJarParams extends Params { + SealJarParams() { + this.enabled = false; + this.name = "sealJar"; + } + } + + public class OsgiCompatibility extends Params { + OsgiCompatibility() { + this.enabled = false; + this.name = "osgiCompatibility"; + } + } +} diff --git a/src/main/java/com/licel/stringer/Params.java b/src/main/java/com/licel/stringer/Params.java new file mode 100644 index 0000000..4da94fb --- /dev/null +++ b/src/main/java/com/licel/stringer/Params.java @@ -0,0 +1,18 @@ +package com.licel.stringer; + +public class Params { + protected String name; + protected boolean enabled = false; + + public String getName() { + return this.name; + } + + public boolean isEnabled() { + return this.enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } +} diff --git a/src/main/java/com/licel/stringer/PersonalizationProfile.java b/src/main/java/com/licel/stringer/PersonalizationProfile.java new file mode 100644 index 0000000..765cd08 --- /dev/null +++ b/src/main/java/com/licel/stringer/PersonalizationProfile.java @@ -0,0 +1,55 @@ +package com.licel.stringer; + +import java.util.HashMap; +import java.util.Map; +import org.apache.commons.jexl3.JexlBuilder; +import org.apache.commons.jexl3.JexlEngine; +import org.apache.commons.jexl3.JxltEngine; +import org.apache.commons.jexl3.JxltEngine.Expression; +import org.apache.commons.jexl3.MapContext; + +public class PersonalizationProfile extends FilteredParams { + private static final JexlEngine JEXL_ENGINE = new JexlBuilder().silent(true).cache(128).strict(false).create(); + private static final JxltEngine JXLT_ENGINE = JEXL_ENGINE.createJxltEngine(); + + private String noticeTemplate = "AV contact email - primary@licelus.com"; + private Expression noticeExpression = JXLT_ENGINE.createExpression(this.noticeTemplate); + private String protectedByTemplate = "${stringer.version} Stringer (${stringer.buildId})"; + private Expression protectedByExpression = JXLT_ENGINE.createExpression(this.protectedByTemplate); + private final Map variables = new HashMap<>(); + + public PersonalizationProfile() { + this.variables.put("stringer.version", ProductInfo.getVersion()); + this.variables.put("stringer.buildId", ProductInfo.getBuildId()); + } + + public void put(String key, Object value) { + this.variables.put(key, value); + } + + public String evaluateNotice() { + return String.valueOf(this.noticeExpression.evaluate(new MapContext(this.variables))); + } + + public void setNoticeTemplate(String template) { + this.noticeTemplate = template; + this.noticeExpression = JXLT_ENGINE.createExpression(template); + } + + public String getNoticeTemplate() { + return this.noticeTemplate; + } + + public String evaluateProtectedBy() { + return String.valueOf(this.protectedByExpression.evaluate(new MapContext(this.variables))); + } + + public void setProtectedByTemplate(String template) { + this.protectedByTemplate = template; + this.protectedByExpression = JXLT_ENGINE.createExpression(template); + } + + public String getProtectedByTemplate() { + return this.protectedByTemplate; + } +} diff --git a/src/main/java/com/licel/stringer/ProductInfo.java b/src/main/java/com/licel/stringer/ProductInfo.java new file mode 100644 index 0000000..0cc082c --- /dev/null +++ b/src/main/java/com/licel/stringer/ProductInfo.java @@ -0,0 +1,38 @@ +package com.licel.stringer; + +import java.util.ResourceBundle; + +public final class ProductInfo { + private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("productInfo"); + + private ProductInfo() { + } + + public static String getTitle() { + return RESOURCE_BUNDLE.getString("title"); + } + + public static String getConsoleTitle() { + return RESOURCE_BUNDLE.getString("consoleTitle"); + } + + public static String getVendor() { + return RESOURCE_BUNDLE.getString("vendor"); + } + + public static String getVersion() { + return RESOURCE_BUNDLE.getString("version"); + } + + public static String getBuildId() { + return RESOURCE_BUNDLE.getString("buildId"); + } + + public static String getInfoText() { + String lineSeparator = System.lineSeparator(); + return getTitle() + lineSeparator + + "Version: " + getVersion() + lineSeparator + + "Build id: " + getBuildId() + lineSeparator + + "Vendor: " + getVendor(); + } +} diff --git a/src/main/java/com/licel/stringer/ProtectionElementParams.java b/src/main/java/com/licel/stringer/ProtectionElementParams.java new file mode 100644 index 0000000..3f2d26b --- /dev/null +++ b/src/main/java/com/licel/stringer/ProtectionElementParams.java @@ -0,0 +1,137 @@ +package com.licel.stringer; + +import java.util.ArrayList; +import org.objectweb.asm.Opcodes; + +public class ProtectionElementParams extends FilteredParams { + protected ArrayList paths = null; + protected StringEncryptionParams stringEncryption = new StringEncryptionParams(); + protected IntegrityControlParams integrityControl = new IntegrityControlParams(); + protected HideAccessParams hideAccess = new HideAccessParams(); + protected ResourceEncryptionParams resourceEncryption = new ResourceEncryptionParams(); + protected String target; + protected int targetInt = 0; + + public ArrayList getPaths() { + return this.paths; + } + + public void setPaths(ArrayList paths) { + this.paths = paths; + } + + public void addPath(String path) { + if (this.paths == null) { + this.paths = new ArrayList<>(); + } + this.paths.add(path); + } + + public String getPathsString() { + if (this.paths == null) { + return ""; + } + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < this.paths.size(); i++) { + builder.append(this.paths.get(i)).append(';'); + } + if (builder.length() > 0 && builder.charAt(builder.length() - 1) == ';') { + builder.deleteCharAt(builder.length() - 1); + } + return builder.toString(); + } + + public StringEncryptionParams getStringEncryption() { + return this.stringEncryption; + } + + public void setStringEncryption(StringEncryptionParams stringEncryption) { + this.stringEncryption = stringEncryption; + } + + public IntegrityControlParams getIntegrityControl() { + return this.integrityControl; + } + + public void setIntegrityControl(IntegrityControlParams integrityControl) { + this.integrityControl = integrityControl; + } + + public HideAccessParams getHideAccess() { + return this.hideAccess; + } + + public void setHideAccess(HideAccessParams hideAccess) { + this.hideAccess = hideAccess; + } + + public ResourceEncryptionParams getResourceEncryption() { + return this.resourceEncryption; + } + + public void setResourceEncryption(ResourceEncryptionParams resourceEncryption) { + this.resourceEncryption = resourceEncryption; + } + + public String getTarget() { + return this.target; + } + + public int getTargetInt() { + return this.targetInt; + } + + public void setTarget(String target) { + this.target = target; + if (target != null) { + try { + this.targetInt = (Integer) Opcodes.class.getField("V" + target.replace('.', '_')).get(null); + } catch (Throwable ex) { + throw new RuntimeException("Incorrect value of target bytecode version: " + target + ". Allowed values are 1.5, 1.6, 1.7, 1.8, 9."); + } + } + } + + public void dump(WorkerListener listener) { + listener.verbose(" protectionElement path: " + this.getPathsString()); + if (this.getTarget() != null) { + listener.verbose(" force bytecode target: " + this.getTarget() + "(" + this.getTargetInt() + ")"); + } + + listener.verbose(" string encryption: "); + listener.verbose(" enabled: " + this.stringEncryption.isEnabled()); + listener.verbose(" checkCaller: " + this.stringEncryption.isCheckCaller()); + listener.verbose(" equalsIntrinsicEnabled: " + this.stringEncryption.isEqualsIntrinsicEnabled()); + listener.verbose(" annotations: " + this.stringEncryption.isAnnotations()); + listener.verbose(" filtered: " + this.stringEncryption.isFiltered()); + if (this.stringEncryption.filters != null) { + listener.verbose(" filter: " + this.stringEncryption.getFilterString(";")); + } + + listener.verbose(" hide access: "); + listener.verbose(" enabled: " + this.hideAccess.isEnabled()); + listener.verbose(" annotations: " + this.hideAccess.isAnnotations()); + listener.verbose(" filtered: " + this.hideAccess.isFiltered()); + if (this.hideAccess.filters != null) { + listener.verbose(" filter: " + this.hideAccess.getFilterString(";")); + } + + listener.verbose(" resource encryption: "); + listener.verbose(" enabled: " + this.resourceEncryption.isEnabled()); + listener.verbose(" filtered: " + this.resourceEncryption.isFiltered()); + if (this.resourceEncryption.filters != null) { + listener.verbose(" filter: " + this.resourceEncryption.getFilterString(";")); + } + + listener.verbose(" integrity control: "); + listener.verbose(" enabled: " + this.integrityControl.isEnabled()); + listener.verbose(" checkBytecode: " + this.integrityControl.checkBytecode().isEnabled()); + listener.verbose(" checkJar: " + this.integrityControl.checkJar().isEnabled()); + listener.verbose(" sealJar: " + this.integrityControl.sealJar().isEnabled()); + listener.verbose(" osgiCompatibility: " + this.integrityControl.osgiCompatibility().isEnabled()); + listener.verbose(" filtered: " + this.integrityControl.isFiltered()); + if (this.integrityControl.filters != null) { + listener.verbose(" filter: " + this.integrityControl.getFilterString(";")); + } + } +} diff --git a/src/main/java/com/licel/stringer/ProtectionElementParamsContainer.java b/src/main/java/com/licel/stringer/ProtectionElementParamsContainer.java new file mode 100644 index 0000000..b103b99 --- /dev/null +++ b/src/main/java/com/licel/stringer/ProtectionElementParamsContainer.java @@ -0,0 +1,17 @@ +package com.licel.stringer; + +import java.util.ArrayList; + +public class ProtectionElementParamsContainer extends FilteredParams { + protected ArrayList elements = new ArrayList<>(); + + public ProtectionElementParams createElement() { + ProtectionElementParams element = new ProtectionElementParams(); + this.elements.add(element); + return element; + } + + public ArrayList getElements() { + return this.elements; + } +} diff --git a/src/main/java/com/licel/stringer/ResourceEncryptionParams.java b/src/main/java/com/licel/stringer/ResourceEncryptionParams.java new file mode 100644 index 0000000..72b2643 --- /dev/null +++ b/src/main/java/com/licel/stringer/ResourceEncryptionParams.java @@ -0,0 +1,39 @@ +package com.licel.stringer; + +public class ResourceEncryptionParams extends FilteredParams { + private boolean generateStdWrappers = false; + private boolean generateWebContaineWrappers = false; + + public ResourceEncryptionParams() { + this.name = "resourceEncryption"; + } + + @Override + public boolean match(String target) { + return this.match(target, false); + } + + @Override + public void setEnabled(boolean enabled) { + super.setEnabled(enabled); + if (enabled) { + this.generateStdWrappers = true; + } + } + + public boolean isGenerateStdWrappers() { + return this.generateStdWrappers; + } + + public void setGenerateStdWrappers(boolean generateStdWrappers) { + this.generateStdWrappers = generateStdWrappers; + } + + public boolean isGenerateWebContaineWrappers() { + return this.generateWebContaineWrappers; + } + + public void setGenerateWebContaineWrappers(boolean generateWebContaineWrappers) { + this.generateWebContaineWrappers = generateWebContaineWrappers; + } +} diff --git a/src/main/java/com/licel/stringer/StringEncryptionParams.java b/src/main/java/com/licel/stringer/StringEncryptionParams.java new file mode 100644 index 0000000..9a8e871 --- /dev/null +++ b/src/main/java/com/licel/stringer/StringEncryptionParams.java @@ -0,0 +1,36 @@ +package com.licel.stringer; + +public class StringEncryptionParams extends FilteredParams { + public static final String ANNOTATION = "Lcom/stringer/annotations/StringEncryption;"; + + private boolean checkCaller = true; + private boolean equalsIntrinsicEnabled = false; + + public StringEncryptionParams() { + this.name = "stringEncryption"; + } + + public boolean isCheckCaller() { + return this.checkCaller; + } + + public void setCheckCaller(boolean checkCaller) { + this.checkCaller = checkCaller; + } + + public boolean isEqualsIntrinsicEnabled() { + return this.equalsIntrinsicEnabled; + } + + public void setEqualsIntrinsicEnabled(boolean equalsIntrinsicEnabled) { + this.equalsIntrinsicEnabled = equalsIntrinsicEnabled; + } + + public boolean isInternStrings() { + return this.equalsIntrinsicEnabled; + } + + public void setInternStrings(boolean equalsIntrinsicEnabled) { + this.equalsIntrinsicEnabled = equalsIntrinsicEnabled; + } +} diff --git a/src/main/java/com/licel/stringer/Watermark.java b/src/main/java/com/licel/stringer/Watermark.java new file mode 100644 index 0000000..ce95206 --- /dev/null +++ b/src/main/java/com/licel/stringer/Watermark.java @@ -0,0 +1,198 @@ +package com.licel.stringer; + +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.util.jar.Attributes; +import java.util.jar.Manifest; +import java.util.zip.Adler32; +import org.bouncycastle.util.encoders.Base64; +import org.zeroturnaround.zip.ZipUtil; +import org.zeroturnaround.zip.commons.FileUtilsV2_2; + +public class Watermark { + private byte[] identitySha1; + private byte[] identityMd5; + private int versionNumber; + private String version; + private String buildId; + private byte[] combinedSha1; + private byte[] combinedMd5; + private Config config; + + public Watermark() { + } + + public Watermark(Config config, File sourceFile) throws IOException, NoSuchAlgorithmException { + this.config = config; + MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); + MessageDigest md5 = MessageDigest.getInstance("MD5"); + byte[] buffer = new byte[1024]; + + byte[] identitySeed = ProductInfo.getVendor().getBytes(StandardCharsets.UTF_8); + sha1.update(identitySeed); + md5.update(identitySeed); + + this.identitySha1 = sha1.digest(); + this.identityMd5 = md5.digest(); + + File tempZip = null; + if (sourceFile.isDirectory() && sourceFile.list().length == 0) { + SecureRandom random = Worker.get().secureRandom; + random.nextBytes(buffer); + sha1.update(buffer, 0, buffer.length); + md5.update(buffer, 0, buffer.length); + } else { + File targetToHash; + if (sourceFile.isDirectory()) { + tempZip = File.createTempFile(sourceFile.getName(), "zip"); + ZipUtil.pack(sourceFile, tempZip, 0); + targetToHash = tempZip; + } else { + targetToHash = sourceFile; + } + + try (RandomAccessFile raf = new RandomAccessFile(targetToHash, "r")) { + int read; + while ((read = raf.read(buffer)) > 0) { + sha1.update(buffer, 0, read); + md5.update(buffer, 0, read); + } + } finally { + if (tempZip != null) { + FileUtilsV2_2.deleteQuietly(tempZip); + } + } + } + + this.combinedSha1 = sha1.digest(); + this.combinedMd5 = md5.digest(); + this.version = ProductInfo.getVersion(); + this.versionNumber = Integer.parseInt(this.version.replace(".", "")); + this.buildId = ProductInfo.getBuildId(); + } + + public byte[] generateHeader(SecureRandom random) { + byte[] header = new byte[]{0, 0, 68, 69, 88, 80, 0, 0}; + random.nextInt(); + + int salt; + do { + salt = random.nextInt() >>> 16; + } while (Integer.bitCount(salt) % 2 != 1); + + byte[] saltBytes = shortToBytes((short) salt, true); + System.arraycopy(saltBytes, 0, header, 0, saltBytes.length); + byte[] versionBytes = shortToBytes((short) this.versionNumber, true); + System.arraycopy(versionBytes, 0, header, header.length - versionBytes.length, versionBytes.length); + this.xorWithKey(header, 2, saltBytes); + return header; + } + + public Manifest createManifest(SecureRandom random) { + Manifest manifest = new Manifest(); + if (!this.config.getPersonalizationProfile().getProtectedByTemplate().trim().isEmpty()) { + manifest.getMainAttributes().putValue("Protected-By", this.config.getPersonalizationProfile().evaluateProtectedBy()); + } + if (!this.config.getPersonalizationProfile().getNoticeTemplate().trim().isEmpty()) { + manifest.getMainAttributes().putValue("Protected-Notice", this.config.getPersonalizationProfile().evaluateNotice()); + } + + random.nextInt(); + int salt; + do { + salt = random.nextInt(); + } while (Integer.bitCount(salt) % 2 != 1); + + byte[] saltBytes = intToBytes(salt, true); + byte[] signatureData = new byte[saltBytes.length + this.identityMd5.length + this.combinedMd5.length]; + System.arraycopy(saltBytes, 0, signatureData, 0, saltBytes.length); + System.arraycopy(this.identityMd5, 0, signatureData, saltBytes.length, this.identityMd5.length); + System.arraycopy(this.combinedMd5, 0, signatureData, saltBytes.length + this.identityMd5.length, this.combinedMd5.length); + this.xorWithKey(signatureData, 4, saltBytes); + + Attributes mainAttributes = manifest.getMainAttributes(); + mainAttributes.putValue("JAR-Signature", new String(Base64.encode(signatureData), StandardCharsets.US_ASCII)); + return manifest; + } + + public byte[] generateExtraField(SecureRandom random) { + byte[] header = this.generateHeader(random); + byte[] payload = new byte[this.identitySha1.length + this.combinedSha1.length + 4]; + byte[] mask = new byte[4]; + random.nextBytes(mask); + byte[] result = new byte[header.length + mask.length + payload.length]; + + System.arraycopy(this.identitySha1, 0, payload, 0, this.identitySha1.length); + System.arraycopy(this.combinedSha1, 0, payload, this.identitySha1.length, this.combinedSha1.length); + Adler32 checksum = new Adler32(); + checksum.update(payload, 0, this.identitySha1.length + this.combinedSha1.length); + byte[] checksumBytes = intToBytes((int) checksum.getValue(), true); + System.arraycopy(checksumBytes, 0, payload, this.identitySha1.length + this.combinedSha1.length, checksumBytes.length); + + this.xorWithKey(payload, 0, mask); + System.arraycopy(header, 0, result, 0, header.length); + System.arraycopy(mask, 0, result, header.length, mask.length); + System.arraycopy(payload, 0, result, header.length + mask.length, payload.length); + return result; + } + + public byte[] generateKeyBlock(SecureRandom random) { + byte[] header = this.generateHeader(random); + byte[] payload = new byte[this.identitySha1.length + this.combinedSha1.length + 4]; + byte[] mask = new byte[payload.length]; + random.nextBytes(mask); + byte[] result = new byte[header.length + payload.length + mask.length]; + + System.arraycopy(this.identitySha1, 0, payload, 0, this.identitySha1.length); + System.arraycopy(this.combinedSha1, 0, payload, this.identitySha1.length, this.combinedSha1.length); + Adler32 checksum = new Adler32(); + checksum.update(payload, 0, this.identitySha1.length + this.combinedSha1.length); + byte[] checksumBytes = intToBytes((int) checksum.getValue(), true); + System.arraycopy(checksumBytes, 0, payload, this.identitySha1.length + this.combinedSha1.length, checksumBytes.length); + + this.xorWithKey(payload, 0, mask); + System.arraycopy(header, 0, result, 0, header.length); + System.arraycopy(payload, 0, result, header.length, payload.length); + System.arraycopy(mask, 0, result, header.length + payload.length, mask.length); + return result; + } + + private void xorWithKey(byte[] data, int startOffset, byte[] key) { + for (int i = 0; i < data.length - startOffset; i++) { + data[i + startOffset] = (byte) (data[i + startOffset] ^ (key[i % key.length] & 0xFF)); + } + } + + public static byte[] intToBytes(int value, boolean littleEndian) { + byte[] bytes = new byte[4]; + if (littleEndian) { + bytes[0] = (byte) (value & 0xFF); + bytes[1] = (byte) (value >> 8 & 0xFF); + bytes[2] = (byte) (value >> 16 & 0xFF); + bytes[3] = (byte) (value >> 24 & 0xFF); + } else { + bytes[3] = (byte) (value & 0xFF); + bytes[2] = (byte) (value >> 8 & 0xFF); + bytes[1] = (byte) (value >> 16 & 0xFF); + bytes[0] = (byte) (value >> 24 & 0xFF); + } + return bytes; + } + + public static byte[] shortToBytes(short value, boolean littleEndian) { + byte[] bytes = new byte[2]; + if (littleEndian) { + bytes[0] = (byte) (value & 0xFF); + bytes[1] = (byte) (value >> 8 & 0xFF); + } else { + bytes[1] = (byte) (value & 0xFF); + bytes[0] = (byte) (value >> 8 & 0xFF); + } + return bytes; + } +} diff --git a/src/main/java/com/licel/stringer/Worker.java b/src/main/java/com/licel/stringer/Worker.java new file mode 100644 index 0000000..b6f275e --- /dev/null +++ b/src/main/java/com/licel/stringer/Worker.java @@ -0,0 +1,1190 @@ +package com.licel.stringer; + +import com.licel.stringer.analysis.ClassMetadataCollector; +import com.licel.stringer.config.PatternMatchUtils; +import com.licel.stringer.crypto.AESFast; +import com.licel.stringer.crypto.CryptoContainer; +import com.licel.stringer.crypto.SipHash; +import com.licel.stringer.io.DirectoryResourcesOutput; +import com.licel.stringer.io.DirectorySourceIterator; +import com.licel.stringer.io.JarIndex; +import com.licel.stringer.io.ResourceEntry; +import com.licel.stringer.io.ResourcesOutput; +import com.licel.stringer.io.SourceIterator; +import com.licel.stringer.io.ZipResourcesOutput; +import com.licel.stringer.io.ZipSourceIterator; +import com.licel.stringer.model.ClassInfo; +import com.licel.stringer.model.ClassMemberInfo; +import com.licel.stringer.model.Job; +import com.licel.stringer.model.PackageProtectionInfo; +import com.licel.stringer.model.ProtectionRegistry; +import com.licel.stringer.model.ResourceBundleInfo; +import com.licel.stringer.model.SigningIdentity; +import com.licel.stringer.naming.AlphabeticNameGenerator; +import com.licel.stringer.naming.NameGenerator; +import com.licel.stringer.runtime.IntrinsicsCreator; +import com.licel.stringer.runtime.LruCacheCreator; +import com.licel.stringer.runtime.ReflectionClassCreator; +import com.licel.stringer.runtime.StringDecoderInjector; +import com.licel.stringer.runtime.StringerFilterInputStreamCreator; +import com.licel.stringer.runtime.StringerInflaterCreator; +import com.licel.stringer.runtime.StringerInputStreamCreator; +import com.licel.stringer.runtime.StringerStreamHandlerFactoryCreator; +import com.licel.stringer.runtime.StringerURLConnectionCreator; +import com.licel.stringer.runtime.StringerURLHandlerCreator; +import com.licel.stringer.transform.ClassCleanupTransformer; +import com.licel.stringer.transform.ClassEncryptionTransformer; +import com.licel.stringer.transform.ClassNameRemappingTransformer; +import com.licel.stringer.transform.ClassOptimizationTransformer; +import com.licel.stringer.transform.ClassProtectionTransformer; +import com.licel.stringer.transform.ClassTransformer; +import com.licel.stringer.transform.FieldInitializationTransformer; +import com.licel.stringer.transform.IntrinsicsTransformer; +import com.licel.stringer.transform.ResourceReflectionTransformer; +import com.licel.stringer.transform.RuntimeClassTransformer; +import com.licel.stringer.transform.StringDecoderTransformer; +import com.licel.stringer.util.StringerUtils; +import com.licel.stringer.webapp.CatalinaApplicationContextWrapperCreator; +import com.licel.stringer.webapp.WebContextClassLoaderCreator; +import com.licel.stringer.webapp.WebContextLoaderListenerCreator; +import com.licel.stringer.webapp.WebXmlCompiler; +import java.io.BufferedInputStream; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Properties; +import java.util.PropertyResourceBundle; +import java.util.jar.Attributes.Name; +import java.util.jar.Manifest; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import org.apache.commons.io.FileUtils; +import org.objectweb.asm.ClassReader; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.ClassWriter; + +public class Worker { + private final Config config; + private static final ThreadLocal CONTEXT = new WorkerContextThreadLocal(); + + public static WorkerContext get() { + return CONTEXT.get(); + } + + public Worker(Config config) { + get().secureRandom = new SecureRandom(); + WorkerListener listener = config.getListener(); + this.config = config; + this.config.validate(); + + this.config.dump(listener); + get().internalNameGenerator = new AlphabeticNameGenerator(get().secureRandom); + } + + public final void stringerIt() { + this.config.getListener(); + ArrayList elementConfigs = this.config.generateProtectionElementsConfigs(); + boolean enterpriseOnly = elementConfigs.size() != 1 || elementConfigs.get(0).getPaths() != null; + if (!enterpriseOnly) { + get().processedStringCount = 0; + get().config = elementConfigs.get(0); + get().cryptoContainer = new CryptoContainer(get().secureRandom, null, true); + get().nameGenerator = new AlphabeticNameGenerator(get().secureRandom); + try { + this.executeProtection(); + } catch (RuntimeException ex) { + throw ex; + } catch (Exception ex) { + throw new RuntimeException(ex); + } + } else { + WorkerException ex = new WorkerException( + this, + "Unfortunately this functionality is supported in the enterprise version only, please visit https://jfxstore.com/stringer/request-quote to request your new-user/upgrade quote."); + ex.setStackTrace(new StackTraceElement[0]); + throw ex; + } + } + + @SuppressWarnings("unchecked") + private void executeProtection() throws Exception { + Config activeConfig = get().config; + boolean verbose = activeConfig.isVerbose(); + SecureRandom random = get().secureRandom; + WorkerListener listener = activeConfig.getListener(); + long startTime = System.currentTimeMillis(); + listener.info("[Protecting " + activeConfig.getSrcFile().getName() + "]"); + + int classesProcessed = 0; + int resourcesProcessed = 0; + HashMap seenEntries = new HashMap<>(); + get().sourceIterator = null; + + if (activeConfig.getSrcFile().isFile()) { + get().sourceIterator = new ZipSourceIterator(activeConfig.getSrcFile()); + if (!activeConfig.getDestFile().exists()) { + File parent = activeConfig.getDestFile().getParentFile(); + if (parent != null) { + parent.mkdirs(); + } + activeConfig.getDestFile().createNewFile(); + } + } else { + get().sourceIterator = new DirectorySourceIterator(activeConfig.getSrcFile()); + if (!activeConfig.getDestFile().exists()) { + activeConfig.getDestFile().mkdirs(); + } + } + + Watermark watermark = new Watermark(activeConfig, activeConfig.getSrcFile()); + SourceIterator sourceIterator = get().sourceIterator; + HashMap plan = this.buildProtectionPlan(sourceIterator, watermark); + if (plan == null) { + listener.info("[Finishing " + activeConfig.getSrcFile().getName() + "]"); + return; + } + + boolean zipOutput = false; + ResourcesOutput output; + if (activeConfig.getDestFile().isFile()) { + output = new ZipResourcesOutput(activeConfig.getDestFile(), activeConfig.isOptimize()); + zipOutput = true; + } else { + output = new DirectoryResourcesOutput(activeConfig.getSrcFile(), activeConfig.getDestFile()); + } + + output.open(); + Iterator entries = sourceIterator.entries(); + long inputBytes = 0L; + long outputBytes = 0L; + JarIndex jarIndex = null; + boolean manifestPatched = false; + + if (zipOutput) { + try (ZipFile zipFile = new ZipFile(activeConfig.getSrcFile())) { + if (zipFile.getEntry(JarIndex.INDEX_NAME) != null) { + jarIndex = new JarIndex(new String[]{activeConfig.getDestFile().getName()}); + } + } + } + + Manifest watermarkManifest = watermark.createManifest(random); + if (activeConfig.getIntegrityControl().sealJar().isEnabled()) { + watermarkManifest.getMainAttributes().putValue("Sealed", "true"); + } + + while (entries.hasNext()) { + ResourceEntry entry = entries.next(); + inputBytes += entry.getSize(); + String entryName = entry.getName(); + String normalizedName = entry.getNormalizedName(); + + if (seenEntries.containsKey(normalizedName)) { + if (verbose) { + listener.verbose("Skipping duplicate file: " + entryName); + } + continue; + } + seenEntries.put(normalizedName, null); + + if (jarIndex != null + && !entryName.equals("META-INF") + && !entryName.equals(JarIndex.INDEX_NAME) + && !entryName.equals("META-INF/MANIFEST.MF") + && entryName.startsWith("META-INF/") + && !entry.isDirectory()) { + jarIndex.addResource(entryName, activeConfig.getDestFile().getName()); + } + + if (!activeConfig.isNoneMode() + && entryName.startsWith("META-INF/") + && (entryName.endsWith(".SF") || entryName.endsWith(".RSA") || entryName.endsWith(".DSA"))) { + if (verbose) { + listener.verbose("Removing signature file: " + entryName); + } + continue; + } + + if ("META-INF/MANIFEST.MF".equals(entryName)) { + if (verbose) { + listener.verbose("Patching META-INF/MANIFEST.MF"); + } + Manifest existingManifest = new Manifest(); + try (BufferedInputStream in = new BufferedInputStream(sourceIterator.openStream(entry))) { + existingManifest.read(in); + } + existingManifest.getMainAttributes().putAll(watermarkManifest.getMainAttributes()); + output.openEntry(new ResourceEntry(entry.getName())); + ByteArrayOutputStream manifestBytes = new ByteArrayOutputStream(); + existingManifest.write(manifestBytes); + output.write(manifestBytes.toByteArray()); + manifestBytes.close(); + manifestPatched = true; + watermarkManifest.getMainAttributes().putAll(existingManifest.getMainAttributes()); + } else if (entry.isDirectory()) { + output.openEntry(new ResourceEntry(entry.getName(), true)); + } else if (plan.containsKey(normalizedName)) { + output.openEntry(new ResourceEntry(entry.getName())); + Job job = (Job) plan.get(normalizedName); + switch (job.type) { + case Job.TRANSFORM_CLASS: + classesProcessed++; + if (verbose) { + listener.verbose("Processing class: " + entryName); + } + byte[] transformed; + try (BufferedInputStream in = new BufferedInputStream(sourceIterator.openStream(entry))) { + transformed = this.applyClassTransformations(in, job); + } + outputBytes += transformed.length; + output.write(transformed); + break; + case Job.ENCRYPT_RESOURCE: + resourcesProcessed++; + if (verbose) { + listener.verbose("Processing resource: " + entryName); + } + int encryptedLength = AESFast.encryptResource( + sourceIterator.openStream(entry), + output, + get().cryptoContainer.getRoundKeys(), + get().cryptoContainer.createResourceIvWords(), + activeConfig); + outputBytes += encryptedLength; + break; + default: + break; + } + } else if (jarIndex != null && JarIndex.INDEX_NAME.equals(entryName)) { + listener.verbose("Skipping: " + entryName); + } else if (!(output instanceof DirectoryResourcesOutput) || !((DirectoryResourcesOutput) output).overwriteSource) { + outputBytes += entry.getSize(); + output.openEntry(new ResourceEntry(entry.getName())); + StringerUtils.copyStream(sourceIterator.openStream(entry), output); + } else if (verbose) { + listener.verbose("Skipping (input and output are the same directory): " + entryName); + } + } + + for (String key : plan.keySet()) { + if (key.endsWith("#newClass")) { + RuntimeClassTransformer creator = (RuntimeClassTransformer) plan.get(key); + ClassInfo createdInfo = creator.getClassInfo(); + ResourceEntry newEntry = new ResourceEntry(createdInfo.name + ".class"); + ClassWriter writer = new ClassWriter(0); + ClassVisitor visitor = creator.createVisitor(writer); + if (visitor == null) { + throw new RuntimeException("Internal error"); + } + + if (!(visitor instanceof ReflectionClassCreator) || !creator.getClassInfo().hiddenMembers.isEmpty()) { + byte[] classBytes = writer.toByteArray(); + if (plan.containsKey(newEntry.getNormalizedName() + "n")) { + try (ByteArrayInputStream in = new ByteArrayInputStream(classBytes)) { + classBytes = this.applyClassTransformations(in, (Job) plan.get(newEntry.getNormalizedName() + "n")); + } + } + if (classBytes.length == 0) { + throw new RuntimeException("Internal error"); + } + if (verbose) { + listener.verbose("Creating class: " + newEntry.getNormalizedName()); + } + if (jarIndex != null) { + jarIndex.addResource(newEntry.getName(), activeConfig.getDestFile().getName()); + } + output.openEntry(newEntry); + output.write(classBytes); + outputBytes += classBytes.length; + } + } + } + + if (jarIndex != null) { + if (verbose) { + listener.verbose("Adding: META-INF/INDEX.LIST"); + } + output.openEntry(new ResourceEntry(JarIndex.INDEX_NAME)); + ByteArrayOutputStream indexOut = new ByteArrayOutputStream(); + jarIndex.write(indexOut); + output.write(indexOut.toByteArray()); + indexOut.close(); + } + + ProtectionRegistry jarInfo = (ProtectionRegistry) get().attributes.get("jarInfo"); + if (activeConfig.isNoneMode() && !manifestPatched && jarInfo != null && !jarInfo.classes.isEmpty()) { + if (verbose) { + listener.verbose("Adding: META-INF/MANIFEST.MF"); + } + output.openEntry(new ResourceEntry("META-INF/MANIFEST.MF")); + ByteArrayOutputStream manifestOut = new ByteArrayOutputStream(); + if (watermarkManifest.getMainAttributes().get(Name.MANIFEST_VERSION) == null) { + watermarkManifest.getMainAttributes().put(Name.MANIFEST_VERSION, "1.0"); + } + watermarkManifest.write(manifestOut); + output.write(manifestOut.toByteArray()); + manifestOut.close(); + } + + sourceIterator.close(); + output.close(); + + if (!activeConfig.isNoneMode()) { + listener.info("[Signing " + activeConfig.getSrcFile().getName() + "]"); + SigningIdentity identity = StringerUtils.loadSigningIdentity(activeConfig); + File signedTemp = File.createTempFile("signed", "jar"); + StringerUtils.signJar(identity, activeConfig.getDestFile(), signedTemp, watermarkManifest); + FileUtils.deleteQuietly(activeConfig.getDestFile()); + FileUtils.moveFile(signedTemp, activeConfig.getDestFile()); + } + + Job permutationJob = (Job) plan.get("jarPermutation"); + if (permutationJob != null) { + reorderArchiveEntries((ArrayList) permutationJob.payload, activeConfig.isOptimize(), activeConfig.getDestFile(), activeConfig.getDestFile()); + } + + listener.info("[Finishing " + activeConfig.getSrcFile().getName() + "]"); + if (verbose) { + listener.verbose("Total time: " + (System.currentTimeMillis() - startTime) + "ms"); + } + listener.info("Total strings processed: " + get().processedStringCount); + listener.info("Total classes processed: " + classesProcessed); + listener.info("Total resources processed: " + resourcesProcessed); + listener.info("Total bytes processed: " + inputBytes + ", ratio " + ((double) outputBytes / inputBytes)); + } + + public static void repairArchive(File sourceFile, File destFile) throws IOException { + ZipFile sourceZip; + try { + sourceZip = new ZipFile(sourceFile); + } catch (Exception ex) { + throw new RuntimeException("Unsupported format of src file for the repair mode"); + } + + if (destFile.isDirectory()) { + sourceZip.close(); + throw new RuntimeException("In the repair mode a jar file must be set as dest"); + } + + ArrayList orderedEntries = new ArrayList<>(); + Enumeration entries = sourceZip.entries(); + boolean sawExtra = false; + + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + if (entry.getExtra() != null) { + ResourceEntry resourceEntry = new ResourceEntry(entry.getName()); + resourceEntry.setExtra(entry.getExtra()); + orderedEntries.add(resourceEntry); + sawExtra = true; + } else if (sawExtra) { + break; + } + } + + if (orderedEntries.isEmpty()) { + sourceZip.close(); + throw new RuntimeException("In the src file there is no information to perform the repair"); + } + + try { + sourceZip.close(); + } catch (Exception ignored) { + } + + reorderArchiveEntries(orderedEntries, false, sourceFile, destFile); + } + + private static void reorderArchiveEntries(ArrayList priorityEntries, boolean optimize, File sourceFile, File destFile) throws IOException { + ZipFile sourceZip = new ZipFile(sourceFile); + ZipFile destZip = new ZipFile(destFile); + HashMap remainingEntries = new HashMap<>(); + + Enumeration entries = destZip.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + remainingEntries.put(entry.getName(), entry); + } + + ZipResourcesOutput output = new ZipResourcesOutput(destFile, optimize); + output.open(); + + for (ResourceEntry priorityEntry : priorityEntries) { + ZipEntry match = remainingEntries.get(priorityEntry.getName()); + if (match == null) { + sourceZip.close(); + destZip.close(); + output.close(); + throw new RuntimeException("Internal error"); + } + output.openEntry(priorityEntry); + StringerUtils.copyStream(sourceZip.getInputStream(match), output); + remainingEntries.remove(priorityEntry.getName()); + } + + for (ZipEntry leftover : remainingEntries.values()) { + output.openEntry(new ResourceEntry(leftover.getName())); + StringerUtils.copyStream(destZip.getInputStream(leftover), output); + } + + sourceZip.close(); + destZip.close(); + output.close(); + } + + @SuppressWarnings("unchecked") + private byte[] applyClassTransformations(InputStream inputStream, Job job) throws IOException { + ClassReader reader = new ClassReader(inputStream); + ArrayList transformers = (ArrayList) job.payload; + ClassWriter writer = null; + + for (ClassTransformer transformer : transformers) { + writer = new ClassWriter(transformer.getClassWriterFlags()); + ClassVisitor visitor = transformer.createVisitor(writer); + reader.accept(visitor, 0); + reader = new ClassReader(writer.toByteArray()); + } + + return writer.toByteArray(); + } + + private ProtectionRegistry analyzeSource(SourceIterator sourceIterator) throws Exception { + WorkerListener listener = get().config.getListener(); + Config activeConfig = get().config; + boolean verbose = activeConfig.isVerbose(); + ProtectionRegistry registry = new ProtectionRegistry(); + + Properties proguardMap = new Properties(); + if (activeConfig.getProguardMapFile() != null) { + try { + proguardMap = StringerUtils.loadProguardMap(activeConfig.getProguardMapFile()); + } catch (Exception ex) { + throw new Exception("Unable to parse the proguardMapFile: " + activeConfig.getProguardMapFile()); + } + } + + ArrayList injectPatterns = null; + if (activeConfig.getInjectList() != null) { + injectPatterns = new ArrayList<>(); + for (String pattern : activeConfig.getInjectList()) { + injectPatterns.add(PatternMatchUtils.tokenizePath(pattern)); + } + } + + Iterator entries = sourceIterator.entries(); + while (entries.hasNext()) { + ResourceEntry entry = entries.next(); + String entryName = entry.getName(); + if (entryName.endsWith(".class")) { + if (entry.getNormalizedName().startsWith("com/javafx/main")) { + if (verbose) { + listener.verbose(" skipping JavaFX loader: " + entryName); + } + registry.javaFxApplication = true; + continue; + } + + try (BufferedInputStream in = new BufferedInputStream(sourceIterator.openStream(entry))) { + ClassReader reader = new ClassReader(in); + String internalName = entryName.substring(0, entryName.indexOf(".class")); + if (verbose) { + listener.verbose(" class " + entryName + (proguardMap.containsKey(internalName) ? " (" + proguardMap.getProperty(internalName) + ")" : "")); + } + + try { + ClassMetadataCollector collector = new ClassMetadataCollector(entryName, activeConfig); + try { + reader.accept(collector, 0); + } catch (ArrayIndexOutOfBoundsException ex) { + listener.verbose(" found corrupted frames, trying to skip them"); + reader.accept(collector, ClassReader.SKIP_FRAMES); + collector.classInfo.hasCorruptedFrames = true; + } + + if (injectPatterns != null) { + String matchName = collector.classInfo.name; + if (proguardMap.containsKey(matchName)) { + matchName = proguardMap.getProperty(matchName); + } + String[] tokenizedName = PatternMatchUtils.tokenizePath(matchName); + for (String[] pattern : injectPatterns) { + if (PatternMatchUtils.matchPath(pattern, tokenizedName, true)) { + collector.classInfo.inInjectList = true; + } + } + } + + registry.registerClass(collector.classInfo); + } catch (Throwable ex) { + throw new RuntimeException("Analysis of " + entryName + " class failed: " + ex.getMessage()); + } + } + } else if ("META-INF/MANIFEST.MF".equalsIgnoreCase(entry.getNormalizedName())) { + Manifest manifest = new Manifest(); + manifest.read(sourceIterator.openStream(entry)); + if (manifest.getMainAttributes().containsKey(new Name("JavaFX-Version"))) { + registry.javaFxApplication = true; + } + } else if (entry.getNormalizedName().startsWith("META-INF/") && entry.getNormalizedName().endsWith(".SF")) { + registry.containsSignature = true; + } else if (activeConfig.getResourceEncryption().isEnabled() && !entry.isDirectory()) { + boolean isMetaInf = entry.getNormalizedName().startsWith("META-INF"); + if (verbose) { + listener.verbose(" resource " + entryName + (isMetaInf ? " (skipping)" : "")); + } + if (!isMetaInf) { + PropertyResourceBundle bundle = null; + if (entryName.endsWith(".properties")) { + bundle = new PropertyResourceBundle(sourceIterator.openStream(entry)); + } + registry.registerResourceBundle(new ResourceBundleInfo(entryName, bundle)); + } + } + } + + return registry; + } + + private String generateClassName(PackageProtectionInfo pkgInfo, String outerClassName, boolean allowInner) { + ArrayList candidates = pkgInfo.getDecoderHostCandidates(); + boolean useInnerNaming = candidates.size() >= 2 & allowInner; + String baseName = outerClassName; + int attempts = 0; + + if (baseName == null && useInnerNaming) { + baseName = get().nameGenerator.pickRandom(candidates); + while (baseName.contains("$")) { + if (++attempts > 10) { + useInnerNaming = false; + break; + } + baseName = get().nameGenerator.pickRandom(candidates); + } + } + + attempts = 0; + int nameLength = 3; + if (baseName == null) { + baseName = pkgInfo.getPackagePath() + get().internalNameGenerator.generateRandomIdentifier(3); + while (pkgInfo.getClasses().containsKey(baseName)) { + if (++attempts > 10) { + nameLength++; + } + baseName = pkgInfo.getPackagePath() + get().internalNameGenerator.generateRandomIdentifier(nameLength); + } + return baseName; + } + + int counter = 0; + String suffix = useInnerNaming + ? get().nameGenerator.pickRandom(candidates).substring(pkgInfo.getPackagePath().length()) + : Integer.toString(counter++); + String prefix = baseName + '$'; + String generated = prefix + suffix; + + for (int tries = 0; pkgInfo.getClasses().containsKey(generated); tries++) { + if (tries > 10) { + useInnerNaming = false; + } + generated = prefix + (useInnerNaming + ? get().nameGenerator.pickRandom(candidates).substring(pkgInfo.getPackagePath().length()) + : Integer.toString(counter++)); + } + + return generated; + } + + private Properties allocateRuntimeClass( + ProtectionRegistry registry, + PackageProtectionInfo pkgInfo, + HashMap plan, + boolean forceNewClass, + int creatorKind, + String superName, + Properties methodTemplates, + Properties fieldTemplates, + int classFileVersion) { + return this.allocateRuntimeClass( + registry, pkgInfo, plan, forceNewClass, creatorKind, null, superName, null, methodTemplates, fieldTemplates, classFileVersion); + } + + private Properties allocateRuntimeClass( + ProtectionRegistry registry, + PackageProtectionInfo pkgInfo, + HashMap plan, + boolean forceNewClass, + int creatorKind, + String superName, + String explicitClassName, + Properties methodTemplates, + Properties fieldTemplates, + int classFileVersion) { + return this.allocateRuntimeClass( + registry, pkgInfo, plan, forceNewClass, creatorKind, null, superName, explicitClassName, methodTemplates, fieldTemplates, classFileVersion); + } + + private Properties allocateRuntimeClass( + ProtectionRegistry registry, + PackageProtectionInfo pkgInfo, + HashMap plan, + boolean forceNewClass, + int creatorKind, + Object creatorPayload, + String superName, + String explicitClassName, + Properties methodTemplates, + Properties fieldTemplates, + int classFileVersion) { + WorkerListener listener = get().config.getListener(); + Config activeConfig = get().config; + boolean verbose = activeConfig.isVerbose(); + + ArrayList hostCandidates = pkgInfo.getDecoderHostCandidates(); + boolean createNew = hostCandidates.isEmpty() || forceNewClass; + String targetClassName = explicitClassName != null + ? explicitClassName + : (!createNew ? get().nameGenerator.pickRandom(hostCandidates) : this.generateClassName(pkgInfo, null, true)); + + if (verbose) { + listener.verbose(" " + (createNew ? "new" : "existing") + " class for injects: " + targetClassName); + } + + Properties generatedMappings = new Properties(); + ClassInfo classInfo; + if (createNew) { + classInfo = new ClassInfo(targetClassName); + classInfo.isGeneratedClass = true; + registry.registerClass(classInfo); + plan.put( + pkgInfo.getPackagePath() + "." + targetClassName + ".#newClass", + new RuntimeClassTransformer(null, creatorKind, classFileVersion, targetClassName, superName, creatorPayload)); + } else { + classInfo = pkgInfo.getClasses().get(targetClassName); + classInfo.isDecoderHost = true; + } + + Enumeration methodKeys = methodTemplates.keys(); + while (methodKeys.hasMoreElements()) { + String key = (String) methodKeys.nextElement(); + String descriptor = methodTemplates.getProperty(key); + String generatedName = get().internalNameGenerator.generateMethodName(classInfo, descriptor, null); + classInfo.declaredMethods.add(new ClassMemberInfo(0, generatedName, descriptor)); + generatedMappings.setProperty(key, generatedName); + if (verbose) { + listener.verbose(" adding method: " + generatedName + descriptor); + } + } + + Enumeration fieldKeys = fieldTemplates.keys(); + while (fieldKeys.hasMoreElements()) { + String key = (String) fieldKeys.nextElement(); + String descriptor = fieldTemplates.getProperty(key); + String generatedName = get().internalNameGenerator.generateFieldName(classInfo, descriptor); + classInfo.declaredFields.add(new ClassMemberInfo(0, generatedName, descriptor)); + generatedMappings.setProperty(key, generatedName); + if (verbose) { + listener.verbose(" adding field: " + generatedName); + } + } + + generatedMappings.setProperty("className", targetClassName); + pkgInfo.evaluateProtection(activeConfig, registry); + return generatedMappings; + } + + private Job createRemapJob( + Properties generatedMappings, + String prototypeInternalName, + Properties methodTemplates, + Properties fieldTemplates, + Properties globalRemapTable) { + for (Object keyObj : generatedMappings.keySet()) { + String key = (String) keyObj; + if (fieldTemplates.containsKey(key)) { + globalRemapTable.setProperty(prototypeInternalName + "." + key + "." + fieldTemplates.getProperty(key), generatedMappings.getProperty(key)); + } else if (methodTemplates.containsKey(key)) { + globalRemapTable.setProperty(prototypeInternalName + "." + key + "." + methodTemplates.getProperty(key), generatedMappings.getProperty(key)); + } + } + + String mappedClassName = generatedMappings.getProperty("className"); + globalRemapTable.setProperty(prototypeInternalName, mappedClassName); + ArrayList transformers = new ArrayList<>(); + transformers.add(new ClassNameRemappingTransformer(new ClassInfo(mappedClassName), globalRemapTable)); + return new Job(Job.TRANSFORM_CLASS, transformers); + } + + @SuppressWarnings("unchecked") + private HashMap buildProtectionPlan(SourceIterator sourceIterator, Watermark watermark) throws Exception { + WorkerListener listener = get().config.getListener(); + Config activeConfig = get().config; + boolean verbose = activeConfig.isVerbose(); + listener.info("[Analyzing " + activeConfig.getSrcFile().getName() + "]"); + + HashMap plan = new HashMap<>(); + ProtectionRegistry registry = this.analyzeSource(sourceIterator); + NameGenerator primaryNames = get().nameGenerator; + NameGenerator internalNames = get().internalNameGenerator; + + if (verbose) { + listener.verbose("Is it a JavaFx application: " + registry.javaFxApplication); + } + if (verbose && activeConfig.getHideAccess().isEnabled()) { + listener.verbose("Classes to inject the security control: " + registry.classesWithMethodRefs + "/" + registry.classesWithoutMethodRefs); + } + if (verbose && activeConfig.getResourceEncryption().isEnabled() && activeConfig.getResourceEncryption().isGenerateStdWrappers()) { + listener.verbose("Use ResourceBundle.getBundle(..): " + registry.usesResourceBundle); + listener.verbose("Use Class/ClassLoader.getResource(..)/getResourceAsStream(..): " + registry.usesResourceStreams); + } + + listener.info("Contains signature: " + registry.containsSignature); + if (registry.containsSignature && activeConfig.isNoneMode()) { + return null; + } + + byte[] jarCheckSalt = null; + boolean checkJarEnabled = activeConfig.getIntegrityControl().isEnabled() + && activeConfig.getIntegrityControl().checkJar().isEnabled() + && sourceIterator instanceof ZipSourceIterator; + if (checkJarEnabled) { + jarCheckSalt = new byte[2]; + get().secureRandom.nextBytes(jarCheckSalt); + } + + Properties runtimeRemapTable = new Properties(); + PackageProtectionInfo runtimePackage = new PackageProtectionInfo("!"); + Properties lruCacheMappings = null; + Properties intrinsicsMappings = null; + + if (!registry.classes.isEmpty() || activeConfig.isForceGenerateInternalLibPkg()) { + String generatedPkg = internalNames.generateRandomIdentifier(3, true) + "/" + internalNames.generateRandomIdentifier(3, true) + "/"; + while (registry.packages.containsKey(generatedPkg) + || generatedPkg.endsWith("file/") + || generatedPkg.endsWith("ftp/") + || generatedPkg.endsWith("gopher/") + || generatedPkg.endsWith("http/") + || generatedPkg.endsWith("https/") + || generatedPkg.endsWith("jar/") + || generatedPkg.endsWith("mailto/") + || generatedPkg.endsWith("netdoc/")) { + generatedPkg = internalNames.generateRandomIdentifier(3, true) + "/" + internalNames.generateRandomIdentifier(3, true) + "/"; + } + + runtimePackage = new PackageProtectionInfo(generatedPkg); + String protocolName = runtimePackage.getPackagePath().split("/")[1]; + registry.packages.put(generatedPkg, runtimePackage); + if (verbose) { + listener.verbose("Stringer protocol name: " + protocolName + ", pkg: " + runtimePackage.getPackagePath()); + } + + if (activeConfig.getStringEncryption().isEqualsIntrinsicEnabled()) { + intrinsicsMappings = this.allocateRuntimeClass( + registry, runtimePackage, plan, true, RuntimeClassTransformer.KIND_INTRINSICS, + "java/lang/Object", IntrinsicsCreator.METHOD_MAPPINGS, IntrinsicsCreator.FIELD_MAPPINGS, 49); + } + + lruCacheMappings = this.allocateRuntimeClass( + registry, runtimePackage, plan, true, RuntimeClassTransformer.KIND_LRU_CACHE, + "java/lang/Object", LruCacheCreator.METHOD_MAPPINGS, LruCacheCreator.FIELD_MAPPINGS, 49); + plan.put( + lruCacheMappings.getProperty("className") + ".classn", + this.createRemapJob( + lruCacheMappings, + "com/licel/stringer/LruCachePrototype", + LruCacheCreator.METHOD_MAPPINGS, + LruCacheCreator.FIELD_MAPPINGS, + runtimeRemapTable)); + } + + Collection allPackages = registry.packages.values(); + for (PackageProtectionInfo pkgInfo : allPackages) { + pkgInfo.evaluateProtection(activeConfig, registry); + if (pkgInfo.isSkipped() && !pkgInfo.getPackagePath().equals(runtimePackage.getPackagePath())) { + if (verbose) { + listener.verbose("Skipping: " + pkgInfo.getPackagePath()); + } + continue; + } + + if (verbose) { + listener.verbose("Processing package: " + pkgInfo.getPackagePath()); + } + + primaryNames.setMethodNameCandidates(pkgInfo.getMethodNameCandidates("")); + primaryNames.setFieldNameCandidates(pkgInfo.getFieldNameCandidates("")); + internalNames.setMethodNameCandidates(pkgInfo.getMethodNameCandidates("")); + internalNames.setFieldNameCandidates(pkgInfo.getFieldNameCandidates("")); + + int decoderCount = pkgInfo.getProtectedClassCount() / 10 + 1; + if (decoderCount > 5) { + decoderCount = 5; + } + if (decoderCount == 1 && activeConfig.getHideAccess().isEnabled()) { + decoderCount = 3; + } + + CryptoContainer[] containers = new CryptoContainer[decoderCount]; + Properties[] decoderProps = new Properties[decoderCount]; + HashMap decoderClassIndexMap = new HashMap<>(); + + for (int i = 0; i < decoderCount; i++) { + containers[i] = new CryptoContainer(get().secureRandom, watermark, false); + String[] extraTypes = {"I", "B", "S", "Z"}; + Properties methodTemplates = new Properties(); + methodTemplates.putAll(StringDecoderInjector.METHOD_MAPPINGS); + String extraSignature = extraTypes[get().secureRandom.nextInt(extraTypes.length)] + + extraTypes[get().secureRandom.nextInt(extraTypes.length)]; + methodTemplates.put("decryptString", "(Ljava/lang/Object;I" + extraSignature + ")Ljava/lang/String;"); + + decoderProps[i] = this.allocateRuntimeClass( + registry, pkgInfo, plan, true, RuntimeClassTransformer.KIND_EMPTY_CLASS, + "java/lang/Object", methodTemplates, StringDecoderInjector.FIELD_MAPPINGS, 51); + decoderClassIndexMap.put(decoderProps[i].getProperty("className"), i); + decoderProps[i].put("extraDecryptStringSignature", extraSignature); + decoderProps[i].put("lruCacheMapClassName", lruCacheMappings.getProperty("className")); + } + + pkgInfo.setCryptoContainers(containers); + + if (pkgInfo.getPackagePath().equals(runtimePackage.getPackagePath()) + && (activeConfig.getResourceEncryption().isGenerateStdWrappers() && (registry.usesResourceBundle || registry.usesResourceStreams) + || activeConfig.getResourceEncryption().isGenerateWebContaineWrappers() + || activeConfig.getStringEncryption().isEqualsIntrinsicEnabled())) { + if (activeConfig.getResourceEncryption().isGenerateStdWrappers() && (registry.usesResourceBundle || registry.usesResourceStreams) + || activeConfig.getResourceEncryption().isGenerateWebContaineWrappers()) { + if (verbose) { + listener.verbose("Generating wrappers for encrypted resources"); + } + + runtimeRemapTable.setProperty("MAGIC", Integer.toString(get().cryptoContainer.getResourceMagicHeader())); + runtimeRemapTable.setProperty("AES1", Long.toString(get().cryptoContainer.getCurrentKeyHigh())); + runtimeRemapTable.setProperty("AES2", Long.toString(get().cryptoContainer.getKeyLow())); + runtimeRemapTable.setProperty("IV0", Integer.toString(get().cryptoContainer.getIvWords()[0])); + runtimeRemapTable.setProperty("IV1", Integer.toString(get().cryptoContainer.getIvWords()[1])); + runtimeRemapTable.setProperty("IV2", Integer.toString(get().cryptoContainer.getIvWords()[2])); + runtimeRemapTable.setProperty("IV3", Integer.toString(get().cryptoContainer.getIvWords()[3])); + + Properties inputStreamProps = this.allocateRuntimeClass( + registry, runtimePackage, plan, true, RuntimeClassTransformer.KIND_INPUT_STREAM, + "java/io/FilterInputStream", StringerInputStreamCreator.METHOD_MAPPINGS, StringerInputStreamCreator.FIELD_MAPPINGS, 49); + Job inputStreamJob = this.createRemapJob( + inputStreamProps, "com/licel/stringer/StringerInputStreamPrototype", + StringerInputStreamCreator.METHOD_MAPPINGS, StringerInputStreamCreator.FIELD_MAPPINGS, runtimeRemapTable); + ((ArrayList) inputStreamJob.payload).add( + new ClassEncryptionTransformer(this, false, new ClassInfo(inputStreamProps.getProperty("className")), containers, decoderProps, activeConfig)); + plan.put(inputStreamProps.getProperty("className") + ".classn", inputStreamJob); + + Properties inflaterProps = this.allocateRuntimeClass( + registry, runtimePackage, plan, true, RuntimeClassTransformer.KIND_INFLATER, + "java/util/zip/Inflater", StringerInflaterCreator.METHOD_MAPPINGS, StringerInflaterCreator.FIELD_MAPPINGS, 49); + plan.put( + inflaterProps.getProperty("className") + ".classn", + this.createRemapJob( + inflaterProps, "com/licel/stringer/StringerInflaterPrototype", + StringerInflaterCreator.METHOD_MAPPINGS, StringerInflaterCreator.FIELD_MAPPINGS, runtimeRemapTable)); + + Properties filterStreamProps = this.allocateRuntimeClass( + registry, runtimePackage, plan, true, RuntimeClassTransformer.KIND_FILTER_INPUT_STREAM, + "java/io/FilterInputStream", StringerFilterInputStreamCreator.METHOD_MAPPINGS, StringerFilterInputStreamCreator.FIELD_MAPPINGS, 49); + plan.put( + filterStreamProps.getProperty("className") + ".classn", + this.createRemapJob( + filterStreamProps, "com/licel/stringer/StringerFilterInputStreamPrototype", + StringerFilterInputStreamCreator.METHOD_MAPPINGS, StringerFilterInputStreamCreator.FIELD_MAPPINGS, runtimeRemapTable)); + + Properties factoryProps = this.allocateRuntimeClass( + registry, runtimePackage, plan, true, RuntimeClassTransformer.KIND_STREAM_HANDLER_FACTORY, + "java/lang/Object", StringerStreamHandlerFactoryCreator.METHOD_MAPPINGS, StringerStreamHandlerFactoryCreator.FIELD_MAPPINGS, 49); + plan.put( + factoryProps.getProperty("className") + ".classn", + this.createRemapJob( + factoryProps, "com/licel/stringer/StringerStreamHandlerFactoryPrototype", + StringerStreamHandlerFactoryCreator.METHOD_MAPPINGS, StringerStreamHandlerFactoryCreator.FIELD_MAPPINGS, runtimeRemapTable)); + + Properties urlHandlerProps = this.allocateRuntimeClass( + registry, runtimePackage, plan, true, RuntimeClassTransformer.KIND_URL_HANDLER, + "java/net/URLStreamHandler", runtimePackage.getPackagePath() + "Handler", + StringerURLHandlerCreator.METHOD_MAPPINGS, StringerURLHandlerCreator.FIELD_MAPPINGS, 49); + Job urlHandlerJob = this.createRemapJob( + urlHandlerProps, "com/licel/stringer/StringerURLHandlerPrototype", + StringerURLHandlerCreator.METHOD_MAPPINGS, StringerURLHandlerCreator.FIELD_MAPPINGS, runtimeRemapTable); + ((ArrayList) urlHandlerJob.payload).add( + new ClassEncryptionTransformer(this, false, new ClassInfo(urlHandlerProps.getProperty("className")), containers, decoderProps, activeConfig)); + plan.put(urlHandlerProps.getProperty("className") + ".classn", urlHandlerJob); + + Properties urlConnProps = this.allocateRuntimeClass( + registry, runtimePackage, plan, true, RuntimeClassTransformer.KIND_URL_CONNECTION, + "java/net/URLConnection", StringerURLConnectionCreator.METHOD_MAPPINGS, StringerURLConnectionCreator.FIELD_MAPPINGS, 49); + plan.put( + urlConnProps.getProperty("className") + ".classn", + this.createRemapJob( + urlConnProps, "com/licel/stringer/StringerURLConnectionPrototype", + StringerURLConnectionCreator.METHOD_MAPPINGS, StringerURLConnectionCreator.FIELD_MAPPINGS, runtimeRemapTable)); + } + + if (activeConfig.getResourceEncryption().isGenerateWebContaineWrappers()) { + WebXmlCompiler webXmlCompiler = (WebXmlCompiler) get().attributes.get("webXmlInfo"); + if (webXmlCompiler != null) { + Properties catalinaProps = this.allocateRuntimeClass( + registry, runtimePackage, plan, true, RuntimeClassTransformer.KIND_CATALINA_CONTEXT_WRAPPER, + "org/apache/catalina/core/ApplicationContext", null, + CatalinaApplicationContextWrapperCreator.METHOD_MAPPINGS, CatalinaApplicationContextWrapperCreator.FIELD_MAPPINGS, 50); + Job catalinaJob = this.createRemapJob( + catalinaProps, "com/licel/stringer/webapp/tomcat/ApplicationContextWrapper", + CatalinaApplicationContextWrapperCreator.METHOD_MAPPINGS, CatalinaApplicationContextWrapperCreator.FIELD_MAPPINGS, runtimeRemapTable); + ((ArrayList) catalinaJob.payload).add( + new ClassEncryptionTransformer(this, false, new ClassInfo(catalinaProps.getProperty("className")), containers, decoderProps, activeConfig)); + plan.put(catalinaProps.getProperty("className") + ".classn", catalinaJob); + + Properties listenerProps = this.allocateRuntimeClass( + registry, runtimePackage, plan, true, RuntimeClassTransformer.KIND_WEB_CONTEXT_LOADER_LISTENER, + webXmlCompiler.getWebApplication(), "java/lang/Object", null, + WebContextLoaderListenerCreator.METHOD_MAPPINGS, WebContextLoaderListenerCreator.FIELD_MAPPINGS, 50); + Job listenerJob = this.createRemapJob( + listenerProps, "com/licel/stringer/webapp/tomcat/ContextLoaderListener", + WebContextLoaderListenerCreator.METHOD_MAPPINGS, WebContextLoaderListenerCreator.FIELD_MAPPINGS, runtimeRemapTable); + ((ArrayList) listenerJob.payload).add( + new ClassEncryptionTransformer(this, false, new ClassInfo(listenerProps.getProperty("className")), containers, decoderProps, activeConfig)); + plan.put(listenerProps.getProperty("className") + ".classn", listenerJob); + webXmlCompiler.setContextLoaderListenerClass(listenerProps.getProperty("className").replace('/', '.')); + + Properties classLoaderProps = this.allocateRuntimeClass( + registry, runtimePackage, plan, true, RuntimeClassTransformer.KIND_WEB_CONTEXT_CLASS_LOADER, + runtimeRemapTable, "java/lang/Object", null, + WebContextClassLoaderCreator.METHOD_MAPPINGS, WebContextClassLoaderCreator.FIELD_MAPPINGS, 50); + Job classLoaderJob = this.createRemapJob( + classLoaderProps, "com/licel/stringer/webapp/tomcat/CustomContextClassLoader", + WebContextClassLoaderCreator.METHOD_MAPPINGS, WebContextClassLoaderCreator.FIELD_MAPPINGS, runtimeRemapTable); + ((ArrayList) classLoaderJob.payload).add( + new ClassEncryptionTransformer(this, false, new ClassInfo(classLoaderProps.getProperty("className")), containers, decoderProps, activeConfig)); + plan.put(classLoaderProps.getProperty("className") + ".classn", classLoaderJob); + } + } + + if (activeConfig.getStringEncryption().isEqualsIntrinsicEnabled()) { + plan.put( + intrinsicsMappings.getProperty("className") + ".classn", + this.createRemapJob( + intrinsicsMappings, "com/licel/stringer/IntrinsicsPrototype", + IntrinsicsCreator.METHOD_MAPPINGS, IntrinsicsCreator.FIELD_MAPPINGS, runtimeRemapTable)); + } + } + + Properties reflectionMappings = new Properties(); + String reflectionClassName = this.generateClassName(pkgInfo, null, false); + ClassInfo reflectionClassInfo = new ClassInfo(reflectionClassName); + reflectionClassInfo.classFileVersion = 49; + reflectionClassInfo.superName = "java/lang/Object"; + reflectionClassInfo.isGeneratedClass = true; + reflectionClassInfo.hiddenMembers = new HashMap<>(65536); + reflectionClassInfo.hiddenClassIndices = new HashMap<>(); + pkgInfo.addClass(reflectionClassInfo); + reflectionMappings.setProperty("reflection.className", reflectionClassName); + if (verbose) { + listener.verbose(" New reflection impl class: " + reflectionClassName); + } + + Enumeration reflMethodKeys = ReflectionClassCreator.METHOD_MAPPINGS.keys(); + while (reflMethodKeys.hasMoreElements()) { + String key = (String) reflMethodKeys.nextElement(); + String descriptor = ReflectionClassCreator.METHOD_MAPPINGS.getProperty(key); + String generatedName = primaryNames.generateMethodName(reflectionClassInfo, descriptor, null); + reflectionClassInfo.declaredMethods.add(new ClassMemberInfo(0, generatedName, descriptor)); + reflectionMappings.setProperty("reflection." + key, generatedName); + if (verbose) { + listener.verbose(" adding method: " + generatedName + descriptor); + } + } + + Enumeration reflFieldKeys = ReflectionClassCreator.FIELD_MAPPINGS.keys(); + while (reflFieldKeys.hasMoreElements()) { + String key = (String) reflFieldKeys.nextElement(); + String descriptor = ReflectionClassCreator.FIELD_MAPPINGS.getProperty(key); + String generatedName = primaryNames.generateFieldName(reflectionClassInfo, descriptor); + reflectionClassInfo.declaredFields.add(new ClassMemberInfo(0, generatedName, descriptor)); + reflectionMappings.setProperty("reflection." + key, generatedName); + if (verbose) { + listener.verbose(" add field " + generatedName + descriptor); + } + } + + int userClassCount = 0; + int hideAccessClassCount = 0; + for (ClassInfo classInfo : pkgInfo.getClasses().values()) { + if (!classInfo.isGeneratedClass) { + userClassCount++; + } + if (classInfo.isModuleInfo) { + continue; + } + + ArrayList pipeline = new ArrayList<>(); + if (activeConfig.isOptimize()) { + pipeline.add(new ClassOptimizationTransformer(classInfo)); + } + if (classInfo.moveStringFields) { + pipeline.add(new FieldInitializationTransformer(registry.hasStringEncryptionAnnotations, classInfo)); + } + if (activeConfig.getResourceEncryption().isEnabled() + && classInfo.usesResourceStreams + && activeConfig.getResourceEncryption().isGenerateStdWrappers()) { + if (verbose) { + listener.verbose("Class is used for resource encryption's methods: " + classInfo.name); + } + pipeline.add(new ResourceReflectionTransformer(classInfo, runtimeRemapTable)); + } + if (classInfo.hideAccessEnabled) { + if (verbose) { + listener.verbose("Class to protect (" + classInfo.classFileVersion + "): " + classInfo.name); + } + pipeline.add(new ClassProtectionTransformer(activeConfig, classInfo, reflectionClassInfo, reflectionMappings, containers[0])); + if (classInfo.hasHideAccessTargets) { + hideAccessClassCount++; + } + } + if (decoderClassIndexMap.containsKey(classInfo.name)) { + int decoderIndex = decoderClassIndexMap.get(classInfo.name); + long expiration = activeConfig.getTrialExpirationTimestampSeconds(); + pipeline.add(new StringDecoderTransformer( + containers[decoderIndex], + classInfo.name, + decoderProps[decoderIndex], + activeConfig, + expiration, + classInfo, + jarCheckSalt, + get().integrityKey0, + get().integrityKey1)); + } + if (activeConfig.getStringEncryption().isEqualsIntrinsicEnabled() && !classInfo.isGeneratedClass) { + pipeline.add(new IntrinsicsTransformer(classInfo, intrinsicsMappings)); + } + if (classInfo.stringEncryptionEnabled) { + if (verbose) { + listener.verbose("Class to encrypt strings in: " + classInfo.name); + } + pipeline.add(new ClassEncryptionTransformer(this, registry.hasStringEncryptionAnnotations, classInfo, containers, decoderProps, activeConfig)); + } + if (classInfo.annotatedInsecure) { + if (verbose) { + listener.verbose("Class " + classInfo.name + " has @insecure annotation/s."); + } + pipeline.add(new ClassCleanupTransformer(classInfo)); + } + + if (!pipeline.isEmpty()) { + String jobKey = classInfo.name + ".class" + (classInfo.isGeneratedClass ? "n" : ""); + Job existingJob = (Job) plan.get(jobKey); + if (existingJob == null) { + existingJob = new Job(Job.TRANSFORM_CLASS, pipeline); + } else if (existingJob.type == Job.TRANSFORM_CLASS) { + ((ArrayList) existingJob.payload).addAll(pipeline); + } + plan.put(jobKey, existingJob); + } + } + + if (hideAccessClassCount > 0) { + Object[] reflectionPayload = new Object[]{reflectionMappings, reflectionClassInfo}; + plan.put( + pkgInfo.getPackagePath() + "." + reflectionClassName + ".#newClass", + new RuntimeClassTransformer(containers[0], RuntimeClassTransformer.KIND_REFLECTION_CLASS, 49, reflectionClassName, "java/lang/Object", reflectionPayload)); + ArrayList reflectionPipeline = new ArrayList<>(); + reflectionPipeline.add(new ClassEncryptionTransformer(this, false, reflectionClassInfo, containers, decoderProps, activeConfig)); + plan.put(reflectionClassName + ".classn", new Job(Job.TRANSFORM_CLASS, reflectionPipeline)); + } + + if (userClassCount == 0 && !pkgInfo.getPackagePath().equals(runtimePackage.getPackagePath())) { + for (Properties decoderProp : decoderProps) { + plan.remove(pkgInfo.getPackagePath() + "." + decoderProp.getProperty("className") + ".#newClass"); + } + } + } + + for (PackageProtectionInfo pkgInfo : allPackages) { + if (activeConfig.getResourceEncryption().isEnabled()) { + if (verbose) { + listener.verbose("Processing resources in package: " + pkgInfo.getPackagePath()); + } + for (ResourceBundleInfo bundleInfo : pkgInfo.getResourceBundles().values()) { + if (!activeConfig.getResourceEncryption().match(bundleInfo.name)) { + if (verbose) { + listener.verbose("skip: " + bundleInfo.name); + } + continue; + } + if (verbose) { + listener.verbose("Resource to encrypt: " + bundleInfo.name); + } + plan.put(bundleInfo.name, new Job(Job.ENCRYPT_RESOURCE, bundleInfo)); + + if (registry.usesResourceBundle && bundleInfo.name.endsWith(".properties")) { + String bundleClassName = bundleInfo.name.substring(0, bundleInfo.name.indexOf(".properties")); + ClassInfo bundleClassInfo = new ClassInfo(bundleClassName); + bundleClassInfo.isGeneratedClass = true; + pkgInfo.addClass(bundleClassInfo); + Object[] bundlePayload = new Object[]{ + bundleInfo.resourceBundle, + runtimeRemapTable.getProperty("com/licel/stringer/StringerInputStreamPrototype"), + runtimeRemapTable.getProperty( + "com/licel/stringer/StringerInputStreamPrototype.decryptStringWithoutCheckCallCtx.(Ljava/lang/Object;)Ljava/lang/String;") + }; + plan.put( + pkgInfo.getPackagePath() + "." + bundleClassName + ".#newClass", + new RuntimeClassTransformer( + get().cryptoContainer, + RuntimeClassTransformer.KIND_RESOURCE_BUNDLE, + 49, + bundleClassName, + "java/util/ListResourceBundle", + bundlePayload)); + } + } + } + } + + if (checkJarEnabled) { + int[] permutation = StringerUtils.generateRandomPermutation(get().secureRandom, registry.classes.size()); + ArrayList permutedEntries = new ArrayList<>(); + ByteArrayOutputStream hashInput = new ByteArrayOutputStream(); + Object[] classNames = registry.classes.keySet().toArray(); + + for (int index : permutation) { + byte[] extra = new byte[12]; + String entryName = classNames[index] + ".class"; + hashInput.write(entryName.getBytes(StandardCharsets.UTF_8)); + get().secureRandom.nextBytes(extra); + extra[0] = jarCheckSalt[0]; + extra[1] = jarCheckSalt[1]; + extra[2] = 8; + extra[3] = 0; + hashInput.write(extra); + ResourceEntry entry = new ResourceEntry(entryName); + entry.setExtra(extra); + permutedEntries.add(entry); + } + + long integrityHash = Math.abs(SipHash.hash(get().integrityKey0, get().integrityKey1, hashInput.toByteArray())); + for (PackageProtectionInfo pkgInfo : allPackages) { + if (pkgInfo.getCryptoContainers() != null) { + for (CryptoContainer container : pkgInfo.getCryptoContainers()) { + container.setIntegrityHash(integrityHash); + } + } + } + plan.put("jarPermutation", new Job(Job.TRANSFORM_WEB_XML, permutedEntries)); + } + + get().attributes.put("jarInfo", registry); + return plan; + } +} diff --git a/src/main/java/com/licel/stringer/WorkerContext.java b/src/main/java/com/licel/stringer/WorkerContext.java new file mode 100644 index 0000000..66bf03f --- /dev/null +++ b/src/main/java/com/licel/stringer/WorkerContext.java @@ -0,0 +1,22 @@ +package com.licel.stringer; + +import com.licel.stringer.crypto.CryptoContainer; +import com.licel.stringer.io.SourceIterator; +import com.licel.stringer.model.ClassInfo; +import com.licel.stringer.naming.NameGenerator; +import java.security.SecureRandom; +import java.util.HashMap; + +public class WorkerContext { + public NameGenerator nameGenerator; + public NameGenerator internalNameGenerator; + public Config config; + public SecureRandom secureRandom; + public SourceIterator sourceIterator; + public int processedStringCount; + public CryptoContainer cryptoContainer; + public HashMap jdkClassCache = new HashMap<>(); + public long integrityKey0; + public long integrityKey1; + public HashMap attributes = new HashMap<>(); +} diff --git a/src/main/java/com/licel/stringer/WorkerContextThreadLocal.java b/src/main/java/com/licel/stringer/WorkerContextThreadLocal.java new file mode 100644 index 0000000..cae9d88 --- /dev/null +++ b/src/main/java/com/licel/stringer/WorkerContextThreadLocal.java @@ -0,0 +1,8 @@ +package com.licel.stringer; + +final class WorkerContextThreadLocal extends ThreadLocal { + @Override + protected WorkerContext initialValue() { + return new WorkerContext(); + } +} diff --git a/src/main/java/com/licel/stringer/WorkerException.java b/src/main/java/com/licel/stringer/WorkerException.java new file mode 100644 index 0000000..72268d6 --- /dev/null +++ b/src/main/java/com/licel/stringer/WorkerException.java @@ -0,0 +1,14 @@ +package com.licel.stringer; + +public class WorkerException extends RuntimeException { + private final Worker worker; + + public WorkerException(Worker worker, String message) { + super(message); + this.worker = worker; + } + + public Worker getWorker() { + return this.worker; + } +} diff --git a/src/main/java/com/licel/stringer/WorkerListener.java b/src/main/java/com/licel/stringer/WorkerListener.java new file mode 100644 index 0000000..11a12ce --- /dev/null +++ b/src/main/java/com/licel/stringer/WorkerListener.java @@ -0,0 +1,7 @@ +package com.licel.stringer; + +public interface WorkerListener { + void info(String message); + + void verbose(String message); +} diff --git a/src/main/java/com/licel/stringer/analysis/ClassMetadataCollector.java b/src/main/java/com/licel/stringer/analysis/ClassMetadataCollector.java new file mode 100644 index 0000000..7872726 --- /dev/null +++ b/src/main/java/com/licel/stringer/analysis/ClassMetadataCollector.java @@ -0,0 +1,85 @@ +package com.licel.stringer.analysis; + +import com.licel.stringer.Config; +import com.licel.stringer.model.ClassInfo; +import com.licel.stringer.model.ClassMemberInfo; +import org.objectweb.asm.AnnotationVisitor; +import org.objectweb.asm.ClassVisitor; +import org.objectweb.asm.FieldVisitor; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.ModuleVisitor; +import org.objectweb.asm.Opcodes; + +public class ClassMetadataCollector extends ClassVisitor implements Opcodes { + public ClassInfo classInfo; + private boolean hideAccessMatched = false; + private boolean hideAccessExcluded = false; + private final Config config; + + public ClassMetadataCollector(String className, Config config) { + super(Opcodes.ASM9); + this.config = config; + this.classInfo = new ClassInfo(className); + } + + public ClassInfo getClassInfo() { + return this.classInfo; + } + + @Override + public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { + this.classInfo.annotatedSecured = "Lcom/licel/stringer/annotations/secured;".equals(descriptor); + this.classInfo.hasStringEncryptionAnnotation = this.classInfo.annotatedSecured; + this.classInfo.annotatedInsecure = "Lcom/licel/stringer/annotations/insecure;".equals(descriptor); + if ("Lcom/stringer/annotations/StringEncryption;".equals(descriptor)) { + this.classInfo.annotatedSecured = true; + this.classInfo.hasExplicitStringEncryptionAnnotation = true; + this.classInfo.hasStringEncryptionAnnotation = true; + } + if ("Lcom/stringer/annotations/HideAccess;".equals(descriptor)) { + this.hideAccessMatched = true; + } + return null; + } + + @Override + public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { + this.classInfo.classFileVersion = version; + this.classInfo.name = name; + this.classInfo.isInterface = (access & ACC_INTERFACE) == ACC_INTERFACE; + this.classInfo.isEnum = (access & ACC_ENUM) == ACC_ENUM; + this.classInfo.isSynthetic = (access & ACC_SYNTHETIC) == ACC_SYNTHETIC; + this.classInfo.superName = superName; + if (this.config.getHideAccess().isEnabled() && this.config.getHideAccess().isFiltered()) { + this.hideAccessMatched = this.config.getHideAccess().match(this.classInfo); + } + } + + @Override + public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) { + this.classInfo.declaredFields.add(new ClassMemberInfo(access, name, descriptor)); + if (descriptor.equals("Ljava/lang/String;")) { + this.classInfo.stringFieldInitialValues.put(name, value); + return new FieldEncryptionAnnotationCollector(this.classInfo, name, value); + } + return null; + } + + @Override + public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { + if ((access & ACC_NATIVE) == ACC_NATIVE) { + this.classInfo.hasNativeMethods = true; + } + if (name.equals("")) { + this.classInfo.hasStaticInitializer = true; + } + this.classInfo.declaredMethods.add(new ClassMemberInfo(access, name, descriptor)); + return new MethodMetadataCollector(this.classInfo, name, descriptor, this.hideAccessMatched, this.hideAccessExcluded, this.config); + } + + @Override + public ModuleVisitor visitModule(String name, int access, String version) { + this.classInfo.isModuleInfo = true; + return null; + } +} diff --git a/src/main/java/com/licel/stringer/analysis/FieldEncryptionAnnotationCollector.java b/src/main/java/com/licel/stringer/analysis/FieldEncryptionAnnotationCollector.java new file mode 100644 index 0000000..88839e0 --- /dev/null +++ b/src/main/java/com/licel/stringer/analysis/FieldEncryptionAnnotationCollector.java @@ -0,0 +1,31 @@ +package com.licel.stringer.analysis; + +import com.licel.stringer.model.ClassInfo; +import org.objectweb.asm.AnnotationVisitor; +import org.objectweb.asm.FieldVisitor; +import org.objectweb.asm.Opcodes; + +public class FieldEncryptionAnnotationCollector extends FieldVisitor implements Opcodes { + private final ClassInfo classInfo; + private final String initialValue; + private final String fieldName; + + public FieldEncryptionAnnotationCollector(ClassInfo classInfo, String fieldName, Object value) { + super(Opcodes.ASM9); + this.classInfo = classInfo; + this.fieldName = fieldName; + this.initialValue = value != null ? (value instanceof String ? (String) value : null) : null; + } + + @Override + public AnnotationVisitor visitAnnotation(String descriptor, boolean visible) { + if (("Lcom/stringer/annotations/StringEncryption;".equals(descriptor) || this.classInfo.annotatedSecured) + && !"Lcom/licel/stringer/annotations/insecure;".equals(descriptor)) { + this.classInfo.hasStringEncryptionAnnotation = true; + this.classInfo.hasSecuredField = true; + this.classInfo.hasExplicitStringEncryptionAnnotation = true; + this.classInfo.securedStringFields.put(this.fieldName, this.initialValue); + } + return null; + } +} diff --git a/src/main/java/com/licel/stringer/analysis/MethodMetadataCollector.java b/src/main/java/com/licel/stringer/analysis/MethodMetadataCollector.java new file mode 100644 index 0000000..fd5440f --- /dev/null +++ b/src/main/java/com/licel/stringer/analysis/MethodMetadataCollector.java @@ -0,0 +1,484 @@ +package com.licel.stringer.analysis; + +import com.licel.stringer.Config; +import com.licel.stringer.WorkerListener; +import com.licel.stringer.model.ClassInfo; +import com.licel.stringer.model.ClassMemberInfo; +import com.licel.stringer.model.FieldInfo; +import com.licel.stringer.model.MethodInfo; +import com.licel.stringer.model.OperandStackModel; +import com.licel.stringer.model.StackValue; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import org.objectweb.asm.AnnotationVisitor; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.Type; + +public class MethodMetadataCollector extends MethodVisitor implements Opcodes { + protected static final int STATE_IDLE = 0; + private static final int STATE_NEW_SEEN = 1; + private static final int STATE_NEW_DUP_SEEN = 2; + + private final ClassInfo classInfo; + private final String methodName; + private final String descriptor; + private String lastStringLiteral = null; + private boolean lastInsnWasStringLdc = false; + private boolean hideAccessEnabled; + private final boolean hideAccessExcluded; + private final WorkerListener listener; + private boolean canTrimTypes = true; + private final String formattedMethodSignature; + private final String formattedConstructorSignature; + private final boolean isConstructor; + private boolean beforeSuperInit = true; + private boolean hasPreInitMethodCalls = false; + private boolean hasPreInitFieldReads = false; + private boolean allocatesSelfOrSuperPreInit = false; + private final Set