// Package oui maps MAC address prefixes to hardware vendors using the IEEE // MA-L registry, which nscan keeps as a compact TSV file. package oui import ( "bufio" "bytes" "context" "encoding/csv" "encoding/hex" "errors" "fmt" "io" "net" "net/http" "os" "path/filepath" "regexp" "sort" "strings" "time" ) // SourceURL is the IEEE registry nscan downloads. const SourceURL = "https://standards-oui.ieee.org/oui/oui.csv" // Private is reported for locally administered (randomized) MAC addresses, // which phones and laptops use per Wi-Fi network. const Private = "Private address" // DB maps 24-bit OUI prefixes to vendor names. A nil *DB is valid and only // recognizes private addresses. type DB struct { m map[[3]byte]string } // Lookup returns the vendor of mac or "" if unknown. func (db *DB) Lookup(mac net.HardwareAddr) string { if len(mac) < 3 { return "" } if mac[0]&0x02 != 0 { return Private } if db == nil { return "" } return db.m[[3]byte{mac[0], mac[1], mac[2]}] } // Len returns the number of known prefixes. func (db *DB) Len() int { if db == nil { return 0 } return len(db.m) } // Load reads a TSV file written by Install. func Load(path string) (*DB, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() db := &DB{m: make(map[[3]byte]string, 40000)} sc := bufio.NewScanner(f) for sc.Scan() { prefix, name, ok := strings.Cut(sc.Text(), "\t") if k, valid := parsePrefix(prefix); ok && valid { db.m[k] = name } } return db, sc.Err() } // Parse reads the IEEE registry in its CSV (oui.csv) or text (oui.txt) form. func Parse(r io.Reader) (*DB, error) { data, err := io.ReadAll(r) if err != nil { return nil, err } data = bytes.TrimPrefix(data, []byte("\xef\xbb\xbf")) db := &DB{m: make(map[[3]byte]string, 40000)} if bytes.HasPrefix(data, []byte("Registry,")) { cr := csv.NewReader(bytes.NewReader(data)) cr.FieldsPerRecord = -1 cr.LazyQuotes = true for { rec, err := cr.Read() if err == io.EOF { break } if err != nil { return nil, err } if len(rec) < 3 { continue } if k, ok := parsePrefix(rec[1]); ok { db.m[k] = ShortName(rec[2]) } } } else { for _, m := range txtLine.FindAllSubmatch(data, -1) { if k, ok := parsePrefix(string(m[1]) + string(m[2]) + string(m[3])); ok { db.m[k] = ShortName(string(m[4])) } } } if len(db.m) == 0 { return nil, errors.New("no OUI entries found – is this the IEEE oui.csv or oui.txt?") } return db, nil } var txtLine = regexp.MustCompile(`(?m)^([0-9A-Fa-f]{2})-([0-9A-Fa-f]{2})-([0-9A-Fa-f]{2})\s+\(hex\)\s+(.+?)\s*$`) func parsePrefix(s string) ([3]byte, bool) { var k [3]byte b, err := hex.DecodeString(strings.TrimSpace(s)) if err != nil || len(b) != 3 { return k, false } copy(k[:], b) return k, true } // Install parses the registry from r and stores it at path. func Install(r io.Reader, path string) (int, error) { db, err := Parse(r) if err != nil { return 0, err } keys := make([][3]byte, 0, len(db.m)) for k := range db.m { keys = append(keys, k) } sort.Slice(keys, func(i, j int) bool { return bytes.Compare(keys[i][:], keys[j][:]) < 0 }) var buf bytes.Buffer for _, k := range keys { fmt.Fprintf(&buf, "%X\t%s\n", k[:], db.m[k]) } if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { return 0, err } tmp := path + ".tmp" if err := os.WriteFile(tmp, buf.Bytes(), 0o644); err != nil { return 0, err } return len(keys), os.Rename(tmp, path) } // Download fetches the registry from the IEEE and installs it at path. func Download(ctx context.Context, path string) (int, error) { ctx, cancel := context.WithTimeout(ctx, 2*time.Minute) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodGet, SourceURL, nil) if err != nil { return 0, err } req.Header.Set("User-Agent", "nscan/1.0 (OUI vendor lookup)") resp, err := http.DefaultClient.Do(req) if err != nil { return 0, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return 0, fmt.Errorf("IEEE server responded with %s", resp.Status) } return Install(resp.Body, path) } var legalSuffixes = []string{ "inc", "inc.", "incorporated", "corp", "corp.", "corporation", "co", "co.", "co.,ltd", "co.,ltd.", "co. ltd", "co. ltd.", "co., ltd", "co., ltd.", "ltd", "ltd.", "limited", "llc", "l.l.c.", "gmbh", "gmbh & co. kg", "ag", "se", "s.a.", "sa", "s.p.a.", "b.v.", "bv", "n.v.", "plc", "pty ltd", "pty. ltd.", "oy", "ab", "as", "a/s", "kg", "sas", "s.r.l.", "srl", } // ShortName strips legal-form suffixes ("Apple, Inc." → "Apple"). func ShortName(name string) string { name = strings.Join(strings.Fields(name), " ") for changed := true; changed; { changed = false name = strings.TrimRight(name, " ,.") lower := strings.ToLower(name) for _, suf := range legalSuffixes { suf = " " + strings.TrimSuffix(suf, ".") if strings.HasSuffix(lower, suf) && len(name) > len(suf) { name = name[:len(name)-len(suf)] changed = true break } } } if strings.HasPrefix(name, "AVM Audiovisuelles") { return "AVM" } return name }