% Scapy IPv4 layers tests

############
############
+ Test IP options

= IP options individual assembly
~ IP options
r = raw(IPOption())
r
assert(r == b'\x00\x02')
r = raw(IPOption_NOP())
r
assert(r == b'\x01')
r = raw(IPOption_EOL())
r
assert(r == b'\x00')
r = raw(IPOption_LSRR(routers=["1.2.3.4","5.6.7.8"]))
r
assert(r == b'\x83\x0b\x04\x01\x02\x03\x04\x05\x06\x07\x08')
r = raw(IPOption_Timestamp(internet_address='192.168.15.7', timestamp=11223344))
r
assert(r == b'D\x0c\t\x01\xc0\xa8\x0f\x07\x00\xabA0')
r = raw(IPOption_Timestamp(flg=0, length=8))
r
assert(r == b'D\x08\t\x00\x00\x00\x00\x00')

= IP options individual dissection
~ IP options
io = IPOption(b"\x00")
io
assert(io.option == 0 and isinstance(io, IPOption_EOL))
io = IPOption(b"\x01")
io
assert(io.option == 1 and isinstance(io, IPOption_NOP))
lsrr=b'\x83\x0b\x04\x01\x02\x03\x04\x05\x06\x07\x08'
p=IPOption_LSRR(lsrr)
p
q=IPOption(lsrr)
q
assert(p == q)

= IP assembly and dissection with options
~ IP options
p = IP(src="9.10.11.12",dst="13.14.15.16",options=IPOption_SDBM(addresses=["1.2.3.4","5.6.7.8"]))/TCP()
r = raw(p)
r
assert(r == b'H\x00\x004\x00\x01\x00\x00@\x06\xa2q\t\n\x0b\x0c\r\x0e\x0f\x10\x95\n\x01\x02\x03\x04\x05\x06\x07\x08\x00\x00\x00\x14\x00P\x00\x00\x00\x00\x00\x00\x00\x00P\x02 \x00_K\x00\x00')
q=IP(r)
q
assert( isinstance(q.options[0],IPOption_SDBM) )
assert( q[IPOption_SDBM].addresses[1] == "5.6.7.8" )
p.options[0].addresses[0] = '5.6.7.8'
assert( IP(raw(p)).options[0].addresses[0] == '5.6.7.8' )
p = IP(src="9.10.11.12", dst="13.14.15.16", options=[IPOption_NOP(),IPOption_LSRR(routers=["1.2.3.4","5.6.7.8"]),IPOption_Security(transmission_control_code="XYZ")])/TCP()
p
r = raw(p)
r
assert(r == b'K\x00\x00@\x00\x01\x00\x00@\x06\xf3\x83\t\n\x0b\x0c\r\x0e\x0f\x10\x01\x83\x0b\x04\x01\x02\x03\x04\x05\x06\x07\x08\x82\x0b\x00\x00\x00\x00\x00\x00XYZ\x00\x00\x14\x00P\x00\x00\x00\x00\x00\x00\x00\x00P\x02 \x00o[\x00\x00')
q = IP(r)
q
assert(q[IPOption_LSRR].get_current_router() == "1.2.3.4")
assert(q[IPOption_Security].transmission_control_code == b"XYZ")
assert(q[TCP].flags == 2)


############
############
+ Sessions

= IPSession - dissect fragmented IP packets on-the-flow
packet = IP()/("data"*1000)
frags = fragment(packet)
tmp_file = get_temp_file()
wrpcap(tmp_file, frags)

dissected_packets = []
def callback(pkt):
    dissected_packets.append(pkt)

sniff(offline=tmp_file, session=IPSession, prn=callback)
assert len(dissected_packets) == 1
assert raw(dissected_packets[0]) == raw(packet)

= StringBuffer

buffer = StringBuffer()
assert not buffer

buffer.append(b"kie", 5)
buffer.append(b"e", 11)
buffer.append(b"pi", 2)
buffer.append(b"pi", 9)
buffer.append(b"n", 4)

assert bytes_hex(bytes(buffer)) == b'0070696e6b696500706965'
assert len(buffer) == 11
assert buffer


############
############
+ Test fragment() / defragment() functions

= fragment()
payloadlen, fragsize = 100, 8
assert fragsize % 8 == 0
fragcount = (payloadlen // fragsize) + bool(payloadlen % fragsize)
* create the packet
pkt = IP() / ("X" * payloadlen)
* create the fragments
frags = fragment(pkt, fragsize)
* count the fragments
assert len(frags) == fragcount
* each fragment except the last one should have MF set
assert all(p.flags == 1 for p in frags[:-1])
assert frags[-1].flags == 0
* each fragment except the last one should have a payload of fragsize bytes
assert all(len(p.payload) == 8 for p in frags[:-1])
assert len(frags[-1].payload) == ((payloadlen % fragsize) or fragsize)

= fragment() and overloaded_fields
pkt1 = Ether() / IP() / UDP()
pkt2 = fragment(pkt1)[0]
pkt3 = pkt2.__class__(raw(pkt2))
assert pkt1[IP].proto == pkt2[IP].proto == pkt3[IP].proto

= fragment() already fragmented packets
payloadlen = 1480 * 3
ffrags = fragment(IP() / ("X" * payloadlen), 1480)
ffrags = fragment(ffrags, 1400)
len(ffrags) == 6
* each fragment except the last one should have MF set
assert all(p.flags == 1 for p in ffrags[:-1])
assert ffrags[-1].flags == 0
* fragment offset should be well computed
plen = 0
for p in ffrags:
    assert p.frag == plen // 8
    plen += len(p.payload)

assert plen == payloadlen

= fragment() with non-multiple-of-8 MTU
paylen = 1400 + 1
frags1 = fragment(IP() / ("X" * paylen), paylen)
assert len(frags1) == 1
frags2 = fragment(IP() / ("X" * (paylen + 1)), paylen)
assert len(frags2) == 2
assert len(frags2[0]) == 20 + paylen - paylen % 8
assert len(frags2[1]) == 20 + 1 + paylen % 8

= defrag()
nonfrag, unfrag, badfrag = defrag(frags)
assert not nonfrag
assert not badfrag
assert len(unfrag) == 1

= defragment()
defrags = defragment(frags)
* we should have one single packet
assert len(defrags) == 1
* which should be the same as pkt reconstructed
assert defrags[0] == IP(raw(pkt))

= defragment() uses timestamp of last fragment
payloadlen, fragsize = 100, 8
assert fragsize % 8 == 0
packet = Ether()/IP()/("X" * payloadlen)
frags = fragment(packet, fragsize)
for i,frag in enumerate(frags):
    frag.time -= 100 + i

last_time = max(frag.time for frag in frags)
defrags = defragment(frags)
assert defrags[0].time == last_time
nonfrag, defrags, badfrag = defrag(frags)
assert defrags[0].time == last_time

= defragment() - Missing fragments

pkts = fragment(IP(dst="10.0.0.5")/ICMP()/("X"*1500))
assert len(defragment(pkts[1:])) == 1

= defrag() / defragment() - Real DNS packets

import base64

a = base64.b64decode('bnmYJ63mREVTUwEACABFAAV0U8UgADIR+u0EAgIECv0DxAA1sRIL83Z7gbCBgAABAB0AAAANA255YwNnb3YAAP8AAcAMAAYAAQAAA4QAKgZ2d2FsbDDADApob3N0bWFzdGVywAx4Og5wAAA4QAAADhAAJOoAAAACWMAMAC4AAQAAA4QAmwAGCAIAAAOEWWm9jVlgdP0mfQNueWMDZ292AHjCDBL0C1rEKUjsuG6Zg3+R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YWxsNMAMwAwADwABAAADhAALAAoGdndhbGwzwAzADAAPAAEAAAOEAAsACgZ2d2FsbDXADMAMAA8AAQAAA4QACwAKBnZ3YWxsNsAMwAwADwABAAADhAALAAoGdndhbGw3wAzADAAPAAEAAAOEAAsACgZ2d2FsbDjADMAMAA8AAQAAA4QACwBkBnZ3YWxsMcAMwAwALgABAAADhACbAA8IAgAAA4RZab2NWWB0/SZ9A255YwNnb3YAooXBSj6PfsdBd8sEN/2AA4cvOl2bcioO')
c = base64.b64decode('bnmYJ63mREVTUwEACABFAAFHU8UBWDIRHcMEAgIECv0DxDtlufeCT1zQktat4aEVA8MF0FO1sNbpEQtqfu5Al//OJISaRvtaArR/tLUj2CoZjS7uEnl7QpP/Ui/gR0YtyLurk9yTw7Vei0lSz4cnaOJqDiTGAKYwzVxjnoR1F3n8lplgQaOalVsHx9UAAQABAAADLAAEobkBA8epAAEAAQAAAywABKG5AQzHvwABAAEAAAMsAASnmYIMx5MAAQABAAADLAAEp5mCDcn9AAEAAQAAAqUABKeZhAvKFAABAAEAAAOEAAShuQIfyisAAQABAAADhAAEobkCKcpCAAEAAQAAA4QABKG5AjPKWQABAAEAAAOEAAShuQI9ynAAAQABAAADhAAEobkCC8nPAAEAAQAAA4QABKG5AgzJ5gABAAEAAAOEAASnmYQMAAApIAAAAAAAAAA=')
d = base64.b64decode('////////REVTUwEACABFAABOawsAAIARtGoK/QExCv0D/wCJAIkAOry/3wsBEAABAAAAAAAAIEVKRkRFQkZFRUJGQUNBQ0FDQUNBQ0FDQUNBQ0FDQUFBAAAgAAEAABYP/WUAAB6N4XIAAB6E4XsAAACR/24AADyEw3sAABfu6BEAAAkx9s4AABXB6j4AAANe/KEAAAAT/+wAAB7z4QwAAEuXtGgAAB304gsAABTB6z4AAAdv+JAAACCu31EAADm+xkEAABR064sAABl85oMAACTw2w8AADrKxTUAABVk6psAABnF5joAABpA5b8AABjP5zAAAAqV9WoAAAUW+ukAACGS3m0AAAEP/vAAABoa5eUAABYP6fAAABX/6gAAABUq6tUAADXIyjcAABpy5Y0AABzb4yQAABqi5V0AAFXaqiUAAEmRtm4AACrL1TQAAESzu0wAAAzs8xMAAI7LcTQAABxN47IAAAbo+RcAABLr7RQAAB3Q4i8AAAck+NsAABbi6R0AAEdruJQAAJl+ZoEAABDH7zgAACOA3H8AAAB5/4YAABQk69sAAEo6tcUAABJU7asAADO/zEAAABGA7n8AAQ9L8LMAAD1DwrwAAB8F4PoAABbG6TkAACmC1n0AAlHErjkAABG97kIAAELBvT4AAEo0tcsAABtC5L0AAA9u8JEAACBU36sAAAAl/9oAABBO77EAAA9M8LMAAA8r8NQAAAp39YgAABB874MAAEDxvw4AAEgyt80AAGwsk9MAAB1O4rEAAAxL87QAADtmxJkAAATo+xcAAAM8/MMAABl55oYAACKh3V4AACGj3lwAAE5ssZMAAC1x0o4AAAO+/EEAABNy7I0AACYp2dYAACb+2QEAABB974IAABc36MgAAA1c8qMAAAf++AEAABDo7xcAACLq3RUAAA8L8PQAAAAV/+oAACNU3KsAABBv75AAABFI7rcAABuH5HgAABAe7+EAAB++4EEAACBl35oAAB7c4SMAADgJx/YAADeVyGoAACKN3XIAAA/C8D0AAASq+1UAAOHPHjAAABRI67cAAABw/48=')

old_debug_dissector = conf.debug_dissector
conf.debug_dissector = 0
plist = PacketList([Ether(x) for x in [a, b, c, d]])
conf.debug_dissector = old_debug_dissector

left, defragmented, errored = defrag(plist)
assert len(left) == 1
assert left[0] == Ether(d)
assert len(defragmented) == 1
assert len(defragmented[0]) == 3093
assert defragmented[0][DNSRR].rrname == b'nyc.gov.'
assert len(errored) == 0

plist_def = defragment(plist)
assert len(plist_def) == 2
assert len(plist_def[0]) == 3093
assert plist_def[0][DNSRR].rrname == b'nyc.gov.'

= Packet().fragment()
payloadlen, fragsize = 100, 8
assert fragsize % 8 == 0
fragcount = (payloadlen // fragsize) + bool(payloadlen % fragsize)
* create the packet
pkt = IP() / ("X" * payloadlen)
* create the fragments
frags = pkt.fragment(fragsize)
* count the fragments
assert len(frags) == fragcount
* each fragment except the last one should have MF set
assert all(p.flags == 1 for p in frags[:-1])
assert frags[-1].flags == 0
* each fragment except the last one should have a payload of fragsize bytes
assert all(len(p.payload) == 8 for p in frags[:-1])
assert len(frags[-1].payload) == ((payloadlen % fragsize) or fragsize)

= Packet().fragment() and overloaded_fields
pkt1 = Ether() / IP() / UDP()
pkt2 = pkt1.fragment()[0]
pkt3 = pkt2.__class__(raw(pkt2))
assert pkt1[IP].proto == pkt2[IP].proto == pkt3[IP].proto

= Packet().fragment() already fragmented packets
payloadlen = 1480 * 3
ffrags = (IP() / ("X" * payloadlen)).fragment(1480)
ffrags = reduce(lambda x, y: x + y, (pkt.fragment(1400) for pkt in ffrags))
len(ffrags) == 6
* each fragment except the last one should have MF set
assert all(p.flags == 1 for p in ffrags[:-1])
assert ffrags[-1].flags == 0
* fragment offset should be well computed
plen = 0
for p in ffrags:
    assert p.frag == plen / 8
    plen += len(p.payload)

assert plen == payloadlen


############
############
+ TCP/IP tests
~ tcp

= TCP options: UTO - basic build
raw(TCP(options=[("UTO", 0xffff)])) == b"\x00\x14\x00\x50\x00\x00\x00\x00\x00\x00\x00\x00\x60\x02\x20\x00\x00\x00\x00\x00\x1c\x04\xff\xff"

= TCP options: UTO - basic dissection
uto = TCP(b"\x00\x14\x00\x50\x00\x00\x00\x00\x00\x00\x00\x00\x60\x02\x20\x00\x00\x00\x00\x00\x1c\x04\xff\xff")
uto[TCP].options[0][0] == "UTO" and uto[TCP].options[0][1] == 0xffff

= TCP options: SAck - basic build
raw(TCP(options=[(5, b"abcdefgh")])) == b"\x00\x14\x00P\x00\x00\x00\x00\x00\x00\x00\x00\x80\x02 \x00\x00\x00\x00\x00\x05\nabcdefgh\x00\x00"

= TCP options: SAck - basic dissection
sack = TCP(b"\x00\x14\x00P\x00\x00\x00\x00\x00\x00\x00\x00\x80\x02 \x00\x00\x00\x00\x00\x05\nabcdefgh\x00\x00")
sack[TCP].options[0][0] == "SAck" and sack[TCP].options[0][1] == (1633837924, 1701209960)

= TCP options: SAckOK - basic build
raw(TCP(options=[('SAckOK', b'')])) == b"\x00\x14\x00P\x00\x00\x00\x00\x00\x00\x00\x00`\x02 \x00\x00\x00\x00\x00\x04\x02\x00\x00"

= TCP options: SAckOK - basic dissection
sackok = TCP(b"\x00\x14\x00P\x00\x00\x00\x00\x00\x00\x00\x00`\x02 \x00\x00\x00\x00\x00\x04\x02\x00\x00")
sackok[TCP].options[0][0] == "SAckOK" and sackok[TCP].options[0][1] == b''

= TCP options: EOL - basic build
raw(TCP(options=[(0, '')])) == b"\x00\x14\x00P\x00\x00\x00\x00\x00\x00\x00\x00`\x02 \x00\x00\x00\x00\x00\x00\x00\x00\x00"

= TCP options: EOL - basic dissection
eol = TCP(b"\x00\x14\x00P\x00\x00\x00\x00\x00\x00\x00\x00`\x02 \x00\x00\x00\x00\x00\x00\x02\x00\x00")
eol[TCP].options[0][0] == "EOL" and eol[TCP].options[0][1] == None

= TCP options: malformed - build
raw(TCP(options=[('unknown', b'')])) == raw(TCP())

= TCP options: malformed - dissection
raw(TCP(b"\x00\x14\x00P\x00\x00\x00\x00\x00\x00\x00\x00`\x02 \x00\x00\x00\x00\x00\x03\x00\x00\x00")) == b"\x00\x14\x00P\x00\x00\x00\x00\x00\x00\x00\x00`\x02 \x00\x00\x00\x00\x00\x03\x00\x00\x00"

= TCP options: wrong offset
TCP(raw(TCP(dataofs=11)/b"o"))

= TCP options: MPTCP - basic build using bytes
raw(TCP(options=[(30, b"\x10\x03\xc1\x1c\x95\x9b\x81R_1")])) == b"\x00\x14\x00P\x00\x00\x00\x00\x00\x00\x00\x00\x80\x02 \x00\x00\x00\x00\x00\x1e\x0c\x10\x03\xc1\x1c\x95\x9b\x81R_1"

= TCP options: invalid data offset
data = b'\x00\x14\x00P\x00\x00\x00\x00\x00\x00\x00\x00\x80\x02 \x00\x1b\xb8\x00\x00\x02\x04\x05\xb4\x04\x02\x08\x06\xf7\xa26C\x00\x00\x00\x00\x01\x03\x03\x07'
p = TCP(data)
assert TCP in p and Raw in p and len(p.options) == 3

= TCP options: build oversized packet

raw(TCP(options=[('TFO', (1607681672, 2269173587)), ('AltChkSum', (81, 27688)), ('TFO', (253281879, 1218258937)), ('Timestamp', (1613741359, 4215831072)), ('Timestamp', (3856332598, 1434258666))]))

= TCP random options
pkt = TCP()
random.seed(0x2807)
pkt = fuzz(pkt)
options = pkt.options._fix()
options
if six.PY2:
    assert options == [('WScale', (32,)), ('NOP', ''), ('WScale', (145,)), ('WScale', (165,))]
else:
    assert options in [[('TFO', (1822729092, 2707522527)), ('Mood', (b'\x19',)), ('WScale', (117,))], [('TFO', (725644109, 3830853589)), ('Timestamp', (2604802746, 4137267106)), ('WScale', (227,)), ('Timestamp', (38044154, 828782501)), ('AltChkSum', (126, 40603))]]

= IP, TCP & UDP checksums (these tests highly depend on default values)
pkt = IP() / TCP()
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x7ccd and bpkt.payload.chksum == 0x917c

pkt = IP(len=40) / TCP()
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x7ccd and bpkt.payload.chksum == 0x917c

pkt = IP(len=40, ihl=5) / TCP()
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x7ccd and bpkt.payload.chksum == 0x917c

pkt = IP() / TCP() / ("A" * 10)
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x7cc3 and bpkt.payload.chksum == 0x4b2c

pkt = IP(len=50) / TCP() / ("A" * 10)
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x7cc3 and bpkt.payload.chksum == 0x4b2c

pkt = IP(len=50, ihl=5) / TCP() / ("A" * 10)
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x7cc3 and bpkt.payload.chksum == 0x4b2c

pkt = IP(options=[IPOption_RR()]) / TCP() / ("A" * 10)
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x70bc and bpkt.payload.chksum == 0x4b2c

pkt = IP(len=54, options=[IPOption_RR()]) / TCP() / ("A" * 10)
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x70bc and bpkt.payload.chksum == 0x4b2c

pkt = IP(len=54, ihl=6, options=[IPOption_RR()]) / TCP() / ("A" * 10)
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x70bc and bpkt.payload.chksum == 0x4b2c

pkt = IP(options=[IPOption_Timestamp()]) / TCP() / ("A" * 10)
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x2caa and bpkt.payload.chksum == 0x4b2c

pkt = IP() / UDP()
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x7cce and bpkt.payload.chksum == 0x0172

pkt = IP(len=28) / UDP()
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x7cce and bpkt.payload.chksum == 0x0172

pkt = IP(len=28, ihl=5) / UDP()
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x7cce and bpkt.payload.chksum == 0x0172

pkt = IP() / UDP() / ("A" * 10)
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x7cc4 and bpkt.payload.chksum == 0xbb17

pkt = IP(len=38) / UDP() / ("A" * 10)
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x7cc4 and bpkt.payload.chksum == 0xbb17

pkt = IP(len=38, ihl=5) / UDP() / ("A" * 10)
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x7cc4 and bpkt.payload.chksum == 0xbb17

pkt = IP(options=[IPOption_RR()]) / UDP() / ("A" * 10)
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x70bd and bpkt.payload.chksum == 0xbb17

pkt = IP(len=42, options=[IPOption_RR()]) / UDP() / ("A" * 10)
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x70bd and bpkt.payload.chksum == 0xbb17

pkt = IP(len=42, ihl=6, options=[IPOption_RR()]) / UDP() / ("A" * 10)
bpkt = IP(raw(pkt))
assert bpkt.chksum == 0x70bd and bpkt.payload.chksum == 0xbb17

= IP with forced-length 0
p = IP()/TCP()
p[IP].len = 0
p = IP(raw(p))

assert p.len == 0

= TCP payload with IP Total Length 0
data = b'1234567890abcdef123456789ABCDEF'
pkt = IP()/TCP()/data
pkt2 = IP(raw(pkt))
pkt2.len = 0
pkt3 = IP(raw(pkt2))
assert pkt3.load == data


= Layer binding

* Test DestMACField & DestIPField
pkt = Ether(raw(Ether()/IP()/UDP(dport=5353)/DNS()))
assert isinstance(pkt, Ether) and pkt.dst == '01:00:5e:00:00:fb'
pkt = pkt.payload
assert isinstance(pkt, IP) and pkt.dst == '224.0.0.251'
pkt = pkt.payload
assert isinstance(pkt, UDP) and pkt.dport == 5353
pkt = pkt.payload
assert isinstance(pkt, DNS) and isinstance(pkt.payload, NoPayload)

* Same with IPv6
pkt = Ether(raw(Ether()/IPv6()/UDP(dport=5353)/DNS()))
assert isinstance(pkt, Ether) and pkt.dst == '33:33:00:00:00:fb'
pkt = pkt.payload
assert isinstance(pkt, IPv6) and pkt.dst == 'ff02::fb'
pkt = pkt.payload
assert isinstance(pkt, UDP) and pkt.dport == 5353
pkt = pkt.payload
assert isinstance(pkt, DNS) and isinstance(pkt.payload, NoPayload)


############
############
+ inet.py

= IPv4 - ICMPTimeStampField
test = ICMPTimeStampField("test", None)
value = test.any2i("", "07:28:28.07")
value == 26908070
test.i2repr("", value) == '7:28:28.70'

= IPv4 - UDP null checksum
IP(raw(IP()/UDP()/Raw(b"\xff\xff\x01\x6a")))[UDP].chksum == 0xFFFF

= IPv4 - (IP|UDP|TCP|ICMP)Error
query = IP(dst="192.168.0.1", src="192.168.0.254", ttl=1)/UDP()/DNS()
answer = IP(dst="192.168.0.254", src="192.168.0.2", ttl=1)/ICMP()/IPerror(dst="192.168.0.1", src="192.168.0.254", ttl=0)/UDPerror()/DNS()

query = IP(dst="192.168.0.1", src="192.168.0.254", ttl=1)/UDP()/DNS()
answer = IP(dst="192.168.0.254", src="192.168.0.2")/ICMP(type=11)/IPerror(dst="192.168.0.1", src="192.168.0.254", ttl=0)/UDPerror()/DNS()
assert(answer.answers(query) == True)

query = IP(dst="192.168.0.1", src="192.168.0.254", ttl=1)/TCP()
answer = IP(dst="192.168.0.254", src="192.168.0.2")/ICMP(type=11)/IPerror(dst="192.168.0.1", src="192.168.0.254", ttl=0)/TCPerror()

assert(answer.answers(query) == True)

query = IP(dst="192.168.0.1", src="192.168.0.254", ttl=1)/ICMP()/"scapy"
answer = IP(dst="192.168.0.254", src="192.168.0.2")/ICMP(type=11)/IPerror(dst="192.168.0.1", src="192.168.0.254", ttl=0)/ICMPerror()/"scapy"
assert(answer.answers(query) == True)

= IPv4 - mDNS
a = IP(dst="224.0.0.251")
assert a.hashret() == b"\x00"

# TODO add real case here

= IPv4 - utilities
l = overlap_frag(IP(dst="1.2.3.4")/ICMP()/("AB"*8), ICMP()/("CD"*8))
assert(len(l) == 6)
assert([len(raw(p[IP].payload)) for p in l] == [8, 8, 8, 8, 8, 8])
assert([(p.frag, p.flags.MF) for p in [IP(raw(p)) for p in l]] == [(0, True), (1, True), (2, True), (0, True), (1, True), (2, False)])

= IPv4 - traceroute utilities
ip_ttl = [("192.168.0.%d" % i, i) for i in six.moves.range(1, 10)]

tr_packets = [ (IP(dst="192.168.0.1", src="192.168.0.254", ttl=ttl)/TCP(options=[("Timestamp", "00:00:%.2d.00" % ttl)])/"scapy",
                IP(dst="192.168.0.254", src=ip)/ICMP(type=11)/IPerror(dst="192.168.0.1", src="192.168.0.254", ttl=0)/TCPerror()/"scapy")
               for (ip, ttl) in ip_ttl ]

tr = TracerouteResult(tr_packets)
assert(tr.get_trace() == {'192.168.0.1': {1: ('192.168.0.1', False), 2: ('192.168.0.2', False), 3: ('192.168.0.3', False), 4: ('192.168.0.4', False), 5: ('192.168.0.5', False), 6: ('192.168.0.6', False), 7: ('192.168.0.7', False), 8: ('192.168.0.8', False), 9: ('192.168.0.9', False)}})

def test_show():
    with ContextManagerCaptureOutput() as cmco:
        tr = TracerouteResult(tr_packets)
        tr.show()
        result_show = cmco.get_output()
    expected = "  192.168.0.1:tcp80  \n"
    expected += "1 192.168.0.1     11 \n"
    expected += "2 192.168.0.2     11 \n"
    expected += "3 192.168.0.3     11 \n"
    expected += "4 192.168.0.4     11 \n"
    expected += "5 192.168.0.5     11 \n"
    expected += "6 192.168.0.6     11 \n"
    expected += "7 192.168.0.7     11 \n"
    expected += "8 192.168.0.8     11 \n"
    expected += "9 192.168.0.9     11 \n"
    index_result = result_show.index("\n1")
    index_expected = expected.index("\n1")
    assert(result_show[index_result:] == expected[index_expected:])

test_show()

def test_summary():
    with ContextManagerCaptureOutput() as cmco:
        tr = TracerouteResult(tr_packets)
        tr.summary()
        result_summary = cmco.get_output()
    assert(len(result_summary.split('\n')) == 10)
    assert(any(
        "IP / TCP 192.168.0.254:%s > 192.168.0.1:%s S / Raw ==> "
        "IP / ICMP 192.168.0.9 > 192.168.0.254 time-exceeded "
        "ttl-zero-during-transit / IPerror / TCPerror / "
        "Raw" % (ftp_data, http) in result_summary
        for ftp_data in ['21', 'ftp_data']
        for http in ['80', 'http', 'www_http', 'www']
    ))

test_summary()

import mock

@mock.patch("scapy.layers.inet.plt")
def test_timeskew_graph(mock_plt):
    def fake_plot(data, **kwargs):
        return data
    mock_plt.plot = fake_plot
    srl = SndRcvList([(a, a) for a in [IP(raw(p[0])) for p in tr_packets]])
    ret = srl.timeskew_graph("192.168.0.254")
    assert(len(ret) == 9)
    assert(ret[0][1] == 0.0)

test_timeskew_graph()

tr = TracerouteResult(tr_packets)
saved_AS_resolver = conf.AS_resolver
conf.AS_resolver = None
tr.make_graph()
assert(len(tr.graphdef) == 491)
tr.graphdef.startswith("digraph trace {") == True
assert(('"192.168.0.9" ->' in tr.graphdef) == True)
conf.AS_resolver = conf.AS_resolver

pl = PacketList(list([Ether()/x for x in itertools.chain(*tr_packets)]))
srl, ul = pl.sr()
assert(len(srl) == 9 and len(ul) == 0)

conf_color_theme = conf.color_theme
conf.color_theme = BlackAndWhite()
assert(len(pl.sessions().keys()) == 10)
conf.color_theme = conf_color_theme

new_pl = pl.replace(IP.src, "192.168.0.254", "192.168.0.42")
assert("192.168.0.254" not in [p[IP].src for p in new_pl])

= IPv4 - reporting
~ netaccess

import mock

@mock.patch("scapy.layers.inet.sr")
def test_report_ports(mock_sr):
    def sr(*args, **kargs):
        return [(IP()/TCP(dport=65081, flags="S"), IP()/TCP(sport=65081, flags="SA")),
                (IP()/TCP(dport=65082, flags="S"), IP()/ICMP(type=3, code=1)),
                (IP()/TCP(dport=65083, flags="S"), IP()/TCP(sport=65083, flags="R"))], [IP()/TCP(dport=65084, flags="S")]
    mock_sr.side_effect = sr
    report = "\\begin{tabular}{|r|l|l|}\n\\hline\n65081 & open & SA \\\\\n\\hline\n?? & closed & ICMP type dest-unreach/host-unreachable from 127.0.0.1 \\\\\n65083 & closed & TCP R \\\\\n\\hline\n65084 & ? & unanswered \\\\\n\\hline\n\\end{tabular}\n"
    assert(report_ports("www.secdev.org", [65081,65082,65083,65084]) == report)

test_report_ports()

def test_IPID_count():
    with ContextManagerCaptureOutput() as cmco:
        random.seed(0x2807)
        IPID_count([(IP()/UDP(), IP(id=random.randint(0, 65535))/UDP()) for i in range(3)])
        result_IPID_count = cmco.get_output()
    lines = result_IPID_count.split("\n")
    assert(len(lines) == 5)
    assert(lines[0] in ["Probably 3 classes: [4613, 53881, 58437]",
                        "Probably 3 classes: [9103, 9227, 46399]"])

test_IPID_count()

= IPv4 - Checksum computation with source routing

no_sr = IP(raw(IP(dst="8.8.8.8")/UDP()/DNS()))
sr = IP(raw(IP(options=[IPOption_SSRR(routers=["1.1.1.1", "8.8.8.8"])])/UDP()/DNS()))
assert no_sr[UDP].chksum == sr[UDP].chksum

sr = IP(raw(IP(options=[IPOption_LSRR(routers=["1.1.1.1"]), IPOption_SSRR(routers=["8.8.8.8"])])/UDP()/DNS()))
assert no_sr[UDP].chksum != sr[UDP].chksum
