after_merge
stringlengths
28
79.6k
before_merge
stringlengths
20
79.6k
url
stringlengths
38
71
full_traceback
stringlengths
43
922k
traceback_type
stringclasses
555 values
def analyze_docker_image(image_obj, dockerfile=False): """Given a DockerImage object, for each layer, retrieve the packages, first looking up in cache and if not there then looking up in the command library. For looking up in command library first mount the filesystem and then look up the command library for commands to run in chroot""" # find the layers that are imported if dockerfile: docker.set_imported_layers(image_obj) # add notices for each layer if it is imported for layer in image_obj.layers: origin_str = "Layer: " + layer.fs_hash[:10] layer.origins.add_notice_origin(origin_str) if layer.import_str: layer.origins.add_notice_to_origins( origin_str, Notice("Imported in Dockerfile using: " + layer.import_str, "info"), ) shell = "" # set up empty master list of package names master_list = [] # find the shell by mounting the base layer target = rootfs.mount_base_layer(image_obj.layers[0].tar_file) binary = common.get_base_bin(image_obj.layers[0]) # find the shell to invoke commands in shell, _ = command_lib.get_image_shell(command_lib.get_base_listing(binary)) if not shell: shell = constants.shell # only extract packages if there is a known binary and the layer is not # cached if binary: if not common.load_from_cache(image_obj.layers[0]): # get the packages of the first layer rootfs.prep_rootfs(target) common.add_base_packages(image_obj.layers[0], binary) # unmount proc, sys and dev rootfs.undo_mount() else: logger.warning( errors.unrecognized_base.format( image_name=image_obj.name, image_tag=image_obj.tag ) ) # unmount the first layer rootfs.unmount_rootfs() # populate the master list with all packages found in the first layer # can't use assignment as that will just point to the image object's layer for p in image_obj.layers[0].get_package_names(): master_list.append(p) # get packages for subsequent layers curr_layer = 1 while curr_layer < len(image_obj.layers): if not common.load_from_cache(image_obj.layers[curr_layer]): # mount diff layers from 0 till the current layer tar_layers = [] for index in range(0, curr_layer + 1): tar_layers.append(image_obj.layers[index].tar_file) target = rootfs.mount_diff_layers(tar_layers) # mount dev, sys and proc after mounting diff layers rootfs.prep_rootfs(target) docker.add_packages_from_history(image_obj.layers[curr_layer], shell) rootfs.undo_mount() rootfs.unmount_rootfs() # update the master list common.update_master_list(master_list, image_obj.layers[curr_layer]) curr_layer = curr_layer + 1 common.save_to_cache(image_obj)
def analyze_docker_image(image_obj, dockerfile=False): """Given a DockerImage object, for each layer, retrieve the packages, first looking up in cache and if not there then looking up in the command library. For looking up in command library first mount the filesystem and then look up the command library for commands to run in chroot""" # find the layers that are imported if dockerfile: docker.set_imported_layers(image_obj) # add notices for each layer if it is imported for layer in image_obj.layers: origin_str = "Layer: " + layer.fs_hash[:10] layer.origins.add_notice_origin(origin_str) if layer.import_str: layer.origins.add_notice_to_origins( origin_str, Notice("Imported in Dockerfile using: " + layer.import_str, "info"), ) shell = "" # set the layer that is mounted. In the beginning this is 0 mounted = 0 # set up empty master list of package names master_list = [] # find the shell by mounting the base layer target = rootfs.mount_base_layer(image_obj.layers[0].tar_file) binary = common.get_base_bin(image_obj.layers[0]) # find the shell to invoke commands in shell, _ = command_lib.get_image_shell(command_lib.get_base_listing(binary)) if not shell: shell = constants.shell # only extract packages if there is a known binary and the layer is not # cached if binary: if not common.load_from_cache(image_obj.layers[0]): # get the packages of the first layer rootfs.prep_rootfs(target) common.add_base_packages(image_obj.layers[0], binary) # unmount proc, sys and dev rootfs.undo_mount() else: logger.warning( errors.unrecognized_base.format( image_name=image_obj.name, image_tag=image_obj.tag ) ) # populate the master list with all packages found in the first layer # can't use assignment as that will just point to the image object's layer for p in image_obj.layers[0].get_package_names(): master_list.append(p) # get packages for subsequent layers curr_layer = 1 while curr_layer < len(image_obj.layers): if not common.load_from_cache(image_obj.layers[curr_layer]): # mount from the layer after the mounted layer till the current # layer for index in range(mounted + 1, curr_layer + 1): target = rootfs.mount_diff_layer(image_obj.layers[index].tar_file) mounted = curr_layer # mount dev, sys and proc after mounting diff layers rootfs.prep_rootfs(target) docker.add_packages_from_history(image_obj.layers[curr_layer], shell) rootfs.undo_mount() # update the master list common.update_master_list(master_list, image_obj.layers[curr_layer]) curr_layer = curr_layer + 1 # undo all the mounts rootfs.unmount_rootfs(mounted + 1) common.save_to_cache(image_obj)
https://github.com/tern-tools/tern/issues/82
./tern report -i ./tern -k report -i docker.io/golang ... 2018-09-10 17:16:35,797 - DEBUG - rootfs - Running command: sudo mount -t overlay overlay -o lowerdir=temp/mergedir,upperdir=temp/6e1bf8ee3b708647f06cac5e20e6998c1f55d1e89b311065c82727c7abbde134/contents,workdir=temp/workdir temp/mergedir Traceback (most recent call last): File "./tern", line 94, in <module> main(args) File "./tern", line 53, in main report.execute_docker_image(args) File "/home/nisha/tern3.7/tern/report/report.py", line 324, in execute_docker_image analyze_docker_image(full_image) File "/home/nisha/tern3.7/tern/report/report.py", line 176, in analyze_docker_image image_obj.layers[index].tar_file) File "/home/nisha/tern3.7/tern/utils/rootfs.py", line 123, in mount_diff_layer root_command(union_mount, args, merge_dir_path) File "/home/nisha/tern3.7/tern/utils/rootfs.py", line 57, in root_command raise subprocess.CalledProcessError(1, cmd=full_cmd, output=error) subprocess.CalledProcessError: Command '['sudo', 'mount', '-t', 'overlay', 'overlay', '-o', 'lowerdir=temp/mergedir,upperdir=temp/6e1bf8ee3b708647f06cac5e20e6998c1f55d1e89b311065c82727c7abbde134/contents,workdir=temp/workdir', 'temp/mergedir']' returned non-zero exit status 1.
subprocess.CalledProcessError
def unmount_rootfs(): """Unmount the filesystem""" rootfs_path = os.path.join(constants.temp_folder, constants.mergedir) root_command(unmount, "-rl", rootfs_path)
def unmount_rootfs(num_layers): """Unmount the overlay filesystem""" rootfs_path = os.path.join(constants.temp_folder, constants.mergedir) for _ in range(num_layers): root_command(unmount, "-rl", rootfs_path)
https://github.com/tern-tools/tern/issues/82
./tern report -i ./tern -k report -i docker.io/golang ... 2018-09-10 17:16:35,797 - DEBUG - rootfs - Running command: sudo mount -t overlay overlay -o lowerdir=temp/mergedir,upperdir=temp/6e1bf8ee3b708647f06cac5e20e6998c1f55d1e89b311065c82727c7abbde134/contents,workdir=temp/workdir temp/mergedir Traceback (most recent call last): File "./tern", line 94, in <module> main(args) File "./tern", line 53, in main report.execute_docker_image(args) File "/home/nisha/tern3.7/tern/report/report.py", line 324, in execute_docker_image analyze_docker_image(full_image) File "/home/nisha/tern3.7/tern/report/report.py", line 176, in analyze_docker_image image_obj.layers[index].tar_file) File "/home/nisha/tern3.7/tern/utils/rootfs.py", line 123, in mount_diff_layer root_command(union_mount, args, merge_dir_path) File "/home/nisha/tern3.7/tern/utils/rootfs.py", line 57, in root_command raise subprocess.CalledProcessError(1, cmd=full_cmd, output=error) subprocess.CalledProcessError: Command '['sudo', 'mount', '-t', 'overlay', 'overlay', '-o', 'lowerdir=temp/mergedir,upperdir=temp/6e1bf8ee3b708647f06cac5e20e6998c1f55d1e89b311065c82727c7abbde134/contents,workdir=temp/workdir', 'temp/mergedir']' returned non-zero exit status 1.
subprocess.CalledProcessError
def calc_fs_hash(fs_path): """Given the path to the filesystem, calculate the filesystem hash We run a shell script located in the tools directory to get the file stats and the file content's sha256sum. We then calculate the sha256sum of the contents and write the contents in the layer directory. Note that this file will be deleted if the -k flag is not given""" try: hash_contents = subprocess.check_output( ["sudo", "./tools/fs_hash.sh", os.path.abspath(fs_path)] ) file_name = hashlib.sha256(hash_contents).hexdigest() # write file to an appropriate location hash_file = os.path.join(os.path.dirname(fs_path), file_name) + ".txt" with open(hash_file, "w") as f: f.write(hash_contents.decode("utf-8")) return file_name except subprocess.CalledProcessError: raise
def calc_fs_hash(fs_path): """Given the path to the filesystem, calculate the filesystem hash We run a shell script located in the tools directory to get the file stats and the file content's sha256sum. We then calculate the sha256sum of the contents and write the contents in the layer directory. Note that this file will be deleted if the -k flag is not given""" try: hash_contents = subprocess.check_output( ["sudo", "./tools/fs_hash.sh", os.path.abspath(fs_path)] ) file_name = hashlib.sha256(hash_contents).hexdigest() # write file to an appropriate location hash_file = os.path.join(os.path.dirname(fs_path), file_name) + ".txt" with open(hash_file, "w") as f: f.write(hash_contents.decode("utf-8")) return file_name except: raise
https://github.com/tern-tools/tern/issues/82
./tern report -i ./tern -k report -i docker.io/golang ... 2018-09-10 17:16:35,797 - DEBUG - rootfs - Running command: sudo mount -t overlay overlay -o lowerdir=temp/mergedir,upperdir=temp/6e1bf8ee3b708647f06cac5e20e6998c1f55d1e89b311065c82727c7abbde134/contents,workdir=temp/workdir temp/mergedir Traceback (most recent call last): File "./tern", line 94, in <module> main(args) File "./tern", line 53, in main report.execute_docker_image(args) File "/home/nisha/tern3.7/tern/report/report.py", line 324, in execute_docker_image analyze_docker_image(full_image) File "/home/nisha/tern3.7/tern/report/report.py", line 176, in analyze_docker_image image_obj.layers[index].tar_file) File "/home/nisha/tern3.7/tern/utils/rootfs.py", line 123, in mount_diff_layer root_command(union_mount, args, merge_dir_path) File "/home/nisha/tern3.7/tern/utils/rootfs.py", line 57, in root_command raise subprocess.CalledProcessError(1, cmd=full_cmd, output=error) subprocess.CalledProcessError: Command '['sudo', 'mount', '-t', 'overlay', 'overlay', '-o', 'lowerdir=temp/mergedir,upperdir=temp/6e1bf8ee3b708647f06cac5e20e6998c1f55d1e89b311065c82727c7abbde134/contents,workdir=temp/workdir', 'temp/mergedir']' returned non-zero exit status 1.
subprocess.CalledProcessError
def clahe(img, clip_limit=2.0, tile_grid_size=(8, 8)): if img.dtype != np.uint8: raise TypeError("clahe supports only uint8 inputs") clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=tile_grid_size) if len(img.shape) == 2: img = clahe.apply(img) else: img = cv2.cvtColor(img, cv2.COLOR_RGB2LAB) img[:, :, 0] = clahe.apply(img[:, :, 0]) img = cv2.cvtColor(img, cv2.COLOR_LAB2RGB) return img
def clahe(img, clip_limit=2.0, tile_grid_size=(8, 8)): if img.dtype != np.uint8: raise TypeError("clahe supports only uint8 inputs") img = cv2.cvtColor(img, cv2.COLOR_RGB2LAB) clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=tile_grid_size) img[:, :, 0] = clahe.apply(img[:, :, 0]) img = cv2.cvtColor(img, cv2.COLOR_LAB2RGB) return img
https://github.com/albumentations-team/albumentations/issues/180
--------------------------------------------------------------------------- error Traceback (most recent call last) <ipython-input-25-6a9d0f41d618> in <module>() 6 img.shape 7 # (256, 256) ----> 8 aug(image=img, p=1) /usr/local/lib/python3.7/site-packages/albumentations/core/transforms_interface.py in __call__(self, **kwargs) 36 target_function = self._get_target_function(key) 37 target_dependencies = {k: kwargs[k] for k in self.target_dependence.get(key, [])} ---> 38 res[key] = target_function(arg, **dict(params, **target_dependencies)) 39 else: 40 res[key] = None /usr/local/lib/python3.7/site-packages/albumentations/augmentations/transforms.py in apply(self, img, clip_limit, **params) 985 986 def apply(self, img, clip_limit=2, **params): --> 987 return F.clahe(img, clip_limit, self.tile_grid_size) 988 989 def get_params(self): /usr/local/lib/python3.7/site-packages/albumentations/augmentations/functional.py in clahe(img, clip_limit, tile_grid_size) 274 if img.dtype != np.uint8: 275 raise TypeError('clahe supports only uint8 inputs') --> 276 img = cv2.cvtColor(img, cv2.COLOR_RGB2LAB) 277 clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=tile_grid_size) 278 img[:, :, 0] = clahe.apply(img[:, :, 0]) error: OpenCV(3.4.3) /Users/travis/build/skvark/opencv-python/opencv/modules/imgproc/src/color.hpp:255: error: (-2:Unspecified error) in function 'cv::CvtHelper<cv::Set<3, 4, -1>, cv::Set<3, -1, -1>, cv::Set<0, 5, -1>, cv::SizePolicy::NONE>::CvtHelper(InputArray, OutputArray, int) [VScn = cv::Set<3, 4, -1>, VDcn = cv::Set<3, -1, -1>, VDepth = cv::Set<0, 5, -1>, sizePolicy = cv::SizePolicy::NONE]' Invalid number of channels in input image: 'VScn::contains(scn)' where 'scn' is 1
TypeError
def quantize_model(to_quantize): """Quantize a whole tf.keras model with the default quantization implementation. To be more precise, `quantize_model` creates a model that emulates quantization during training and stores information that downstream tools will use to produce actually quantized models. Quantize a model: ```python model = quantize_model( keras.Sequential([ layers.Dense(10, activation='relu', input_shape=(100,)), layers.Dense(2, activation='sigmoid') ])) ``` Note that this function removes the optimizer from the original model. Additionally, training the model returned by `quantize_model` will not affect the weights of the original model. Args: to_quantize: tf.keras model to be quantized. It can have pre-trained weights. Returns: Returns a new tf.keras model prepared for quantization. """ if to_quantize is None: raise ValueError("`to_quantize` cannot be None") if not isinstance(to_quantize, keras.Model): raise ValueError( "`to_quantize` can only be a `tf.keras.Model` instance. Use " "the `quantize_annotate_layer` API to handle individual layers." "You passed an instance of type: {input}.".format( input=to_quantize.__class__.__name__ ) ) if ( not isinstance(to_quantize, keras.Sequential) and not to_quantize._is_graph_network ): # pylint: disable=protected-access raise ValueError( "`to_quantize` can only either be a tf.keras Sequential or " "Functional model." ) annotated_model = quantize_annotate_model(to_quantize) return quantize_apply(annotated_model)
def quantize_model(to_quantize): """Quantize a whole tf.keras model with the default quantization implementation. To be more precise, `quantize_model` creates a model that emulates quantization during training and stores information that downstream tools will use to produce actually quantized models. Quantize a model: ```python model = quantize_model( keras.Sequential([ layers.Dense(10, activation='relu', input_shape=(100,)), layers.Dense(2, activation='sigmoid') ])) ``` Note that this function removes the optimizer from the original model. Additionally, training the model returned by `quantize_model` will not affect the weights of the original model. Args: to_quantize: tf.keras model to be quantized. It can have pre-trained weights. Returns: Returns a new tf.keras model prepared for quantization. """ if to_quantize is None: raise ValueError("`to_quantize` cannot be None") if not isinstance(to_quantize, keras.Model): raise ValueError( "`to_quantize` can only be a `tf.keras.Model` instance. Use " "the `quantize_annotate_layer` API to handle individual layers." "You passed an instance of type: {input}.".format( input=to_quantize.__class__.__name__ ) ) annotated_model = quantize_annotate_model(to_quantize) return quantize_apply(annotated_model)
https://github.com/tensorflow/model-optimization/issues/292
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-10-ff8232533be0> in <module> 3 outputs = backbone(input_image) 4 not_working_model = keras.Model(input_image, outputs) ----> 5 q_aware_model = quantize_model(not_working_model) ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow_model_optimization/python/core/quantization/keras/quantize.py in quantize_model(to_quantize) 99 'the `quantize_annotate_layer` API to handle individual layers.') 100 --> 101 annotated_model = quantize_annotate_model(to_quantize) 102 return quantize_apply(annotated_model) 103 ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow_model_optimization/python/core/quantization/keras/quantize.py in quantize_annotate_model(to_annotate) 148 149 return keras.models.clone_model( --> 150 to_annotate, input_tensors=None, clone_function=_add_quant_wrapper) 151 152 ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow/python/keras/models.py in clone_model(model, input_tensors, clone_function) 425 else: 426 return _clone_functional_model( --> 427 model, input_tensors=input_tensors, layer_fn=clone_function) 428 429 ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow/python/keras/models.py in _clone_functional_model(model, input_tensors, layer_fn) 198 input_tensors, output_tensors, created_layers = ( 199 network.reconstruct_from_config(model_config, --> 200 created_layers=created_layers)) 201 metrics_names = model.metrics_names 202 model = Model(input_tensors, output_tensors, name=model.name) ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow/python/keras/engine/network.py in reconstruct_from_config(config, custom_objects, created_layers) 2044 layer = created_layers[layer_name] 2045 node_index = get_node_index(layer, node_index) -> 2046 layer_output_tensors = layer._inbound_nodes[node_index].output_tensors 2047 output_tensors.append(nest.flatten(layer_output_tensors)[tensor_index]) 2048 TypeError: list indices must be integers or slices, not NoneType
TypeError
def quantize_annotate_model(to_annotate): """Annotate a model to be quantized. This function does not actually quantize anything. It is merely to specify that the model needs to be quantized. This function is intended to be used in conjunction with the `quantize_annotate_layer` API. It's otherwise simpler to use `quantize_model`. Annotate a model while overriding the default behavior for one layer: ```python quantize_config = MyDenseQuantizeConfig() model = quantize_annotate_model(keras.Sequential([ layers.Dense(10, activation='relu', input_shape=(100,)), quantize_annotate_layer(layers.Dense(2, activation='sigmoid'), quantize_config=quantize_config) ]))) ``` Note that this function removes the optimizer from the original model. Args: to_annotate: tf.keras model to annotate to be quantized. Returns: New tf.keras model with each layer in the model wrapped with `QuantizeAnnotate`. """ if to_annotate is None: raise ValueError("`to_annotate` cannot be None") if not isinstance(to_annotate, keras.Model): raise ValueError( "`to_annotate` can only be a `tf.keras.Model` instance. Use " "the `quantize_annotate_layer` API to handle individual layers. " "You passed an instance of type: {input}.".format( input=to_annotate.__class__.__name__ ) ) if ( not isinstance(to_annotate, keras.Sequential) and not to_annotate._is_graph_network ): # pylint: disable=protected-access raise ValueError( "`to_annotate` can only either be a tf.keras Sequential or " "Functional model." ) def _add_quant_wrapper(layer): """Add annotation wrapper.""" # Already annotated layer. No need to wrap. if isinstance(layer, quantize_annotate_mod.QuantizeAnnotate): return layer if isinstance(layer, tf.keras.Model): raise ValueError( "Quantizing a tf.keras Model inside another tf.keras Model is not supported." ) return quantize_annotate_mod.QuantizeAnnotate(layer) return keras.models.clone_model( to_annotate, input_tensors=None, clone_function=_add_quant_wrapper )
def quantize_annotate_model(to_annotate): """Annotate a model to be quantized. This function does not actually quantize anything. It is merely to specify that the model needs to be quantized. This function is intended to be used in conjunction with the `quantize_annotate_layer` API. It's otherwise simpler to use `quantize_model`. Annotate a model while overriding the default behavior for one layer: ```python quantize_config = MyDenseQuantizeConfig() model = quantize_annotate_model(keras.Sequential([ layers.Dense(10, activation='relu', input_shape=(100,)), quantize_annotate_layer(layers.Dense(2, activation='sigmoid'), quantize_config=quantize_config) ]))) ``` Note that this function removes the optimizer from the original model. Args: to_annotate: tf.keras model to annotate to be quantized. Returns: New tf.keras model with each layer in the model wrapped with `QuantizeAnnotate`. """ if to_annotate is None: raise ValueError("`to_annotate` cannot be None") if not isinstance(to_annotate, keras.Model): raise ValueError( "`to_annotate` can only be a `tf.keras.Model` instance. Use " "the `quantize_annotate_layer` API to handle individual layers. " "You passed an instance of type: {input}.".format( input=to_annotate.__class__.__name__ ) ) def _add_quant_wrapper(layer): # Already annotated layer. No need to wrap. if isinstance(layer, quantize_annotate_mod.QuantizeAnnotate): return layer return quantize_annotate_mod.QuantizeAnnotate(layer) return keras.models.clone_model( to_annotate, input_tensors=None, clone_function=_add_quant_wrapper )
https://github.com/tensorflow/model-optimization/issues/292
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-10-ff8232533be0> in <module> 3 outputs = backbone(input_image) 4 not_working_model = keras.Model(input_image, outputs) ----> 5 q_aware_model = quantize_model(not_working_model) ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow_model_optimization/python/core/quantization/keras/quantize.py in quantize_model(to_quantize) 99 'the `quantize_annotate_layer` API to handle individual layers.') 100 --> 101 annotated_model = quantize_annotate_model(to_quantize) 102 return quantize_apply(annotated_model) 103 ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow_model_optimization/python/core/quantization/keras/quantize.py in quantize_annotate_model(to_annotate) 148 149 return keras.models.clone_model( --> 150 to_annotate, input_tensors=None, clone_function=_add_quant_wrapper) 151 152 ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow/python/keras/models.py in clone_model(model, input_tensors, clone_function) 425 else: 426 return _clone_functional_model( --> 427 model, input_tensors=input_tensors, layer_fn=clone_function) 428 429 ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow/python/keras/models.py in _clone_functional_model(model, input_tensors, layer_fn) 198 input_tensors, output_tensors, created_layers = ( 199 network.reconstruct_from_config(model_config, --> 200 created_layers=created_layers)) 201 metrics_names = model.metrics_names 202 model = Model(input_tensors, output_tensors, name=model.name) ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow/python/keras/engine/network.py in reconstruct_from_config(config, custom_objects, created_layers) 2044 layer = created_layers[layer_name] 2045 node_index = get_node_index(layer, node_index) -> 2046 layer_output_tensors = layer._inbound_nodes[node_index].output_tensors 2047 output_tensors.append(nest.flatten(layer_output_tensors)[tensor_index]) 2048 TypeError: list indices must be integers or slices, not NoneType
TypeError
def _add_quant_wrapper(layer): """Add annotation wrapper.""" # Already annotated layer. No need to wrap. if isinstance(layer, quantize_annotate_mod.QuantizeAnnotate): return layer if isinstance(layer, tf.keras.Model): raise ValueError( "Quantizing a tf.keras Model inside another tf.keras Model is not supported." ) return quantize_annotate_mod.QuantizeAnnotate(layer)
def _add_quant_wrapper(layer): # Already annotated layer. No need to wrap. if isinstance(layer, quantize_annotate_mod.QuantizeAnnotate): return layer return quantize_annotate_mod.QuantizeAnnotate(layer)
https://github.com/tensorflow/model-optimization/issues/292
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-10-ff8232533be0> in <module> 3 outputs = backbone(input_image) 4 not_working_model = keras.Model(input_image, outputs) ----> 5 q_aware_model = quantize_model(not_working_model) ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow_model_optimization/python/core/quantization/keras/quantize.py in quantize_model(to_quantize) 99 'the `quantize_annotate_layer` API to handle individual layers.') 100 --> 101 annotated_model = quantize_annotate_model(to_quantize) 102 return quantize_apply(annotated_model) 103 ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow_model_optimization/python/core/quantization/keras/quantize.py in quantize_annotate_model(to_annotate) 148 149 return keras.models.clone_model( --> 150 to_annotate, input_tensors=None, clone_function=_add_quant_wrapper) 151 152 ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow/python/keras/models.py in clone_model(model, input_tensors, clone_function) 425 else: 426 return _clone_functional_model( --> 427 model, input_tensors=input_tensors, layer_fn=clone_function) 428 429 ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow/python/keras/models.py in _clone_functional_model(model, input_tensors, layer_fn) 198 input_tensors, output_tensors, created_layers = ( 199 network.reconstruct_from_config(model_config, --> 200 created_layers=created_layers)) 201 metrics_names = model.metrics_names 202 model = Model(input_tensors, output_tensors, name=model.name) ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow/python/keras/engine/network.py in reconstruct_from_config(config, custom_objects, created_layers) 2044 layer = created_layers[layer_name] 2045 node_index = get_node_index(layer, node_index) -> 2046 layer_output_tensors = layer._inbound_nodes[node_index].output_tensors 2047 output_tensors.append(nest.flatten(layer_output_tensors)[tensor_index]) 2048 TypeError: list indices must be integers or slices, not NoneType
TypeError
def __init__(self, layer, quantize_config=None, **kwargs): """Create a quantize annotate wrapper over a keras layer. Args: layer: The keras layer to be quantized. quantize_config: `QuantizeConfig` to quantize layer. **kwargs: Additional keyword arguments to be passed to the keras layer. """ super(QuantizeAnnotate, self).__init__(layer, **kwargs) if layer is None: raise ValueError("`layer` cannot be None.") # Check against keras.Model since it is an instance of keras.layers.Layer. if not isinstance(layer, tf.keras.layers.Layer) or isinstance( layer, tf.keras.Model ): raise ValueError( "`layer` can only be a `tf.keras.layers.Layer` instance. " "You passed an instance of type: {input}.".format( input=layer.__class__.__name__ ) ) self.quantize_config = quantize_config self._track_trackable(layer, name="layer") # Enables end-user to annotate the first layer in Sequential models, while # passing the input shape to the original layer. # # tf.keras.Sequential( # quantize_annotate_layer(tf.keras.layers.Dense(2, input_shape=(3,))) # ) # # as opposed to # # tf.keras.Sequential( # quantize_annotate_layer(tf.keras.layers.Dense(2), input_shape=(3,)) # ) # # Without this code, the QuantizeAnnotate wrapper doesn't have an input # shape and being the first layer, this causes the model to not be # built. Being not built is confusing since the end-user has passed an # input shape. if not hasattr(self, "_batch_input_shape") and hasattr(layer, "_batch_input_shape"): self._batch_input_shape = self.layer._batch_input_shape # pylint: disable=protected-access
def __init__(self, layer, quantize_config=None, **kwargs): """Create a quantize annotate wrapper over a keras layer. Args: layer: The keras layer to be quantized. quantize_config: `QuantizeConfig` to quantize layer. **kwargs: Additional keyword arguments to be passed to the keras layer. """ super(QuantizeAnnotate, self).__init__(layer, **kwargs) self.quantize_config = quantize_config self._track_trackable(layer, name="layer") # Enables end-user to annotate the first layer in Sequential models, while # passing the input shape to the original layer. # # tf.keras.Sequential( # quantize_annotate_layer(tf.keras.layers.Dense(2, input_shape=(3,))) # ) # # as opposed to # # tf.keras.Sequential( # quantize_annotate_layer(tf.keras.layers.Dense(2), input_shape=(3,)) # ) # # Without this code, the QuantizeAnnotate wrapper doesn't have an input # shape and being the first layer, this causes the model to not be # built. Being not built is confusing since the end-user has passed an # input shape. if not hasattr(self, "_batch_input_shape") and hasattr(layer, "_batch_input_shape"): self._batch_input_shape = self.layer._batch_input_shape # pylint: disable=protected-access
https://github.com/tensorflow/model-optimization/issues/292
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-10-ff8232533be0> in <module> 3 outputs = backbone(input_image) 4 not_working_model = keras.Model(input_image, outputs) ----> 5 q_aware_model = quantize_model(not_working_model) ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow_model_optimization/python/core/quantization/keras/quantize.py in quantize_model(to_quantize) 99 'the `quantize_annotate_layer` API to handle individual layers.') 100 --> 101 annotated_model = quantize_annotate_model(to_quantize) 102 return quantize_apply(annotated_model) 103 ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow_model_optimization/python/core/quantization/keras/quantize.py in quantize_annotate_model(to_annotate) 148 149 return keras.models.clone_model( --> 150 to_annotate, input_tensors=None, clone_function=_add_quant_wrapper) 151 152 ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow/python/keras/models.py in clone_model(model, input_tensors, clone_function) 425 else: 426 return _clone_functional_model( --> 427 model, input_tensors=input_tensors, layer_fn=clone_function) 428 429 ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow/python/keras/models.py in _clone_functional_model(model, input_tensors, layer_fn) 198 input_tensors, output_tensors, created_layers = ( 199 network.reconstruct_from_config(model_config, --> 200 created_layers=created_layers)) 201 metrics_names = model.metrics_names 202 model = Model(input_tensors, output_tensors, name=model.name) ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow/python/keras/engine/network.py in reconstruct_from_config(config, custom_objects, created_layers) 2044 layer = created_layers[layer_name] 2045 node_index = get_node_index(layer, node_index) -> 2046 layer_output_tensors = layer._inbound_nodes[node_index].output_tensors 2047 output_tensors.append(nest.flatten(layer_output_tensors)[tensor_index]) 2048 TypeError: list indices must be integers or slices, not NoneType
TypeError
def __init__(self, layer, quantize_config, **kwargs): """Create a quantize emulate wrapper for a keras layer. Args: layer: The keras layer to be quantized. quantize_config: `QuantizeConfig` to quantize layer. **kwargs: Additional keyword arguments to be passed to the keras layer. """ if layer is None: raise ValueError("`layer` cannot be None.") # Check against keras.Model since it is an instance of keras.layers.Layer. if not isinstance(layer, tf.keras.layers.Layer) or isinstance( layer, tf.keras.Model ): raise ValueError( "`layer` can only be a `tf.keras.layers.Layer` instance. " "You passed an instance of type: {input}.".format( input=layer.__class__.__name__ ) ) if quantize_config is None: raise ValueError( "quantize_config cannot be None. It is needed to quantize a layer." ) if "name" not in kwargs: kwargs["name"] = self._make_layer_name(layer) super(QuantizeWrapper, self).__init__(layer, **kwargs) self.quantize_config = quantize_config self._track_trackable(layer, name="layer")
def __init__(self, layer, quantize_config, **kwargs): """Create a quantize emulate wrapper for a keras layer. Args: layer: The keras layer to be quantized. quantize_config: `QuantizeConfig` to quantize layer. **kwargs: Additional keyword arguments to be passed to the keras layer. """ if quantize_config is None: raise ValueError( "quantize_config cannot be None. It is needed to quantize a layer." ) if "name" not in kwargs: kwargs["name"] = self._make_layer_name(layer) super(QuantizeWrapper, self).__init__(layer, **kwargs) self.quantize_config = quantize_config self._track_trackable(layer, name="layer")
https://github.com/tensorflow/model-optimization/issues/292
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-10-ff8232533be0> in <module> 3 outputs = backbone(input_image) 4 not_working_model = keras.Model(input_image, outputs) ----> 5 q_aware_model = quantize_model(not_working_model) ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow_model_optimization/python/core/quantization/keras/quantize.py in quantize_model(to_quantize) 99 'the `quantize_annotate_layer` API to handle individual layers.') 100 --> 101 annotated_model = quantize_annotate_model(to_quantize) 102 return quantize_apply(annotated_model) 103 ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow_model_optimization/python/core/quantization/keras/quantize.py in quantize_annotate_model(to_annotate) 148 149 return keras.models.clone_model( --> 150 to_annotate, input_tensors=None, clone_function=_add_quant_wrapper) 151 152 ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow/python/keras/models.py in clone_model(model, input_tensors, clone_function) 425 else: 426 return _clone_functional_model( --> 427 model, input_tensors=input_tensors, layer_fn=clone_function) 428 429 ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow/python/keras/models.py in _clone_functional_model(model, input_tensors, layer_fn) 198 input_tensors, output_tensors, created_layers = ( 199 network.reconstruct_from_config(model_config, --> 200 created_layers=created_layers)) 201 metrics_names = model.metrics_names 202 model = Model(input_tensors, output_tensors, name=model.name) ~/anaconda3/envs/tensorflow2/lib/python3.7/site-packages/tensorflow/python/keras/engine/network.py in reconstruct_from_config(config, custom_objects, created_layers) 2044 layer = created_layers[layer_name] 2045 node_index = get_node_index(layer, node_index) -> 2046 layer_output_tensors = layer._inbound_nodes[node_index].output_tensors 2047 output_tensors.append(nest.flatten(layer_output_tensors)[tensor_index]) 2048 TypeError: list indices must be integers or slices, not NoneType
TypeError
def _make_attr_tuple_class(cls_name, attr_names): """ Create a tuple subclass to hold `Attribute`s for an `attrs` class. The subclass is a bare tuple with properties for names. class MyClassAttributes(tuple): __slots__ = () x = property(itemgetter(0)) """ attr_class_name = "{}Attributes".format(cls_name) attr_class_template = [ "class {}(tuple):".format(attr_class_name), " __slots__ = ()", ] if attr_names: for i, attr_name in enumerate(attr_names): attr_class_template.append( _tuple_property_pat.format(index=i, attr_name=attr_name) ) else: attr_class_template.append(" pass") globs = {"_attrs_itemgetter": itemgetter, "_attrs_property": property} _compile_and_eval("\n".join(attr_class_template), globs) return globs[attr_class_name]
def _make_attr_tuple_class(cls_name, attr_names): """ Create a tuple subclass to hold `Attribute`s for an `attrs` class. The subclass is a bare tuple with properties for names. class MyClassAttributes(tuple): __slots__ = () x = property(itemgetter(0)) """ attr_class_name = "{}Attributes".format(cls_name) attr_class_template = [ "class {}(tuple):".format(attr_class_name), " __slots__ = ()", ] if attr_names: for i, attr_name in enumerate(attr_names): attr_class_template.append( _tuple_property_pat.format(index=i, attr_name=attr_name) ) else: attr_class_template.append(" pass") globs = {"_attrs_itemgetter": itemgetter, "_attrs_property": property} eval(compile("\n".join(attr_class_template), "", "exec"), globs) return globs[attr_class_name]
https://github.com/python-attrs/attrs/issues/593
Traceback (most recent call last): File "example.py", line 8, in <module> print(get_type_hints(C.__init__)) File "C:\Python37\lib\typing.py", line 1001, in get_type_hints value = _eval_type(value, globalns, localns) File "C:\Python37\lib\typing.py", line 260, in _eval_type return t._evaluate(globalns, localns) File "C:\Python37\lib\typing.py", line 464, in _evaluate eval(self.__forward_code__, globalns, localns), File "<string>", line 1, in <module> NameError: name 'List' is not defined
NameError
def _make_hash(cls, attrs, frozen, cache_hash): attrs = tuple( a for a in attrs if a.hash is True or (a.hash is None and a.eq is True) ) tab = " " unique_filename = _generate_unique_filename(cls, "hash") type_hash = hash(unique_filename) hash_def = "def __hash__(self" hash_func = "hash((" closing_braces = "))" if not cache_hash: hash_def += "):" else: if not PY2: hash_def += ", *" hash_def += ( ", _cache_wrapper=" + "__import__('attr._make')._make._CacheHashWrapper):" ) hash_func = "_cache_wrapper(" + hash_func closing_braces += ")" method_lines = [hash_def] def append_hash_computation_lines(prefix, indent): """ Generate the code for actually computing the hash code. Below this will either be returned directly or used to compute a value which is then cached, depending on the value of cache_hash """ method_lines.extend( [ indent + prefix + hash_func, indent + " %d," % (type_hash,), ] ) for a in attrs: method_lines.append(indent + " self.%s," % a.name) method_lines.append(indent + " " + closing_braces) if cache_hash: method_lines.append(tab + "if self.%s is None:" % _hash_cache_field) if frozen: append_hash_computation_lines( "object.__setattr__(self, '%s', " % _hash_cache_field, tab * 2 ) method_lines.append(tab * 2 + ")") # close __setattr__ else: append_hash_computation_lines("self.%s = " % _hash_cache_field, tab * 2) method_lines.append(tab + "return self.%s" % _hash_cache_field) else: append_hash_computation_lines("return ", tab) script = "\n".join(method_lines) return _make_method("__hash__", script, unique_filename)
def _make_hash(cls, attrs, frozen, cache_hash): attrs = tuple( a for a in attrs if a.hash is True or (a.hash is None and a.eq is True) ) tab = " " unique_filename = _generate_unique_filename(cls, "hash") type_hash = hash(unique_filename) hash_def = "def __hash__(self" hash_func = "hash((" closing_braces = "))" if not cache_hash: hash_def += "):" else: if not PY2: hash_def += ", *" hash_def += ( ", _cache_wrapper=" + "__import__('attr._make')._make._CacheHashWrapper):" ) hash_func = "_cache_wrapper(" + hash_func closing_braces += ")" method_lines = [hash_def] def append_hash_computation_lines(prefix, indent): """ Generate the code for actually computing the hash code. Below this will either be returned directly or used to compute a value which is then cached, depending on the value of cache_hash """ method_lines.extend( [ indent + prefix + hash_func, indent + " %d," % (type_hash,), ] ) for a in attrs: method_lines.append(indent + " self.%s," % a.name) method_lines.append(indent + " " + closing_braces) if cache_hash: method_lines.append(tab + "if self.%s is None:" % _hash_cache_field) if frozen: append_hash_computation_lines( "object.__setattr__(self, '%s', " % _hash_cache_field, tab * 2 ) method_lines.append(tab * 2 + ")") # close __setattr__ else: append_hash_computation_lines("self.%s = " % _hash_cache_field, tab * 2) method_lines.append(tab + "return self.%s" % _hash_cache_field) else: append_hash_computation_lines("return ", tab) script = "\n".join(method_lines) globs = {} locs = {} bytecode = compile(script, unique_filename, "exec") eval(bytecode, globs, locs) # In order of debuggers like PDB being able to step through the code, # we add a fake linecache entry. linecache.cache[unique_filename] = ( len(script), None, script.splitlines(True), unique_filename, ) return locs["__hash__"]
https://github.com/python-attrs/attrs/issues/593
Traceback (most recent call last): File "example.py", line 8, in <module> print(get_type_hints(C.__init__)) File "C:\Python37\lib\typing.py", line 1001, in get_type_hints value = _eval_type(value, globalns, localns) File "C:\Python37\lib\typing.py", line 260, in _eval_type return t._evaluate(globalns, localns) File "C:\Python37\lib\typing.py", line 464, in _evaluate eval(self.__forward_code__, globalns, localns), File "<string>", line 1, in <module> NameError: name 'List' is not defined
NameError
def _make_eq(cls, attrs): """ Create __eq__ method for *cls* with *attrs*. """ attrs = [a for a in attrs if a.eq] unique_filename = _generate_unique_filename(cls, "eq") lines = [ "def __eq__(self, other):", " if other.__class__ is not self.__class__:", " return NotImplemented", ] # We can't just do a big self.x = other.x and... clause due to # irregularities like nan == nan is false but (nan,) == (nan,) is true. if attrs: lines.append(" return (") others = [" ) == ("] for a in attrs: lines.append(" self.%s," % (a.name,)) others.append(" other.%s," % (a.name,)) lines += others + [" )"] else: lines.append(" return True") script = "\n".join(lines) return _make_method("__eq__", script, unique_filename)
def _make_eq(cls, attrs): """ Create __eq__ method for *cls* with *attrs*. """ attrs = [a for a in attrs if a.eq] unique_filename = _generate_unique_filename(cls, "eq") lines = [ "def __eq__(self, other):", " if other.__class__ is not self.__class__:", " return NotImplemented", ] # We can't just do a big self.x = other.x and... clause due to # irregularities like nan == nan is false but (nan,) == (nan,) is true. if attrs: lines.append(" return (") others = [" ) == ("] for a in attrs: lines.append(" self.%s," % (a.name,)) others.append(" other.%s," % (a.name,)) lines += others + [" )"] else: lines.append(" return True") script = "\n".join(lines) globs = {} locs = {} bytecode = compile(script, unique_filename, "exec") eval(bytecode, globs, locs) # In order of debuggers like PDB being able to step through the code, # we add a fake linecache entry. linecache.cache[unique_filename] = ( len(script), None, script.splitlines(True), unique_filename, ) return locs["__eq__"]
https://github.com/python-attrs/attrs/issues/593
Traceback (most recent call last): File "example.py", line 8, in <module> print(get_type_hints(C.__init__)) File "C:\Python37\lib\typing.py", line 1001, in get_type_hints value = _eval_type(value, globalns, localns) File "C:\Python37\lib\typing.py", line 260, in _eval_type return t._evaluate(globalns, localns) File "C:\Python37\lib\typing.py", line 464, in _evaluate eval(self.__forward_code__, globalns, localns), File "<string>", line 1, in <module> NameError: name 'List' is not defined
NameError
def _make_init( cls, attrs, pre_init, post_init, frozen, slots, cache_hash, base_attr_map, is_exc, has_global_on_setattr, attrs_init, ): if frozen and has_global_on_setattr: raise ValueError("Frozen classes can't use on_setattr.") needs_cached_setattr = cache_hash or frozen filtered_attrs = [] attr_dict = {} for a in attrs: if not a.init and a.default is NOTHING: continue filtered_attrs.append(a) attr_dict[a.name] = a if a.on_setattr is not None: if frozen is True: raise ValueError("Frozen classes can't use on_setattr.") needs_cached_setattr = True elif ( has_global_on_setattr and a.on_setattr is not setters.NO_OP ) or _is_slot_attr(a.name, base_attr_map): needs_cached_setattr = True unique_filename = _generate_unique_filename(cls, "init") script, globs, annotations = _attrs_to_init_script( filtered_attrs, frozen, slots, pre_init, post_init, cache_hash, base_attr_map, is_exc, needs_cached_setattr, has_global_on_setattr, attrs_init, ) if cls.__module__ in sys.modules: # This makes typing.get_type_hints(CLS.__init__) resolve string types. globs.update(sys.modules[cls.__module__].__dict__) globs.update({"NOTHING": NOTHING, "attr_dict": attr_dict}) if needs_cached_setattr: # Save the lookup overhead in __init__ if we need to circumvent # setattr hooks. globs["_cached_setattr"] = _obj_setattr init = _make_method( "__attrs_init__" if attrs_init else "__init__", script, unique_filename, globs, ) init.__annotations__ = annotations return init
def _make_init( cls, attrs, pre_init, post_init, frozen, slots, cache_hash, base_attr_map, is_exc, has_global_on_setattr, attrs_init, ): if frozen and has_global_on_setattr: raise ValueError("Frozen classes can't use on_setattr.") needs_cached_setattr = cache_hash or frozen filtered_attrs = [] attr_dict = {} for a in attrs: if not a.init and a.default is NOTHING: continue filtered_attrs.append(a) attr_dict[a.name] = a if a.on_setattr is not None: if frozen is True: raise ValueError("Frozen classes can't use on_setattr.") needs_cached_setattr = True elif ( has_global_on_setattr and a.on_setattr is not setters.NO_OP ) or _is_slot_attr(a.name, base_attr_map): needs_cached_setattr = True unique_filename = _generate_unique_filename(cls, "init") script, globs, annotations = _attrs_to_init_script( filtered_attrs, frozen, slots, pre_init, post_init, cache_hash, base_attr_map, is_exc, needs_cached_setattr, has_global_on_setattr, attrs_init, ) locs = {} bytecode = compile(script, unique_filename, "exec") globs.update({"NOTHING": NOTHING, "attr_dict": attr_dict}) if needs_cached_setattr: # Save the lookup overhead in __init__ if we need to circumvent # setattr hooks. globs["_cached_setattr"] = _obj_setattr eval(bytecode, globs, locs) # In order of debuggers like PDB being able to step through the code, # we add a fake linecache entry. linecache.cache[unique_filename] = ( len(script), None, script.splitlines(True), unique_filename, ) init = locs["__attrs_init__"] if attrs_init else locs["__init__"] init.__annotations__ = annotations return init
https://github.com/python-attrs/attrs/issues/593
Traceback (most recent call last): File "example.py", line 8, in <module> print(get_type_hints(C.__init__)) File "C:\Python37\lib\typing.py", line 1001, in get_type_hints value = _eval_type(value, globalns, localns) File "C:\Python37\lib\typing.py", line 260, in _eval_type return t._evaluate(globalns, localns) File "C:\Python37\lib\typing.py", line 464, in _evaluate eval(self.__forward_code__, globalns, localns), File "<string>", line 1, in <module> NameError: name 'List' is not defined
NameError
def make_set_closure_cell(): """Return a function of two arguments (cell, value) which sets the value stored in the closure cell `cell` to `value`. """ # pypy makes this easy. (It also supports the logic below, but # why not do the easy/fast thing?) if PYPY: def set_closure_cell(cell, value): cell.__setstate__((value,)) return set_closure_cell # Otherwise gotta do it the hard way. # Create a function that will set its first cellvar to `value`. def set_first_cellvar_to(value): x = value return # This function will be eliminated as dead code, but # not before its reference to `x` forces `x` to be # represented as a closure cell rather than a local. def force_x_to_be_a_cell(): # pragma: no cover return x try: # Extract the code object and make sure our assumptions about # the closure behavior are correct. if PY2: co = set_first_cellvar_to.func_code else: co = set_first_cellvar_to.__code__ if co.co_cellvars != ("x",) or co.co_freevars != (): raise AssertionError # pragma: no cover # Convert this code object to a code object that sets the # function's first _freevar_ (not cellvar) to the argument. if sys.version_info >= (3, 8): # CPython 3.8+ has an incompatible CodeType signature # (added a posonlyargcount argument) but also added # CodeType.replace() to do this without counting parameters. set_first_freevar_code = co.replace( co_cellvars=co.co_freevars, co_freevars=co.co_cellvars ) else: args = [co.co_argcount] if not PY2: args.append(co.co_kwonlyargcount) args.extend( [ co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, co.co_consts, co.co_names, co.co_varnames, co.co_filename, co.co_name, co.co_firstlineno, co.co_lnotab, # These two arguments are reversed: co.co_cellvars, co.co_freevars, ] ) set_first_freevar_code = types.CodeType(*args) def set_closure_cell(cell, value): # Create a function using the set_first_freevar_code, # whose first closure cell is `cell`. Calling it will # change the value of that cell. setter = types.FunctionType( set_first_freevar_code, {}, "setter", (), (cell,) ) # And call it to set the cell. setter(value) # Make sure it works on this interpreter: def make_func_with_cell(): x = None def func(): return x # pragma: no cover return func if PY2: cell = make_func_with_cell().func_closure[0] else: cell = make_func_with_cell().__closure__[0] set_closure_cell(cell, 100) if cell.cell_contents != 100: raise AssertionError # pragma: no cover except Exception: return just_warn else: return set_closure_cell
def make_set_closure_cell(): """Return a function of two arguments (cell, value) which sets the value stored in the closure cell `cell` to `value`. """ # pypy makes this easy. (It also supports the logic below, but # why not do the easy/fast thing?) if PYPY: # pragma: no cover def set_closure_cell(cell, value): cell.__setstate__((value,)) return set_closure_cell # Otherwise gotta do it the hard way. # Create a function that will set its first cellvar to `value`. def set_first_cellvar_to(value): x = value return # This function will be eliminated as dead code, but # not before its reference to `x` forces `x` to be # represented as a closure cell rather than a local. def force_x_to_be_a_cell(): # pragma: no cover return x try: # Extract the code object and make sure our assumptions about # the closure behavior are correct. if PY2: co = set_first_cellvar_to.func_code else: co = set_first_cellvar_to.__code__ if co.co_cellvars != ("x",) or co.co_freevars != (): raise AssertionError # pragma: no cover # Convert this code object to a code object that sets the # function's first _freevar_ (not cellvar) to the argument. if sys.version_info >= (3, 8): # CPython 3.8+ has an incompatible CodeType signature # (added a posonlyargcount argument) but also added # CodeType.replace() to do this without counting parameters. set_first_freevar_code = co.replace( co_cellvars=co.co_freevars, co_freevars=co.co_cellvars ) else: args = [co.co_argcount] if not PY2: args.append(co.co_kwonlyargcount) args.extend( [ co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, co.co_consts, co.co_names, co.co_varnames, co.co_filename, co.co_name, co.co_firstlineno, co.co_lnotab, # These two arguments are reversed: co.co_cellvars, co.co_freevars, ] ) set_first_freevar_code = types.CodeType(*args) def set_closure_cell(cell, value): # Create a function using the set_first_freevar_code, # whose first closure cell is `cell`. Calling it will # change the value of that cell. setter = types.FunctionType( set_first_freevar_code, {}, "setter", (), (cell,) ) # And call it to set the cell. setter(value) # Make sure it works on this interpreter: def make_func_with_cell(): x = None def func(): return x # pragma: no cover return func if PY2: cell = make_func_with_cell().func_closure[0] else: cell = make_func_with_cell().__closure__[0] set_closure_cell(cell, 100) if cell.cell_contents != 100: raise AssertionError # pragma: no cover except Exception: return just_warn else: return set_closure_cell
https://github.com/python-attrs/attrs/issues/703
Traceback (most recent call last): File "scratch.py", line 10, in <module> raise MyException("test") from None __main__.MyException: test
__main__.MyException
def _transform_attrs(cls, these): """ Transforms all `_CountingAttr`s on a class into `Attribute`s and saves the list in `__attrs_attrs__`. If *these* is passed, use that and don't look for them on the class. """ if these is None: ca_list = [ (name, attr) for name, attr in cls.__dict__.items() if isinstance(attr, _CountingAttr) ] else: ca_list = [(name, ca) for name, ca in iteritems(these)] non_super_attrs = [ Attribute.from_counting_attr(name=attr_name, ca=ca) for attr_name, ca in sorted(ca_list, key=lambda e: e[1].counter) ] super_cls = [] non_super_names = set(a.name for a in non_super_attrs) for c in reversed(cls.__mro__[1:-1]): sub_attrs = getattr(c, "__attrs_attrs__", None) if sub_attrs is not None: super_cls.extend( a for a in sub_attrs if a not in super_cls and a.name not in non_super_names ) attr_names = [a.name for a in super_cls + non_super_attrs] AttrsClass = _make_attr_tuple_class(cls.__name__, attr_names) cls.__attrs_attrs__ = AttrsClass( super_cls + [ Attribute.from_counting_attr(name=attr_name, ca=ca) for attr_name, ca in sorted(ca_list, key=lambda e: e[1].counter) ] ) had_default = False for a in cls.__attrs_attrs__: if these is None and a not in super_cls: setattr(cls, a.name, a) if had_default is True and a.default is NOTHING and a.init is True: raise ValueError( "No mandatory attributes allowed after an attribute with a " "default value or factory. Attribute in question: {a!r}".format(a=a) ) elif had_default is False and a.default is not NOTHING and a.init is not False: had_default = True
def _transform_attrs(cls, these): """ Transforms all `_CountingAttr`s on a class into `Attribute`s and saves the list in `__attrs_attrs__`. If *these* is passed, use that and don't look for them on the class. """ super_cls = [] for c in reversed(cls.__mro__[1:-1]): sub_attrs = getattr(c, "__attrs_attrs__", None) if sub_attrs is not None: super_cls.extend(a for a in sub_attrs if a not in super_cls) if these is None: ca_list = [ (name, attr) for name, attr in cls.__dict__.items() if isinstance(attr, _CountingAttr) ] else: ca_list = [(name, ca) for name, ca in iteritems(these)] non_super_attrs = [ Attribute.from_counting_attr(name=attr_name, ca=ca) for attr_name, ca in sorted(ca_list, key=lambda e: e[1].counter) ] attr_names = [a.name for a in super_cls + non_super_attrs] AttrsClass = _make_attr_tuple_class(cls.__name__, attr_names) cls.__attrs_attrs__ = AttrsClass( super_cls + [ Attribute.from_counting_attr(name=attr_name, ca=ca) for attr_name, ca in sorted(ca_list, key=lambda e: e[1].counter) ] ) had_default = False for a in cls.__attrs_attrs__: if these is None and a not in super_cls: setattr(cls, a.name, a) if had_default is True and a.default is NOTHING and a.init is True: raise ValueError( "No mandatory attributes allowed after an attribute with a " "default value or factory. Attribute in question: {a!r}".format(a=a) ) elif had_default is False and a.default is not NOTHING and a.init is not False: had_default = True
https://github.com/python-attrs/attrs/issues/221
Traceback (most recent call last): File "E:/D/OneDrive/PyCharm/attrs_test/01.py", line 44, in <module> class B(A): File "E:\D\OneDrive\Miniconda3\envs\dev\lib\site-packages\attr\_make.py", line 391, in attributes return wrap(maybe_cls) File "E:\D\OneDrive\Miniconda3\envs\dev\lib\site-packages\attr\_make.py", line 364, in wrap cls = _add_init(cls, effectively_frozen) File "E:\D\OneDrive\Miniconda3\envs\dev\lib\site-packages\attr\_make.py", line 569, in _add_init bytecode = compile(script, unique_filename, "exec") File "<attrs generated init 6e95dcc9478c7a8b8784f6244afbff55f563f7c6>", line 1 SyntaxError: duplicate argument 'p' in function definition
SyntaxError
def stop_httptools(url): """Kill httptools.""" # Invoke HTTPtools UI Kill Request try: requests.get(f"{url}/kill", timeout=5) logger.info("Killing httptools UI") except Exception: pass # Invoke HTTPtools Proxy Kill Request try: http_proxy = url.replace("https://", "http://") headers = {"httptools": "kill"} url = "http://127.0.0.1" requests.get(url, headers=headers, proxies={"http": http_proxy}) logger.info("Killing httptools Proxy") except Exception: pass
def stop_httptools(port): """Kill httptools.""" # Invoke HTTPtools UI Kill Request try: requests.get("http://127.0.0.1:" + str(port) + "/kill", timeout=5) logger.info("Killing httptools UI") except Exception: pass # Inkoke HTTPtools Proxy Kill Request try: http_proxy = "http://127.0.0.1:" + str(port) headers = {"httptools": "kill"} url = "http://127.0.0.1" requests.get(url, headers=headers, proxies={"http": http_proxy}) logger.info("Killing httptools Proxy") except Exception: pass
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1666
[ERROR] 05/Feb/2021 02:43:41 - Internal Server Error: /search Traceback (most recent call last): File "\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "\mobsf\MobSF\views\home.py", line 227, in search return HttpResponseRedirect('/' + db_obj[0].URL) AttributeError: 'RecentScansDB' object has no attribute 'URL' [ERROR] 05/Feb/2021 02:43:41 - "GET /search?md5=<the file md5> HTTP/1.1" 500 80105
AttributeError
def dynamic_analyzer(request, checksum, api=False): """Android Dynamic Analyzer Environment.""" logger.info("Creating Dynamic Analysis Environment") try: no_device = False if not is_md5(checksum): # We need this check since checksum is not validated # in REST API return print_n_send_error_response(request, "Invalid Parameters", api) package = get_package_name(checksum) if not package: return print_n_send_error_response(request, "Invalid Parameters", api) try: identifier = get_device() except Exception: no_device = True if no_device or not identifier: msg = ( "Is the android instance running? MobSF cannot" " find android instance identifier. " "Please run an android instance and refresh" " this page. If this error persists," " set ANALYZER_IDENTIFIER in " f"{get_config_loc()}" ) return print_n_send_error_response(request, msg, api) env = Environment(identifier) if not env.connect_n_mount(): msg = "Cannot Connect to " + identifier return print_n_send_error_response(request, msg, api) version = env.get_android_version() logger.info("Android Version identified as %s", version) xposed_first_run = False if not env.is_mobsfyied(version): msg = ( "This Android instance is not MobSfyed/Outdated.\n" "MobSFying the android runtime environment" ) logger.warning(msg) if not env.mobsfy_init(): return print_n_send_error_response( request, "Failed to MobSFy the instance", api ) if version < 5: xposed_first_run = True if xposed_first_run: msg = ( "Have you MobSFyed the instance before" " attempting Dynamic Analysis?" " Install Framework for Xposed." " Restart the device and enable" " all Xposed modules. And finally" " restart the device once again." ) return print_n_send_error_response(request, msg, api) # Clean up previous analysis env.dz_cleanup(checksum) # Configure Web Proxy env.configure_proxy(package, request) # Supported in Android 5+ env.enable_adb_reverse_tcp(version) # Apply Global Proxy to device env.set_global_proxy(version) # Start Clipboard monitor env.start_clipmon() # Get Screen Resolution screen_width, screen_height = env.get_screen_res() apk_path = Path(settings.UPLD_DIR) / checksum / f"{checksum}.apk" # Install APK status, output = env.install_apk(apk_path.as_posix(), package) if not status: # Unset Proxy env.unset_global_proxy() msg = ( f"This APK cannot be installed. Is this APK " f"compatible the Android VM/Emulator?\n{output}" ) return print_n_send_error_response(request, msg, api) logger.info("Testing Environment is Ready!") context = { "screen_witdth": screen_width, "screen_height": screen_height, "package": package, "hash": checksum, "android_version": version, "version": settings.MOBSF_VER, "title": "Dynamic Analyzer", } template = "dynamic_analysis/android/dynamic_analyzer.html" if api: return context return render(request, template, context) except Exception: logger.exception("Dynamic Analyzer") return print_n_send_error_response(request, "Dynamic Analysis Failed.", api)
def dynamic_analyzer(request, checksum, api=False): """Android Dynamic Analyzer Environment.""" logger.info("Creating Dynamic Analysis Environment") try: no_device = False if not is_md5(checksum): # We need this check since checksum is not validated # in REST API return print_n_send_error_response(request, "Invalid Parameters", api) package = get_package_name(checksum) if not package: return print_n_send_error_response(request, "Invalid Parameters", api) try: identifier = get_device() except Exception: no_device = True if no_device or not identifier: msg = ( "Is the android instance running? MobSF cannot" " find android instance identifier. " "Please run an android instance and refresh" " this page. If this error persists," " set ANALYZER_IDENTIFIER in " f"{get_config_loc()}" ) return print_n_send_error_response(request, msg, api) env = Environment(identifier) if not env.connect_n_mount(): msg = "Cannot Connect to " + identifier return print_n_send_error_response(request, msg, api) version = env.get_android_version() logger.info("Android Version identified as %s", version) xposed_first_run = False if not env.is_mobsfyied(version): msg = ( "This Android instance is not MobSfyed/Outdated.\n" "MobSFying the android runtime environment" ) logger.warning(msg) if not env.mobsfy_init(): return print_n_send_error_response( request, "Failed to MobSFy the instance", api ) if version < 5: xposed_first_run = True if xposed_first_run: msg = ( "Have you MobSFyed the instance before" " attempting Dynamic Analysis?" " Install Framework for Xposed." " Restart the device and enable" " all Xposed modules. And finally" " restart the device once again." ) return print_n_send_error_response(request, msg, api) # Clean up previous analysis env.dz_cleanup(checksum) # Configure Web Proxy env.configure_proxy(package) # Supported in Android 5+ env.enable_adb_reverse_tcp(version) # Apply Global Proxy to device env.set_global_proxy(version) # Start Clipboard monitor env.start_clipmon() # Get Screen Resolution screen_width, screen_height = env.get_screen_res() apk_path = Path(settings.UPLD_DIR) / checksum / f"{checksum}.apk" # Install APK status, output = env.install_apk(apk_path.as_posix(), package) if not status: # Unset Proxy env.unset_global_proxy() msg = ( f"This APK cannot be installed. Is this APK " f"compatible the Android VM/Emulator?\n{output}" ) return print_n_send_error_response(request, msg, api) logger.info("Testing Environment is Ready!") context = { "screen_witdth": screen_width, "screen_height": screen_height, "package": package, "hash": checksum, "android_version": version, "version": settings.MOBSF_VER, "title": "Dynamic Analyzer", } template = "dynamic_analysis/android/dynamic_analyzer.html" if api: return context return render(request, template, context) except Exception: logger.exception("Dynamic Analyzer") return print_n_send_error_response(request, "Dynamic Analysis Failed.", api)
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1666
[ERROR] 05/Feb/2021 02:43:41 - Internal Server Error: /search Traceback (most recent call last): File "\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "\mobsf\MobSF\views\home.py", line 227, in search return HttpResponseRedirect('/' + db_obj[0].URL) AttributeError: 'RecentScansDB' object has no attribute 'URL' [ERROR] 05/Feb/2021 02:43:41 - "GET /search?md5=<the file md5> HTTP/1.1" 500 80105
AttributeError
def httptools_start(request): """Start httprools UI.""" logger.info("Starting httptools Web UI") try: httptools_url = get_http_tools_url(request) stop_httptools(httptools_url) start_httptools_ui(settings.PROXY_PORT) time.sleep(3) logger.info("httptools UI started") if request.GET["project"]: project = request.GET["project"] else: project = "" url = f"{httptools_url}/dashboard/{project}" return HttpResponseRedirect(url) # lgtm [py/reflective-xss] except Exception: logger.exception("Starting httptools Web UI") err = "Error Starting httptools UI" return print_n_send_error_response(request, err)
def httptools_start(request): """Start httprools UI.""" logger.info("Starting httptools Web UI") try: stop_httptools(settings.PROXY_PORT) start_httptools_ui(settings.PROXY_PORT) time.sleep(3) logger.info("httptools UI started") if request.GET["project"]: project = request.GET["project"] else: project = "" url = "http://localhost:{}/dashboard/{}".format( str(settings.PROXY_PORT), project ) return HttpResponseRedirect(url) # lgtm [py/reflective-xss] except Exception: logger.exception("Starting httptools Web UI") err = "Error Starting httptools UI" return print_n_send_error_response(request, err)
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1666
[ERROR] 05/Feb/2021 02:43:41 - Internal Server Error: /search Traceback (most recent call last): File "\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "\mobsf\MobSF\views\home.py", line 227, in search return HttpResponseRedirect('/' + db_obj[0].URL) AttributeError: 'RecentScansDB' object has no attribute 'URL' [ERROR] 05/Feb/2021 02:43:41 - "GET /search?md5=<the file md5> HTTP/1.1" 500 80105
AttributeError
def configure_proxy(self, project, request): """HTTPS Proxy.""" self.install_mobsf_ca("install") proxy_port = settings.PROXY_PORT logger.info("Starting HTTPs Proxy on %s", proxy_port) httptools_url = get_http_tools_url(request) stop_httptools(httptools_url) start_proxy(proxy_port, project)
def configure_proxy(self, project): """HTTPS Proxy.""" self.install_mobsf_ca("install") proxy_port = settings.PROXY_PORT logger.info("Starting HTTPs Proxy on %s", proxy_port) stop_httptools(proxy_port) start_proxy(proxy_port, project)
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1666
[ERROR] 05/Feb/2021 02:43:41 - Internal Server Error: /search Traceback (most recent call last): File "\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "\mobsf\MobSF\views\home.py", line 227, in search return HttpResponseRedirect('/' + db_obj[0].URL) AttributeError: 'RecentScansDB' object has no attribute 'URL' [ERROR] 05/Feb/2021 02:43:41 - "GET /search?md5=<the file md5> HTTP/1.1" 500 80105
AttributeError
def install_mobsf_ca(self, action): """Install or Remove MobSF Root CA.""" mobsf_ca = get_ca_file() ca_file = None if is_file_exists(mobsf_ca): ca_construct = "{}.0" pem = open(mobsf_ca, "rb") ca_obj = crypto.load_certificate(crypto.FILETYPE_PEM, pem.read()) md = md5(ca_obj.get_subject().der()).digest() ret = md[0] | (md[1] << 8) | (md[2] << 16) | md[3] << 24 ca_file_hash = hex(ret).lstrip("0x") ca_file = os.path.join( "/system/etc/security/cacerts/", ca_construct.format(ca_file_hash) ) pem.close() else: logger.warning("mitmproxy root CA is not generated yet.") return if action == "install": logger.info("Installing MobSF RootCA") self.adb_command(["push", mobsf_ca, ca_file]) self.adb_command(["chmod", "644", ca_file], True) elif action == "remove": logger.info("Removing MobSF RootCA") self.adb_command(["rm", ca_file], True)
def install_mobsf_ca(self, action): """Install or Remove MobSF Root CA.""" mobsf_ca = get_ca_file() ca_file = None if is_file_exists(mobsf_ca): ca_construct = "{}.0" pem = open(mobsf_ca, "rb").read() ca_obj = crypto.load_certificate(crypto.FILETYPE_PEM, pem) ca_file_hash = hex(ca_obj.subject_name_hash()).lstrip("0x") ca_file = os.path.join( "/system/etc/security/cacerts/", ca_construct.format(ca_file_hash) ) else: logger.warning("mitmproxy root CA is not generated yet.") return if action == "install": logger.info("Installing MobSF RootCA") self.adb_command(["push", mobsf_ca, ca_file]) self.adb_command(["chmod", "644", ca_file], True) elif action == "remove": logger.info("Removing MobSF RootCA") self.adb_command(["rm", ca_file], True)
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1666
[ERROR] 05/Feb/2021 02:43:41 - Internal Server Error: /search Traceback (most recent call last): File "\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "\mobsf\MobSF\views\home.py", line 227, in search return HttpResponseRedirect('/' + db_obj[0].URL) AttributeError: 'RecentScansDB' object has no attribute 'URL' [ERROR] 05/Feb/2021 02:43:41 - "GET /search?md5=<the file md5> HTTP/1.1" 500 80105
AttributeError
def search(request): """Search Scan by MD5 Route.""" md5 = request.GET["md5"] if re.match("[0-9a-f]{32}", md5): db_obj = RecentScansDB.objects.filter(MD5=md5) if db_obj.exists(): e = db_obj[0] url = ( f"/{e.ANALYZER}/?name={e.FILE_NAME}&amp;" f"checksum={e.MD5}&amp;type={e.SCAN_TYPE}" ) return HttpResponseRedirect(url) else: return HttpResponseRedirect("/not_found/") return print_n_send_error_response(request, "Invalid Scan Hash")
def search(request): """Search Scan by MD5 Route.""" md5 = request.GET["md5"] if re.match("[0-9a-f]{32}", md5): db_obj = RecentScansDB.objects.filter(MD5=md5) if db_obj.exists(): return HttpResponseRedirect("/" + db_obj[0].URL) else: return HttpResponseRedirect("/not_found/") return print_n_send_error_response(request, "Invalid Scan Hash")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1666
[ERROR] 05/Feb/2021 02:43:41 - Internal Server Error: /search Traceback (most recent call last): File "\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "\mobsf\MobSF\views\home.py", line 227, in search return HttpResponseRedirect('/' + db_obj[0].URL) AttributeError: 'RecentScansDB' object has no attribute 'URL' [ERROR] 05/Feb/2021 02:43:41 - "GET /search?md5=<the file md5> HTTP/1.1" 500 80105
AttributeError
def is_package_installed(self, package, extra): """Check if package is installed.""" success = "\nSuccess" in extra out = self.adb_command(["pm", "list", "packages"], True) pkg = f"{package}".encode("utf-8") pkg_fmts = [pkg + b"\n", pkg + b"\r\n", pkg + b"\r\r\n"] if any(pkg in out for pkg in pkg_fmts): # Windows uses \r\n and \r\r\n return True if success: # Fallback check return True return False
def is_package_installed(self, package): """Check if package is installed.""" out = self.adb_command(["pm", "list", "packages"], True) pkg = f"{package}".encode("utf-8") if pkg + b"\n" in out or pkg + b"\r\n" in out: # Windows uses \r\n return True return False
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1582
1. This is the first step upload the specific app to do the static analysis, the mobsf will be killed for no reason 2. This is the second step restart the mobsf ,Traceback (most recent call last): 'security_score'] = score(context['code_analysis']) TypeError: 'NoneType' object is not subscriptable [ERROR] 07/Nov/2020 21:42:48 - 'NoneType' object is not subscriptable [ERROR] 07/Nov/2020 21:42:48 - Internal Server Error: /StaticAnalyzer/ 3. Further steps, etc.
TypeError
def install_apk(self, apk_path, package): """Install APK and Verify Installation.""" if self.is_package_installed(package, ""): logger.info("Removing existing installation") # Remove existing installation' self.adb_command(["uninstall", package], False, True) # Disable install verification self.adb_command( [ "settings", "put", "global", "verifier_verify_adb_installs", "0", ], True, ) logger.info("Installing APK") # Install APK out = self.adb_command(["install", "-r", "-t", "-d", apk_path], False, True) if not out: return False, "adb install failed" out = out.decode("utf-8", "ignore") # Verify Installation return self.is_package_installed(package, out), out
def install_apk(self, apk_path, package): """Install APK and Verify Installation.""" if self.is_package_installed(package): logger.info("Removing existing installation") # Remove existing installation' self.adb_command(["uninstall", package], False, True) # Disable install verification self.adb_command( [ "settings", "put", "global", "verifier_verify_adb_installs", "0", ], True, ) logger.info("Installing APK") # Install APK out = self.adb_command(["install", "-r", "-t", "-d", apk_path], False, True) if not out: return False, "adb install failed" out = out.decode("utf-8", "ignore") # Verify Installation return self.is_package_installed(package), out
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1582
1. This is the first step upload the specific app to do the static analysis, the mobsf will be killed for no reason 2. This is the second step restart the mobsf ,Traceback (most recent call last): 'security_score'] = score(context['code_analysis']) TypeError: 'NoneType' object is not subscriptable [ERROR] 07/Nov/2020 21:42:48 - 'NoneType' object is not subscriptable [ERROR] 07/Nov/2020 21:42:48 - Internal Server Error: /StaticAnalyzer/ 3. Further steps, etc.
TypeError
def checksec(self): elf_dict = {} elf_dict["name"] = self.elf_rel is_nx = self.is_nx() if is_nx: severity = "info" desc = ( "The shared object has NX bit set. This marks a " "memory page non-executable making attacker " "injected shellcode non-executable." ) else: severity = "high" desc = ( "The shared object does not have NX bit set. NX bit " "offer protection against exploitation of memory corruption " "vulnerabilities by marking memory page as non-executable. " "Use option --noexecstack or -z noexecstack to mark stack as " "non executable." ) elf_dict["nx"] = { "is_nx": is_nx, "severity": severity, "description": desc, } severity = "info" is_pie = self.is_pie() if is_pie == "dso": is_pie = "Dynamic Shared Object (DSO)" desc = ( "The shared object is build with -fPIC flag which " "enables Position independent code. This makes Return " "Oriented Programming (ROP) attacks much more difficult " "to execute reliably." ) elif is_pie: desc = ( "The shared object is build with -fPIC flag which " "enables Position independent code. This makes Return " "Oriented Programming (ROP) attacks much more difficult " "to execute reliably." ) else: severity = "high" desc = ( "The shared object is built without Position " "Independent Code flag. In order to prevent " "an attacker from reliably jumping to, for example, a " "particular exploited function in memory, Address " "space layout randomization (ASLR) randomly arranges " "the address space positions of key data areas of a " "process, including the base of the executable and the " "positions of the stack,heap and libraries. Use compiler " "option -fPIC to enable Position Independent Code." ) elf_dict["pie"] = { "is_pie": is_pie, "severity": severity, "description": desc, } has_canary = self.has_canary() if has_canary: severity = "info" desc = ( "This shared object has a stack canary value " "added to the stack so that it will be overwritten by " "a stack buffer that overflows the return address. " "This allows detection of overflows by verifying the " "integrity of the canary before function return." ) else: severity = "high" desc = ( "This shared object does not have a stack " "canary value added to the stack. Stack canraies " "are used to detect and prevent exploits from " "overwriting return address. Use the option " "-fstack-protector-all to enable stack canaries." ) elf_dict["stack_canary"] = { "has_canary": has_canary, "severity": severity, "description": desc, } relro = self.relro() if relro == "Full": severity = "info" desc = ( "This shared object has full RELRO " "enabled. RELRO ensures that the GOT cannot be " "overwritten in vulnerable ELF binaries. " "In Full RELRO, the entire GOT (.got and " ".got.plt both) is marked as read-only." ) elif relro == "Partial": severity = "warning" desc = ( "This shared object has partial RELRO " "enabled. RELRO ensures that the GOT cannot be " "overwritten in vulnerable ELF binaries. " "In partial RELRO, the non-PLT part of the GOT " "section is read only but .got.plt is still " "writeable. Use the option -z,relro,-z,now to " "enable full RELRO." ) else: severity = "high" desc = ( "This shared object does not have RELRO " "enabled. The entire GOT (.got and " ".got.plt both) are writable. Without this compiler " "flag, buffer overflows on a global variable can " "overwrite GOT entries. Use the option " "-z,relro,-z,now to enable full RELRO and only " "-z,relro to enable partial RELRO." ) elf_dict["relocation_readonly"] = { "relro": relro, "severity": severity, "description": desc, } rpath = self.rpath() if rpath: severity = "high" desc = ( "The shared object has RPATH set. In certain cases " "an attacker can abuse this feature to run arbitrary " "shared objects for code execution and privilege " "escalation. The only time a shared library in " "should set RPATH is if it is linked to private " "shared libraries in the same package. Remove the " "compiler option -rpath to remove RPATH." ) else: severity = "info" desc = "The shared object does not have run-time search path or RPATH set." elf_dict["rpath"] = { "rpath": rpath, "severity": severity, "description": desc, } runpath = self.runpath() if runpath: severity = "high" desc = ( "The shared object has RUNPATH set. In certain cases " "an attacker can abuse this feature and or modify " "environment variables to run arbitrary " "shared objects for code execution and privilege " "escalation. The only time a shared library in should " "set RUNPATH is if it is linked to private shared " "libraries in the same package. Remove the compiler " "option --enable-new-dtags,-rpath to remove RUNPATH." ) rnp = runpath.runpath else: severity = "info" desc = "The shared object does not have RUNPATH set." rnp = runpath elf_dict["runpath"] = { "runpath": rnp, "severity": severity, "description": desc, } fortified_functions = self.fortify() if fortified_functions: severity = "info" desc = ( "The shared object has the " f"following fortifed functions: {fortified_functions}" ) else: severity = "warning" desc = ( "The shared object does not have any " "fortified functions. Fortified functions " "provides buffer overflow checks against " "glibc's commons insecure functions like " "strcpy, gets etc. Use the compiler option " "-D_FORTIFY_SOURCE=2 to fority functions." ) elf_dict["fortify"] = { "is_fortified": bool(fortified_functions), "severity": severity, "description": desc, } is_stripped = self.is_symbols_stripped() if is_stripped: severity = "info" desc = "Symbols are stripped." else: severity = "warning" desc = "Symbols are available." elf_dict["symbol"] = { "is_stripped": is_stripped, "severity": severity, "description": desc, } return elf_dict
def checksec(self): elf_dict = {} elf_dict["name"] = self.elf_rel is_nx = self.is_nx() if is_nx: severity = "info" desc = ( "The shared object has NX bit set. This marks a " "memory page non-executable making attacker " "injected shellcode non-executable." ) else: severity = "high" desc = ( "The shared object does not have NX bit set. NX bit " "offer protection against exploitation of memory corruption " "vulnerabilities by marking memory page as non-executable. " "Use option --noexecstack or -z noexecstack to mark stack as " "non executable." ) elf_dict["nx"] = { "is_nx": is_nx, "severity": severity, "description": desc, } severity = "info" is_pie = self.is_pie() if is_pie == "dso": is_pie = "Dynamic Shared Object (DSO)" desc = ( "The shared object is build with -fPIC flag which " "enables Position independent code. This makes Return " "Oriented Programming (ROP) attacks much more difficult " "to execute reliably." ) elif is_pie: desc = ( "The shared object is build with -fPIC flag which " "enables Position independent code. This makes Return " "Oriented Programming (ROP) attacks much more difficult " "to execute reliably." ) else: severity = "high" desc = ( "The shared object is built without Position " "Independent Code flag. In order to prevent " "an attacker from reliably jumping to, for example, a " "particular exploited function in memory, Address " "space layout randomization (ASLR) randomly arranges " "the address space positions of key data areas of a " "process, including the base of the executable and the " "positions of the stack,heap and libraries. Use compiler " "option -fPIC to enable Position Independent Code." ) elf_dict["pie"] = { "is_pie": is_pie, "severity": severity, "description": desc, } has_canary = self.has_canary() if has_canary: severity = "info" desc = ( "This shared object has a stack canary value " "added to the stack so that it will be overwritten by " "a stack buffer that overflows the return address. " "This allows detection of overflows by verifying the " "integrity of the canary before function return." ) else: severity = "high" desc = ( "This shared object does not have a stack " "canary value added to the stack. Stack canraies " "are used to detect and prevent exploits from " "overwriting return address. Use the option " "-fstack-protector-all to enable stack canaries." ) elf_dict["stack_canary"] = { "has_canary": has_canary, "severity": severity, "description": desc, } relro = self.relro() if relro == "Full": severity = "info" desc = ( "This shared object has full RELRO " "enabled. RELRO ensures that the GOT cannot be " "overwritten in vulnerable ELF binaries. " "In Full RELRO, the entire GOT (.got and " ".got.plt both) is marked as read-only." ) elif relro == "Partial": severity = "warning" desc = ( "This shared object has partial RELRO " "enabled. RELRO ensures that the GOT cannot be " "overwritten in vulnerable ELF binaries. " "In partial RELRO, the non-PLT part of the GOT " "section is read only but .got.plt is still " "writeable. Use the option -z,relro,-z,now to " "enable full RELRO." ) else: severity = "high" desc = ( "This shared object does not have RELRO " "enabled. The entire GOT (.got and " ".got.plt both) are writable. Without this compiler " "flag, buffer overflows on a global variable can " "overwrite GOT entries. Use the option " "-z,relro,-z,now to enable full RELRO and only " "-z,relro to enable partial RELRO." ) elf_dict["relocation_readonly"] = { "relro": relro, "severity": severity, "description": desc, } rpath = self.rpath() if rpath: severity = "high" desc = ( "The shared object has RPATH set. In certain cases " "an attacker can abuse this feature to run arbitrary " "shared objects for code execution and privilege " "escalation. The only time a shared library in " "should set RPATH is if it is linked to private " "shared libraries in the same package. Remove the " "compiler option -rpath to remove RPATH." ) else: severity = "info" desc = "The shared object does not have run-time search path or RPATH set." elf_dict["rpath"] = { "rpath": rpath, "severity": severity, "description": desc, } runpath = self.runpath() if runpath: severity = "high" desc = ( "The shared object has RUNPATH set. In certain cases " "an attacker can abuse this feature and or modify " "environment variables to run arbitrary " "shared objects for code execution and privilege " "escalation. The only time a shared library in should " "set RUNPATH is if it is linked to private shared " "libraries in the same package. Remove the compiler " "option --enable-new-dtags,-rpath to remove RUNPATH." ) else: severity = "info" desc = "The shared object does not have RUNPATH set." elf_dict["runpath"] = { "runpath": runpath, "severity": severity, "description": desc, } fortified_functions = self.fortify() if fortified_functions: severity = "info" desc = ( "The shared object has the " f"following fortifed functions: {fortified_functions}" ) else: severity = "warning" desc = ( "The shared object does not have any " "fortified functions. Fortified functions " "provides buffer overflow checks against " "glibc's commons insecure functions like " "strcpy, gets etc. Use the compiler option " "-D_FORTIFY_SOURCE=2 to fority functions." ) elf_dict["fortify"] = { "is_fortified": bool(fortified_functions), "severity": severity, "description": desc, } is_stripped = self.is_symbols_stripped() if is_stripped: severity = "info" desc = "Symbols are stripped." else: severity = "warning" desc = "Symbols are available." elf_dict["symbol"] = { "is_stripped": is_stripped, "severity": severity, "description": desc, } return elf_dict
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1582
1. This is the first step upload the specific app to do the static analysis, the mobsf will be killed for no reason 2. This is the second step restart the mobsf ,Traceback (most recent call last): 'security_score'] = score(context['code_analysis']) TypeError: 'NoneType' object is not subscriptable [ERROR] 07/Nov/2020 21:42:48 - 'NoneType' object is not subscriptable [ERROR] 07/Nov/2020 21:42:48 - Internal Server Error: /StaticAnalyzer/ 3. Further steps, etc.
TypeError
def static_analyzer(request, api=False): """Do static analysis on an request and save to db.""" try: if api: typ = request.POST["scan_type"] checksum = request.POST["hash"] filename = request.POST["file_name"] rescan = str(request.POST.get("re_scan", 0)) else: typ = request.GET["type"] checksum = request.GET["checksum"] filename = request.GET["name"] rescan = str(request.GET.get("rescan", 0)) # Input validation app_dic = {} match = re.match("^[0-9a-f]{32}$", checksum) if ( (match) and (filename.lower().endswith(".apk") or filename.lower().endswith(".zip")) and (typ in ["zip", "apk"]) ): app_dic["dir"] = Path(settings.BASE_DIR) # BASE DIR app_dic["app_name"] = filename # APP ORGINAL NAME app_dic["md5"] = checksum # MD5 # APP DIRECTORY app_dic["app_dir"] = Path(settings.UPLD_DIR) / checksum app_dic["tools_dir"] = app_dic["dir"] / "StaticAnalyzer" / "tools" app_dic["tools_dir"] = app_dic["tools_dir"].as_posix() logger.info("Starting Analysis on : %s", app_dic["app_name"]) if typ == "apk": app_dic["app_file"] = app_dic["md5"] + ".apk" # NEW FILENAME app_dic["app_path"] = ( app_dic["app_dir"] / app_dic["app_file"] ).as_posix() app_dic["app_dir"] = app_dic["app_dir"].as_posix() + "/" # Check if in DB # pylint: disable=E1101 db_entry = StaticAnalyzerAndroid.objects.filter(MD5=app_dic["md5"]) if db_entry.exists() and rescan == "0": context = get_context_from_db_entry(db_entry) else: # ANALYSIS BEGINS app_dic["size"] = ( str(file_size(app_dic["app_path"])) + "MB" ) # FILE SIZE app_dic["sha1"], app_dic["sha256"] = hash_gen(app_dic["app_path"]) app_dic["files"] = unzip(app_dic["app_path"], app_dic["app_dir"]) if not app_dic["files"]: # Can't Analyze APK, bail out. msg = "APK file is invalid or corrupt" if api: return print_n_send_error_response(request, msg, True) else: return print_n_send_error_response(request, msg, False) app_dic["certz"] = get_hardcoded_cert_keystore(app_dic["files"]) logger.info("APK Extracted") # Manifest XML app_dic["parsed_xml"] = get_manifest( app_dic["app_path"], app_dic["app_dir"], app_dic["tools_dir"], "", True, ) # get app_name app_dic["real_name"] = get_app_name( app_dic["app_path"], app_dic["app_dir"], app_dic["tools_dir"], True, ) # Get icon res_path = os.path.join(app_dic["app_dir"], "res") app_dic["icon_hidden"] = True # Even if the icon is hidden, try to guess it by the # default paths app_dic["icon_found"] = False app_dic["icon_path"] = "" # TODO: Check for possible different names for resource # folder? if os.path.exists(res_path): icon_dic = get_icon(app_dic["app_path"], res_path) if icon_dic: app_dic["icon_hidden"] = icon_dic["hidden"] app_dic["icon_found"] = bool(icon_dic["path"]) app_dic["icon_path"] = icon_dic["path"] # Set Manifest link app_dic["mani"] = ( "../ManifestView/?md5=" + app_dic["md5"] + "&type=apk&bin=1" ) man_data_dic = manifest_data(app_dic["parsed_xml"]) app_dic["playstore"] = get_app_details(man_data_dic["packagename"]) man_an_dic = manifest_analysis( app_dic["parsed_xml"], man_data_dic, "", app_dic["app_dir"], ) bin_an_buff = [] bin_an_buff += elf_analysis(app_dic["app_dir"]) bin_an_buff += res_analysis(app_dic["app_dir"]) cert_dic = cert_info(app_dic["app_dir"], app_dic["app_file"]) apkid_results = apkid_analysis( app_dic["app_dir"], app_dic["app_path"], app_dic["app_name"] ) tracker = Trackers.Trackers( app_dic["app_dir"], app_dic["tools_dir"] ) tracker_res = tracker.get_trackers() apk_2_java( app_dic["app_path"], app_dic["app_dir"], app_dic["tools_dir"] ) dex_2_smali(app_dic["app_dir"], app_dic["tools_dir"]) code_an_dic = code_analysis(app_dic["app_dir"], "apk") # Get the strings string_res = strings_jar(app_dic["app_file"], app_dic["app_dir"]) if string_res: app_dic["strings"] = string_res["strings"] app_dic["secrets"] = string_res["secrets"] code_an_dic["urls_list"].extend(string_res["urls_list"]) code_an_dic["urls"].extend(string_res["url_nf"]) code_an_dic["emails"].extend(string_res["emails_nf"]) else: app_dic["strings"] = [] app_dic["secrets"] = [] # Firebase DB Check code_an_dic["firebase"] = firebase_analysis( list(set(code_an_dic["urls_list"])) ) # Domain Extraction and Malware Check logger.info("Performing Malware Check on extracted Domains") code_an_dic["domains"] = malware_check( list(set(code_an_dic["urls_list"])) ) # Copy App icon copy_icon(app_dic["md5"], app_dic["icon_path"]) app_dic["zipped"] = "apk" logger.info("Connecting to Database") try: # SAVE TO DB if rescan == "1": logger.info("Updating Database...") save_or_update( "update", app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, apkid_results, tracker_res, ) update_scan_timestamp(app_dic["md5"]) elif rescan == "0": logger.info("Saving to Database") save_or_update( "save", app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, apkid_results, tracker_res, ) except Exception: logger.exception("Saving to Database Failed") context = get_context_from_analysis( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, apkid_results, tracker_res, ) context["average_cvss"], context["security_score"] = score( context["code_analysis"] ) context["dynamic_analysis_done"] = is_file_exists( os.path.join(app_dic["app_dir"], "logcat.txt") ) context["virus_total"] = None if settings.VT_ENABLED: vt = VirusTotal.VirusTotal() context["virus_total"] = vt.get_result( app_dic["app_path"], app_dic["md5"] ) template = "static_analysis/android_binary_analysis.html" if api: return context else: return render(request, template, context) elif typ == "zip": ios_ret = HttpResponseRedirect( "/StaticAnalyzer_iOS/?name=" + app_dic["app_name"] + "&type=ios&checksum=" + app_dic["md5"] ) # Check if in DB # pylint: disable=E1101 cert_dic = { "certificate_info": "", "certificate_status": "", "description": "", } bin_an_buff = [] app_dic["strings"] = [] app_dic["secrets"] = [] app_dic["zipped"] = "" # Above fields are only available for APK and not ZIP app_dic["app_file"] = app_dic["md5"] + ".zip" # NEW FILENAME app_dic["app_path"] = ( app_dic["app_dir"] / app_dic["app_file"] ).as_posix() app_dic["app_dir"] = app_dic["app_dir"].as_posix() + "/" db_entry = StaticAnalyzerAndroid.objects.filter(MD5=app_dic["md5"]) ios_db_entry = StaticAnalyzerIOS.objects.filter(MD5=app_dic["md5"]) if db_entry.exists() and rescan == "0": context = get_context_from_db_entry(db_entry) elif ios_db_entry.exists() and rescan == "0": if api: return {"type": "ios"} else: return ios_ret else: logger.info("Extracting ZIP") app_dic["files"] = unzip(app_dic["app_path"], app_dic["app_dir"]) # Check if Valid Directory Structure and get ZIP Type pro_type, valid = valid_android_zip(app_dic["app_dir"]) if valid and pro_type == "ios": logger.info("Redirecting to iOS Source Code Analyzer") if api: return {"type": "ios"} else: return ios_ret app_dic["certz"] = get_hardcoded_cert_keystore(app_dic["files"]) app_dic["zipped"] = pro_type logger.info("ZIP Type - %s", pro_type) if valid and (pro_type in ["eclipse", "studio"]): # ANALYSIS BEGINS app_dic["size"] = ( str(file_size(app_dic["app_path"])) + "MB" ) # FILE SIZE app_dic["sha1"], app_dic["sha256"] = hash_gen( app_dic["app_path"] ) # Manifest XML app_dic["persed_xml"] = get_manifest( "", app_dic["app_dir"], app_dic["tools_dir"], pro_type, False, ) # get app_name app_dic["real_name"] = get_app_name( app_dic["app_path"], app_dic["app_dir"], app_dic["tools_dir"], False, ) # Set manifest view link app_dic["mani"] = ( "../ManifestView/?md5=" + app_dic["md5"] + "&type=" + pro_type + "&bin=0" ) man_data_dic = manifest_data(app_dic["persed_xml"]) app_dic["playstore"] = get_app_details( man_data_dic["packagename"] ) man_an_dic = manifest_analysis( app_dic["persed_xml"], man_data_dic, pro_type, app_dic["app_dir"], ) # Get icon eclipse_res_path = os.path.join(app_dic["app_dir"], "res") studio_res_path = os.path.join( app_dic["app_dir"], "app", "src", "main", "res" ) if os.path.exists(eclipse_res_path): res_path = eclipse_res_path elif os.path.exists(studio_res_path): res_path = studio_res_path else: res_path = "" app_dic["icon_hidden"] = man_an_dic["icon_hidden"] app_dic["icon_found"] = False app_dic["icon_path"] = "" if res_path: app_dic["icon_path"] = find_icon_path_zip( res_path, man_data_dic["icons"] ) if app_dic["icon_path"]: app_dic["icon_found"] = True if app_dic["icon_path"]: if os.path.exists(app_dic["icon_path"]): shutil.copy2( app_dic["icon_path"], os.path.join( settings.DWD_DIR, app_dic["md5"] + "-icon.png" ), ) code_an_dic = code_analysis(app_dic["app_dir"], pro_type) # Firebase DB Check code_an_dic["firebase"] = firebase_analysis( list(set(code_an_dic["urls_list"])) ) # Domain Extraction and Malware Check logger.info("Performing Malware Check on extracted Domains") code_an_dic["domains"] = malware_check( list(set(code_an_dic["urls_list"])) ) logger.info("Connecting to Database") try: # SAVE TO DB if rescan == "1": logger.info("Updating Database...") save_or_update( "update", app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, {}, {}, ) update_scan_timestamp(app_dic["md5"]) elif rescan == "0": logger.info("Saving to Database") save_or_update( "save", app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, {}, {}, ) except Exception: logger.exception("Saving to Database Failed") context = get_context_from_analysis( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, {}, {}, ) else: msg = "This ZIP Format is not supported" if api: return print_n_send_error_response(request, msg, True) else: print_n_send_error_response(request, msg, False) ctx = { "title": "Invalid ZIP archive", "version": settings.MOBSF_VER, } template = "general/zip.html" return render(request, template, ctx) context["average_cvss"], context["security_score"] = score( context["code_analysis"] ) template = "static_analysis/android_source_analysis.html" if api: return context else: return render(request, template, context) else: err = "Only APK,IPA and Zipped Android/iOS Source code supported now!" logger.error(err) else: msg = "Hash match failed or Invalid file extension or file type" if api: return print_n_send_error_response(request, msg, True) else: return print_n_send_error_response(request, msg, False) except Exception as excep: logger.exception("Error Performing Static Analysis") msg = str(excep) exp = excep.__doc__ if api: return print_n_send_error_response(request, msg, True, exp) else: return print_n_send_error_response(request, msg, False, exp)
def static_analyzer(request, api=False): """Do static analysis on an request and save to db.""" try: if api: typ = request.POST["scan_type"] checksum = request.POST["hash"] filename = request.POST["file_name"] rescan = str(request.POST.get("re_scan", 0)) else: typ = request.GET["type"] checksum = request.GET["checksum"] filename = request.GET["name"] rescan = str(request.GET.get("rescan", 0)) # Input validation app_dic = {} match = re.match("^[0-9a-f]{32}$", checksum) if ( (match) and (filename.lower().endswith(".apk") or filename.lower().endswith(".zip")) and (typ in ["zip", "apk"]) ): app_dic["dir"] = Path(settings.BASE_DIR) # BASE DIR app_dic["app_name"] = filename # APP ORGINAL NAME app_dic["md5"] = checksum # MD5 # APP DIRECTORY app_dic["app_dir"] = Path(settings.UPLD_DIR) / checksum app_dic["tools_dir"] = app_dic["dir"] / "StaticAnalyzer" / "tools" app_dic["tools_dir"] = app_dic["tools_dir"].as_posix() logger.info("Starting Analysis on : %s", app_dic["app_name"]) if typ == "apk": app_dic["app_file"] = app_dic["md5"] + ".apk" # NEW FILENAME app_dic["app_path"] = ( app_dic["app_dir"] / app_dic["app_file"] ).as_posix() app_dic["app_dir"] = app_dic["app_dir"].as_posix() + "/" # Check if in DB # pylint: disable=E1101 db_entry = StaticAnalyzerAndroid.objects.filter(MD5=app_dic["md5"]) if db_entry.exists() and rescan == "0": context = get_context_from_db_entry(db_entry) else: # ANALYSIS BEGINS app_dic["size"] = ( str(file_size(app_dic["app_path"])) + "MB" ) # FILE SIZE app_dic["sha1"], app_dic["sha256"] = hash_gen(app_dic["app_path"]) app_dic["files"] = unzip(app_dic["app_path"], app_dic["app_dir"]) if not app_dic["files"]: # Can't Analyze APK, bail out. msg = "APK file is invalid or corrupt" if api: return print_n_send_error_response(request, msg, True) else: return print_n_send_error_response(request, msg, False) app_dic["certz"] = get_hardcoded_cert_keystore(app_dic["files"]) logger.info("APK Extracted") # Manifest XML app_dic["parsed_xml"] = get_manifest( app_dic["app_path"], app_dic["app_dir"], app_dic["tools_dir"], "", True, ) # get app_name app_dic["real_name"] = get_app_name( app_dic["app_path"], app_dic["app_dir"], app_dic["tools_dir"], True, ) # Get icon res_path = os.path.join(app_dic["app_dir"], "res") app_dic["icon_hidden"] = True # Even if the icon is hidden, try to guess it by the # default paths app_dic["icon_found"] = False app_dic["icon_path"] = "" # TODO: Check for possible different names for resource # folder? if os.path.exists(res_path): icon_dic = get_icon(app_dic["app_path"], res_path) if icon_dic: app_dic["icon_hidden"] = icon_dic["hidden"] app_dic["icon_found"] = bool(icon_dic["path"]) app_dic["icon_path"] = icon_dic["path"] # Set Manifest link app_dic["mani"] = ( "../ManifestView/?md5=" + app_dic["md5"] + "&type=apk&bin=1" ) man_data_dic = manifest_data(app_dic["parsed_xml"]) app_dic["playstore"] = get_app_details(man_data_dic["packagename"]) man_an_dic = manifest_analysis( app_dic["parsed_xml"], man_data_dic, "", app_dic["app_dir"], ) bin_an_buff = [] bin_an_buff += elf_analysis(app_dic["app_dir"]) bin_an_buff += res_analysis(app_dic["app_dir"]) cert_dic = cert_info(app_dic["app_dir"], app_dic["app_file"]) apkid_results = apkid_analysis( app_dic["app_dir"], app_dic["app_path"], app_dic["app_name"] ) tracker = Trackers.Trackers( app_dic["app_dir"], app_dic["tools_dir"] ) tracker_res = tracker.get_trackers() apk_2_java( app_dic["app_path"], app_dic["app_dir"], app_dic["tools_dir"] ) dex_2_smali(app_dic["app_dir"], app_dic["tools_dir"]) code_an_dic = code_analysis(app_dic["app_dir"], "apk") # Get the strings string_res = strings_jar(app_dic["app_file"], app_dic["app_dir"]) if string_res: app_dic["strings"] = string_res["strings"] app_dic["secrets"] = string_res["secrets"] code_an_dic["urls_list"].extend(string_res["urls_list"]) code_an_dic["urls"].extend(string_res["url_nf"]) code_an_dic["emails"].extend(string_res["emails_nf"]) else: app_dic["strings"] = [] app_dic["secrets"] = [] # Firebase DB Check code_an_dic["firebase"] = firebase_analysis( list(set(code_an_dic["urls_list"])) ) # Domain Extraction and Malware Check logger.info("Performing Malware Check on extracted Domains") code_an_dic["domains"] = malware_check( list(set(code_an_dic["urls_list"])) ) # Copy App icon copy_icon(app_dic["md5"], app_dic["icon_path"]) app_dic["zipped"] = "apk" logger.info("Connecting to Database") try: # SAVE TO DB if rescan == "1": logger.info("Updating Database...") save_or_update( "update", app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, apkid_results, tracker_res, ) update_scan_timestamp(app_dic["md5"]) elif rescan == "0": logger.info("Saving to Database") save_or_update( "save", app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, apkid_results, tracker_res, ) except Exception: logger.exception("Saving to Database Failed") context = get_context_from_analysis( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, apkid_results, tracker_res, ) context["average_cvss"], context["security_score"] = score( context["code_analysis"] ) context["dynamic_analysis_done"] = is_file_exists( os.path.join(app_dic["app_dir"], "logcat.txt") ) context["virus_total"] = None if settings.VT_ENABLED: vt = VirusTotal.VirusTotal() context["virus_total"] = vt.get_result( app_dic["app_path"], app_dic["md5"] ) template = "static_analysis/android_binary_analysis.html" if api: return context else: return render(request, template, context) elif typ == "zip": # Check if in DB # pylint: disable=E1101 cert_dic = { "certificate_info": "", "certificate_status": "", "description": "", } bin_an_buff = [] app_dic["strings"] = [] app_dic["secrets"] = [] app_dic["zipped"] = "" # Above fields are only available for APK and not ZIP app_dic["app_file"] = app_dic["md5"] + ".zip" # NEW FILENAME app_dic["app_path"] = ( app_dic["app_dir"] / app_dic["app_file"] ).as_posix() app_dic["app_dir"] = app_dic["app_dir"].as_posix() + "/" db_entry = StaticAnalyzerAndroid.objects.filter(MD5=app_dic["md5"]) if db_entry.exists() and rescan == "0": context = get_context_from_db_entry(db_entry) else: logger.info("Extracting ZIP") app_dic["files"] = unzip(app_dic["app_path"], app_dic["app_dir"]) # Check if Valid Directory Structure and get ZIP Type pro_type, valid = valid_android_zip(app_dic["app_dir"]) if valid and pro_type == "ios": logger.info("Redirecting to iOS Source Code Analyzer") if api: return {"type": "ios"} else: return HttpResponseRedirect( "/StaticAnalyzer_iOS/?name=" + app_dic["app_name"] + "&type=ios&checksum=" + app_dic["md5"] ) app_dic["certz"] = get_hardcoded_cert_keystore(app_dic["files"]) app_dic["zipped"] = pro_type logger.info("ZIP Type - %s", pro_type) if valid and (pro_type in ["eclipse", "studio"]): # ANALYSIS BEGINS app_dic["size"] = ( str(file_size(app_dic["app_path"])) + "MB" ) # FILE SIZE app_dic["sha1"], app_dic["sha256"] = hash_gen( app_dic["app_path"] ) # Manifest XML app_dic["persed_xml"] = get_manifest( "", app_dic["app_dir"], app_dic["tools_dir"], pro_type, False, ) # get app_name app_dic["real_name"] = get_app_name( app_dic["app_path"], app_dic["app_dir"], app_dic["tools_dir"], False, ) # Set manifest view link app_dic["mani"] = ( "../ManifestView/?md5=" + app_dic["md5"] + "&type=" + pro_type + "&bin=0" ) man_data_dic = manifest_data(app_dic["persed_xml"]) app_dic["playstore"] = get_app_details( man_data_dic["packagename"] ) man_an_dic = manifest_analysis( app_dic["persed_xml"], man_data_dic, pro_type, app_dic["app_dir"], ) # Get icon eclipse_res_path = os.path.join(app_dic["app_dir"], "res") studio_res_path = os.path.join( app_dic["app_dir"], "app", "src", "main", "res" ) if os.path.exists(eclipse_res_path): res_path = eclipse_res_path elif os.path.exists(studio_res_path): res_path = studio_res_path else: res_path = "" app_dic["icon_hidden"] = man_an_dic["icon_hidden"] app_dic["icon_found"] = False app_dic["icon_path"] = "" if res_path: app_dic["icon_path"] = find_icon_path_zip( res_path, man_data_dic["icons"] ) if app_dic["icon_path"]: app_dic["icon_found"] = True if app_dic["icon_path"]: if os.path.exists(app_dic["icon_path"]): shutil.copy2( app_dic["icon_path"], os.path.join( settings.DWD_DIR, app_dic["md5"] + "-icon.png" ), ) code_an_dic = code_analysis(app_dic["app_dir"], pro_type) # Firebase DB Check code_an_dic["firebase"] = firebase_analysis( list(set(code_an_dic["urls_list"])) ) # Domain Extraction and Malware Check logger.info("Performing Malware Check on extracted Domains") code_an_dic["domains"] = malware_check( list(set(code_an_dic["urls_list"])) ) logger.info("Connecting to Database") try: # SAVE TO DB if rescan == "1": logger.info("Updating Database...") save_or_update( "update", app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, {}, {}, ) update_scan_timestamp(app_dic["md5"]) elif rescan == "0": logger.info("Saving to Database") save_or_update( "save", app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, {}, {}, ) except Exception: logger.exception("Saving to Database Failed") context = get_context_from_analysis( app_dic, man_data_dic, man_an_dic, code_an_dic, cert_dic, bin_an_buff, {}, {}, ) else: msg = "This ZIP Format is not supported" if api: return print_n_send_error_response(request, msg, True) else: print_n_send_error_response(request, msg, False) ctx = { "title": "Invalid ZIP archive", "version": settings.MOBSF_VER, } template = "general/zip.html" return render(request, template, ctx) context["average_cvss"], context["security_score"] = score( context["code_analysis"] ) template = "static_analysis/android_source_analysis.html" if api: return context else: return render(request, template, context) else: err = "Only APK,IPA and Zipped Android/iOS Source code supported now!" logger.error(err) else: msg = "Hash match failed or Invalid file extension or file type" if api: return print_n_send_error_response(request, msg, True) else: return print_n_send_error_response(request, msg, False) except Exception as excep: logger.exception("Error Performing Static Analysis") msg = str(excep) exp = excep.__doc__ if api: return print_n_send_error_response(request, msg, True, exp) else: return print_n_send_error_response(request, msg, False, exp)
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1542
[ERROR] 18/Sep/2020 16:56:43 - Reading from Info.plist Traceback (most recent call last): File "/root/Mobile-Security-Framework-MobSF/StaticAnalyzer/views/ios/plist_analysis.py", line 67, in plist_analysis dirs = os.listdir(src) FileNotFoundError: [Errno 2] No such file or directory: '/root/.MobSF/uploads/ab66d07fa05376c8bb931e981e9e470e/Payload/' [ERROR] 18/Sep/2020 16:56:43 - Error Perfroming Static Analysis Traceback (most recent call last): File "/root/Mobile-Security-Framework-MobSF/StaticAnalyzer/views/ios/static_analyzer.py", line 102, in static_analyzer_ios app_dict['appstore'] = app_search(infoplist_dict.get('id')) AttributeError: 'NoneType' object has no attribute 'get' [ERROR] 18/Sep/2020 16:56:43 - 'NoneType' object has no attribute 'get' [ERROR] 18/Sep/2020 16:56:43 - Internal Server Error: /StaticAnalyzer_iOS/
FileNotFoundError
def static_analyzer_ios(request, api=False): """Module that performs iOS IPA/ZIP Static Analysis.""" try: logger.info("iOS Static Analysis Started") if api: file_type = request.POST["scan_type"] checksum = request.POST["hash"] rescan = str(request.POST.get("re_scan", 0)) filename = request.POST["file_name"] else: file_type = request.GET["type"] checksum = request.GET["checksum"] rescan = str(request.GET.get("rescan", 0)) filename = request.GET["name"] md5_match = re.match("^[0-9a-f]{32}$", checksum) if ( (md5_match) and (filename.lower().endswith(".ipa") or filename.lower().endswith(".zip")) and (file_type in ["ipa", "ios"]) ): app_dict = {} app_dict["directory"] = Path(settings.BASE_DIR) # BASE DIR app_dict["file_name"] = filename # APP ORGINAL NAME app_dict["md5_hash"] = checksum # MD5 app_dir = Path(settings.UPLD_DIR) / checksum tools_dir = app_dict["directory"] / "StaticAnalyzer" / "tools" / "ios" tools_dir = tools_dir.as_posix() if file_type == "ipa": app_dict["app_file"] = app_dict["md5_hash"] + ".ipa" # NEW FILENAME app_dict["app_path"] = app_dir / app_dict["app_file"] app_dict["app_path"] = app_dict["app_path"].as_posix() # DB ipa_db = StaticAnalyzerIOS.objects.filter(MD5=app_dict["md5_hash"]) if ipa_db.exists() and rescan == "0": context = get_context_from_db_entry(ipa_db) else: logger.info("iOS Binary (IPA) Analysis Started") app_dict["app_dir"] = app_dir.as_posix() + "/" app_dict["size"] = ( str(file_size(app_dict["app_path"])) + "MB" ) # FILE SIZE app_dict["sha1"], app_dict["sha256"] = hash_gen( app_dict["app_path"] ) # SHA1 & SHA256 HASHES logger.info("Extracting IPA") # EXTRACT IPA unzip(app_dict["app_path"], app_dict["app_dir"]) # Identify Payload directory dirs = app_dir.glob("**/*") for _dir in dirs: if "payload" in _dir.as_posix().lower(): app_dict["bin_dir"] = app_dict["app_dir"] / _dir break else: msg = "IPA is malformed! MobSF cannot find Payload directory" if api: return print_n_send_error_response(request, msg, True) else: return print_n_send_error_response(request, msg, False) app_dict["bin_dir"] = app_dict["bin_dir"].as_posix() + "/" # Get Files all_files = ios_list_files( app_dict["bin_dir"], app_dict["md5_hash"], True, "ipa" ) infoplist_dict = plist_analysis(app_dict["bin_dir"], False) app_dict["appstore"] = app_search(infoplist_dict.get("id")) bin_analysis_dict = binary_analysis( app_dict["bin_dir"], tools_dir, app_dict["app_dir"], infoplist_dict.get("bin"), ) # Get Icon app_dict["icon_found"] = get_icon( app_dict["md5_hash"], app_dict["bin_dir"], infoplist_dict.get("bin"), ) # IPA URL and Email Extract recon = extract_urls_n_email( app_dict["bin_dir"], all_files["files_long"], bin_analysis_dict["strings"], ) code_dict = { "api": {}, "code_anal": {}, "urlnfile": recon["urlnfile"], "domains": recon["domains"], "emailnfile": recon["emailnfile"], "firebase": firebase_analysis(recon["urls_list"]), } # Saving to DB logger.info("Connecting to DB") if rescan == "1": logger.info("Updating Database...") save_or_update( "update", app_dict, infoplist_dict, code_dict, bin_analysis_dict, all_files, ) update_scan_timestamp(app_dict["md5_hash"]) elif rescan == "0": logger.info("Saving to Database") save_or_update( "save", app_dict, infoplist_dict, code_dict, bin_analysis_dict, all_files, ) context = get_context_from_analysis( app_dict, infoplist_dict, code_dict, bin_analysis_dict, all_files, ) context["virus_total"] = None if settings.VT_ENABLED: vt = VirusTotal.VirusTotal() context["virus_total"] = vt.get_result( app_dict["app_path"], app_dict["md5_hash"] ) context["average_cvss"], context["security_score"] = score( context["binary_analysis"] ) template = "static_analysis/ios_binary_analysis.html" if api: return context else: return render(request, template, context) elif file_type == "ios": ios_zip_db = StaticAnalyzerIOS.objects.filter(MD5=app_dict["md5_hash"]) if ios_zip_db.exists() and rescan == "0": context = get_context_from_db_entry(ios_zip_db) else: logger.info("iOS Source Code Analysis Started") app_dict["app_file"] = app_dict["md5_hash"] + ".zip" # NEW FILENAME app_dict["app_path"] = app_dir / app_dict["app_file"] app_dict["app_path"] = app_dict["app_path"].as_posix() app_dict["app_dir"] = app_dir.as_posix() + "/" # ANALYSIS BEGINS - Already Unzipped app_dict["size"] = ( str(file_size(app_dict["app_path"])) + "MB" ) # FILE SIZE app_dict["sha1"], app_dict["sha256"] = hash_gen( app_dict["app_path"] ) # SHA1 & SHA256 HASHES all_files = ios_list_files( app_dict["app_dir"], app_dict["md5_hash"], False, "ios" ) infoplist_dict = plist_analysis(app_dict["app_dir"], True) app_dict["appstore"] = app_search(infoplist_dict.get("id")) code_analysis_dic = ios_source_analysis(app_dict["app_dir"]) # Get App Icon app_dict["icon_found"] = get_icon_source( app_dict["md5_hash"], app_dict["app_dir"] ) # Firebase DB Check code_analysis_dic["firebase"] = firebase_analysis( list(set(code_analysis_dic["urls_list"])) ) fake_bin_dict = { "bin_type": code_analysis_dic["source_type"], "macho": {}, "bin_res": [], "libs": [], "strings": [], } # Saving to DB logger.info("Connecting to DB") if rescan == "1": logger.info("Updating Database...") save_or_update( "update", app_dict, infoplist_dict, code_analysis_dic, fake_bin_dict, all_files, ) update_scan_timestamp(app_dict["md5_hash"]) elif rescan == "0": logger.info("Saving to Database") save_or_update( "save", app_dict, infoplist_dict, code_analysis_dic, fake_bin_dict, all_files, ) context = get_context_from_analysis( app_dict, infoplist_dict, code_analysis_dic, fake_bin_dict, all_files, ) context["average_cvss"], context["security_score"] = score( context["code_analysis"] ) template = "static_analysis/ios_source_analysis.html" if api: return context else: return render(request, template, context) else: msg = "File Type not supported!" if api: return print_n_send_error_response(request, msg, True) else: return print_n_send_error_response(request, msg, False) else: msg = "Hash match failed or Invalid file extension or file type" if api: return print_n_send_error_response(request, msg, True) else: return print_n_send_error_response(request, msg, False) except Exception as exp: logger.exception("Error Perfroming Static Analysis") msg = str(exp) exp_doc = exp.__doc__ if api: return print_n_send_error_response(request, msg, True, exp_doc) else: return print_n_send_error_response(request, msg, False, exp_doc)
def static_analyzer_ios(request, api=False): """Module that performs iOS IPA/ZIP Static Analysis.""" try: logger.info("iOS Static Analysis Started") if api: file_type = request.POST["scan_type"] checksum = request.POST["hash"] rescan = str(request.POST.get("re_scan", 0)) filename = request.POST["file_name"] else: file_type = request.GET["type"] checksum = request.GET["checksum"] rescan = str(request.GET.get("rescan", 0)) filename = request.GET["name"] md5_match = re.match("^[0-9a-f]{32}$", checksum) if ( (md5_match) and (filename.lower().endswith(".ipa") or filename.lower().endswith(".zip")) and (file_type in ["ipa", "ios"]) ): app_dict = {} app_dict["directory"] = Path(settings.BASE_DIR) # BASE DIR app_dict["file_name"] = filename # APP ORGINAL NAME app_dict["md5_hash"] = checksum # MD5 app_dict["app_dir"] = Path(settings.UPLD_DIR) / checksum tools_dir = app_dict["directory"] / "StaticAnalyzer" / "tools" / "ios" tools_dir = tools_dir.as_posix() if file_type == "ipa": app_dict["app_file"] = app_dict["md5_hash"] + ".ipa" # NEW FILENAME app_dict["app_path"] = app_dict["app_dir"] / app_dict["app_file"] app_dict["app_path"] = app_dict["app_path"].as_posix() # DB ipa_db = StaticAnalyzerIOS.objects.filter(MD5=app_dict["md5_hash"]) if ipa_db.exists() and rescan == "0": context = get_context_from_db_entry(ipa_db) else: logger.info("iOS Binary (IPA) Analysis Started") app_dict["bin_dir"] = app_dict["app_dir"] / "Payload" app_dict["bin_dir"] = app_dict["bin_dir"].as_posix() + "/" app_dict["app_dir"] = app_dict["app_dir"].as_posix() + "/" app_dict["size"] = ( str(file_size(app_dict["app_path"])) + "MB" ) # FILE SIZE app_dict["sha1"], app_dict["sha256"] = hash_gen( app_dict["app_path"] ) # SHA1 & SHA256 HASHES logger.info("Extracting IPA") # EXTRACT IPA unzip(app_dict["app_path"], app_dict["app_dir"]) # Get Files, normalize + to x, # and convert binary plist -> xml all_files = ios_list_files( app_dict["bin_dir"], app_dict["md5_hash"], True, "ipa" ) infoplist_dict = plist_analysis(app_dict["bin_dir"], False) app_dict["appstore"] = app_search(infoplist_dict.get("id")) bin_analysis_dict = binary_analysis( app_dict["bin_dir"], tools_dir, app_dict["app_dir"], infoplist_dict.get("bin"), ) # Get Icon app_dict["icon_found"] = get_icon( app_dict["md5_hash"], app_dict["bin_dir"], infoplist_dict.get("bin"), ) # IPA URL and Email Extract recon = extract_urls_n_email( app_dict["bin_dir"], all_files["files_long"], bin_analysis_dict["strings"], ) code_dict = { "api": {}, "code_anal": {}, "urlnfile": recon["urlnfile"], "domains": recon["domains"], "emailnfile": recon["emailnfile"], "firebase": firebase_analysis(recon["urls_list"]), } # Saving to DB logger.info("Connecting to DB") if rescan == "1": logger.info("Updating Database...") save_or_update( "update", app_dict, infoplist_dict, code_dict, bin_analysis_dict, all_files, ) update_scan_timestamp(app_dict["md5_hash"]) elif rescan == "0": logger.info("Saving to Database") save_or_update( "save", app_dict, infoplist_dict, code_dict, bin_analysis_dict, all_files, ) context = get_context_from_analysis( app_dict, infoplist_dict, code_dict, bin_analysis_dict, all_files, ) context["virus_total"] = None if settings.VT_ENABLED: vt = VirusTotal.VirusTotal() context["virus_total"] = vt.get_result( app_dict["app_path"], app_dict["md5_hash"] ) context["average_cvss"], context["security_score"] = score( context["binary_analysis"] ) template = "static_analysis/ios_binary_analysis.html" if api: return context else: return render(request, template, context) elif file_type == "ios": ios_zip_db = StaticAnalyzerIOS.objects.filter(MD5=app_dict["md5_hash"]) if ios_zip_db.exists() and rescan == "0": context = get_context_from_db_entry(ios_zip_db) else: logger.info("iOS Source Code Analysis Started") app_dict["app_file"] = app_dict["md5_hash"] + ".zip" # NEW FILENAME app_dict["app_path"] = app_dict["app_dir"] / app_dict["app_file"] app_dict["app_path"] = app_dict["app_path"].as_posix() app_dict["app_dir"] = app_dict["app_dir"].as_posix() + "/" # ANALYSIS BEGINS - Already Unzipped logger.info("ZIP Already Extracted") app_dict["size"] = ( str(file_size(app_dict["app_path"])) + "MB" ) # FILE SIZE app_dict["sha1"], app_dict["sha256"] = hash_gen( app_dict["app_path"] ) # SHA1 & SHA256 HASHES all_files = ios_list_files( app_dict["app_dir"], app_dict["md5_hash"], False, "ios" ) infoplist_dict = plist_analysis(app_dict["app_dir"], True) app_dict["appstore"] = app_search(infoplist_dict.get("id")) code_analysis_dic = ios_source_analysis(app_dict["app_dir"]) # Get App Icon app_dict["icon_found"] = get_icon_source( app_dict["md5_hash"], app_dict["app_dir"] ) # Firebase DB Check code_analysis_dic["firebase"] = firebase_analysis( list(set(code_analysis_dic["urls_list"])) ) fake_bin_dict = { "bin_type": code_analysis_dic["source_type"], "macho": {}, "bin_res": [], "libs": [], "strings": [], } # Saving to DB logger.info("Connecting to DB") if rescan == "1": logger.info("Updating Database...") save_or_update( "update", app_dict, infoplist_dict, code_analysis_dic, fake_bin_dict, all_files, ) update_scan_timestamp(app_dict["md5_hash"]) elif rescan == "0": logger.info("Saving to Database") save_or_update( "save", app_dict, infoplist_dict, code_analysis_dic, fake_bin_dict, all_files, ) context = get_context_from_analysis( app_dict, infoplist_dict, code_analysis_dic, fake_bin_dict, all_files, ) context["average_cvss"], context["security_score"] = score( context["code_analysis"] ) template = "static_analysis/ios_source_analysis.html" if api: return context else: return render(request, template, context) else: msg = "File Type not supported!" if api: return print_n_send_error_response(request, msg, True) else: return print_n_send_error_response(request, msg, False) else: msg = "Hash match failed or Invalid file extension or file type" if api: return print_n_send_error_response(request, msg, True) else: return print_n_send_error_response(request, msg, False) except Exception as exp: logger.exception("Error Perfroming Static Analysis") msg = str(exp) exp_doc = exp.__doc__ if api: return print_n_send_error_response(request, msg, True, exp_doc) else: return print_n_send_error_response(request, msg, False, exp_doc)
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1542
[ERROR] 18/Sep/2020 16:56:43 - Reading from Info.plist Traceback (most recent call last): File "/root/Mobile-Security-Framework-MobSF/StaticAnalyzer/views/ios/plist_analysis.py", line 67, in plist_analysis dirs = os.listdir(src) FileNotFoundError: [Errno 2] No such file or directory: '/root/.MobSF/uploads/ab66d07fa05376c8bb931e981e9e470e/Payload/' [ERROR] 18/Sep/2020 16:56:43 - Error Perfroming Static Analysis Traceback (most recent call last): File "/root/Mobile-Security-Framework-MobSF/StaticAnalyzer/views/ios/static_analyzer.py", line 102, in static_analyzer_ios app_dict['appstore'] = app_search(infoplist_dict.get('id')) AttributeError: 'NoneType' object has no attribute 'get' [ERROR] 18/Sep/2020 16:56:43 - 'NoneType' object has no attribute 'get' [ERROR] 18/Sep/2020 16:56:43 - Internal Server Error: /StaticAnalyzer_iOS/
FileNotFoundError
def run(request, api=False): """View iOS Files.""" try: logger.info("View iOS Source File") exp = "Error Description" file_format = None if api: fil = request.POST["file"] md5_hash = request.POST["hash"] mode = request.POST["type"] viewsource_form = ViewSourceIOSApiForm(request.POST) else: fil = request.GET["file"] md5_hash = request.GET["md5"] mode = request.GET["type"] viewsource_form = ViewSourceIOSForm(request.GET) typ = set_ext_api(fil) if not viewsource_form.is_valid(): err = FormUtil.errors_message(viewsource_form) if api: return err return print_n_send_error_response(request, err, False, exp) base = Path(settings.UPLD_DIR) / md5_hash if mode == "ipa": src1 = base / "payload" src2 = base / "Payload" if src1.exists(): src = src1 elif src2.exists(): src = src2 else: raise Exception("MobSF cannot find Payload directory") elif mode == "ios": src = base sfile = src / fil sfile = sfile.as_posix() if not is_safe_path(src, sfile): msg = "Path Traversal Detected!" if api: return {"error": "Path Traversal Detected!"} return print_n_send_error_response(request, msg, False, exp) dat = "" sql_dump = {} if typ == "m": file_format = "cpp" with io.open(sfile, mode="r", encoding="utf8", errors="ignore") as flip: dat = flip.read() elif typ == "xml": file_format = "xml" with io.open(sfile, mode="r", encoding="utf8", errors="ignore") as flip: dat = flip.read() elif typ == "plist": file_format = "json" dat = biplist.readPlist(sfile) try: dat = json.dumps(dat, indent=4, sort_keys=True) except Exception: pass elif typ == "db": file_format = "asciidoc" sql_dump = read_sqlite(sfile) elif typ == "txt" and fil == "classdump.txt": file_format = "cpp" app_dir = os.path.join(settings.UPLD_DIR, md5_hash + "/") cls_dump_file = os.path.join(app_dir, "classdump.txt") if is_file_exists(cls_dump_file): with io.open( cls_dump_file, mode="r", encoding="utf8", errors="ignore" ) as flip: dat = flip.read() else: dat = "Class Dump result not Found" elif typ == "txt": file_format = "text" with io.open(sfile, mode="r", encoding="utf8", errors="ignore") as flip: dat = flip.read() else: if api: return {"error": "Invalid Parameters"} return HttpResponseRedirect("/error/") context = { "title": escape(ntpath.basename(fil)), "file": escape(ntpath.basename(fil)), "type": file_format, "dat": dat, "sql": sql_dump, "version": settings.MOBSF_VER, } template = "general/view.html" if api: return context return render(request, template, context) except Exception as exp: logger.exception("Error Viewing Source") msg = str(exp) exp = exp.__doc__ if api: return print_n_send_error_response(request, msg, True, exp) return print_n_send_error_response(request, msg, False, exp)
def run(request, api=False): """View iOS Files.""" try: logger.info("View iOS Source File") exp = "Error Description" file_format = None if api: fil = request.POST["file"] md5_hash = request.POST["hash"] mode = request.POST["type"] viewsource_form = ViewSourceIOSApiForm(request.POST) else: fil = request.GET["file"] md5_hash = request.GET["md5"] mode = request.GET["type"] viewsource_form = ViewSourceIOSForm(request.GET) typ = set_ext_api(fil) if not viewsource_form.is_valid(): err = FormUtil.errors_message(viewsource_form) if api: return err return print_n_send_error_response(request, err, False, exp) if mode == "ipa": src = os.path.join(settings.UPLD_DIR, md5_hash + "/Payload/") elif mode == "ios": src = os.path.join(settings.UPLD_DIR, md5_hash + "/") sfile = os.path.join(src, fil) if not is_safe_path(src, sfile): msg = "Path Traversal Detected!" if api: return {"error": "Path Traversal Detected!"} return print_n_send_error_response(request, msg, False, exp) dat = "" sql_dump = {} if typ == "m": file_format = "cpp" with io.open(sfile, mode="r", encoding="utf8", errors="ignore") as flip: dat = flip.read() elif typ == "xml": file_format = "xml" with io.open(sfile, mode="r", encoding="utf8", errors="ignore") as flip: dat = flip.read() elif typ == "plist": file_format = "json" dat = biplist.readPlist(sfile) try: dat = json.dumps(dat, indent=4, sort_keys=True) except Exception: pass elif typ == "db": file_format = "asciidoc" sql_dump = read_sqlite(sfile) elif typ == "txt" and fil == "classdump.txt": file_format = "cpp" app_dir = os.path.join(settings.UPLD_DIR, md5_hash + "/") cls_dump_file = os.path.join(app_dir, "classdump.txt") if is_file_exists(cls_dump_file): with io.open( cls_dump_file, mode="r", encoding="utf8", errors="ignore" ) as flip: dat = flip.read() else: dat = "Class Dump result not Found" elif typ == "txt": file_format = "text" with io.open(sfile, mode="r", encoding="utf8", errors="ignore") as flip: dat = flip.read() else: if api: return {"error": "Invalid Parameters"} return HttpResponseRedirect("/error/") context = { "title": escape(ntpath.basename(fil)), "file": escape(ntpath.basename(fil)), "type": file_format, "dat": dat, "sql": sql_dump, "version": settings.MOBSF_VER, } template = "general/view.html" if api: return context return render(request, template, context) except Exception as exp: logger.exception("Error Viewing Source") msg = str(exp) exp = exp.__doc__ if api: return print_n_send_error_response(request, msg, True, exp) return print_n_send_error_response(request, msg, False, exp)
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1542
[ERROR] 18/Sep/2020 16:56:43 - Reading from Info.plist Traceback (most recent call last): File "/root/Mobile-Security-Framework-MobSF/StaticAnalyzer/views/ios/plist_analysis.py", line 67, in plist_analysis dirs = os.listdir(src) FileNotFoundError: [Errno 2] No such file or directory: '/root/.MobSF/uploads/ab66d07fa05376c8bb931e981e9e470e/Payload/' [ERROR] 18/Sep/2020 16:56:43 - Error Perfroming Static Analysis Traceback (most recent call last): File "/root/Mobile-Security-Framework-MobSF/StaticAnalyzer/views/ios/static_analyzer.py", line 102, in static_analyzer_ios app_dict['appstore'] = app_search(infoplist_dict.get('id')) AttributeError: 'NoneType' object has no attribute 'get' [ERROR] 18/Sep/2020 16:56:43 - 'NoneType' object has no attribute 'get' [ERROR] 18/Sep/2020 16:56:43 - Internal Server Error: /StaticAnalyzer_iOS/
FileNotFoundError
def httptools_start(request): """Start httprools UI.""" logger.info("Starting httptools Web UI") try: stop_httptools(settings.PROXY_PORT) start_httptools_ui(settings.PROXY_PORT) time.sleep(3) logger.info("httptools UI started") if request.GET["project"]: project = request.GET["project"] else: project = "" url = "http://localhost:{}/dashboard/{}".format( str(settings.PROXY_PORT), project ) return HttpResponseRedirect(url) # lgtm [py/reflective-xss] except Exception: logger.exception("Starting httptools Web UI") err = "Error Starting httptools UI" return print_n_send_error_response(request, err)
def httptools_start(request): """Start httprools UI.""" logger.info("Starting httptools Web UI") try: stop_httptools(settings.PROXY_PORT) start_httptools_ui(settings.PROXY_PORT) time.sleep(3) logger.info("httptools UI started") if request.GET["project"]: project = request.GET["project"] else: project = "" url = "http://localhost:{}/dashboard/{}".format( str(settings.PROXY_PORT), project ) return HttpResponseRedirect(url) except Exception: logger.exception("Starting httptools Web UI") err = "Error Starting httptools UI" return print_n_send_error_response(request, err)
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1352
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"
FileNotFoundError
def configure_proxy(self, project): """HTTPS Proxy.""" self.install_mobsf_ca("install") proxy_port = settings.PROXY_PORT logger.info("Starting HTTPs Proxy on %s", proxy_port) stop_httptools(proxy_port) start_proxy(proxy_port, project)
def configure_proxy(self, project): """HTTPS Proxy.""" proxy_port = settings.PROXY_PORT logger.info("Starting HTTPs Proxy on %s", proxy_port) stop_httptools(proxy_port) start_proxy(proxy_port, project)
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1352
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"
FileNotFoundError
def install_mobsf_ca(self, action): """Install or Remove MobSF Root CA.""" mobsf_ca = get_ca_file() ca_file = None if is_file_exists(mobsf_ca): ca_construct = "{}.0" pem = open(mobsf_ca, "rb").read() ca_obj = crypto.load_certificate(crypto.FILETYPE_PEM, pem) ca_file_hash = hex(ca_obj.subject_name_hash()).lstrip("0x") ca_file = os.path.join( "/system/etc/security/cacerts/", ca_construct.format(ca_file_hash) ) else: logger.warning("mitmproxy root CA is not generated yet.") return if action == "install": logger.info("Installing MobSF RootCA") self.adb_command(["push", mobsf_ca, ca_file]) self.adb_command(["chmod", "644", ca_file], True) elif action == "remove": logger.info("Removing MobSF RootCA") self.adb_command(["rm", ca_file], True)
def install_mobsf_ca(self, action): """Install or Remove MobSF Root CA.""" ca_construct = "{}.0" pem = open(get_ca_dir(), "rb").read() ca_file = crypto.load_certificate(crypto.FILETYPE_PEM, pem) ca_file_hash = hex(ca_file.subject_name_hash()).lstrip("0x") ca_file = os.path.join( "/system/etc/security/cacerts/", ca_construct.format(ca_file_hash) ) if action == "install": logger.info("Installing MobSF RootCA") self.adb_command(["push", get_ca_dir(), ca_file]) self.adb_command(["chmod", "644", ca_file], True) elif action == "remove": logger.info("Removing MobSF RootCA") self.adb_command(["rm", ca_file], True)
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1352
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"
FileNotFoundError
def get_embedded_classes(self): """ Get the list of Java classes from all DEX files. :return: list of Java classes """ if self.classes is not None: return self.classes for dex_file in glob.iglob(os.path.join(self.apk_dir, "*.dex")): if len(settings.BACKSMALI_BINARY) > 0 and is_file_exists( settings.BACKSMALI_BINARY ): bs_path = settings.BACKSMALI_BINARY else: bs_path = os.path.join(self.tools_dir, "baksmali-2.4.0.jar") args = [find_java_binary(), "-jar", bs_path, "list", "classes", dex_file] classes = subprocess.check_output(args, universal_newlines=True).splitlines() if self.classes is not None: self.classes = self.classes + classes else: self.classes = classes return self.classes
def get_embedded_classes(self): """ Get the list of Java classes from all DEX files. :return: list of Java classes """ if self.classes is not None: return self.classes for dex_file in glob.iglob(os.path.join(self.apk_dir, "*.dex")): if len(settings.BACKSMALI_BINARY) > 0 and is_file_exists( settings.BACKSMALI_BINARY ): bs_path = settings.BACKSMALI_BINARY else: bs_path = os.path.join(self.tools_dir, "baksmali-2.4.0.jar") args = [settings.JAVA_BINARY, "-jar", bs_path, "list", "classes", dex_file] classes = subprocess.check_output(args, universal_newlines=True).splitlines() if self.classes is not None: self.classes = self.classes + classes else: self.classes = classes return self.classes
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1352
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"
FileNotFoundError
def is_internet_available(): try: proxies, verify = upstream_proxy("https") except Exception: logger.exception("Setting upstream proxy") try: requests.get(settings.GOOGLE, timeout=5, proxies=proxies, verify=verify) return True except Exception: try: requests.get(settings.BAIDU, timeout=5, proxies=proxies, verify=verify) return True except Exception: return False
def is_internet_available(): try: proxies, verify = upstream_proxy("https") except Exception: logger.exception("Setting upstream proxy") try: requests.get(settings.GOOGLE, timeout=5, proxies=proxies, verify=verify) return True except Exception: try: requests.get(settings.BAIDU, timeout=5, proxies=proxies, verify=verify) return True except Exception: return False return False
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1352
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"
FileNotFoundError
def check_basic_env(): """Check if we have basic env for MobSF to run.""" logger.info("MobSF Basic Environment Check") try: import http_tools # noqa F401 except ImportError: logger.exception("httptools not installed!") os.kill(os.getpid(), signal.SIGTERM) try: import lxml # noqa F401 except ImportError: logger.exception("lxml is not installed!") os.kill(os.getpid(), signal.SIGTERM) if not is_file_exists(find_java_binary()): logger.error( "JDK 8+ is not available. " "Set JAVA_HOME environment variable" " or JAVA_DIRECTORY in MobSF/settings.py" ) logger.info("Current Configuration: JAVA_DIRECTORY=%s", settings.JAVA_DIRECTORY) logger.info( "Example Configuration:" '\nJAVA_DIRECTORY = "C:/Program Files/' 'Java/jdk1.7.0_17/bin/"' '\nJAVA_DIRECTORY = "/usr/bin/"' ) os.kill(os.getpid(), signal.SIGTERM) get_adb()
def check_basic_env(): """Check if we have basic env for MobSF to run.""" logger.info("MobSF Basic Environment Check") try: import http_tools # noqa F401 except ImportError: logger.exception("httptools not installed!") os.kill(os.getpid(), signal.SIGTERM) try: import lxml # noqa F401 except ImportError: logger.exception("lxml is not installed!") os.kill(os.getpid(), signal.SIGTERM) if not is_file_exists(settings.JAVA_BINARY): logger.error( "JDK 8+ is not available. " "Set JAVA_HOME environment variable" " or JAVA_DIRECTORY in MobSF/settings.py" ) logger.info("Current Configuration: JAVA_DIRECTORY=%s", settings.JAVA_DIRECTORY) logger.info( "Example Configuration:" '\nJAVA_DIRECTORY = "C:/Program Files/' 'Java/jdk1.7.0_17/bin/"' '\nJAVA_DIRECTORY = "/usr/bin/"' ) os.kill(os.getpid(), signal.SIGTERM) get_adb()
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1352
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"
FileNotFoundError
def check_elf_built(f): has_pi = False has_sp = False has_pi_fg = { 3: [8], # EM_386=3, R_386_RELATIVE=8, 62: [8], # EM_X86_64=62, R_X86_64_RELATIVE=8, 40: [23, 3], # EM_ARM=40, R_ARM_RELATIVE=23,R_ARM_REL32=3, 183: [1027, 3], # EM_AARCH64=183, # R_AARCH64_RELATIVE=1027,R_ARM_REL32=3, 8: [3], # EM_MIPS=8, R_MIPS_REL32=3, } elffile = TinyELFFile(f) for j in range(elffile.header["e_shnum"]): section_header = elffile.decode_shdr( elffile.header["e_shoff"] + j * elffile.header["e_shentsize"] ) sectype = section_header["sh_type"] if sectype in (4, 9): # SHT_RELA=4,SHT_REL=9, if section_header["sh_entsize"] > 0: siz = section_header["sh_size"] // section_header["sh_entsize"] for i in range(siz): elffile.stream.seek( section_header["sh_offset"] + i * section_header["sh_entsize"] ) if section_header["sh_type"] == 9: entry = elffile.decode_rel( section_header["sh_offset"] + i * section_header["sh_entsize"] ) elif section_header["sh_type"] == 4: entry = elffile.decode_rela( section_header["sh_offset"] + i * section_header["sh_entsize"] ) else: continue if entry["r_info_type"] in has_pi_fg.get( elffile.header["e_machine"], [] ): if entry["r_info_sym"] == 0: has_pi = True break return has_pi, has_sp
def check_elf_built(f): has_pi = False has_sp = False has_pi_fg = { 3: [8], # EM_386=3, R_386_RELATIVE=8, 62: [8], # EM_X86_64=62, R_X86_64_RELATIVE=8, 40: [23, 3], # EM_ARM=40, R_ARM_RELATIVE=23,R_ARM_REL32=3, 183: [1027, 3], # EM_AARCH64=183, # R_AARCH64_RELATIVE=1027,R_ARM_REL32=3, 8: [3], # EM_MIPS=8, R_MIPS_REL32=3, } elffile = TinyELFFile(f) for i in range(elffile.header["e_shnum"]): section_header = elffile.decode_shdr( elffile.header["e_shoff"] + i * elffile.header["e_shentsize"] ) sectype = section_header["sh_type"] if sectype in (4, 9): # SHT_RELA=4,SHT_REL=9, if section_header["sh_entsize"] > 0: siz = section_header["sh_size"] // section_header["sh_entsize"] for i in range(siz): elffile.stream.seek( section_header["sh_offset"] + i * section_header["sh_entsize"] ) if section_header["sh_type"] == 9: entry = elffile.decode_rel( section_header["sh_offset"] + i * section_header["sh_entsize"] ) elif section_header["sh_type"] == 4: entry = elffile.decode_rela( section_header["sh_offset"] + i * section_header["sh_entsize"] ) else: continue if entry["r_info_type"] in has_pi_fg.get( elffile.header["e_machine"], [] ): if entry["r_info_sym"] == 0: has_pi = True break return has_pi, has_sp
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1352
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"
FileNotFoundError
def dex_2_smali(app_dir, tools_dir): """Run dex2smali.""" try: logger.info("DEX -> SMALI") dexes = get_dex_files(app_dir) for dex_path in dexes: logger.info("Converting %s to Smali Code", filename_from_path(dex_path)) if len(settings.BACKSMALI_BINARY) > 0 and is_file_exists( settings.BACKSMALI_BINARY ): bs_path = settings.BACKSMALI_BINARY else: bs_path = os.path.join(tools_dir, "baksmali-2.4.0.jar") output = os.path.join(app_dir, "smali_source/") smali = [ find_java_binary(), "-jar", bs_path, "d", dex_path, "-o", output, ] trd = threading.Thread(target=subprocess.call, args=(smali,)) trd.daemon = True trd.start() except Exception: logger.exception("Converting DEX to SMALI")
def dex_2_smali(app_dir, tools_dir): """Run dex2smali.""" try: logger.info("DEX -> SMALI") dexes = get_dex_files(app_dir) for dex_path in dexes: logger.info("Converting %s to Smali Code", filename_from_path(dex_path)) if len(settings.BACKSMALI_BINARY) > 0 and is_file_exists( settings.BACKSMALI_BINARY ): bs_path = settings.BACKSMALI_BINARY else: bs_path = os.path.join(tools_dir, "baksmali-2.4.0.jar") output = os.path.join(app_dir, "smali_source/") smali = [ settings.JAVA_BINARY, "-jar", bs_path, "d", dex_path, "-o", output, ] trd = threading.Thread(target=subprocess.call, args=(smali,)) trd.daemon = True trd.start() except Exception: logger.exception("Converting DEX to SMALI")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1352
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"
FileNotFoundError
def apk_2_java(app_path, app_dir, tools_dir): """Run jadx.""" try: logger.info("APK -> JAVA") args = [] output = os.path.join(app_dir, "java_source/") logger.info("Decompiling to Java with jadx") if os.path.exists(output): shutil.rmtree(output) if len(settings.JADX_BINARY) > 0 and is_file_exists(settings.JADX_BINARY): jadx = settings.JADX_BINARY elif platform.system() == "Windows": jadx = os.path.join(tools_dir, "jadx/bin/jadx.bat") else: jadx = os.path.join(tools_dir, "jadx/bin/jadx") # Set execute permission, if JADX is not executable if not os.access(jadx, os.X_OK): os.chmod(jadx, stat.S_IEXEC) args = [ jadx, "-ds", output, "-q", "-r", "--show-bad-code", app_path, ] fnull = open(os.devnull, "w") subprocess.call(args, stdout=fnull, stderr=subprocess.STDOUT) except Exception: logger.exception("Decompiling to JAVA")
def apk_2_java(app_path, app_dir, tools_dir): """Run jadx.""" try: logger.info("APK -> JAVA") args = [] output = os.path.join(app_dir, "java_source/") logger.info("Decompiling to Java with jadx") if os.path.exists(output): shutil.rmtree(output) if len(settings.JADX_BINARY) > 0 and is_file_exists(settings.JADX_BINARY): jadx = settings.JADX_BINARY else: if platform.system() == "Windows": jadx = os.path.join(tools_dir, "jadx/bin/jadx.bat") else: jadx = os.path.join(tools_dir, "jadx/bin/jadx") # Set write permission, if JADX is not executable if not os.access(jadx, os.X_OK): os.chmod(jadx, stat.S_IEXEC) args = [ jadx, "-ds", output, "-q", "-r", "--show-bad-code", app_path, ] fnull = open(os.devnull, "w") subprocess.call(args, stdout=fnull, stderr=subprocess.STDOUT) except Exception: logger.exception("Decompiling to JAVA")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1352
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"
FileNotFoundError
def get_manifest_file(app_path, app_dir, tools_dir): """Get readable AndroidManifest.xml.""" try: manifest = None if len(settings.APKTOOL_BINARY) > 0 and is_file_exists(settings.APKTOOL_BINARY): apktool_path = settings.APKTOOL_BINARY else: apktool_path = os.path.join(tools_dir, "apktool_2.4.1.jar") output_dir = os.path.join(app_dir, "apktool_out") args = [ find_java_binary(), "-jar", apktool_path, "--match-original", "--frame-path", tempfile.gettempdir(), "-f", "-s", "d", app_path, "-o", output_dir, ] manifest = os.path.join(output_dir, "AndroidManifest.xml") if is_file_exists(manifest): # APKTool already created readable XML return manifest logger.info("Converting AXML to XML") subprocess.check_output(args) return manifest except Exception: logger.exception("Getting Manifest file")
def get_manifest_file(app_path, app_dir, tools_dir): """Get readable AndroidManifest.xml.""" try: manifest = None if len(settings.APKTOOL_BINARY) > 0 and is_file_exists(settings.APKTOOL_BINARY): apktool_path = settings.APKTOOL_BINARY else: apktool_path = os.path.join(tools_dir, "apktool_2.4.1.jar") output_dir = os.path.join(app_dir, "apktool_out") args = [ settings.JAVA_BINARY, "-jar", apktool_path, "--match-original", "--frame-path", tempfile.gettempdir(), "-f", "-s", "d", app_path, "-o", output_dir, ] manifest = os.path.join(output_dir, "AndroidManifest.xml") if is_file_exists(manifest): # APKTool already created readable XML return manifest logger.info("Converting AXML to XML") subprocess.check_output(args) return manifest except Exception: logger.exception("Getting Manifest file")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1352
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"
FileNotFoundError
def valid_android_zip(app_dir): """Test if this is an valid android zip.""" try: logger.info("Checking for ZIP Validity and Mode") # Eclipse man = os.path.isfile(os.path.join(app_dir, "AndroidManifest.xml")) src = os.path.exists(os.path.join(app_dir, "src/")) if man and src: return "eclipse", True # Studio man = os.path.isfile( os.path.join(app_dir, "app/src/main/AndroidManifest.xml"), ) src = os.path.exists(os.path.join(app_dir, "app/src/main/java/")) if man and src: return "studio", True # iOS Source xcode = [f for f in os.listdir(app_dir) if f.endswith(".xcodeproj")] if xcode: return "ios", True # Relaxed iOS Source Check for x in os.listdir(app_dir): obj = os.path.join(app_dir, x) if not is_dir_exists(obj): continue if [f for f in os.listdir(obj) if f.endswith(".xcodeproj")]: return "ios", True return "", False except Exception: logger.exception("Determining Upload type")
def valid_android_zip(app_dir): """Test if this is an valid android zip.""" try: logger.info("Checking for ZIP Validity and Mode") # Eclipse man = os.path.isfile(os.path.join(app_dir, "AndroidManifest.xml")) src = os.path.exists(os.path.join(app_dir, "src/")) if man and src: return "eclipse", True # Studio man = os.path.isfile( os.path.join(app_dir, "app/src/main/AndroidManifest.xml"), ) src = os.path.exists(os.path.join(app_dir, "app/src/main/java/")) if man and src: return "studio", True # iOS Source xcode = [f for f in os.listdir(app_dir) if f.endswith(".xcodeproj")] if xcode: return "ios", True return "", False except Exception: logger.exception("Determining Upload type")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1352
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"
FileNotFoundError
def win_fix_java(tools_dir): """Run JAVA path fix in Windows.""" try: logger.info("Running JAVA path fix in Windows") dmy = os.path.join(tools_dir, "d2j2/d2j_invoke.tmp") org = os.path.join(tools_dir, "d2j2/d2j_invoke.bat") dat = "" with open(dmy, "r") as file_pointer: dat = file_pointer.read().replace("[xxx]", find_java_binary()) with open(org, "w") as file_pointer: file_pointer.write(dat) except Exception: logger.exception("Running JAVA path fix in Windows")
def win_fix_java(tools_dir): """Run JAVA path fix in Windows.""" try: logger.info("Running JAVA path fix in Windows") dmy = os.path.join(tools_dir, "d2j2/d2j_invoke.tmp") org = os.path.join(tools_dir, "d2j2/d2j_invoke.bat") dat = "" with open(dmy, "r") as file_pointer: dat = file_pointer.read().replace("[xxx]", settings.JAVA_BINARY) with open(org, "w") as file_pointer: file_pointer.write(dat) except Exception: logger.exception("Running JAVA path fix in Windows")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1352
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"
FileNotFoundError
def check_transport_security(p_list): """Check info.plist for insecure connection configurations.""" logger.info("Checking for Insecure Connections") ats = [] if "NSAppTransportSecurity" in p_list: ats_dict = p_list["NSAppTransportSecurity"] if ats_dict.get("NSAllowsArbitraryLoads"): ats.append( { "issue": ("App Transport Security AllowsArbitraryLoads is allowed"), "status": "insecure", "description": ( "App Transport Security restrictions are disabled " "for all network connections. Disabling ATS means that " "unsecured HTTP connections are allowed. HTTPS " "connections are also allowed, and are still subject " "to default server trust evaluation. However, " "extended security checks like requiring a minimum " "Transport Layer Security (TLS) protocol version—are " "disabled. This setting is not applicable to domains " "listed in NSExceptionDomains." ), } ) if ats_dict.get("NSAllowsArbitraryLoadsForMedia"): ats.append( { "issue": "Insecure media load is allowed", "status": "insecure", "description": ( "App Transport Security restrictions are disabled for " "media loaded using the AVFoundation framework, " "without affecting your URLSession connections. " "This setting is not applicable to domains " "listed in NSExceptionDomains." ), } ) if ats_dict.get("NSAllowsArbitraryLoadsInWebContent"): ats.append( { "issue": "Insecure WebView load is allowed", "status": "insecure", "description": ( "App Transport Security restrictions are disabled for " "requests made from WebViews without affecting your " "URLSession connections. This setting is not applicable " "to domains listed in NSExceptionDomains." ), } ) if ats_dict.get("NSAllowsLocalNetworking"): ats.append( { "issue": "Insecure local networking is allowed", "status": "insecure", "description": ( "App Transport Security restrictions are disabled for " "requests made from local networking " "without affecting your " "URLSession connections. This setting is not applicable " "to domains listed in NSExceptionDomains." ), } ) # NS Domain Exceptions exception_domains = ats_dict.get("NSExceptionDomains") if exception_domains: ats.append( { "issue": "NSExceptionDomains", "status": "info", "description": ", ".join(exception_domains.keys()), } ) for domain, config in exception_domains.items(): if not isinstance(config, dict): continue old_exp = "NSTemporaryExceptionAllowsInsecureHTTPLoads" old_exp2 = "NSThirdPartyExceptionAllowsInsecureHTTPLoads" if ( config.get("NSExceptionAllowsInsecureHTTPLoads", False) or config.get(old_exp, False) or config.get(old_exp2, False) ): findings = { "issue": ( "Insecure communication to {} is allowed".format(domain) ), "status": "insecure", "description": ( "NSExceptionAllowsInsecureHTTPLoads allows " "insecure HTTP loads to {}, " "or to be able to loosen the " "server trust evaluation " "requirements for HTTPS " "connections to the domain.".format(domain) ), } ats.append(findings) if config.get("NSIncludesSubdomains", False): findings = { "issue": ( "NSIncludesSubdomains set to TRUE for {}".format(domain) ), "status": "insecure", "description": ( "NSIncludesSubdomains applies the ATS exceptions " "for the given domain to all " "subdomains as well. " "For example, the ATS exceptions in the " "domain exception dictionary apply to {}, " "as well as math.{}, history.{}, and so on. " "Otherwise, if the value is NO, the exceptions " "apply only to " "{}.".format(domain, domain, domain, domain) ), } ats.append(findings) old_tls = "NSTemporaryExceptionMinimumTLSVersion" inc_min_tls = config.get( "NSExceptionMinimumTLSVersion", None ) or config.get(old_tls, None) if inc_min_tls in ["TLSv1.0", "TLSv1.1"]: findings = { "issue": ( "NSExceptionMinimumTLSVersion set to {} on {}".format( inc_min_tls, domain ) ), "status": "insecure", "description": ( "The minimum Transport Layer " "Security (TLS) version " "for network connections sent to {} " "is set to {}. This version is deemed " "to be insecure".format(domain, inc_min_tls) ), } ats.append(findings) elif inc_min_tls == "TLSv1.2": findings = { "issue": ( "NSExceptionMinimumTLSVersion set to {} on {}".format( inc_min_tls, domain ) ), "status": "warning", "description": ( "The minimum Transport Layer " "Security (TLS) version " "for network connections sent to {} " "is set to {}. " "This version is vulnerable to " "attacks such as POODLE, FREAK, " "or CurveSwap etc.".format(domain, inc_min_tls) ), } ats.append(findings) elif inc_min_tls == "TLSv1.3": findings = { "issue": ( "NSExceptionMinimumTLSVersion set to {} on {}".format( inc_min_tls, domain ) ), "status": "secure", "description": ( "The minimum Transport Layer " "Security (TLS) version " "for network connections sent to {} " "is set to {}.".format(domain, inc_min_tls) ), } ats.append(findings) elif inc_min_tls is None: pass else: findings = { "issue": ( "NSExceptionMinimumTLSVersion set to {} on {}".format( inc_min_tls, domain ) ), "status": "info", "description": ( "The minimum Transport Layer " "Security (TLS) version " "for network connections sent to {} " "is set to {}.".format(domain, inc_min_tls) ), } ats.append(findings) old_fwd = "NSTemporaryExceptionRequiresForwardSecrecy" old_fwd2 = "NSThirdPartyExceptionRequiresForwardSecrecy" if not ( config.get("NSExceptionRequiresForwardSecrecy", False) or config.get(old_fwd, False) or config.get(old_fwd2, False) ): findings = { "issue": ( "NSExceptionRequiresForwardSecrecy set to NO for {}".format( domain ) ), "status": "insecure", "description": ( "NSExceptionRequiresForwardSecrecy " "limits the accepted ciphers to " "those that support perfect " "forward secrecy (PFS) through the " "Elliptic Curve Diffie-Hellman " "Ephemeral (ECDHE) key exchange. " "Set the value for this key to NO to override " "the requirement that a server must support " "PFS for the given domain. This key is optional. " "The default value is YES, which limits the " "accepted ciphers to those that support " "PFS through Elliptic Curve Diffie-Hellman " "Ephemeral (ECDHE) key exchange." ), } ats.append(findings) if config.get("NSRequiresCertificateTransparency", False): findings = { "issue": ( "NSRequiresCertificateTransparency" " set to YES for {}".format(domain) ), "status": "secure", "description": ( "Certificate Transparency (CT) is a protocol " "that ATS can use to identify " "mistakenly or maliciously " "issued X.509 certificates. " "Set the value for the " "NSRequiresCertificateTransparency " "key to YES to require that for a given domain, " "server certificates are supported by valid, " "signed CT timestamps from at least " "two CT logs trusted by Apple. " "This key is optional. The default value is NO." ), } ats.append(findings) return ats
def check_transport_security(p_list): """Check info.plist for insecure connection configurations.""" logger.info("Checking for Insecure Connections") ats = [] if "NSAppTransportSecurity" in p_list: ats_dict = p_list["NSAppTransportSecurity"] if ats_dict.get("NSAllowsArbitraryLoads"): ats.append( { "issue": ("App Transport Security AllowsArbitraryLoads is allowed"), "status": "insecure", "description": ( "App Transport Security restrictions are disabled " "for all network connections. Disabling ATS means that " "unsecured HTTP connections are allowed. HTTPS " "connections are also allowed, and are still subject " "to default server trust evaluation. However, " "extended security checks like requiring a minimum " "Transport Layer Security (TLS) protocol version—are " "disabled. This setting is not applicable to domains " "listed in NSExceptionDomains." ), } ) if ats_dict.get("NSAllowsArbitraryLoadsForMedia"): ats.append( { "issue": "Insecure media load is allowed", "status": "insecure", "description": ( "App Transport Security restrictions are disabled for " "media loaded using the AVFoundation framework, " "without affecting your URLSession connections. " "This setting is not applicable to domains " "listed in NSExceptionDomains." ), } ) if ats_dict.get("NSAllowsArbitraryLoadsInWebContent"): ats.append( { "issue": "Insecure WebView load is allowed", "status": "insecure", "description": ( "App Transport Security restrictions are disabled for " "requests made from WebViews without affecting your " "URLSession connections. This setting is not applicable " "to domains listed in NSExceptionDomains." ), } ) if ats_dict.get("NSAllowsLocalNetworking"): ats.append( { "issue": "Insecure local networking is allowed", "status": "insecure", "description": ( "App Transport Security restrictions are disabled for " "requests made from local networking " "without affecting your " "URLSession connections. This setting is not applicable " "to domains listed in NSExceptionDomains." ), } ) # NS Domain Exceptions exception_domains = ats_dict.get("NSExceptionDomains") if exception_domains: ats.append( { "issue": "NSExceptionDomains", "status": "info", "description": ", ".join(exception_domains.keys()), } ) for domain, config in exception_domains.items(): if not isinstance(config, dict): continue old_exp = "NSTemporaryExceptionAllowsInsecureHTTPLoads" if config.get( "NSExceptionAllowsInsecureHTTPLoads", False ) or config.get(old_exp, False): findings = { "issue": ( "Insecure communication to {} is allowed".format(domain) ), "status": "insecure", "description": ( "NSExceptionAllowsInsecureHTTPLoads allows " "insecure HTTP loads to {}, " "or to be able to loosen the " "server trust evaluation " "requirements for HTTPS " "connections to the domain.".format(domain) ), } ats.append(findings) if config.get("NSIncludesSubdomains", False): findings = { "issue": ( "NSIncludesSubdomains set to TRUE for {}".format(domain) ), "status": "insecure", "description": ( "NSIncludesSubdomains applies the ATS exceptions " "for the given domain to all " "subdomains as well. " "For example, the ATS exceptions in the " "domain exception dictionary apply to {}, " "as well as math.{}, history.{}, and so on. " "Otherwise, if the value is NO, the exceptions " "apply only to " "{}.".format(domain, domain, domain, domain) ), } ats.append(findings) old_tls = "NSTemporaryExceptionMinimumTLSVersion" inc_min_tls = config.get( "NSExceptionMinimumTLSVersion", None ) or config.get(old_tls, None) if inc_min_tls in ["TLSv1.0", "TLSv1.1"]: findings = { "issue": ( "NSExceptionMinimumTLSVersion set to {} on {}".format( inc_min_tls, domain ) ), "status": "insecure", "description": ( "The minimum Transport Layer " "Security (TLS) version " "for network connections sent to {} " "is set to {}. This version is deemed " "to be insecure".format(domain, inc_min_tls) ), } ats.append(findings) elif inc_min_tls == "TLSv1.2": findings = { "issue": ( "NSExceptionMinimumTLSVersion set to {} on {}".format( inc_min_tls, domain ) ), "status": "warning", "description": ( "The minimum Transport Layer " "Security (TLS) version " "for network connections sent to {} " "is set to {}. " "This version is vulnerable to " "attacks such as POODLE, FREAK, " "or CurveSwap etc.".format(domain, inc_min_tls) ), } ats.append(findings) elif inc_min_tls == "TLSv1.3": findings = { "issue": ( "NSExceptionMinimumTLSVersion set to {} on {}".format( inc_min_tls, domain ) ), "status": "secure", "description": ( "The minimum Transport Layer " "Security (TLS) version " "for network connections sent to {} " "is set to {}.".format(domain, inc_min_tls) ), } ats.append(findings) elif inc_min_tls is None: pass else: findings = { "issue": ( "NSExceptionMinimumTLSVersion set to {} on {}".format( inc_min_tls, domain ) ), "status": "info", "description": ( "The minimum Transport Layer " "Security (TLS) version " "for network connections sent to {} " "is set to {}.".format(domain, inc_min_tls) ), } ats.append(findings) old_fwd = "NSTemporaryExceptionRequiresForwardSecrecy" if config.get("NSExceptionRequiresForwardSecrecy", False) or config.get( old_fwd, False ): findings = { "issue": ( "NSExceptionRequiresForwardSecrecy " "set to YES" " for {}".format(domain) ), "status": "secure", "description": ( "NSExceptionRequiresForwardSecrecy " "limits the accepted ciphers to " "those that support perfect " "forward secrecy (PFS) through the " "Elliptic Curve Diffie-Hellman " "Ephemeral (ECDHE) key exchange. " "Set the value for this key to NO to override " "the requirement that a server must support " "PFS for the given domain. This key is optional. " "The default value is YES, which limits the " "accepted ciphers to those that support " "PFS through Elliptic Curve Diffie-Hellman " "Ephemeral (ECDHE) key exchange." ), } ats.append(findings) if config.get("NSRequiresCertificateTransparency", False): findings = { "issue": ( "NSRequiresCertificateTransparency" " set to YES for {}".format(domain) ), "status": "secure", "description": ( "Certificate Transparency (CT) is a protocol " "that ATS can use to identify " "mistakenly or maliciously " "issued X.509 certificates. " "Set the value for the " "NSRequiresCertificateTransparency " "key to YES to require that for a given domain, " "server certificates are supported by valid, " "signed CT timestamps from at least " "two CT logs trusted by Apple. " "This key is optional. The default value is NO." ), } ats.append(findings) return ats
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1352
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"
FileNotFoundError
def get_otool_out(tools_dir, cmd_type, bin_path, bin_dir): """Get otool args by OS and type.""" if len(settings.OTOOL_BINARY) > 0 and is_file_exists(settings.OTOOL_BINARY): otool_bin = settings.OTOOL_BINARY else: otool_bin = "otool" if len(settings.JTOOL_BINARY) > 0 and is_file_exists(settings.JTOOL_BINARY): jtool_bin = settings.JTOOL_BINARY else: jtool_bin = os.path.join(tools_dir, "jtool.ELF64") jtool2_bin = os.path.join(tools_dir, "jtool2.ELF64") # jtool execute permission check for toolbin in [jtool_bin, jtool2_bin]: if not os.access(toolbin, os.X_OK): os.chmod(toolbin, stat.S_IEXEC) plat = platform.system() if cmd_type == "libs": if plat == "Darwin": args = [otool_bin, "-L", bin_path] args2 = args elif plat == "Linux": args = [jtool_bin, "-arch", "arm", "-L", "-v", bin_path] args2 = [jtool2_bin, "-L", "-v", "-q", bin_path] else: # Platform Not Supported return None try: libs = subprocess.check_output(args2).decode("utf-8", "ignore") except Exception: libs = subprocess.check_output(args).decode("utf-8", "ignore") libs = smart_text(escape(libs.replace(bin_dir + "/", ""))) return libs.split("\n") elif cmd_type == "header": if plat == "Darwin": args = [otool_bin, "-hv", bin_path] args2 = args elif plat == "Linux": args = [jtool_bin, "-arch", "arm", "-h", "-v", bin_path] args2 = [jtool2_bin, "-h", "-v", "-q", bin_path] else: # Platform Not Supported return None try: return subprocess.check_output(args2) except Exception: return subprocess.check_output(args) elif cmd_type == "symbols": if plat == "Darwin": args = [otool_bin, "-Iv", bin_path] return subprocess.check_output(args) elif plat == "Linux": args = [jtool_bin, "-arch", "arm", "-S", bin_path] arg2 = [jtool2_bin, "-S", bin_path] try: with open(os.devnull, "w") as devnull: return subprocess.check_output(arg2, stderr=devnull) except Exception: return subprocess.check_output(args) else: # Platform Not Supported return None elif cmd_type == "classdump": # Handle Classdump in Linux # Add timeout to handle ULEB128 malformed return [jtool_bin, "-arch", "arm", "-d", "objc", "-v", bin_path] return None
def get_otool_out(tools_dir, cmd_type, bin_path, bin_dir): """Get otool args by OS and type.""" if len(settings.OTOOL_BINARY) > 0 and is_file_exists(settings.OTOOL_BINARY): otool_bin = settings.OTOOL_BINARY else: otool_bin = "otool" if len(settings.JTOOL_BINARY) > 0 and is_file_exists(settings.JTOOL_BINARY): jtool_bin = settings.JTOOL_BINARY else: jtool_bin = os.path.join(tools_dir, "jtool.ELF64") jtool2_bin = os.path.join(tools_dir, "jtool2.ELF64") # jtool execute permission check for toolbin in [jtool_bin, jtool2_bin]: if not os.access(toolbin, os.X_OK): os.chmod(toolbin, stat.S_IEXEC) plat = platform.system() if cmd_type == "libs": if plat == "Darwin": args = [otool_bin, "-L", bin_path] args2 = args elif plat == "Linux": args = [jtool_bin, "-arch", "arm", "-L", "-v", bin_path] args2 = [jtool2_bin, "-L", "-v", "-q", bin_path] else: # Platform Not Supported return None try: libs = subprocess.check_output(args2).decode("utf-8", "ignore") except Exception: libs = subprocess.check_output(args).decode("utf-8", "ignore") libs = smart_text(escape(libs.replace(bin_dir + "/", ""))) return libs.split("\n") elif cmd_type == "header": if plat == "Darwin": args = [otool_bin, "-hv", bin_path] args2 = args elif plat == "Linux": args = [jtool_bin, "-arch", "arm", "-h", "-v", bin_path] args2 = [jtool2_bin, "-h", "-v", "-q", bin_path] else: # Platform Not Supported return None try: return subprocess.check_output(args2) except Exception: return subprocess.check_output(args) elif cmd_type == "symbols": if plat == "Darwin": args = [otool_bin, "-Iv", bin_path] args2 = args return subprocess.check_output(args) elif plat == "Linux": args = [jtool_bin, "-arch", "arm", "-S", bin_path] arg2 = [jtool2_bin, "-S", bin_path] try: with open(os.devnull, "w") as devnull: return subprocess.check_output(arg2, stderr=devnull) except Exception: return subprocess.check_output(args) else: # Platform Not Supported return None elif cmd_type == "classdump": # Handle Classdump in Linux # Add timeout to handle ULEB128 malformed return [jtool_bin, "-arch", "arm", "-d", "objc", "-v", bin_path] return None
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1352
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"
FileNotFoundError
def convert_bin_xml(bin_xml_file): """Convert Binary XML to Readable XML.""" try: plist_obj = readPlist(bin_xml_file) data = writePlistToString(plist_obj) return data except InvalidPlistException: logger.warning("Failed to convert plist")
def convert_bin_xml(bin_xml_file): """Convert Binary XML to Readable XML.""" try: plist_obj = readPlist(bin_xml_file) data = writePlistToString(plist_obj) return data except biplist.InvalidPlistException: logger.warning("Failed to convert plist")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1352
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"
FileNotFoundError
def run(request, api=False): """View iOS Files.""" try: logger.info("View iOS Source File") exp = "Error Description" file_format = None if api: fil = request.POST["file"] md5_hash = request.POST["hash"] mode = request.POST["type"] viewsource_form = ViewSourceIOSApiForm(request.POST) else: fil = request.GET["file"] md5_hash = request.GET["md5"] mode = request.GET["type"] viewsource_form = ViewSourceIOSForm(request.GET) typ = set_ext_api(fil) if not viewsource_form.is_valid(): err = FormUtil.errors_message(viewsource_form) if api: return err return print_n_send_error_response(request, err, False, exp) if mode == "ipa": src = os.path.join(settings.UPLD_DIR, md5_hash + "/Payload/") elif mode == "ios": src = os.path.join(settings.UPLD_DIR, md5_hash + "/") sfile = os.path.join(src, fil) if not is_safe_path(src, sfile): msg = "Path Traversal Detected!" if api: return {"error": "Path Traversal Detected!"} return print_n_send_error_response(request, msg, False, exp) dat = "" sql_dump = {} if typ == "m": file_format = "cpp" with io.open(sfile, mode="r", encoding="utf8", errors="ignore") as flip: dat = flip.read() elif typ == "xml": file_format = "xml" with io.open(sfile, mode="r", encoding="utf8", errors="ignore") as flip: dat = flip.read() elif typ == "plist": file_format = "json" dat = biplist.readPlist(sfile) try: dat = json.dumps(dat, indent=4, sort_keys=True) except Exception: pass elif typ == "db": file_format = "asciidoc" sql_dump = read_sqlite(sfile) elif typ == "txt" and fil == "classdump.txt": file_format = "cpp" app_dir = os.path.join(settings.UPLD_DIR, md5_hash + "/") cls_dump_file = os.path.join(app_dir, "classdump.txt") if is_file_exists(cls_dump_file): with io.open( cls_dump_file, mode="r", encoding="utf8", errors="ignore" ) as flip: dat = flip.read() else: dat = "Class Dump result not Found" elif typ == "txt": file_format = "text" with io.open(sfile, mode="r", encoding="utf8", errors="ignore") as flip: dat = flip.read() else: if api: return {"error": "Invalid Parameters"} return HttpResponseRedirect("/error/") context = { "title": escape(ntpath.basename(fil)), "file": escape(ntpath.basename(fil)), "type": file_format, "dat": dat, "sql": sql_dump, "version": settings.MOBSF_VER, } template = "general/view.html" if api: return context return render(request, template, context) except Exception as exp: logger.exception("Error Viewing Source") msg = str(exp) exp = exp.__doc__ if api: return print_n_send_error_response(request, msg, True, exp) return print_n_send_error_response(request, msg, False, exp)
def run(request, api=False): """View iOS Files.""" try: logger.info("View iOS Source File") exp = "Error Description" file_format = "cpp" if api: fil = request.POST["file"] md5_hash = request.POST["hash"] mode = request.POST["type"] viewsource_form = ViewSourceIOSApiForm(request.POST) else: fil = request.GET["file"] md5_hash = request.GET["md5"] mode = request.GET["type"] viewsource_form = ViewSourceIOSForm(request.GET) typ = set_ext_api(fil) if not viewsource_form.is_valid(): err = FormUtil.errors_message(viewsource_form) if api: return err return print_n_send_error_response(request, err, False, exp) if mode == "ipa": src = os.path.join(settings.UPLD_DIR, md5_hash + "/Payload/") elif mode == "ios": src = os.path.join(settings.UPLD_DIR, md5_hash + "/") sfile = os.path.join(src, fil) if not is_safe_path(src, sfile): msg = "Path Traversal Detected!" if api: return {"error": "Path Traversal Detected!"} return print_n_send_error_response(request, msg, False, exp) dat = "" sql_dump = {} if typ == "m": file_format = "cpp" with io.open(sfile, mode="r", encoding="utf8", errors="ignore") as flip: dat = flip.read() elif typ == "xml": file_format = "xml" with io.open(sfile, mode="r", encoding="utf8", errors="ignore") as flip: dat = flip.read() elif typ == "plist": file_format = "json" dat = biplist.readPlist(sfile) try: dat = json.dumps(dat, indent=4, sort_keys=True) except Exception: pass elif typ == "db": file_format = "asciidoc" sql_dump = read_sqlite(sfile) elif typ == "txt" and fil == "classdump.txt": file_format = "cpp" app_dir = os.path.join(settings.UPLD_DIR, md5_hash + "/") cls_dump_file = os.path.join(app_dir, "classdump.txt") if is_file_exists(cls_dump_file): with io.open( cls_dump_file, mode="r", encoding="utf8", errors="ignore" ) as flip: dat = flip.read() else: dat = "Class Dump result not Found" elif typ == "txt": file_format = "text" with io.open(sfile, mode="r", encoding="utf8", errors="ignore") as flip: dat = flip.read() else: if api: return {"error": "Invalid Parameters"} return HttpResponseRedirect("/error/") context = { "title": escape(ntpath.basename(fil)), "file": escape(ntpath.basename(fil)), "type": file_format, "dat": dat, "sql": sql_dump, "version": settings.MOBSF_VER, } template = "general/view.html" if api: return context return render(request, template, context) except Exception as exp: logger.exception("Error Viewing Source") msg = str(exp) exp = exp.__doc__ if api: return print_n_send_error_response(request, msg, True, exp) return print_n_send_error_response(request, msg, False, exp)
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1352
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"
FileNotFoundError
def check_transport_security(p_list): """Check info.plist for insecure connection configurations.""" logger.info("Checking for Insecure Connections") ats = [] if "NSAppTransportSecurity" in p_list: ats_dict = p_list["NSAppTransportSecurity"] if ats_dict.get("NSAllowsArbitraryLoads"): ats.append( { "issue": ("App Transport Security AllowsArbitraryLoads is allowed"), "status": "insecure", "description": ( "App Transport Security restrictions are disabled " "for all network connections. Disabling ATS means that " "unsecured HTTP connections are allowed. HTTPS " "connections are also allowed, and are still subject " "to default server trust evaluation. However, " "extended security checks like requiring a minimum " "Transport Layer Security (TLS) protocol version—are " "disabled. This setting is not applicable to domains " "listed in NSExceptionDomains." ), } ) if ats_dict.get("NSAllowsArbitraryLoadsForMedia"): ats.append( { "issue": "Insecure media load is allowed", "status": "insecure", "description": ( "App Transport Security restrictions are disabled for " "media loaded using the AVFoundation framework, " "without affecting your URLSession connections. " "This setting is not applicable to domains " "listed in NSExceptionDomains." ), } ) if ats_dict.get("NSAllowsArbitraryLoadsInWebContent"): ats.append( { "issue": "Insecure WebView load is allowed", "status": "insecure", "description": ( "App Transport Security restrictions are disabled for " "requests made from WebViews without affecting your " "URLSession connections. This setting is not applicable " "to domains listed in NSExceptionDomains." ), } ) if ats_dict.get("NSAllowsLocalNetworking"): ats.append( { "issue": "Insecure local networking is allowed", "status": "insecure", "description": ( "App Transport Security restrictions are disabled for " "requests made from local networking " "without affecting your " "URLSession connections. This setting is not applicable " "to domains listed in NSExceptionDomains." ), } ) # NS Domain Exceptions exception_domains = ats_dict.get("NSExceptionDomains") if exception_domains: ats.append( { "issue": "NSExceptionDomains", "status": "info", "description": ", ".join(exception_domains.keys()), } ) for domain, config in exception_domains.items(): if not isinstance(config, dict): continue old_exp = "NSTemporaryExceptionAllowsInsecureHTTPLoads" if config.get( "NSExceptionAllowsInsecureHTTPLoads", False ) or config.get(old_exp, False): findings = { "issue": ( "Insecure communication to {} is allowed".format(domain) ), "status": "insecure", "description": ( "NSExceptionAllowsInsecureHTTPLoads allows " "insecure HTTP loads to {}, " "or to be able to loosen the " "server trust evaluation " "requirements for HTTPS " "connections to the domain.".format(domain) ), } ats.append(findings) if config.get("NSIncludesSubdomains", False): findings = { "issue": ( "NSIncludesSubdomains set to TRUE for {}".format(domain) ), "status": "insecure", "description": ( "NSIncludesSubdomains applies the ATS exceptions " "for the given domain to all " "subdomains as well. " "For example, the ATS exceptions in the " "domain exception dictionary apply to {}, " "as well as math.{}, history.{}, and so on. " "Otherwise, if the value is NO, the exceptions " "apply only to " "{}.".format(domain, domain, domain, domain) ), } ats.append(findings) old_tls = "NSTemporaryExceptionMinimumTLSVersion" inc_min_tls = config.get( "NSExceptionMinimumTLSVersion", None ) or config.get(old_tls, None) if inc_min_tls in ["TLSv1.0", "TLSv1.1"]: findings = { "issue": ( "NSExceptionMinimumTLSVersion set to {} on {}".format( inc_min_tls, domain ) ), "status": "insecure", "description": ( "The minimum Transport Layer " "Security (TLS) version " "for network connections sent to {} " "is set to {}. This version is deemed " "to be insecure".format(domain, inc_min_tls) ), } ats.append(findings) elif inc_min_tls == "TLSv1.2": findings = { "issue": ( "NSExceptionMinimumTLSVersion set to {} on {}".format( inc_min_tls, domain ) ), "status": "warning", "description": ( "The minimum Transport Layer " "Security (TLS) version " "for network connections sent to {} " "is set to {}. " "This version is vulnerable to " "attacks such as POODLE, FREAK, " "or CurveSwap etc.".format(domain, inc_min_tls) ), } ats.append(findings) elif inc_min_tls == "TLSv1.3": findings = { "issue": ( "NSExceptionMinimumTLSVersion set to {} on {}".format( inc_min_tls, domain ) ), "status": "secure", "description": ( "The minimum Transport Layer " "Security (TLS) version " "for network connections sent to {} " "is set to {}.".format(domain, inc_min_tls) ), } ats.append(findings) elif inc_min_tls is None: pass else: findings = { "issue": ( "NSExceptionMinimumTLSVersion set to {} on {}".format( inc_min_tls, domain ) ), "status": "info", "description": ( "The minimum Transport Layer " "Security (TLS) version " "for network connections sent to {} " "is set to {}.".format(domain, inc_min_tls) ), } ats.append(findings) old_fwd = "NSTemporaryExceptionRequiresForwardSecrecy" if config.get("NSExceptionRequiresForwardSecrecy", False) or config.get( old_fwd, False ): findings = { "issue": ( "NSExceptionRequiresForwardSecrecy " "set to YES" " for {}".format(domain) ), "status": "secure", "description": ( "NSExceptionRequiresForwardSecrecy " "limits the accepted ciphers to " "those that support perfect " "forward secrecy (PFS) through the " "Elliptic Curve Diffie-Hellman " "Ephemeral (ECDHE) key exchange. " "Set the value for this key to NO to override " "the requirement that a server must support " "PFS for the given domain. This key is optional. " "The default value is YES, which limits the " "accepted ciphers to those that support " "PFS through Elliptic Curve Diffie-Hellman " "Ephemeral (ECDHE) key exchange." ), } ats.append(findings) if config.get("NSRequiresCertificateTransparency", False): findings = { "issue": ( "NSRequiresCertificateTransparency" " set to YES for {}".format(domain) ), "status": "secure", "description": ( "Certificate Transparency (CT) is a protocol " "that ATS can use to identify " "mistakenly or maliciously " "issued X.509 certificates. " "Set the value for the " "NSRequiresCertificateTransparency " "key to YES to require that for a given domain, " "server certificates are supported by valid, " "signed CT timestamps from at least " "two CT logs trusted by Apple. " "This key is optional. The default value is NO." ), } ats.append(findings) return ats
def check_transport_security(p_list): """Check info.plist for insecure connection configurations.""" logger.info("Checking for Insecure Connections") ats = [] if "NSAppTransportSecurity" in p_list: ats_dict = p_list["NSAppTransportSecurity"] if ats_dict.get("NSAllowsArbitraryLoads"): ats.append( { "issue": ("App Transport Security AllowsArbitraryLoads is allowed"), "status": "insecure", "description": ( "App Transport Security restrictions are disabled " "for all network connections. Disabling ATS means that " "unsecured HTTP connections are allowed. HTTPS " "connections are also allowed, and are still subject " "to default server trust evaluation. However, " "extended security checks like requiring a minimum " "Transport Layer Security (TLS) protocol version—are " "disabled. This setting is not applicable to domains " "listed in NSExceptionDomains." ), } ) if ats_dict.get("NSAllowsArbitraryLoadsForMedia"): ats.append( { "issue": "Insecure media load is allowed", "status": "insecure", "description": ( "App Transport Security restrictions are disabled for " "media loaded using the AVFoundation framework, " "without affecting your URLSession connections. " "This setting is not applicable to domains " "listed in NSExceptionDomains." ), } ) if ats_dict.get("NSAllowsArbitraryLoadsInWebContent"): ats.append( { "issue": "Insecure WebView load is allowed", "status": "insecure", "description": ( "App Transport Security restrictions are disabled for " "requests made from WebViews without affecting your " "URLSession connections. This setting is not applicable " "to domains listed in NSExceptionDomains." ), } ) if ats_dict.get("NSAllowsLocalNetworking"): ats.append( { "issue": "Insecure local networking is allowed", "status": "insecure", "description": ( "App Transport Security restrictions are disabled for " "requests made from local networking " "without affecting your " "URLSession connections. This setting is not applicable " "to domains listed in NSExceptionDomains." ), } ) # NS Domain Exceptions exception_domains = ats_dict.get("NSExceptionDomains") if exception_domains: for domain, config in exception_domains.items(): old_exp = "NSTemporaryExceptionAllowsInsecureHTTPLoads" if config.get( "NSExceptionAllowsInsecureHTTPLoads", False ) or config.get(old_exp, False): findings = { "issue": ( "Insecure communication to {} is allowed".format(domain) ), "status": "insecure", "description": ( "NSExceptionAllowsInsecureHTTPLoads allows " "insecure HTTP loads to {}, " "or to be able to loosen the " "server trust evaluation " "requirements for HTTPS " "connections to the domain.".format(domain) ), } ats.append(findings) if config.get("NSIncludesSubdomains", False): findings = { "issue": ( "NSIncludesSubdomains set to TRUE for {}".format(domain) ), "status": "insecure", "description": ( "NSIncludesSubdomains applies the ATS exceptions " "for the given domain to all " "subdomains as well. " "For example, the ATS exceptions in the " "domain exception dictionary apply to {}, " "as well as math.{}, history.{}, and so on. " "Otherwise, if the value is NO, the exceptions " "apply only to " "{}.".format(domain, domain, domain, domain) ), } ats.append(findings) old_tls = "NSTemporaryExceptionMinimumTLSVersion" inc_min_tls = config.get( "NSExceptionMinimumTLSVersion", None ) or config.get(old_tls, None) if inc_min_tls in ["TLSv1.0", "TLSv1.1"]: findings = { "issue": ( "NSExceptionMinimumTLSVersion set to {} on {}".format( inc_min_tls, domain ) ), "status": "insecure", "description": ( "The minimum Transport Layer " "Security (TLS) version " "for network connections sent to {} " "is set to {}. This version is deemed " "to be insecure".format(domain, inc_min_tls) ), } ats.append(findings) elif inc_min_tls == "TLSv1.2": findings = { "issue": ( "NSExceptionMinimumTLSVersion set to {} on {}".format( inc_min_tls, domain ) ), "status": "warning", "description": ( "The minimum Transport Layer " "Security (TLS) version " "for network connections sent to {} " "is set to {}. " "This version is vulnerable to " "attacks such as POODLE, FREAK, " "or CurveSwap etc.".format(domain, inc_min_tls) ), } ats.append(findings) elif inc_min_tls == "TLSv1.3": findings = { "issue": ( "NSExceptionMinimumTLSVersion set to {} on {}".format( inc_min_tls, domain ) ), "status": "secure", "description": ( "The minimum Transport Layer " "Security (TLS) version " "for network connections sent to {} " "is set to {}.".format(domain, inc_min_tls) ), } ats.append(findings) elif inc_min_tls is None: pass else: findings = { "issue": ( "NSExceptionMinimumTLSVersion set to {} on {}".format( inc_min_tls, domain ) ), "status": "info", "description": ( "The minimum Transport Layer " "Security (TLS) version " "for network connections sent to {} " "is set to {}.".format(domain, inc_min_tls) ), } ats.append(findings) old_fwd = "NSTemporaryExceptionRequiresForwardSecrecy" if config.get("NSExceptionRequiresForwardSecrecy", False) or config.get( old_fwd, False ): findings = { "issue": ( "NSExceptionRequiresForwardSecrecy " "set to YES" " for {}".format(domain) ), "status": "secure", "description": ( "NSExceptionRequiresForwardSecrecy " "limits the accepted ciphers to " "those that support perfect " "forward secrecy (PFS) through the " "Elliptic Curve Diffie-Hellman " "Ephemeral (ECDHE) key exchange. " "Set the value for this key to NO to override " "the requirement that a server must support " "PFS for the given domain. This key is optional. " "The default value is YES, which limits the " "accepted ciphers to those that support " "PFS through Elliptic Curve Diffie-Hellman " "Ephemeral (ECDHE) key exchange." ), } ats.append(findings) if config.get("NSRequiresCertificateTransparency", False): findings = { "issue": ( "NSRequiresCertificateTransparency" " set to YES for {}".format(domain) ), "status": "secure", "description": ( "Certificate Transparency (CT) is a protocol " "that ATS can use to identify " "mistakenly or maliciously " "issued X.509 certificates. " "Set the value for the " "NSRequiresCertificateTransparency " "key to YES to require that for a given domain, " "server certificates are supported by valid, " "signed CT timestamps from at least " "two CT logs trusted by Apple. " "This key is optional. The default value is NO." ), } ats.append(findings) return ats
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1344
__ __ _ ____ _____ _____ ___ | \/ | ___ | |__/ ___|| ___|_ _|___ / / _ \ | |\/| |/ _ \| '_ \___ \| |_ \ \ / / |_ \| | | | | | | | (_) | |_) |__) | _| \ V / ___) | |_| | |_| |_|\___/|_.__/____/|_| \_/ |____(_)___/ [INFO] 02/Apr/2020 15:43:11 - Mobile Security Framework v3.0.6 Beta REST API Key: 618941ebdec42a7f519ed5dca40d9b3c5f17606ca6142fc2fc725f36cce06c40 [INFO] 02/Apr/2020 15:43:11 - OS: Linux [INFO] 02/Apr/2020 15:43:11 - Platform: Linux-4.4.0-173-generic-x86_64-with-Ubuntu-18.04-bionic [INFO] 02/Apr/2020 15:43:11 - Dist: ubuntu 18.04 bionic [INFO] 02/Apr/2020 15:43:11 - MobSF Basic Environment Check [INFO] 02/Apr/2020 15:43:11 - Checking for Update. [INFO] 02/Apr/2020 15:43:12 - No updates available. [INFO] 02/Apr/2020 15:44:21 - MIME Type: application/octet-stream FILE: ziaanalytics.ipa [INFO] 02/Apr/2020 15:44:22 - Performing Static Analysis of iOS IPA [INFO] 02/Apr/2020 15:44:22 - iOS Static Analysis Started [INFO] 02/Apr/2020 15:44:22 - iOS Binary (IPA) Analysis Started [INFO] 02/Apr/2020 15:44:22 - Generating Hashes [INFO] 02/Apr/2020 15:44:22 - Extracting IPA [INFO] 02/Apr/2020 15:44:22 - Unzipping [INFO] 02/Apr/2020 15:44:25 - Get Files, BIN Plist -> XML, and Normalize [INFO] 02/Apr/2020 15:44:25 - iOS Info.plist Analysis Started [INFO] 02/Apr/2020 15:44:25 - Finding Info.plist in iOS Binary [INFO] 02/Apr/2020 15:44:25 - Checking Permissions [INFO] 02/Apr/2020 15:44:25 - Checking for Insecure Connections [ERROR] 02/Apr/2020 15:44:25 - Reading from Info.plist Traceback (most recent call last): File "/root/Mobile-Security-Framework-MobSF/StaticAnalyzer/views/ios/plist_analysis.py", line 99, in plist_analysis plist_info['inseccon'] = check_transport_security(plist_obj) File "/root/Mobile-Security-Framework-MobSF/StaticAnalyzer/views/ios/app_transport_security.py", line 68, in check_transport_security if (config.get('NSExceptionAllowsInsecureHTTPLoads', False) AttributeError: 'str' object has no attribute 'get' [ERROR] 02/Apr/2020 15:44:25 - Error Perfroming Static Analysis Traceback (most recent call last): File "/root/Mobile-Security-Framework-MobSF/StaticAnalyzer/views/ios/static_analyzer.py", line 99, in static_analyzer_ios app_dict['appstore'] = app_search(infoplist_dict.get('id')) AttributeError: 'NoneType' object has no attribute 'get' [ERROR] 02/Apr/2020 15:44:25 - 'NoneType' object has no attribute 'get' [ERROR] 02/Apr/2020 15:44:25 - Internal Server Error: /StaticAnalyzer_iOS/
AttributeError
def cert_info(app_dir, app_file): """Return certificate information.""" try: logger.info("Reading Code Signing Certificate") issued = "" manidat = "" certlist = [] cert_path = os.path.join(app_dir, "META-INF/") apk_file = os.path.join(app_dir, app_file) hashfunctions = { "md5": hashlib.md5, "sha1": hashlib.sha1, "sha256": hashlib.sha256, "sha512": hashlib.sha512, } files = [ f for f in os.listdir(cert_path) if os.path.isfile(os.path.join(cert_path, f)) ] a = APK(apk_file) if a.is_signed(): certlist.append("APK is signed") else: certlist.append("Missing certificate") certlist.append("v1 signature: {}".format(a.is_signed_v1())) certlist.append("v2 signature: {}".format(a.is_signed_v2())) certlist.append("v3 signature: {}".format(a.is_signed_v3())) certs = set( a.get_certificates_der_v3() + a.get_certificates_der_v2() + [a.get_certificate_der(x) for x in a.get_signature_names()] ) pkeys = set(a.get_public_keys_der_v3() + a.get_public_keys_der_v2()) if len(certs) > 0: certlist.append("Found {} unique certificates".format(len(certs))) for cert in certs: x509_cert = x509.Certificate.load(cert) certlist.append( "Subject: {}".format( get_certificate_name_string(x509_cert.subject, short=True) ) ) certlist.append("Signature Algorithm: {}".format(x509_cert.signature_algo)) certlist.append( "Valid From: {}".format( x509_cert["tbs_certificate"]["validity"]["not_before"].native ) ) certlist.append( "Valid To: {}".format( x509_cert["tbs_certificate"]["validity"]["not_after"].native ) ) certlist.append( "Issuer: {}".format( get_certificate_name_string(x509_cert.issuer, short=True) ) ) certlist.append("Serial Number: {}".format(hex(x509_cert.serial_number))) certlist.append("Hash Algorithm: {}".format(x509_cert.hash_algo)) for k, v in hashfunctions.items(): certlist.append("{}: {}".format(k, v(cert).hexdigest())) for public_key in pkeys: x509_public_key = asymmetric.load_public_key(public_key) certlist.append("PublicKey Algorithm: {}".format(x509_public_key.algorithm)) certlist.append("Bit Size: {}".format(x509_public_key.bit_size)) certlist.append( "Fingerprint: {}".format( binascii.hexlify(x509_public_key.fingerprint).decode("utf-8") ) ) certlist = "\n".join(certlist) if a.is_signed(): issued = "good" else: issued = "missing" if re.findall(r"CN=Android Debug", certlist): issued = "bad" if re.findall(r"Hash Algorithm: sha1", certlist): issued = "bad hash" if "MANIFEST.MF" in files: manifestfile = os.path.join(cert_path, "MANIFEST.MF") if manifestfile: with open(manifestfile, "r", encoding="utf-8") as manifile: manidat = manifile.read() sha256_digest = bool(re.findall(r"SHA-256-Digest", manidat)) cert_dic = { "cert_info": certlist, "issued": issued, "sha256Digest": sha256_digest, } return cert_dic except Exception: logger.exception("Reading Code Signing Certificate")
def cert_info(app_dir, app_file): """Return certificate information.""" try: logger.info("Reading Code Signing Certificate") issued = "" manidat = "" certlist = [] cert_path = os.path.join(app_dir, "META-INF/") apk_file = os.path.join(app_dir, app_file) hashfunctions = { "md5": hashlib.md5, "sha1": hashlib.sha1, "sha256": hashlib.sha256, "sha512": hashlib.sha512, } files = [ f for f in os.listdir(cert_path) if os.path.isfile(os.path.join(cert_path, f)) ] a = APK(apk_file) if a.is_signed(): certlist.append("APK is signed") else: certlist.append("Missing certificate") certlist.append("v1 signature: {}".format(a.is_signed_v1())) certlist.append("v2 signature: {}".format(a.is_signed_v2())) certlist.append("v3 signature: {}".format(a.is_signed_v3())) certs = set( a.get_certificates_der_v3() + a.get_certificates_der_v2() + [a.get_certificate_der(x) for x in a.get_signature_names()] ) pkeys = set(a.get_public_keys_der_v3() + a.get_public_keys_der_v2()) if len(certs) > 0: certlist.append("Found {} unique certificates".format(len(certs))) for cert in certs: x509_cert = x509.Certificate.load(cert) certlist.append( "Subject: {}".format( get_certificate_name_string(x509_cert.subject, short=True) ) ) certlist.append("Signature Algorithm: {}".format(x509_cert.signature_algo)) certlist.append( "Valid From: {}".format( x509_cert["tbs_certificate"]["validity"]["not_before"].native ) ) certlist.append( "Valid To: {}".format( x509_cert["tbs_certificate"]["validity"]["not_after"].native ) ) certlist.append( "Issuer: {}".format( get_certificate_name_string(x509_cert.issuer, short=True) ) ) certlist.append("Serial Number: {}".format(hex(x509_cert.serial_number))) certlist.append("Hash Algorithm: {}".format(x509_cert.hash_algo)) for k, v in hashfunctions.items(): certlist.append("{}: {}".format(k, v(cert).hexdigest())) for public_key in pkeys: x509_public_key = keys.PublicKeyInfo.load(public_key) certlist.append("PublicKey Algorithm: {}".format(x509_public_key.algorithm)) certlist.append("Bit Size: {}".format(x509_public_key.bit_size)) certlist.append( "Fingerprint: {}".format( binascii.hexlify(x509_public_key.fingerprint).decode("utf-8") ) ) try: certlist.append("Hash Algorithm: {}".format(x509_public_key.hash_algo)) except ValueError: pass certlist = "\n".join(certlist) if a.is_signed(): issued = "good" else: issued = "missing" if re.findall(r"CN=Android Debug", certlist): issued = "bad" if re.findall(r"Hash Algorithm: sha1", certlist): issued = "bad hash" if "MANIFEST.MF" in files: manifestfile = os.path.join(cert_path, "MANIFEST.MF") if manifestfile: with open(manifestfile, "r", encoding="utf-8") as manifile: manidat = manifile.read() sha256_digest = bool(re.findall(r"SHA-256-Digest", manidat)) cert_dic = { "cert_info": certlist, "issued": issued, "sha256Digest": sha256_digest, } return cert_dic except Exception: logger.exception("Reading Code Signing Certificate")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1105
[INFO] 03/Oct/2019 02:35:15 - Generating Hashes [INFO] 03/Oct/2019 02:35:15 - Unzipping [INFO] 03/Oct/2019 02:35:15 - Getting Hardcoded Certificates/Keystores [INFO] 03/Oct/2019 02:35:15 - APK Extracted [INFO] 03/Oct/2019 02:35:15 - Converting AXML to XML [INFO] 03/Oct/2019 02:35:18 - Reading Android Manifest [INFO] 03/Oct/2019 02:35:18 - Parsing AndroidManifest.xml [INFO] 03/Oct/2019 02:35:19 - Fetching icon path [INFO] 03/Oct/2019 02:35:19 - Extracting Manifest Data [INFO] 03/Oct/2019 02:35:19 - Fetching Details from Play Store: com.everbridge.mobile.iv.recipient [WARNING] 03/Oct/2019 02:35:19 - Unable to get app details. [INFO] 03/Oct/2019 02:35:19 - Manifest Analysis Started [INFO] 03/Oct/2019 02:35:19 - Static Android Binary Analysis Started [INFO] 03/Oct/2019 02:35:19 - Static Android Resource Analysis Started [INFO] 03/Oct/2019 02:35:19 - Reading Code Signing Certificate [ERROR] 03/Oct/2019 02:35:20 - Reading Code Signing Certificate Traceback (most recent call last): File "/home/gclair/Mobile-Security-Framework-MobSF/StaticAnalyzer/views/android/cert_analysis.py", line 111, in cert_info binascii.hexlify(x509_public_key.fingerprint).decode('utf-8'))) File "/home/gclair/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/asn1crypto/keys.py", line 1212, in fingerprint 'asn1crypto.keys.PublicKeyInfo().fingerprint has been removed, ' asn1crypto._errors.APIException: asn1crypto.keys.PublicKeyInfo().fingerprint has been removed, please use oscrypto.asymmetric.PublicKey().fingerprint instead [INFO] 03/Oct/2019 02:35:21 - Trackers Database is outdated! [INFO] 03/Oct/2019 02:35:21 - Updating Trackers Database.... [INFO] 03/Oct/2019 02:35:21 - Detecting Trackers [INFO] 03/Oct/2019 02:35:22 - APK -> JAVA [INFO] 03/Oct/2019 02:35:22 - Decompiling to Java with jadx [INFO] 03/Oct/2019 02:35:31 - DEX -> SMALI [INFO] 03/Oct/2019 02:35:31 - Converting classes2.dex to Smali Code [INFO] 03/Oct/2019 02:35:31 - Converting classes.dex to Smali Code [INFO] 03/Oct/2019 02:35:31 - Static Android Code Analysis Started [INFO] 03/Oct/2019 02:35:31 - Code Analysis Started on - java_source [INFO] 03/Oct/2019 02:35:38 - Finished Code Analysis, Email and URL Extraction [INFO] 03/Oct/2019 02:35:38 - Extracting Strings from APK [INFO] 03/Oct/2019 02:35:40 - Detecting Firebase URL(s) [INFO] 03/Oct/2019 02:35:40 - Performing Malware Check on extracted Domains [INFO] 03/Oct/2019 02:35:41 - Malware Database is up-to-date [INFO] 03/Oct/2019 02:35:41 - Generating Java and Smali Downloads [INFO] 03/Oct/2019 02:35:41 - Generating Downloads [INFO] 03/Oct/2019 02:35:41 - Zipping [INFO] 03/Oct/2019 02:35:41 - Zipping [INFO] 03/Oct/2019 02:35:42 - Connecting to Database [INFO] 03/Oct/2019 02:35:42 - Saving to Database [ERROR] 03/Oct/2019 02:35:42 - Saving to DB Traceback (most recent call last): File "/home/gclair/Mobile-Security-Framework-MobSF/StaticAnalyzer/views/android/db_interaction.py", line 255, in create_db_entry CERT_INFO=cert_dic['cert_info'], TypeError: 'NoneType' object is not subscriptable [ERROR] 03/Oct/2019 02:35:42 - Rendering to Template Traceback (most recent call last): File "/home/gclair/Mobile-Security-Framework-MobSF/StaticAnalyzer/views/android/db_interaction.py", line 120, in get_context_from_analysis 'certinfo': cert_dic['cert_info'], TypeError: 'NoneType' object is not subscriptable [ERROR] 03/Oct/2019 02:35:42 - Error Performing Static Analysis Traceback (most recent call last): File "/home/gclair/Mobile-Security-Framework-MobSF/StaticAnalyzer/views/android/static_analyzer.py", line 271, in static_analyzer 'security_score'] = score(context['findings']) TypeError: 'NoneType' object is not subscriptable [ERROR] 03/Oct/2019 02:35:42 - 'NoneType' object is not subscriptable [ERROR] 03/Oct/2019 02:35:42 - Internal Server Error: /StaticAnalyzer/
TypeError
def binary_analysis(src, tools_dir, app_dir, executable_name): """Binary Analysis of IPA.""" try: binary_analysis_dict = {} logger.info("Starting Binary Analysis") dirs = os.listdir(src) dot_app_dir = "" for dir_ in dirs: if dir_.endswith(".app"): dot_app_dir = dir_ break # Bin Dir - Dir/Payload/x.app/ bin_dir = os.path.join(src, dot_app_dir) if executable_name and is_file_exists(executable_name): bin_name = executable_name else: bin_name = dot_app_dir.replace(".app", "") # Bin Path - Dir/Payload/x.app/x bin_path = os.path.join(bin_dir, bin_name) binary_analysis_dict["libs"] = [] binary_analysis_dict["bin_res"] = [] binary_analysis_dict["strings"] = [] if not is_file_exists(bin_path): logger.warning("MobSF Cannot find binary in %s", bin_path) logger.warning("Skipping Otool, Classdump and Strings") else: bin_info = get_bin_info(bin_path) otool_dict = otool_analysis(tools_dir, bin_name, bin_path, bin_dir) bin_type = detect_bin_type(otool_dict["libs"]) cls_dump = class_dump(tools_dir, bin_path, app_dir, bin_type) if not cls_dump: cls_dump = {} strings_in_ipa = strings_on_ipa(bin_path) otool_dict["anal"] = list(filter(None, otool_dict["anal"] + [cls_dump])) binary_analysis_dict["libs"] = otool_dict["libs"] binary_analysis_dict["bin_res"] = otool_dict["anal"] binary_analysis_dict["strings"] = strings_in_ipa binary_analysis_dict["macho"] = bin_info binary_analysis_dict["bin_type"] = bin_type return binary_analysis_dict except Exception: logger.exception("iOS Binary Analysis")
def binary_analysis(src, tools_dir, app_dir, executable_name): """Binary Analysis of IPA.""" try: binary_analysis_dict = {} logger.info("Starting Binary Analysis") dirs = os.listdir(src) dot_app_dir = "" for dir_ in dirs: if dir_.endswith(".app"): dot_app_dir = dir_ break # Bin Dir - Dir/Payload/x.app/ bin_dir = os.path.join(src, dot_app_dir) if executable_name is None: bin_name = dot_app_dir.replace(".app", "") else: bin_name = executable_name # Bin Path - Dir/Payload/x.app/x bin_path = os.path.join(bin_dir, bin_name) binary_analysis_dict["libs"] = [] binary_analysis_dict["bin_res"] = [] binary_analysis_dict["strings"] = [] if not is_file_exists(bin_path): logger.warning("MobSF Cannot find binary in %s", bin_path) logger.warning("Skipping Otool, Classdump and Strings") else: bin_info = get_bin_info(bin_path) otool_dict = otool_analysis(tools_dir, bin_name, bin_path, bin_dir) bin_type = detect_bin_type(otool_dict["libs"]) cls_dump = class_dump(tools_dir, bin_path, app_dir, bin_type) if not cls_dump: cls_dump = {} strings_in_ipa = strings_on_ipa(bin_path) otool_dict["anal"] = list(filter(None, otool_dict["anal"] + [cls_dump])) binary_analysis_dict["libs"] = otool_dict["libs"] binary_analysis_dict["bin_res"] = otool_dict["anal"] binary_analysis_dict["strings"] = strings_in_ipa binary_analysis_dict["macho"] = bin_info binary_analysis_dict["bin_type"] = bin_type return binary_analysis_dict except Exception: logger.exception("iOS Binary Analysis")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/1073
[WARNING] 23/Aug/2019 07:28:40 - Could not find VirtualBox path [INFO] 23/Aug/2019 07:28:40 - MobSF Basic Environment Check [INFO] 23/Aug/2019 07:28:40 - Checking for Update. [INFO] 23/Aug/2019 07:28:41 - No updates available. [INFO] 23/Aug/2019 07:28:55 - MIME Type: application/octet-stream FILE: test_uuu.ipa [INFO] 23/Aug/2019 07:28:56 - Performing Static Analysis of iOS IPA [INFO] 23/Aug/2019 07:28:56 - iOS Static Analysis Started [INFO] 23/Aug/2019 07:28:56 - iOS Binary (IPA) Analysis Started [INFO] 23/Aug/2019 07:28:56 - Generating Hashes [INFO] 23/Aug/2019 07:28:56 - Extracting IPA [INFO] 23/Aug/2019 07:28:56 - Unzipping [INFO] 23/Aug/2019 07:28:57 - Get Files, BIN Plist -> XML, and Normalize [INFO] 23/Aug/2019 07:28:57 - iOS Info.plist Analysis Started [INFO] 23/Aug/2019 07:28:57 - Finding Info.plist in iOS Binary [INFO] 23/Aug/2019 07:28:57 - Checking Permissions [INFO] 23/Aug/2019 07:28:57 - Checking for Insecure Connections [INFO] 23/Aug/2019 07:28:57 - Fetching Details from App Store: tw.gov.post.guard [WARNING] 23/Aug/2019 07:28:58 - Unable to get app details [INFO] 23/Aug/2019 07:28:58 - Starting Binary Analysis [WARNING] 23/Aug/2019 07:28:58 - MobSF Cannot find binary in /Users/digicentre/Mobile-Security-Framework-MobSF/uploads/a9b35b6f9832daeeae2be49bff523a6c/Payload/test_UUU.app/test_UUU [WARNING] 23/Aug/2019 07:28:58 - Skipping Otool, Classdump and Strings [INFO] 23/Aug/2019 07:28:58 - Connecting to DB [INFO] 23/Aug/2019 07:28:58 - Saving to Database [ERROR] 23/Aug/2019 07:28:58 - Saving to DB Traceback (most recent call last): File "/Users/digicentre/Mobile-Security-Framework-MobSF/StaticAnalyzer/views/ios/db_interaction.py", line 174, in create_db_entry_ipa MACHOINFO=bin_dict['macho'], KeyError: 'macho' [ERROR] 23/Aug/2019 07:28:58 - Rendering to Template Traceback (most recent call last): File "/Users/digicentre/Mobile-Security-Framework-MobSF/StaticAnalyzer/views/ios/db_interaction.py", line 46, in get_context_from_analysis_ipa 'binary_info': bin_dict['macho'], KeyError: 'macho' [ERROR] 23/Aug/2019 07:28:58 - Error Perfroming Static Analysis Traceback (most recent call last): File "/Users/digicentre/Mobile-Security-Framework-MobSF/StaticAnalyzer/views/ios/static_analyzer.py", line 181, in static_analyzer_ios context['VT_RESULT'] = None TypeError: 'NoneType' object does not support item assignment [ERROR] 23/Aug/2019 07:28:58 - 'NoneType' object does not support item assignment [ERROR] 23/Aug/2019 07:28:58 - Internal Server Error: /StaticAnalyzer_iOS/
KeyError
def api_analysis(package, location): """API Analysis""" api_analysis_result = {} logger.info("Dynamic API Analysis") dat = "" api_base64 = [] api_fileio = [] api_reflect = [] api_sysprop = [] api_cntvl = [] api_binder = [] api_crypto = [] api_acntmnger = [] api_deviceinfo = [] api_net = [] api_dexloader = [] api_cmd = [] api_sms = [] try: with open(location, "r", encoding="utf-8") as flip: dat = flip.readlines() res_id = "Droidmon-apimonitor-" + package + ":" for line in dat: if res_id in line: # print "LINE: " + line _, value = line.split(res_id, 1) # print "PARAM is :" + param # print "Value is :"+ value try: apis = json.loads(value, strict=False) ret = "" args = "" mtd = str(apis["method"]) clss = str(apis["class"]) # print "Called Class: " + CLS # print "Called Method: " + MTD if apis.get("return"): ret = str(apis["return"]) # print "Return Data: " + RET else: # print "No Return Data" ret = "No Return Data" if apis.get("args"): args = str(apis["args"]) # print "Passed Arguments" + ARGS else: # print "No Arguments Passed" args = "No Arguments Passed" # XSS Safe call_data = ( "</br>METHOD: " + escape(mtd) + "</br>ARGUMENTS: " + escape(args) + "</br>RETURN DATA: " + escape(ret) ) if re.findall("android.util.Base64", clss): # Base64 Decode if "decode" in mtd: args_list = python_list(args) if isBase64(args_list[0]): call_data += ( '</br><span class="label label-info">' + "Decoded String:</span> " + escape(base64.b64decode(args_list[0])) ) api_base64.append(call_data) if re.findall( "libcore.io|android.app.SharedPreferencesImpl\$EditorImpl", clss ): api_fileio.append(call_data) if re.findall("java.lang.reflect", clss): api_reflect.append(call_data) if re.findall( "android.content.ContentResolver|android.location.Location|android.media.AudioRecord|android.media.MediaRecorder|android.os.SystemProperties", clss, ): api_sysprop.append(call_data) if re.findall( "android.app.Activity|android.app.ContextImpl|android.app.ActivityThread", clss, ): api_binder.append(call_data) if re.findall( "javax.crypto.spec.SecretKeySpec|javax.crypto.Cipher|javax.crypto.Mac", clss, ): api_crypto.append(call_data) if re.findall( "android.accounts.AccountManager|android.app.ApplicationPackageManager|android.app.NotificationManager|android.net.ConnectivityManager|android.content.BroadcastReceiver", clss, ): api_acntmnger.append(call_data) if re.findall( "android.telephony.TelephonyManager|android.net.wifi.WifiInfo|android.os.Debug", clss, ): api_deviceinfo.append(call_data) if re.findall( "dalvik.system.BaseDexClassLoader|dalvik.system.DexFile|dalvik.system.DexClassLoader|dalvik.system.PathClassLoader", clss, ): api_dexloader.append(call_data) if re.findall( "java.lang.Runtime|java.lang.ProcessBuilder|java.io.FileOutputStream|java.io.FileInputStream|android.os.Process", clss, ): api_cmd.append(call_data) if re.findall("android.content.ContentValues", clss): api_cntvl.append(call_data) if re.findall("android.telephony.SmsManager", clss): api_sms.append(call_data) if re.findall( "java.net.URL|org.apache.http.impl.client.AbstractHttpClient", clss, ): api_net.append(call_data) except: PrintException("Parsing JSON Failed for: " + value) except: PrintException("Dynamic API Analysis") api_analysis_result["api_net"] = list(set(api_net)) api_analysis_result["api_base64"] = list(set(api_base64)) api_analysis_result["api_fileio"] = list(set(api_fileio)) api_analysis_result["api_binder"] = list(set(api_binder)) api_analysis_result["api_crypto"] = list(set(api_crypto)) api_analysis_result["api_deviceinfo"] = list(set(api_deviceinfo)) api_analysis_result["api_cntvl"] = list(set(api_cntvl)) api_analysis_result["api_sms"] = list(set(api_sms)) api_analysis_result["api_sysprop"] = list(set(api_sysprop)) api_analysis_result["api_dexloader"] = list(set(api_dexloader)) api_analysis_result["api_reflect"] = list(set(api_reflect)) api_analysis_result["api_acntmnger"] = list(set(api_acntmnger)) api_analysis_result["api_cmd"] = list(set(api_cmd)) return api_analysis_result
def api_analysis(package, location): """API Analysis""" api_analysis_result = {} logger.info("Dynamic API Analysis") dat = "" api_base64 = [] api_fileio = [] api_reflect = [] api_sysprop = [] api_cntvl = [] api_binder = [] api_crypto = [] api_acntmnger = [] api_deviceinfo = [] api_net = [] api_dexloader = [] api_cmd = [] api_sms = [] try: with open(location, "r", encoding="utf-8") as flip: dat = flip.readlines() res_id = "Droidmon-apimonitor-" + package + ":" for line in dat: if res_id in line: # print "LINE: " + line _, value = line.split(res_id, 1) # print "PARAM is :" + param # print "Value is :"+ value try: apis = json.loads(value, strict=False) ret = "" args = "" mtd = str(apis["method"]) clss = str(apis["class"]) # print "Called Class: " + CLS # print "Called Method: " + MTD if apis.get("return"): ret = str(apis["return"]) # print "Return Data: " + RET else: # print "No Return Data" ret = "No Return Data" if apis.get("args"): args = str(apis["args"]) # print "Passed Arguments" + ARGS else: # print "No Arguments Passed" args = "No Arguments Passed" # XSS Safe call_data = ( "</br>METHOD: " + escape(mtd) + "</br>ARGUMENTS: " + escape(args) + "</br>RETURN DATA: " + escape(ret) ) if re.findall("android.util.Base64", clss): # Base64 Decode if "decode" in mtd: args_list = python_list(args) if isBase64(args_list[0]): call_data += ( '</br><span class="label label-info">' + "Decoded String:</span> " + escape(base64.b64decode(args_list[0])) ) api_base64.append(call_data) if re.findall( "libcore.io|android.app.SharedPreferencesImpl\$EditorImpl", clss ): api_fileio.append(call_data) if re.findall("java.lang.reflect", clss): api_reflect.append(call_data) if re.findall( "android.content.ContentResolver|android.location.Location|android.media.AudioRecord|android.media.MediaRecorder|android.os.SystemProperties", clss, ): api_sysprop.append(call_data) if re.findall( "android.app.Activity|android.app.ContextImpl|android.app.ActivityThread", clss, ): api_binder.append(call_data) if re.findall( "javax.crypto.spec.SecretKeySpec|javax.crypto.Cipher|javax.crypto.Mac", clss, ): api_crypto.append(call_data) if re.findall( "android.accounts.AccountManager|android.app.ApplicationPackageManager|android.app.NotificationManager|android.net.ConnectivityManager|android.content.BroadcastReceiver", clss, ): api_acntmnger.append(call_data) if re.findall( "android.telephony.TelephonyManager|android.net.wifi.WifiInfo|android.os.Debug", clss, ): api_deviceinfo.append(call_data) if re.findall( "dalvik.system.BaseDexClassLoader|dalvik.system.DexFile|dalvik.system.DexClassLoader|dalvik.system.PathClassLoader", clss, ): api_dexloader.append(call_data) if re.findall( "java.lang.Runtime|java.lang.ProcessBuilder|java.io.FileOutputStream|java.io.FileInputStream|android.os.Process", clss, ): api_cmd.append(call_data) if re.findall("android.content.ContentValues", clss): api_cntvl.append(call_data) if re.findall("android.telephony.SmsManager", clss): api_sms.append(call_data) if re.findall( "java.net.URL|org.apache.http.impl.client.AbstractHttpClient", clss, ): api_net.append(call_data) except: PrintException("[ERROR] Parsing JSON Failed for: " + value) except: PrintException("[ERROR] Dynamic API Analysis") api_analysis_result["api_net"] = list(set(api_net)) api_analysis_result["api_base64"] = list(set(api_base64)) api_analysis_result["api_fileio"] = list(set(api_fileio)) api_analysis_result["api_binder"] = list(set(api_binder)) api_analysis_result["api_crypto"] = list(set(api_crypto)) api_analysis_result["api_deviceinfo"] = list(set(api_deviceinfo)) api_analysis_result["api_cntvl"] = list(set(api_cntvl)) api_analysis_result["api_sms"] = list(set(api_sms)) api_analysis_result["api_sysprop"] = list(set(api_sysprop)) api_analysis_result["api_dexloader"] = list(set(api_dexloader)) api_analysis_result["api_reflect"] = list(set(api_reflect)) api_analysis_result["api_acntmnger"] = list(set(api_acntmnger)) api_analysis_result["api_cmd"] = list(set(api_cmd)) return api_analysis_result
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def run_analysis(apk_dir, md5_hash, package): """Run Dynamic File Analysis""" analysis_result = {} logger.info("Dynamic File Analysis") capfuzz_home = os.path.join(str(Path.home()), ".capfuzz") web = os.path.join(capfuzz_home, "flows", package + ".flows.txt") logcat = os.path.join(apk_dir, "logcat.txt") xlogcat = os.path.join(apk_dir, "x_logcat.txt") traffic = "" web_data = "" xlg = "" domains = {} logcat_data = [] clipboard = [] clip_tag = "I/CLIPDUMP-INFO-LOG" try: with io.open(web, mode="r", encoding="utf8", errors="ignore") as flip: web_data = flip.read() except: pass with io.open(logcat, mode="r", encoding="utf8", errors="ignore") as flip: logcat_data = flip.readlines() traffic = "".join(logcat_data) with io.open(xlogcat, mode="r", encoding="utf8", errors="ignore") as flip: xlg = flip.read() traffic = web_data + traffic + xlg for log_line in logcat_data: if log_line.startswith(clip_tag): clipboard.append(log_line.replace(clip_tag, "Process ID ")) urls = [] # URLs My Custom regex url_pattern = re.compile( r"((?:https?://|s?ftps?://|file://|javascript:|data:|www\d{0,3}[.])[\w().=/;,#:@?&~*+!$%\'{}-]+)", re.UNICODE, ) urllist = re.findall(url_pattern, traffic.lower()) # Domain Extraction and Malware Check logger.info("Performing Malware Check on extracted Domains") domains = malware_check(urllist) for url in urllist: if url not in urls: urls.append(url) # Email Etraction Regex emails = [] regex = re.compile(r"[\w.-]+@[\w-]+\.[\w.]+") for email in regex.findall(traffic.lower()): if (email not in emails) and (not email.startswith("//")): if email == "yodleebanglore@gmail.com": pass else: emails.append(email) # Extract Device Data try: tar_loc = os.path.join(apk_dir, package + ".tar") untar_dir = os.path.join(apk_dir, "DYNAMIC_DeviceData/") if not os.path.exists(untar_dir): os.makedirs(untar_dir) with tarfile.open(tar_loc) as tar: try: tar.extractall(untar_dir) except: pass except: PrintException("TAR EXTRACTION FAILED") # Do Static Analysis on Data from Device xmlfiles = "" sqlite_db = "" other_files = "" typ = "" untar_dir = os.path.join(apk_dir, "DYNAMIC_DeviceData/") if not os.path.exists(untar_dir): os.makedirs(untar_dir) try: for dir_name, _, files in os.walk(untar_dir): for jfile in files: file_path = os.path.join(untar_dir, dir_name, jfile) if "+" in file_path: shutil.move(file_path, file_path.replace("+", "x")) file_path = file_path.replace("+", "x") fileparam = file_path.replace(untar_dir, "") if jfile == "lib": pass else: if jfile.endswith(".xml"): typ = "xml" xmlfiles += ( "<tr><td><a href='../View/?file=" + escape(fileparam) + "&md5=" + md5_hash + "&type=" + typ + "'>" + escape(fileparam) + "</a></td><tr>" ) else: with io.open( file_path, mode="r", encoding="utf8", errors="ignore" ) as flip: file_cnt_sig = flip.read(6) if file_cnt_sig == "SQLite": typ = "db" sqlite_db += ( "<tr><td><a href='../View/?file=" + escape(fileparam) + "&md5=" + md5_hash + "&type=" + typ + "'>" + escape(fileparam) + "</a></td><tr>" ) elif not jfile.endswith(".DS_Store"): typ = "others" other_files += ( "<tr><td><a href='../View/?file=" + escape(fileparam) + "&md5=" + md5_hash + "&type=" + typ + "'>" + escape(fileparam) + "</a></td><tr>" ) except: PrintException("Dynamic File Analysis") analysis_result["urls"] = urls analysis_result["domains"] = domains analysis_result["emails"] = emails analysis_result["clipboard"] = clipboard analysis_result["web_data"] = web_data analysis_result["xmlfiles"] = xmlfiles analysis_result["sqlite_db"] = sqlite_db analysis_result["other_files"] = other_files return analysis_result
def run_analysis(apk_dir, md5_hash, package): """Run Dynamic File Analysis""" analysis_result = {} logger.info("Dynamic File Analysis") capfuzz_home = os.path.join(str(Path.home()), ".capfuzz") web = os.path.join(capfuzz_home, "flows", package + ".flows.txt") logcat = os.path.join(apk_dir, "logcat.txt") xlogcat = os.path.join(apk_dir, "x_logcat.txt") traffic = "" web_data = "" xlg = "" domains = {} logcat_data = [] clipboard = [] clip_tag = "I/CLIPDUMP-INFO-LOG" try: with io.open(web, mode="r", encoding="utf8", errors="ignore") as flip: web_data = flip.read() except: pass with io.open(logcat, mode="r", encoding="utf8", errors="ignore") as flip: logcat_data = flip.readlines() traffic = "".join(logcat_data) with io.open(xlogcat, mode="r", encoding="utf8", errors="ignore") as flip: xlg = flip.read() traffic = web_data + traffic + xlg for log_line in logcat_data: if log_line.startswith(clip_tag): clipboard.append(log_line.replace(clip_tag, "Process ID ")) urls = [] # URLs My Custom regex url_pattern = re.compile( r"((?:https?://|s?ftps?://|file://|javascript:|data:|www\d{0,3}[.])[\w().=/;,#:@?&~*+!$%\'{}-]+)", re.UNICODE, ) urllist = re.findall(url_pattern, traffic.lower()) # Domain Extraction and Malware Check logger.info("Performing Malware Check on extracted Domains") domains = malware_check(urllist) for url in urllist: if url not in urls: urls.append(url) # Email Etraction Regex emails = [] regex = re.compile(r"[\w.-]+@[\w-]+\.[\w.]+") for email in regex.findall(traffic.lower()): if (email not in emails) and (not email.startswith("//")): if email == "yodleebanglore@gmail.com": pass else: emails.append(email) # Extract Device Data try: tar_loc = os.path.join(apk_dir, package + ".tar") untar_dir = os.path.join(apk_dir, "DYNAMIC_DeviceData/") if not os.path.exists(untar_dir): os.makedirs(untar_dir) with tarfile.open(tar_loc) as tar: try: tar.extractall(untar_dir) except: pass except: PrintException("[ERROR] TAR EXTRACTION FAILED") # Do Static Analysis on Data from Device xmlfiles = "" sqlite_db = "" other_files = "" typ = "" untar_dir = os.path.join(apk_dir, "DYNAMIC_DeviceData/") if not os.path.exists(untar_dir): os.makedirs(untar_dir) try: for dir_name, _, files in os.walk(untar_dir): for jfile in files: file_path = os.path.join(untar_dir, dir_name, jfile) if "+" in file_path: shutil.move(file_path, file_path.replace("+", "x")) file_path = file_path.replace("+", "x") fileparam = file_path.replace(untar_dir, "") if jfile == "lib": pass else: if jfile.endswith(".xml"): typ = "xml" xmlfiles += ( "<tr><td><a href='../View/?file=" + escape(fileparam) + "&md5=" + md5_hash + "&type=" + typ + "'>" + escape(fileparam) + "</a></td><tr>" ) else: with io.open( file_path, mode="r", encoding="utf8", errors="ignore" ) as flip: file_cnt_sig = flip.read(6) if file_cnt_sig == "SQLite": typ = "db" sqlite_db += ( "<tr><td><a href='../View/?file=" + escape(fileparam) + "&md5=" + md5_hash + "&type=" + typ + "'>" + escape(fileparam) + "</a></td><tr>" ) elif not jfile.endswith(".DS_Store"): typ = "others" other_files += ( "<tr><td><a href='../View/?file=" + escape(fileparam) + "&md5=" + md5_hash + "&type=" + typ + "'>" + escape(fileparam) + "</a></td><tr>" ) except: PrintException("[ERROR] Dynamic File Analysis") analysis_result["urls"] = urls analysis_result["domains"] = domains analysis_result["emails"] = emails analysis_result["clipboard"] = clipboard analysis_result["web_data"] = web_data analysis_result["xmlfiles"] = xmlfiles analysis_result["sqlite_db"] = sqlite_db analysis_result["other_files"] = other_files return analysis_result
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def download(md5_hash, download_dir, apk_dir, package): """Generating Downloads""" logger.info("Generating Downloads") try: capfuzz_home = os.path.join(str(Path.home()), ".capfuzz") logcat = os.path.join(apk_dir, "logcat.txt") xlogcat = os.path.join(apk_dir, "x_logcat.txt") dumpsys = os.path.join(apk_dir, "dump.txt") sshot = os.path.join(apk_dir, "screenshots-apk/") web = os.path.join(capfuzz_home, "flows", package + ".flows.txt") star = os.path.join(apk_dir, package + ".tar") dlogcat = os.path.join(download_dir, md5_hash + "-logcat.txt") dxlogcat = os.path.join(download_dir, md5_hash + "-x_logcat.txt") ddumpsys = os.path.join(download_dir, md5_hash + "-dump.txt") dsshot = os.path.join(download_dir, md5_hash + "-screenshots-apk/") dweb = os.path.join(download_dir, md5_hash + "-WebTraffic.txt") dstar = os.path.join(download_dir, md5_hash + "-AppData.tar") # Delete existing data dellist = [dlogcat, dxlogcat, ddumpsys, dsshot, dweb, dstar] for item in dellist: if os.path.isdir(item): shutil.rmtree(item) elif os.path.isfile(item): os.remove(item) # Copy new data shutil.copyfile(logcat, dlogcat) shutil.copyfile(xlogcat, dxlogcat) shutil.copyfile(dumpsys, ddumpsys) try: shutil.copytree(sshot, dsshot) except: pass try: shutil.copyfile(web, dweb) except: pass try: shutil.copyfile(star, dstar) except: pass except: PrintException("Generating Downloads")
def download(md5_hash, download_dir, apk_dir, package): """Generating Downloads""" logger.info("Generating Downloads") try: capfuzz_home = os.path.join(str(Path.home()), ".capfuzz") logcat = os.path.join(apk_dir, "logcat.txt") xlogcat = os.path.join(apk_dir, "x_logcat.txt") dumpsys = os.path.join(apk_dir, "dump.txt") sshot = os.path.join(apk_dir, "screenshots-apk/") web = os.path.join(capfuzz_home, "flows", package + ".flows.txt") star = os.path.join(apk_dir, package + ".tar") dlogcat = os.path.join(download_dir, md5_hash + "-logcat.txt") dxlogcat = os.path.join(download_dir, md5_hash + "-x_logcat.txt") ddumpsys = os.path.join(download_dir, md5_hash + "-dump.txt") dsshot = os.path.join(download_dir, md5_hash + "-screenshots-apk/") dweb = os.path.join(download_dir, md5_hash + "-WebTraffic.txt") dstar = os.path.join(download_dir, md5_hash + "-AppData.tar") # Delete existing data dellist = [dlogcat, dxlogcat, ddumpsys, dsshot, dweb, dstar] for item in dellist: if os.path.isdir(item): shutil.rmtree(item) elif os.path.isfile(item): os.remove(item) # Copy new data shutil.copyfile(logcat, dlogcat) shutil.copyfile(xlogcat, dxlogcat) shutil.copyfile(dumpsys, ddumpsys) try: shutil.copytree(sshot, dsshot) except: pass try: shutil.copyfile(web, dweb) except: pass try: shutil.copyfile(star, dstar) except: pass except: PrintException("[ERROR] Generating Downloads")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def stop_avd(): """Stop AVD""" logger.info("Stopping MobSF Emulator") try: adb_command(["emu", "kill"], silent=True) except: PrintException("Stopping MobSF Emulator")
def stop_avd(): """Stop AVD""" logger.info("Stopping MobSF Emulator") try: adb_command(["emu", "kill"], silent=True) except: PrintException("[ERROR] Stopping MobSF Emulator")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def start_avd_from_snapshot(): """Start AVD""" logger.info("Starting MobSF Emulator") try: if platform.system() == "Darwin": # There is a strage error in mac with the dyld one in a while.. # this should fix it.. if "DYLD_FALLBACK_LIBRARY_PATH" in list(os.environ.keys()): del os.environ["DYLD_FALLBACK_LIBRARY_PATH"] args = [ settings.AVD_EMULATOR, "-avd", settings.AVD_NAME, "-writable-system", "-snapshot", settings.AVD_SNAPSHOT, "-netspeed", "full", "-netdelay", "none", "-port", str(settings.AVD_ADB_PORT), ] subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Give a few seconds and check if the snapshot load succeed time.sleep(5) result = adb_command(["getprop", "init.svc.bootanim"], True) if result: if result.strip() == b"stopped": return True # Snapshot failed, stop the avd and return an error adb_command(["emu", "kill"]) return False except: PrintException("Starting MobSF Emulator") return False
def start_avd_from_snapshot(): """Start AVD""" logger.info("Starting MobSF Emulator") try: if platform.system() == "Darwin": # There is a strage error in mac with the dyld one in a while.. # this should fix it.. if "DYLD_FALLBACK_LIBRARY_PATH" in list(os.environ.keys()): del os.environ["DYLD_FALLBACK_LIBRARY_PATH"] args = [ settings.AVD_EMULATOR, "-avd", settings.AVD_NAME, "-writable-system", "-snapshot", settings.AVD_SNAPSHOT, "-netspeed", "full", "-netdelay", "none", "-port", str(settings.AVD_ADB_PORT), ] subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Give a few seconds and check if the snapshot load succeed time.sleep(5) result = adb_command(["getprop", "init.svc.bootanim"], True) if result: if result.strip() == b"stopped": return True # Snapshot failed, stop the avd and return an error adb_command(["emu", "kill"]) return False except: PrintException("[ERROR] Starting MobSF Emulator") return False
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def refresh_avd(): """Refresh AVD""" # Before we load the AVD, check paths for path in [settings.AVD_EMULATOR, settings.ADB_BINARY]: if not path: logger.error( "AVD binaries not configured, please refer to the official documentation" ) return False logger.info("Refreshing MobSF Emulator") try: # Stop existing emulator stop_avd() # Check if configuration specifies cold or warm boot if settings.AVD_COLD_BOOT: if start_avd_cold(): logger.info("AVD has been started successfully") return True else: if not settings.AVD_SNAPSHOT: logger.error("AVD not configured properly - AVD_SNAPSHOT is missing") return False if start_avd_from_snapshot(): logger.info("AVD has been loaded from snapshot successfully") return True return False except: PrintException("Refreshing MobSF VM") return False
def refresh_avd(): """Refresh AVD""" # Before we load the AVD, check paths for path in [settings.AVD_EMULATOR, settings.ADB_BINARY]: if not path: logger.error( "AVD binaries not configured, please refer to the official documentation" ) return False logger.info("Refreshing MobSF Emulator") try: # Stop existing emulator stop_avd() # Check if configuration specifies cold or warm boot if settings.AVD_COLD_BOOT: if start_avd_cold(): logger.info("AVD has been started successfully") return True else: if not settings.AVD_SNAPSHOT: logger.error("AVD not configured properly - AVD_SNAPSHOT is missing") return False if start_avd_from_snapshot(): logger.info("AVD has been loaded from snapshot successfully") return True return False except: PrintException("[ERROR] Refreshing MobSF VM") return False
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def android_dynamic_analyzer(request): """Android Dynamic Analyzer View""" logger.info("Dynamic Analysis Started") try: if request.method == "POST": md5_hash = request.POST["md5"] package = request.POST["pkg"] launcher = request.POST["lng"] if re.findall(r";|\$\(|\|\||&&", package) or re.findall( r";|\$\(|\|\||&&", launcher ): return print_n_send_error_response(request, "Possible RCE Attack") if re.match("^[0-9a-f]{32}$", md5_hash): # Delete ScreenCast Cache screen_file = os.path.join(settings.SCREEN_DIR, "screen.png") if os.path.exists(screen_file): os.remove(screen_file) # Delete Contents of Screenshot Dir screen_dir = os.path.join( settings.UPLD_DIR, md5_hash + "/screenshots-apk/" ) if os.path.isdir(screen_dir): shutil.rmtree(screen_dir) else: os.makedirs(screen_dir) # Start DM stop_capfuzz(settings.PORT) adb = getADB() is_avd = False if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_REAL_DEVICE": logger.info( "MobSF will perform Dynamic Analysis on real Android Device" ) elif settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": # adb, avd_path, reference_name, dup_name, emulator is_avd = True if not os.path.exists(settings.AVD_EMULATOR): return print_n_send_error_response( request, "Cannot Find AVD Emulator" ) if not refresh_avd(): return print_n_send_error_response( request, "Cannot Refresh AVD" ) else: # Refersh VM refresh_vm(settings.UUID, settings.SUUID, settings.VBOX) context = { "md5": md5_hash, "pkg": package, "lng": launcher, "title": "Start Testing", "AVD": is_avd, } template = "dynamic_analysis/start_test.html" return render(request, template, context) else: return print_n_send_error_response(request, "Invalid Scan Hash") else: return print_n_send_error_response(request, "Only POST allowed") except: PrintException("DynamicAnalyzer") return print_n_send_error_response(request, "Dynamic Analysis Failed.")
def android_dynamic_analyzer(request): """Android Dynamic Analyzer View""" logger.info("Dynamic Analysis Started") try: if request.method == "POST": md5_hash = request.POST["md5"] package = request.POST["pkg"] launcher = request.POST["lng"] if re.findall(r";|\$\(|\|\||&&", package) or re.findall( r";|\$\(|\|\||&&", launcher ): logger.info("[ATTACK] Possible RCE") return HttpResponseRedirect("/error/") if re.match("^[0-9a-f]{32}$", md5_hash): # Delete ScreenCast Cache screen_file = os.path.join(settings.SCREEN_DIR, "screen.png") if os.path.exists(screen_file): os.remove(screen_file) # Delete Contents of Screenshot Dir screen_dir = os.path.join( settings.UPLD_DIR, md5_hash + "/screenshots-apk/" ) if os.path.isdir(screen_dir): shutil.rmtree(screen_dir) else: os.makedirs(screen_dir) # Start DM stop_capfuzz(settings.PORT) adb = getADB() is_avd = False if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_REAL_DEVICE": logger.info( "MobSF will perform Dynamic Analysis on real Android Device" ) elif settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": # adb, avd_path, reference_name, dup_name, emulator is_avd = True if not os.path.exists(settings.AVD_EMULATOR): return HttpResponseRedirect("/error/") if not refresh_avd(): return HttpResponseRedirect("/error/") else: # Refersh VM refresh_vm(settings.UUID, settings.SUUID, settings.VBOX) context = { "md5": md5_hash, "pkg": package, "lng": launcher, "title": "Start Testing", "AVD": is_avd, } template = "dynamic_analysis/start_test.html" return render(request, template, context) else: return HttpResponseRedirect("/error/") else: return HttpResponseRedirect("/error/") except: PrintException("[ERROR] DynamicAnalyzer") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def get_env(request): """Get Dynamic Analysis Environment for Android""" logger.info("Setting up Dynamic Analysis Environment") try: if request.method == "POST": data = {} md5_hash = request.POST["md5"] package = request.POST["pkg"] launcher = request.POST["lng"] if re.findall(r";|\$\(|\|\||&&", package) or re.findall( r";|\$\(|\|\||&&", launcher ): return print_n_send_error_response(request, "Possible RCE Attack", True) if re.match("^[0-9a-f]{32}$", md5_hash): base_dir = settings.BASE_DIR app_dir = os.path.join( settings.UPLD_DIR, md5_hash + "/" ) # APP DIRECTORY app_file = md5_hash + ".apk" # NEW FILENAME app_path = app_dir + app_file # APP PATH adb = getADB() if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": proxy_ip = "127.0.0.1" else: proxy_ip = settings.PROXY_IP # Proxy IP start_proxy(settings.PORT, package) # vm needs the connect function try: if not settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": connect() except Exception as exp: data = { "ready": "no", "msg": "Cannot Connect to the VM/Device.", "error": str(exp), } return HttpResponse( json.dumps(data), content_type="application/json" ) # Change True to support non-activity components install_and_run(app_path, package, launcher, True) screen_width, screen_width = get_res() data = { "ready": "yes", "screen_witdth": screen_width, "screen_height": screen_width, } return HttpResponse(json.dumps(data), content_type="application/json") else: return print_n_send_error_response(request, "Invalid Scan Hash", True) else: return print_n_send_error_response(request, "Only POST allowed", True) except: PrintException("Setting up Dynamic Analysis Environment") return print_n_send_error_response(request, "Environment Setup Failed", True)
def get_env(request): """Get Dynamic Analysis Environment for Android""" logger.info("Setting up Dynamic Analysis Environment") try: if request.method == "POST": data = {} md5_hash = request.POST["md5"] package = request.POST["pkg"] launcher = request.POST["lng"] if re.findall(r";|\$\(|\|\||&&", package) or re.findall( r";|\$\(|\|\||&&", launcher ): logger.info("[ATTACK] Possible RCE") return HttpResponseRedirect("/error/") if re.match("^[0-9a-f]{32}$", md5_hash): base_dir = settings.BASE_DIR app_dir = os.path.join( settings.UPLD_DIR, md5_hash + "/" ) # APP DIRECTORY app_file = md5_hash + ".apk" # NEW FILENAME app_path = app_dir + app_file # APP PATH adb = getADB() if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": proxy_ip = "127.0.0.1" else: proxy_ip = settings.PROXY_IP # Proxy IP start_proxy(settings.PORT, package) # vm needs the connect function try: if not settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": connect() except Exception as exp: data = { "ready": "no", "msg": "Cannot Connect to the VM/Device.", "error": str(exp), } return HttpResponse( json.dumps(data), content_type="application/json" ) # Change True to support non-activity components install_and_run(app_path, package, launcher, True) screen_width, screen_width = get_res() data = { "ready": "yes", "screen_witdth": screen_width, "screen_height": screen_width, } return HttpResponse(json.dumps(data), content_type="application/json") else: return HttpResponseRedirect("/error/") else: return HttpResponseRedirect("/error/") except: PrintException("[ERROR] Setting up Dynamic Analysis Environment") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def take_screenshot(request): """Take Screenshot""" logger.info("Taking Screenshot") try: if request.method == "POST": md5_hash = request.POST["md5"] if re.match("^[0-9a-f]{32}$", md5_hash): data = {} rand_int = random.randint(1, 1000000) base_dir = settings.BASE_DIR # make sure that list only png from this directory screen_dir = os.path.join( settings.UPLD_DIR, md5_hash + "/screenshots-apk/" ) if not os.path.exists(screen_dir): os.makedirs(screen_dir) adb_command(["screencap", "-p", "/data/local/screen.png"], True) adb_command( [ "pull", "/data/local/screen.png", screen_dir + "screenshot-" + str(rand_int) + ".png", ] ) logger.info("Screenshot Taken") data = {"screenshot": "yes"} return HttpResponse(json.dumps(data), content_type="application/json") else: return print_n_send_error_response(request, "Invalid Scan Hash", True) else: return print_n_send_error_response(request, "Only POST allowed", True) except: PrintException("Taking Screenshot") return print_n_send_error_response(request, "Error Taking Screenshot", True)
def take_screenshot(request): """Take Screenshot""" logger.info("Taking Screenshot") try: if request.method == "POST": md5_hash = request.POST["md5"] if re.match("^[0-9a-f]{32}$", md5_hash): data = {} rand_int = random.randint(1, 1000000) base_dir = settings.BASE_DIR # make sure that list only png from this directory screen_dir = os.path.join( settings.UPLD_DIR, md5_hash + "/screenshots-apk/" ) if not os.path.exists(screen_dir): os.makedirs(screen_dir) adb_command(["screencap", "-p", "/data/local/screen.png"], True) adb_command( [ "pull", "/data/local/screen.png", screen_dir + "screenshot-" + str(rand_int) + ".png", ] ) logger.info("Screenshot Taken") data = {"screenshot": "yes"} return HttpResponse(json.dumps(data), content_type="application/json") else: return HttpResponseRedirect("/error/") else: return HttpResponseRedirect("/error/") except: PrintException("[ERROR] Taking Screenshot") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def screen_cast(request): """Start or Stop ScreenCast Feature""" logger.info("Invoking ScreenCast Service in VM/Device") try: global TCP_SERVER_MODE data = {} if request.method == "POST": mode = request.POST["mode"] if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": ip_address = "10.0.2.2" else: ip_address = settings.SCREEN_IP port = str(settings.SCREEN_PORT) if mode == "on": args = [ "am", "startservice", "-a", ip_address + ":" + port, "opensecurity.screencast/.StartScreenCast", ] data = {"status": "on"} TCP_SERVER_MODE = "on" elif mode == "off": args = ["am", "force-stop", "opensecurity.screencast"] data = {"status": "off"} TCP_SERVER_MODE = "off" if mode in ["on", "off"]: try: adb_command(args, True) screen_trd = threading.Thread(target=screencast_service) screen_trd.setDaemon(True) screen_trd.start() except: PrintException("Casting Screen") data = {"status": "error"} return HttpResponse( json.dumps(data), content_type="application/json" ) else: data = {"status": "failed"} else: data = {"status": "failed"} return HttpResponse(json.dumps(data), content_type="application/json") except: PrintException("Casting Screen") return print_n_send_error_response(request, "Error Casting Screen", True)
def screen_cast(request): """Start or Stop ScreenCast Feature""" logger.info("Invoking ScreenCast Service in VM/Device") try: global TCP_SERVER_MODE data = {} if request.method == "POST": mode = request.POST["mode"] if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": ip_address = "10.0.2.2" else: ip_address = settings.SCREEN_IP port = str(settings.SCREEN_PORT) if mode == "on": args = [ "am", "startservice", "-a", ip_address + ":" + port, "opensecurity.screencast/.StartScreenCast", ] data = {"status": "on"} TCP_SERVER_MODE = "on" elif mode == "off": args = ["am", "force-stop", "opensecurity.screencast"] data = {"status": "off"} TCP_SERVER_MODE = "off" if mode in ["on", "off"]: try: adb_command(args, True) screen_trd = threading.Thread(target=screencast_service) screen_trd.setDaemon(True) screen_trd.start() except: PrintException("[ERROR] Casting Screen") data = {"status": "error"} return HttpResponse( json.dumps(data), content_type="application/json" ) else: data = {"status": "failed"} else: data = {"status": "failed"} return HttpResponse(json.dumps(data), content_type="application/json") except: PrintException("[ERROR] Casting Screen") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def clip_dump(request): """Dump Android ClipBoard""" logger.info("Starting Clipboard Dump Service in VM/Device") try: data = {} if request.method == "POST": adb = getADB() args = ["am", "startservice", "opensecurity.clipdump/.ClipDumper"] try: adb_command(args, True) data = {"status": "success"} except: PrintException("Dumping Clipboard") data = {"status": "error"} else: data = {"status": "failed"} return HttpResponse(json.dumps(data), content_type="application/json") except: PrintException("Dumping Clipboard") return print_n_send_error_response(request, "Error Dumping Clipboard", True)
def clip_dump(request): """Dump Android ClipBoard""" logger.info("Starting Clipboard Dump Service in VM/Device") try: data = {} if request.method == "POST": adb = getADB() args = ["am", "startservice", "opensecurity.clipdump/.ClipDumper"] try: adb_command(args, True) data = {"status": "success"} except: PrintException("[ERROR] Dumping Clipboard") data = {"status": "error"} else: data = {"status": "failed"} return HttpResponse(json.dumps(data), content_type="application/json") except: PrintException("[ERROR] Dumping Clipboard") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def touch(request): """Sending Touch Events""" logger.info("Sending Touch Events") try: data = {} if ( (request.method == "POST") and (is_number(request.POST["x"])) and (is_number(request.POST["y"])) ): x_axis = request.POST["x"] y_axis = request.POST["y"] adb = getADB() args = ["input", "tap", x_axis, y_axis] data = {"status": "success"} try: adb_command(args, True) except: data = {"status": "error"} PrintException("Performing Touch Action") else: data = {"status": "failed"} return HttpResponse(json.dumps(data), content_type="application/json") except: PrintException("Sending Touch Events") return print_n_send_error_response(request, "Error Sending Touch Events", True)
def touch(request): """Sending Touch Events""" logger.info("Sending Touch Events") try: data = {} if ( (request.method == "POST") and (is_number(request.POST["x"])) and (is_number(request.POST["y"])) ): x_axis = request.POST["x"] y_axis = request.POST["y"] adb = getADB() args = ["input", "tap", x_axis, y_axis] data = {"status": "success"} try: adb_command(args, True) except: data = {"status": "error"} PrintException("[ERROR] Performing Touch Action") else: data = {"status": "failed"} return HttpResponse(json.dumps(data), content_type="application/json") except: PrintException("[ERROR] Sending Touch Events") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def execute_adb(request): """Execute ADB Commands""" logger.info("Executing ADB Commands") try: if request.method == "POST": data = {} cmd = request.POST["cmd"] resp = "error" try: resp = adb_command(cmd.split(" ")) except: PrintException("Executing ADB Commands") data = {"cmd": "yes", "resp": resp.decode("utf8", "ignore")} return HttpResponse(json.dumps(data), content_type="application/json") else: return print_n_send_error_response(request, "Only POST allowed", True) except: PrintException("Executing ADB Commands") return print_n_send_error_response(request, "Error running ADB commands", True)
def execute_adb(request): """Execute ADB Commands""" logger.info("Executing ADB Commands") try: if request.method == "POST": data = {} cmd = request.POST["cmd"] resp = "error" try: resp = adb_command(cmd.split(" ")) except: PrintException("[ERROR] Executing ADB Commands") data = {"cmd": "yes", "resp": resp.decode("utf8", "ignore")} return HttpResponse(json.dumps(data), content_type="application/json") else: return HttpResponseRedirect("/error/") except: PrintException("[ERROR] Executing ADB Commands") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def mobsf_ca(request): """Install and Remove MobSF Proxy RootCA""" try: if request.method == "POST": data = {} act = request.POST["action"] rootca = get_ca_dir() adb = getADB() if act == "install": logger.info("Installing MobSF RootCA") adb_command(["push", rootca, "/data/local/tmp/" + settings.ROOT_CA]) if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": # For some reason, avd emulator does not have cp binary adb_command( [ "/data/local/tmp/busybox", "cp", "/data/local/tmp/" + settings.ROOT_CA, "/system/etc/security/cacerts/" + settings.ROOT_CA, ], True, ) adb_command( [ "chmod", "644", "/system/etc/security/cacerts/" + settings.ROOT_CA, ], True, ) else: adb_command( [ "su", "-c", "cp", "/data/local/tmp/" + settings.ROOT_CA, "/system/etc/security/cacerts/" + settings.ROOT_CA, ], True, ) adb_command( [ "su", "-c", "chmod", "644", "/system/etc/security/cacerts/" + settings.ROOT_CA, ], True, ) adb_command(["rm", "/data/local/tmp/" + settings.ROOT_CA], True) data = {"ca": "installed"} elif act == "remove": logger.info("Removing MobSF RootCA") if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": adb_command( ["rm", "/system/etc/security/cacerts/" + settings.ROOT_CA], True ) else: adb_command( [ "su", "-c", "rm", "/system/etc/security/cacerts/" + settings.ROOT_CA, ], True, ) data = {"ca": "removed"} return HttpResponse(json.dumps(data), content_type="application/json") else: return print_n_send_error_response(request, "Only POST allowed", True) except: PrintException("MobSF RootCA Handler") return print_n_send_error_response(request, "Error in RootCA Handler", True)
def mobsf_ca(request): """Install and Remove MobSF Proxy RootCA""" try: if request.method == "POST": data = {} act = request.POST["action"] rootca = get_ca_dir() adb = getADB() if act == "install": logger.info("Installing MobSF RootCA") adb_command(["push", rootca, "/data/local/tmp/" + settings.ROOT_CA]) if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": # For some reason, avd emulator does not have cp binary adb_command( [ "/data/local/tmp/busybox", "cp", "/data/local/tmp/" + settings.ROOT_CA, "/system/etc/security/cacerts/" + settings.ROOT_CA, ], True, ) adb_command( [ "chmod", "644", "/system/etc/security/cacerts/" + settings.ROOT_CA, ], True, ) else: adb_command( [ "su", "-c", "cp", "/data/local/tmp/" + settings.ROOT_CA, "/system/etc/security/cacerts/" + settings.ROOT_CA, ], True, ) adb_command( [ "su", "-c", "chmod", "644", "/system/etc/security/cacerts/" + settings.ROOT_CA, ], True, ) adb_command(["rm", "/data/local/tmp/" + settings.ROOT_CA], True) data = {"ca": "installed"} elif act == "remove": logger.info("Removing MobSF RootCA") if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": adb_command( ["rm", "/system/etc/security/cacerts/" + settings.ROOT_CA], True ) else: adb_command( [ "su", "-c", "rm", "/system/etc/security/cacerts/" + settings.ROOT_CA, ], True, ) data = {"ca": "removed"} return HttpResponse(json.dumps(data), content_type="application/json") else: return HttpResponseRedirect("/error/") except: PrintException("[ERROR] MobSF RootCA Handler") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def dump_data(request): """Downloading Application Data from Device""" logger.info("Downloading Application Data from Device") try: if request.method == "POST": data = {} package = request.POST["pkg"] md5_hash = request.POST["md5"] if re.match("^[0-9a-f]{32}$", md5_hash): if re.findall(r";|\$\(|\|\||&&", package): return print_n_send_error_response( request, "Possible RCE Attack", True ) base_dir = settings.BASE_DIR apk_dir = os.path.join(settings.UPLD_DIR, md5_hash + "/") # Let's try to close Proxy a bit early as we don't have much # control on the order of thread execution stop_capfuzz(settings.PORT) logger.info("Deleting Dump Status File") adb_command(["rm", "/sdcard/mobsec_status"], True) logger.info("Creating TAR of Application Files.") adb_command( [ "am", "startservice", "-a", package, "opensecurity.ajin.datapusher/.GetPackageLocation", ], True, ) logger.info("Waiting for TAR dump to complete...") if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_REAL_DEVICE": timeout = settings.DEVICE_TIMEOUT else: timeout = settings.VM_TIMEOUT start_time = time.time() while True: current_time = time.time() if b"MOBSEC-TAR-CREATED" in adb_command( ["cat", "/sdcard/mobsec_status"], shell=True ): break if (current_time - start_time) > timeout: logger.error("TAR Generation Failed. Process timed out.") break logger.info("Dumping Application Files from Device/VM") adb_command( [ "pull", "/data/local/" + package + ".tar", apk_dir + package + ".tar", ] ) if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": logger.info("Removing package") adb_command(["uninstall", package]) stop_avd() logger.info("Stopping ADB") adb_command(["kill-server"]) data = {"dump": "yes"} return HttpResponse(json.dumps(data), content_type="application/json") else: return print_n_send_error_response(request, "Invalid Scan Hash", True) else: return print_n_send_error_response(request, "Only POST allowed", True) except: PrintException("Downloading Application Data from Device") return print_n_send_error_response( request, "Application Data Dump from Device failed", True )
def dump_data(request): """Downloading Application Data from Device""" logger.info("Downloading Application Data from Device") try: if request.method == "POST": data = {} package = request.POST["pkg"] md5_hash = request.POST["md5"] if re.match("^[0-9a-f]{32}$", md5_hash): if re.findall(r";|\$\(|\|\||&&", package): logger.info("[ATTACK] Possible RCE") return HttpResponseRedirect("/error/") base_dir = settings.BASE_DIR apk_dir = os.path.join(settings.UPLD_DIR, md5_hash + "/") # Let's try to close Proxy a bit early as we don't have much # control on the order of thread execution stop_capfuzz(settings.PORT) logger.info("Deleting Dump Status File") adb_command(["rm", "/sdcard/mobsec_status"], True) logger.info("Creating TAR of Application Files.") adb_command( [ "am", "startservice", "-a", package, "opensecurity.ajin.datapusher/.GetPackageLocation", ], True, ) logger.info("Waiting for TAR dump to complete...") if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_REAL_DEVICE": timeout = settings.DEVICE_TIMEOUT else: timeout = settings.VM_TIMEOUT start_time = time.time() while True: current_time = time.time() if b"MOBSEC-TAR-CREATED" in adb_command( ["cat", "/sdcard/mobsec_status"], shell=True ): break if (current_time - start_time) > timeout: logger.error("TAR Generation Failed. Process timed out.") break logger.info("Dumping Application Files from Device/VM") adb_command( [ "pull", "/data/local/" + package + ".tar", apk_dir + package + ".tar", ] ) if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": logger.info("Removing package") adb_command(["uninstall", package]) stop_avd() logger.info("Stopping ADB") adb_command(["kill-server"]) data = {"dump": "yes"} return HttpResponse(json.dumps(data), content_type="application/json") else: return HttpResponseRedirect("/error/") else: return HttpResponseRedirect("/error/") except: PrintException("[ERROR] Downloading Application Data from Device") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def report(request): """Dynamic Analysis Report Generation""" logger.info("Dynamic Analysis Report Generation") try: if request.method == "GET": md5_hash = request.GET["md5"] package = request.GET["pkg"] if re.findall(r";|\$\(|\|\||&&", package): return print_n_send_error_response(request, "Possible RCE Attack") if re.match("^[0-9a-f]{32}$", md5_hash): app_dir = os.path.join( settings.UPLD_DIR, md5_hash + "/" ) # APP DIRECTORY download_dir = settings.DWD_DIR droidmon_api_loc = os.path.join(app_dir, "x_logcat.txt") api_analysis_result = api_analysis(package, droidmon_api_loc) analysis_result = run_analysis(app_dir, md5_hash, package) download(md5_hash, download_dir, app_dir, package) # Only After Download Process is Done imgs = [] act_imgs = [] act = {} expact_imgs = [] exp_act = {} if os.path.exists( os.path.join(download_dir, md5_hash + "-screenshots-apk/") ): try: imp_path = os.path.join( download_dir, md5_hash + "-screenshots-apk/" ) for img in os.listdir(imp_path): if img.endswith(".png"): if img.startswith("act"): act_imgs.append(img) elif img.startswith("expact"): expact_imgs.append(img) else: imgs.append(img) static_android_db = StaticAnalyzerAndroid.objects.filter( MD5=md5_hash ) if static_android_db.exists(): logger.info( "\nFetching Exported Activity & Activity List from DB" ) exported_act = python_list( static_android_db[0].EXPORTED_ACT ) act_desc = python_list(static_android_db[0].ACTIVITIES) if act_imgs: if len(act_imgs) == len(act_desc): act = dict(list(zip(act_imgs, act_desc))) if expact_imgs: if len(expact_imgs) == len(exported_act): exp_act = dict(list(zip(expact_imgs, exported_act))) else: logger.warning("Entry does not exists in the DB.") except: PrintException("Screenshot Sorting") context = { "md5": md5_hash, "emails": analysis_result["emails"], "urls": analysis_result["urls"], "domains": analysis_result["domains"], "clipboard": analysis_result["clipboard"], "http": analysis_result["web_data"], "xml": analysis_result["xmlfiles"], "sqlite": analysis_result["sqlite_db"], "others": analysis_result["other_files"], "imgs": imgs, "acttest": act, "expacttest": exp_act, "net": api_analysis_result["api_net"], "base64": api_analysis_result["api_base64"], "crypto": api_analysis_result["api_crypto"], "fileio": api_analysis_result["api_fileio"], "binder": api_analysis_result["api_binder"], "divinfo": api_analysis_result["api_deviceinfo"], "cntval": api_analysis_result["api_cntvl"], "sms": api_analysis_result["api_sms"], "sysprop": api_analysis_result["api_sysprop"], "dexload": api_analysis_result["api_dexloader"], "reflect": api_analysis_result["api_reflect"], "sysman": api_analysis_result["api_acntmnger"], "process": api_analysis_result["api_cmd"], "pkg": package, "title": "Dynamic Analysis", } template = "dynamic_analysis/dynamic_analysis.html" return render(request, template, context) else: return print_n_send_error_response(request, "Invalid Scan Hash") else: return print_n_send_error_response(request, "Only GET allowed") except: PrintException("Dynamic Analysis Report Generation") return print_n_send_error_response( request, "Error Geneating Dynamic Analysis Report" )
def report(request): """Dynamic Analysis Report Generation""" logger.info("Dynamic Analysis Report Generation") try: if request.method == "GET": md5_hash = request.GET["md5"] package = request.GET["pkg"] if re.findall(r";|\$\(|\|\||&&", package): logger.info("[ATTACK] Possible RCE") return HttpResponseRedirect("/error/") if re.match("^[0-9a-f]{32}$", md5_hash): app_dir = os.path.join( settings.UPLD_DIR, md5_hash + "/" ) # APP DIRECTORY download_dir = settings.DWD_DIR droidmon_api_loc = os.path.join(app_dir, "x_logcat.txt") api_analysis_result = api_analysis(package, droidmon_api_loc) analysis_result = run_analysis(app_dir, md5_hash, package) download(md5_hash, download_dir, app_dir, package) # Only After Download Process is Done imgs = [] act_imgs = [] act = {} expact_imgs = [] exp_act = {} if os.path.exists( os.path.join(download_dir, md5_hash + "-screenshots-apk/") ): try: imp_path = os.path.join( download_dir, md5_hash + "-screenshots-apk/" ) for img in os.listdir(imp_path): if img.endswith(".png"): if img.startswith("act"): act_imgs.append(img) elif img.startswith("expact"): expact_imgs.append(img) else: imgs.append(img) static_android_db = StaticAnalyzerAndroid.objects.filter( MD5=md5_hash ) if static_android_db.exists(): logger.info( "\n[INFO] Fetching Exported Activity & Activity List from DB" ) exported_act = python_list( static_android_db[0].EXPORTED_ACT ) act_desc = python_list(static_android_db[0].ACTIVITIES) if act_imgs: if len(act_imgs) == len(act_desc): act = dict(list(zip(act_imgs, act_desc))) if expact_imgs: if len(expact_imgs) == len(exported_act): exp_act = dict(list(zip(expact_imgs, exported_act))) else: logger.warning("Entry does not exists in the DB.") except: PrintException("[ERROR] Screenshot Sorting") context = { "md5": md5_hash, "emails": analysis_result["emails"], "urls": analysis_result["urls"], "domains": analysis_result["domains"], "clipboard": analysis_result["clipboard"], "http": analysis_result["web_data"], "xml": analysis_result["xmlfiles"], "sqlite": analysis_result["sqlite_db"], "others": analysis_result["other_files"], "imgs": imgs, "acttest": act, "expacttest": exp_act, "net": api_analysis_result["api_net"], "base64": api_analysis_result["api_base64"], "crypto": api_analysis_result["api_crypto"], "fileio": api_analysis_result["api_fileio"], "binder": api_analysis_result["api_binder"], "divinfo": api_analysis_result["api_deviceinfo"], "cntval": api_analysis_result["api_cntvl"], "sms": api_analysis_result["api_sms"], "sysprop": api_analysis_result["api_sysprop"], "dexload": api_analysis_result["api_dexloader"], "reflect": api_analysis_result["api_reflect"], "sysman": api_analysis_result["api_acntmnger"], "process": api_analysis_result["api_cmd"], "pkg": package, "title": "Dynamic Analysis", } template = "dynamic_analysis/dynamic_analysis.html" return render(request, template, context) else: return HttpResponseRedirect("/error/") else: return HttpResponseRedirect("/error/") except: PrintException("[ERROR] Dynamic Analysis Report Generation") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def handle_sqlite(sfile): """SQLite Dump - Readable Text""" logger.info("SQLite DB Extraction") try: data = "" con = sq.connect(sfile) cur = con.cursor() cur.execute("SELECT name FROM sqlite_master WHERE type='table';") tables = cur.fetchall() for table in tables: data += ( "\nTABLE: " + table[0] + " \n=====================================================\n" ) cur.execute("PRAGMA table_info('%s')" % table) rows = cur.fetchall() head = "" for sq_row in rows: elm_data = sq_row[1] head += elm_data + " | " data += ( head + " \n============================================" + "=========================\n" ) cur.execute("SELECT * FROM '%s'" % table) rows = cur.fetchall() for sq_row in rows: dat = "" for each_row in sq_row: dat += str(each_row) + " | " data += dat + "\n" return data except: PrintException("SQLite DB Extraction")
def handle_sqlite(sfile): """SQLite Dump - Readable Text""" logger.info("SQLite DB Extraction") try: data = "" con = sq.connect(sfile) cur = con.cursor() cur.execute("SELECT name FROM sqlite_master WHERE type='table';") tables = cur.fetchall() for table in tables: data += ( "\nTABLE: " + table[0] + " \n=====================================================\n" ) cur.execute("PRAGMA table_info('%s')" % table) rows = cur.fetchall() head = "" for sq_row in rows: elm_data = sq_row[1] head += elm_data + " | " data += ( head + " \n============================================" + "=========================\n" ) cur.execute("SELECT * FROM '%s'" % table) rows = cur.fetchall() for sq_row in rows: dat = "" for each_row in sq_row: dat += str(each_row) + " | " data += dat + "\n" return data except: PrintException("[ERROR] SQLite DB Extraction")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def view(request): """View File""" logger.info("Viewing File") try: typ = "" fil = "" rtyp = "" dat = "" if re.match("^[0-9a-f]{32}$", request.GET["md5"]): fil = request.GET["file"] md5_hash = request.GET["md5"] typ = request.GET["type"] src = os.path.join(settings.UPLD_DIR, md5_hash + "/DYNAMIC_DeviceData/") sfile = os.path.join(src, fil) # Prevent Directory Traversal Attacks if ("../" in fil) or ("%2e%2e" in fil) or (".." in fil) or ("%252e" in fil): return print_n_send_error_response( request, "Path Traversal Attack Detected" ) else: with io.open(sfile, mode="r", encoding="utf8", errors="ignore") as flip: dat = flip.read() if (fil.endswith(".xml")) and (typ == "xml"): rtyp = "xml" elif typ == "db": dat = handle_sqlite(sfile) rtyp = "asciidoc" elif typ == "others": rtyp = "asciidoc" else: return print_n_send_error_response( request, "File Type not supported" ) context = { "title": escape(ntpath.basename(fil)), "file": escape(ntpath.basename(fil)), "dat": dat, "type": rtyp, } template = "general/view.html" return render(request, template, context) else: return print_n_send_error_response(request, "Invalid Scan Hash") except: PrintException("Viewing File") return print_n_send_error_response(request, "ERROR Viewing File")
def view(request): """View File""" logger.info("Viewing File") try: typ = "" fil = "" rtyp = "" dat = "" if re.match("^[0-9a-f]{32}$", request.GET["md5"]): fil = request.GET["file"] md5_hash = request.GET["md5"] typ = request.GET["type"] src = os.path.join(settings.UPLD_DIR, md5_hash + "/DYNAMIC_DeviceData/") sfile = os.path.join(src, fil) # Prevent Directory Traversal Attacks if ("../" in fil) or ("%2e%2e" in fil) or (".." in fil) or ("%252e" in fil): return HttpResponseRedirect("/error/") else: with io.open(sfile, mode="r", encoding="utf8", errors="ignore") as flip: dat = flip.read() if (fil.endswith(".xml")) and (typ == "xml"): rtyp = "xml" elif typ == "db": dat = handle_sqlite(sfile) rtyp = "asciidoc" elif typ == "others": rtyp = "asciidoc" else: return HttpResponseRedirect("/error/") context = { "title": escape(ntpath.basename(fil)), "file": escape(ntpath.basename(fil)), "dat": dat, "type": rtyp, } template = "general/view.html" return render(request, template, context) else: return HttpResponseRedirect("/error/") except: PrintException("[ERROR] Viewing File") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def capfuzz_start(request): """Start CapFuzz UI""" logger.info("Starting CapFuzz Web UI") try: stop_capfuzz(settings.PORT) start_fuzz_ui(settings.PORT) time.sleep(3) logger.info("CapFuzz UI Started") if request.GET["project"]: project = request.GET["project"] else: project = "" return HttpResponseRedirect( "http://localhost:" + str(settings.PORT) + "/dashboard/" + project ) except: PrintException("Starting CapFuzz Web UI") return print_n_send_error_response(request, "Error Starting CapFuzz UI")
def capfuzz_start(request): """Start CapFuzz UI""" logger.info("Starting CapFuzz Web UI") try: stop_capfuzz(settings.PORT) start_fuzz_ui(settings.PORT) time.sleep(3) logger.info("CapFuzz UI Started") if request.GET["project"]: project = request.GET["project"] else: project = "" return HttpResponseRedirect( "http://localhost:" + str(settings.PORT) + "/dashboard/" + project ) except: PrintException("[ERROR] Starting CapFuzz Web UI") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def screencast_service(): """Start or Stop ScreenCast Services""" global TCP_SERVER_MODE logger.info("ScreenCast Service Status: " + TCP_SERVER_MODE) try: screen_dir = settings.SCREEN_DIR if not os.path.exists(screen_dir): os.makedirs(screen_dir) screen_socket = socket.socket() if TCP_SERVER_MODE == "on": screen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": addr = ("127.0.0.1", settings.SCREEN_PORT) else: addr = (settings.SCREEN_IP, settings.SCREEN_PORT) screen_socket.bind(addr) screen_socket.listen(10) while TCP_SERVER_MODE == "on": screens, address = screen_socket.accept() logger.info("Got Connection from: %s", address[0]) if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_REAL_DEVICE": ip_address = settings.DEVICE_IP else: ip_address = settings.VM_IP if address[0] in [ip_address, "127.0.0.1"]: # Very Basic Check to ensure that only MobSF VM/Device/Emulator # is allowed to connect to MobSF ScreenCast Service. with open(screen_dir + "screen.png", "wb") as flip: while True: data = screens.recv(1024) if not data: break flip.write(data) else: logger.warning( "\n[ATTACK] An unknown client :" + address[0] + " is trying " + "to make a connection with MobSF ScreenCast Service!" ) elif TCP_SERVER_MODE == "off": screen_socket.close() except: screen_socket.close() PrintException("ScreenCast Server")
def screencast_service(): """Start or Stop ScreenCast Services""" global TCP_SERVER_MODE logger.info("ScreenCast Service Status: " + TCP_SERVER_MODE) try: screen_dir = settings.SCREEN_DIR if not os.path.exists(screen_dir): os.makedirs(screen_dir) screen_socket = socket.socket() if TCP_SERVER_MODE == "on": screen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": addr = ("127.0.0.1", settings.SCREEN_PORT) else: addr = (settings.SCREEN_IP, settings.SCREEN_PORT) screen_socket.bind(addr) screen_socket.listen(10) while TCP_SERVER_MODE == "on": screens, address = screen_socket.accept() logger.info("Got Connection from: %s", address[0]) if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_REAL_DEVICE": ip_address = settings.DEVICE_IP else: ip_address = settings.VM_IP if address[0] in [ip_address, "127.0.0.1"]: # Very Basic Check to ensure that only MobSF VM/Device/Emulator # is allowed to connect to MobSF ScreenCast Service. with open(screen_dir + "screen.png", "wb") as flip: while True: data = screens.recv(1024) if not data: break flip.write(data) else: logger.info( "\n[ATTACK] An unknown client :" + address[0] + " is trying " + "to make a connection with MobSF ScreenCast Service!" ) elif TCP_SERVER_MODE == "off": screen_socket.close() except: screen_socket.close() PrintException("[ERROR] ScreenCast Server")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def get_res(): """Get Screen Resolution or Device or VM""" logger.info("Getting Screen Resolution") try: adb = getADB() resp = subprocess.check_output( [adb, "-s", get_identifier(), "shell", "dumpsys", "window"] ) resp = resp.decode("utf-8").split("\n") res = "" for line in resp: if "mUnrestrictedScreen" in line: res = line break res = res.split("(0,0)")[1] res = res.strip() res = res.split("x") if len(res) == 2: return res[0], res[1] # width, height return "", "" except: PrintException("Getting Screen Resolution") return "", ""
def get_res(): """Get Screen Resolution or Device or VM""" logger.info("Getting Screen Resolution") try: adb = getADB() resp = subprocess.check_output( [adb, "-s", get_identifier(), "shell", "dumpsys", "window"] ) resp = resp.decode("utf-8").split("\n") res = "" for line in resp: if "mUnrestrictedScreen" in line: res = line break res = res.split("(0,0)")[1] res = res.strip() res = res.split("x") if len(res) == 2: return res[0], res[1] # width, height return "", "" except: PrintException("[ERROR] Getting Screen Resolution") return "", ""
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def get_identifier(): """Get Device Type""" try: if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_REAL_DEVICE": return settings.DEVICE_IP + ":" + str(settings.DEVICE_ADB_PORT) elif settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": return "emulator-" + str(settings.AVD_ADB_PORT) else: return settings.VM_IP + ":" + str(settings.VM_ADB_PORT) except: PrintException("Getting ADB Connection Identifier for Device/VM")
def get_identifier(): """Get Device Type""" try: if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_REAL_DEVICE": return settings.DEVICE_IP + ":" + str(settings.DEVICE_ADB_PORT) elif settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD": return "emulator-" + str(settings.AVD_ADB_PORT) else: return settings.VM_IP + ":" + str(settings.VM_ADB_PORT) except: PrintException("[ERROR] Getting ADB Connection Identifier for Device/VM")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def adb_command(cmd_list, shell=False, silent=False): emulator = get_identifier() adb = getADB() args = [adb, "-s", emulator] if shell: args += ["shell"] args += cmd_list try: result = subprocess.check_output(args) return result except: if not silent: PrintException("Running ADB Command") return None
def adb_command(cmd_list, shell=False, silent=False): emulator = get_identifier() adb = getADB() args = [adb, "-s", emulator] if shell: args += ["shell"] args += cmd_list try: result = subprocess.check_output(args) return result except: if not silent: PrintException("[ERROR] adb_command") return None
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def connect(): """Connect to VM/Device""" logger.info("Connecting to VM/Device") adb = getADB() subprocess.call([adb, "kill-server"]) subprocess.call([adb, "start-server"]) logger.info("ADB Started") wait(5) logger.info("Connecting to VM/Device") out = subprocess.check_output([adb, "connect", get_identifier()]) if b"unable to connect" in out: raise ValueError( "ERROR Connecting to VM/Device. ", out.decode("utf-8").replace("\n", "") ) try: subprocess.call([adb, "-s", get_identifier(), "wait-for-device"]) logger.info("Mounting") if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_REAL_DEVICE": adb_command(["su", "-c", "mount", "-o", "rw,remount,rw", "/system"], True) else: adb_command(["su", "-c", "mount", "-o", "rw,remount,rw", "/system"], True) # This may not work for VMs other than the default MobSF VM adb_command( [ "mount", "-o", "rw,remount", "-t", "rfs", "/dev/block/sda6", "/system", ], True, ) except: PrintException("Connecting to VM/Device")
def connect(): """Connect to VM/Device""" logger.info("Connecting to VM/Device") adb = getADB() subprocess.call([adb, "kill-server"]) subprocess.call([adb, "start-server"]) logger.info("ADB Started") wait(5) logger.info("Connecting to VM/Device") out = subprocess.check_output([adb, "connect", get_identifier()]) if b"unable to connect" in out: raise ValueError( "ERROR Connecting to VM/Device. ", out.decode("utf-8").replace("\n", "") ) try: subprocess.call([adb, "-s", get_identifier(), "wait-for-device"]) logger.info("Mounting") if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_REAL_DEVICE": adb_command(["su", "-c", "mount", "-o", "rw,remount,rw", "/system"], True) else: adb_command(["su", "-c", "mount", "-o", "rw,remount,rw", "/system"], True) # This may not work for VMs other than the default MobSF VM adb_command( [ "mount", "-o", "rw,remount", "-t", "rfs", "/dev/block/sda6", "/system", ], True, ) except: PrintException("[ERROR] Connecting to VM/Device")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def install_and_run(apk_path, package, launcher, is_activity): """Install APK and Run it""" logger.info("Starting App for Dynamic Analysis") try: adb = getADB() logger.info("Installing APK") adb_command(["install", "-r", apk_path]) if is_activity: run_app = package + "/" + launcher logger.info("Launching APK Main Activity") adb_command(["am", "start", "-n", run_app], True) else: logger.info("App Doesn't have a Main Activity") # Handle Service or Give Choice to Select in Future. logger.info("Testing Environment is Ready!") except: PrintException("Starting App for Dynamic Analysis")
def install_and_run(apk_path, package, launcher, is_activity): """Install APK and Run it""" logger.info("Starting App for Dynamic Analysis") try: adb = getADB() logger.info("Installing APK") adb_command(["install", "-r", apk_path]) if is_activity: run_app = package + "/" + launcher logger.info("Launching APK Main Activity") adb_command(["am", "start", "-n", run_app], True) else: logger.info("App Doesn't have a Main Activity") # Handle Service or Give Choice to Select in Future. logger.info("Testing Environment is Ready!") except: PrintException("[ERROR] Starting App for Dynamic Analysis")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def refresh_vm(uuid, snapshot_uuid, vbox_exe): """Refresh VirtualBox based VMs""" logger.info("Refreshing MobSF VM") try: if not vbox_exe: logger.error( "VirtualBox not found, Manually set VBOXMANAGE_BINARY in settings.py" ) # Close VM args = [vbox_exe, "controlvm", uuid, "poweroff"] subprocess.call(args) logger.info("VM Closed") time.sleep(3) # Restore Snapshot args = [vbox_exe, "snapshot", uuid, "restore", snapshot_uuid] subprocess.call(args) logger.info("VM Restore Snapshot") # Start Fresh VM args = [vbox_exe, "startvm", uuid] if settings.VBOX_HEADLESS: args += ["--type", "headless"] subprocess.call(args) logger.info("VM Starting") except: PrintException("Refreshing MobSF VM")
def refresh_vm(uuid, snapshot_uuid, vbox_exe): """Refresh VirtualBox based VMs""" logger.info("Refreshing MobSF VM") try: if not vbox_exe: logger.error( "VirtualBox not found, Manually set VBOXMANAGE_BINARY in settings.py" ) # Close VM args = [vbox_exe, "controlvm", uuid, "poweroff"] subprocess.call(args) logger.info("VM Closed") time.sleep(3) # Restore Snapshot args = [vbox_exe, "snapshot", uuid, "restore", snapshot_uuid] subprocess.call(args) logger.info("VM Restore Snapshot") # Start Fresh VM args = [vbox_exe, "startvm", uuid] if settings.VBOX_HEADLESS: args += ["--type", "headless"] subprocess.call(args) logger.info("VM Starting") except: PrintException("[ERROR] Refreshing MobSF VM")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def api_key(): """Print REST API Key""" if os.environ.get("MOBSF_API_KEY"): logger.info("\nAPI Key read from environment variable") return os.environ["MOBSF_API_KEY"] secret_file = os.path.join(settings.MobSF_HOME, "secret") if isFileExists(secret_file): try: _api_key = open(secret_file).read().strip() return gen_sha256_hash(_api_key) except Exception: PrintException("Cannot Read API Key")
def api_key(): """Print REST API Key""" if os.environ.get("MOBSF_API_KEY"): logger.info("\nAPI Key read from environment variable") return os.environ["MOBSF_API_KEY"] secret_file = os.path.join(settings.MobSF_HOME, "secret") if isFileExists(secret_file): try: _api_key = open(secret_file).read().strip() return gen_sha256_hash(_api_key) except Exception: PrintException("[ERROR] Cannot Read API Key")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def check_update(): try: logger.info("Checking for Update.") github_url = "https://raw.githubusercontent.com/MobSF/Mobile-Security-Framework-MobSF/master/MobSF/settings.py" try: proxies, verify = upstream_proxy("https") except Exception: PrintException("Setting upstream proxy") response = requests.get(github_url, timeout=5, proxies=proxies, verify=verify) html = str(response.text).split("\n") for line in html: if line.startswith("MOBSF_VER"): line = line.replace("MOBSF_VER", "").replace('"', "") line = line.replace("=", "").strip() if line != settings.MOBSF_VER: logger.warning( "A new version of MobSF is available, Please update from master branch or check " "for new releases." ) else: logger.info("No updates available.") except requests.exceptions.HTTPError as err: logger.warning("\nCannot check for updates.. No Internet Connection Found.") return except: PrintException("Cannot Check for updates.")
def check_update(): try: logger.info("Checking for Update.") github_url = "https://raw.githubusercontent.com/MobSF/Mobile-Security-Framework-MobSF/master/MobSF/settings.py" try: proxies, verify = upstream_proxy("https") except Exception: PrintException("[ERROR] Setting upstream proxy") response = requests.get(github_url, timeout=5, proxies=proxies, verify=verify) html = str(response.text).split("\n") for line in html: if line.startswith("MOBSF_VER"): line = line.replace("MOBSF_VER", "").replace('"', "") line = line.replace("=", "").strip() if line != settings.MOBSF_VER: logger.warning( "A new version of MobSF is available, Please update from master branch or check " "for new releases." ) else: logger.info("No updates available.") except requests.exceptions.HTTPError as err: logger.warning( "\n[WARN] Cannot check for updates.. No Internet Connection Found." ) return except: PrintException("[ERROR] Cannot Check for updates.")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def createUserConfig(MobSF_HOME): try: CONFIG_PATH = os.path.join(MobSF_HOME, "config.py") if isFileExists(CONFIG_PATH) == False: SAMPLE_CONF = os.path.join(settings.BASE_DIR, "MobSF/settings.py") with io.open(SAMPLE_CONF, mode="r", encoding="utf8", errors="ignore") as f: dat = f.readlines() CONFIG = list() add = False for line in dat: if "^CONFIG-START^" in line: add = True if "^CONFIG-END^" in line: break if add: CONFIG.append(line.lstrip()) CONFIG.pop(0) COMFIG_STR = "".join(CONFIG) with io.open(CONFIG_PATH, mode="w", encoding="utf8", errors="ignore") as f: f.write(COMFIG_STR) except: PrintException("Cannot create config file")
def createUserConfig(MobSF_HOME): try: CONFIG_PATH = os.path.join(MobSF_HOME, "config.py") if isFileExists(CONFIG_PATH) == False: SAMPLE_CONF = os.path.join(settings.BASE_DIR, "MobSF/settings.py") with io.open(SAMPLE_CONF, mode="r", encoding="utf8", errors="ignore") as f: dat = f.readlines() CONFIG = list() add = False for line in dat: if "^CONFIG-START^" in line: add = True if "^CONFIG-END^" in line: break if add: CONFIG.append(line.lstrip()) CONFIG.pop(0) COMFIG_STR = "".join(CONFIG) with io.open(CONFIG_PATH, mode="w", encoding="utf8", errors="ignore") as f: f.write(COMFIG_STR) except: PrintException("[ERROR] Cannot create config file")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def getMobSFHome(useHOME): try: MobSF_HOME = "" if useHOME: MobSF_HOME = os.path.join(os.path.expanduser("~"), ".MobSF") # MobSF Home Directory if not os.path.exists(MobSF_HOME): os.makedirs(MobSF_HOME) createUserConfig(MobSF_HOME) else: MobSF_HOME = settings.BASE_DIR # Logs Directory LOG_DIR = os.path.join(MobSF_HOME, "logs/") if not os.path.exists(LOG_DIR): os.makedirs(LOG_DIR) # Certs Directory CERT_DIR = os.path.join(LOG_DIR, "certs/") if not os.path.exists(CERT_DIR): os.makedirs(CERT_DIR) # Download Directory DWD_DIR = os.path.join(MobSF_HOME, "downloads/") if not os.path.exists(DWD_DIR): os.makedirs(DWD_DIR) # Screenshot Directory SCREEN_DIR = os.path.join(DWD_DIR, "screen/") if not os.path.exists(SCREEN_DIR): os.makedirs(SCREEN_DIR) # Upload Directory UPLD_DIR = os.path.join(MobSF_HOME, "uploads/") if not os.path.exists(UPLD_DIR): os.makedirs(UPLD_DIR) return MobSF_HOME except: PrintException("Creating MobSF Home Directory")
def getMobSFHome(useHOME): try: MobSF_HOME = "" if useHOME: MobSF_HOME = os.path.join(os.path.expanduser("~"), ".MobSF") # MobSF Home Directory if not os.path.exists(MobSF_HOME): os.makedirs(MobSF_HOME) createUserConfig(MobSF_HOME) else: MobSF_HOME = settings.BASE_DIR # Logs Directory LOG_DIR = os.path.join(MobSF_HOME, "logs/") if not os.path.exists(LOG_DIR): os.makedirs(LOG_DIR) # Certs Directory CERT_DIR = os.path.join(LOG_DIR, "certs/") if not os.path.exists(CERT_DIR): os.makedirs(CERT_DIR) # Download Directory DWD_DIR = os.path.join(MobSF_HOME, "downloads/") if not os.path.exists(DWD_DIR): os.makedirs(DWD_DIR) # Screenshot Directory SCREEN_DIR = os.path.join(DWD_DIR, "screen/") if not os.path.exists(SCREEN_DIR): os.makedirs(SCREEN_DIR) # Upload Directory UPLD_DIR = os.path.join(MobSF_HOME, "uploads/") if not os.path.exists(UPLD_DIR): os.makedirs(UPLD_DIR) return MobSF_HOME except: PrintException("[ERROR] Creating MobSF Home Directory")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def make_migrations(base_dir): """Create Database Migrations""" try: python = get_python() manage = os.path.join(base_dir, "manage.py") args = [python, manage, "makemigrations"] subprocess.call(args) args = [python, manage, "makemigrations", "StaticAnalyzer"] subprocess.call(args) except: PrintException("Cannot Make Migrations")
def make_migrations(base_dir): """Create Database Migrations""" try: python = get_python() manage = os.path.join(base_dir, "manage.py") args = [python, manage, "makemigrations"] subprocess.call(args) args = [python, manage, "makemigrations", "StaticAnalyzer"] subprocess.call(args) except: PrintException("[ERROR] Cannot Make Migrations")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def migrate(BASE_DIR): """Migrate Database""" try: python = get_python() manage = os.path.join(BASE_DIR, "manage.py") args = [python, manage, "migrate"] subprocess.call(args) except: PrintException("Cannot Migrate")
def migrate(BASE_DIR): """Migrate Database""" try: python = get_python() manage = os.path.join(BASE_DIR, "manage.py") args = [python, manage, "migrate"] subprocess.call(args) except: PrintException("[ERROR] Cannot Migrate")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def kali_fix(BASE_DIR): try: if platform.system() == "Linux" and platform.dist()[0] == "Kali": fix_path = os.path.join(BASE_DIR, "scripts/kali_fix.sh") subprocess.call(["chmod", "a+x", fix_path]) subprocess.call([fix_path], shell=True) except: PrintException("Cannot run Kali Fix")
def kali_fix(BASE_DIR): try: if platform.system() == "Linux" and platform.dist()[0] == "Kali": fix_path = os.path.join(BASE_DIR, "scripts/kali_fix.sh") subprocess.call(["chmod", "a+x", fix_path]) subprocess.call([fix_path], shell=True) except: PrintException("[ERROR] Cannot run Kali Fix")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def FindVbox(debug=False): try: if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_VM": if len(settings.VBOXMANAGE_BINARY) > 0 and isFileExists( settings.VBOXMANAGE_BINARY ): return settings.VBOXMANAGE_BINARY if platform.system() == "Windows": # Path to VBoxManage.exe vbox_path = [ "C:\Program Files\Oracle\VirtualBox\VBoxManage.exe", "C:\Program Files (x86)\Oracle\VirtualBox\VBoxManage.exe", ] for path in vbox_path: if os.path.isfile(path): return path else: # Path to VBoxManage in Linux/Mac vbox_path = ["/usr/bin/VBoxManage", "/usr/local/bin/VBoxManage"] for path in vbox_path: if os.path.isfile(path): return path if debug: logger.warning("Could not find VirtualBox path.") except: if debug: PrintException("Cannot find VirtualBox path.")
def FindVbox(debug=False): try: if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_VM": if len(settings.VBOXMANAGE_BINARY) > 0 and isFileExists( settings.VBOXMANAGE_BINARY ): return settings.VBOXMANAGE_BINARY if platform.system() == "Windows": # Path to VBoxManage.exe vbox_path = [ "C:\Program Files\Oracle\VirtualBox\VBoxManage.exe", "C:\Program Files (x86)\Oracle\VirtualBox\VBoxManage.exe", ] for path in vbox_path: if os.path.isfile(path): return path else: # Path to VBoxManage in Linux/Mac vbox_path = ["/usr/bin/VBoxManage", "/usr/local/bin/VBoxManage"] for path in vbox_path: if os.path.isfile(path): return path if debug: logger.warning("Could not find VirtualBox path.") except: if debug: PrintException("[ERROR] Cannot find VirtualBox path.")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def FindJava(debug=False): """Find Java""" # Maintain JDK Version java_versions = "1.7|1.8|1.9|2.0|2.1|2.2|2.3|8|9|10|11" """ This code is needed because some people are not capable of setting java path :-( """ win_java_paths = [ "C:/Program Files/Java/", "C:/Program Files (x86)/Java/", "D:/Program Files/Java/", "D:/Program Files (x86)/Java/", "E:/Program Files/Java/", "E:/Program Files (x86)/Java/", "F:/Program Files/Java/", "F:/Program Files (x86)/Java/", "G:/Program Files/Java/", "G:/Program Files (x86)/Java/", "H:/Program Files/Java/", "H:/Program Files (x86)/Java/", "I:/Program Files/Java/", "I:/Program Files (x86)/Java/", ] try: err_msg1 = "Oracle JDK 1.7 or above is not found!" if isDirExists(settings.JAVA_DIRECTORY): if settings.JAVA_DIRECTORY.endswith("/"): return settings.JAVA_DIRECTORY elif settings.JAVA_DIRECTORY.endswith("\\"): return settings.JAVA_DIRECTORY else: return settings.JAVA_DIRECTORY + "/" elif platform.system() == "Windows": if debug: logger.info("Finding JDK Location in Windows....") # JDK 7 jdk1.7.0_17/bin/ for java_path in win_java_paths: if os.path.isdir(java_path): for dirname in os.listdir(java_path): if "jdk" in dirname: win_java_path = java_path + dirname + "/bin/" args = [win_java_path + "java", "-version"] dat = RunProcess(args) if "java" in dat: if debug: logger.info("Oracle Java JDK is installed!") return win_java_path for env in ["JDK_HOME", "JAVA_HOME"]: java_home = os.environ.get(env) if java_home and os.path.isdir(java_home): win_java_path = java_home + "/bin/" args = [win_java_path + "java", "-version"] dat = RunProcess(args) if "java" in dat: if debug: logger.info("Oracle Java is installed!") return win_java_path if debug: logger.info(err_msg1) return "java" else: if debug: logger.info("Finding JDK Location in Linux/MAC....") # Check in Environment Variables for env in ["JDK_HOME", "JAVA_HOME"]: java_home = os.environ.get(env) if java_home and os.path.isdir(java_home): lm_java_path = java_home + "/bin/" args = [lm_java_path + "java", "-version"] dat = RunProcess(args) if "oracle" in dat: if debug: logger.info("Oracle Java is installed!") return lm_java_path mac_linux_java_dir = "/usr/bin/" args = [mac_linux_java_dir + "java"] dat = RunProcess(args) if "oracle" in dat: args = [mac_linux_java_dir + "java", "-version"] dat = RunProcess(args) f_line = dat.split("\n")[0] if re.findall(java_versions, f_line): if debug: logger.info("JDK 1.7 or above is available") return mac_linux_java_dir else: err_msg = "Please install Oracle JDK 1.7 or above" if debug: logger.error(err_msg) return "java" else: args = [mac_linux_java_dir + "java", "-version"] dat = RunProcess(args) f_line = dat.split("\n")[0] if re.findall(java_versions, f_line): if debug: logger.info("JDK 1.7 or above is available") return mac_linux_java_dir else: err_msg = "Please install Oracle JDK 1.7 or above" if debug: logger.error(err_msg) return "java" except: if debug: PrintException("Oracle Java (JDK >=1.7) is not found!") return "java"
def FindJava(debug=False): """Find Java""" # Maintain JDK Version java_versions = "1.7|1.8|1.9|2.0|2.1|2.2|2.3|8|9|10|11" """ This code is needed because some people are not capable of setting java path :-( """ win_java_paths = [ "C:/Program Files/Java/", "C:/Program Files (x86)/Java/", "D:/Program Files/Java/", "D:/Program Files (x86)/Java/", "E:/Program Files/Java/", "E:/Program Files (x86)/Java/", "F:/Program Files/Java/", "F:/Program Files (x86)/Java/", "G:/Program Files/Java/", "G:/Program Files (x86)/Java/", "H:/Program Files/Java/", "H:/Program Files (x86)/Java/", "I:/Program Files/Java/", "I:/Program Files (x86)/Java/", ] try: err_msg1 = "[ERROR] Oracle JDK 1.7 or above is not found!" if isDirExists(settings.JAVA_DIRECTORY): if settings.JAVA_DIRECTORY.endswith("/"): return settings.JAVA_DIRECTORY elif settings.JAVA_DIRECTORY.endswith("\\"): return settings.JAVA_DIRECTORY else: return settings.JAVA_DIRECTORY + "/" elif platform.system() == "Windows": if debug: logger.info("Finding JDK Location in Windows....") # JDK 7 jdk1.7.0_17/bin/ for java_path in win_java_paths: if os.path.isdir(java_path): for dirname in os.listdir(java_path): if "jdk" in dirname: win_java_path = java_path + dirname + "/bin/" args = [win_java_path + "java", "-version"] dat = RunProcess(args) if "java" in dat: if debug: logger.info("Oracle Java JDK is installed!") return win_java_path for env in ["JDK_HOME", "JAVA_HOME"]: java_home = os.environ.get(env) if java_home and os.path.isdir(java_home): win_java_path = java_home + "/bin/" args = [win_java_path + "java", "-version"] dat = RunProcess(args) if "java" in dat: if debug: logger.info("Oracle Java is installed!") return win_java_path if debug: logger.info(err_msg1) return "java" else: if debug: logger.info("Finding JDK Location in Linux/MAC....") # Check in Environment Variables for env in ["JDK_HOME", "JAVA_HOME"]: java_home = os.environ.get(env) if java_home and os.path.isdir(java_home): lm_java_path = java_home + "/bin/" args = [lm_java_path + "java", "-version"] dat = RunProcess(args) if "oracle" in dat: if debug: logger.info("Oracle Java is installed!") return lm_java_path mac_linux_java_dir = "/usr/bin/" args = [mac_linux_java_dir + "java"] dat = RunProcess(args) if "oracle" in dat: args = [mac_linux_java_dir + "java", "-version"] dat = RunProcess(args) f_line = dat.split("\n")[0] if re.findall(java_versions, f_line): if debug: logger.info("JDK 1.7 or above is available") return mac_linux_java_dir else: err_msg = "[ERROR] Please install Oracle JDK 1.7 or above" if debug: logger.error(Color.BOLD + Color.RED + err_msg + Color.END) return "java" else: args = [mac_linux_java_dir + "java", "-version"] dat = RunProcess(args) f_line = dat.split("\n")[0] if re.findall(java_versions, f_line): if debug: logger.info("JDK 1.7 or above is available") return mac_linux_java_dir else: err_msg = "Please install Oracle JDK 1.7 or above" if debug: logger.error(Color.BOLD + Color.RED + err_msg + Color.END) return "java" except: if debug: PrintException("[ERROR] Oracle Java (JDK >=1.7) is not found!") return "java"
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def RunProcess(args): try: proc = subprocess.Popen( args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) dat = "" while True: line = proc.stdout.readline() if not line: break dat += str(line) return dat except: PrintException("Finding Java path - Cannot Run Process") return ""
def RunProcess(args): try: proc = subprocess.Popen( args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) dat = "" while True: line = proc.stdout.readline() if not line: break dat += str(line) return dat except: PrintException("[ERROR] Finding Java path - Cannot Run Process") return ""
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def PrintException(msg, web=False): """Print Exception verbose""" exc_type, exc_obj, tb = sys.exc_info() f = tb.tb_frame lineno = tb.tb_lineno filename = f.f_code.co_filename linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) dat = ( "\n" + msg + ' ({0}, LINE {1} "{2}"): {3}'.format(filename, lineno, line.strip(), exc_obj) ) if web: logger.warning(dat) else: logger.error(dat)
def PrintException(msg, web=False): try: LOGPATH = settings.LOG_DIR except: LOGPATH = os.path.join(settings.BASE_DIR, "logs/") if not os.path.exists(LOGPATH): os.makedirs(LOGPATH) exc_type, exc_obj, tb = sys.exc_info() f = tb.tb_frame lineno = tb.tb_lineno filename = f.f_code.co_filename linecache.checkcache(filename) line = linecache.getline(filename, lineno, f.f_globals) ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S") dat = ( "\n[" + st + "]\n" + msg + ' ({0}, LINE {1} "{2}"): {3}'.format(filename, lineno, line.strip(), exc_obj) ) if platform.system() == "Windows": logger.error(dat) else: if web: logger.error(Color.BOLD + Color.ORANGE + dat + Color.END) else: logger.error(Color.BOLD + Color.RED + dat + Color.END) with open(LOGPATH + "MobSF.log", "a") as f: f.write(dat)
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def print_n_send_error_response(request, msg, api=False, exp="Error Description"): """Print and log errors""" logger.error(msg) if api: api_response = {"error": msg} return api_response else: context = {"title": "Error", "exp": exp, "doc": msg} template = "general/error.html" return render(request, template, context, status=500)
def print_n_send_error_response(request, msg, api, exp="Error Description"): """Print and log errors""" logger.error(Color.BOLD + Color.RED + "[ERROR] " + msg + Color.END) time_stamp = time.time() formatted_tms = datetime.datetime.fromtimestamp(time_stamp).strftime( "%Y-%m-%d %H:%M:%S" ) data = "\n[" + formatted_tms + "]\n[ERROR] " + msg try: log_path = settings.LOG_DIR except: log_path = os.path.join(settings.BASE_DIR, "logs/") if not os.path.exists(log_path): os.makedirs(log_path) with open(os.path.join(log_path, "MobSF.log"), "a") as flip: flip.write(data) if api: api_response = {"error": msg} return api_response else: context = {"title": "Error", "exp": exp, "doc": msg} template = "general/error.html" return render(request, template, context, status=500)
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def isInternetAvailable(): try: proxies, verify = upstream_proxy("https") except: PrintException("Setting upstream proxy") try: requests.get( "https://www.google.com", timeout=5, proxies=proxies, verify=verify ) return True except requests.exceptions.HTTPError as err: try: requests.get( "https://www.baidu.com/", timeout=5, proxies=proxies, verify=verify ) return True except requests.exceptions.HTTPError as err1: return False return False
def isInternetAvailable(): try: proxies, verify = upstream_proxy("https") except: PrintException("[ERROR] Setting upstream proxy") try: requests.get( "https://www.google.com", timeout=5, proxies=proxies, verify=verify ) return True except requests.exceptions.HTTPError as err: try: requests.get( "https://www.baidu.com/", timeout=5, proxies=proxies, verify=verify ) return True except requests.exceptions.HTTPError as err1: return False return False
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def zipdir(path, zip_file): """Zip a directory.""" try: logger.info("Zipping") # pylint: disable=unused-variable # Needed by os.walk for root, _sub_dir, files in os.walk(path): for file_name in files: zip_file.write(os.path.join(root, file_name)) except: PrintException("Zipping")
def zipdir(path, zip_file): """Zip a directory.""" try: logger.info("Zipping") # pylint: disable=unused-variable # Needed by os.walk for root, _sub_dir, files in os.walk(path): for file_name in files: zip_file.write(os.path.join(root, file_name)) except: PrintException("[ERROR] Zipping")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def getADB(): """Get ADB binary path""" try: if len(settings.ADB_BINARY) > 0 and isFileExists(settings.ADB_BINARY): return settings.ADB_BINARY else: adb = "adb" if platform.system() == "Darwin": adb_dir = os.path.join(settings.TOOLS_DIR, "adb/mac/") subprocess.call(["chmod", "777", adb_dir]) adb = os.path.join(settings.TOOLS_DIR, "adb/mac/adb") elif platform.system() == "Linux": adb_dir = os.path.join(settings.TOOLS_DIR, "adb/linux/") subprocess.call(["chmod", "777", adb_dir]) adb = os.path.join(settings.TOOLS_DIR, "adb/linux/adb") elif platform.system() == "Windows": adb = os.path.join(settings.TOOLS_DIR, "adb/windows/adb.exe") return adb except: PrintException("Getting ADB Location") return "adb"
def getADB(): """Get ADB binary path""" try: if len(settings.ADB_BINARY) > 0 and isFileExists(settings.ADB_BINARY): return settings.ADB_BINARY else: adb = "adb" if platform.system() == "Darwin": adb_dir = os.path.join(settings.TOOLS_DIR, "adb/mac/") subprocess.call(["chmod", "777", adb_dir]) adb = os.path.join(settings.TOOLS_DIR, "adb/mac/adb") elif platform.system() == "Linux": adb_dir = os.path.join(settings.TOOLS_DIR, "adb/linux/") subprocess.call(["chmod", "777", adb_dir]) adb = os.path.join(settings.TOOLS_DIR, "adb/linux/adb") elif platform.system() == "Windows": adb = os.path.join(settings.TOOLS_DIR, "adb/windows/adb.exe") return adb except: PrintException("[ERROR] Getting ADB Location") return "adb"
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def adb_binary_or32bit_support(): """Check if 32bit is supported. Also if the binary works""" adb_path = getADB() try: fnull = open(os.devnull, "w") subprocess.call([adb_path], stdout=fnull, stderr=fnull) except: msg = ( "\nYou don't have 32 bit execution support enabled or MobSF shipped" " ADB binary is not compatible with your OS." "\nPlease set the 'ADB_BINARY' path in settings.py" ) logger.warning(msg)
def adb_binary_or32bit_support(): """Check if 32bit is supported. Also if the binary works""" adb_path = getADB() try: fnull = open(os.devnull, "w") subprocess.call([adb_path], stdout=fnull, stderr=fnull) except: msg = ( "\n[WARNING] You don't have 32 bit execution support enabled or MobSF shipped" " ADB binary is not compatible with your OS." "\nPlease set the 'ADB_BINARY' path in settings.py" ) if platform.system != "Windows": logger.warning(Color.BOLD + Color.ORANGE + msg + Color.END) else: logger.warning(msg)
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def check_basic_env(): """Check if we have basic env for MobSF to run""" logger.info("MobSF Basic Environment Check") try: import capfuzz except ImportError: PrintException("CapFuzz not installed!") os.kill(os.getpid(), signal.SIGTERM) try: import lxml except ImportError: PrintException("lxml is not installed!") os.kill(os.getpid(), signal.SIGTERM) if platform.system() == "Windows": java = settings.JAVA_PATH + "java.exe" else: java = settings.JAVA_PATH + "java" if not isFileExists(java): logger.error( "Oracle Java is not available or `JAVA_DIRECTORY` in settings.py is configured incorrectly!" ) logger.info("JAVA_DIRECTORY=%s" % settings.JAVA_DIRECTORY) logger.info("""Example Configuration: JAVA_DIRECTORY = "C:/Program Files/Java/jdk1.7.0_17/bin/" JAVA_DIRECTORY = "/usr/bin/" """) os.kill(os.getpid(), signal.SIGTERM)
def check_basic_env(): """Check if we have basic env for MobSF to run""" logger.info("MobSF Basic Environment Check") try: import capfuzz except ImportError: PrintException("[ERROR] CapFuzz not installed!") os.kill(os.getpid(), signal.SIGTERM) try: import lxml except ImportError: PrintException("[ERROR] lxml is not installed!") os.kill(os.getpid(), signal.SIGTERM) if platform.system() == "Windows": java = settings.JAVA_PATH + "java.exe" else: java = settings.JAVA_PATH + "java" if not isFileExists(java): logger.error( "Oracle Java is not available or `JAVA_DIRECTORY` in settings.py is configured incorrectly!" ) logger.info("JAVA_DIRECTORY=%s" % settings.JAVA_DIRECTORY) logger.info("""Example Configuration: JAVA_DIRECTORY = "C:/Program Files/Java/jdk1.7.0_17/bin/" JAVA_DIRECTORY = "/usr/bin/" """) os.kill(os.getpid(), signal.SIGTERM)
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def search(request): """ Search Scan by MD5 Route """ md5 = request.GET["md5"] if re.match("[0-9a-f]{32}", md5): db_obj = RecentScansDB.objects.filter(MD5=md5) if db_obj.exists(): return HttpResponseRedirect("/" + db_obj[0].URL) else: return HttpResponseRedirect("/not_found") return print_n_send_error_response(request, "Invalid Scan Hash")
def search(request): """ Search Scan by MD5 Route """ md5 = request.GET["md5"] if re.match("[0-9a-f]{32}", md5): db_obj = RecentScansDB.objects.filter(MD5=md5) if db_obj.exists(): return HttpResponseRedirect("/" + db_obj[0].URL) else: return HttpResponseRedirect("/not_found") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def download(request): """ Download from MobSF Route """ msg = "Error Downloading File " if request.method == "GET": allowed_exts = settings.ALLOWED_EXTENSIONS filename = request.path.replace("/download/", "", 1) # Security Checks if "../" in filename: return print_n_send_error_response( request, "Path Traversal Attack detected" ) ext = os.path.splitext(filename)[1] if ext in allowed_exts: dwd_file = os.path.join(settings.DWD_DIR, filename) if os.path.isfile(dwd_file): wrapper = FileWrapper(open(dwd_file, "rb")) response = HttpResponse(wrapper, content_type=allowed_exts[ext]) response["Content-Length"] = os.path.getsize(dwd_file) return response msg += filename return print_n_send_error_response(request, msg)
def download(request): """ Download from MobSF Route """ try: if request.method == "GET": allowed_exts = settings.ALLOWED_EXTENSIONS filename = request.path.replace("/download/", "", 1) # Security Checks if "../" in filename: logger.info("\n[ATTACK] Path Traversal Attack detected") return HttpResponseRedirect("/error/") ext = os.path.splitext(filename)[1] if ext in allowed_exts: dwd_file = os.path.join(settings.DWD_DIR, filename) if os.path.isfile(dwd_file): wrapper = FileWrapper(open(dwd_file, "rb")) response = HttpResponse(wrapper, content_type=allowed_exts[ext]) response["Content-Length"] = os.path.getsize(dwd_file) return response except: PrintException("Error Downloading File") return HttpResponseRedirect("/error/")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def add_to_recent_scan(name, md5, url): """ Add Entry to Database under Recent Scan """ try: db_obj = RecentScansDB.objects.filter(MD5=md5) if not db_obj.exists(): new_db_obj = RecentScansDB(NAME=name, MD5=md5, URL=url, TS=timezone.now()) new_db_obj.save() except: PrintException("Adding Scan URL to Database")
def add_to_recent_scan(name, md5, url): """ Add Entry to Database under Recent Scan """ try: db_obj = RecentScansDB.objects.filter(MD5=md5) if not db_obj.exists(): new_db_obj = RecentScansDB(NAME=name, MD5=md5, URL=url, TS=timezone.now()) new_db_obj.save() except: PrintException("[ERROR] Adding Scan URL to Database")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def get_report(self, file_hash): """ :param file_hash: md5/sha1/sha256 :return: json response / None """ try: url = self.base_url + "report" params = {"apikey": settings.VT_API_KEY, "resource": file_hash} headers = {"Accept-Encoding": "gzip, deflate"} try: proxies, verify = upstream_proxy("https") except: PrintException("Setting upstream proxy") try: response = requests.get( url, params=params, headers=headers, proxies=proxies, verify=verify ) if response.status_code == 403: logger.error("VirusTotal Permission denied, wrong api key?") return None except: logger.error("VirusTotal ConnectionError, check internet connectivity") return None try: json_response = response.json() return json_response except ValueError: return None except: PrintException("VirusTotal get_report") return None
def get_report(self, file_hash): """ :param file_hash: md5/sha1/sha256 :return: json response / None """ try: url = self.base_url + "report" params = {"apikey": settings.VT_API_KEY, "resource": file_hash} headers = {"Accept-Encoding": "gzip, deflate"} try: proxies, verify = upstream_proxy("https") except: PrintException("[ERROR] Setting upstream proxy") try: response = requests.get( url, params=params, headers=headers, proxies=proxies, verify=verify ) if response.status_code == 403: logger.error("VirusTotal Permission denied, wrong api key?") return None except: logger.error("VirusTotal ConnectionError, check internet connectivity") return None try: json_response = response.json() return json_response except ValueError: return None except: PrintException("[ERROR] in VirusTotal get_report") return None
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def upload_file(self, file_path): """ :param file_path: file path to upload :return: json response / None """ try: url = self.base_url + "scan" files = {"file": open(file_path, "rb")} headers = {"apikey": settings.VT_API_KEY} try: proxies, verify = upstream_proxy("https") except: PrintException("Setting upstream proxy") try: response = requests.post( url, files=files, data=headers, proxies=proxies, verify=verify ) if response.status_code == 403: logger.error("VirusTotal Permission denied, wrong api key?") return None except: logger.error("VirusTotal Connection Error, check internet connectivity") return None json_response = response.json() return json_response except: PrintException("VirusTotal upload_file") return None
def upload_file(self, file_path): """ :param file_path: file path to upload :return: json response / None """ try: url = self.base_url + "scan" files = {"file": open(file_path, "rb")} headers = {"apikey": settings.VT_API_KEY} try: proxies, verify = upstream_proxy("https") except: PrintException("[ERROR] Setting upstream proxy") try: response = requests.post( url, files=files, data=headers, proxies=proxies, verify=verify ) if response.status_code == 403: logger.error("VirusTotal Permission denied, wrong api key?") return None except: logger.error("VirusTotal ConnectionError, check internet connectivity") return None json_response = response.json() return json_response except: PrintException("[ERROR] in VirusTotal upload_file") return None
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def get_result(self, file_path, file_hash): """ Uoloading a file and getting the approval msg from VT or fetching existing report :param file_path: file's path :param file_hash: file's hash - md5/sha1/sha256 :return: VirusTotal result json / None upon error """ try: logger.info("VirusTotal: Check for existing report") report = self.get_report(file_hash) # Check for existing report if report: if report["response_code"] == 1: logger.info("VirusTotal: " + report["verbose_msg"]) return report if settings.VT_UPLOAD: logger.info("VirusTotal: file upload") upload_response = self.upload_file(file_path) if upload_response: logger.info("VirusTotal: {}".format(upload_response["verbose_msg"])) return upload_response else: logger.info( "MobSF: VirusTotal Scan not performed as file upload is disabled in settings.py. " "To enable file upload, set VT_UPLOAD to True." ) report = { "verbose_msg": "Scan Not performed, VirusTotal file upload disabled in settings.py", "positives": 0, "total": 0, } return report except: PrintException("VirusTotal get_result")
def get_result(self, file_path, file_hash): """ Uoloading a file and getting the approval msg from VT or fetching existing report :param file_path: file's path :param file_hash: file's hash - md5/sha1/sha256 :return: VirusTotal result json / None upon error """ try: logger.info("[INFO] VirusTotal: Check for existing report") report = self.get_report(file_hash) # Check for existing report if report: if report["response_code"] == 1: logger.info("[INFO] VirusTotal: " + report["verbose_msg"]) return report if settings.VT_UPLOAD: logger.info("[INFO] VirusTotal: file upload") upload_response = self.upload_file(file_path) if upload_response: logger.info( "[INFO] VirusTotal: {}".format(upload_response["verbose_msg"]) ) return upload_response else: logger.info( "MobSF: VirusTotal Scan not performed as file upload is disabled in settings.py. " "To enable file upload, set VT_UPLOAD to True." ) report = { "verbose_msg": "Scan Not performed, VirusTotal file upload disabled in settings.py", "positives": 0, "total": 0, } return report except: PrintException("[ERROR] in VirusTotal get_result")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def res_analysis(app_dir): """Perform the elf analysis.""" try: logger.info("Static Android Resource Analysis Started") elf_desc = { "html_infected": ( "Found html files infected by malware.", "high", "The built environment was probably infected by malware, The html file " "used in this APK is infected.", ), } html_an_dic = {} for k in list(elf_desc.keys()): html_an_dic[k] = [] resraw = os.path.join(app_dir, "res", "raw") assets = os.path.join(app_dir, "assets") for resdir in (resraw, assets): if os.path.exists(resdir) and os.path.isdir(resdir): for pdir, dirl, filel in os.walk(resdir): for filename in filel: if filename.endswith(".htm") or filename.endswith(".html"): try: filepath = os.path.join(pdir, filename) buf = "" with io.open(filepath, mode="rb") as filp: buf = filp.read() if "svchost.exe" in buf: html_an_dic["html_infected"].append( filepath.replace(app_dir, "") ) except Exception as e: pass res = [] for k, filelist in list(html_an_dic.items()): if len(filelist): descs = elf_desc.get(k) res.append( { "title": descs[0], "stat": descs[1], "desc": descs[2], "file": " ".join(filelist), } ) return res except: PrintException("Performing Resourse Analysis")
def res_analysis(app_dir): """Perform the elf analysis.""" try: logger.info("Static Android Resource Analysis Started") elf_desc = { "html_infected": ( "Found html files infected by malware.", "high", "The built environment was probably infected by malware, The html file " "used in this APK is infected.", ), } html_an_dic = {} for k in list(elf_desc.keys()): html_an_dic[k] = [] resraw = os.path.join(app_dir, "res", "raw") assets = os.path.join(app_dir, "assets") for resdir in (resraw, assets): if os.path.exists(resdir) and os.path.isdir(resdir): for pdir, dirl, filel in os.walk(resdir): for filename in filel: if filename.endswith(".htm") or filename.endswith(".html"): try: filepath = os.path.join(pdir, filename) buf = "" with io.open(filepath, mode="rb") as filp: buf = filp.read() if "svchost.exe" in buf: html_an_dic["html_infected"].append( filepath.replace(app_dir, "") ) except Exception as e: pass res = [] for k, filelist in list(html_an_dic.items()): if len(filelist): descs = elf_desc.get(k) res.append( { "title": descs[0], "stat": descs[1], "desc": descs[2], "file": " ".join(filelist), } ) return res except: PrintException("[ERROR] Performing Resourse Analysis")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def elf_analysis(app_dir: str) -> list: """Perform the elf analysis.""" try: logger.info("Static Android Binary Analysis Started") elf_desc = { "elf_no_pi": ( "Found elf built without Position Independent Executable (PIE) flag", "high", "In order to prevent an attacker from reliably jumping to, for example, a particular" " exploited function in memory, Address space layout randomization (ASLR) randomly " "arranges the address space positions of key data areas of a process, including the " "base of the executable and the positions of the stack, heap and libraries. Built with" " option <strong>-pie</strong>.", ) } elf_an_dic = {} for k in list(elf_desc.keys()): elf_an_dic[k] = [] libdir = os.path.join(app_dir, "lib") if os.path.exists(libdir): for pdir, dirl, filel in os.walk(libdir): for filename in filel: if filename.endswith(".so"): try: filepath = os.path.join(pdir, filename) f = io.open(filepath, mode="rb") has_pie, has_sg = check_elf_built(f) f.close() if not has_pie: if not any( pie_str in ["nopie", "nonpie", "no-pie"] for pie_str in filename ): elf_an_dic["elf_no_pi"].append( filepath.replace(libdir, "lib") ) except Exception as e: pass res = [] for k, filelist in list(elf_an_dic.items()): if len(filelist): descs = elf_desc.get(k) res.append( { "title": descs[0], "stat": descs[1], "desc": descs[2], "file": " ".join(filelist), } ) return res except: PrintException("Performing Binary Analysis")
def elf_analysis(app_dir: str) -> list: """Perform the elf analysis.""" try: logger.info("Static Android Binary Analysis Started") elf_desc = { "elf_no_pi": ( "Found elf built without Position Independent Executable (PIE) flag", "high", "In order to prevent an attacker from reliably jumping to, for example, a particular" " exploited function in memory, Address space layout randomization (ASLR) randomly " "arranges the address space positions of key data areas of a process, including the " "base of the executable and the positions of the stack, heap and libraries. Built with" " option <strong>-pie</strong>.", ) } elf_an_dic = {} for k in list(elf_desc.keys()): elf_an_dic[k] = [] libdir = os.path.join(app_dir, "lib") if os.path.exists(libdir): for pdir, dirl, filel in os.walk(libdir): for filename in filel: if filename.endswith(".so"): try: filepath = os.path.join(pdir, filename) f = io.open(filepath, mode="rb") has_pie, has_sg = check_elf_built(f) f.close() if not has_pie: if not any( pie_str in ["nopie", "nonpie", "no-pie"] for pie_str in filename ): elf_an_dic["elf_no_pi"].append( filepath.replace(libdir, "lib") ) except Exception as e: pass res = [] for k, filelist in list(elf_an_dic.items()): if len(filelist): descs = elf_desc.get(k) res.append( { "title": descs[0], "stat": descs[1], "desc": descs[2], "file": " ".join(filelist), } ) return res except: PrintException("[ERROR] Performing Binary Analysis")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def get_hardcoded_cert_keystore(files): """Returns the hardcoded certificate keystore.""" try: logger.info("Getting Hardcoded Certificates/Keystores") dat = "" certz = "" key_store = "" for file_name in files: ext = file_name.split(".")[-1] if re.search("cer|pem|cert|crt|pub|key|pfx|p12", ext): certz += escape(file_name) + "</br>" if re.search("jks|bks", ext): key_store += escape(file_name) + "</br>" if len(certz) > 1: dat += ( "<tr><td>Certificate/Key Files Hardcoded inside the App.</td><td>" + certz + "</td><tr>" ) if len(key_store) > 1: dat += ( "<tr><td>Hardcoded Keystore Found.</td><td>" + key_store + "</td><tr>" ) return dat except: PrintException("Getting Hardcoded Certificates/Keystores")
def get_hardcoded_cert_keystore(files): """Returns the hardcoded certificate keystore.""" try: logger.info("Getting Hardcoded Certificates/Keystores") dat = "" certz = "" key_store = "" for file_name in files: ext = file_name.split(".")[-1] if re.search("cer|pem|cert|crt|pub|key|pfx|p12", ext): certz += escape(file_name) + "</br>" if re.search("jks|bks", ext): key_store += escape(file_name) + "</br>" if len(certz) > 1: dat += ( "<tr><td>Certificate/Key Files Hardcoded inside the App.</td><td>" + certz + "</td><tr>" ) if len(key_store) > 1: dat += ( "<tr><td>Hardcoded Keystore Found.</td><td>" + key_store + "</td><tr>" ) return dat except: PrintException("[ERROR] Getting Hardcoded Certificates/Keystores")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def cert_info(app_dir, tools_dir): """Return certificate information.""" try: logger.info("Reading Code Signing Certificate") cert = os.path.join(app_dir, "META-INF/") cp_path = tools_dir + "CertPrint.jar" files = [f for f in os.listdir(cert) if os.path.isfile(os.path.join(cert, f))] certfile = None dat = "" manidat = "" manifestfile = None if "CERT.RSA" in files: certfile = os.path.join(cert, "CERT.RSA") else: for file_name in files: if file_name.lower().endswith(".rsa"): certfile = os.path.join(cert, file_name) elif file_name.lower().endswith(".dsa"): certfile = os.path.join(cert, file_name) if certfile: args = [settings.JAVA_PATH + "java", "-jar", cp_path, certfile] issued = "good" dat = subprocess.check_output(args) unicode_output = str(dat, encoding="utf-8", errors="replace") dat = escape(unicode_output).replace("\n", "</br>") else: dat = "No Code Signing Certificate Found!" issued = "missing" if re.findall(r"Issuer: CN=Android Debug|Subject: CN=Android Debug", dat): issued = "bad" if re.findall(r"\[SHA1withRSA\]", dat): issued = "bad hash" if "MANIFEST.MF" in files: manifestfile = os.path.join(cert, "MANIFEST.MF") if manifestfile: with open(manifestfile, "r", encoding="utf-8") as manifile: manidat = manifile.read() sha256Digest = bool(re.findall(r"SHA-256-Digest", manidat)) cert_dic = {"cert_info": dat, "issued": issued, "sha256Digest": sha256Digest} return cert_dic except: PrintException("Reading Code Signing Certificate")
def cert_info(app_dir, tools_dir): """Return certificate information.""" try: logger.info("Reading Code Signing Certificate") cert = os.path.join(app_dir, "META-INF/") cp_path = tools_dir + "CertPrint.jar" files = [f for f in os.listdir(cert) if os.path.isfile(os.path.join(cert, f))] certfile = None dat = "" manidat = "" manifestfile = None if "CERT.RSA" in files: certfile = os.path.join(cert, "CERT.RSA") else: for file_name in files: if file_name.lower().endswith(".rsa"): certfile = os.path.join(cert, file_name) elif file_name.lower().endswith(".dsa"): certfile = os.path.join(cert, file_name) if certfile: args = [settings.JAVA_PATH + "java", "-jar", cp_path, certfile] issued = "good" dat = subprocess.check_output(args) unicode_output = str(dat, encoding="utf-8", errors="replace") dat = escape(unicode_output).replace("\n", "</br>") else: dat = "No Code Signing Certificate Found!" issued = "missing" if re.findall(r"Issuer: CN=Android Debug|Subject: CN=Android Debug", dat): issued = "bad" if re.findall(r"\[SHA1withRSA\]", dat): issued = "bad hash" if "MANIFEST.MF" in files: manifestfile = os.path.join(cert, "MANIFEST.MF") if manifestfile: with open(manifestfile, "r", encoding="utf-8") as manifile: manidat = manifile.read() sha256Digest = bool(re.findall(r"SHA-256-Digest", manidat)) cert_dic = {"cert_info": dat, "issued": issued, "sha256Digest": sha256Digest} return cert_dic except: PrintException("[ERROR] Reading Code Signing Certificate")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError
def code_analysis(app_dir, perms, typ): """Perform the code analysis.""" try: logger.info("Static Android Code Analysis Started") api_rules = android_apis.APIS code_rules = android_rules.RULES code_findings = {} api_findings = {} email_n_file = [] url_n_file = [] url_list = [] domains = {} if typ == "apk": java_src = os.path.join(app_dir, "java_source/") elif typ == "studio": java_src = os.path.join(app_dir, "app/src/main/java/") elif typ == "eclipse": java_src = os.path.join(app_dir, "src/") logger.info("Code Analysis Started on - " + java_src) # pylint: disable=unused-variable # Needed by os.walk for dir_name, sub_dir, files in os.walk(java_src): for jfile in files: jfile_path = os.path.join(java_src, dir_name, jfile) if "+" in jfile: p_2 = os.path.join(java_src, dir_name, jfile.replace("+", "x")) shutil.move(jfile_path, p_2) jfile_path = p_2 repath = dir_name.replace(java_src, "") if ( jfile.endswith(".java") and any(re.search(cls, repath) for cls in settings.SKIP_CLASSES) is False ): dat = "" with io.open( jfile_path, mode="r", encoding="utf8", errors="ignore" ) as file_pointer: dat = file_pointer.read() # Code Analysis # print "[INFO] Doing Code Analysis on - " + jfile_path relative_java_path = jfile_path.replace(java_src, "") code_rule_matcher( code_findings, list(perms.keys()), dat, relative_java_path, code_rules, ) # API Check api_rule_matcher( api_findings, list(perms.keys()), dat, relative_java_path, api_rules, ) # Extract URLs and Emails urls, urls_nf, emails_nf = url_n_email_extract( dat, relative_java_path ) url_list.extend(urls) url_n_file.extend(urls_nf) email_n_file.extend(emails_nf) # Domain Extraction and Malware Check logger.info("Performing Malware Check on extracted Domains") domains = malware_check(list(set(url_list))) logger.info("Finished Code Analysis, Email and URL Extraction") code_an_dic = { "api": api_findings, "findings": code_findings, "urls": url_n_file, "domains": domains, "emails": email_n_file, } return code_an_dic except: PrintException("Performing Code Analysis")
def code_analysis(app_dir, perms, typ): """Perform the code analysis.""" try: logger.info("Static Android Code Analysis Started") api_rules = android_apis.APIS code_rules = android_rules.RULES code_findings = {} api_findings = {} email_n_file = [] url_n_file = [] url_list = [] domains = {} if typ == "apk": java_src = os.path.join(app_dir, "java_source/") elif typ == "studio": java_src = os.path.join(app_dir, "app/src/main/java/") elif typ == "eclipse": java_src = os.path.join(app_dir, "src/") logger.info("Code Analysis Started on - " + java_src) # pylint: disable=unused-variable # Needed by os.walk for dir_name, sub_dir, files in os.walk(java_src): for jfile in files: jfile_path = os.path.join(java_src, dir_name, jfile) if "+" in jfile: p_2 = os.path.join(java_src, dir_name, jfile.replace("+", "x")) shutil.move(jfile_path, p_2) jfile_path = p_2 repath = dir_name.replace(java_src, "") if ( jfile.endswith(".java") and any(re.search(cls, repath) for cls in settings.SKIP_CLASSES) is False ): dat = "" with io.open( jfile_path, mode="r", encoding="utf8", errors="ignore" ) as file_pointer: dat = file_pointer.read() # Code Analysis # print "[INFO] Doing Code Analysis on - " + jfile_path relative_java_path = jfile_path.replace(java_src, "") code_rule_matcher( code_findings, list(perms.keys()), dat, relative_java_path, code_rules, ) # API Check api_rule_matcher( api_findings, list(perms.keys()), dat, relative_java_path, api_rules, ) # Extract URLs and Emails urls, urls_nf, emails_nf = url_n_email_extract( dat, relative_java_path ) url_list.extend(urls) url_n_file.extend(urls_nf) email_n_file.extend(emails_nf) # Domain Extraction and Malware Check logger.info("Performing Malware Check on extracted Domains") domains = malware_check(list(set(url_list))) logger.info("Finished Code Analysis, Email and URL Extraction") code_an_dic = { "api": api_findings, "findings": code_findings, "urls": url_n_file, "domains": domains, "emails": email_n_file, } return code_an_dic except: PrintException("[ERROR] Performing Code Analysis")
https://github.com/MobSF/Mobile-Security-Framework-MobSF/issues/861
[INFO] 08/Feb/2019 16:17:54 - VM Starting [INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400 [INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241 [INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0 [DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'. Traceback (most recent call last): File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup current = current[bit] File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'exp' During handling of the above exception, another exception occurred:
KeyError