initial commit [141.14.140.180,mike]

This commit is contained in:
mike committed 2026-10-26 15:52:55 +01:00
commit e34ba75b7b
33 files changed
+6267

No files matched your search

+202
View File
@@ -0,0 +1,202 @@
// 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
}
+87
View File
@@ -0,0 +1,87 @@
package oui
import (
"net"
"path/filepath"
"strings"
"testing"
)
const sampleCSV = `Registry,Assignment,Organization Name,Organization Address
MA-L,3CA62F,AVM Audiovisuelles Marketing und Computersysteme GmbH,Alt-Moabit 95 Berlin DE 10559
MA-L,F0189B,"Apple, Inc.",1 Infinite Loop Cupertino CA US 95014
MA-L,B827EB,Raspberry Pi Foundation,Mitchell Wood House Caldecote GB CB23 7NU
`
const sampleTXT = `OUI/MA-L Organization
company_id Organization
Address
50-C7-BF (hex) TP-LINK TECHNOLOGIES CO.,LTD.
50C7BF (base 16) TP-LINK TECHNOLOGIES CO.,LTD.
Building 24 (floors 1,3,4,5) and 28 (floors1-4)
`
func TestParseAndLookup(t *testing.T) {
db, err := Parse(strings.NewReader(sampleCSV))
if err != nil {
t.Fatal(err)
}
for mac, want := range map[string]string{
"3c:a6:2f:01:02:03": "AVM",
"f0:18:9b:aa:bb:cc": "Apple",
"b8:27:eb:00:00:01": "Raspberry Pi Foundation",
"00:00:00:00:00:01": "",
"da:a1:19:00:00:01": Private,
} {
hw, _ := net.ParseMAC(mac)
if got := db.Lookup(hw); got != want {
t.Errorf("Lookup(%s) = %q, want %q", mac, got, want)
}
}
db, err = Parse(strings.NewReader(sampleTXT))
if err != nil {
t.Fatal(err)
}
hw, _ := net.ParseMAC("50:c7:bf:11:22:33")
if got := db.Lookup(hw); got != "TP-LINK TECHNOLOGIES" {
t.Errorf("txt Lookup = %q", got)
}
}
func TestInstallLoad(t *testing.T) {
path := filepath.Join(t.TempDir(), "oui.tsv")
n, err := Install(strings.NewReader(sampleCSV), path)
if err != nil || n != 3 {
t.Fatalf("Install = %d, %v", n, err)
}
db, err := Load(path)
if err != nil || db.Len() != 3 {
t.Fatalf("Load = %d, %v", db.Len(), err)
}
if _, err := Parse(strings.NewReader("<html>blocked</html>")); err == nil {
t.Error("Parse accepted garbage")
}
}
func TestShortName(t *testing.T) {
for in, want := range map[string]string{
"Apple, Inc.": "Apple",
"Samsung Electronics Co.,Ltd": "Samsung Electronics",
"Sonos, Inc.": "Sonos",
"Espressif Inc.": "Espressif",
"Synology Incorporated": "Synology",
"Hewlett Packard Enterprise, LLC.": "Hewlett Packard Enterprise",
"Ubiquiti Inc": "Ubiquiti",
" Intel Corporate ": "Intel Corporate",
} {
if got := ShortName(in); got != want {
t.Errorf("ShortName(%q) = %q, want %q", in, got, want)
}
}
var nilDB *DB
if nilDB.Lookup(net.HardwareAddr{0, 1, 2, 3, 4, 5}) != "" || nilDB.Len() != 0 {
t.Error("nil DB misbehaves")
}
}