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