Skip to content

Commit 0cf4aa8

Browse files
committed
try read mac of tap0 and fallback to /dev/Xrandom: rootless-containers#259
1 parent 32fae28 commit 0cf4aa8

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

main.c

+15-6
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,7 @@ static const char *pseudo_random_global_id(const char *device)
228228
unsigned char hash[SHA_DIGEST_LENGTH];
229229
struct ntptimeval ntv;
230230
struct ifreq ifr;
231-
const unsigned char *mac;
231+
unsigned char mac[18];
232232
int sockfd;
233233

234234
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
@@ -246,11 +246,20 @@ static const char *pseudo_random_global_id(const char *device)
246246
strncpy(ifr.ifr_name, device, sizeof(ifr.ifr_name) - 1);
247247

248248
if (ioctl(sockfd, SIOCGIFHWADDR, &ifr) < 0) {
249-
perror("cannot get dev hwaddr");
250-
return NULL;
249+
int rand = open("/dev/urandom", O_RDONLY);
250+
if (rand == -1) {
251+
rand = open("/dev/random", O_RDONLY);
252+
}
253+
if (rand == -1) {
254+
perror("cannot get dev hwaddr and cannot open random");
255+
return NULL;
256+
}
257+
read(rand, &mac, sizeof(mac));
258+
close(rand);
259+
}
260+
else {
261+
strncpy(mac, ifr.ifr_ifru.ifru_addr.sa_data, sizeof(mac));
251262
}
252-
253-
mac = (unsigned char*)ifr.ifr_ifru.ifru_addr.sa_data;
254263

255264
/* https://tools.ietf.org/html/rfc4193
256265
*
@@ -1177,7 +1186,7 @@ static int slirp4netns_config_from_options(struct slirp4netns_config *cfg,
11771186
if (cidr == NULL) {
11781187
cidr = DEFAULT_CIDR6;
11791188
if (opt->ipv6_random) {
1180-
cidr = pseudo_random_global_id("lo");
1189+
cidr = pseudo_random_global_id("tap0");
11811190
if (cidr == NULL) {
11821191
fprintf(stderr, "cannot create pseudo random global id\n");
11831192
rc = -1;

0 commit comments

Comments
 (0)