1 /*
2  * Universally Unique IDentifier (UUID)
3  * Copyright (c) 2008, Jouni Malinen <j@w1.fi>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * Alternatively, this software may be distributed under the terms of BSD
10  * license.
11  *
12  * See README and COPYING for more details.
13  */
14 
15 #include "includes.h"
16 
17 #include "common.h"
18 #include "crypto.h"
19 #include "sha1.h"
20 #include "uuid.h"
21 
22 int uuid_str2bin(const char *str, u8 *bin)
23 {
24 	const char *pos;
25 	u8 *opos;
26 
27 	pos = str;
28 	opos = bin;
29 
30 	if (hexstr2bin(pos, opos, 4))
31 		return -1;
32 	pos += 8;
33 	opos += 4;
34 
35 	if (*pos++ != '-' || hexstr2bin(pos, opos, 2))
36 		return -1;
37 	pos += 4;
38 	opos += 2;
39 
40 	if (*pos++ != '-' || hexstr2bin(pos, opos, 2))
41 		return -1;
42 	pos += 4;
43 	opos += 2;
44 
45 	if (*pos++ != '-' || hexstr2bin(pos, opos, 2))
46 		return -1;
47 	pos += 4;
48 	opos += 2;
49 
50 	if (*pos++ != '-' || hexstr2bin(pos, opos, 6))
51 		return -1;
52 
53 	return 0;
54 }
55 
56 
57 int uuid_bin2str(const u8 *bin, char *str, size_t max_len)
58 {
59 	int len;
60 	len = os_snprintf(str, max_len, "%02x%02x%02x%02x-%02x%02x-%02x%02x-"
61 			  "%02x%02x-%02x%02x%02x%02x%02x%02x",
62 			  bin[0], bin[1], bin[2], bin[3],
63 			  bin[4], bin[5], bin[6], bin[7],
64 			  bin[8], bin[9], bin[10], bin[11],
65 			  bin[12], bin[13], bin[14], bin[15]);
66 	if (len < 0 || (size_t) len >= max_len)
67 		return -1;
68 	return 0;
69 }
70 
71 
72 int is_nil_uuid(const u8 *uuid)
73 {
74 	int i;
75 	for (i = 0; i < UUID_LEN; i++)
76 		if (uuid[i])
77 			return 0;
78 	return 1;
79 }
80 
81 
82 void uuid_gen_mac_addr(const u8 *mac_addr, u8 *uuid)
83 {
84 	const u8 *addr[2];
85 	size_t len[2];
86 	u8 hash[SHA1_MAC_LEN];
87 	u8 nsid[16] = {
88 		0x52, 0x64, 0x80, 0xf8,
89 		0xc9, 0x9b,
90 		0x4b, 0xe5,
91 		0xa6, 0x55,
92 		0x58, 0xed, 0x5f, 0x5d, 0x60, 0x84
93 	};
94 
95 	addr[0] = nsid;
96 	len[0] = sizeof(nsid);
97 	addr[1] = mac_addr;
98 	len[1] = 6;
99 	sha1_vector(2, addr, len, hash);
100 	os_memcpy(uuid, hash, 16);
101 
102 	/* Version: 5 = named-based version using SHA-1 */
103 	uuid[6] = (5 << 4) | (uuid[6] & 0x0f);
104 
105 	/* Variant specified in RFC 4122 */
106 	uuid[8] = 0x80 | (uuid[8] & 0x3f);
107 }
108