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