Last active
January 20, 2021 15:37
-
-
Save maiqueb/4072d75d75c69513bdd5630a8e96f90b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "flag" | |
| "fmt" | |
| "net" | |
| "os" | |
| "syscall" | |
| "github.com/golang/glog" | |
| "github.com/spf13/cobra" | |
| "github.com/vishvananda/netlink" | |
| "golang.org/x/sys/unix" | |
| ) | |
| func main() { | |
| flag.Parse() | |
| if err := flag.Set("alsologtostderr", "true"); err != nil { | |
| os.Exit(1) | |
| } | |
| rootCmd := &cobra.Command{ | |
| Use: "raw-socket", | |
| } | |
| rootCmd.AddCommand( | |
| &cobra.Command{ | |
| Use: "bind-to-device", | |
| Args: cobra.MinimumNArgs(1), | |
| RunE: func(cmd *cobra.Command, args []string) error { | |
| ifaceName := args[0] | |
| bridgeName := "br0" | |
| bridge := &netlink.Bridge{ | |
| LinkAttrs: netlink.LinkAttrs{ | |
| Name: bridgeName, | |
| }, | |
| } | |
| if err := netlink.LinkAdd(bridge); err != nil { | |
| return fmt.Errorf("cannot create a bridge: %v", err) | |
| } | |
| glog.Infof("Will create a RAW socket on interface: %s", ifaceName) | |
| fd, err := unix.Socket(unix.AF_INET6, unix.SOCK_RAW, unix.IPPROTO_ICMPV6) | |
| if err != nil { | |
| return fmt.Errorf("cannot get a RAW socket: %v", err) | |
| } | |
| // we now bind to a the bridge | |
| if err := syscall.SetsockoptString(fd, syscall.SOL_SOCKET, syscall.SO_BINDTODEVICE, bridgeName); err != nil { | |
| return fmt.Errorf("cannot bindtodevice: %v", err) | |
| } | |
| // and use the iface address on the connectAddr | |
| connectAddr := &net.IPAddr{ | |
| IP: net.IPv6unspecified, | |
| Zone: ifaceName, | |
| } | |
| // Bind to the port. | |
| saddr := &unix.SockaddrInet6{} | |
| copy(saddr.Addr[:], connectAddr.IP) | |
| if err := unix.Connect(fd, saddr); err != nil { | |
| return fmt.Errorf("could *NOT* connect to the socket: %v", err) | |
| } | |
| glog.Infof("Successfully created a RAW socket on iface: %s w/ fd number: %d and CONNECTED TO IT", ifaceName, fd) | |
| return nil | |
| }, | |
| }) | |
| if err := rootCmd.Execute(); err != nil { | |
| _, _ = fmt.Fprintln(os.Stderr, err) | |
| os.Exit(1) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment