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