#!/usr/bin/env python3
# sudo python3 ./reportevidence.py --host_iface enp7s0


from scapy.all import *
import argparse
import binascii
from datetime import datetime

previous_snapshot = None

def get_if(host_iface):
    iface = None
    for i in get_if_list():
        if host_iface in i:
            iface = i
            break
    if not iface:
        print(f"Cannot find interface {host_iface}")
    return iface

def print_if_different(name, v1, v2):
    if v1 != v2:
        print(f">{name}: {v1.hex()} -> {v2.hex()}")

def print_v(name, v):
    print(f">{name}: {v.hex()}")

def handle_pkt(pkt):
    pld = pkt[Raw].load
    devreg = pld[:16]
    devtbl = pld[16:32]
    devprog = pld[32:48]
    current_snapshot = {'devreg': devreg, 'devtbl': devtbl, 'devprog': devprog}
    global previous_snapshot
    if None == previous_snapshot:
        previous_snapshot = current_snapshot
        print_v('reg', current_snapshot['devreg'])
        print_v('tbl', current_snapshot['devtbl'])
        print_v('prg', current_snapshot['devprog'])
    else:
        if previous_snapshot != current_snapshot:
            print_if_different('reg', previous_snapshot['devreg'], current_snapshot['devreg'])
            print_if_different('tbl', previous_snapshot['devtbl'], current_snapshot['devtbl'])
            print_if_different('prg', previous_snapshot['devprog'], current_snapshot['devprog'])
            #print(f"Warning!")
            #print(f"[{str(datetime.now().time())}] Potentially unauthorized program change")
            #print(f"Old: {oldprog.hex()}")
            #print(f"New: {devprog.hex()}")
            previous_snapshot = current_snapshot
        else:
            #print(".", end="")
            #sys.stdout.flush()
            print(">.")
    #print(f"devreg: {devreg}\ndevtbl: {devtbl}\ndevprog: {devprog}")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--host_iface', type=str, help="The interface to monitor")
    args = parser.parse_args()
    iface = get_if(args.host_iface)
    #print("Monitoring " + args.host_iface)
    sniff(iface=iface, prn=lambda x: handle_pkt(x), filter="ether[12:2] = 0x5241")

if __name__ == '__main__':
    main()