xref: /freebsd/sys/kern/kern_uuid.c (revision 6bb132ba)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2002 Marcel Moolenaar
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 #include <sys/param.h>
30 #include <sys/endian.h>
31 #include <sys/kernel.h>
32 #include <sys/lock.h>
33 #include <sys/malloc.h>
34 #include <sys/mutex.h>
35 #include <sys/sbuf.h>
36 #include <sys/socket.h>
37 #include <sys/sysproto.h>
38 #include <sys/systm.h>
39 #include <sys/jail.h>
40 #include <sys/uuid.h>
41 
42 #include <net/if.h>
43 #include <net/if_dl.h>
44 #include <net/if_types.h>
45 #include <net/vnet.h>
46 
47 /*
48  * See also:
49  *	http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt
50  *	http://www.opengroup.org/onlinepubs/009629399/apdxa.htm
51  *
52  * Note that the generator state is itself an UUID, but the time and clock
53  * sequence fields are written in the native byte order.
54  */
55 
56 CTASSERT(sizeof(struct uuid) == 16);
57 
58 /* We use an alternative, more convenient representation in the generator. */
59 struct uuid_private {
60 	union {
61 		uint64_t	ll;	/* internal, for uuid_last only */
62 		struct {
63 			uint32_t	low;
64 			uint16_t	mid;
65 			uint16_t	hi;
66 		} x;
67 	} time;
68 	uint16_t	seq;			/* Big-endian. */
69 	uint16_t	node[UUID_NODE_LEN>>1];
70 };
71 
72 CTASSERT(sizeof(struct uuid_private) == 16);
73 
74 struct uuid_macaddr {
75 	uint16_t	state;
76 #define	UUID_ETHER_EMPTY	0
77 #define	UUID_ETHER_RANDOM	1
78 #define	UUID_ETHER_UNIQUE	2
79 	uint16_t	node[UUID_NODE_LEN>>1];
80 };
81 
82 static struct uuid_private uuid_last;
83 
84 #define UUID_NETHER	4
85 static struct uuid_macaddr uuid_ether[UUID_NETHER];
86 
87 static struct mtx uuid_mutex;
88 MTX_SYSINIT(uuid_lock, &uuid_mutex, "UUID generator mutex lock", MTX_DEF);
89 
90 /*
91  * Return the first MAC address added in the array. If it's empty, then
92  * construct a sufficiently random multicast MAC address first. Any
93  * addresses added later will bump the random MAC address up tp the next
94  * index.
95  */
96 static void
uuid_node(uint16_t * node)97 uuid_node(uint16_t *node)
98 {
99 	int i;
100 
101 	if (uuid_ether[0].state == UUID_ETHER_EMPTY) {
102 		for (i = 0; i < (UUID_NODE_LEN>>1); i++)
103 			uuid_ether[0].node[i] = (uint16_t)arc4random();
104 		*((uint8_t*)uuid_ether[0].node) |= 0x01;
105 		uuid_ether[0].state = UUID_ETHER_RANDOM;
106 	}
107 	for (i = 0; i < (UUID_NODE_LEN>>1); i++)
108 		node[i] = uuid_ether[0].node[i];
109 }
110 
111 /*
112  * Get the current time as a 60 bit count of 100-nanosecond intervals
113  * since 00:00:00.00, October 15,1582. We apply a magic offset to convert
114  * the Unix time since 00:00:00.00, January 1, 1970 to the date of the
115  * Gregorian reform to the Christian calendar.
116  */
117 static uint64_t
uuid_time(void)118 uuid_time(void)
119 {
120 	struct bintime bt;
121 	uint64_t time = 0x01B21DD213814000LL;
122 
123 	bintime(&bt);
124 	time += (uint64_t)bt.sec * 10000000LL;
125 	time += (10000000LL * (uint32_t)(bt.frac >> 32)) >> 32;
126 	return (time & ((1LL << 60) - 1LL));
127 }
128 
129 struct uuid *
kern_uuidgen(struct uuid * store,size_t count)130 kern_uuidgen(struct uuid *store, size_t count)
131 {
132 	struct uuid_private uuid;
133 	uint64_t time;
134 	size_t n;
135 
136 	mtx_lock(&uuid_mutex);
137 
138 	uuid_node(uuid.node);
139 	time = uuid_time();
140 
141 	if (uuid_last.time.ll == 0LL || uuid_last.node[0] != uuid.node[0] ||
142 	    uuid_last.node[1] != uuid.node[1] ||
143 	    uuid_last.node[2] != uuid.node[2])
144 		uuid.seq = (uint16_t)arc4random() & 0x3fff;
145 	else if (uuid_last.time.ll >= time)
146 		uuid.seq = (uuid_last.seq + 1) & 0x3fff;
147 	else
148 		uuid.seq = uuid_last.seq;
149 
150 	uuid_last = uuid;
151 	uuid_last.time.ll = (time + count - 1) & ((1LL << 60) - 1LL);
152 
153 	mtx_unlock(&uuid_mutex);
154 
155 	/* Set sequence and variant and deal with byte order. */
156 	uuid.seq = htobe16(uuid.seq | 0x8000);
157 
158 	for (n = 0; n < count; n++) {
159 		/* Set time and version (=1). */
160 		uuid.time.x.low = (uint32_t)time;
161 		uuid.time.x.mid = (uint16_t)(time >> 32);
162 		uuid.time.x.hi = ((uint16_t)(time >> 48) & 0xfff) | (1 << 12);
163 		store[n] = *(struct uuid *)&uuid;
164 		time++;
165 	}
166 
167 	return (store);
168 }
169 
170 #ifndef _SYS_SYSPROTO_H_
171 struct uuidgen_args {
172 	struct uuid *store;
173 	int	count;
174 };
175 #endif
176 int
sys_uuidgen(struct thread * td,struct uuidgen_args * uap)177 sys_uuidgen(struct thread *td, struct uuidgen_args *uap)
178 {
179 	struct uuid *store;
180 	size_t count;
181 	int error;
182 
183 	/*
184 	 * Limit the number of UUIDs that can be created at the same time
185 	 * to some arbitrary number. This isn't really necessary, but I
186 	 * like to have some sort of upper-bound that's less than 2G :-)
187 	 * XXX probably needs to be tunable.
188 	 */
189 	if (uap->count < 1 || uap->count > 2048)
190 		return (EINVAL);
191 
192 	count = uap->count;
193 	store = malloc(count * sizeof(struct uuid), M_TEMP, M_WAITOK);
194 	kern_uuidgen(store, count);
195 	error = copyout(store, uap->store, count * sizeof(struct uuid));
196 	free(store, M_TEMP);
197 	return (error);
198 }
199 
200 int
uuid_ether_add(const uint8_t * addr)201 uuid_ether_add(const uint8_t *addr)
202 {
203 	int i, sum;
204 
205 	/*
206 	 * Validate input. No multicast (flag 0x1), no locally administered
207 	 * (flag 0x2) and no 'all-zeroes' addresses.
208 	 */
209 	if (addr[0] & 0x03)
210 		return (EINVAL);
211 	sum = 0;
212 	for (i = 0; i < UUID_NODE_LEN; i++)
213 		sum += addr[i];
214 	if (sum == 0)
215 		return (EINVAL);
216 
217 	mtx_lock(&uuid_mutex);
218 
219 	/* Make sure the MAC isn't known already and that there's space. */
220 	i = 0;
221 	while (i < UUID_NETHER && uuid_ether[i].state == UUID_ETHER_UNIQUE) {
222 		if (!bcmp(addr, uuid_ether[i].node, UUID_NODE_LEN)) {
223 			mtx_unlock(&uuid_mutex);
224 			return (EEXIST);
225 		}
226 		i++;
227 	}
228 	if (i == UUID_NETHER) {
229 		mtx_unlock(&uuid_mutex);
230 		return (ENOSPC);
231 	}
232 
233 	/* Insert MAC at index, moving the non-empty entry if possible. */
234 	if (uuid_ether[i].state == UUID_ETHER_RANDOM && i < UUID_NETHER - 1)
235 		uuid_ether[i + 1] = uuid_ether[i];
236 	uuid_ether[i].state = UUID_ETHER_UNIQUE;
237 	bcopy(addr, uuid_ether[i].node, UUID_NODE_LEN);
238 	mtx_unlock(&uuid_mutex);
239 	return (0);
240 }
241 
242 int
uuid_ether_del(const uint8_t * addr)243 uuid_ether_del(const uint8_t *addr)
244 {
245 	int i;
246 
247 	mtx_lock(&uuid_mutex);
248 	i = 0;
249 	while (i < UUID_NETHER && uuid_ether[i].state == UUID_ETHER_UNIQUE &&
250 	    bcmp(addr, uuid_ether[i].node, UUID_NODE_LEN))
251 		i++;
252 	if (i == UUID_NETHER || uuid_ether[i].state != UUID_ETHER_UNIQUE) {
253 		mtx_unlock(&uuid_mutex);
254 		return (ENOENT);
255 	}
256 
257 	/* Remove it by shifting higher index entries down. */
258 	while (i < UUID_NETHER - 1 && uuid_ether[i].state != UUID_ETHER_EMPTY) {
259 		uuid_ether[i] = uuid_ether[i + 1];
260 		i++;
261 	}
262 	if (uuid_ether[i].state != UUID_ETHER_EMPTY) {
263 		uuid_ether[i].state = UUID_ETHER_EMPTY;
264 		bzero(uuid_ether[i].node, UUID_NODE_LEN);
265 	}
266 	mtx_unlock(&uuid_mutex);
267 	return (0);
268 }
269 
270 int
snprintf_uuid(char * buf,size_t sz,struct uuid * uuid)271 snprintf_uuid(char *buf, size_t sz, struct uuid *uuid)
272 {
273 	struct uuid_private *id;
274 	int cnt;
275 
276 	id = (struct uuid_private *)uuid;
277 	cnt = snprintf(buf, sz, "%08x-%04x-%04x-%04x-%04x%04x%04x",
278 	    id->time.x.low, id->time.x.mid, id->time.x.hi, be16toh(id->seq),
279 	    be16toh(id->node[0]), be16toh(id->node[1]), be16toh(id->node[2]));
280 	return (cnt);
281 }
282 
283 int
printf_uuid(struct uuid * uuid)284 printf_uuid(struct uuid *uuid)
285 {
286 	char buf[38];
287 
288 	snprintf_uuid(buf, sizeof(buf), uuid);
289 	return (printf("%s", buf));
290 }
291 
292 int
sbuf_printf_uuid(struct sbuf * sb,struct uuid * uuid)293 sbuf_printf_uuid(struct sbuf *sb, struct uuid *uuid)
294 {
295 	char buf[38];
296 
297 	snprintf_uuid(buf, sizeof(buf), uuid);
298 	return (sbuf_cat(sb, buf));
299 }
300 
301 /*
302  * Encode/Decode UUID into byte-stream.
303  *   http://www.opengroup.org/dce/info/draft-leach-uuids-guids-01.txt
304  *
305  * 0                   1                   2                   3
306  *   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
307  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
308  *  |                          time_low                             |
309  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
310  *  |       time_mid                |         time_hi_and_version   |
311  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
312  *  |clk_seq_hi_res |  clk_seq_low  |         node (0-1)            |
313  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
314  *  |                         node (2-5)                            |
315  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
316  */
317 
318 void
le_uuid_enc(void * buf,struct uuid const * uuid)319 le_uuid_enc(void *buf, struct uuid const *uuid)
320 {
321 	u_char *p;
322 	int i;
323 
324 	p = buf;
325 	le32enc(p, uuid->time_low);
326 	le16enc(p + 4, uuid->time_mid);
327 	le16enc(p + 6, uuid->time_hi_and_version);
328 	p[8] = uuid->clock_seq_hi_and_reserved;
329 	p[9] = uuid->clock_seq_low;
330 	for (i = 0; i < _UUID_NODE_LEN; i++)
331 		p[10 + i] = uuid->node[i];
332 }
333 
334 void
le_uuid_dec(void const * buf,struct uuid * uuid)335 le_uuid_dec(void const *buf, struct uuid *uuid)
336 {
337 	u_char const *p;
338 	int i;
339 
340 	p = buf;
341 	uuid->time_low = le32dec(p);
342 	uuid->time_mid = le16dec(p + 4);
343 	uuid->time_hi_and_version = le16dec(p + 6);
344 	uuid->clock_seq_hi_and_reserved = p[8];
345 	uuid->clock_seq_low = p[9];
346 	for (i = 0; i < _UUID_NODE_LEN; i++)
347 		uuid->node[i] = p[10 + i];
348 }
349 
350 void
be_uuid_enc(void * buf,struct uuid const * uuid)351 be_uuid_enc(void *buf, struct uuid const *uuid)
352 {
353 	u_char *p;
354 	int i;
355 
356 	p = buf;
357 	be32enc(p, uuid->time_low);
358 	be16enc(p + 4, uuid->time_mid);
359 	be16enc(p + 6, uuid->time_hi_and_version);
360 	p[8] = uuid->clock_seq_hi_and_reserved;
361 	p[9] = uuid->clock_seq_low;
362 	for (i = 0; i < _UUID_NODE_LEN; i++)
363 		p[10 + i] = uuid->node[i];
364 }
365 
366 void
be_uuid_dec(void const * buf,struct uuid * uuid)367 be_uuid_dec(void const *buf, struct uuid *uuid)
368 {
369 	u_char const *p;
370 	int i;
371 
372 	p = buf;
373 	uuid->time_low = be32dec(p);
374 	uuid->time_mid = be16dec(p + 4);
375 	uuid->time_hi_and_version = be16dec(p + 6);
376 	uuid->clock_seq_hi_and_reserved = p[8];
377 	uuid->clock_seq_low = p[9];
378 	for (i = 0; i < _UUID_NODE_LEN; i++)
379 		uuid->node[i] = p[10 + i];
380 }
381 
382 int
validate_uuid(const char * str,size_t size,struct uuid * uuid,int flags)383 validate_uuid(const char *str, size_t size, struct uuid *uuid, int flags)
384 {
385 	u_int c[11];
386 	int n;
387 
388 	if (size == 0 || *str == '\0') {
389 		/* An empty string may represent a nil UUID. */
390 		if ((flags & VUUIDF_EMPTYOK) != 0) {
391 			if (uuid != NULL)
392 				bzero(uuid, sizeof(*uuid));
393 			return (0);
394 		}
395 
396 		return (EINVAL);
397 	}
398 
399 	/* The UUID string representation has a fixed length. */
400 	if (size != 36)
401 		return (EINVAL);
402 
403 	/*
404 	 * We only work with "new" UUIDs. New UUIDs have the form:
405 	 *      01234567-89ab-cdef-0123-456789abcdef
406 	 * The so called "old" UUIDs, which we don't support, have the form:
407 	 *      0123456789ab.cd.ef.01.23.45.67.89.ab
408 	 */
409 	if (str[8] != '-')
410 		return (EINVAL);
411 
412 	/* Now check the format. */
413 	n = sscanf(str, "%8x-%4x-%4x-%2x%2x-%2x%2x%2x%2x%2x%2x", c + 0, c + 1,
414 	    c + 2, c + 3, c + 4, c + 5, c + 6, c + 7, c + 8, c + 9, c + 10);
415 	/* Make sure we have all conversions. */
416 	if (n != 11)
417 		return (EINVAL);
418 
419 	/* Successful scan. Build the UUID if requested. */
420 	if (uuid != NULL) {
421 		uuid->time_low = c[0];
422 		uuid->time_mid = c[1];
423 		uuid->time_hi_and_version = c[2];
424 		uuid->clock_seq_hi_and_reserved = c[3];
425 		uuid->clock_seq_low = c[4];
426 		for (n = 0; n < 6; n++)
427 			uuid->node[n] = c[n + 5];
428 	}
429 
430 	if ((flags & VUUIDF_CHECKSEMANTICS) == 0)
431 		return (0);
432 
433 	return (((c[3] & 0x80) != 0x00 &&		/* variant 0? */
434 	    (c[3] & 0xc0) != 0x80 &&			/* variant 1? */
435 	    (c[3] & 0xe0) != 0xc0) ? EINVAL : 0);	/* variant 2? */
436 }
437 
438 #define	VUUIDF_PARSEFLAGS	(VUUIDF_EMPTYOK | VUUIDF_CHECKSEMANTICS)
439 
440 int
parse_uuid(const char * str,struct uuid * uuid)441 parse_uuid(const char *str, struct uuid *uuid)
442 {
443 
444 	return (validate_uuid(str, strlen(str), uuid, VUUIDF_PARSEFLAGS));
445 }
446 
447 int
uuidcmp(const struct uuid * uuid1,const struct uuid * uuid2)448 uuidcmp(const struct uuid *uuid1, const struct uuid *uuid2)
449 {
450 
451 	return (memcmp(uuid1, uuid2, sizeof(struct uuid)));
452 }
453