SpringBoot自定義classloader加密保護class檔案

code2roc發表於2022-02-19

背景

最近針對公司框架進行關鍵業務程式碼進行加密處理,防止通過jd-gui等反編譯工具能夠輕鬆還原工程程式碼,相關混淆方案配置使用比較複雜且針對springboot專案問題較多,所以針對class檔案加密再通過自定義的classloder進行解密載入,此方案並不是絕對安全,只是加大反編譯的困難程度,防君子不防小人,整體加密保護流程圖如下圖所示

maven外掛加密

使用自定義maven外掛對編譯後指定的class檔案進行加密,加密後的class檔案拷貝到指定路徑,這裡是儲存到resource/coreclass下,刪除源class檔案,加密使用的是簡單的DES對稱加密

 @Parameter(name = "protectClassNames", defaultValue = "")
 private List<String> protectClassNames;
 @Parameter(name = "noCompileClassNames", defaultValue = "")
 private List<String> noCompileClassNames;
 private List<String> protectClassNameList = new ArrayList<>();
 private void protectCore(File root) throws IOException {
        if (root.isDirectory()) {
            for (File file : root.listFiles()) {
                protectCore(file);
            }
        }
        String className = root.getName().replace(".class", "");
        if (root.getName().endsWith(".class")) {
            //class篩選
            boolean flag = false;
            if (protectClassNames!=null && protectClassNames.size()>0) {
                for (String item : protectClassNames) {
                    if (className.equals(item)) {
                        flag = true;
                    }
                }
            }
            if(noCompileClassNames.contains(className)){
                boolean deleteResult = root.delete();
                if(!deleteResult){
                    System.gc();
                    deleteResult = root.delete();
                }
                System.out.println("【noCompile-deleteResult】:" + deleteResult);
            }
            if (flag && !protectClassNameList.contains(className)) {
                protectClassNameList.add(className);
                System.out.println("【protectCore】:" + className);
                FileOutputStream fos = null;
                try {
                    final byte[] instrumentBytes = doProtectCore(root);
                    //加密後的class檔案儲存路徑
                    String folderPath = output.getAbsolutePath() + "\\" + "classes";
                    File  folder = new File(folderPath);
                    if(!folder.exists()){
                        folder.mkdir();
                    }
                    folderPath = output.getAbsolutePath() + "\\" + "classes"+ "\\" + "coreclass" ;
                    folder = new File(folderPath);
                    if(!folder.exists()){
                        folder.mkdir();
                    }
                    String filePath = output.getAbsolutePath() + "\\" + "classes" + "\\" + "coreclass" + "\\" + className + ".class";
                    System.out.println("【filePath】:" + filePath);
                    File protectFile = new File(filePath);
                    if (protectFile.exists()) {
                        protectFile.delete();
                    }
                    protectFile.createNewFile();
                    fos = new FileOutputStream(protectFile);
                    fos.write(instrumentBytes);
                    fos.flush();
                } catch (MojoExecutionException e) {
                    System.out.println("【protectCore-exception】:" + className);
                    e.printStackTrace();
                } finally {
                    if (fos != null) {
                        fos.close();
                    }
                    if(root.exists()){
                        boolean deleteResult = root.delete();
                        if(!deleteResult){
                            System.gc();
                            deleteResult = root.delete();
                        }
                        System.out.println("【protectCore-deleteResult】:" + deleteResult);
                    }
                }
            }
        }
    }

    private byte[] doProtectCore(File clsFile) throws MojoExecutionException {
        try {
            FileInputStream inputStream = new FileInputStream(clsFile);
            byte[] content = ProtectUtil.encrypt(inputStream);
            inputStream.close();
            return content;
        } catch (Exception e) {
            throw new MojoExecutionException("doProtectCore error", e);
        }
    }

注意事項

1.加密後的檔案也是class檔案,為了防止在遞迴查詢中重複加密,需要對已經加密後的class名稱記錄防止重複

2.在刪除原始檔時可能出現編譯佔用的情況,執行System.gc()後方可刪除

3.針對自定義外掛的列表形式的configuration節點可以使用List來對映

外掛使用配置如圖所示

自定義classloader

建立CustomClassLoader繼承自ClassLoader,重寫findClass方法只處理裝載加密後的class檔案,其他class交有預設載入器處理,需要注意的是預設處理不能呼叫super.finclass方法,在idea除錯沒問題,打成jar包執行就會報加密的class中的依賴class無法載入(ClassNoDefException/ClassNotFoundException),這裡使用的是當前執行緒的上下文的類載入器就沒有問題(Thread.currentThread().getContextClassLoader())

public class CustomClassLoader extends ClassLoader {

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        Class<?> clz = findLoadedClass(name);
        //先查詢有沒有載入過這個類。如果已經載入,則直接返回載入好的類。如果沒有,則載入新的類。
        if (clz != null) {
            return clz;
        }
        String[] classNameList = name.split("\\.");
        String classFileName = classNameList[classNameList.length - 1];
        if (classFileName.endsWith("MethodAccess") || !classFileName.endsWith("CoreUtil")) {
            return Thread.currentThread().getContextClassLoader().loadClass(name);
        }
        ClassLoader parent = this.getParent();
        try {
            //委派給父類載入
            clz = parent.loadClass(name);
        } catch (Exception e) {
            //log.warn("parent load class fail:"+ e.getMessage(),e);
        }
        if (clz != null) {
            return clz;
        } else {
            byte[] classData = null;
            ClassPathResource classPathResource = new ClassPathResource("coreclass/" + classFileName + ".class");
            InputStream is = null;
            try {
                is = classPathResource.getInputStream();
                classData = DESEncryptUtil.decryptFromByteV2(FileUtil.convertStreamToByte(is), "xxxxxxx");
            } catch (Exception e) {
                e.printStackTrace();
                throw new ProtectClassLoadException("getClassData error");
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (classData == null) {
                throw new ClassNotFoundException();
            } else {
                clz = defineClass(name, classData, 0, classData.length);
            }
            return clz;
        }
    }


}

隱藏classloader

classloader加密class檔案處理方案的漏洞在於自定義類載入器是完全暴露的,只需進行分析解密流程就能獲取到原始class檔案,所以我們需要對classloder的內容進行隱藏

1.把classloader的原始檔在編譯期間進行刪除(maven自定義外掛實現)

2.將classloder的內容進行base64編碼後拆分內容尋找多個系統啟動注入點寫入到loader.key檔案中(拆分時寫入的路徑和檔名需要進行base64加密避免全域性搜尋),例如

    private static void init() {
        String source = "dCA9IG5hbWUuc3BsaXQoIlxcLiIpOwogICAgICAgIFN0cmluZyBjbGFzc0ZpbGVOYW1lID0gY2xhc3NOYW1lTGlzdFtjbGFzc05hbWVMaXN0Lmxlbmd0aCAtIDFdOwogICAgICAgIGlmIChjbGFzc0ZpbGVOYW1lLmVuZHNXaXRoKCJNZXRob2RBY2Nlc3MiKSB8fCAhY2xhc3NGaWxlTmFtZS5lbmRzV2l0aCgiQ29yZVV0aWwiKSkgewogICAgICAgICAgICByZXR1cm4gVGhyZWFkLmN1cnJlbnRUaHJlYWQoKS5nZXRDb250ZXh0Q2xhc3NMb2FkZXIoKS5sb2FkQ2xhc3MobmFtZSk7CiAgICAgICAgfQogICAgICAgIENsYXNzTG9hZGVyIHBhcmVudCA9IHRoaXMuZ2V0UGFyZW50KCk7CiAgICAgICAgdHJ5IHsKICAgICAgICAgICAgLy/lp5TmtL7nu5nniLbnsbvliqDovb0KICAgICAgICAgICAgY2x6ID0gcGFyZW50LmxvYWRDbGFzcyhuYW1lKTsKICAgICAgICB9IGNhdGNoIChFeGNlcHRpb24gZSkgewogICAgICAgICAgICAvL2xvZy53YXJuKCJwYXJlbnQgbG9hZCBjbGFzcyBmYWls77yaIisgZS5nZXRNZXNzYWdlKCksZSk7CiAgICAgICAgfQogICAgICAgIGlmIChjbHogIT0gbnVsbCkgewogICAgICAgICAgICByZXR1cm4gY2x6OwogICAgICAgIH0gZWxzZSB7CiAgICAgICAgICAgIGJ5dGVbXSBjbGFzc0RhdGEgPSBudWxsOwogICAgICAgICAgICBDbGFzc1BhdGhSZXNvdXJjZSBjbGFzc1BhdGhSZXNvdXJjZSA9IG5ldyBDbGFzc1BhdGhSZXNvdXJjZSgiY29yZWNsYXNzLyIgKyBjbGFzc0ZpbGVOYW1lICsgIi5jbGFzcyIpOwogICAgICAgICAgICBJbnB1dFN0cmVhbSBpcyA9IG51bGw7CiAgICAgICAgICAgIHRyeSB7CiAgICAgICAgICAgICAgICBpcyA9IGNsYXNzUGF0aFJlc291cmNlLmdldElucHV0U3RyZWFtKCk7CiAgICAgICAgICAgICAgICBjbGFzc0RhdGEgPSBERVNFbmNyeXB0VXRpbC5kZWNyeXB0RnJvbUJ5dGVWMihGaWxlVXRpbC5jb252ZXJ0U3RyZWFtVG9CeXRlKGlzKSwgIlNGQkRiRzkxWkZoaFltTmtNVEl6TkE9PSIpOwogICAgICAgICAgICB9IGNhdGNoIChFeGNlcHRpb24gZSkgewogICAgICAgICAgICAgICAgZS5wcmludFN0YWNrVHJhY2UoKTsKICAgICAgICAgICAgICAgIHRocm93IG5ldyBQc";
        String filePath = "";
        try{
            filePath = new String(Base64.decodeBase64("dGVtcGZpbGVzL2R5bmFtaWNnZW5zZXJhdGUvbG9hZGVyLmtleQ=="),"utf-8");
        }catch (Exception e){
            e.printStackTrace();
        }
        FileUtil.writeFile(filePath, source,true);
    }

3.通過GroovyClassLoader對classloder的內容(字串)進行動態編譯獲取到物件,刪除loader.key檔案

pom檔案增加動態編譯依賴

        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.13</version>
        </dependency>

獲取檔案內容進行編譯程式碼如下(寫入/讀取注意utf-8處理防止亂碼)

public class CustomCompile {
    private static Object Compile(String source){
        Object instance = null;
        try{
            // 編譯器
            CompilerConfiguration config = new CompilerConfiguration();
            config.setSourceEncoding("UTF-8");
            // 設定該GroovyClassLoader的父ClassLoader為當前執行緒的載入器(預設)
            GroovyClassLoader groovyClassLoader = new GroovyClassLoader(Thread.currentThread().getContextClassLoader(), config);
            Class<?> clazz = groovyClassLoader.parseClass(source);
            // 建立例項
            instance = clazz.newInstance();
        }catch (Exception e){
            e.printStackTrace();
        }
        return instance;
    }

    public static  ClassLoader getClassLoader(){
        String filePath = "tempfiles/dynamicgenserate/loader.key";
        String source = FileUtil.readFileContent(filePath);
        byte[] decodeByte = Base64.decodeBase64(source);
        String str = "";
        try{
            str = new String(decodeByte, "utf-8");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            FileUtil.deleteDirectory("tempfiles/dynamicgenserate/");
        }
        return (ClassLoader)Compile(str);
    }
}

被保護class手動加殼

因為相關需要加密的class檔案都是通過customerclassloder載入的,獲取不到顯示的class型別,所以我們實際的業務類只能通過反射的方法進行呼叫,例如業務工具類LicenseUtil,加密後類為LicenseCoreUtil,我們在LicenseUtil的方法中需要反射呼叫,LicenseCoreUtil中的方法,例如

@Component
public class LicenseUtil {
    private String coreClassName = "com.haopan.frame.core.util.LicenseCoreUtil";

    public String getMachineCode() throws Exception {
        return (String) CoreLoader.getInstance().executeMethod(coreClassName, "getMachineCode");
    }

    public boolean checkLicense(boolean startCheck) {
        return (boolean)CoreLoader.getInstance().executeMethod(coreClassName, "checkLicense",startCheck);
    }
}

為了避免反射呼叫隨著呼叫次數的增加損失較多的效能,使用了一個第三方的外掛reflectasm,pom增加依賴

        <dependency>
            <groupId>com.esotericsoftware</groupId>
            <artifactId>reflectasm</artifactId>
            <version>1.11.0</version>
        </dependency>

reflectasm使用了MethodAccess快速定位方法並在位元組碼層面進行呼叫,CoreLoader的程式碼如下

public class CoreLoader {
    private ClassLoader classLoader;

    private CoreLoader() {
        classLoader = CustomCompile.getClassLoader();
    }

    private static class SingleInstace {
        private static final CoreLoader instance = new CoreLoader();
    }

    public static CoreLoader getInstance() {
        return SingleInstace.instance;
    }

    public Object executeMethod(String className,String methodName, Object... args) {
        Object result = null;
        try {
            Class clz = classLoader.loadClass(className);
            MethodAccess access = MethodAccess.get(clz);
            result = access.invoke(clz.newInstance(), methodName, args);

        } catch (Exception e) {
            e.printStackTrace();
            throw  new ProtectClassLoadException("executeMethod error");
        }
        return result;
    }
}

總結

自定義classloder並不是一個完美的程式碼加密保護的解決方案,但就改造工作量與對專案的影響程度來說是最小的,只需要針對關鍵核心邏輯方法進行保護,不會對系統執行邏輯產生影響製造bug,理論上來說只要classloder的拆分越小,系統啟動注入點隱藏的越多,那破解的成本就會越高,如果有不足之處還請見諒

相關文章