device: allow blackholing sockets

This commit is contained in:
Jason A. Donenfeld 2019-10-21 13:29:57 +02:00
parent 47b02c618b
commit ffffbbcc8a
2 changed files with 14 additions and 4 deletions

View file

@ -18,7 +18,7 @@ const (
sockoptIPV6_UNICAST_IF = 31 sockoptIPV6_UNICAST_IF = 31
) )
func (device *Device) BindSocketToInterface4(interfaceIndex uint32) error { func (device *Device) BindSocketToInterface4(interfaceIndex uint32, blackhole bool) error {
/* MSDN says for IPv4 this needs to be in net byte order, so that it's like an IP address with leading zeros. */ /* MSDN says for IPv4 this needs to be in net byte order, so that it's like an IP address with leading zeros. */
bytes := make([]byte, 4) bytes := make([]byte, 4)
binary.BigEndian.PutUint32(bytes, interfaceIndex) binary.BigEndian.PutUint32(bytes, interfaceIndex)
@ -41,10 +41,11 @@ func (device *Device) BindSocketToInterface4(interfaceIndex uint32) error {
if err != nil { if err != nil {
return err return err
} }
device.net.bind.(*nativeBind).blackhole4 = blackhole
return nil return nil
} }
func (device *Device) BindSocketToInterface6(interfaceIndex uint32) error { func (device *Device) BindSocketToInterface6(interfaceIndex uint32, blackhole bool) error {
sysconn, err := device.net.bind.(*nativeBind).ipv6.SyscallConn() sysconn, err := device.net.bind.(*nativeBind).ipv6.SyscallConn()
if err != nil { if err != nil {
return err return err
@ -58,5 +59,6 @@ func (device *Device) BindSocketToInterface6(interfaceIndex uint32) error {
if err != nil { if err != nil {
return err return err
} }
device.net.bind.(*nativeBind).blackhole6 = blackhole
return nil return nil
} }

View file

@ -21,8 +21,10 @@ import (
*/ */
type nativeBind struct { type nativeBind struct {
ipv4 *net.UDPConn ipv4 *net.UDPConn
ipv6 *net.UDPConn ipv6 *net.UDPConn
blackhole4 bool
blackhole6 bool
} }
type NativeEndpoint net.UDPAddr type NativeEndpoint net.UDPAddr
@ -159,11 +161,17 @@ func (bind *nativeBind) Send(buff []byte, endpoint Endpoint) error {
if bind.ipv4 == nil { if bind.ipv4 == nil {
return syscall.EAFNOSUPPORT return syscall.EAFNOSUPPORT
} }
if bind.blackhole4 {
return nil
}
_, err = bind.ipv4.WriteToUDP(buff, (*net.UDPAddr)(nend)) _, err = bind.ipv4.WriteToUDP(buff, (*net.UDPAddr)(nend))
} else { } else {
if bind.ipv6 == nil { if bind.ipv6 == nil {
return syscall.EAFNOSUPPORT return syscall.EAFNOSUPPORT
} }
if bind.blackhole6 {
return nil
}
_, err = bind.ipv6.WriteToUDP(buff, (*net.UDPAddr)(nend)) _, err = bind.ipv6.WriteToUDP(buff, (*net.UDPAddr)(nend))
} }
return err return err