Example #1
1
func TestPacketDot11CtrlAck(t *testing.T) {
	p := gopacket.NewPacket(testPacketDot11CtrlAck, LinkTypeIEEE80211Radio, gopacket.Default)
	if p.ErrorLayer() != nil {
		t.Error("Failed to decode packet:", p.ErrorLayer().Error())
	}
	checkLayers(p, []gopacket.LayerType{LayerTypeRadioTap, LayerTypeDot11}, t)

	if got, ok := p.Layer(LayerTypeDot11).(*Dot11); ok {
		if !got.ChecksumValid() {
			t.Errorf("Dot11 packet processing failed:\nchecksum failed. got  :\n%#v\n\n", got)
		}
	}

	if got, ok := p.Layer(LayerTypeDot11).(*Dot11); ok {
		want := &Dot11{
			BaseLayer: BaseLayer{
				Contents: []uint8{0xd4, 0x0, 0x0, 0x0, 0x0, 0x19, 0xe3, 0xd3, 0x53, 0x52},
				Payload:  []uint8{},
			},
			Type:       Dot11TypeCtrlAck,
			Proto:      0x0,
			Flags:      0x0,
			DurationID: 0x0,
			Address1:   net.HardwareAddr{0x0, 0x19, 0xe3, 0xd3, 0x53, 0x52},
			Address2:   net.HardwareAddr(nil),
			Address3:   net.HardwareAddr(nil),
			Address4:   net.HardwareAddr(nil),
			Checksum:   0x8776e946,
		}
		if !reflect.DeepEqual(got, want) {
			t.Errorf("Dot11 packet processing failed:\ngot  :\n%#v\n\nwant :\n%#v\n\n", got, want)
		}
	}
}
Example #2
0
func NewEthernet() *Ethernet {
	eth := new(Ethernet)
	eth.HWDst = net.HardwareAddr(make([]byte, 6))
	eth.HWSrc = net.HardwareAddr(make([]byte, 6))
	eth.VLANID = *NewVLAN()
	eth.Ethertype = 0x800
	return eth
}
Example #3
0
func (vb *VXLANBackend) handleInitialSubnetEvents(batch []subnet.Event) error {
	log.Infof("Handling initial subnet events")
	fdbTable, err := vb.dev.GetL2List()
	if err != nil {
		return fmt.Errorf("Error fetching L2 table: %v", err)
	}

	for _, fdbEntry := range fdbTable {
		log.Infof("fdb already populated with: %s %s ", fdbEntry.IP, fdbEntry.HardwareAddr)
	}

	evtMarker := make([]bool, len(batch))
	leaseAttrsList := make([]vxlanLeaseAttrs, len(batch))
	fdbEntryMarker := make([]bool, len(fdbTable))

	for i, evt := range batch {
		if evt.Lease.Attrs.BackendType != "vxlan" {
			log.Warningf("Ignoring non-vxlan subnet: type=%v", evt.Lease.Attrs.BackendType)
			evtMarker[i] = true
			continue
		}

		if err := json.Unmarshal(evt.Lease.Attrs.BackendData, &leaseAttrsList[i]); err != nil {
			log.Error("Error decoding subnet lease JSON: ", err)
			evtMarker[i] = true
			continue
		}

		for j, fdbEntry := range fdbTable {
			if evt.Lease.Attrs.PublicIP.ToIP().Equal(fdbEntry.IP) && bytes.Equal([]byte(leaseAttrsList[i].VtepMAC), []byte(fdbEntry.HardwareAddr)) {
				evtMarker[i] = true
				fdbEntryMarker[j] = true
				break
			}
		}
		vb.rts.set(evt.Lease.Subnet, net.HardwareAddr(leaseAttrsList[i].VtepMAC))
	}

	for j, marker := range fdbEntryMarker {
		if !marker && fdbTable[j].IP != nil {
			err := vb.dev.DelL2(neigh{IP: ip.FromIP(fdbTable[j].IP), MAC: fdbTable[j].HardwareAddr})
			if err != nil {
				log.Error("Delete L2 failed: ", err)
			}
		}
	}

	for i, marker := range evtMarker {
		if !marker {
			err := vb.dev.AddL2(neigh{IP: batch[i].Lease.Attrs.PublicIP, MAC: net.HardwareAddr(leaseAttrsList[i].VtepMAC)})
			if err != nil {
				log.Error("Add L2 failed: ", err)
			}

		}
	}
	return nil
}
Example #4
0
func (vb *VXLANBackend) handleSubnetEvents(batch subnet.EventBatch) {
	for _, evt := range batch {
		switch evt.Type {
		case subnet.SubnetAdded:
			log.Info("Subnet added: ", evt.Lease.Network)

			if evt.Lease.Attrs.BackendType != "vxlan" {
				log.Warningf("Ignoring non-vxlan subnet: type=%v", evt.Lease.Attrs.BackendType)
				continue
			}

			var attrs vxlanLeaseAttrs
			if err := json.Unmarshal(evt.Lease.Attrs.BackendData, &attrs); err != nil {
				log.Error("Error decoding subnet lease JSON: ", err)
				continue
			}

			if err := vb.dev.AddL2(neigh{IP: evt.Lease.Attrs.PublicIP, MAC: net.HardwareAddr(attrs.VtepMAC)}); err != nil {
				log.Error("Error adding L2 entry: ", err)
			}
			if err := vb.dev.AddL3(neigh{IP: evt.Lease.Network.IP, MAC: net.HardwareAddr(attrs.VtepMAC)}); err != nil {
				log.Error("Error adding L3 entry: ", err)
			}
			if err := vb.dev.AddRoute(evt.Lease.Network); err != nil {
				log.Error("Error adding route: ", err)
			}

		case subnet.SubnetRemoved:
			log.Info("Subnet removed: ", evt.Lease.Network)

			if evt.Lease.Attrs.BackendType != "vxlan" {
				log.Warningf("Ignoring non-vxlan subnet: type=%v", evt.Lease.Attrs.BackendType)
				continue
			}

			var attrs vxlanLeaseAttrs
			if err := json.Unmarshal(evt.Lease.Attrs.BackendData, &attrs); err != nil {
				log.Error("Error decoding subnet lease JSON: ", err)
				continue
			}

			if err := vb.dev.DelRoute(evt.Lease.Network); err != nil {
				log.Error("Error deleting route: ", err)
			}
			if len(attrs.VtepMAC) > 0 {
				if err := vb.dev.DelL2(neigh{IP: evt.Lease.Attrs.PublicIP, MAC: net.HardwareAddr(attrs.VtepMAC)}); err != nil {
					log.Error("Error deleting L2 entry: ", err)
				}
				if err := vb.dev.DelL3(neigh{IP: evt.Lease.Network.IP, MAC: net.HardwareAddr(attrs.VtepMAC)}); err != nil {
					log.Error("Error deleting L3 entry: ", err)
				}
			}

		default:
			log.Error("Internal error: unknown event type: ", int(evt.Type))
		}
	}
}
Example #5
0
// NewMatch returns a Match whose fields are all wildcarded
func NewMatch() openflow.Match {
	return &Match{
		wildcards: newWildcardAll(),
		srcMAC:    net.HardwareAddr([]byte{0, 0, 0, 0, 0, 0}),
		dstMAC:    net.HardwareAddr([]byte{0, 0, 0, 0, 0, 0}),
		srcIP:     net.IPv4zero,
		dstIP:     net.IPv4zero,
	}
}
Example #6
0
func (m *Dot11) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error {
	if len(data) < 10 {
		df.SetTruncated()
		return fmt.Errorf("Dot11 length %v too short, %v required", len(data), 10)
	}
	m.Type = Dot11Type((data[0])&0xFC) >> 2

	m.Proto = uint8(data[0]) & 0x0003
	m.Flags = Dot11Flags(data[1])
	m.DurationID = binary.LittleEndian.Uint16(data[2:4])
	m.Address1 = net.HardwareAddr(data[4:10])

	offset := 10

	mainType := m.Type.MainType()

	switch mainType {
	case Dot11TypeCtrl:
		switch m.Type {
		case Dot11TypeCtrlRTS, Dot11TypeCtrlPowersavePoll, Dot11TypeCtrlCFEnd, Dot11TypeCtrlCFEndAck:
			if len(data) < offset+6 {
				df.SetTruncated()
				return fmt.Errorf("Dot11 length %v too short, %v required", len(data), offset+6)
			}
			m.Address2 = net.HardwareAddr(data[offset : offset+6])
			offset += 6
		}
	case Dot11TypeMgmt, Dot11TypeData:
		if len(data) < offset+14 {
			df.SetTruncated()
			return fmt.Errorf("Dot11 length %v too short, %v required", len(data), offset+14)
		}
		m.Address2 = net.HardwareAddr(data[offset : offset+6])
		offset += 6
		m.Address3 = net.HardwareAddr(data[offset : offset+6])
		offset += 6

		m.SequenceNumber = (binary.LittleEndian.Uint16(data[offset:offset+2]) & 0xFFF0) >> 4
		m.FragmentNumber = (binary.LittleEndian.Uint16(data[offset:offset+2]) & 0x000F)
		offset += 2
	}

	if mainType == Dot11TypeData && m.Flags.FromDS() && m.Flags.ToDS() {
		if len(data) < offset+6 {
			df.SetTruncated()
			return fmt.Errorf("Dot11 length %v too short, %v required", len(data), offset+6)
		}
		m.Address4 = net.HardwareAddr(data[offset : offset+6])
		offset += 6
	}

	m.BaseLayer = BaseLayer{Contents: data[0:offset], Payload: data[offset : len(data)-4]}
	m.Checksum = binary.LittleEndian.Uint32(data[len(data)-4 : len(data)])
	return nil
}
Example #7
0
func decodeFDDI(data []byte, p gopacket.PacketBuilder) error {
	f := &FDDI{
		FrameControl: FDDIFrameControl(data[0] & 0xF8),
		Priority:     data[0] & 0x07,
		SrcMAC:       net.HardwareAddr(data[1:7]),
		DstMAC:       net.HardwareAddr(data[7:13]),
		BaseLayer:    BaseLayer{data[:13], data[13:]},
	}
	p.SetLinkLayer(f)
	p.AddLayer(f)
	return p.NextDecoder(f.FrameControl)
}
Example #8
0
// http://en.wikipedia.org/wiki/Ethernet_frame#Structure
//
// - no preamble / SFD / FCS (handle by hardware)
//
// +---------+---------+------+------------------------------------
// | dest    | src     | type | payload
// +---------+---------+------+------------------------------------
func decodeEthernet(raw []byte) (Impl, decodeFunc, error) {
	if len(raw) < 14 {
		return nil, nil, errDecodeFailed
	}

	dest := net.HardwareAddr(raw[0:6])
	src := net.HardwareAddr(raw[6:12])
	type_ := EthernetType(binary.BigEndian.Uint16(raw[12:14]))
	p := &Ethernet{dest, src, type_, raw}

	return p, p.Type.Decoder(), nil
}
Example #9
0
func (p *Packet) Unpack(buf *packet.Buffer) error {
	p.DstAddr = net.HardwareAddr(buf.Next(6))
	p.SrcAddr = net.HardwareAddr(buf.Next(6))

	buf.ReadN(&p.Type)

	if p.Type < 0x0600 {
		p.Length = uint16(p.Type)
		p.Type = LLC
	}

	return nil
}
Example #10
0
func (router *Router) handleForwardedPacket(key ForwardPacketKey) FlowOp {
	if key.DstPeer != router.Ourself.Peer {
		// it's not for us, we're just relaying it
		router.PacketLogging.LogForwardPacket("Relaying", key)
		return router.relay(key)
	}

	// At this point, it's either unicast to us, or a broadcast
	// (because the DstPeer on a forwarded broadcast packet is
	// always set to the peer being forwarded to)

	srcMac := net.HardwareAddr(key.SrcMAC[:])
	dstMac := net.HardwareAddr(key.DstMAC[:])

	switch newSrcMac, conflictPeer := router.Macs.AddForced(srcMac, key.SrcPeer); {
	case newSrcMac:
		log.Print("Discovered remote MAC ", srcMac, " at ", key.SrcPeer)

	case conflictPeer != nil:
		log.Print("Discovered remote MAC ", srcMac, " at ", key.SrcPeer, " (was at ", conflictPeer, ")")

		// We need to clear out any flows destined to the MAC
		// that forward to the old peer.
		router.Overlay.InvalidateRoutes()
	}

	router.PacketLogging.LogForwardPacket("Injecting", key)
	injectFop := router.Bridge.InjectPacket(key.PacketKey)
	dstPeer := router.Macs.Lookup(dstMac)
	if dstPeer == router.Ourself.Peer {
		return injectFop
	}

	router.PacketLogging.LogForwardPacket("Relaying broadcast", key)
	relayFop := router.relayBroadcast(key.SrcPeer, key.PacketKey)
	switch {
	case injectFop == nil:
		return relayFop

	case relayFop == nil:
		return injectFop

	default:
		mfop := NewMultiFlowOp(false)
		mfop.Add(injectFop)
		mfop.Add(relayFop)
		return mfop
	}
}
Example #11
0
func TestRequestPacket(t *testing.T) {
	var tests = []struct {
		description string
		mt          MessageType
		chAddr      net.HardwareAddr
		cIAddr      net.IP
		xId         []byte
		broadcast   bool
		options     []Option
	}{
		{
			description: "discover request",
			mt:          Discover,
			chAddr:      net.HardwareAddr([]byte("01:23:45:67:89:ab")),
			cIAddr:      net.IP([]byte{192, 168, 1, 1}),
			xId:         []byte{0, 1, 2, 3},
			broadcast:   true,
			options:     nil,
		},
		{
			description: "request request",
			mt:          Request,
			chAddr:      net.HardwareAddr([]byte("de:ad:be:ef:de:ad")),
			xId:         []byte{4, 5, 6, 7},
			broadcast:   false,
			options:     oneOptionSlice,
		},
		{
			description: "decline request",
			mt:          Decline,
			chAddr:      net.HardwareAddr([]byte("ff:ff:ff:ff:ff:ff")),
			xId:         []byte{8, 9, 10, 11},
			broadcast:   true,
			options:     twoOptionsSlice,
		},
	}

	for i, tt := range tests {
		// Compare our basic test implementation's packet against the library's
		// implementation
		want := newRequestPacket(tt.mt, tt.chAddr, tt.cIAddr, tt.xId, tt.broadcast, tt.options)
		got := RequestPacket(tt.mt, tt.chAddr, tt.cIAddr, tt.xId, tt.broadcast, tt.options)

		if !bytes.Equal(want, got) {
			t.Fatalf("%02d: RequestPacket(), test %q, unexpected result: %v != %v",
				i, tt.description, want, got)
		}
	}
}
Example #12
0
File: alfred.go Project: hwhw/mesh
// JSON encoder for MAC addresses
func (i HardwareAddr) MarshalJSON() ([]byte, error) {
	buf := new(bytes.Buffer)
	buf.WriteByte('"')
	buf.WriteString(net.HardwareAddr(i).String())
	buf.WriteByte('"')
	return buf.Bytes(), nil
}
Example #13
0
func (r *BaseAction) DstMAC() (ok bool, mac net.HardwareAddr) {
	if r.dstMAC == nil {
		return false, net.HardwareAddr([]byte{0, 0, 0, 0, 0, 0})
	}

	return true, *r.dstMAC
}
Example #14
0
func newInterfaces(ctx *C.struct_ibv_context) {
	var deviceAttr C.struct_ibv_device_attr
	errno := C.ibv_query_device(ctx, &deviceAttr)
	if errno != 0 {
		return
	}

	pd := C.ibv_alloc_pd(ctx)
	if pd == nil {
		panic(newError("ibv_alloc_pd", -1))
	}
	pds[pd] = true

	for port := C.uint8_t(1); port <= deviceAttr.phys_port_cnt; port++ {
		var portAttr C.struct_ibv_port_attr
		errno := C.ibv_query_port(ctx, port, &portAttr)
		if errno != 0 {
			continue
		}

		var gid C.union_ibv_gid
		errno = C.ibv_query_gid(ctx, port, 0, &gid)
		if errno != 0 {
			continue
		}
		// last 8 bytes of GID is the GUID
		guid := net.HardwareAddr(gid[8:])
		iface := &Interface{ctx, pd, uint8(port), &deviceAttr, guid}
		interfaces = append(interfaces, iface)
		guidToInterface[string([]byte(guid))] = iface
	}
}
Example #15
0
func (m *Dot11MgmtReassociationReq) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error {
	m.CapabilityInfo = binary.LittleEndian.Uint16(data[0:2])
	m.ListenInterval = binary.LittleEndian.Uint16(data[2:4])
	m.CurrentApAddress = net.HardwareAddr(data[4:10])
	m.Payload = data[10:]
	return m.Dot11Mgmt.DecodeFromBytes(data, df)
}
Example #16
0
// readARP watches a handle for incoming ARP responses we might care about, and prints them.
//
// readARP loops until 'stop' is closed.
func readARP(handle *pcap.Handle, iface *net.Interface, stop chan struct{}) {
	src := gopacket.NewPacketSource(handle, layers.LayerTypeEthernet)
	in := src.Packets()
	for {
		var packet gopacket.Packet
		select {
		case <-stop:
			return
		case packet = <-in:
			arpLayer := packet.Layer(layers.LayerTypeARP)
			if arpLayer == nil {
				continue
			}
			arp := arpLayer.(*layers.ARP)
			if arp.Operation != layers.ARPReply || bytes.Equal([]byte(iface.HardwareAddr), arp.SourceHwAddress) {
				// This is a packet I sent.
				continue
			}
			// Note:  we might get some packets here that aren't responses to ones we've sent,
			// if for example someone else sends US an ARP request.  Doesn't much matter, though...
			// all information is good information :)
			log.Printf("IP %v is at %v", net.IP(arp.SourceProtAddress), net.HardwareAddr(arp.SourceHwAddress))
		}
	}
}
Example #17
0
func (p Packet) CHAddr() net.HardwareAddr {
	hLen := p.HLen()
	if hLen > 16 { // Prevent chaddr exceeding p boundary
		hLen = 16
	}
	return net.HardwareAddr(p[28 : 28+hLen]) // max endPos 44
}
Example #18
0
func NeighDeserialize(m []byte) (*Neigh, error) {
	msg := deserializeNdmsg(m)

	neigh := Neigh{
		LinkIndex: int(msg.Index),
		Family:    int(msg.Family),
		State:     int(msg.State),
		Type:      int(msg.Type),
		Flags:     int(msg.Flags),
	}

	attrs, err := nl.ParseRouteAttr(m[msg.Len():])
	if err != nil {
		return nil, err
	}

	for _, attr := range attrs {
		switch attr.Attr.Type {
		case NDA_DST:
			neigh.IP = net.IP(attr.Value)
		case NDA_LLADDR:
			neigh.HardwareAddr = net.HardwareAddr(attr.Value)
		}
	}

	return &neigh, nil
}
Example #19
0
func spammer() {
	hostname := "SpamSpamSpam      SpamSpamSpamSpamSpamSpamSpamSpamSpamSpamSpamSpam"

	broadcastConn := openUDPConnOrDie(spamerPort)
	defer broadcastConn.Close()

	addr, err := net.ResolveUDPAddr("udp4", net.IPv4bcast.String()+":"+strconv.Itoa(receiverPort))
	if err != nil {
		log.Fatalf("Cannot resolve broadcast receiver address: %s", err)
	}

	hardwareAddr := make([]byte, 6)
	broadcastCommonData := append(hardwareAddr, byte(len(hostname)))
	broadcastCommonData = append(broadcastCommonData, ([]byte)(hostname)...)

	timestampBuff := make([]byte, 4) //32!!!!
	ticker := time.NewTicker(spamInterval)
	for _ = range ticker.C {
		unixTimestamp := Timestamp(time.Now().Unix())
		endian.PutUint32(timestampBuff, uint32(unixTimestamp))
		endian.PutUint32(broadcastCommonData, rand.Uint32())
		endian.PutUint32(broadcastCommonData[2:], rand.Uint32())
		copy(broadcastCommonData[7:], []byte(net.HardwareAddr(broadcastCommonData[0:6]).String()))
		_, err = broadcastConn.WriteTo(append(broadcastCommonData, timestampBuff...), addr)
		if err != nil {
			log.Fatalf("Unable to broadcast SPAM: %s", err)
		}
	}
}
Example #20
0
func NewARP(opt int) (*ARP, error) {
	if opt != Type_Request && opt != Type_Reply {
		return nil, errors.New("Invalid ARP Operation.")
	}
	a := new(ARP)
	a.HWType = 1
	a.ProtoType = 0x800
	a.HWLength = 6
	a.ProtoLength = 4
	a.Operation = uint16(opt)
	a.HWSrc = net.HardwareAddr(make([]byte, 6))
	a.IPSrc = net.IP(make([]byte, 4))
	a.HWDst = net.HardwareAddr(make([]byte, 6))
	a.IPDst = net.IP(make([]byte, 4))
	return a, nil
}
Example #21
0
File: mac.go Project: d4l3k/chmac
// RandomMac returns a random mac address.
func RandomMac() (net.HardwareAddr, error) {
	addr := make([]byte, 6)
	if _, err := rand.Read(addr[1:]); err != nil {
		return nil, err
	}
	return net.HardwareAddr(addr), nil
}
Example #22
0
func (p *Packet) Unpack(buf *packet.Buffer) error {
	buf.ReadN(&p.HWType)
	buf.ReadN(&p.ProtoType)

	buf.ReadN(&p.HWAddrLen)
	buf.ReadN(&p.ProtoAddrLen)

	buf.ReadN(&p.Operation)

	p.HWSrcAddr = net.HardwareAddr(buf.Next(int(p.HWAddrLen)))
	p.ProtoSrcAddr = net.IP(buf.Next(int(p.ProtoAddrLen)))

	p.HWDstAddr = net.HardwareAddr(buf.Next(int(p.HWAddrLen)))
	p.ProtoDstAddr = net.IP(buf.Next(int(p.ProtoAddrLen)))

	return nil
}
Example #23
0
func decodePBB(data []byte, p gopacket.PacketBuilder) error {
	if data[0]&0x3 != 0 {
		return errors.New("I-TAG TCI Res2 must be zero")
	}
	pbb := &PBB{
		Priority:           data[0] >> 5,
		DropEligible:       data[0]&0x10 != 0,
		UseCustomerAddress: data[0]&0x08 != 0,
		ServiceIdentifier:  binary.BigEndian.Uint32(append(make([]byte, 1), data[1:4]...)),
		DstMAC:             net.HardwareAddr(data[4:10]),
		SrcMAC:             net.HardwareAddr(data[10:16]),
		Type:               layers.EthernetType(binary.BigEndian.Uint16(data[16:18])),
		BaseLayer:          layers.BaseLayer{Contents: data[:18], Payload: data[18:]},
	}
	p.AddLayer(pbb)
	return p.NextDecoder(pbb.Type)
}
Example #24
0
// Address returns the address of the remote peripheral.
func (a *Advertisement) Address() ble.Addr {
	b := a.e.Address(a.i)
	addr := net.HardwareAddr([]byte{b[5], b[4], b[3], b[2], b[1], b[0]})
	if a.e.AddressType(a.i) == 1 {
		return RandomAddress{addr}
	}
	return addr
}
func TestFilename(t *testing.T) {
	for _, tt := range []struct {
		i logicalInterface
		f string
	}{
		{logicalInterface{name: "iface", configDepth: 0}, "00-iface"},
		{logicalInterface{name: "iface", configDepth: 9}, "09-iface"},
		{logicalInterface{name: "iface", configDepth: 10}, "0a-iface"},
		{logicalInterface{name: "iface", configDepth: 53}, "35-iface"},
		{logicalInterface{hwaddr: net.HardwareAddr([]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}), configDepth: 1}, "01-01:23:45:67:89:ab"},
		{logicalInterface{name: "iface", hwaddr: net.HardwareAddr([]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}), configDepth: 1}, "01-iface"},
	} {
		if tt.i.Filename() != tt.f {
			t.Fatalf("bad filename (%q): got %q, want %q", tt.i, tt.i.Filename(), tt.f)
		}
	}
}
Example #26
0
// TestNewDUIDLLT verifies that NewDUIDLLT generates a proper DUIDLLT or error
// from an input hardware type, time value, and hardware address.
func TestNewDUIDLLT(t *testing.T) {
	var tests = []struct {
		desc         string
		hardwareType uint16
		time         time.Time
		hardwareAddr net.HardwareAddr
		duid         *DUIDLLT
		err          error
	}{
		{
			desc: "date too early",
			time: duidLLTTime.Add(-1 * time.Minute),
			err:  ErrInvalidDUIDLLTTime,
		},
		{
			desc:         "OK",
			hardwareType: 1,
			time:         duidLLTTime.Add(1 * time.Minute),
			hardwareAddr: net.HardwareAddr([]byte{0, 1, 0, 1, 0, 1}),
			duid: &DUIDLLT{
				Type:         DUIDTypeLLT,
				HardwareType: 1,
				Time:         duidLLTTime.Add(1 * time.Minute).Sub(duidLLTTime),
				HardwareAddr: net.HardwareAddr([]byte{0, 1, 0, 1, 0, 1}),
			},
		},
	}

	for i, tt := range tests {
		duid, err := NewDUIDLLT(tt.hardwareType, tt.time, tt.hardwareAddr)
		if err != nil {
			if want, got := tt.err, err; want != got {
				t.Fatalf("[%02d] test %q, unexpected error: %v != %v",
					i, tt.desc, want, got)
			}

			continue
		}

		if want, got := tt.duid, duid; !reflect.DeepEqual(want, got) {
			t.Fatalf("[%02d] test %q, unexpected DUIDLLT:\n- want %v\n-  got %v",
				i, tt.desc, want, got)
		}
	}
}
Example #27
0
func (router *NetworkRouter) handleCapturedPacket(key PacketKey) FlowOp {
	router.PacketLogging.LogPacket("Captured", key)
	srcMac := net.HardwareAddr(key.SrcMAC[:])

	switch newSrcMac, conflictPeer := router.Macs.Add(srcMac, router.Ourself.Peer); {
	case newSrcMac:
		log.Println("Discovered local MAC", srcMac)

	case conflictPeer != nil:
		// The MAC cache has an entry for the source MAC
		// associated with another peer.  This probably means
		// we are seeing a frame we injected ourself.  That
		// shouldn't happen, but discard it just in case.
		log.Error("Captured frame from MAC (", srcMac, ") associated with another peer ", conflictPeer)
		return DiscardingFlowOp{}
	}

	// Discard STP broadcasts
	if key.DstMAC == [...]byte{0x01, 0x80, 0xC2, 0x00, 0x00, 0x00} {
		return DiscardingFlowOp{}
	}

	dstMac := net.HardwareAddr(key.DstMAC[:])
	switch dstPeer := router.Macs.Lookup(dstMac); dstPeer {
	case router.Ourself.Peer:
		// The packet is destined for a local MAC.  The bridge
		// won't normally send us such packets, and if it does
		// it's likely to be broadcasting the packet to all
		// ports.  So if it happens, just drop the packet to
		// avoid warnings if we try to forward it.
		return DiscardingFlowOp{}
	case nil:
		// If we don't know which peer corresponds to the dest
		// MAC, broadcast it.
		router.PacketLogging.LogPacket("Broadcasting", key)
		return router.relayBroadcast(router.Ourself.Peer, key)
	default:
		router.PacketLogging.LogPacket("Forwarding", key)
		return router.relay(ForwardPacketKey{
			PacketKey: key,
			SrcPeer:   router.Ourself.Peer,
			DstPeer:   dstPeer})
	}
}
Example #28
0
// Generate a MAC address.
func GenerateMAC() (net.HardwareAddr, error) {
	buf := make([]byte, 6)
	_, err := rand.Read(buf)
	if err != nil {
		return nil, err
	}
	buf[0] &= 0xFE // Unicast
	buf[0] |= 0x02 // Locally administered
	return net.HardwareAddr(buf), nil
}
Example #29
0
func (vb *VXLANBackend) handleSubnetEvents(batch []subnet.Event) {
	for _, evt := range batch {
		switch evt.Type {
		case subnet.EventAdded:
			log.Info("Subnet added: ", evt.Lease.Subnet)

			if evt.Lease.Attrs.BackendType != "vxlan" {
				log.Warningf("Ignoring non-vxlan subnet: type=%v", evt.Lease.Attrs.BackendType)
				continue
			}

			var attrs vxlanLeaseAttrs
			if err := json.Unmarshal(evt.Lease.Attrs.BackendData, &attrs); err != nil {
				log.Error("Error decoding subnet lease JSON: ", err)
				continue
			}
			vb.rts.set(evt.Lease.Subnet, net.HardwareAddr(attrs.VtepMAC))
			vb.dev.AddL2(neigh{IP: evt.Lease.Attrs.PublicIP, MAC: net.HardwareAddr(attrs.VtepMAC)})

		case subnet.EventRemoved:
			log.Info("Subnet removed: ", evt.Lease.Subnet)

			if evt.Lease.Attrs.BackendType != "vxlan" {
				log.Warningf("Ignoring non-vxlan subnet: type=%v", evt.Lease.Attrs.BackendType)
				continue
			}

			var attrs vxlanLeaseAttrs
			if err := json.Unmarshal(evt.Lease.Attrs.BackendData, &attrs); err != nil {
				log.Error("Error decoding subnet lease JSON: ", err)
				continue
			}

			if len(attrs.VtepMAC) > 0 {
				vb.dev.DelL2(neigh{IP: evt.Lease.Attrs.PublicIP, MAC: net.HardwareAddr(attrs.VtepMAC)})
			}
			vb.rts.remove(evt.Lease.Subnet)

		default:
			log.Error("Internal error: unknown event type: ", int(evt.Type))
		}
	}
}
Example #30
0
func (m *Dot11) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error {
	m.Type = Dot11Type((data[0])&0xFC) >> 2

	m.Proto = uint8(data[0]) & 0x0003
	m.Flags = Dot11Flags(data[1])
	m.DurationID = binary.LittleEndian.Uint16(data[2:4])
	m.Address1 = net.HardwareAddr(data[4:10])

	offset := 10

	mainType := m.Type.MainType()

	switch mainType {
	case Dot11TypeCtrl:
		switch m.Type {
		case Dot11TypeCtrlRTS, Dot11TypeCtrlPowersavePoll, Dot11TypeCtrlCFEnd, Dot11TypeCtrlCFEndAck:
			m.Address2 = net.HardwareAddr(data[offset : offset+6])
			offset += 6
		}
	case Dot11TypeMgmt, Dot11TypeData:
		m.Address2 = net.HardwareAddr(data[offset : offset+6])
		offset += 6
		m.Address3 = net.HardwareAddr(data[offset : offset+6])
		offset += 6

		m.SequenceNumber = (binary.LittleEndian.Uint16(data[offset:offset+2]) & 0xFFC0) >> 6
		m.FragmentNumber = (binary.LittleEndian.Uint16(data[offset:offset+2]) & 0x003F)
		offset += 2
	}

	if mainType == Dot11TypeData && m.Flags.FromDS() && m.Flags.ToDS() {
		m.Address4 = net.HardwareAddr(data[offset : offset+6])
		offset += 6
	}

	if mainType == Dot11TypeData {
		m.BaseLayer = BaseLayer{Contents: data[0:offset], Payload: data[offset:len(data)]}
	} else {
		m.BaseLayer = BaseLayer{Contents: data[0:offset], Payload: data[offset : len(data)-4]}
		m.Checksum = binary.LittleEndian.Uint32(data[len(data)-4 : len(data)])
	}
	return nil
}