|
| 1 | +package org.clyze.doop.common; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.FileInputStream; |
| 5 | +import java.io.InputStream; |
| 6 | +import java.io.IOException; |
| 7 | +import java.nio.file.Files; |
| 8 | +import java.util.*; |
| 9 | +import java.util.concurrent.*; |
| 10 | +import java.util.function.Consumer; |
| 11 | +import java.util.zip.ZipEntry; |
| 12 | +import java.util.zip.ZipFile; |
| 13 | +import java.util.zip.ZipInputStream; |
| 14 | + |
| 15 | +import org.apache.commons.io.IOUtils; |
| 16 | +import org.apache.log4j.Logger; |
| 17 | +import org.clyze.scanner.BinaryAnalysis; |
| 18 | +import org.clyze.scanner.NativeDatabaseConsumer; |
| 19 | +import org.clyze.scanner.NativeScanner; |
| 20 | +import org.clyze.utils.TypeUtils; |
| 21 | +import org.jf.dexlib2.Opcodes; |
| 22 | +import org.jf.dexlib2.dexbacked.DexBackedDexFile; |
| 23 | +import org.jf.dexlib2.iface.MultiDexContainer; |
| 24 | +import org.jf.dexlib2.dexbacked.DexBackedClassDef; |
| 25 | +import org.objectweb.asm.ClassReader; |
| 26 | +//import org.objectweb.asm.ClassVisitor; |
| 27 | +//import org.objectweb.asm.tree.ClassNode; |
| 28 | + |
| 29 | +import static org.clyze.scanner.BinaryAnalysis.AnalysisType.*; |
| 30 | +import static org.jf.dexlib2.DexFileFactory.loadDexContainer; |
| 31 | +//import static org.objectweb.asm.Opcodes.*; |
| 32 | + |
| 33 | +/** |
| 34 | + * This class scans input artifacts (.jar, .aar, or .apk files) and |
| 35 | + * registers each found class. Optional actions can also be performed |
| 36 | + * on the artifact entries, when they are scanned. |
| 37 | + */ |
| 38 | +public class ArtifactScanner { |
| 39 | + |
| 40 | + private final Map<String, Set<ArtifactEntry>> artifactToClassMap = new ConcurrentHashMap<>(); |
| 41 | + private final Logger logger = Logger.getLogger(getClass()); |
| 42 | + private final Set<GenericFieldInfo> genericFields = ConcurrentHashMap.newKeySet(); |
| 43 | + |
| 44 | + Set<GenericFieldInfo> getGenericFields() { return genericFields; } |
| 45 | + |
| 46 | + public Map<String, Set<ArtifactEntry>> getArtifactToClassMap() { |
| 47 | + return artifactToClassMap; |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * Registers a class with its container artifact. |
| 52 | + * @param artifact the file name of the artifact containing the class |
| 53 | + * @param className the name of the class |
| 54 | + * @param subArtifact the sub-artifact (such as "classes.dex" for APKs) |
| 55 | + * @param size the size of the class |
| 56 | + */ |
| 57 | + public void registerArtifactClass(String artifact, String className, String subArtifact, int size) { |
| 58 | + ArtifactEntry ae = new ArtifactEntry(className, subArtifact, size); |
| 59 | + artifactToClassMap.computeIfAbsent(artifact, x -> new CopyOnWriteArraySet<>()).add(ae); |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * Register .dex entries and perform actions over .dex entries (if |
| 64 | + * processor is not null). |
| 65 | + * |
| 66 | + * @param inputApk the path of the input APK file |
| 67 | + * @param classProc the processor for .class entries (takes entry name) |
| 68 | + */ |
| 69 | + public void processAPKClasses(String inputApk, Consumer<String> classProc) { |
| 70 | + try { |
| 71 | + Opcodes opcodes = Opcodes.getDefault(); |
| 72 | + File apk = new File(inputApk); |
| 73 | + MultiDexContainer<? extends DexBackedDexFile> multiDex = loadDexContainer(apk, opcodes); |
| 74 | + for (String dexEntry : multiDex.getDexEntryNames()) { |
| 75 | + MultiDexContainer.DexEntry<?> dex = multiDex.getEntry(dexEntry); |
| 76 | + if (dex == null) |
| 77 | + logger.debug("No .dex entry for " + dexEntry); |
| 78 | + else |
| 79 | + for (DexBackedClassDef dexClass : ((DexBackedDexFile)dex.getDexFile()).getClasses()) { |
| 80 | + String className = TypeUtils.raiseTypeId(dexClass.getType()); |
| 81 | + registerArtifactClass(apk.getName(), className, dexEntry, dexClass.getSize()); |
| 82 | + if (classProc != null) |
| 83 | + classProc.accept(className); |
| 84 | + } |
| 85 | + } |
| 86 | + } catch (Exception ex) { |
| 87 | + logger.debug("Error while calculating artifacts on Android: " + ex.getMessage()); |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + public void processClass(InputStream is, File f, Consumer<String> classProc) throws IOException { |
| 92 | + String className = BytecodeUtil.getClassName(new ClassReader(is)); |
| 93 | + String artifact = f.getName(); |
| 94 | + registerArtifactClass(artifact, className, "-", IOUtils.toByteArray(is).length); |
| 95 | + if (classProc != null) |
| 96 | + classProc.accept(className); |
| 97 | + |
| 98 | +// ClassNode cn = new ClassNode(ASM5); |
| 99 | +// reader.accept(cn, ClassReader.EXPAND_FRAMES); |
| 100 | +// ClassVisitor genericSignaturesRetriever = new GenericSignaturesRetriever(ASM5); |
| 101 | +// cn.accept(genericSignaturesRetriever); |
| 102 | +// Set<GenericFieldInfo> classGenericFields = ((GenericSignaturesRetriever) genericSignaturesRetriever).getGenericFields(); |
| 103 | +// this.genericFields.addAll(classGenericFields); |
| 104 | + } |
| 105 | + |
| 106 | + /** |
| 107 | + * Register archive (.class) entries and perform actions over |
| 108 | + * other types of entries (if processors are not null). |
| 109 | + * |
| 110 | + * @param input the path of the input archive |
| 111 | + * @param classProc the processor for .class entries (takes entry name) |
| 112 | + * @param generalProc the general processor for all other entries |
| 113 | + */ |
| 114 | + public void processArchive(String input, Consumer<String> classProc, |
| 115 | + EntryProcessor generalProc) throws IOException { |
| 116 | + try (ZipInputStream zin = new ZipInputStream(new FileInputStream(input)); ZipFile zipFile = new ZipFile(input)) { |
| 117 | + ZipEntry entry; |
| 118 | + while ((entry = zin.getNextEntry()) != null) { |
| 119 | + /* Skip directories */ |
| 120 | + if (entry.isDirectory()) |
| 121 | + continue; |
| 122 | + |
| 123 | + String entryName = entry.getName().toLowerCase(); |
| 124 | + if (entryName.endsWith(".class")) { |
| 125 | + try { |
| 126 | + processClass(zipFile.getInputStream(entry), new File(zipFile.getName()), classProc); |
| 127 | + } catch (Exception ex) { |
| 128 | + ex.printStackTrace(); |
| 129 | + System.err.println("Error while preprocessing entry \"" + entryName + "\", it will be ignored."); |
| 130 | + } |
| 131 | + } else if (generalProc != null) |
| 132 | + generalProc.accept(zipFile, entry, entryName); |
| 133 | + } |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + /** |
| 138 | + * Helper method to extract an entry inside a ZIP archive and save |
| 139 | + * it as a file. |
| 140 | + * |
| 141 | + * @param tmpDirName a name for the intermediate temporary directory |
| 142 | + * @param zipFile the ZIP archive |
| 143 | + * @param entry the archive entry |
| 144 | + * @param entryName the name of the entry |
| 145 | + * @return the output file |
| 146 | + */ |
| 147 | + public static File extractZipEntryAsFile(String tmpDirName, ZipFile zipFile, ZipEntry entry, String entryName) throws IOException { |
| 148 | + File tmpDir = Files.createTempDirectory(tmpDirName).toFile(); |
| 149 | + tmpDir.deleteOnExit(); |
| 150 | + String tmpName = entryName.replaceAll(File.separator, "_"); |
| 151 | + File libTmpFile = new File(tmpDir, tmpName); |
| 152 | + libTmpFile.deleteOnExit(); |
| 153 | + Files.copy(zipFile.getInputStream(entry), libTmpFile.toPath()); |
| 154 | + return libTmpFile; |
| 155 | + } |
| 156 | + |
| 157 | + public static void scanNativeCode(Database db, Parameters parameters, |
| 158 | + Set<String> methodStrings) { |
| 159 | + NativeDatabaseConsumer dbc = new DatabaseConnector(db); |
| 160 | + BinaryAnalysis.AnalysisType analysisType; |
| 161 | + if (parameters._nativeRadare) |
| 162 | + analysisType = RADARE; |
| 163 | + else if (parameters._nativeBuiltin) |
| 164 | + analysisType = BUILTIN; |
| 165 | + else if (parameters._nativeBinutils) |
| 166 | + analysisType = BINUTILS; |
| 167 | + else { |
| 168 | + analysisType = BUILTIN; |
| 169 | + System.out.println("No binary analysis type given, using default: " + analysisType.name()); |
| 170 | + } |
| 171 | + scanNativeInputs(dbc, analysisType, parameters._preciseNativeStrings, methodStrings, parameters.getInputs()); |
| 172 | + } |
| 173 | + |
| 174 | + private static void scanNativeInputs(NativeDatabaseConsumer dbc, |
| 175 | + BinaryAnalysis.AnalysisType binAnalysisType, |
| 176 | + boolean preciseNativeStrings, |
| 177 | + Set<String> methodStrings, |
| 178 | + Iterable<String> inputs) { |
| 179 | + final boolean demangle = false; |
| 180 | + final boolean truncateAddresses = true; |
| 181 | + final NativeScanner scanner = new NativeScanner(true, methodStrings); |
| 182 | + |
| 183 | + EntryProcessor gProc = (file, entry, entryName) -> scanner.scanArchiveEntry(dbc, binAnalysisType, preciseNativeStrings, truncateAddresses, demangle, file, entry, entryName); |
| 184 | + for (String input : inputs) { |
| 185 | + System.out.println("Processing native code in input: " + input); |
| 186 | + try { |
| 187 | + (new ArtifactScanner()).processArchive(input, null, gProc); |
| 188 | + } catch (IOException ex) { |
| 189 | + ex.printStackTrace(); |
| 190 | + } |
| 191 | + } |
| 192 | + } |
| 193 | + |
| 194 | + @FunctionalInterface |
| 195 | + public interface EntryProcessor { |
| 196 | + /** |
| 197 | + * Process an entry inside a .zip (JAR/AAR/APK) file. |
| 198 | + * |
| 199 | + * @param file the ZIP file |
| 200 | + * @param entry the ZIP entry |
| 201 | + * @param entryName the name of the ZIP entry |
| 202 | + */ |
| 203 | + void accept(ZipFile file, ZipEntry entry, String entryName) throws IOException; |
| 204 | + } |
| 205 | +} |
0 commit comments