Skip to content

Commit 24054e5

Browse files
authored
Use persisted random MACs for eth0 interface (#410)
Add a persistent MAC pre-up hook for eth0 and implement /usr/local/sbin/derived-mac to generate interface MAC for locally administered mac address. This will be used for cases where there's no mac address configured on USB adapter, due to missing firmware of other reasons.
1 parent 31823e7 commit 24054e5

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
--- a/etc/network/interfaces.d/eth0
2+
+++ b/etc/network/interfaces.d/eth0
3+
@@ -1,3 +1,4 @@
4+
iface eth0 inet manual
5+
+ pre-up /usr/local/sbin/restore-mac eth0
6+
dhcp-up /sbin/dhcpcd
7+
dhcp-down /sbin/dhcpcd -k
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
#!/bin/bash
2+
3+
set -eu
4+
5+
is_locally_administered_unicast_mac() {
6+
case "$1" in
7+
[0-9a-fA-F][0-9a-fA-F]:*)
8+
first_octet="${1%%:*}"
9+
first_octet_value=$((0x$first_octet))
10+
[[ $((first_octet_value & 0x02)) -ne 0 ]] && [[ $((first_octet_value & 0x01)) -eq 0 ]]
11+
;;
12+
*)
13+
return 1
14+
;;
15+
esac
16+
}
17+
18+
is_valid_mac_address() {
19+
[[ "$1" =~ ^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$ ]]
20+
}
21+
22+
generate_random_mac() {
23+
local raw
24+
25+
raw="$(hexdump -n 5 -v -e '/1 "%02x"' /dev/urandom)"
26+
27+
printf 'fe:%s:%s:%s:%s:%s\n' \
28+
"${raw:0:2}" \
29+
"${raw:2:2}" \
30+
"${raw:4:2}" \
31+
"${raw:6:2}" \
32+
"${raw:8:2}"
33+
}
34+
35+
ifname="${1:-}"
36+
37+
if [[ $# -ne 1 || -z "$ifname" ]]; then
38+
echo "Usage: $0 <ifname>" >&2
39+
exit 1
40+
fi
41+
42+
if [[ ! -e "/sys/class/net/$ifname/address" ]]; then
43+
echo "Interface '$ifname' does not exist" >&2
44+
exit 1
45+
fi
46+
47+
current_mac="$(cat "/sys/class/net/$ifname/address" 2>/dev/null || true)"
48+
if ! is_locally_administered_unicast_mac "$current_mac"; then
49+
echo "The $ifname MAC is not random, leaving it unchanged" >&2
50+
exit 0
51+
fi
52+
53+
mac_dir="/oem/printer_data/network"
54+
mac_file="$mac_dir/${ifname}.address"
55+
mkdir -p "$mac_dir"
56+
57+
stable_mac="$(cat "$mac_file" 2>/dev/null || true)"
58+
if ! is_valid_mac_address "$stable_mac"; then
59+
stable_mac="$(generate_random_mac)"
60+
printf '%s\n' "$stable_mac" > "$mac_file"
61+
fi
62+
63+
[[ "$current_mac" == "$stable_mac" ]] || /sbin/ip link set dev "$ifname" address "$stable_mac"

0 commit comments

Comments
 (0)