diff options
author | Pablo Mazzini <pmazzini@gmail.com> | 2018-11-18 11:59:57 +0000 |
---|---|---|
committer | Pablo Mazzini <pmazzini@gmail.com> | 2018-11-18 11:59:57 +0000 |
commit | 9be884266e5fd226a2663d90f36e72fc1d15bd2e (patch) | |
tree | 53821d9e394b09de6288160301870de198347610 /dhcpv6/iputils.go | |
parent | 01251f1da16d2734ca8e4fe503ba1c911ade2032 (diff) |
iputils: add ExtractMAC
Diffstat (limited to 'dhcpv6/iputils.go')
-rw-r--r-- | dhcpv6/iputils.go | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/dhcpv6/iputils.go b/dhcpv6/iputils.go index 2b9788c..3ad157e 100644 --- a/dhcpv6/iputils.go +++ b/dhcpv6/iputils.go @@ -42,3 +42,54 @@ func GetGlobalAddr(ifname string) (net.IP, error) { return ip.To4() == nil && ip.IsGlobalUnicast() }) } + +// GetMacAddressFromEUI64 will return a valid MAC address ONLY if it's a EUI-48 +func GetMacAddressFromEUI64(ip net.IP) (net.HardwareAddr, error) { + if ip.To16() == nil { + return nil, fmt.Errorf("IP address shorter than 16 bytes") + } + + if isEUI48 := ip[11] == 0xff && ip[12] == 0xfe; !isEUI48 { + return nil, fmt.Errorf("IP address is not an EUI48 address") + } + + mac := make(net.HardwareAddr, 6) + copy(mac[0:3], ip[8:11]) + copy(mac[3:6], ip[13:16]) + mac[0] ^= 0x02 + + return mac, nil +} + +// ExtractMAC looks into the inner most PeerAddr field in the RelayInfo header +// which contains the EUI-64 address of the client making the request, populated +// by the dhcp relay, it is possible to extract the mac address from that IP. +// If that fails, it looks for the MAC addressed embededded in the DUID. +// Note that this only works with type DuidLL and DuidLLT. +// If a mac address cannot be found an error will be returned. +func ExtractMAC(packet DHCPv6) (net.HardwareAddr, error) { + msg := packet + if packet.IsRelay() { + inner, err := DecapsulateRelayIndex(packet, -1) + if err != nil { + return nil, err + } + ip := inner.(*DHCPv6Relay).PeerAddr() + if mac, err := GetMacAddressFromEUI64(ip); err == nil { + return mac, nil + } + msg, err = msg.(*DHCPv6Relay).GetInnerMessage() + if err != nil { + return nil, err + } + } + optclientid := msg.GetOneOption(OptionClientID) + if optclientid == nil { + return nil, fmt.Errorf("client ID not found in packet") + } + duid := optclientid.(*OptClientId).Cid + if duid.LinkLayerAddr == nil { + return nil, fmt.Errorf("failed to extract MAC") + } + return duid.LinkLayerAddr, nil +} |