
# coding: utf-8

# In[14]:


import keras
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.models import model_from_json
from androguard.misc import AnalyzeAPK
from androguard.core.analysis.analysis import ExternalMethod
from time import time
import os
import numpy as np
import random
from random import shuffle
import math
import sys



# In[15]:


import tensorflow as tf

gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.3)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

tf.keras.backend.set_session(sess)


# In[16]:


def load_model():
    # load JSON and create model
    json_file = open('fully_connected.json', 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = model_from_json(loaded_model_json)
    # load weights into new model
    loaded_model.load_weights("fully_connected.h5")
    print("Loaded model from disk")
    loaded_model.compile(loss=keras.losses.binary_crossentropy,
                  optimizer=keras.optimizers.Adadelta(),
                  metrics=['accuracy'])
    return loaded_model
loaded_model = load_model()


# In[17]:


family_dict = {'Benign': 0, 'Jifake': 1, 'Fakenotify': 2, 'Nandrobox': 3, 'MazarBot': 4, 'Biige': 5, 'Plankton': 6, 'SMSsniffer': 7, 'Fakemart': 8, 'FakeInst': 9, 'Zsone': 10, 'BeanBot': 11, 'Simplocker': 12, 'LockerPin': 13, 'Charger': 14, 'RansomBO': 15, 'Koler': 16, 'Wannalocker': 17, 'Svpeng': 18, 'Pletor': 19, 'PornDroid': 20, 'Jisut': 21, 'fakeJobOffer': 22, 'fakeApp_AL': 23, 'AvForAndroid': 24, 'avPass': 25, 'fakeAV': 26, 'fakeApp': 27, 'android.spy.277': 28, 'penetho': 29, 'faketaoBao': 30, 'virusShield': 31, 'AndroidDefender': 32, 'selfmite': 33, 'koodous': 34, 'kemoge': 35, 'gooligan': 36, 'mobidash': 37, 'youmi': 38, 'dowgin': 39, 'feiwo': 40, 'shuanet': 41, 'edwin': 42}


# In[32]:


def get_inform(t):
    permissions = []
    intents = []
    key = "android"
    for x in t.iter():
        for ss in x.iter():
            try:
#                 print(ss.items()[0][1].split('.'))
                items = ss.items()[0][1].split('.')
                if key in items:
                    if 'permission' in items:
                        permissions.append(items[-1])
                    elif 'intent' in items:
                        intents.append(items[-1])
            except:
                pass
    return permissions, intents


# In[33]:


def load_file(file):
    a = []
    perm = []
    intent = []
    print(file)
    a_temp, d_temp, dx_temp = AnalyzeAPK(file)
    a.append(0)
    a_temp.get_android_manifest_xml()
    t = a_temp.get_android_manifest_xml()
    p,i = get_inform(t)
    perm.append(p)
    intent.append(i)
    return a,perm,intent


# In[45]:


a,perm,intent = load_file(sys.argv[1])


# In[44]:


def create_permission_dict():
    permission2n = []
    n2permission = []
    with open('permission.txt') as f:
        data = f.readline()
        data = [x.strip().split(' ') for x in data.split(',')[:-1]]
        permission2n = [x[0] for x in data]
        n2permission = [x[1] for x in data]
        return permission2n, n2permission
        f.close()
p2n, n2p = create_permission_dict()


# In[43]:


def create_intent_dict():
    i2n = []
    n2i = []
    with open('intents.txt') as f:
        data = f.readline()
        data = [x.strip().split(' ') for x in data.split(',')[:-1]]
        i2n = [x[0] for x in data]
        n2i = [x[1] for x in data]
        return i2n, n2i
        f.close()
i2n, n2i = create_intent_dict()


# In[46]:


def create_vector(perm,intent):
    x_p = []
    x_i = []
    count = 0
    for p in p2n:
        if p in perm[0]:
            x_p.append(1)
        else:
            x_p.append(0)
    for i in i2n:
        if i in intent[0]:
            x_i.append(1)
        else:
            x_i.append(0)
    x = x_p+x_i
    return x
x = create_vector(perm,intent)
x_test = np.array(x).reshape((1,369))


# In[47]:

mal={'0':"Benign",'1':"SMSmalware",'2':"Ransomware",'3':"Scareware",'4':"Adware"}

prediction = loaded_model.predict(x_test,verbose=1)
print(prediction)
a=str(np.argmax(prediction))
print(a)
with open("tmp", 'a') as the_file:
    the_file.write(mal[a]+'\n')

