Giter Site home page Giter Site logo

h2so4t / ares Goto Github PK

View Code? Open in Web Editor NEW
68.0 6.0 20.0 20.57 MB

Black-box tool that uses Deep Reinforcement Learning to test and explore Android applications

License: GNU Affero General Public License v3.0

Python 100.00%
android android-testing appium-android black-box-testing appium deep-learning reinforcement-learning deep-reinforcement-learning pytorch applesilicon

ares's Introduction

MacOS Build Status Ubuntu Build Status Windows Build Status Android Version Python Version License

ARES

ARES is a black-box tool that uses Deep Reinforcement Learning to test and explore Android applications.

ARES does not instrument any application, however supports emma code coverage (for legacy apps) and JaCoCo (to instruement Android apps from source code go to https://github.com/H2SO4T/COSMO)

Publication

More details about ARES can be found in the TOSEM paper "Deep Reinforcement Learning for Black-Box Testing of Android Apps" Please use the following bibtex entry to cite our work:

@article{10.1145/3502868, 
author = {Romdhana, Andrea and Merlo, Alessio and Ceccato, Mariano and Tonella, Paolo}, 
title = {Deep Reinforcement Learning for Black-Box Testing of Android Apps}, year = {2021}, publisher = {Association for Computing Machinery}, 
issn = {1049-331X}, 
url = {https://doi.org/10.1145/3502868}, doi = {10.1145/3502868}, 
journal = {ACM Trans. Softw. Eng. Methodol.},
keywords = {Deep reinforcement learning, Android testing}}

Demo

video

Requirements

  • Android emulator or Android smartphone (more stable)
  • MacOS or Ubuntu or Windows
  • Python 3.7+

Compatibility

  • Android from 6.0 to 12.0
  • OpenAI Gym

Installation and Setup

  • Install Appium from http://appium.io/docs/en/about-appium/getting-started/; please make sure to set up the environment variables. $ANDROID_HOME and $JAVA_HOME
  • Use appium-doctor to check that everything is working correctly
  • Create a virtualenv named venv in folder ARES (not in rl_interaction): virtualenv -p python3 venv and source it source venv/bin/activate
  • Go to rl_interaction: cd rl_interaction
  • Install the requirements requirements.txt using the command pip3 install -r requirements.txt

Using the testing Tool (Quick Guide)

  • Export PYTHONPATH: export PYTHONPATH="path/to/ares"
  • Move yourself to ares/rl_interaction
  • Generate a folder for the apks, and put them inside
  • Activate the venv
  • Start testing

Testing with emulated devices

  • Create one or more Android emulators.
  • Run the tests using parallel_exec.py: python3 parallel_exec.py --instr_jacoco --list_devices "avd-name0 avd-name1 ..." --appium_ports "4270 4277 ..." --android_ports "5554 5556 ..." --path "apps" --timer 60 --rotation --internet --emu headless --platform_version 8.1 --iterations 10 --algo SAC --timesteps 4000 --trials_per_app 3

The flag --instr_jacoco is not useful if you are not interested in code coverage. You don't need to boot the emulators; ARES will do it for you. To see the avd names of your emulators, you can run emulator -list-avds. There is no need to specify udids using emulated devices since ARES will manage them automatically. Read Available Flags for more information.

Testing with real devices

  • Buy one or more Android devices.
  • Activate ADB and usb debug.
  • Run the testing using parallel_exec.py: python3 parallel_exec.py --instr_jacoco --real_device --udids "HG*****9 PO********NA" --list_device "lenovo1 levecchio2" --appium_ports "4270 4290" --android_ports "5554 5556" --path "apps" --timer 70 --rotation --internet --platform_version 7.0 --iterations 2 --algo SAC --timesteps 5000 --trials_per_app 3

With real devices the flag --list_devices can contain arbitrary names, while the flag --udids must contain the real udids of your devices. You can find the udids using the command adb devices Flag --real_device is required.

Available Flags:

  • --instr_emma, If you want to collect code coverage with EMMA.
  • --instr_jacoco, If you want to collect code coverage using JaCoCo. --save_policy, You can save an exploration policy of your app and use it in new explorations. --reload_policy, Tell ARES to reload a previous policy.
  • --real_device, If you are using a real device you must specify it.
  • --timer: [time_in_minutes], You can specify the time to test the app, required=True.
  • --platform_version [android_version], You have to specify the android version, default = 10.0 .
  • --iterations [number_of_iterations], How many times you want to repeat the test, default=10 .
  • --algo [algo], Choose one between SAC random and Q-Learning (SAC is the algorithm used in the paper).
  • --timesteps, Number of time steps of each testing, (--timer has higher priority ), required=True.
  • --rotation, If you want to enable rotation.
  • --internet, If you want to toggle data during testing.
  • --emu, If you are using an emulator, you need to specify in what mode (normal or headless).
  • --max_timesteps, You can specify the duration of an episode, default = 250 .
  • --pool_strings, Name of the file to pick the strings from, default = strings.txt .
  • --list_devices [emulators], A list of the device_names (avd_names), required = True.
  • --appium_ports [ports], A list of the ports you want to use, required = True.
  • --android_ports [ports], A list of the adb-ports you want to use, required = True.
  • --udids [strings], A list of the udids of the real devices, in case you are using emulators don't use this flag (ARES will assign udids for you).
  • --trials_per_app, How many times ARES attempts to launch an app.
  • --path [folders],The folder containing all apks, ARES will equally subdivide the apps between the devices available.

Testing Phase, Coverage Reports and Logs

During the testing phase several files are generated:

  • In a folder named coverage you will find all .ec files associated to each app tested organized by algorithm and number of executions.
  • In a folder named logs you will find the trace of the entire execution (the time, the activity and the operation generated), it is useful to recreate a bug or a specific set of actions. You will also find all the stack traces associated to the generated bugs.
  • In a folder named policies you will find the policies saved by ARES of your apps.

To automatically instrument apps from source code, you can use COSMO: https://github.com/H2SO4T/COSMO

FATE: https://github.com/H2SO4T/FATE

Troubleshooting

Generic Errors:

We strongly suggest using Android 8.1 (to the best of our knowledge, the most stable). Google emulators are not meant to run for multiple days, and they can have unexpected behaviors due to this. ARES integrates many protection systems that save the current session and restart the emulators. However, sometimes the emulators are irremediably broken, and you need to delete and recreate them.

In case of connection errors:

Connection errors usually depend on the emulator, using a real devices can reduce these errors

  • At first try to delete and recreate the emulator
  • If it does not work, try to reinstall the packages selenium and Appium-Python-Client

How To Contribute

If you are interested in the project, please feel free to suggest new features!

Working with Apple Silicon (M1 SoCs)

Using ARES on Apple Silicon is possible, but the configuration is a bit longer. The configuration steps are identical, except for the Python part.

We tested this procedure on a Mac Mini 16Gb, Python3.9 and a real device.

Install Miniconda and Setup

  • At first install miniconda from https://github.com/conda-forge/miniforge.
  • Create a venv using conda create --name venv and activate it conda activate venv.
  • Run conda install pandas, conda install numpy and conda install scipy, and conda install pyyaml, conda install typing_extensions.

Installing Pytorch on Apple Silicon

  • Run brew install openblas
  • Then clone pytorch: git clone --recursive https://github.com/pytorch/pytorch
  • cd pytorch
  • run python setup.py build
  • run python setup.py develop
  • Install the missing packages using pip: stable_baselines3, loguru==0.5.0, androguard==3.3.5, Appium-Python-Client==1.0.2, cloudpickle==1.2.2, future==0.18.2 and gym==0.18.0
  • At last, modify il parallel_exec.py at line 99: insert a string with the path to the venv python (use which python when the venv is activated)

Now the environt is ready!

New Saving and Reloading Policies

  • Use the flags save-policy and reload-policy to save or reload previous policies in SAC. The policies are saved under the folder policies with the same name of the apk file in apps folder. WARNING: If save-policy is True, then at the end of the testing the previous policy will be overwritten.

ares's People

Contributors

claudiugeorgiu avatar h2so4t avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

ares's Issues

ARES seems blocked

Hi @H2SO4T ,
First of all thanks for the very interesting and useful project.

However, after your update, it stopped working on some applications.

My setup is based on python3.9 and a Macbook PRO M1 Max with 32GB of RAM.

I have tested the tool with different applications and it works perfectly.
However, with some apps, it gets stuck and doesn't seem to find and perform the actions to do.

Can I upload one of the apps that give me this kind of problem?

Crash after the error "type numpy.ndarray doesn't define __round__ method"

Hi, I use the default settings to test the APK
org.woheller69.spritpreise_18.apk.zip

The script I used is:

python3 parallel_exec.py --list_device AVDName --appium_ports APPIUMNAME --android_ports ANDROIDPORT --path APPDIR --timer 70 --platform_version 8.1 --algo SAC --timesteps 5000 --trials_per_app 3

The test performs well at the beginning. However, the test speed rush up and suddenly output the error

type numpy.ndarray doesn't define __round__ method
OK: killing emulator, bye bye

Then the emulator restarts again.

Would you please kindly check what's wrong with it?

Thank you very much!

Evaluate a trained model

Hello!
I have a question.

During the implementation of ARES, did you ever think of trying to implement a way to evaluate an already trained model, and not just continue with the training?
Since in your paper I don't see it mentioned as a limitation.
Besides, at this moment I am trying to implement it, but I have been stuck because of a limitation that may be Stable Baselines3 has to change the action space each time you try to predict an action.

Like this

env.action_space.high[0] = env.env.ACTION_SPACE
logger.info("Loading policy...")
model = SAC.load(os.path.splitext(file_path)[0], env)

obs = env.reset()
for i in range(10):
    action, _states = model.predict(obs)
    obs, rewards, dones, info = env.step(action)

As you can see, the predict method only receives the observation, not the environment, so modifying the action space is useless.

I just wanted to know if maybe you who developed this tool have any idea or clarification that you can give me, I would appreciate it. πŸ˜‰

Cannot start the 'com.android.insecurebankv2' application

android version: 8.1
error happend when I run with the cmd: python test_application.py --instr_emma --appium_port "4723" --android_port "62002" --timer 10 --rotation --internet --emu normal --platform_version "8.1" --iterations 2 --algo random --timesteps 50 --trials_per_app 3 --apps "D:\code\pycharm\gym\test\test_resources\InsecureBankv2.apk" --save_policy

image-20221018212644209

Quick question about SACExploration.py

The ML model checks the dimension only at the beginning, and then it will never use the action_space variable anymore. This means that the output of the ML model is always in the range 0:30.
But if you have 3 buttons in Activity Something.Main, it is not useful to generate a value greater than 2 (i.e., 0, 1, 2).
So I'm just using the action_space variable to save the actual action space dimension.

Originally posted by @H2SO4T in #8 (comment)

Adb error - failed to access

Hello, I am a Macbook pro owner with an Apple Silicon processor. I have tried to test ARES with various apks using Android Studio and an emulator with Android 9 API 28, but the tool fails to create files with Coverage information as the folder is empty.
When running the tool, I get the following error:
Broadcasting: Intent { act=intent.END_COVERAGE flg=0x400000 pkg=com.shazam.android } Broadcast completed: result=0 adb: error: failed to access 'path/to/ARES/rl_interaction/coverage/shazam-13-27-0-230420/SAC/0/18.ec': No such file or directory
The command I use to launch the tool is as follows:
python3 parallel_exec.py --instr_jacoco --list_devices "emulator-5554" --appium_ports "4270" --android_ports "5554" --path "apps" --timer 60 --internet --emu headless --platform_version 9.0 --iterations 1 --algo SAC --timesteps 1000 --trials_per_app 1 --save_policy

I would appreciate it if you could help me.

Thank you vary much.

Some quetions about app experiment

Hi, thanks for your good job.
I have questions about the 'Experimental Results: Study 2' in your paper.
The results are obtained during training or testing? Is it necessary to load the pretrained model to test after training the model?
The results are obtained using one hour or 4000 steps ? And how many steps is runing within one hour in your experiment if the results is obtained using one hour.

I'm trying to use SAC of ARES to test apps(Markor and MicroMathematics).
The first item of action_number is tent always to be zero or one after 1125 steps(generate 45 converage files) .
I use the instruction:
python3 parallel_exec.py --instr_jacoco --list_devices "gtestapi27" --appium_ports "4270" --android_ports "5554" --path "apps" --timer 60 --rotation --internet --emu normal --platform_version 8.1 --iterations 10 --algo SAC --timesteps 5000 --trials_per_app 3
Do you konw why is that ? Thanks a lot.

Problem when running ARES

Hello,

I tried to test ARES with Ubuntu 20.04 and an emulator with Android 10.0 API 29 but failed. When running the tool, I get the following error:
Broadcasting: Intent { act=intent.END_COVERAGE flg=0x400000 pkg=com.shazam.android } Broadcast completed: result=0 adb: error: failed to access 'path/to/ARES/rl_interaction/coverage/shazam-13-27-0-230420/SAC/0/18.ec': No such file or directory

node: no process found
INFO | Android emulator version 32.1.11.0 (build_id 9536276) (CL:N/A)
INFO | Found systemPath /home/zhliao/Android/Sdk/system-images/android-29/google_apis/x86/
INFO | Crashreporting disabled, not reporting crashes.
INFO | Duplicate loglines will be removed, if you wish to see each indiviudal line launch with the -log-nofilter flag.
WARNING | Please update the emulator to one that supports the feature(s): Vulkan
WARNING | cannot add library /home/zhliao/Android/Sdk/emulator/qemu/linux-x86_64/lib64/vulkan/libvulkan.so: failed
INFO | added library /home/zhliao/Android/Sdk/emulator/lib64/vulkan/libvulkan.so
INFO | Setting display: 0 configuration to: 1080x2400, dpi: 420x420
INFO | Cold boot: requested by the user
cmd: Can't find service: settings
cmd: Can't find service: settings
cmd: Can't find service: settings
2023-05-17 03:28:26.181 | INFO | main:main:122 - now testing: com.willianveiga.countdowntimer_4

2023-05-17 03:28:26.197 | INFO | main:main:137 - app: com.willianveiga.countdowntimer_4, test 0 of 1 starting
Performing Streamed Install
adb: failed to install ./apks/com.willianveiga.countdowntimer_4.apk: cmd: Can't find service: package
2023-05-17 03:28:26.400 | DEBUG | rl_interaction.RL_application_env:init:129 - ./apks/com.willianveiga.countdowntimer_4.apk START
2023-05-17 03:28:27.386 | ERROR | main:main:213 - Message: An unknown server-side error occurred while processing the command. Original error: Error executing adbExec. Original error: 'Command '/home/zhliao/Android/Sdk/platform-tools/adb -P 5037 -s emulator-5554 shell 'settings delete global hidden_api_policy_pre_p_apps;settings delete global hidden_api_policy_p_apps;settings delete global hidden_api_policy'' exited with code 20'; Command output: cmd: Can't find service: settings
cmd: Can't find service: settings
cmd: Can't find service: settings

The command I use to launch the tool is as follows:
python3 parallel_exec.py --instr_jacoco --list_devices "Pixel_6_API_29" --appium_ports "4273" --android_ports "5554" --path "./apks" --timer 60 --rotation --internet --emu headless --platform_version 10.0 --iterations 3 --algo SAC --timesteps 4000 --trials_per_app 3

I use Appium 1.22.3 with Appium-Python-Client 1.0.2, as this post suggested.

Thank you very much for your time.

Some questions about RL_application_env.py

Hi, I find self.check_activity() will change the size of self.action_space = spaces.Box() in RL_application_env.py init(). Will it cause wrong action_space size init in the model?

Some questions about running

Hi, thanks for your good job.
I use the instruction:
"python parallel_exec.py --instr_jacoco --real_device --udids "e62b6cf8" --list_device "qualcomm1" --appium_ports "4270" --android_ports "5554" --path "D:\apk/" --timer 70 --rotation --internet --platform_version 12.0 --iterations 2 --algo SAC --timesteps 5000 --trials_per_app 1"
But it come into errors about
"ERROR: The process "node.exe" not found.
Traceback (most recent call last):
File "parallel_exec.py", line 132, in
main()
File "parallel_exec.py", line 126, in main
processes.append(subprocess.Popen(cmd))
File "D:\Python3\lib\subprocess.py", line 800, in init
restore_signals, start_new_session)
File "D:\Python3\lib\subprocess.py", line 1207, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified "
Do you konw why is that ? Thanks a lot.

where can I get your app benchmark ?

hi, itβ€˜s quiet a good job! can you share your app benchmark ?
I also try to build app by cosmo, but it didn't work for some android source code.
Github project VinylMusicPlayer is buided success after cosmo, but it didn't generate converge files after using "adb shell am broadcast -p com.poupa.vinylmusicplayer -a intent.END_COVERAGE". Do you know why is that?
Thanks a lot.

about the observation

It seems that you use activity index as the obervation code, I think there are other imformation we need to feed to the agent. That will get a better result.
The amount of information is too little, simple Q learning feels like enough.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.