Wipe (some) secrets from memory after use
[tinc] / src / utils.c
1 /*
2     utils.c -- gathering of some stupid small functions
3     Copyright (C) 1999-2005 Ivo Timmermans
4                   2000-2013 Guus Sliepen <guus@tinc-vpn.org>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include <assert.h>
22
23 #include "logger.h"
24 #include "system.h"
25 #include "utils.h"
26 #include "xalloc.h"
27
28 static const char hexadecimals[] = "0123456789ABCDEF";
29 static const char base64_original[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
30 static const char base64_urlsafe[] =  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
31 static const char base64_decode[256] = {
32         -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
33                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
34                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, 62, -1, 63,
35                 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
36                 -1,  0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14,
37                 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63,
38                 -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
39                 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
40                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
41                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
42                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
43                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
44                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
45                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
46                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
47                 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
48         };
49
50 static uint8_t charhex2bin(char c) {
51         uint8_t cu = (uint8_t) c;
52
53         if(isdigit(cu)) {
54                 return cu - '0';
55         } else {
56                 return toupper(cu) - 'A' + 10;
57         }
58 }
59
60 size_t hex2bin(const char *src, void *vdst, size_t length) {
61         uint8_t *dst = vdst;
62         size_t i;
63
64         for(i = 0; i < length && isxdigit((uint8_t) src[i * 2]) && isxdigit((uint8_t) src[i * 2 + 1]); i++) {
65                 dst[i] = charhex2bin(src[i * 2]) * 16 + charhex2bin(src[i * 2 + 1]);
66         }
67
68         return i;
69 }
70
71 size_t bin2hex(const void *vsrc, char *dst, size_t length) {
72         const char *src = vsrc;
73
74         for(size_t i = length; i > 0;) {
75                 --i;
76                 dst[i * 2 + 1] = hexadecimals[(unsigned char) src[i] & 15];
77                 dst[i * 2] = hexadecimals[(unsigned char) src[i] >> 4];
78         }
79
80         dst[length * 2] = 0;
81         return length * 2;
82 }
83
84 size_t b64decode_tinc(const char *src, void *dst, size_t length) {
85         size_t i;
86         uint32_t triplet = 0;
87         unsigned char *udst = (unsigned char *)dst;
88
89         for(i = 0; i < length && src[i]; i++) {
90                 triplet |= base64_decode[src[i] & 0xff] << (6 * (i & 3));
91
92                 if((i & 3) == 3) {
93                         if(triplet & 0xff000000U) {
94                                 return 0;
95                         }
96
97                         udst[0] = triplet & 0xff;
98                         triplet >>= 8;
99                         udst[1] = triplet & 0xff;
100                         triplet >>= 8;
101                         udst[2] = triplet;
102                         triplet = 0;
103                         udst += 3;
104                 }
105         }
106
107         if(triplet & 0xff000000U) {
108                 return 0;
109         }
110
111         if((i & 3) == 3) {
112                 udst[0] = triplet & 0xff;
113                 triplet >>= 8;
114                 udst[1] = triplet & 0xff;
115                 return i / 4 * 3 + 2;
116         } else if((i & 3) == 2) {
117                 udst[0] = triplet & 0xff;
118                 return i / 4 * 3 + 1;
119         } else {
120                 return i / 4 * 3;
121         }
122 }
123
124 bool is_decimal(const char *str) {
125         if(!str) {
126                 return false;
127         }
128
129         errno = 0;
130         char *badchar = NULL;
131         strtol(str, &badchar, 10);
132         return !errno && badchar != str && !*badchar;
133 }
134
135 // itoa() conflicts with a similarly named function under MinGW.
136 char *int_to_str(int num) {
137         char *str = NULL;
138         xasprintf(&str, "%d", num);
139         return str;
140 }
141
142 static size_t b64encode_tinc_internal(const void *src, char *dst, size_t length, const char *alphabet) {
143         uint32_t triplet;
144         const unsigned char *usrc = (unsigned char *)src;
145         size_t si = length / 3 * 3;
146         size_t di = length / 3 * 4;
147
148         switch(length % 3) {
149         case 2:
150                 triplet = usrc[si] | usrc[si + 1] << 8;
151                 dst[di] = alphabet[triplet & 63];
152                 triplet >>= 6;
153                 dst[di + 1] = alphabet[triplet & 63];
154                 triplet >>= 6;
155                 dst[di + 2] = alphabet[triplet];
156                 dst[di + 3] = 0;
157                 length = di + 3;
158                 break;
159
160         case 1:
161                 triplet = usrc[si];
162                 dst[di] = alphabet[triplet & 63];
163                 triplet >>= 6;
164                 dst[di + 1] = alphabet[triplet];
165                 dst[di + 2] = 0;
166                 length = di + 2;
167                 break;
168
169         default:
170                 dst[di] = 0;
171                 length = di;
172                 break;
173         }
174
175         while(si > 0) {
176                 di -= 4;
177                 si -= 3;
178                 triplet = usrc[si] | usrc[si + 1] << 8 | usrc[si + 2] << 16;
179                 dst[di] = alphabet[triplet & 63];
180                 triplet >>= 6;
181                 dst[di + 1] = alphabet[triplet & 63];
182                 triplet >>= 6;
183                 dst[di + 2] = alphabet[triplet & 63];
184                 triplet >>= 6;
185                 dst[di + 3] = alphabet[triplet];
186         }
187
188         return length;
189 }
190
191 size_t b64encode_tinc(const void *src, char *dst, size_t length) {
192         return b64encode_tinc_internal(src, dst, length, base64_original);
193 }
194
195 size_t b64encode_tinc_urlsafe(const void *src, char *dst, size_t length) {
196         return b64encode_tinc_internal(src, dst, length, base64_urlsafe);
197 }
198
199 #ifdef HAVE_WINDOWS
200 const char *winerror(int err) {
201         static char buf[1024], *ptr;
202
203         ptr = buf + snprintf(buf, sizeof(buf), "(%d) ", err);
204
205         if(!FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
206                           NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), ptr, sizeof(buf) - (ptr - buf), NULL)) {
207                 strncpy(buf, "(unable to format errormessage)", sizeof(buf));
208         };
209
210         if((ptr = strchr(buf, '\r'))) {
211                 *ptr = '\0';
212         }
213
214         return buf;
215 }
216 #endif
217
218 bool check_id(const char *id) {
219         if(!id || !*id) {
220                 return false;
221         }
222
223         for(; *id; id++)
224                 if(!isalnum((uint8_t) *id) && *id != '_') {
225                         return false;
226                 }
227
228         return true;
229 }
230
231 bool check_netname(const char *netname, bool strict) {
232         if(!netname || !*netname || *netname == '.') {
233                 return false;
234         }
235
236         for(const char *c = netname; *c; c++) {
237                 if(iscntrl((uint8_t) *c)) {
238                         return false;
239                 }
240
241                 if(*c == '/' || *c == '\\') {
242                         return false;
243                 }
244
245                 if(strict && strchr(" $%<>:`\"|?*", *c)) {
246                         return false;
247                 }
248         }
249
250         return true;
251 }
252
253 /* Windows doesn't define HOST_NAME_MAX. */
254 #ifndef HOST_NAME_MAX
255 #define HOST_NAME_MAX 255
256 #endif
257
258 char *replace_name(const char *name) {
259         char *ret_name;
260
261         if(name[0] == '$') {
262                 char *envname = getenv(name + 1);
263                 char hostname[HOST_NAME_MAX + 1];
264
265                 if(!envname) {
266                         if(strcmp(name + 1, "HOST")) {
267                                 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid Name: environment variable %s does not exist\n", name + 1);
268                                 return NULL;
269                         }
270
271                         if(gethostname(hostname, sizeof(hostname)) || !*hostname) {
272                                 logger(DEBUG_ALWAYS, LOG_ERR, "Could not get hostname: %s\n", sockstrerror(sockerrno));
273                                 return NULL;
274                         }
275
276                         hostname[HOST_NAME_MAX] = 0;
277                         envname = hostname;
278                 }
279
280                 ret_name = xstrdup(envname);
281
282                 for(char *c = ret_name; *c; c++)
283                         if(!isalnum((uint8_t) *c)) {
284                                 *c = '_';
285                         }
286         } else {
287                 ret_name = xstrdup(name);
288         }
289
290         if(!check_id(ret_name)) {
291                 logger(DEBUG_ALWAYS, LOG_ERR, "Invalid name for myself!");
292                 free(ret_name);
293                 return NULL;
294         }
295
296         return ret_name;
297 }
298
299 /* Open a file with the desired permissions, minus the umask.
300    Also, if we want to create an executable file, we call fchmod()
301    to set the executable bits. */
302
303 FILE *fopenmask(const char *filename, const char *mode, mode_t perms) {
304         mode_t mask = umask(0);
305         perms &= ~mask;
306         umask(~perms & 0777);
307         FILE *f = fopen(filename, mode);
308
309         if(!f) {
310                 fprintf(stderr, "Could not open %s: %s\n", filename, strerror(errno));
311                 return NULL;
312         }
313
314 #ifdef HAVE_FCHMOD
315
316         if(perms & 0444) {
317                 fchmod(fileno(f), perms);
318         }
319
320 #endif
321         umask(mask);
322         return f;
323 }
324