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