libcollectdclient: Replace TODOs with (hopefully) useful comments.
[collectd.git] / src / libcollectdclient / network_parse.c
1 /**
2  * Copyright 2017 Florian Forster
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a copy
5  * of this software and associated documentation files (the "Software"), to deal
6  * in the Software without restriction, including without limitation the rights
7  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8  * copies of the Software, and to permit persons to whom the Software is
9  * furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20  * SOFTWARE.
21  *
22  * Authors:
23  *   Florian octo Forster <octo at collectd.org>
24  **/
25
26 #if HAVE_CONFIG_H
27 #include "config.h"
28 #endif
29
30 #if !defined(__GNUC__) || !__GNUC__
31 #define __attribute__(x) /**/
32 #endif
33
34 #include "collectd/lcc_features.h"
35 #include "collectd/network_parse.h"
36
37 #include <errno.h>
38 #include <math.h>
39 #include <pthread.h>
40
41 #define GCRYPT_NO_DEPRECATED
42 #include <gcrypt.h>
43
44 #include <stdio.h>
45 #define DEBUG(...) printf(__VA_ARGS__)
46
47 GCRY_THREAD_OPTION_PTHREAD_IMPL;
48
49 /* forward declaration because parse_sign_sha256()/parse_encrypt_aes256() and
50  * network_parse() need to call each other. */
51 static int network_parse(void *data, size_t data_size, lcc_security_level_t sl,
52                          lcc_network_parse_options_t const *opts);
53
54 static int init_gcrypt() {
55   /* http://lists.gnupg.org/pipermail/gcrypt-devel/2003-August/000458.html
56    * Because you can't know in a library whether another library has
57    * already initialized the library */
58   if (gcry_control(GCRYCTL_ANY_INITIALIZATION_P))
59     return (0);
60
61 /* http://www.gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html
62  * To ensure thread-safety, it's important to set GCRYCTL_SET_THREAD_CBS
63  * *before* initalizing Libgcrypt with gcry_check_version(), which itself must
64  * be called before any other gcry_* function. GCRYCTL_ANY_INITIALIZATION_P
65  * above doesn't count, as it doesn't implicitly initalize Libgcrypt.
66  *
67  * tl;dr: keep all these gry_* statements in this exact order please. */
68 #if GCRYPT_VERSION_NUMBER < 0x010600
69   if (gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread)) {
70     return -1;
71   }
72 #endif
73
74   gcry_check_version(NULL);
75
76   if (gcry_control(GCRYCTL_INIT_SECMEM, 32768)) {
77     return -1;
78   }
79
80   gcry_control(GCRYCTL_INITIALIZATION_FINISHED);
81   return 0;
82 }
83
84 typedef struct {
85   uint8_t *data;
86   size_t len;
87 } buffer_t;
88
89 static int buffer_next(buffer_t *b, void *out, size_t n) {
90   if (b->len < n) {
91     return -1;
92   }
93   memmove(out, b->data, n);
94
95   b->data += n;
96   b->len -= n;
97
98   return 0;
99 }
100
101 static int buffer_uint16(buffer_t *b, uint16_t *out) {
102   uint16_t tmp;
103   if (buffer_next(b, &tmp, sizeof(tmp)) != 0)
104     return -1;
105
106   *out = be16toh(tmp);
107   return 0;
108 }
109
110 #define TYPE_HOST 0x0000
111 #define TYPE_TIME 0x0001
112 #define TYPE_TIME_HR 0x0008
113 #define TYPE_PLUGIN 0x0002
114 #define TYPE_PLUGIN_INSTANCE 0x0003
115 #define TYPE_TYPE 0x0004
116 #define TYPE_TYPE_INSTANCE 0x0005
117 #define TYPE_VALUES 0x0006
118 #define TYPE_INTERVAL 0x0007
119 #define TYPE_INTERVAL_HR 0x0009
120 #define TYPE_SIGN_SHA256 0x0200
121 #define TYPE_ENCR_AES256 0x0210
122
123 static int parse_int(void *payload, size_t payload_size, uint64_t *out) {
124   uint64_t tmp;
125
126   if (payload_size != sizeof(tmp))
127     return EINVAL;
128
129   memmove(&tmp, payload, sizeof(tmp));
130   *out = be64toh(tmp);
131   return 0;
132 }
133
134 static int parse_string(void *payload, size_t payload_size, char *out,
135                         size_t out_size) {
136   char *in = payload;
137
138   if ((payload_size < 1) || (in[payload_size - 1] != 0) ||
139       (payload_size > out_size))
140     return EINVAL;
141
142   strncpy(out, in, out_size);
143   return 0;
144 }
145
146 static int parse_identifier(uint16_t type, void *payload, size_t payload_size,
147                             lcc_value_list_t *state) {
148   char buf[LCC_NAME_LEN];
149
150   if (parse_string(payload, payload_size, buf, sizeof(buf)) != 0)
151     return EINVAL;
152
153   switch (type) {
154   case TYPE_HOST:
155     memmove(state->identifier.host, buf, LCC_NAME_LEN);
156     break;
157   case TYPE_PLUGIN:
158     memmove(state->identifier.plugin, buf, LCC_NAME_LEN);
159     break;
160   case TYPE_PLUGIN_INSTANCE:
161     memmove(state->identifier.plugin_instance, buf, LCC_NAME_LEN);
162     break;
163   case TYPE_TYPE:
164     memmove(state->identifier.type, buf, LCC_NAME_LEN);
165     break;
166   case TYPE_TYPE_INSTANCE:
167     memmove(state->identifier.type_instance, buf, LCC_NAME_LEN);
168     break;
169   default:
170     return EINVAL;
171   }
172
173   return 0;
174 }
175
176 static int parse_time(uint16_t type, void *payload, size_t payload_size,
177                       lcc_value_list_t *state) {
178   uint64_t tmp = 0;
179   if (parse_int(payload, payload_size, &tmp))
180     return EINVAL;
181
182   double t = (double)tmp;
183   switch (type) {
184   case TYPE_INTERVAL:
185     state->interval = t;
186     break;
187   case TYPE_INTERVAL_HR:
188     state->interval = t / 1073741824.0;
189     break;
190   case TYPE_TIME:
191     state->time = t;
192     break;
193   case TYPE_TIME_HR:
194     state->time = t / 1073741824.0;
195     break;
196   default:
197     return EINVAL;
198   }
199
200   return 0;
201 }
202
203 static double ntohd(double val) /* {{{ */
204 {
205   static int config = 0;
206
207   union {
208     uint8_t byte[8];
209     double floating;
210   } in = {
211       .floating = val,
212   };
213   union {
214     uint8_t byte[8];
215     double floating;
216   } out = {
217       .byte = {0},
218   };
219
220   if (config == 0) {
221     double d = 8.642135e130;
222     uint8_t b[8];
223
224     memcpy(b, &d, sizeof(b));
225
226     if ((b[0] == 0x2f) && (b[1] == 0x25) && (b[2] == 0xc0) && (b[3] == 0xc7) &&
227         (b[4] == 0x43) && (b[5] == 0x2b) && (b[6] == 0x1f) && (b[7] == 0x5b))
228       config = 1; /* need nothing */
229     else if ((b[7] == 0x2f) && (b[6] == 0x25) && (b[5] == 0xc0) &&
230              (b[4] == 0xc7) && (b[3] == 0x43) && (b[2] == 0x2b) &&
231              (b[1] == 0x1f) && (b[0] == 0x5b))
232       config = 2; /* endian flip */
233     else if ((b[4] == 0x2f) && (b[5] == 0x25) && (b[6] == 0xc0) &&
234              (b[7] == 0xc7) && (b[0] == 0x43) && (b[1] == 0x2b) &&
235              (b[2] == 0x1f) && (b[3] == 0x5b))
236       config = 3; /* int swap */
237     else
238       config = 4;
239   }
240
241   if (memcmp((char[]){0, 0, 0, 0, 0, 0, 0xf8, 0x7f}, in.byte, 8) == 0) {
242     return NAN;
243   } else if (config == 1) {
244     return val;
245   } else if (config == 2) {
246     in.floating = val;
247     out.byte[0] = in.byte[7];
248     out.byte[1] = in.byte[6];
249     out.byte[2] = in.byte[5];
250     out.byte[3] = in.byte[4];
251     out.byte[4] = in.byte[3];
252     out.byte[5] = in.byte[2];
253     out.byte[6] = in.byte[1];
254     out.byte[7] = in.byte[0];
255     return (out.floating);
256   } else if (config == 3) {
257     in.floating = val;
258     out.byte[0] = in.byte[4];
259     out.byte[1] = in.byte[5];
260     out.byte[2] = in.byte[6];
261     out.byte[3] = in.byte[7];
262     out.byte[4] = in.byte[0];
263     out.byte[5] = in.byte[1];
264     out.byte[6] = in.byte[2];
265     out.byte[7] = in.byte[3];
266     return out.floating;
267   } else {
268     /* If in doubt, just copy the value back to the caller. */
269     return val;
270   }
271 } /* }}} double ntohd */
272
273 static int parse_values(void *payload, size_t payload_size,
274                         lcc_value_list_t *state) {
275   buffer_t *b = &(buffer_t){
276       .data = payload, .len = payload_size,
277   };
278
279   uint16_t n;
280   if (buffer_uint16(b, &n))
281     return EINVAL;
282
283   if (((size_t)n * 9) != b->len)
284     return EINVAL;
285
286   state->values_len = (size_t)n;
287   state->values = calloc(sizeof(*state->values), state->values_len);
288   state->values_types = calloc(sizeof(*state->values_types), state->values_len);
289   if ((state->values == NULL) || (state->values_types == NULL)) {
290     free(state->values);
291     free(state->values_types);
292     return ENOMEM;
293   }
294
295   for (uint16_t i = 0; i < n; i++) {
296     uint8_t tmp;
297     if (buffer_next(b, &tmp, sizeof(tmp)))
298       return EINVAL;
299     state->values_types[i] = (int)tmp;
300   }
301
302   for (uint16_t i = 0; i < n; i++) {
303     uint64_t tmp;
304     if (buffer_next(b, &tmp, sizeof(tmp)))
305       return EINVAL;
306
307     if (state->values_types[i] == LCC_TYPE_GAUGE) {
308       union {
309         uint64_t i;
310         double d;
311       } conv = {.i = tmp};
312       state->values[i].gauge = ntohd(conv.d);
313       continue;
314     }
315
316     tmp = be64toh(tmp);
317     switch (state->values_types[i]) {
318     case LCC_TYPE_COUNTER:
319       state->values[i].counter = (counter_t)tmp;
320       break;
321     case LCC_TYPE_DERIVE:
322       state->values[i].derive = (derive_t)tmp;
323       break;
324     case LCC_TYPE_ABSOLUTE:
325       state->values[i].absolute = (absolute_t)tmp;
326       break;
327     default:
328       return EINVAL;
329     }
330   }
331
332   return 0;
333 }
334
335 static int verify_sha256(void *payload, size_t payload_size,
336                          char const *username, char const *password,
337                          uint8_t hash_provided[32]) {
338   gcry_md_hd_t hd = NULL;
339
340   gcry_error_t err = gcry_md_open(&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
341   if (err != 0) {
342     return (int)err;
343   }
344
345   err = gcry_md_setkey(hd, password, strlen(password));
346   if (err != 0) {
347     gcry_md_close(hd);
348     return (int)err;
349   }
350
351   gcry_md_write(hd, username, strlen(username));
352   gcry_md_write(hd, payload, payload_size);
353
354   unsigned char *hash_calculated = gcry_md_read(hd, GCRY_MD_SHA256);
355   if (!hash_calculated) {
356     gcry_md_close(hd);
357     return -1;
358   }
359
360   int ret = memcmp(hash_provided, hash_calculated, 32);
361
362   gcry_md_close(hd);
363   hash_calculated = NULL;
364
365   return !!ret;
366 }
367
368 static int parse_sign_sha256(void *signature, size_t signature_len,
369                              void *payload, size_t payload_size,
370                              lcc_network_parse_options_t const *opts) {
371   if (opts->password_lookup == NULL) {
372     /* The sender signed the packet but we can't verify it. Handle it as if it
373      * were unsigned, i.e. security level NONE. */
374     return network_parse(payload, payload_size, NONE, opts);
375   }
376
377   buffer_t *b = &(buffer_t){
378       .data = signature, .len = signature_len,
379   };
380
381   uint8_t hash[32];
382   if (buffer_next(b, hash, sizeof(hash)))
383     return EINVAL;
384
385   char username[b->len + 1];
386   memset(username, 0, sizeof(username));
387   if (buffer_next(b, username, sizeof(username) - 1)) {
388     return EINVAL;
389   }
390
391   char const *password = opts->password_lookup(username);
392   if (!password)
393     return network_parse(payload, payload_size, NONE, opts);
394
395   int status = verify_sha256(payload, payload_size, username, password, hash);
396   if (status != 0)
397     return status;
398
399   return network_parse(payload, payload_size, SIGN, opts);
400 }
401
402 static int decrypt_aes256(buffer_t *b, void *iv, size_t iv_size,
403                           char const *password) {
404   gcry_cipher_hd_t cipher = NULL;
405
406   if (gcry_cipher_open(&cipher, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB,
407                        /* flags = */ 0))
408     return -1;
409
410   uint8_t pwhash[32] = {0};
411   gcry_md_hash_buffer(GCRY_MD_SHA256, pwhash, password, strlen(password));
412
413   fprintf(stderr, "sizeof(iv) = %zu\n", sizeof(iv));
414   if (gcry_cipher_setkey(cipher, pwhash, sizeof(pwhash)) ||
415       gcry_cipher_setiv(cipher, iv, iv_size) ||
416       gcry_cipher_decrypt(cipher, b->data, b->len, /* in = */ NULL,
417                           /* in_size = */ 0)) {
418     gcry_cipher_close(cipher);
419     return -1;
420   }
421
422   gcry_cipher_close(cipher);
423   return 0;
424 }
425
426 static int parse_encrypt_aes256(void *data, size_t data_size,
427                                 lcc_network_parse_options_t const *opts) {
428   if (opts->password_lookup == NULL) {
429     /* Without a password source it's (hopefully) impossible to decrypt the
430      * network packet. */
431     return ENOENT;
432   }
433
434   buffer_t *b = &(buffer_t){
435       .data = data, .len = data_size,
436   };
437
438   uint16_t username_len;
439   if (buffer_uint16(b, &username_len))
440     return EINVAL;
441   if ((size_t)username_len > data_size)
442     return ENOMEM;
443   char username[((size_t)username_len) + 1];
444   memset(username, 0, sizeof(username));
445   if (buffer_next(b, username, (size_t)username_len))
446     return EINVAL;
447
448   char const *password = opts->password_lookup(username);
449   if (!password)
450     return ENOENT;
451
452   uint8_t iv[16];
453   if (buffer_next(b, iv, sizeof(iv)))
454     return EINVAL;
455
456   int status = decrypt_aes256(b, iv, sizeof(iv), password);
457   if (status != 0)
458     return status;
459
460   uint8_t hash_provided[20];
461   if (buffer_next(b, hash_provided, sizeof(hash_provided))) {
462     return -1;
463   }
464
465   uint8_t hash_calculated[20];
466   gcry_md_hash_buffer(GCRY_MD_SHA1, hash_calculated, b->data, b->len);
467
468   if (memcmp(hash_provided, hash_calculated, sizeof(hash_provided)) != 0) {
469     return -1;
470   }
471
472   return network_parse(b->data, b->len, ENCRYPT, opts);
473 }
474
475 static int network_parse(void *data, size_t data_size, lcc_security_level_t sl,
476                          lcc_network_parse_options_t const *opts) {
477   buffer_t *b = &(buffer_t){
478       .data = data, .len = data_size,
479   };
480
481   lcc_value_list_t state = {0};
482
483   while (b->len > 0) {
484     uint16_t type = 0, sz = 0;
485     if (buffer_uint16(b, &type) || buffer_uint16(b, &sz)) {
486       DEBUG("lcc_network_parse(): reading type and/or length failed.\n");
487       return EINVAL;
488     }
489
490     if ((sz < 5) || (((size_t)sz - 4) > b->len)) {
491       DEBUG("lcc_network_parse(): invalid 'sz' field: sz = %" PRIu16
492             ", b->len = %zu\n",
493             sz, b->len);
494       return EINVAL;
495     }
496     sz -= 4;
497
498     uint8_t payload[sz];
499     if (buffer_next(b, payload, sizeof(payload)))
500       return EINVAL;
501
502     switch (type) {
503     case TYPE_HOST:
504     case TYPE_PLUGIN:
505     case TYPE_PLUGIN_INSTANCE:
506     case TYPE_TYPE:
507     case TYPE_TYPE_INSTANCE: {
508       if (parse_identifier(type, payload, sizeof(payload), &state)) {
509         DEBUG("lcc_network_parse(): parse_identifier failed.\n");
510         return EINVAL;
511       }
512       break;
513     }
514
515     case TYPE_INTERVAL:
516     case TYPE_INTERVAL_HR:
517     case TYPE_TIME:
518     case TYPE_TIME_HR: {
519       if (parse_time(type, payload, sizeof(payload), &state)) {
520         DEBUG("lcc_network_parse(): parse_time failed.\n");
521         return EINVAL;
522       }
523       break;
524     }
525
526     case TYPE_VALUES: {
527       lcc_value_list_t vl = state;
528       if (parse_values(payload, sizeof(payload), &vl)) {
529         DEBUG("lcc_network_parse(): parse_values failed.\n");
530         return EINVAL;
531       }
532
533       int status = 0;
534
535       /* Write metrics if they have the required security level. */
536       if (sl >= opts->security_level)
537         status = opts->writer(&vl);
538
539       free(vl.values);
540       free(vl.values_types);
541
542       if (status != 0)
543         return status;
544       break;
545     }
546
547     case TYPE_SIGN_SHA256: {
548       int status =
549           parse_sign_sha256(payload, sizeof(payload), b->data, b->len, opts);
550       if (status != 0) {
551         DEBUG("lcc_network_parse(): parse_sign_sha256() = %d\n", status);
552         return -1;
553       }
554       /* parse_sign_sha256, if successful, consumes all remaining data. */
555       b->data = NULL;
556       b->len = 0;
557       break;
558     }
559
560     case TYPE_ENCR_AES256: {
561       int status = parse_encrypt_aes256(payload, sizeof(payload), opts);
562       if (status != 0) {
563         DEBUG("lcc_network_parse(): parse_encrypt_aes256() = %d\n", status);
564         return -1;
565       }
566       break;
567     }
568
569     default: {
570       DEBUG("lcc_network_parse(): ignoring unknown type %" PRIu16 "\n", type);
571       return EINVAL;
572     }
573     }
574   }
575
576   return 0;
577 }
578
579 int lcc_network_parse(void *data, size_t data_size,
580                       lcc_network_parse_options_t opts) {
581   if (opts.password_lookup) {
582     int status;
583     if ((status = init_gcrypt())) {
584       return status;
585     }
586   }
587
588   return network_parse(data, data_size, NONE, &opts);
589 }