Exemplo n.º 1
0
    def start(self):
        """
        Uses telnetlib to connect to the emulator. We grep for keyword "OK" and 
        launch the different commands to simulate operations. Between each of them, 
        we sleep for a random time.
        Remark: from the Android Documentation, we do not have meaning to simulate 
        neither WIFI nor bluetooth
        """
        self._logger.debug("Starting stimulation with emulator: {0}.".format(self.__emulatorSerialNumber))

        Analysis.reportEvent(self.reporter, self.idXp, "Emulator", "Opening telnet session with emulator: {0}".format(self.__emulatorSerialNumber))
        self.session = telnetlib.Telnet(self.__host, self.__telnetPort)
        self._checkAnswer(1)
   
        #Todo: build something different each time
        try:
            list_functions = [self._sendSms, self._setGpsLocation, self._simulatePhoneConversation, self._simulateChangingData, self._sendSensorAcceleration, self._simulateChangingData]
            random.seed()
            for function in list_functions:
                function()
                n = random.randint(2, 10)
                self._logger.debug("Sleeping for {0} seconds".format(n))
                time.sleep(n)

        except NameError as ne:
            raise Exception (ne)

        Analysis.reportEvent(self.reporter, self.idXp, "Emulator", "Closing telnet for emulator: {0}".format(self.__emulatorSerialNumber))
        self._logger.debug("Closing telnet")
        self.session.write("exit\r\n")
        self.session.close()
Exemplo n.º 2
0
 def _simulatePhoneConversation(self):
     """
     Simulate a phone conversation on the emulator.
     First, start the call, wait for several seconds, and hang up.
     """
     Analysis.reportEvent(self.reporter, self.idXp, "Emulator", "Calling emulator: {0}".format(self.__emulatorSerialNumber))
     self._logger.debug("Calling emulator"),
     self.session.write("gsm call 0633416719\r\n")
     if self._checkAnswer(1):
         time.sleep(5)
         Analysis.reportEvent(self.reporter, self.idXp, "Emulator", "Answering call for emulator: {0}".format(self.__emulatorSerialNumber))
         self._logger.debug("Answer call"),
         self.session.write("gsm accept 0633416719\r\n")
         if self._checkAnswer(1):
             time.sleep(10)
             Analysis.reportEvent(self.reporter, self.idXp, "Emulator", "Hanging up call for emulator: {0}".format(self.__emulatorSerialNumber))
             self._logger.debug("Hang up call"),
             self.session.write("gsm cancel 0633416719\r\n")
             self._checkAnswer(1)
         else:
             Analysis.reportEvent(self.reporter, self.idXp, "Emulator", "Cannot accept call for emulator: {0}".format(self.__emulatorSerialNumber))
             self._logger.error("Cannot accept call")
     else:
         Analysis.reportEvent(self.reporter, self.idXp, "Emulator", "Cannot make call for emulator: {0}".format(self.__emulatorSerialNumber))
         self._logger.error("Cannot make call")
Exemplo n.º 3
0
 def _simulate2Gto3G(self):
     """ Simulate a 2G to 3G connection """
     Analysis.reportEvent(self.reporter, self.idXp, "Emulator", "Simulating 2G to 3G for emulator: {0}".format(self.__emulatorSerialNumber))
     self._logger.debug("Simulating 2G to 3G"),
     self.session.write("gsm voice on\r\n")
     if self._checkAnswer(0):
         self.session.write("gsm data on\r\n")
         self._checkAnswer(1)
Exemplo n.º 4
0
 def _sendSensorAcceleration(self):
     """ Simulate a sensor acceleration """
     Analysis.reportEvent(self.reporter, self.idXp, "Emulator", "Sending sensor acceleration for emulator: {0}".format(self.__emulatorSerialNumber))
     self._logger.debug("Sending a sensor acceleration"),
     self.session.write("sensor set acceleration 10\r\n")
     self._checkAnswer(1)
     self.session.write("sensor set orientation 10\r\n") #--> this is disabled for emulator?
     if not self._checkAnswer(0):
         self._logger.warning("Emulator doesn't seem to implement sensor orientation")
Exemplo n.º 5
0
 def _simulate3Gto2G(self):
     """ Simulate a 3G to 2G connection """
     Analysis.reportEvent(self.reporter, self.idXp, "Emulator", "Simulating 3G to 2G for emulator: {0}".format(self.__emulatorSerialNumber))
     self._logger.debug("Simulating 3G to 2G"),
     self.session.write("gsm voice on\r\n")
     if self._checkAnswer(0):
         self.session.write("gsm data off\r\n")
         self._checkAnswer(1)
     else:
         self._logger.errr("Error: Cannot make GSM voice on")
Exemplo n.º 6
0
 def _simulate2Gto3G(self):
     """ Simulate a 2G to 3G connection """
     Analysis.reportEvent(
         self.reporter, self.idXp, "Emulator",
         "Simulating 2G to 3G for emulator: {0}".format(
             self.__emulatorSerialNumber))
     self._logger.debug("Simulating 2G to 3G"),
     self.session.write("gsm voice on\r\n")
     if self._checkAnswer(0):
         self.session.write("gsm data on\r\n")
         self._checkAnswer(1)
Exemplo n.º 7
0
 def _simulateChangingData(self):
     """ Simulate a change of data connection """
     Analysis.reportEvent(self.reporter, self.idXp, "Emulator", "Simulating data connection change for emulator: {0}".format(self.__emulatorSerialNumber))
     self._logger.debug("Simulating data connection change"),
     self.session.write("gsm status\r\n")
     # This is a little different since we need the return string to chose which way to go: 2G -> 3G or 3G -> 2G
     res = self.session.read_until("OK")
     
     if ("unregistered" in res):
         self._simulate2Gto3G()
     else:
         self._simulate3Gto2G()
Exemplo n.º 8
0
 def _simulate3Gto2G(self):
     """ Simulate a 3G to 2G connection """
     Analysis.reportEvent(
         self.reporter, self.idXp, "Emulator",
         "Simulating 3G to 2G for emulator: {0}".format(
             self.__emulatorSerialNumber))
     self._logger.debug("Simulating 3G to 2G"),
     self.session.write("gsm voice on\r\n")
     if self._checkAnswer(0):
         self.session.write("gsm data off\r\n")
         self._checkAnswer(1)
     else:
         self._logger.errr("Error: Cannot make GSM voice on")
Exemplo n.º 9
0
 def _sendSensorAcceleration(self):
     """ Simulate a sensor acceleration """
     Analysis.reportEvent(
         self.reporter, self.idXp, "Emulator",
         "Sending sensor acceleration for emulator: {0}".format(
             self.__emulatorSerialNumber))
     self._logger.debug("Sending a sensor acceleration"),
     self.session.write("sensor set acceleration 10\r\n")
     self._checkAnswer(1)
     self.session.write("sensor set orientation 10\r\n"
                        )  #--> this is disabled for emulator?
     if not self._checkAnswer(0):
         self._logger.warning(
             "Emulator doesn't seem to implement sensor orientation")
Exemplo n.º 10
0
    def _simulateChangingData(self):
        """ Simulate a change of data connection """
        Analysis.reportEvent(
            self.reporter, self.idXp, "Emulator",
            "Simulating data connection change for emulator: {0}".format(
                self.__emulatorSerialNumber))
        self._logger.debug("Simulating data connection change"),
        self.session.write("gsm status\r\n")
        # This is a little different since we need the return string to chose which way to go: 2G -> 3G or 3G -> 2G
        res = self.session.read_until("OK")

        if ("unregistered" in res):
            self._simulate2Gto3G()
        else:
            self._simulate3Gto2G()
Exemplo n.º 11
0
    def start(self):
        """
        Uses telnetlib to connect to the emulator. We grep for keyword "OK" and 
        launch the different commands to simulate operations. Between each of them, 
        we sleep for a random time.
        Remark: from the Android Documentation, we do not have meaning to simulate 
        neither WIFI nor bluetooth
        """
        self._logger.debug("Starting stimulation with emulator: {0}.".format(
            self.__emulatorSerialNumber))

        Analysis.reportEvent(
            self.reporter, self.idXp, "Emulator",
            "Opening telnet session with emulator: {0}".format(
                self.__emulatorSerialNumber))
        self.session = telnetlib.Telnet(self.__host, self.__telnetPort)
        self._checkAnswer(1)

        #Todo: build something different each time
        try:
            list_functions = [
                self._sendSms, self._setGpsLocation,
                self._simulatePhoneConversation, self._simulateChangingData,
                self._sendSensorAcceleration, self._simulateChangingData
            ]
            random.seed()
            for function in list_functions:
                function()
                n = random.randint(20, 30)
                self._logger.debug("Sleeping for {0} seconds".format(n))
                time.sleep(n)

        except NameError as ne:
            raise Exception(ne)

        Analysis.reportEvent(
            self.reporter, self.idXp, "Emulator",
            "Closing telnet for emulator: {0}".format(
                self.__emulatorSerialNumber))
        self._logger.debug("Closing telnet")
        self.session.write("exit\r\n")
        self.session.close()
Exemplo n.º 12
0
    def test(self):
        device = Analysis.createDevice(0, self.mainConfiguration.deviceId, self.mainConfiguration, self.analysisConfiguration.backupDirectory)
        if device is None:
            raise Exception("Something has prevented the instanciation of the device.")

        # Starts the device
        device.start()
        #device.restoreSDCard()
        time.sleep(5)
        device.stop()
        exit()
Exemplo n.º 13
0
 def _simulatePhoneConversation(self):
     """
     Simulate a phone conversation on the emulator.
     First, start the call, wait for several seconds, and hang up.
     """
     Analysis.reportEvent(
         self.reporter, self.idXp, "Emulator",
         "Calling emulator: {0}".format(self.__emulatorSerialNumber))
     self._logger.debug("Calling emulator"),
     self.session.write("gsm call 0633416719\r\n")
     if self._checkAnswer(1):
         time.sleep(5)
         Analysis.reportEvent(
             self.reporter, self.idXp, "Emulator",
             "Answering call for emulator: {0}".format(
                 self.__emulatorSerialNumber))
         self._logger.debug("Answer call"),
         self.session.write("gsm accept 0633416719\r\n")
         if self._checkAnswer(1):
             time.sleep(10)
             Analysis.reportEvent(
                 self.reporter, self.idXp, "Emulator",
                 "Hanging up call for emulator: {0}".format(
                     self.__emulatorSerialNumber))
             self._logger.debug("Hang up call"),
             self.session.write("gsm cancel 0633416719\r\n")
             self._checkAnswer(1)
         else:
             Analysis.reportEvent(
                 self.reporter, self.idXp, "Emulator",
                 "Cannot accept call for emulator: {0}".format(
                     self.__emulatorSerialNumber))
             self._logger.error("Cannot accept call")
     else:
         Analysis.reportEvent(
             self.reporter, self.idXp, "Emulator",
             "Cannot make call for emulator: {0}".format(
                 self.__emulatorSerialNumber))
         self._logger.error("Cannot make call")
Exemplo n.º 14
0
    def test(self):
        device = Analysis.createDevice(
            0, self.mainConfiguration.deviceId, self.mainConfiguration,
            self.analysisConfiguration.backupDirectory)
        if device is None:
            raise Exception(
                "Something has prevented the instanciation of the device.")

        # Starts the device
        device.start()
        #device.restoreSDCard()
        time.sleep(5)
        device.stop()
        exit()
Exemplo n.º 15
0
    def start(self):
        """Starts the current manual analysis"""

        if self.mainConfiguration is None:
            raise Exception(
                "No main configuration found, cannot start the analysis..")

        if self.reportingConfiguration is None:
            raise Exception(
                "No reporting configuration found, cannot start the analysis.")

        if self.analysisConfiguration is None:
            raise Exception(
                "No analysis configuration found, cannot start the analysis.")

        self._logger.info(str(self))

        # Build the identifier experiment
        idXp = self._generateIdXp(self.analysisConfiguration.apkFiles)

        # Targeted APK
        analyzedAPKFile = self.analysisConfiguration.apkFiles[0]

        # Execute the analysis on the first emulator
        iEmulator = 0
        emulatorName = "Emulator_{0}".format(iEmulator)

        # Create a new report for this analysis
        Analysis.createReport(self.reporter, idXp, emulatorName, "unknown",
                              analyzedAPKFile, "manual", None)

        # Execute static analysis
        staticAnalysis = StaticAnalysis(analyzedAPKFile,
                                        self.mainConfiguration, self.reporter,
                                        idXp)

        Analysis.reportEvent(
            self.reporter, idXp, "Analysis",
            "Executing Static Analysis on {0}".format(analyzedAPKFile))
        staticAnalysis.execute()
        self._logger.info(staticAnalysis)

        Analysis.reportEvent(
            self.reporter, idXp, "Emulator",
            "creation of the Emulator {0}".format(emulatorName))
        emulator = self._createEmulator(iEmulator, emulatorName)

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

        # Starts the emulator
        Analysis.reportEvent(self.reporter, idXp, "Emulator", "start")
        emulator.start()

        # Install preparation applications
        for prepareAPK in self.analysisConfiguration.prepareAPKs:
            Analysis.reportEvent(self.reporter, idXp, "Emulator", "installAPK",
                                 prepareAPK)
            emulator.installAPK(prepareAPK)

        # Execute preparation applications
        for prepareAPK in self.analysisConfiguration.prepareAPKs:
            Analysis.reportEvent(self.reporter, idXp, "Emulator",
                                 "startActivity",
                                 os.path.basename(prepareAPK)[:-4])
            emulator.startActivity(os.path.basename(prepareAPK)[:-4])

        # Writes the experiment configuration on the emulator
        Analysis.reportEvent(self.reporter, idXp, "Emulator",
                             "writeConfiguration")
        self._writeConfigurationOnEmulator(emulator, idXp)

        sleepDuration = 30
        self._logger.debug(
            "Waiting {0} seconds for the emulator to prepare...".format(
                sleepDuration))
        time.sleep(sleepDuration)

        # Install the targeted application
        for analysisAPK in self.analysisConfiguration.apkFiles:
            Analysis.reportEvent(self.reporter, idXp, "Emulator", "installAPK",
                                 analysisAPK)
            emulator.installAPK(analysisAPK)

        Analysis.reportEvent(self.reporter, idXp, "Emulator",
                             "Launching main activity",
                             staticAnalysis.mainActivity)
        self._logger.info("Starting main activity: {0}".format(
            staticAnalysis.mainActivity))
        emulator.startActivityFromPackage(staticAnalysis.packageName,
                                          staticAnalysis.mainActivity)

        # The user is now requested to perform any operations he wants
        # this script waits for the emulator process to be closed
        self._logger.info("Proceed to the stimulation of the environnment.")
        self._logger.info(
            "Once achieved, close the emulator and waits for the hooker to finish."
        )
        Analysis.reportEvent(self.reporter, idXp, "Emulator", "waitToBeClosed")

        emulator.waitToBeClosed()

        Analysis.reportEvent(self.reporter, idXp, "Emulator", "closed")
        self._logger.info("Emulator has finished.")
Exemplo n.º 16
0
    def start(self):
        """Starts a manual analysis"""

        if self.mainConfiguration is None:
            raise Exception(
                "No main configuration found, cannot start the analysis..")
        if self.reportingConfiguration is None:
            raise Exception(
                "No reporting configuration found, cannot start the analysis.")
        if self.analysisConfiguration is None:
            raise Exception(
                "No analysis configuration found, cannot start the analysis.")

        self._logger.info(str(self))

        # Build the identifier experiment
        idXp = self._generateIdXp(self.analysisConfiguration.apkFiles)

        # Targeted APK
        analyzedAPKFile = self.analysisConfiguration.apkFiles[0]

        # Execute the analysis on the first emulator
        iEmulator = 0
        emulatorName = "Emulator_{0}".format(iEmulator)

        # Create a new report for this analysis
        Analysis.createReport(self.reporter, idXp, emulatorName, "unknown",
                              analyzedAPKFile, "manual",
                              self.mainConfiguration.name)

        # Execute static analysis
        staticAnalysis = StaticAnalysis(analyzedAPKFile,
                                        self.mainConfiguration, self.reporter,
                                        idXp)

        Analysis.reportEvent(
            self.reporter, idXp, "Analysis",
            "Executing static analysis on {0}".format(analyzedAPKFile))
        staticAnalysis.execute()
        self._logger.info(staticAnalysis)

        if self.mainConfiguration.typeOfDevice == 'emulated':
            device = Analysis.createEmulator(iEmulator,
                                             emulatorName,
                                             self.mainConfiguration,
                                             analysisType="manual")
        else:
            device = Analysis.createDevice(
                iEmulator,
                self.mainConfiguration.deviceId,
                self.mainConfiguration,
                self.analysisConfiguration.backupDirectory,
                analysisType="manual")

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

        # Starts the device
        Analysis.reportEvent(self.reporter, idXp, emulatorName, "Start device")
        try:
            device.start()
        except:
            self._logger.error(traceback.format_exc())
            device.stop()
            return

        # Install preparation applications
        # A real device do not need preparation applications
        if self.mainConfiguration.typeOfDevice == 'emulated':
            for prepareAPK in self.analysisConfiguration.prepareAPKs:
                Analysis.reportEvent(self.reporter, idXp, emulatorName,
                                     "Install preparation APK", prepareAPK)
                device.installAPK(prepareAPK)

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

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

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

        # Install the targeted application
        for analysisAPK in self.analysisConfiguration.apkFiles:
            Analysis.reportEvent(self.reporter, idXp, emulatorName,
                                 "Install target APK", analysisAPK)
            device.installAPK(analysisAPK)

        Analysis.reportEvent(self.reporter, idXp, emulatorName,
                             "Launching main activity",
                             staticAnalysis.mainActivity)
        self._logger.info("Starting main activity: {0}".format(
            staticAnalysis.mainActivity))
        device.startActivityFromPackage(staticAnalysis.packageName,
                                        staticAnalysis.mainActivity)

        # The user is now requested to perform any operations he wants
        # this script waits for the device process to be closed
        self._logger.info("Proceed to the stimulation of the environnment.")
        self._logger.info(
            "Once achieved, close the device and waits for the hooker to finish."
        )
        Analysis.reportEvent(self.reporter, idXp, emulatorName,
                             "Wait for emulator to be closed")

        device.waitToBeClosed()
        if self.mainConfiguration.typeOfDevice == 'real':
            device.stop(True)
        Analysis.reportEvent(self.reporter, idXp, emulatorName,
                             "Analysis has finished")
        Analysis.reportEvent(self.reporter, idXp, emulatorName,
                             "Emulator closed")
        self._logger.info("Device has finished, IDXP is {0}".format(idXp))
Exemplo n.º 17
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)))

    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
            emulatorName = "Emulator_{0}".format(iEmulator)

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

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

            # Create the emulator
            emulator = Analysis.createEmulator(iEmulator, emulatorName,
                                               mainConfiguration)

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

            # Starts the emulator
            Analysis.reportEvent(reporter, idXp, "Emulator", "start")
            emulator.start()

            # Install et execute preparation applications
            for prepareAPK in analysisConfiguration.prepareAPKs:
                Analysis.reportEvent(reporter, idXp, "Emulator", "installAPK",
                                     prepareAPK)
                emulator.installAPK(prepareAPK)

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

            # Writes the experiment configuration on the emulator
            Analysis.reportEvent(reporter, idXp, "Emulator",
                                 "writeConfiguration")
            Analysis.writeConfigurationOnEmulator(emulator, idXp,
                                                  reportingConfiguration)

            sleepDuration = 30
            logger.debug(
                "Waiting {0} seconds for the emulator to prepare...".format(
                    sleepDuration))
            time.sleep(sleepDuration)

            # Install the targeted application
            Analysis.reportEvent(reporter, idXp, "Emulator", "installAPK",
                                 apkToAnalyze)
            emulator.installAPK(apkToAnalyze)
            time.sleep(5)

            # We then follow the scenario user has filled in configuration
            for order in analysisConfiguration.scenario:
                if "execute" == order:
                    Analysis.reportEvent(reporter, idXp, "Emulator",
                                         "Launching main activity",
                                         staticAnalysis.mainActivity)
                    logger.info("Starting main activity: {0}".format(
                        staticAnalysis.mainActivity))
                    emulator.startActivityFromPackage(
                        staticAnalysis.packageName,
                        staticAnalysis.mainActivity)
                    time.sleep(60)
                elif "stimulate" == order:
                    Analysis.reportEvent(reporter, idXp, "Emulator",
                                         "Stimulating package with monkey",
                                         staticAnalysis.packageName)
                    logger.info("Stimulating with monkey: {0}".format(
                        staticAnalysis.packageName))
                    emulator.stimulateWithMonkey(staticAnalysis.packageName)
                    time.sleep(80)
                elif "externalStimulation" == order:
                    Analysis.reportEvent(
                        reporter, idXp, "Emulator",
                        "Stimulating phone with external conditions")
                    logger.info(
                        "Stimulating phone with external conditions...")
                    externalStimulation = TelnetEmulation(
                        reporter, idXp, emulator, iEmulator)
                    externalStimulation.start()
                    time.sleep(30)
                elif "reboot" == order:
                    Analysis.reportEvent(reporter, idXp, "Emulator",
                                         "Rebooting emulator")
                    logger.info("Rebooting emulator.")
                    emulator.rebootAVD()
                    time.sleep(100)

            Analysis.reportEvent(reporter, idXp, "Emulator",
                                 "Finished analysis", apkToAnalyze)

            logger.info("Analysis of APK {0} has been finished.")
            Analysis.reportEvent(reporter, idXp, "Emulator", "closed")
            emulator.stopAVD()

        except KeyboardInterrupt:
            pass
        except Exception, e:
            logger.error(
                "Exception while executing an experiment : {0}".format(e))
            tb = traceback.format_exc()
            logger.error(tb)
            try:
                emulator.stopAVD()
            except Exception:
                logger.error("Cannot stop the AVD.")
Exemplo n.º 18
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 = 30
                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(5 * SLEEP_FACTOR / 5)

            # 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("Rebooting device.")
                    device.reboot()
                    time.sleep(5 * 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()

        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
Exemplo n.º 19
0
    def start(self):
        """Starts a manual analysis"""

        if self.mainConfiguration is None:
            raise Exception("No main configuration found, cannot start the analysis..")
        if self.reportingConfiguration is None:
            raise Exception("No reporting configuration found, cannot start the analysis.")
        if self.analysisConfiguration is None:
            raise Exception("No analysis configuration found, cannot start the analysis.")

        self._logger.info(str(self))

        # Build the identifier experiment
        idXp = self._generateIdXp(self.analysisConfiguration.apkFiles)

        # Targeted APK
        analyzedAPKFile = self.analysisConfiguration.apkFiles[0]

        # Execute the analysis on the first emulator
        iEmulator = 0
        emulatorName = "Emulator_{0}".format(iEmulator)

        # Create a new report for this analysis
        Analysis.createReport(self.reporter, idXp, emulatorName, "unknown", analyzedAPKFile, "manual", None)

        # Execute static analysis
        staticAnalysis = StaticAnalysis(analyzedAPKFile, self.mainConfiguration, self.reporter, idXp)

        Analysis.reportEvent(
            self.reporter, idXp, "Analysis", "Executing Static Analysis on {0}".format(analyzedAPKFile)
        )
        staticAnalysis.execute()
        self._logger.info(staticAnalysis)

        Analysis.reportEvent(self.reporter, idXp, "Emulator", "creation of the Emulator {0}".format(emulatorName))

        if self.mainConfiguration.typeOfDevice == "emulated":

            # first step is to create the templates for all our emulators
            self._logger.debug(
                "Create {0} templates, one for each emulator".format(self.analysisConfiguration.maxNumberOfEmulators)
            )
            AVDEmulator.createTemplates(self.mainConfiguration, self.analysisConfiguration)
            device = self._createEmulator(iEmulator, emulatorName)
        else:
            device = Analysis.createDevice(
                iEmulator,
                self.mainConfiguration.deviceId,
                self.mainConfiguration,
                self.analysisConfiguration.backupDirectory,
            )

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

        # Starts the device
        Analysis.reportEvent(self.reporter, idXp, "Emulator", "start")
        device.start()

        # Install preparation applications
        # A real device do not need preparation applications
        if self.mainConfiguration.typeOfDevice == "emulated":
            for prepareAPK in self.analysisConfiguration.prepareAPKs:
                Analysis.reportEvent(self.reporter, idXp, "Emulator", "installAPK", prepareAPK)
                device.installAPK(prepareAPK)

            # Execute preparation applications
            for prepareAPK in self.analysisConfiguration.prepareAPKs:
                Analysis.reportEvent(
                    self.reporter, idXp, "Emulator", "startActivity", os.path.basename(prepareAPK)[:-4]
                )
                device.startActivity(os.path.basename(prepareAPK)[:-4])
        else:
            self._logger.debug("Continuing...")

        # Writes the experiment configuration on the device
        Analysis.reportEvent(self.reporter, idXp, "Emulator", "writeConfiguration")
        self._writeConfigurationOnEmulator(device, idXp)

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

        # Install the targeted application
        for analysisAPK in self.analysisConfiguration.apkFiles:
            Analysis.reportEvent(self.reporter, idXp, "Emulator", "installAPK", analysisAPK)
            device.installAPK(analysisAPK)

        Analysis.reportEvent(self.reporter, idXp, "Emulator", "Launching main activity", staticAnalysis.mainActivity)
        self._logger.info("Starting main activity: {0}".format(staticAnalysis.mainActivity))
        device.startActivityFromPackage(staticAnalysis.packageName, staticAnalysis.mainActivity)

        # The user is now requested to perform any operations he wants
        # this script waits for the device process to be closed
        self._logger.info("Proceed to the stimulation of the environnment.")
        self._logger.info("Once achieved, close the device and waits for the hooker to finish.")
        Analysis.reportEvent(self.reporter, idXp, "Emulator", "waitToBeClosed")

        device.waitToBeClosed()
        if self.mainConfiguration.typeOfDevice == "real":
            device.stop(True)

        Analysis.reportEvent(self.reporter, idXp, "Emulator", "closed")
        self._logger.info("Device has finished, IDXP is {0}".format(idXp))
Exemplo n.º 20
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)))

    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
            emulatorName = "Emulator_{0}".format(iEmulator)

            # Create a new report for this analysis
            logger.debug("Create report.")
            Analysis.createReport(reporter, idXp, emulatorName, "unknown", apkToAnalyze, "automatic", None) 
        
            # Execute static analysis
            logger.debug("Executing the Static Analysis")
            staticAnalysis = StaticAnalysis(apkToAnalyze, mainConfiguration, reporter, idXp)
            staticAnalysis.execute()
            logger.info(staticAnalysis)

            # Create the emulator
            emulator = Analysis.createEmulator(iEmulator, emulatorName, mainConfiguration)
            
            if emulator is None:
                raise Exception("Something has prevented the creation of an emulator.")

            # Starts the emulator
            Analysis.reportEvent(reporter, idXp, "Emulator", "start")
            emulator.start()

            # Install et execute preparation applications
            for prepareAPK in analysisConfiguration.prepareAPKs:
                Analysis.reportEvent(reporter, idXp, "Emulator", "installAPK", prepareAPK)
                emulator.installAPK(prepareAPK)

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

            # Writes the experiment configuration on the emulator
            Analysis.reportEvent(reporter, idXp, "Emulator", "writeConfiguration")
            Analysis.writeConfigurationOnEmulator(emulator, idXp, reportingConfiguration)

            sleepDuration = 30
            logger.debug("Waiting {0} seconds for the emulator to prepare...".format(sleepDuration))
            time.sleep(sleepDuration)

            # Install the targeted application
            Analysis.reportEvent(reporter, idXp, "Emulator", "installAPK", apkToAnalyze)
            emulator.installAPK(apkToAnalyze)
            time.sleep(5)

            # We then follow the scenario user has filled in configuration
            for order in analysisConfiguration.scenario:
                if "execute" == order:
                    Analysis.reportEvent(reporter, idXp, "Emulator", "Launching main activity", staticAnalysis.mainActivity)
                    logger.info("Starting main activity: {0}".format(staticAnalysis.mainActivity))
                    emulator.startActivityFromPackage(staticAnalysis.packageName, staticAnalysis.mainActivity)
                    time.sleep(60)
                elif "stimulate" == order:
                    Analysis.reportEvent(reporter, idXp, "Emulator", "Stimulating package with monkey", staticAnalysis.packageName)
                    logger.info("Stimulating with monkey: {0}".format(staticAnalysis.packageName))
                    emulator.stimulateWithMonkey(staticAnalysis.packageName)
                    time.sleep(80)
                elif "externalStimulation" == order:
                    Analysis.reportEvent(reporter, idXp, "Emulator", "Stimulating phone with external conditions")
                    logger.info("Stimulating phone with external conditions...")
                    externalStimulation = TelnetEmulation(reporter, idXp, emulator, iEmulator)
                    externalStimulation.start()
                    time.sleep(30)
                elif "reboot" == order:
                    Analysis.reportEvent(reporter, idXp, "Emulator", "Rebooting emulator")
                    logger.info("Rebooting emulator.")
                    emulator.rebootAVD()
                    time.sleep(100)

            Analysis.reportEvent(reporter, idXp, "Emulator", "Finished analysis", apkToAnalyze)
            
            logger.info("Analysis of APK {0} has been finished.")
            Analysis.reportEvent(reporter, idXp, "Emulator", "closed")
            emulator.stopAVD()

        except KeyboardInterrupt:
            pass
        except Exception, e:
            logger.error("Exception while executing an experiment : {0}".format(e))
            tb = traceback.format_exc()
            logger.error(tb)
            try:
                emulator.stopAVD()
            except Exception:
                logger.error("Cannot stop the AVD.")
Exemplo n.º 21
0
 def _setGpsLocation(self):
     """ Set the GPS location of emulator somewhere in Paris """
     Analysis.reportEvent(self.reporter, self.idXp, "Emulator", "Setting GPS location to somewhere in Paris for emulator: {0}".format(self.__emulatorSerialNumber))
     self._logger.debug("Setting GPS location to somewhere in Paris"),
     self.session.write("geo fix 2.33 48.89\r\n")
     self._checkAnswer(1)
Exemplo n.º 22
0
 def _sendSms(self):
     """ Send an SMS to emulator """
     Analysis.reportEvent(self.reporter, self.idXp, "Emulator", "Sending SMS to emulator: {0}".format(self.__emulatorSerialNumber))
     self._logger.debug("Sending SMS to emulator"),
     self.session.write("sms send 062445581 It was nice to see you again, thx for this evening.\r\n")
     self._checkAnswer(1)
Exemplo n.º 23
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 = 10
    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", None) 
        
            # Execute static analysis
            logger.debug("Executing the Static Analysis")
            staticAnalysis = StaticAnalysis(apkToAnalyze, mainConfiguration, reporter, idXp)
            staticAnalysis.execute()
            logger.info(staticAnalysis)

            # Create the emulator
            device = Analysis.createDevice(iEmulator, emulatorName, mainConfiguration, analysisConfiguration.backupDirectory)
            
            if device is None:
                raise Exception("Something has prevented the creation of an device.")

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

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

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

            # Writes the experiment configuration on the device
            Analysis.reportEvent(reporter, idXp, "Emulator", "writeConfiguration")
            Analysis.writeConfigurationOnEmulator(device, idXp, reportingConfiguration)

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

            # Install the targeted application
            Analysis.reportEvent(reporter, idXp, "Emulator", "installAPK", apkToAnalyze)
            device.installAPK(apkToAnalyze)
            time.sleep(5*SLEEP_FACTOR/5)

            # We then follow the scenario user has filled in configuration
            for order in analysisConfiguration.scenario:
                if "execute" == order:
                    Analysis.reportEvent(reporter, idXp, "Emulator", "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, "Emulator", "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, "Emulator", "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, "Emulator", "Rebooting device")
                    logger.info("Rebooting device.")
                    device.reboot()
                    time.sleep(5*SLEEP_FACTOR)

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

        except KeyboardInterrupt:
            pass
        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.")
Exemplo n.º 24
0
    def start(self):
        """Starts the current manual analysis"""

        if self.mainConfiguration is None:
            raise Exception("No main configuration found, cannot start the analysis..")

        if self.reportingConfiguration is None:
            raise Exception("No reporting configuration found, cannot start the analysis.")
        
        if self.analysisConfiguration is None:
            raise Exception("No analysis configuration found, cannot start the analysis.")

        self._logger.info(str(self))

        # Build the identifier experiment
        idXp = self._generateIdXp(self.analysisConfiguration.apkFiles)

        # Targeted APK
        analyzedAPKFile = self.analysisConfiguration.apkFiles[0]
        
        # Execute the analysis on the first emulator
        iEmulator = 0
        emulatorName = "Emulator_{0}".format(iEmulator)
        
        # Create a new report for this analysis
        Analysis.createReport(self.reporter, idXp, emulatorName, "unknown", analyzedAPKFile, "manual", None)

        # Execute static analysis
        staticAnalysis = StaticAnalysis(analyzedAPKFile, self.mainConfiguration, self.reporter, idXp)

        Analysis.reportEvent(self.reporter, idXp, "Analysis", "Executing Static Analysis on {0}".format(analyzedAPKFile))        
        staticAnalysis.execute()
        self._logger.info(staticAnalysis)
        
        Analysis.reportEvent(self.reporter, idXp, "Emulator", "creation of the Emulator {0}".format(emulatorName))
        emulator = self._createEmulator(iEmulator, emulatorName)        

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

        # Starts the emulator
        Analysis.reportEvent(self.reporter, idXp, "Emulator", "start")
        emulator.start()

        # Install preparation applications
        for prepareAPK in self.analysisConfiguration.prepareAPKs:
            Analysis.reportEvent(self.reporter, idXp, "Emulator", "installAPK", prepareAPK)
            emulator.installAPK(prepareAPK)

        # Execute preparation applications
        for prepareAPK in self.analysisConfiguration.prepareAPKs:
            Analysis.reportEvent(self.reporter, idXp, "Emulator", "startActivity", os.path.basename(prepareAPK)[:-4])
            emulator.startActivity(os.path.basename(prepareAPK)[:-4])        

        # Writes the experiment configuration on the emulator
        Analysis.reportEvent(self.reporter, idXp, "Emulator", "writeConfiguration")
        self._writeConfigurationOnEmulator(emulator, idXp)

        sleepDuration = 30
        self._logger.debug("Waiting {0} seconds for the emulator to prepare...".format(sleepDuration))
        time.sleep(sleepDuration)
        
        # Install the targeted application
        for analysisAPK in self.analysisConfiguration.apkFiles:
            Analysis.reportEvent(self.reporter, idXp, "Emulator", "installAPK", analysisAPK)
            emulator.installAPK(analysisAPK)

        Analysis.reportEvent(self.reporter, idXp, "Emulator", "Launching main activity", staticAnalysis.mainActivity)
        self._logger.info("Starting main activity: {0}".format(staticAnalysis.mainActivity))
        emulator.startActivityFromPackage(staticAnalysis.packageName, staticAnalysis.mainActivity)

        # The user is now requested to perform any operations he wants
        # this script waits for the emulator process to be closed
        self._logger.info("Proceed to the stimulation of the environnment.")
        self._logger.info("Once achieved, close the emulator and waits for the hooker to finish.")
        Analysis.reportEvent(self.reporter, idXp, "Emulator", "waitToBeClosed")
        
        emulator.waitToBeClosed()

        Analysis.reportEvent(self.reporter, idXp, "Emulator", "closed")
        self._logger.info("Emulator has finished.")