import os, json, tkinter, sys, csv
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from tkinter import filedialog
from tkinter import messagebox
from tkinter import *
from PIL import ImageTk, Image
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier
def createFolder(directory):
    if not os.path.exists(directory):
        os.makedirs(directory)
        global filesForProgram
        filesForProgram = directory
createFolder(str(os.getcwd()) + "/Malware_Analysis_Tool_Files/")
createFolder(str(os.getcwd()) + "/Malware_Analysis_Tool_Files/logs/")
createFolder(str(os.getcwd()) + "/Malware_Analysis_Tool_Files/Dataset/")
def dirLocation():
    global dirname
    dirname = filedialog.askdirectory(initialdir="/",title='Please select a directory')
    return dirname
def popup():
    global classificationSelection
    classSelect = tkinter.Tk()
    classificationSelection = StringVar(classSelect)
    classificationSelection.set("Benign")
    classSelect.title("Select Classification")
    classSelect.geometry("250x70")
    classSelect.resizable(False, False)
    w = OptionMenu(classSelect, classificationSelection, "Benign", "Ransomware", "Keylogger", "RAT")
    w.pack()
    saveBtn = tkinter.Button(classSelect, text="Select", fg='black', width=5, height=1, command=lambda: classSelect.destroy()).place(x=90, y=35)
def getJSON(filePathName):
    with open(filePathName, 'r') as fp:
        return json.load(fp)
def logExtract():
    path = dirLocation()
    global logFiles
    logFiles = []
    for r, d, f in os.walk(path):
        for file in f:
            if '.json' in file:
                logFiles.append(os.path.join(r, file))
    popup()
    i = 0
    saveLocation = str(os.getcwd())+"/Malware_Analysis_Tool_Files/logs/"
    for r, d, f in os.walk(saveLocation):
        for file in f:
            if str(classificationSelection.get()) in file:
                i = i + 1
    while i < (len(logFiles)): # error is here
        newFileName = str(classificationSelection.get()) + str(i) + ".log"
        newFile = open(saveLocation + newFileName, "w")
        myObj = getJSON(logFiles[i])
        strings = myObj.get("strings", "")
        behavior = myObj.get("behavior", "")
        newFile.write(str(strings) + str(behavior))
        newFile.close()
        i += 1
def createDataset():
    path =  str(os.getcwd()) + "/Malware_Analysis_Tool_Files/logs/"# path of files
    labels = []
    text = []
    for filename in os.listdir(path):
        if "Benign" in filename:
            labels.append("1")
        elif "Ransomware" in filename:
            labels.append("2")
        elif "Keylogger" in filename:
            labels.append("3")
        elif "RAT" in filename:
            labels.append("4")
        else:
            pass
        filename = os.path.join(path, filename)
        with open(filename) as f:
            content = f.read()
        content.replace(",", " ")
        content.replace('"', " ")
        text.append(content)
    vectorizer = CountVectorizer(stop_words='english', max_features=1000)
    dtm = vectorizer.fit_transform(text)
    df = pd.DataFrame(dtm.toarray(), index=labels, columns=vectorizer.get_feature_names())
    df.index.name = "Labels"
    df.to_csv(str(os.getcwd()) + "/Malware_Analysis_Tool_Files/Dataset/" + r'Dataset.csv')
    features_list = vectorizer.get_feature_names()
def loadDataset():
    global dataset
    dataset =  filedialog.askopenfilename(initialdir = str(os.getcwd()) + "/Malware_Analysis_Tool_Files/Dataset/",title = "Select Dataset")
    df = pd.read_csv(dataset, usecols=['Labels'])
    global featureList
    featureList = []
    featureSet = pd.read_csv(dataset)
    for cols in featureSet.columns:
        if cols == "Labels":
            pass
        else:
            featureList.append(cols)
    i = 1
    from csv import reader
    with open(dataset, 'r') as read_obj:
        csv_reader = reader(read_obj)
        global datasetRows
        datasetRows = []
        for row in csv_reader:
            datasetRows.append(str(row))
    i = 0
    labelCount = []
    while i < len(df):
        labelAdd = df['Labels'][i]
        labelCount.append(str(labelAdd))
        i = i + 1
    i = 0
    ransomware = 0
    rat = 0
    keylogger = 0
    benign = 0
    while i < len(labelCount):
        if labelCount[i] == '1': #benign
            benign = benign + 1
            i = i + 1
        elif labelCount[i] == '2': #ransomware
            ransomware = ransomware + 1
            i = i + 1
        elif labelCount[i] == '3': #keylogger
            keylogger = keylogger + 1
            i = i + 1
        elif labelCount[i] == '4': #rat
            rat = rat + 1
            i = i + 1
    types = ['Benign', 'Ransomware', 'Keylogger', 'RAT']
    values = [benign, ransomware, keylogger, rat]
    ypos = np.arange(len(types))
    plt.xlabel("Sample Types")
    plt.ylabel("No. of Samples")
    plt.title("Dataset Sample Division")
    plt.xticks(ypos, types)
    plt.bar(ypos, values)
    barColour = plt.bar(ypos, values)
    barColour[0].set_color('g')
    barColour[1].set_color('r')
    barColour[2].set_color('r')
    barColour[3].set_color('r')
    plt.show()
def results():
    windowRESULTS = tkinter.Tk()
    windowRESULTS.title("My Malware Analysis Tool")
    windowRESULTS.geometry("500x200")
    windowRESULTS.resizable(False, False)
    label0 = tkinter.Label(windowRESULTS, text="Classification: "+ classifiedMalware,font=("Arial Black", 18))
    label0.pack()
def submitLog():
    featureList = []
    featureSet = pd.read_csv(dataset)
    for cols in featureSet.columns:
        if cols == "Labels":
            pass
        else:
            featureList.append(cols)
    label = []
    text = [] 
    label.append("0")
    filename =  filedialog.askopenfilename(initialdir = str(os.getcwd()) + "/Malware_Analysis_Tool_Files/logs/",title = "Select a Log")
    with open(filename) as f:
        content = f.read()
    content.replace(",", " ")
    content.replace('"', " ")
    text.append(content)
    vectorizer = CountVectorizer(stop_words='english', max_features=1001, vocabulary=featureList)
    dtm = vectorizer.fit_transform(text)
    dfNewSample = pd.DataFrame(dtm.toarray(), index=label, columns=vectorizer.get_feature_names())
    df = pd.read_csv(dataset)
    features = list(df.columns.values.tolist())
    features.remove("Labels")
    X = df[features]
    y = df['Labels']
    dtree = DecisionTreeClassifier()
    dtree = dtree.fit(X, y)
    classResult = dtree.predict(dfNewSample)
    global classifiedMalware
    classifiedMalware = "" #default
    if classResult[0] == 1:
        classifiedMalware = "Benign"
    elif classResult[0] == 2:
        classifiedMalware = "Ransomware"
    elif classResult[0] == 3:
        classifiedMalware = "Keylogger"
    elif classResult[0] == 4:
        classifiedMalware = "Remote Administration Tool (RAT)"
    results()
def about():
    windowABOUT = tkinter.Tk()
    windowABOUT.title("My Malware Analysis Tool")
    windowABOUT.geometry("600x150")
    windowABOUT.resizable(False, False)
    label0 = tkinter.Label(windowABOUT, text="\nThis program was developed to allow machine learning algoritms \nto identify determine the classification of malware. \n\n\nCreated by William Fitzgerald",font=("Arial Black", 12))
    label0.pack()
windowMENU = tkinter.Tk()
windowMENU.title("My Malware Analysis Tool")
windowMENU.geometry("250x300")
windowMENU.resizable(False, False)
buttonONE = tkinter.Button(windowMENU, text="Log Extract", fg='black', width=15, height=2, command=logExtract).place(x=50, y=25)
buttonTWO = tkinter.Button(windowMENU, text="Create Dataset", fg='black', width=15, height=2, command=lambda: createDataset()).place(x=50, y=75)
buttonTHREE = tkinter.Button(windowMENU, text="Load Dataset", fg='black', width=15, height=2, command=lambda: loadDataset()).place(x=50, y=125)
buttonFOUR = tkinter.Button(windowMENU, text="Submit Log", fg='black', width=15, height=2, command=lambda: submitLog()).place(x=50, y=175)
buttonABOUT = tkinter.Button(windowMENU, text="About", fg='black', width=15, height=2, command=lambda: about()).place(x=50, y=225)
windowMENU.mainloop()

8504c1c6136160d9a517c9fa6c80cd379922d672
<mask token>


def createFolder(directory):
    if not os.path.exists(directory):
        os.makedirs(directory)
        global filesForProgram
        filesForProgram = directory


<mask token>


def dirLocation():
    global dirname
    dirname = filedialog.askdirectory(initialdir='/', title=
        'Please select a directory')
    return dirname


<mask token>


def getJSON(filePathName):
    with open(filePathName, 'r') as fp:
        return json.load(fp)


def logExtract():
    path = dirLocation()
    global logFiles
    logFiles = []
    for r, d, f in os.walk(path):
        for file in f:
            if '.json' in file:
                logFiles.append(os.path.join(r, file))
    popup()
    i = 0
    saveLocation = str(os.getcwd()) + '/Malware_Analysis_Tool_Files/logs/'
    for r, d, f in os.walk(saveLocation):
        for file in f:
            if str(classificationSelection.get()) in file:
                i = i + 1
    while i < len(logFiles):
        newFileName = str(classificationSelection.get()) + str(i) + '.log'
        newFile = open(saveLocation + newFileName, 'w')
        myObj = getJSON(logFiles[i])
        strings = myObj.get('strings', '')
        behavior = myObj.get('behavior', '')
        newFile.write(str(strings) + str(behavior))
        newFile.close()
        i += 1


def createDataset():
    path = str(os.getcwd()) + '/Malware_Analysis_Tool_Files/logs/'
    labels = []
    text = []
    for filename in os.listdir(path):
        if 'Benign' in filename:
            labels.append('1')
        elif 'Ransomware' in filename:
            labels.append('2')
        elif 'Keylogger' in filename:
            labels.append('3')
        elif 'RAT' in filename:
            labels.append('4')
        else:
            pass
        filename = os.path.join(path, filename)
        with open(filename) as f:
            content = f.read()
        content.replace(',', ' ')
        content.replace('"', ' ')
        text.append(content)
    vectorizer = CountVectorizer(stop_words='english', max_features=1000)
    dtm = vectorizer.fit_transform(text)
    df = pd.DataFrame(dtm.toarray(), index=labels, columns=vectorizer.
        get_feature_names())
    df.index.name = 'Labels'
    df.to_csv(str(os.getcwd()) + '/Malware_Analysis_Tool_Files/Dataset/' +
        'Dataset.csv')
    features_list = vectorizer.get_feature_names()


def loadDataset():
    global dataset
    dataset = filedialog.askopenfilename(initialdir=str(os.getcwd()) +
        '/Malware_Analysis_Tool_Files/Dataset/', title='Select Dataset')
    df = pd.read_csv(dataset, usecols=['Labels'])
    global featureList
    featureList = []
    featureSet = pd.read_csv(dataset)
    for cols in featureSet.columns:
        if cols == 'Labels':
            pass
        else:
            featureList.append(cols)
    i = 1
    from csv import reader
    with open(dataset, 'r') as read_obj:
        csv_reader = reader(read_obj)
        global datasetRows
        datasetRows = []
        for row in csv_reader:
            datasetRows.append(str(row))
    i = 0
    labelCount = []
    while i < len(df):
        labelAdd = df['Labels'][i]
        labelCount.append(str(labelAdd))
        i = i + 1
    i = 0
    ransomware = 0
    rat = 0
    keylogger = 0
    benign = 0
    while i < len(labelCount):
        if labelCount[i] == '1':
            benign = benign + 1
            i = i + 1
        elif labelCount[i] == '2':
            ransomware = ransomware + 1
            i = i + 1
        elif labelCount[i] == '3':
            keylogger = keylogger + 1
            i = i + 1
        elif labelCount[i] == '4':
            rat = rat + 1
            i = i + 1
    types = ['Benign', 'Ransomware', 'Keylogger', 'RAT']
    values = [benign, ransomware, keylogger, rat]
    ypos = np.arange(len(types))
    plt.xlabel('Sample Types')
    plt.ylabel('No. of Samples')
    plt.title('Dataset Sample Division')
    plt.xticks(ypos, types)
    plt.bar(ypos, values)
    barColour = plt.bar(ypos, values)
    barColour[0].set_color('g')
    barColour[1].set_color('r')
    barColour[2].set_color('r')
    barColour[3].set_color('r')
    plt.show()


def results():
    windowRESULTS = tkinter.Tk()
    windowRESULTS.title('My Malware Analysis Tool')
    windowRESULTS.geometry('500x200')
    windowRESULTS.resizable(False, False)
    label0 = tkinter.Label(windowRESULTS, text='Classification: ' +
        classifiedMalware, font=('Arial Black', 18))
    label0.pack()


def submitLog():
    featureList = []
    featureSet = pd.read_csv(dataset)
    for cols in featureSet.columns:
        if cols == 'Labels':
            pass
        else:
            featureList.append(cols)
    label = []
    text = []
    label.append('0')
    filename = filedialog.askopenfilename(initialdir=str(os.getcwd()) +
        '/Malware_Analysis_Tool_Files/logs/', title='Select a Log')
    with open(filename) as f:
        content = f.read()
    content.replace(',', ' ')
    content.replace('"', ' ')
    text.append(content)
    vectorizer = CountVectorizer(stop_words='english', max_features=1001,
        vocabulary=featureList)
    dtm = vectorizer.fit_transform(text)
    dfNewSample = pd.DataFrame(dtm.toarray(), index=label, columns=
        vectorizer.get_feature_names())
    df = pd.read_csv(dataset)
    features = list(df.columns.values.tolist())
    features.remove('Labels')
    X = df[features]
    y = df['Labels']
    dtree = DecisionTreeClassifier()
    dtree = dtree.fit(X, y)
    classResult = dtree.predict(dfNewSample)
    global classifiedMalware
    classifiedMalware = ''
    if classResult[0] == 1:
        classifiedMalware = 'Benign'
    elif classResult[0] == 2:
        classifiedMalware = 'Ransomware'
    elif classResult[0] == 3:
        classifiedMalware = 'Keylogger'
    elif classResult[0] == 4:
        classifiedMalware = 'Remote Administration Tool (RAT)'
    results()


def about():
    windowABOUT = tkinter.Tk()
    windowABOUT.title('My Malware Analysis Tool')
    windowABOUT.geometry('600x150')
    windowABOUT.resizable(False, False)
    label0 = tkinter.Label(windowABOUT, text=
        """
This program was developed to allow machine learning algoritms 
to identify determine the classification of malware. 


Created by William Fitzgerald"""
        , font=('Arial Black', 12))
    label0.pack()


<mask token>

<mask token>


def createFolder(directory):
    if not os.path.exists(directory):
        os.makedirs(directory)
        global filesForProgram
        filesForProgram = directory


<mask token>


def dirLocation():
    global dirname
    dirname = filedialog.askdirectory(initialdir='/', title=
        'Please select a directory')
    return dirname


def popup():
    global classificationSelection
    classSelect = tkinter.Tk()
    classificationSelection = StringVar(classSelect)
    classificationSelection.set('Benign')
    classSelect.title('Select Classification')
    classSelect.geometry('250x70')
    classSelect.resizable(False, False)
    w = OptionMenu(classSelect, classificationSelection, 'Benign',
        'Ransomware', 'Keylogger', 'RAT')
    w.pack()
    saveBtn = tkinter.Button(classSelect, text='Select', fg='black', width=
        5, height=1, command=lambda : classSelect.destroy()).place(x=90, y=35)


def getJSON(filePathName):
    with open(filePathName, 'r') as fp:
        return json.load(fp)


def logExtract():
    path = dirLocation()
    global logFiles
    logFiles = []
    for r, d, f in os.walk(path):
        for file in f:
            if '.json' in file:
                logFiles.append(os.path.join(r, file))
    popup()
    i = 0
    saveLocation = str(os.getcwd()) + '/Malware_Analysis_Tool_Files/logs/'
    for r, d, f in os.walk(saveLocation):
        for file in f:
            if str(classificationSelection.get()) in file:
                i = i + 1
    while i < len(logFiles):
        newFileName = str(classificationSelection.get()) + str(i) + '.log'
        newFile = open(saveLocation + newFileName, 'w')
        myObj = getJSON(logFiles[i])
        strings = myObj.get('strings', '')
        behavior = myObj.get('behavior', '')
        newFile.write(str(strings) + str(behavior))
        newFile.close()
        i += 1


def createDataset():
    path = str(os.getcwd()) + '/Malware_Analysis_Tool_Files/logs/'
    labels = []
    text = []
    for filename in os.listdir(path):
        if 'Benign' in filename:
            labels.append('1')
        elif 'Ransomware' in filename:
            labels.append('2')
        elif 'Keylogger' in filename:
            labels.append('3')
        elif 'RAT' in filename:
            labels.append('4')
        else:
            pass
        filename = os.path.join(path, filename)
        with open(filename) as f:
            content = f.read()
        content.replace(',', ' ')
        content.replace('"', ' ')
        text.append(content)
    vectorizer = CountVectorizer(stop_words='english', max_features=1000)
    dtm = vectorizer.fit_transform(text)
    df = pd.DataFrame(dtm.toarray(), index=labels, columns=vectorizer.
        get_feature_names())
    df.index.name = 'Labels'
    df.to_csv(str(os.getcwd()) + '/Malware_Analysis_Tool_Files/Dataset/' +
        'Dataset.csv')
    features_list = vectorizer.get_feature_names()


def loadDataset():
    global dataset
    dataset = filedialog.askopenfilename(initialdir=str(os.getcwd()) +
        '/Malware_Analysis_Tool_Files/Dataset/', title='Select Dataset')
    df = pd.read_csv(dataset, usecols=['Labels'])
    global featureList
    featureList = []
    featureSet = pd.read_csv(dataset)
    for cols in featureSet.columns:
        if cols == 'Labels':
            pass
        else:
            featureList.append(cols)
    i = 1
    from csv import reader
    with open(dataset, 'r') as read_obj:
        csv_reader = reader(read_obj)
        global datasetRows
        datasetRows = []
        for row in csv_reader:
            datasetRows.append(str(row))
    i = 0
    labelCount = []
    while i < len(df):
        labelAdd = df['Labels'][i]
        labelCount.append(str(labelAdd))
        i = i + 1
    i = 0
    ransomware = 0
    rat = 0
    keylogger = 0
    benign = 0
    while i < len(labelCount):
        if labelCount[i] == '1':
            benign = benign + 1
            i = i + 1
        elif labelCount[i] == '2':
            ransomware = ransomware + 1
            i = i + 1
        elif labelCount[i] == '3':
            keylogger = keylogger + 1
            i = i + 1
        elif labelCount[i] == '4':
            rat = rat + 1
            i = i + 1
    types = ['Benign', 'Ransomware', 'Keylogger', 'RAT']
    values = [benign, ransomware, keylogger, rat]
    ypos = np.arange(len(types))
    plt.xlabel('Sample Types')
    plt.ylabel('No. of Samples')
    plt.title('Dataset Sample Division')
    plt.xticks(ypos, types)
    plt.bar(ypos, values)
    barColour = plt.bar(ypos, values)
    barColour[0].set_color('g')
    barColour[1].set_color('r')
    barColour[2].set_color('r')
    barColour[3].set_color('r')
    plt.show()


def results():
    windowRESULTS = tkinter.Tk()
    windowRESULTS.title('My Malware Analysis Tool')
    windowRESULTS.geometry('500x200')
    windowRESULTS.resizable(False, False)
    label0 = tkinter.Label(windowRESULTS, text='Classification: ' +
        classifiedMalware, font=('Arial Black', 18))
    label0.pack()


def submitLog():
    featureList = []
    featureSet = pd.read_csv(dataset)
    for cols in featureSet.columns:
        if cols == 'Labels':
            pass
        else:
            featureList.append(cols)
    label = []
    text = []
    label.append('0')
    filename = filedialog.askopenfilename(initialdir=str(os.getcwd()) +
        '/Malware_Analysis_Tool_Files/logs/', title='Select a Log')
    with open(filename) as f:
        content = f.read()
    content.replace(',', ' ')
    content.replace('"', ' ')
    text.append(content)
    vectorizer = CountVectorizer(stop_words='english', max_features=1001,
        vocabulary=featureList)
    dtm = vectorizer.fit_transform(text)
    dfNewSample = pd.DataFrame(dtm.toarray(), index=label, columns=
        vectorizer.get_feature_names())
    df = pd.read_csv(dataset)
    features = list(df.columns.values.tolist())
    features.remove('Labels')
    X = df[features]
    y = df['Labels']
    dtree = DecisionTreeClassifier()
    dtree = dtree.fit(X, y)
    classResult = dtree.predict(dfNewSample)
    global classifiedMalware
    classifiedMalware = ''
    if classResult[0] == 1:
        classifiedMalware = 'Benign'
    elif classResult[0] == 2:
        classifiedMalware = 'Ransomware'
    elif classResult[0] == 3:
        classifiedMalware = 'Keylogger'
    elif classResult[0] == 4:
        classifiedMalware = 'Remote Administration Tool (RAT)'
    results()


def about():
    windowABOUT = tkinter.Tk()
    windowABOUT.title('My Malware Analysis Tool')
    windowABOUT.geometry('600x150')
    windowABOUT.resizable(False, False)
    label0 = tkinter.Label(windowABOUT, text=
        """
This program was developed to allow machine learning algoritms 
to identify determine the classification of malware. 


Created by William Fitzgerald"""
        , font=('Arial Black', 12))
    label0.pack()


<mask token>

<mask token>


def createFolder(directory):
    if not os.path.exists(directory):
        os.makedirs(directory)
        global filesForProgram
        filesForProgram = directory


createFolder(str(os.getcwd()) + '/Malware_Analysis_Tool_Files/')
createFolder(str(os.getcwd()) + '/Malware_Analysis_Tool_Files/logs/')
createFolder(str(os.getcwd()) + '/Malware_Analysis_Tool_Files/Dataset/')


def dirLocation():
    global dirname
    dirname = filedialog.askdirectory(initialdir='/', title=
        'Please select a directory')
    return dirname


def popup():
    global classificationSelection
    classSelect = tkinter.Tk()
    classificationSelection = StringVar(classSelect)
    classificationSelection.set('Benign')
    classSelect.title('Select Classification')
    classSelect.geometry('250x70')
    classSelect.resizable(False, False)
    w = OptionMenu(classSelect, classificationSelection, 'Benign',
        'Ransomware', 'Keylogger', 'RAT')
    w.pack()
    saveBtn = tkinter.Button(classSelect, text='Select', fg='black', width=
        5, height=1, command=lambda : classSelect.destroy()).place(x=90, y=35)


def getJSON(filePathName):
    with open(filePathName, 'r') as fp:
        return json.load(fp)


def logExtract():
    path = dirLocation()
    global logFiles
    logFiles = []
    for r, d, f in os.walk(path):
        for file in f:
            if '.json' in file:
                logFiles.append(os.path.join(r, file))
    popup()
    i = 0
    saveLocation = str(os.getcwd()) + '/Malware_Analysis_Tool_Files/logs/'
    for r, d, f in os.walk(saveLocation):
        for file in f:
            if str(classificationSelection.get()) in file:
                i = i + 1
    while i < len(logFiles):
        newFileName = str(classificationSelection.get()) + str(i) + '.log'
        newFile = open(saveLocation + newFileName, 'w')
        myObj = getJSON(logFiles[i])
        strings = myObj.get('strings', '')
        behavior = myObj.get('behavior', '')
        newFile.write(str(strings) + str(behavior))
        newFile.close()
        i += 1


def createDataset():
    path = str(os.getcwd()) + '/Malware_Analysis_Tool_Files/logs/'
    labels = []
    text = []
    for filename in os.listdir(path):
        if 'Benign' in filename:
            labels.append('1')
        elif 'Ransomware' in filename:
            labels.append('2')
        elif 'Keylogger' in filename:
            labels.append('3')
        elif 'RAT' in filename:
            labels.append('4')
        else:
            pass
        filename = os.path.join(path, filename)
        with open(filename) as f:
            content = f.read()
        content.replace(',', ' ')
        content.replace('"', ' ')
        text.append(content)
    vectorizer = CountVectorizer(stop_words='english', max_features=1000)
    dtm = vectorizer.fit_transform(text)
    df = pd.DataFrame(dtm.toarray(), index=labels, columns=vectorizer.
        get_feature_names())
    df.index.name = 'Labels'
    df.to_csv(str(os.getcwd()) + '/Malware_Analysis_Tool_Files/Dataset/' +
        'Dataset.csv')
    features_list = vectorizer.get_feature_names()


def loadDataset():
    global dataset
    dataset = filedialog.askopenfilename(initialdir=str(os.getcwd()) +
        '/Malware_Analysis_Tool_Files/Dataset/', title='Select Dataset')
    df = pd.read_csv(dataset, usecols=['Labels'])
    global featureList
    featureList = []
    featureSet = pd.read_csv(dataset)
    for cols in featureSet.columns:
        if cols == 'Labels':
            pass
        else:
            featureList.append(cols)
    i = 1
    from csv import reader
    with open(dataset, 'r') as read_obj:
        csv_reader = reader(read_obj)
        global datasetRows
        datasetRows = []
        for row in csv_reader:
            datasetRows.append(str(row))
    i = 0
    labelCount = []
    while i < len(df):
        labelAdd = df['Labels'][i]
        labelCount.append(str(labelAdd))
        i = i + 1
    i = 0
    ransomware = 0
    rat = 0
    keylogger = 0
    benign = 0
    while i < len(labelCount):
        if labelCount[i] == '1':
            benign = benign + 1
            i = i + 1
        elif labelCount[i] == '2':
            ransomware = ransomware + 1
            i = i + 1
        elif labelCount[i] == '3':
            keylogger = keylogger + 1
            i = i + 1
        elif labelCount[i] == '4':
            rat = rat + 1
            i = i + 1
    types = ['Benign', 'Ransomware', 'Keylogger', 'RAT']
    values = [benign, ransomware, keylogger, rat]
    ypos = np.arange(len(types))
    plt.xlabel('Sample Types')
    plt.ylabel('No. of Samples')
    plt.title('Dataset Sample Division')
    plt.xticks(ypos, types)
    plt.bar(ypos, values)
    barColour = plt.bar(ypos, values)
    barColour[0].set_color('g')
    barColour[1].set_color('r')
    barColour[2].set_color('r')
    barColour[3].set_color('r')
    plt.show()


def results():
    windowRESULTS = tkinter.Tk()
    windowRESULTS.title('My Malware Analysis Tool')
    windowRESULTS.geometry('500x200')
    windowRESULTS.resizable(False, False)
    label0 = tkinter.Label(windowRESULTS, text='Classification: ' +
        classifiedMalware, font=('Arial Black', 18))
    label0.pack()


def submitLog():
    featureList = []
    featureSet = pd.read_csv(dataset)
    for cols in featureSet.columns:
        if cols == 'Labels':
            pass
        else:
            featureList.append(cols)
    label = []
    text = []
    label.append('0')
    filename = filedialog.askopenfilename(initialdir=str(os.getcwd()) +
        '/Malware_Analysis_Tool_Files/logs/', title='Select a Log')
    with open(filename) as f:
        content = f.read()
    content.replace(',', ' ')
    content.replace('"', ' ')
    text.append(content)
    vectorizer = CountVectorizer(stop_words='english', max_features=1001,
        vocabulary=featureList)
    dtm = vectorizer.fit_transform(text)
    dfNewSample = pd.DataFrame(dtm.toarray(), index=label, columns=
        vectorizer.get_feature_names())
    df = pd.read_csv(dataset)
    features = list(df.columns.values.tolist())
    features.remove('Labels')
    X = df[features]
    y = df['Labels']
    dtree = DecisionTreeClassifier()
    dtree = dtree.fit(X, y)
    classResult = dtree.predict(dfNewSample)
    global classifiedMalware
    classifiedMalware = ''
    if classResult[0] == 1:
        classifiedMalware = 'Benign'
    elif classResult[0] == 2:
        classifiedMalware = 'Ransomware'
    elif classResult[0] == 3:
        classifiedMalware = 'Keylogger'
    elif classResult[0] == 4:
        classifiedMalware = 'Remote Administration Tool (RAT)'
    results()


def about():
    windowABOUT = tkinter.Tk()
    windowABOUT.title('My Malware Analysis Tool')
    windowABOUT.geometry('600x150')
    windowABOUT.resizable(False, False)
    label0 = tkinter.Label(windowABOUT, text=
        """
This program was developed to allow machine learning algoritms 
to identify determine the classification of malware. 


Created by William Fitzgerald"""
        , font=('Arial Black', 12))
    label0.pack()


<mask token>
windowMENU.title('My Malware Analysis Tool')
windowMENU.geometry('250x300')
windowMENU.resizable(False, False)
<mask token>
windowMENU.mainloop()

<mask token>


def createFolder(directory):
    if not os.path.exists(directory):
        os.makedirs(directory)
        global filesForProgram
        filesForProgram = directory


createFolder(str(os.getcwd()) + '/Malware_Analysis_Tool_Files/')
createFolder(str(os.getcwd()) + '/Malware_Analysis_Tool_Files/logs/')
createFolder(str(os.getcwd()) + '/Malware_Analysis_Tool_Files/Dataset/')


def dirLocation():
    global dirname
    dirname = filedialog.askdirectory(initialdir='/', title=
        'Please select a directory')
    return dirname


def popup():
    global classificationSelection
    classSelect = tkinter.Tk()
    classificationSelection = StringVar(classSelect)
    classificationSelection.set('Benign')
    classSelect.title('Select Classification')
    classSelect.geometry('250x70')
    classSelect.resizable(False, False)
    w = OptionMenu(classSelect, classificationSelection, 'Benign',
        'Ransomware', 'Keylogger', 'RAT')
    w.pack()
    saveBtn = tkinter.Button(classSelect, text='Select', fg='black', width=
        5, height=1, command=lambda : classSelect.destroy()).place(x=90, y=35)


def getJSON(filePathName):
    with open(filePathName, 'r') as fp:
        return json.load(fp)


def logExtract():
    path = dirLocation()
    global logFiles
    logFiles = []
    for r, d, f in os.walk(path):
        for file in f:
            if '.json' in file:
                logFiles.append(os.path.join(r, file))
    popup()
    i = 0
    saveLocation = str(os.getcwd()) + '/Malware_Analysis_Tool_Files/logs/'
    for r, d, f in os.walk(saveLocation):
        for file in f:
            if str(classificationSelection.get()) in file:
                i = i + 1
    while i < len(logFiles):
        newFileName = str(classificationSelection.get()) + str(i) + '.log'
        newFile = open(saveLocation + newFileName, 'w')
        myObj = getJSON(logFiles[i])
        strings = myObj.get('strings', '')
        behavior = myObj.get('behavior', '')
        newFile.write(str(strings) + str(behavior))
        newFile.close()
        i += 1


def createDataset():
    path = str(os.getcwd()) + '/Malware_Analysis_Tool_Files/logs/'
    labels = []
    text = []
    for filename in os.listdir(path):
        if 'Benign' in filename:
            labels.append('1')
        elif 'Ransomware' in filename:
            labels.append('2')
        elif 'Keylogger' in filename:
            labels.append('3')
        elif 'RAT' in filename:
            labels.append('4')
        else:
            pass
        filename = os.path.join(path, filename)
        with open(filename) as f:
            content = f.read()
        content.replace(',', ' ')
        content.replace('"', ' ')
        text.append(content)
    vectorizer = CountVectorizer(stop_words='english', max_features=1000)
    dtm = vectorizer.fit_transform(text)
    df = pd.DataFrame(dtm.toarray(), index=labels, columns=vectorizer.
        get_feature_names())
    df.index.name = 'Labels'
    df.to_csv(str(os.getcwd()) + '/Malware_Analysis_Tool_Files/Dataset/' +
        'Dataset.csv')
    features_list = vectorizer.get_feature_names()


def loadDataset():
    global dataset
    dataset = filedialog.askopenfilename(initialdir=str(os.getcwd()) +
        '/Malware_Analysis_Tool_Files/Dataset/', title='Select Dataset')
    df = pd.read_csv(dataset, usecols=['Labels'])
    global featureList
    featureList = []
    featureSet = pd.read_csv(dataset)
    for cols in featureSet.columns:
        if cols == 'Labels':
            pass
        else:
            featureList.append(cols)
    i = 1
    from csv import reader
    with open(dataset, 'r') as read_obj:
        csv_reader = reader(read_obj)
        global datasetRows
        datasetRows = []
        for row in csv_reader:
            datasetRows.append(str(row))
    i = 0
    labelCount = []
    while i < len(df):
        labelAdd = df['Labels'][i]
        labelCount.append(str(labelAdd))
        i = i + 1
    i = 0
    ransomware = 0
    rat = 0
    keylogger = 0
    benign = 0
    while i < len(labelCount):
        if labelCount[i] == '1':
            benign = benign + 1
            i = i + 1
        elif labelCount[i] == '2':
            ransomware = ransomware + 1
            i = i + 1
        elif labelCount[i] == '3':
            keylogger = keylogger + 1
            i = i + 1
        elif labelCount[i] == '4':
            rat = rat + 1
            i = i + 1
    types = ['Benign', 'Ransomware', 'Keylogger', 'RAT']
    values = [benign, ransomware, keylogger, rat]
    ypos = np.arange(len(types))
    plt.xlabel('Sample Types')
    plt.ylabel('No. of Samples')
    plt.title('Dataset Sample Division')
    plt.xticks(ypos, types)
    plt.bar(ypos, values)
    barColour = plt.bar(ypos, values)
    barColour[0].set_color('g')
    barColour[1].set_color('r')
    barColour[2].set_color('r')
    barColour[3].set_color('r')
    plt.show()


def results():
    windowRESULTS = tkinter.Tk()
    windowRESULTS.title('My Malware Analysis Tool')
    windowRESULTS.geometry('500x200')
    windowRESULTS.resizable(False, False)
    label0 = tkinter.Label(windowRESULTS, text='Classification: ' +
        classifiedMalware, font=('Arial Black', 18))
    label0.pack()


def submitLog():
    featureList = []
    featureSet = pd.read_csv(dataset)
    for cols in featureSet.columns:
        if cols == 'Labels':
            pass
        else:
            featureList.append(cols)
    label = []
    text = []
    label.append('0')
    filename = filedialog.askopenfilename(initialdir=str(os.getcwd()) +
        '/Malware_Analysis_Tool_Files/logs/', title='Select a Log')
    with open(filename) as f:
        content = f.read()
    content.replace(',', ' ')
    content.replace('"', ' ')
    text.append(content)
    vectorizer = CountVectorizer(stop_words='english', max_features=1001,
        vocabulary=featureList)
    dtm = vectorizer.fit_transform(text)
    dfNewSample = pd.DataFrame(dtm.toarray(), index=label, columns=
        vectorizer.get_feature_names())
    df = pd.read_csv(dataset)
    features = list(df.columns.values.tolist())
    features.remove('Labels')
    X = df[features]
    y = df['Labels']
    dtree = DecisionTreeClassifier()
    dtree = dtree.fit(X, y)
    classResult = dtree.predict(dfNewSample)
    global classifiedMalware
    classifiedMalware = ''
    if classResult[0] == 1:
        classifiedMalware = 'Benign'
    elif classResult[0] == 2:
        classifiedMalware = 'Ransomware'
    elif classResult[0] == 3:
        classifiedMalware = 'Keylogger'
    elif classResult[0] == 4:
        classifiedMalware = 'Remote Administration Tool (RAT)'
    results()


def about():
    windowABOUT = tkinter.Tk()
    windowABOUT.title('My Malware Analysis Tool')
    windowABOUT.geometry('600x150')
    windowABOUT.resizable(False, False)
    label0 = tkinter.Label(windowABOUT, text=
        """
This program was developed to allow machine learning algoritms 
to identify determine the classification of malware. 


Created by William Fitzgerald"""
        , font=('Arial Black', 12))
    label0.pack()


windowMENU = tkinter.Tk()
windowMENU.title('My Malware Analysis Tool')
windowMENU.geometry('250x300')
windowMENU.resizable(False, False)
buttonONE = tkinter.Button(windowMENU, text='Log Extract', fg='black',
    width=15, height=2, command=logExtract).place(x=50, y=25)
buttonTWO = tkinter.Button(windowMENU, text='Create Dataset', fg='black',
    width=15, height=2, command=lambda : createDataset()).place(x=50, y=75)
buttonTHREE = tkinter.Button(windowMENU, text='Load Dataset', fg='black',
    width=15, height=2, command=lambda : loadDataset()).place(x=50, y=125)
buttonFOUR = tkinter.Button(windowMENU, text='Submit Log', fg='black',
    width=15, height=2, command=lambda : submitLog()).place(x=50, y=175)
buttonABOUT = tkinter.Button(windowMENU, text='About', fg='black', width=15,
    height=2, command=lambda : about()).place(x=50, y=225)
windowMENU.mainloop()

import os, json, tkinter, sys, csv
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
from tkinter import filedialog
from tkinter import messagebox
from tkinter import *
from PIL import ImageTk, Image
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier
def createFolder(directory):
    if not os.path.exists(directory):
        os.makedirs(directory)
        global filesForProgram
        filesForProgram = directory
createFolder(str(os.getcwd()) + "/Malware_Analysis_Tool_Files/")
createFolder(str(os.getcwd()) + "/Malware_Analysis_Tool_Files/logs/")
createFolder(str(os.getcwd()) + "/Malware_Analysis_Tool_Files/Dataset/")
def dirLocation():
    global dirname
    dirname = filedialog.askdirectory(initialdir="/",title='Please select a directory')
    return dirname
def popup():
    global classificationSelection
    classSelect = tkinter.Tk()
    classificationSelection = StringVar(classSelect)
    classificationSelection.set("Benign")
    classSelect.title("Select Classification")
    classSelect.geometry("250x70")
    classSelect.resizable(False, False)
    w = OptionMenu(classSelect, classificationSelection, "Benign", "Ransomware", "Keylogger", "RAT")
    w.pack()
    saveBtn = tkinter.Button(classSelect, text="Select", fg='black', width=5, height=1, command=lambda: classSelect.destroy()).place(x=90, y=35)
def getJSON(filePathName):
    with open(filePathName, 'r') as fp:
        return json.load(fp)
def logExtract():
    path = dirLocation()
    global logFiles
    logFiles = []
    for r, d, f in os.walk(path):
        for file in f:
            if '.json' in file:
                logFiles.append(os.path.join(r, file))
    popup()
    i = 0
    saveLocation = str(os.getcwd())+"/Malware_Analysis_Tool_Files/logs/"
    for r, d, f in os.walk(saveLocation):
        for file in f:
            if str(classificationSelection.get()) in file:
                i = i + 1
    while i < (len(logFiles)): # error is here
        newFileName = str(classificationSelection.get()) + str(i) + ".log"
        newFile = open(saveLocation + newFileName, "w")
        myObj = getJSON(logFiles[i])
        strings = myObj.get("strings", "")
        behavior = myObj.get("behavior", "")
        newFile.write(str(strings) + str(behavior))
        newFile.close()
        i += 1
def createDataset():
    path =  str(os.getcwd()) + "/Malware_Analysis_Tool_Files/logs/"# path of files
    labels = []
    text = []
    for filename in os.listdir(path):
        if "Benign" in filename:
            labels.append("1")
        elif "Ransomware" in filename:
            labels.append("2")
        elif "Keylogger" in filename:
            labels.append("3")
        elif "RAT" in filename:
            labels.append("4")
        else:
            pass
        filename = os.path.join(path, filename)
        with open(filename) as f:
            content = f.read()
        content.replace(",", " ")
        content.replace('"', " ")
        text.append(content)
    vectorizer = CountVectorizer(stop_words='english', max_features=1000)
    dtm = vectorizer.fit_transform(text)
    df = pd.DataFrame(dtm.toarray(), index=labels, columns=vectorizer.get_feature_names())
    df.index.name = "Labels"
    df.to_csv(str(os.getcwd()) + "/Malware_Analysis_Tool_Files/Dataset/" + r'Dataset.csv')
    features_list = vectorizer.get_feature_names()
def loadDataset():
    global dataset
    dataset =  filedialog.askopenfilename(initialdir = str(os.getcwd()) + "/Malware_Analysis_Tool_Files/Dataset/",title = "Select Dataset")
    df = pd.read_csv(dataset, usecols=['Labels'])
    global featureList
    featureList = []
    featureSet = pd.read_csv(dataset)
    for cols in featureSet.columns:
        if cols == "Labels":
            pass
        else:
            featureList.append(cols)
    i = 1
    from csv import reader
    with open(dataset, 'r') as read_obj:
        csv_reader = reader(read_obj)
        global datasetRows
        datasetRows = []
        for row in csv_reader:
            datasetRows.append(str(row))
    i = 0
    labelCount = []
    while i < len(df):
        labelAdd = df['Labels'][i]
        labelCount.append(str(labelAdd))
        i = i + 1
    i = 0
    ransomware = 0
    rat = 0
    keylogger = 0
    benign = 0
    while i < len(labelCount):
        if labelCount[i] == '1': #benign
            benign = benign + 1
            i = i + 1
        elif labelCount[i] == '2': #ransomware
            ransomware = ransomware + 1
            i = i + 1
        elif labelCount[i] == '3': #keylogger
            keylogger = keylogger + 1
            i = i + 1
        elif labelCount[i] == '4': #rat
            rat = rat + 1
            i = i + 1
    types = ['Benign', 'Ransomware', 'Keylogger', 'RAT']
    values = [benign, ransomware, keylogger, rat]
    ypos = np.arange(len(types))
    plt.xlabel("Sample Types")
    plt.ylabel("No. of Samples")
    plt.title("Dataset Sample Division")
    plt.xticks(ypos, types)
    plt.bar(ypos, values)
    barColour = plt.bar(ypos, values)
    barColour[0].set_color('g')
    barColour[1].set_color('r')
    barColour[2].set_color('r')
    barColour[3].set_color('r')
    plt.show()
def results():
    windowRESULTS = tkinter.Tk()
    windowRESULTS.title("My Malware Analysis Tool")
    windowRESULTS.geometry("500x200")
    windowRESULTS.resizable(False, False)
    label0 = tkinter.Label(windowRESULTS, text="Classification: "+ classifiedMalware,font=("Arial Black", 18))
    label0.pack()
def submitLog():
    featureList = []
    featureSet = pd.read_csv(dataset)
    for cols in featureSet.columns:
        if cols == "Labels":
            pass
        else:
            featureList.append(cols)
    label = []
    text = [] 
    label.append("0")
    filename =  filedialog.askopenfilename(initialdir = str(os.getcwd()) + "/Malware_Analysis_Tool_Files/logs/",title = "Select a Log")
    with open(filename) as f:
        content = f.read()
    content.replace(",", " ")
    content.replace('"', " ")
    text.append(content)
    vectorizer = CountVectorizer(stop_words='english', max_features=1001, vocabulary=featureList)
    dtm = vectorizer.fit_transform(text)
    dfNewSample = pd.DataFrame(dtm.toarray(), index=label, columns=vectorizer.get_feature_names())
    df = pd.read_csv(dataset)
    features = list(df.columns.values.tolist())
    features.remove("Labels")
    X = df[features]
    y = df['Labels']
    dtree = DecisionTreeClassifier()
    dtree = dtree.fit(X, y)
    classResult = dtree.predict(dfNewSample)
    global classifiedMalware
    classifiedMalware = "" #default
    if classResult[0] == 1:
        classifiedMalware = "Benign"
    elif classResult[0] == 2:
        classifiedMalware = "Ransomware"
    elif classResult[0] == 3:
        classifiedMalware = "Keylogger"
    elif classResult[0] == 4:
        classifiedMalware = "Remote Administration Tool (RAT)"
    results()
def about():
    windowABOUT = tkinter.Tk()
    windowABOUT.title("My Malware Analysis Tool")
    windowABOUT.geometry("600x150")
    windowABOUT.resizable(False, False)
    label0 = tkinter.Label(windowABOUT, text="\nThis program was developed to allow machine learning algoritms \nto identify determine the classification of malware. \n\n\nCreated by William Fitzgerald",font=("Arial Black", 12))
    label0.pack()
windowMENU = tkinter.Tk()
windowMENU.title("My Malware Analysis Tool")
windowMENU.geometry("250x300")
windowMENU.resizable(False, False)
buttonONE = tkinter.Button(windowMENU, text="Log Extract", fg='black', width=15, height=2, command=logExtract).place(x=50, y=25)
buttonTWO = tkinter.Button(windowMENU, text="Create Dataset", fg='black', width=15, height=2, command=lambda: createDataset()).place(x=50, y=75)
buttonTHREE = tkinter.Button(windowMENU, text="Load Dataset", fg='black', width=15, height=2, command=lambda: loadDataset()).place(x=50, y=125)
buttonFOUR = tkinter.Button(windowMENU, text="Submit Log", fg='black', width=15, height=2, command=lambda: submitLog()).place(x=50, y=175)
buttonABOUT = tkinter.Button(windowMENU, text="About", fg='black', width=15, height=2, command=lambda: about()).place(x=50, y=225)
windowMENU.mainloop()
