Skip to content

Commit

Permalink
Fix slice bounds out of range on address copy
Browse files Browse the repository at this point in the history
An IP address embedded in a net.TCPAddr (or net.UDPAddr) struct returned
from net.ResolveTCPAddr (or net.ResolveUDPAddr) can be either a 4-byte
or 16-byte slice depending on platform and configuration. Therefore, we
must check the length of the address before copying it into the
syscall.Sockaddr to avoid a "slice bounds out of range" panic.
  • Loading branch information
csstaub committed Dec 20, 2018
1 parent ffa96de commit ac899c6
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 2 deletions.
6 changes: 5 additions & 1 deletion tcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,11 @@ func getTCPSockaddr(proto, addr string) (sa syscall.Sockaddr, soType int, err er
sa := &syscall.SockaddrInet4{Port: tcp.Port}

if tcp.IP != nil {
copy(sa.Addr[:], tcp.IP[12:16]) // copy last 4 bytes of slice to array
if len(tcp.IP) == 16 {
copy(sa.Addr[:], tcp.IP[12:16]) // copy last 4 bytes of slice to array
} else {
copy(sa.Addr[:], tcp.IP) // copy all bytes of slice to array
}
}

return sa, syscall.AF_INET, nil
Expand Down
6 changes: 5 additions & 1 deletion udp.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ func getUDPSockaddr(proto, addr string) (sa syscall.Sockaddr, soType int, err er
sa := &syscall.SockaddrInet4{Port: udp.Port}

if udp.IP != nil {
copy(sa.Addr[:], udp.IP[12:16]) // copy last 4 bytes of slice to array
if len(udp.IP) == 16 {
copy(sa.Addr[:], udp.IP[12:16]) // copy last 4 bytes of slice to array
} else {
copy(sa.Addr[:], udp.IP) // copy all bytes of slice to array
}
}

return sa, syscall.AF_INET, nil
Expand Down

0 comments on commit ac899c6

Please sign in to comment.