2020-08-27 00:03:14 +02:00
|
|
|
import asyncfutures, asyncdispatch, asyncnet, strformat
|
2020-10-02 17:12:29 +02:00
|
|
|
from net import IpAddress, Port, `$`, `==`, getPrimaryIPAddr, toSockAddr, parseIpAddress
|
2020-07-17 20:06:52 +02:00
|
|
|
from nativesockets import SockAddr, Sockaddr_storage, SockLen, setSockOptInt
|
2020-10-02 17:12:29 +02:00
|
|
|
from sequtils import any
|
2020-07-07 19:39:28 +02:00
|
|
|
import asyncutils
|
2020-07-10 00:27:21 +02:00
|
|
|
import ip_packet
|
2020-07-07 19:39:28 +02:00
|
|
|
import network_interface
|
|
|
|
import raw_socket
|
|
|
|
|
|
|
|
var IPPROTO_IP {.importc: "IPPROTO_IP", header: "<netinet/in.h>".}: cint
|
|
|
|
var IP_TTL {.importc: "IP_TTL", header: "<netinet/in.h>".}: cint
|
|
|
|
|
2020-08-27 00:03:14 +02:00
|
|
|
const Timeout = 3000
|
|
|
|
|
2020-07-07 19:39:28 +02:00
|
|
|
type
|
2020-10-02 17:12:29 +02:00
|
|
|
ConnectAttempt* = ref object
|
|
|
|
srcIp: IpAddress
|
|
|
|
srcPort: Port
|
|
|
|
dstIp: IpAddress
|
|
|
|
dstPorts: seq[Port]
|
|
|
|
firewallRules: seq[string]
|
|
|
|
|
|
|
|
AcceptAttempt* = ref object
|
2020-07-07 19:39:28 +02:00
|
|
|
srcIp: IpAddress
|
|
|
|
srcPort: Port
|
|
|
|
dstIp: IpAddress
|
2020-07-21 11:10:56 +02:00
|
|
|
dstPorts: seq[Port]
|
2020-07-07 19:39:28 +02:00
|
|
|
seqNums: seq[uint32]
|
2020-08-21 23:12:45 +02:00
|
|
|
firewallRules: seq[string]
|
2020-10-02 17:12:29 +02:00
|
|
|
future: Future[AsyncSocket]
|
|
|
|
|
|
|
|
TcpSyniPuncher* = ref object
|
|
|
|
connectAttempts: seq[ConnectAttempt]
|
|
|
|
acceptAttempts: seq[AcceptAttempt]
|
2020-07-07 19:39:28 +02:00
|
|
|
|
|
|
|
PunchProgressCb* = proc (seqNums: seq[uint32]) {.async.}
|
|
|
|
|
|
|
|
PunchHoleError* = object of ValueError
|
|
|
|
|
2020-08-21 23:12:45 +02:00
|
|
|
proc makeFirewallRule(srcIp: IpAddress, srcPort: Port,
|
|
|
|
dstIp: IpAddress, dstPort: Port): string =
|
|
|
|
result = fmt"""-w \
|
2020-07-07 19:39:28 +02:00
|
|
|
-d {srcIp} \
|
|
|
|
-p icmp \
|
|
|
|
--icmp-type time-exceeded \
|
|
|
|
-m conntrack \
|
|
|
|
--ctstate RELATED \
|
|
|
|
--ctproto tcp \
|
|
|
|
--ctorigsrc {srcIp} \
|
|
|
|
--ctorigsrcport {srcPort.int} \
|
|
|
|
--ctorigdst {dstIp} \
|
|
|
|
--ctorigdstport {dstPort.int} \
|
|
|
|
-j DROP"""
|
2020-08-21 23:12:45 +02:00
|
|
|
|
|
|
|
proc iptablesInsert(chain: string, rule: string) {.async.} =
|
|
|
|
let firewall_cmd = fmt"iptables -I {chain} {rule}"
|
2020-08-18 00:34:21 +02:00
|
|
|
discard await asyncExecCmd(firewall_cmd)
|
2020-07-07 19:39:28 +02:00
|
|
|
|
2020-08-21 23:12:45 +02:00
|
|
|
proc iptablesDelete(chain: string, rule: string) {.async.} =
|
|
|
|
let firewall_cmd = fmt"iptables -D {chain} {rule}"
|
2020-08-18 00:34:21 +02:00
|
|
|
discard await asyncExecCmd(firewall_cmd)
|
2020-07-07 19:39:28 +02:00
|
|
|
|
2020-10-02 17:12:29 +02:00
|
|
|
proc addFirewallRules[T](attempt: T) {.async.} =
|
|
|
|
for dstPort in attempt.dstPorts:
|
|
|
|
let rule = makeFirewallRule(attempt.srcIp, attempt.srcPort,
|
|
|
|
attempt.dstIp, dstPort)
|
|
|
|
try:
|
|
|
|
await iptablesInsert("INPUT", rule)
|
|
|
|
attempt.firewallRules.add(rule)
|
|
|
|
except OSError as e:
|
|
|
|
echo "cannot add firewall rule: ", e.msg
|
|
|
|
raise newException(PunchHoleError, e.msg)
|
|
|
|
|
|
|
|
proc deleteFirewallRules[T](attempt: T) {.async.} =
|
|
|
|
for rule in attempt.firewallRules:
|
|
|
|
# FIXME: close sock?
|
|
|
|
try:
|
|
|
|
await iptablesDelete("INPUT", rule)
|
|
|
|
except OSError:
|
|
|
|
# At least we tried
|
|
|
|
discard
|
|
|
|
|
2020-08-23 14:36:19 +02:00
|
|
|
proc injectTcpPacket(rawFd: AsyncFD, ipPacket: IpPacket) {.async.} =
|
|
|
|
assert(ipPacket.protocol == tcp)
|
|
|
|
try:
|
|
|
|
let packet = serialize(ipPacket)
|
|
|
|
var sockaddr: Sockaddr_storage
|
|
|
|
var sockaddrLen: SockLen
|
|
|
|
toSockAddr(ipPacket.ipAddrDst, ipPacket.tcpPortDst, sockaddr, sockaddrLen)
|
|
|
|
await rawFd.sendTo(packet.cstring, packet.len,
|
|
|
|
cast[ptr SockAddr](addr sockaddr), sockaddrLen)
|
|
|
|
except OSError as e:
|
|
|
|
raise newException(PunchHoleError, e.msg)
|
|
|
|
|
2020-10-02 17:12:29 +02:00
|
|
|
proc captureSeqNumbers(attempt: ConnectAttempt, rawFd: AsyncFD,
|
2020-07-07 19:39:28 +02:00
|
|
|
cb: PunchProgressCb) {.async.} =
|
|
|
|
# FIXME: timeout?
|
|
|
|
var seqNums = newSeq[uint32]()
|
2020-10-02 17:12:29 +02:00
|
|
|
while seqNums.len < attempt.dstPorts.len:
|
2020-07-07 19:39:28 +02:00
|
|
|
let packet = await rawFd.recv(4000)
|
|
|
|
if packet == "":
|
|
|
|
break
|
2020-07-09 21:10:25 +02:00
|
|
|
let parsed = parseEthernetPacket(packet)
|
|
|
|
if parsed.protocol == tcp and
|
2020-10-02 17:12:29 +02:00
|
|
|
parsed.ipAddrSrc == attempt.srcIp and
|
|
|
|
parsed.tcpPortSrc.int == attempt.srcPort.int and
|
|
|
|
parsed.ipAddrDst == attempt.dstIp and
|
2020-07-17 10:37:33 +02:00
|
|
|
parsed.tcpFlags == {SYN}:
|
2020-10-02 17:12:29 +02:00
|
|
|
for port in attempt.dstPorts:
|
2020-07-09 21:10:25 +02:00
|
|
|
if parsed.tcpPortDst.int == port.int:
|
|
|
|
seqNums.add(parsed.tcpSeqNumber)
|
2020-07-07 19:39:28 +02:00
|
|
|
break
|
|
|
|
await cb(seqNums)
|
|
|
|
|
2020-10-02 17:12:29 +02:00
|
|
|
proc captureAndResendAck(attempt: ConnectAttempt, captureFd: AsyncFD,
|
2020-08-23 15:52:50 +02:00
|
|
|
injectFd: AsyncFD) {.async.} =
|
2020-08-23 14:36:19 +02:00
|
|
|
while true:
|
2020-08-23 15:52:50 +02:00
|
|
|
let packet = await captureFd.recv(4000)
|
2020-08-23 14:36:19 +02:00
|
|
|
if packet == "":
|
|
|
|
break
|
2020-08-23 22:48:34 +02:00
|
|
|
var parsed = parseEthernetPacket(packet)
|
2020-08-23 14:36:19 +02:00
|
|
|
if parsed.protocol == tcp and
|
2020-10-02 17:12:29 +02:00
|
|
|
parsed.ipAddrSrc == attempt.srcIp and
|
|
|
|
parsed.tcpPortSrc.int == attempt.srcPort.int and
|
|
|
|
parsed.ipAddrDst == attempt.dstIp and
|
2020-08-23 15:17:19 +02:00
|
|
|
parsed.tcpFlags == {ACK}:
|
2020-10-02 17:12:29 +02:00
|
|
|
for port in attempt.dstPorts:
|
2020-08-23 14:36:19 +02:00
|
|
|
if parsed.tcpPortDst.int == port.int:
|
2020-08-23 22:48:34 +02:00
|
|
|
parsed.ipTTL = 64
|
2020-09-25 17:19:34 +02:00
|
|
|
echo &"[{parsed.ipAddrSrc}:{parsed.tcpPortSrc.int} -> {parsed.ipAddrDst}:{parsed.tcpPortDst}, SEQ {parsed.tcpSeqNumber}] resending ACK with TTL {parsed.ipTTL}"
|
2020-08-23 22:48:34 +02:00
|
|
|
await injectFd.injectTcpPacket(parsed)
|
2020-08-23 16:02:28 +02:00
|
|
|
return
|
2020-07-11 14:46:37 +02:00
|
|
|
|
2020-10-02 17:12:29 +02:00
|
|
|
proc initPuncher*(): TcpSyniPuncher = TcpSyniPuncher()
|
|
|
|
|
|
|
|
proc findConnectAttempt(puncher: TcpSyniPuncher, srcIp: IpAddress,
|
|
|
|
srcPort: Port, dstIp: IpAddress,
|
|
|
|
dstPorts: seq[Port]): int =
|
|
|
|
for (index, attempt) in puncher.connectAttempts.pairs():
|
|
|
|
if attempt.srcIp == srcIp and attempt.srcPort == srcPort and
|
|
|
|
attempt.dstIp == dstIp and
|
|
|
|
attempt.dstPorts.any(proc (p: Port): bool = p in dstPorts):
|
|
|
|
return index
|
2020-10-02 17:18:31 +02:00
|
|
|
return -1
|
2020-10-02 17:12:29 +02:00
|
|
|
|
|
|
|
proc findAcceptAttempt(puncher: TcpSyniPuncher, srcIp: IpAddress,
|
|
|
|
srcPort: Port, dstIp: IpAddress,
|
|
|
|
dstPorts: seq[Port]): int =
|
|
|
|
for (index, attempt) in puncher.acceptAttempts.pairs():
|
|
|
|
if attempt.srcIp == srcIp and attempt.srcPort == srcPort and
|
|
|
|
attempt.dstIp == dstIp and
|
|
|
|
attempt.dstPorts.any(proc (p: Port): bool = p in dstPorts):
|
|
|
|
return index
|
2020-10-02 17:18:31 +02:00
|
|
|
return -1
|
2020-10-02 17:12:29 +02:00
|
|
|
|
|
|
|
proc findAcceptAttemptsByLocalAddr(puncher: TcpSyniPuncher, address: IpAddress,
|
|
|
|
port: Port): seq[AcceptAttempt] =
|
|
|
|
for attempt in puncher.acceptAttempts:
|
|
|
|
if attempt.srcIp == address and attempt.srcPort == port:
|
|
|
|
result.add(attempt)
|
|
|
|
|
|
|
|
proc predictPortRange(dstPorts: seq[Port]): seq[Port] =
|
2020-07-07 19:39:28 +02:00
|
|
|
# TODO: do real port prediction
|
2020-10-02 17:12:29 +02:00
|
|
|
result = newSeq[Port](1)
|
2020-07-21 11:10:56 +02:00
|
|
|
let basePort = min(dstPorts[1].uint16,
|
2020-10-02 17:12:29 +02:00
|
|
|
uint16.high - (result.len - 1).uint16)
|
|
|
|
for i in 0 .. result.len - 1:
|
|
|
|
result[i] = Port(basePort + i.uint16)
|
2020-08-21 23:12:45 +02:00
|
|
|
|
|
|
|
proc cleanup*(puncher: TcpSyniPuncher) {.async.} =
|
2020-10-02 17:12:29 +02:00
|
|
|
for attempt in puncher.connectAttempts:
|
|
|
|
await attempt.deleteFirewallRules()
|
|
|
|
for attempt in puncher.acceptAttempts:
|
|
|
|
await attempt.deleteFirewallRules()
|
2020-08-21 23:12:45 +02:00
|
|
|
|
|
|
|
proc doConnect(srcIp: IpAddress, srcPort: Port, dstIp: IpAddress, dstPort: Port,
|
|
|
|
future: Future[AsyncSocket]) {.async.} =
|
2020-07-07 19:39:28 +02:00
|
|
|
let sock = newAsyncSocket()
|
|
|
|
sock.setSockOpt(OptReuseAddr, true)
|
|
|
|
sock.getFd.setSockOptInt(IPPROTO_IP, IP_TTL, 2)
|
2020-09-25 22:59:53 +02:00
|
|
|
echo &"doConnect {srcIp}:{srcPort} -> {dstIp}:{dstPort}"
|
2020-07-07 19:39:28 +02:00
|
|
|
sock.bindAddr(srcPort, $srcIp)
|
|
|
|
try:
|
|
|
|
await sock.connect($dstIp, dstPort)
|
2020-08-23 14:36:19 +02:00
|
|
|
sock.getFd.setSockOptInt(IPPROTO_IP, IP_TTL, 64)
|
2020-07-07 19:39:28 +02:00
|
|
|
future.complete(sock)
|
|
|
|
except OSError as e:
|
|
|
|
echo &"connection {srcIP}:{srcPort.int} -> {dstIp}:{dstPort.int} failed: ", e.msg
|
|
|
|
discard
|
2020-08-21 23:12:45 +02:00
|
|
|
|
2020-10-02 17:12:29 +02:00
|
|
|
proc connect*(puncher: TcpSyniPuncher, srcPort: Port, dstIp: IpAddress,
|
|
|
|
dstPorts: seq[Port],
|
2020-08-21 23:12:45 +02:00
|
|
|
progressCb: PunchProgressCb): Future[AsyncSocket] {.async.} =
|
2020-10-02 17:12:29 +02:00
|
|
|
let localIp = getPrimaryIPAddr(dstIp)
|
|
|
|
if puncher.findConnectAttempt(localIp, srcPort, dstIp, dstPorts) != -1:
|
|
|
|
raise newException(PunchHoleError, "hole punching for given parameters already active")
|
|
|
|
let attempt = ConnectAttempt(srcIp: localIp, srcPort: srcPort, dstIp: dstIp,
|
|
|
|
dstPorts: predictPortRange(dstPorts))
|
|
|
|
puncher.connectAttempts.add(attempt)
|
|
|
|
await attempt.addFirewallRules()
|
|
|
|
let iface = fromIpAddress(attempt.srcIp)
|
2020-08-23 14:36:19 +02:00
|
|
|
let captureSeqFd = setupEthernetCapturingSocket(iface)
|
2020-08-23 15:17:19 +02:00
|
|
|
let captureAckFd = setupEthernetCapturingSocket(iface)
|
2020-08-23 15:52:50 +02:00
|
|
|
let injectAckFd = setupTcpInjectingSocket()
|
2020-10-02 17:12:29 +02:00
|
|
|
asyncCheck attempt.captureSeqNumbers(captureSeqFd, progressCb)
|
|
|
|
asyncCheck attempt.captureAndResendAck(captureAckFd, injectAckFd)
|
2020-08-18 00:34:21 +02:00
|
|
|
try:
|
2020-10-02 17:12:29 +02:00
|
|
|
let connectFuture = newFuture[AsyncSocket]("connect")
|
|
|
|
for dstPort in attempt.dstPorts:
|
|
|
|
asyncCheck doConnect(attempt.srcIp, attempt.srcPort, attempt.dstIp,
|
|
|
|
dstPort, connectfuture)
|
|
|
|
await connectFuture or sleepAsync(Timeout)
|
|
|
|
await attempt.deleteFirewallRules()
|
|
|
|
puncher.connectAttempts.del(puncher.connectAttempts.find(attempt))
|
|
|
|
if connectFuture.finished():
|
|
|
|
result = connectFuture.read()
|
2020-08-27 00:03:14 +02:00
|
|
|
else:
|
|
|
|
raise newException(PunchHoleError, "timeout")
|
2020-08-18 00:34:21 +02:00
|
|
|
except OSError as e:
|
2020-08-21 23:12:45 +02:00
|
|
|
raise newException(PunchHoleError, e.msg)
|
2020-07-07 19:39:28 +02:00
|
|
|
|
2020-10-02 17:12:29 +02:00
|
|
|
proc prepareAccept(attempt: AcceptAttempt) {.async.} =
|
|
|
|
for dstPort in attempt.dstPorts:
|
2020-07-18 15:04:06 +02:00
|
|
|
try:
|
|
|
|
let sock = newAsyncSocket()
|
|
|
|
sock.setSockOpt(OptReuseAddr, true)
|
|
|
|
sock.getFd.setSockOptInt(IPPROTO_IP, IP_TTL, 2)
|
2020-10-02 17:12:29 +02:00
|
|
|
sock.bindAddr(attempt.srcPort, $(attempt.srcIp))
|
|
|
|
let connectFuture = sock.connect($(attempt.dstIp), dstPort)
|
2020-08-27 00:03:14 +02:00
|
|
|
await connectFuture or sleepAsync(Timeout)
|
|
|
|
if connectFuture.finished():
|
|
|
|
echo "connected during accept phase"
|
|
|
|
sock.close()
|
2020-07-18 15:04:06 +02:00
|
|
|
except OSError:
|
|
|
|
discard
|
2020-08-21 23:12:45 +02:00
|
|
|
|
2020-10-02 17:12:29 +02:00
|
|
|
proc doAccept(puncher: TcpSyniPuncher, srcIp: IpAddress,
|
|
|
|
srcPort: Port) {.async.} =
|
|
|
|
let sock = newAsyncSocket()
|
|
|
|
sock.setSockOpt(OptReuseAddr, true)
|
|
|
|
sock.bindAddr(srcPort, $(srcIp))
|
|
|
|
sock.listen()
|
|
|
|
while true:
|
|
|
|
let acceptFuture = sock.accept()
|
|
|
|
await acceptFuture or sleepAsync(Timeout)
|
|
|
|
if acceptFuture.finished():
|
|
|
|
let peer = acceptFuture.read()
|
|
|
|
let (peerAddr, peerPort) = peer.getPeerAddr()
|
|
|
|
let peerIp = parseIpAddress(peerAddr)
|
|
|
|
let i = puncher.findAcceptAttempt(srcIp, srcPort, peerIp, @[peerPort])
|
|
|
|
if i == -1:
|
|
|
|
echo "Accepted connection, but no attempt found. Discarding."
|
|
|
|
else:
|
|
|
|
let attempt = puncher.acceptAttempts[i]
|
|
|
|
attempt.future.complete(peer)
|
|
|
|
else:
|
|
|
|
let attempts = puncher.findAcceptAttemptsByLocalAddr(srcIp, srcPort)
|
|
|
|
# FIXME: should attempts have timestamps, so we can decide here which ones to delete?
|
|
|
|
if attempts.len() <= 1:
|
|
|
|
break
|
2020-10-04 11:43:46 +02:00
|
|
|
sock.close()
|
2020-10-02 17:12:29 +02:00
|
|
|
|
|
|
|
proc accept*(puncher: TcpSyniPuncher, srcPort: Port, dstIp: IpAddress,
|
|
|
|
dstPorts: seq[Port],
|
|
|
|
seqNums: seq[uint32]): Future[AsyncSocket] {.async.} =
|
|
|
|
let localIp = getPrimaryIPAddr(dstIp)
|
|
|
|
let existingAttempts = puncher.findAcceptAttemptsByLocalAddr(localIp, srcPort)
|
|
|
|
if existingAttempts.len() == 0:
|
|
|
|
echo &"accepting connections from {dstIp}:{dstPorts[0].int}"
|
|
|
|
asyncCheck puncher.doAccept(localIp, srcPort)
|
|
|
|
else:
|
|
|
|
for a in existingAttempts:
|
|
|
|
if a.dstIp == dstIp and
|
|
|
|
a.dstPorts.any(proc (p: Port): bool = p in dstPorts):
|
|
|
|
raise newException(PunchHoleError, "hole punching for given parameters already active")
|
|
|
|
let attempt = AcceptAttempt(srcIp: localIp, srcPort: srcPort, dstIp: dstIp,
|
|
|
|
dstPorts: dstPorts, seqNums: seqNums,
|
|
|
|
future: newFuture[AsyncSocket]("accept"))
|
|
|
|
puncher.acceptAttempts.add(attempt)
|
|
|
|
await attempt.addFirewallRules()
|
|
|
|
await attempt.prepareAccept()
|
2020-07-11 14:46:37 +02:00
|
|
|
try:
|
2020-07-18 12:41:07 +02:00
|
|
|
let rawFd = setupTcpInjectingSocket()
|
2020-10-02 17:12:29 +02:00
|
|
|
for dstPort in attempt.dstPorts:
|
|
|
|
for seqNum in attempt.seqNums:
|
|
|
|
let ipPacket = IpPacket(protocol: tcp, ipAddrSrc: attempt.dstIp,
|
|
|
|
ipAddrDst: attempt.srcIp, ipTTL: 64,
|
2020-08-23 14:36:19 +02:00
|
|
|
tcpPortSrc: dstPort,
|
2020-10-02 17:12:29 +02:00
|
|
|
tcpPortDst: attempt.srcPort,
|
|
|
|
tcpSeqNumber: seqNum, tcpAckNumber: 0,
|
|
|
|
tcpFlags: {SYN}, tcpWindowSize: 1452 * 10)
|
2020-09-25 17:19:34 +02:00
|
|
|
echo &"[{ipPacket.ipAddrSrc}:{ipPacket.tcpPortSrc} -> {ipPacket.ipAddrDst}:{ipPacket.tcpPortDst}, SEQ {ipPacket.tcpSeqNumber}] injecting SYN"
|
2020-08-23 14:36:19 +02:00
|
|
|
asyncCheck rawFd.injectTcpPacket(ipPacket)
|
2020-10-02 17:12:29 +02:00
|
|
|
await attempt.future or sleepAsync(Timeout)
|
|
|
|
await attempt.deleteFirewallRules()
|
|
|
|
puncher.acceptAttempts.del(puncher.acceptAttempts.find(attempt))
|
|
|
|
if attempt.future.finished():
|
|
|
|
result = attempt.future.read()
|
2020-08-27 00:03:14 +02:00
|
|
|
else:
|
|
|
|
raise newException(PunchHoleError, "timeout")
|
2020-07-11 14:46:37 +02:00
|
|
|
except OSError as e:
|
2020-10-02 17:12:29 +02:00
|
|
|
echo &"accepting connections from {dstIP}:{dstPorts[0].int} failed: ", e.msg
|