Scapy and Sage
“Scapy is a powerful interactive packet manipulation program. It is able to forge or decode packets of a wide number of protocols, send them on the wire, capture them, match requests and replies, and much more. It can easily handle most classical tasks like scanning, tracerouting, probing, unit tests, attacks or network discovery (it can replace hping, 85% of nmap, arpspoof, arp-sk, arping, tcpdump, tethereal, p0f, etc.). It also performs very well at a lot of other specific tasks that most other tools can’t handle, like sending invalid frames, injecting your own 802.11 frames, combining technics (VLAN hopping+ARP cache poisoning, VOIP decoding on WEP encrypted channel, …)”
At the end of the day Scapy is one (one!) Python file so it couldn’t be easier to use it from within Sage. As an example let’s assume we have sniffed an SSH connection establishment including a Diffie-Hellmann Group Exchange as described in RFC 4419. Scapy can do live packet capture and injection but that would require root privileges, so I’m working with a pcap file in this example:
from scapy import rdpcap, TCP, IP
SSH2_MSG_KEX_DH_GEX_GROUP = 31
# read packets
packets = [p[IP] for p in rdpcap("/home/malb/example.pcap") \
if p[TCP] and len(p[TCP]) > 32]
# find correct package & payload
for packet in packets:
try:
pl = [ord(e) for e in packet[TCP].payload.load]
if pl[5] == SSH2_MSG_KEX_DH_GEX_GROUP:
break
except AttributeError:
pass
def get_uint(pl, length):
# this is not as generic as it should be since it doesn't work
# with negative numbers
value = ZZ(0)
for i in range(length):
value += pl[i] * 2**(8*(length - i - 1))
return value, pl[length:]
packet_length, pl = get_uint(pl, 4)
padlen, pl = get_uint(pl, 1)
packet_type, pl = get_uint(pl, 1)
assert(packet_type == SSH2_MSG_KEX_DH_GEX_GROUP)
# p
p_length, pl = get_uint(pl, 4)
p, pl = get_uint(pl, p_length)
# g
g_length, pl = get_uint(pl, 4)
g, pl = get_uint(pl, g_length)
assert(len(pl) == padlen)
assert(p.is_prime())
Zp = GF(p)
g = Zp(g)
e = g**ZZ.random_element(0,p)
e.log(g) # yeah, right ;-)
Happy hacking.

