Exemple #1
0
    def writeConfigurationOnEmulator(emulator, idXP, reportingConfiguration):
        logger = Logger.getLogger(__name__)
        configurationContent = """# Hooker Analysis Configuration File
# Network configuration
[elasticsearch]
elasticsearch_mode={0}
elasticsearch_nb_thread={1}
elasticsearch_ip={2}
elasticsearch_port={3}
elasticsearch_index={4}
elasticsearch_doctype={5}

# File configuration
[file]
file_mode={6}
file_name={7}

[analysis]
idXP={8}
""".format(reportingConfiguration.elasticsearchMode,
           1,
           "10.0.2.2",
           reportingConfiguration.elasticsearchPort,           
           reportingConfiguration.elasticsearchIndex,
           reportingConfiguration.elasticsearchDoctype,           
           reportingConfiguration.fileMode,
           "events.logs",
           idXP)
        logger.debug("Deploy the following configuration on emulator {0}: \n{1}".format(emulator.name, configurationContent))

        # Write on the emulator
        emulator.writeContentOnSdCard("experiment.conf", configurationContent)
 def __init__(self, commandLineParser):
     super(ManualAnalysis, self).__init__(
         MainConfiguration.build(commandLineParser),
         ReportingConfiguration.build(commandLineParser),
     )
     self._logger = Logger.getLogger(__name__)
     self.analysisConfiguration = self.__prepareAnalysis(commandLineParser)
Exemple #3
0
 def __init__(self, adbPort, name, mainConfiguration):
     self._logger = Logger.getLogger(__name__)
     self.name = name
     self.mainConfiguration = mainConfiguration
     self.adbPort = adbPort
     self._dnadroidDir = "/mnt/sdcard/dnadroid/"
     self.serialNumber = ''
     self.state = AndroidDevice.STATE_NOT_PREPARED
Exemple #4
0
 def __init__(self):
     self._logger = Logger.getLogger(__name__)
     self.parser = None
     self.manualAnalysisRequested = False
     self.automaticAnalysisRequested = False
     self.mainOptions = dict()
     self.manualOptions = dict()
     self.automaticOptions = dict()
     self.reportingOptions = dict()
     
     self.usage = "usage: %prog [options]"
     self.__parse()
Exemple #5
0
    def __init__(self, adbPort, name, mainConfiguration, backupDirectory,
                 analysisType):
        super(PhysicalDevice, self).__init__(adbPort, name, mainConfiguration)
        self.__backupDir = backupDirectory
        self._logger = Logger.getLogger(__name__)

        # Check if backup directory contains 2 folders named sdcard and partitions
        self.__checkBackupDirectories()
        self.serialNumber = name
        self.analysisType = analysisType
        self.checkAPKInstrumenter()
        # Put the state directly in started, since there is no FS preparation for real device
        self.state = AndroidDevice.STATE_STARTED
Exemple #6
0
    def __init__(self, reporter, idXp, emulator, host="127.0.0.1"):
        self._logger = Logger.getLogger(__name__)
        self.emulator = emulator
        self.emulatorNumber = emulator.emulatorId
        self.reporter = reporter
        self.idXp = idXp
        self.__telnetPort = 5554 + (self.emulatorNumber * 2)
        self.__host = host

        if emulator.mainConfiguration.typeOfDevice == 'emulated':
            self.__emulatorSerialNumber = "emulator-{0}".format(
                self.__telnetPort)
        else:
            self.__emulatorSerialNumber = emulator.name
Exemple #7
0
    def createDevice(adbNumber, name, mainConfiguration, backupDirectory, analysisType):
        logger = Logger.getLogger(__name__)

        if adbNumber is None or int(adbNumber)<0:
            raise Exception("Cannot create a device with an invalid adb number, must be > 0")

        if name is None or len(name)==0:
            raise Exception("Cannot create a device if no name is provided.")
            
        logger.debug("Creation of new device: '{0}'.".format(name))
        
        if mainConfiguration.typeOfDevice=='real':
            return PhysicalDevice(adbNumber, name, mainConfiguration, backupDirectory, analysisType)
        else:
            return AVDEmulator(adbNumber, name, mainConfiguration, analysisType)
Exemple #8
0
    def __init__(self, emulatorId, name, mainConfiguration, analysisType):
        self._logger = Logger.getLogger(__name__)
        super(AVDEmulator, self).__init__(5554 + (int(emulatorId) * 2), name,
                                          mainConfiguration)
        self.__emulatorProcess = None
        self.__partitionSize = None
        self.emulatorId = emulatorId
        self.analysisType = analysisType
        self.__duplicateAVD()

        self.serialNumber = "emulator-{0}".format(self.adbPort)
        if self.mainConfiguration.typeOfDevice != 'emulated':
            raise Exception(
                "Type of device is not emulated, please check your configuration"
            )
Exemple #9
0
    def generateIdXp(apkFiles):
        """Generates and returns the identifier of the experiment
        based on the provided list of apk following schema:
        md5("".join(sorted(apkFileNames))+currentDate)
        """
        logger = Logger.getLogger(__name__)
        apkNames = [os.path.basename(apkFile) for apkFile in apkFiles]
        strApkNames = ''.join(sorted(apkNames))
        logger.warning(strApkNames)
        
        currentDate = str(int(round(time.time() * 1000)))

        # builds an IDXP (md5(apkFile+currentDate))
        #idXp = str(hashlib.md5(strApkNames+currentDate).hexdigest())
        idXp = str(strApkNames)
        #idxp = str(models.CharField(max_length=255, unique=True, default=uuid.uuid4)

        logger.debug("ID Experiment: {0} (based on {1} and {2})".format(idXp, strApkNames, currentDate))
        
        return idXp
Exemple #10
0
 def __init__(self, reportingConfiguration):
     self._logger = Logger.getLogger(__name__)
     self.reportingConfiguration = reportingConfiguration
     self.__initializeReporters()
     if self.reportingConfiguration.elasticsearchMode:
         self.esInterrogator = EsInterrogator(self.es)
Exemple #11
0
 def __init__(self, mainConfiguration, reportingConfiguration):        
     self._logger = Logger.getLogger(__name__)
     self.mainConfiguration = mainConfiguration
     self.reportingConfiguration = reportingConfiguration
     self.reporter = Reporter(self.reportingConfiguration)
Exemple #12
0
def executeExperiment(args):
    """
    Executes the analysis for an application.
    The analysis depends of the scenario the user as defined in configuration.
    """
    logger = Logger.getLogger(__name__)
    (listOfAPKs, iEmulator, mainConfiguration, analysisConfiguration,
     reportingConfiguration) = args
    reporter = Reporter(reportingConfiguration)

    logger.warning("Execute experiment with scenario: [{0}]".format(', '.join(
        analysisConfiguration.scenario)))

    # When you play with emulators, you can modify this variable to sleep a bit longer.
    # Default has to be >1
    SLEEP_FACTOR = 1

    if mainConfiguration.typeOfDevice == 'emulated':
        SLEEP_FACTOR = 5
    if SLEEP_FACTOR < 1:
        raise Exception("SLEEP_FACTOR variable cannot be less than 1.")

    while True:
        # Pick one APK to analyse
        try:
            apkToAnalyze = listOfAPKs.get()  # 0xFFFF
            logger.info("APK to analyze : {0}".format(apkToAnalyze))

            # Build the identifier experiment
            idXp = Analysis.generateIdXp([apkToAnalyze])

            # Build the emulator name
            if mainConfiguration.typeOfDevice == 'emulated':
                emulatorName = "Emulator_{0}".format(iEmulator)
            else:
                emulatorName = mainConfiguration.deviceId

            # Create a new report for this analysis
            logger.debug("Create report.")
            Analysis.createReport(reporter, idXp, emulatorName, "unknown",
                                  apkToAnalyze, "automatic",
                                  mainConfiguration.name)

            # Execute static analysis
            logger.debug("Executing the Static Analysis")
            staticAnalysis = StaticAnalysis(apkToAnalyze, mainConfiguration,
                                            reporter, idXp)
            staticAnalysis.execute()
            logger.info(staticAnalysis)

            # Create the emulator
            if mainConfiguration.typeOfDevice == 'emulated':
                device = Analysis.createEmulator(iEmulator,
                                                 emulatorName,
                                                 mainConfiguration,
                                                 analysisType="automatic")
            else:
                device = Analysis.createDevice(
                    iEmulator,
                    mainConfiguration.deviceId,
                    mainConfiguration,
                    analysisConfiguration.backupDirectory,
                    analysisType="automatic")

            if device is None:
                raise Exception(
                    "Something has prevented the creation of an device.")

            # Starts the device
            Analysis.reportEvent(reporter, idXp, emulatorName, "Start device")
            device.start()

            # Install et execute preparation applications
            if mainConfiguration.typeOfDevice == 'emulated':
                for prepareAPK in analysisConfiguration.prepareAPKs:
                    Analysis.reportEvent(reporter, idXp, emulatorName,
                                         "Install preparation APK", prepareAPK)
                    device.installAPK(prepareAPK)

                # Execute preparation applications
                for prepareAPK in analysisConfiguration.prepareAPKs:
                    Analysis.reportEvent(reporter, idXp, emulatorName,
                                         "Start activity",
                                         os.path.basename(prepareAPK)[:-4])
                    device.startActivity(os.path.basename(prepareAPK)[:-4])

            # Writes the experiment configuration on the device
            Analysis.reportEvent(reporter, idXp, emulatorName,
                                 "Write configuration file")
            Analysis.writeConfigurationOnEmulator(device, idXp,
                                                  reportingConfiguration)

            if mainConfiguration.typeOfDevice == 'emulated':
                sleepDuration = 20
                logger.debug(
                    "Waiting {0} seconds for the device to prepare...".format(
                        sleepDuration))
                time.sleep(sleepDuration)

            # Install the targeted application
            Analysis.reportEvent(reporter, idXp, emulatorName,
                                 "Install target APK", apkToAnalyze)
            device.installAPK(apkToAnalyze)
            time.sleep(SLEEP_FACTOR)

            # We then follow the scenario user has filled in configuration
            for order in analysisConfiguration.scenario:
                if "execute" == order:
                    Analysis.reportEvent(reporter, idXp, emulatorName,
                                         "Launching main activity",
                                         staticAnalysis.mainActivity)
                    logger.info("Starting main activity: {0}".format(
                        staticAnalysis.mainActivity))
                    device.startActivityFromPackage(
                        staticAnalysis.packageName,
                        staticAnalysis.mainActivity)
                    time.sleep(5 * SLEEP_FACTOR)
                elif "stimulate" == order:
                    Analysis.reportEvent(reporter, idXp, emulatorName,
                                         "Stimulating package with monkey",
                                         staticAnalysis.packageName)
                    logger.info("Stimulating with monkey: {0}".format(
                        staticAnalysis.packageName))
                    device.stimulateWithMonkey(staticAnalysis.packageName)
                    time.sleep(10 * SLEEP_FACTOR)
                elif "externalStimulation" == order:
                    Analysis.reportEvent(
                        reporter, idXp, emulatorName,
                        "Stimulating phone with external conditions")
                    logger.info(
                        "Stimulating phone with external conditions...")
                    externalStimulation = TelnetEmulation(
                        reporter, idXp, device)
                    externalStimulation.start()
                    time.sleep(10 * SLEEP_FACTOR)
                elif "reboot" == order:
                    Analysis.reportEvent(reporter, idXp, emulatorName,
                                         "Rebooting device")
                    logger.info("Accepting Installation")
                    device.reboot()
                    time.sleep(5 * SLEEP_FACTOR)
                elif "accept" == order:
                    logger.info("Accepting Installation")
                    Analysis.reportEvent(reporter, idXp, emulatorName,
                                         "Accepting Installation")
                    device.accept()
                    time.sleep(7 * SLEEP_FACTOR)

            Analysis.reportEvent(reporter, idXp, emulatorName,
                                 "Analysis has finished", apkToAnalyze)

            logger.info("Analysis of APK {0} has been finished.")
            Analysis.reportEvent(reporter, idXp, emulatorName,
                                 "Emulator closed")
            device.stop()
            finalize()

        except KeyboardInterrupt:
            logger.debug("Keyboard interrupt caught\n")
            # Try to stop device if necessary
            if device is not None:
                device.stop()
            break

        except Exception, e:
            logger.error(
                "Exception while executing an experiment : {0}".format(e))
            tb = traceback.format_exc()
            logger.error(tb)
            try:
                device.stop()
            except Exception:
                logger.error("Cannot stop the AVD, quitting experience.")
                break
Exemple #13
0
 def __init__(self, apkToAnalyze, mainConfiguration, reporter, idXp):
     self._logger = Logger.getLogger(__name__)
     self.apkToAnalyze = os.path.abspath(apkToAnalyze)
     self.androguardPath = mainConfiguration.androguardPath
     self.reporter = reporter
     self.idXp = idXp
Exemple #14
0
#!/usr/bin/env python

from dnadroid_common import Logger
logger = Logger.getLogger(__name__)

import traceback

from dnadroid.cli.CommandLine import CommandLine
from dnadroid.ManualAnalysis import ManualAnalysis
from dnadroid.AutomaticAnalysis import AutomaticAnalysis


def main():
    """Global entry point"""
    # Initiates the command line parser
    commandLineParser = CommandLine()

    # Prepare the proper kind of analysis based on user args.
    analysis = None
    if commandLineParser.manualAnalysisRequested:
        # Manual analysis
        analysis = ManualAnalysis(commandLineParser)

    elif commandLineParser.automaticAnalysisRequested:
        # Automated analysis
        analysis = AutomaticAnalysis(commandLineParser)
    else:
        # No analysis specified
        logger.warning("No analysis requested.")

    # Executes the prepared analysis