Skip to content

Commit 9eaab91

Browse files
assign{Ips,Macs}: Fix integer overflow
Half of SHA256 sums truncated to 16 chars actually go over 2^63, which is beyond the range for hexToDec. This fixes the integer overflow error in Lix 2.91+ and Nix 2.25+, as well as undefined behaviour for versions below.
1 parent e81b403 commit 9eaab91

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

nix/net-extensions.nix

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,8 @@ in {
239239
#
240240
# > net.cidr.assignIps "192.168.100.1/24" [202 "192.168.100.74"] ["a" "b" "c"]
241241
# { a = "192.168.100.203"; b = "192.168.100.75"; c = "192.168.100.226"; }
242+
#
243+
# WARN: Does not work on IPv6 addresses with Lix 2.91+ and Nix.25+ as they ban integer overflow.
242244
assignIps = net: reserved: hosts: let
243245
cidrSize = libNet.cidr.size net;
244246
capacity = libNet.cidr.capacity net;
@@ -266,7 +268,8 @@ in {
266268
# Generates a hash (i.e. offset value) for a given hostname
267269
hashElem = x:
268270
builtins.bitAnd (capacity - 1)
269-
(hexToDec (builtins.substring 0 16 (builtins.hashString "sha256" x)));
271+
# 15 characters is as many hexToDec can handle (60 bits)
272+
(hexToDec (builtins.substring 0 15 (builtins.hashString "sha256" x)));
270273
# Do linear probing. Returns the first unused value at or after the given value.
271274
probe = avoid: value:
272275
if elem value avoid
@@ -333,6 +336,8 @@ in {
333336
#
334337
# > net.mac.assignMacs "11:22:33:00:00:00" 24 ["11:22:33:1b:bd:ca"] ["a" "b" "c"]
335338
# { a = "11:22:33:1b:bd:cb"; b = "11:22:33:39:59:4a"; c = "11:22:33:50:7a:e2"; }
339+
#
340+
# WARN: Does not work with Lix 2.91+ and Nix.25+ as they ban integer overflow.
336341
assignMacs = base: size: reserved: hosts: let
337342
capacity = pow 2 size;
338343
baseAsInt = libNet.mac.diff base "00:00:00:00:00:00";
@@ -353,7 +358,8 @@ in {
353358
# Generates a hash (i.e. offset value) for a given hostname
354359
hashElem = x:
355360
builtins.bitAnd (capacity - 1)
356-
(hexToDec (substring 0 16 (builtins.hashString "sha256" x)));
361+
# 15 characters is as many hexToDec can handle (60 bits)
362+
(hexToDec (substring 0 15 (builtins.hashString "sha256" x)));
357363
# Do linear probing. Returns the first unused value at or after the given value.
358364
probe = avoid: value:
359365
if elem value avoid

0 commit comments

Comments
 (0)