from lxml import etree
import os
import json
import sys, traceback

"""

1. get filename from folder
2. read into lxml
3. extract all event nodes
4. initialize the result dict
5. for each node
	get operation and path
	if no operation-path elemen in dict
		create a new entry, add value 1
	else
		increment value of the entry
6. write this as a json?


"""

def updateDataFrame(element, results, label):

    final = []
    # read from disk
    if os.path.exists('./lvl4/binaries.df'):
        df = open('./lvl4/binaries.df','r+')
    
        final = json.loads(df.read())
        df.close()

    # update
    final.append({element : results})
    #print(final)

    print(json.dumps(final, sort_keys=True, indent=4))


    # write to disk
    df = open('./lvl4/binaries.df','w+')
    df.write(json.dumps(final))
    df.close()

def parseXML(filepath):

    doc = etree.parse(filepath)

    filename = os.path.basename(filepath)
    auxname = filename.split(".")
    auxname = filename[:filename.index(auxname[-1])]+"exe"
    

    processpath="".join(["C:\\tmp\\sample\\",auxname])

    try:

        # extract all imagepath
        expr = "processlist/process/ImagePath"
        pi = doc.xpath(expr)
        
        for elem in pi:
            if elem.text.startswith("C:\\tmp\\sample"):
                processpath=elem.text

        expr = "processlist/process[ImagePath = $name ]/ProcessIndex"
        pi = doc.xpath(expr, name = processpath )[0].text

        print(pi)
        expr = "eventlist/event[ProcessIndex= $name ]"
        e = doc.xpath(expr, name = pi)

        result={}

        for event in e:
            try:
                op = event.xpath('Operation')[0].text
                path = event.xpath('Path')[0].text
                id = op+"_"+path
                if id in list(result.keys()):
                    result[id]+=1
                else:
                    result[id]=1

            except:
                continue

        updateDataFrame(os.path.basename(filepath), result, 'safe')

    except Exception:
        print("filename not found! "+processpath)
        traceback.print_exc(file=sys.stdout)
    
if __name__ == '__main__':
    parseXML('./lvl3/wireshark-win32-1.4.4.xml')
from lxml import etree
import os
import json
import sys, traceback

"""

1. get filename from folder
2. read into lxml
3. extract all event nodes
4. initialize the result dict
5. for each node
	get operation and path
	if no operation-path elemen in dict
		create a new entry, add value 1
	else
		increment value of the entry
6. write this as a json?


"""

def updateDataFrame(element, results, label):

    final = []
    # read from disk
    if os.path.exists('./lvl4/binaries.df'):
        df = open('./lvl4/binaries.df','r+')
    
        final = json.loads(df.read())
        df.close()

    # update
    final.append({element : results})
    #print(final)

    print(json.dumps(final, sort_keys=True, indent=4))


    # write to disk
    df = open('./lvl4/binaries.df','w+')
    df.write(json.dumps(final))
    df.close()

def parseXML(filepath):

    doc = etree.parse(filepath)

    filename = os.path.basename(filepath)
    auxname = filename.split(".")
    auxname = filename[:filename.index(auxname[-1])]+"exe"
    

    processpath="".join(["C:\\tmp\\sample\\",auxname])

    try:

        # extract all imagepath
        expr = "processlist/process/ImagePath"
        pi = doc.xpath(expr)
        
        for elem in pi:
            if elem.text.startswith("C:\\tmp\\sample"):
                processpath=elem.text

        expr = "processlist/process[ImagePath = $name ]/ProcessIndex"
        pi = doc.xpath(expr, name = processpath )[0].text

        print(pi)
        expr = "eventlist/event[ProcessIndex= $name ]"
        e = doc.xpath(expr, name = pi)

        result={}

        for event in e:
            try:
                op = event.xpath('Operation')[0].text
                path = event.xpath('Path')[0].text
                id = op+"_"+path
                if id in list(result.keys()):
                    result[id]+=1
                else:
                    result[id]=1

            except:
                continue

        updateDataFrame(os.path.basename(filepath), result, 'safe')

    except Exception:
        print("filename not found! "+processpath)
        traceback.print_exc(file=sys.stdout)
    
if __name__ == '__main__':
    parseXML('./lvl3/wireshark-win32-1.4.4.xml')
1. get filename from folder 2. read into lxml 3. extract all event nodes 4. initialize the result dict 5. for each node 	get operation and path 	if no operation-path elemen in dict 		create a new entry, add value 1 	else 		increment value of the entry 6. write this as a json? # read from disk # update #print(final) # write to disk # extract all imagepath