4c610bb0b7efe487dd5652eba6022479d058ffcb
[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 "collectd/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 - 1);
162   out[out_size - 1] = '\0';
163   return 0;
164 }
165
166 static int parse_identifier(uint16_t type, void *payload, size_t payload_size,
167                             lcc_value_list_t *state) {
168   char buf[LCC_NAME_LEN];
169
170   if (parse_string(payload, payload_size, buf, sizeof(buf)) != 0)
171     return EINVAL;
172
173   switch (type) {
174   case TYPE_HOST:
175     memmove(state->identifier.host, buf, LCC_NAME_LEN);
176     break;
177   case TYPE_PLUGIN:
178     memmove(state->identifier.plugin, buf, LCC_NAME_LEN);
179     break;
180   case TYPE_PLUGIN_INSTANCE:
181     memmove(state->identifier.plugin_instance, buf, LCC_NAME_LEN);
182     break;
183   case TYPE_TYPE:
184     memmove(state->identifier.type, buf, LCC_NAME_LEN);
185     break;
186   case TYPE_TYPE_INSTANCE:
187     memmove(state->identifier.type_instance, buf, LCC_NAME_LEN);
188     break;
189   default:
190     return EINVAL;
191   }
192
193   return 0;
194 }
195
196 static int parse_time(uint16_t type, void *payload, size_t payload_size,
197                       lcc_value_list_t *state) {
198   uint64_t tmp = 0;
199   if (parse_int(payload, payload_size, &tmp))
200     return EINVAL;
201
202   double t = (double)tmp;
203   switch (type) {
204   case TYPE_INTERVAL:
205     state->interval = t;
206     break;
207   case TYPE_INTERVAL_HR:
208     state->interval = t / 1073741824.0;
209     break;
210   case TYPE_TIME:
211     state->time = t;
212     break;
213   case TYPE_TIME_HR:
214     state->time = t / 1073741824.0;
215     break;
216   default:
217     return EINVAL;
218   }
219
220   return 0;
221 }
222
223 static double ntohd(double val) /* {{{ */
224 {
225   static int config;
226
227   union {
228     uint8_t byte[8];
229     double floating;
230   } in = {
231       .floating = val,
232   };
233   union {
234     uint8_t byte[8];
235     double floating;
236   } out = {
237       .byte = {0},
238   };
239
240   if (config == 0) {
241     double d = 8.642135e130;
242     uint8_t b[8];
243
244     memcpy(b, &d, sizeof(b));
245
246     if ((b[0] == 0x2f) && (b[1] == 0x25) && (b[2] == 0xc0) && (b[3] == 0xc7) &&
247         (b[4] == 0x43) && (b[5] == 0x2b) && (b[6] == 0x1f) && (b[7] == 0x5b))
248       config = 1; /* need nothing */
249     else if ((b[7] == 0x2f) && (b[6] == 0x25) && (b[5] == 0xc0) &&
250              (b[4] == 0xc7) && (b[3] == 0x43) && (b[2] == 0x2b) &&
251              (b[1] == 0x1f) && (b[0] == 0x5b))
252       config = 2; /* endian flip */
253     else if ((b[4] == 0x2f) && (b[5] == 0x25) && (b[6] == 0xc0) &&
254              (b[7] == 0xc7) && (b[0] == 0x43) && (b[1] == 0x2b) &&
255              (b[2] == 0x1f) && (b[3] == 0x5b))
256       config = 3; /* int swap */
257     else
258       config = 4;
259   }
260
261   if (memcmp((char[]){0, 0, 0, 0, 0, 0, 0xf8, 0x7f}, in.byte, 8) == 0) {
262     return NAN;
263   } else if (config == 1) {
264     return val;
265   } else if (config == 2) {
266     in.floating = val;
267     out.byte[0] = in.byte[7];
268     out.byte[1] = in.byte[6];
269     out.byte[2] = in.byte[5];
270     out.byte[3] = in.byte[4];
271     out.byte[4] = in.byte[3];
272     out.byte[5] = in.byte[2];
273     out.byte[6] = in.byte[1];
274     out.byte[7] = in.byte[0];
275     return (out.floating);
276   } else if (config == 3) {
277     in.floating = val;
278     out.byte[0] = in.byte[4];
279     out.byte[1] = in.byte[5];
280     out.byte[2] = in.byte[6];
281     out.byte[3] = in.byte[7];
282     out.byte[4] = in.byte[0];
283     out.byte[5] = in.byte[1];
284     out.byte[6] = in.byte[2];
285     out.byte[7] = in.byte[3];
286     return out.floating;
287   } else {
288     /* If in doubt, just copy the value back to the caller. */
289     return val;
290   }
291 } /* }}} double ntohd */
292
293 static int parse_values(void *payload, size_t payload_size,
294                         lcc_value_list_t *state) {
295   buffer_t *b = &(buffer_t){
296       .data = payload, .len = payload_size,
297   };
298
299   uint16_t n;
300   if (buffer_uint16(b, &n))
301     return EINVAL;
302
303   if (((size_t)n * 9) != b->len)
304     return EINVAL;
305
306   state->values_len = (size_t)n;
307   state->values = calloc(state->values_len, sizeof(*state->values));
308   state->values_types = calloc(state->values_len, sizeof(*state->values_types));
309   if ((state->values == NULL) || (state->values_types == NULL)) {
310     return ENOMEM;
311   }
312
313   for (uint16_t i = 0; i < n; i++) {
314     uint8_t tmp;
315     if (buffer_next(b, &tmp, sizeof(tmp)))
316       return EINVAL;
317     state->values_types[i] = (int)tmp;
318   }
319
320   for (uint16_t i = 0; i < n; i++) {
321     uint64_t tmp;
322     if (buffer_next(b, &tmp, sizeof(tmp)))
323       return EINVAL;
324
325     if (state->values_types[i] == LCC_TYPE_GAUGE) {
326       union {
327         uint64_t i;
328         double d;
329       } conv = {.i = tmp};
330       state->values[i].gauge = ntohd(conv.d);
331       continue;
332     }
333
334     tmp = be64toh(tmp);
335     switch (state->values_types[i]) {
336     case LCC_TYPE_COUNTER:
337       state->values[i].counter = (counter_t)tmp;
338       break;
339     case LCC_TYPE_DERIVE:
340       state->values[i].derive = (derive_t)tmp;
341       break;
342     case LCC_TYPE_ABSOLUTE:
343       state->values[i].absolute = (absolute_t)tmp;
344       break;
345     default:
346       return EINVAL;
347     }
348   }
349
350   return 0;
351 }
352
353 #if HAVE_GCRYPT_H
354 static int verify_sha256(void *payload, size_t payload_size,
355                          char const *username, char const *password,
356                          uint8_t hash_provided[32]) {
357   gcry_md_hd_t hd = NULL;
358
359   gcry_error_t err = gcry_md_open(&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
360   if (err != 0) {
361     return (int)err;
362   }
363
364   err = gcry_md_setkey(hd, password, strlen(password));
365   if (err != 0) {
366     gcry_md_close(hd);
367     return (int)err;
368   }
369
370   gcry_md_write(hd, username, strlen(username));
371   gcry_md_write(hd, payload, payload_size);
372
373   unsigned char *hash_calculated = gcry_md_read(hd, GCRY_MD_SHA256);
374   if (!hash_calculated) {
375     gcry_md_close(hd);
376     return -1;
377   }
378
379   int ret = memcmp(hash_provided, hash_calculated, 32);
380
381   gcry_md_close(hd);
382   hash_calculated = NULL;
383
384   return !!ret;
385 }
386 #else /* !HAVE_GCRYPT_H */
387 static int verify_sha256(void *payload, size_t payload_size,
388                          char const *username, char const *password,
389                          uint8_t hash_provided[32]) {
390   return ENOTSUP;
391 }
392 #endif
393
394 static int parse_sign_sha256(void *signature, size_t signature_len,
395                              void *payload, size_t payload_size,
396                              lcc_network_parse_options_t const *opts) {
397   if (opts->password_lookup == NULL) {
398     /* The sender signed the packet but we can't verify it. Handle it as if it
399      * were unsigned, i.e. security level NONE. */
400     return network_parse(payload, payload_size, NONE, opts);
401   }
402
403   buffer_t *b = &(buffer_t){
404       .data = signature, .len = signature_len,
405   };
406
407   uint8_t hash[32];
408   if (buffer_next(b, hash, sizeof(hash)))
409     return EINVAL;
410
411   char username[b->len + 1];
412   memset(username, 0, sizeof(username));
413   if (buffer_next(b, username, sizeof(username) - 1)) {
414     return EINVAL;
415   }
416
417   char const *password = opts->password_lookup(username);
418   if (!password)
419     return network_parse(payload, payload_size, NONE, opts);
420
421   int status = verify_sha256(payload, payload_size, username, password, hash);
422   if (status != 0)
423     return status;
424
425   return network_parse(payload, payload_size, SIGN, opts);
426 }
427
428 #if HAVE_GCRYPT_H
429 static int decrypt_aes256(buffer_t *b, void *iv, size_t iv_size,
430                           char const *password) {
431   gcry_cipher_hd_t cipher = NULL;
432
433   if (gcry_cipher_open(&cipher, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB,
434                        /* flags = */ 0))
435     return -1;
436
437   uint8_t pwhash[32] = {0};
438   gcry_md_hash_buffer(GCRY_MD_SHA256, pwhash, password, strlen(password));
439
440   fprintf(stderr, "sizeof(iv) = %" PRIsz "\n", sizeof(iv));
441   if (gcry_cipher_setkey(cipher, pwhash, sizeof(pwhash)) ||
442       gcry_cipher_setiv(cipher, iv, iv_size) ||
443       gcry_cipher_decrypt(cipher, b->data, b->len, /* in = */ NULL,
444                           /* in_size = */ 0)) {
445     gcry_cipher_close(cipher);
446     return -1;
447   }
448
449   gcry_cipher_close(cipher);
450   return 0;
451 }
452
453 static int parse_encrypt_aes256(void *data, size_t data_size,
454                                 lcc_network_parse_options_t const *opts) {
455   if (opts->password_lookup == NULL) {
456     /* Without a password source it's (hopefully) impossible to decrypt the
457      * network packet. */
458     return ENOENT;
459   }
460
461   buffer_t *b = &(buffer_t){
462       .data = data, .len = data_size,
463   };
464
465   uint16_t username_len;
466   if (buffer_uint16(b, &username_len))
467     return EINVAL;
468   if ((size_t)username_len > data_size)
469     return ENOMEM;
470   char username[((size_t)username_len) + 1];
471   memset(username, 0, sizeof(username));
472   if (buffer_next(b, username, (size_t)username_len))
473     return EINVAL;
474
475   char const *password = opts->password_lookup(username);
476   if (!password)
477     return ENOENT;
478
479   uint8_t iv[16];
480   if (buffer_next(b, iv, sizeof(iv)))
481     return EINVAL;
482
483   int status = decrypt_aes256(b, iv, sizeof(iv), password);
484   if (status != 0)
485     return status;
486
487   uint8_t hash_provided[20];
488   if (buffer_next(b, hash_provided, sizeof(hash_provided))) {
489     return -1;
490   }
491
492   uint8_t hash_calculated[20];
493   gcry_md_hash_buffer(GCRY_MD_SHA1, hash_calculated, b->data, b->len);
494
495   if (memcmp(hash_provided, hash_calculated, sizeof(hash_provided)) != 0) {
496     return -1;
497   }
498
499   return network_parse(b->data, b->len, ENCRYPT, opts);
500 }
501 #else /* !HAVE_GCRYPT_H */
502 static int parse_encrypt_aes256(void *data, size_t data_size,
503                                 lcc_network_parse_options_t const *opts) {
504   return ENOTSUP;
505 }
506 #endif
507
508 static int network_parse(void *data, size_t data_size, lcc_security_level_t sl,
509                          lcc_network_parse_options_t const *opts) {
510   buffer_t *b = &(buffer_t){
511       .data = data, .len = data_size,
512   };
513
514   lcc_value_list_t state = {0};
515
516   while (b->len > 0) {
517     uint16_t type = 0, sz = 0;
518     if (buffer_uint16(b, &type) || buffer_uint16(b, &sz)) {
519       DEBUG("lcc_network_parse(): reading type and/or length failed.\n");
520       return EINVAL;
521     }
522
523     if ((sz < 5) || (((size_t)sz - 4) > b->len)) {
524       DEBUG("lcc_network_parse(): invalid 'sz' field: sz = %" PRIu16
525             ", b->len = %" PRIsz "\n",
526             sz, b->len);
527       return EINVAL;
528     }
529     sz -= 4;
530
531     uint8_t payload[sz];
532     if (buffer_next(b, payload, sizeof(payload)))
533       return EINVAL;
534
535     switch (type) {
536     case TYPE_HOST:
537     case TYPE_PLUGIN:
538     case TYPE_PLUGIN_INSTANCE:
539     case TYPE_TYPE:
540     case TYPE_TYPE_INSTANCE: {
541       if (parse_identifier(type, payload, sizeof(payload), &state)) {
542         DEBUG("lcc_network_parse(): parse_identifier failed.\n");
543         return EINVAL;
544       }
545       break;
546     }
547
548     case TYPE_INTERVAL:
549     case TYPE_INTERVAL_HR:
550     case TYPE_TIME:
551     case TYPE_TIME_HR: {
552       if (parse_time(type, payload, sizeof(payload), &state)) {
553         DEBUG("lcc_network_parse(): parse_time failed.\n");
554         return EINVAL;
555       }
556       break;
557     }
558
559     case TYPE_VALUES: {
560       lcc_value_list_t vl = state;
561       if (parse_values(payload, sizeof(payload), &vl)) {
562         free(vl.values);
563         free(vl.values_types);
564         DEBUG("lcc_network_parse(): parse_values failed.\n");
565         return EINVAL;
566       }
567
568       int status = 0;
569
570       /* Write metrics if they have the required security level. */
571       if (sl >= opts->security_level)
572         status = opts->writer(&vl);
573
574       free(vl.values);
575       free(vl.values_types);
576
577       if (status != 0)
578         return status;
579       break;
580     }
581
582     case TYPE_SIGN_SHA256: {
583       int status =
584           parse_sign_sha256(payload, sizeof(payload), b->data, b->len, opts);
585       if (status != 0) {
586         DEBUG("lcc_network_parse(): parse_sign_sha256() = %d\n", status);
587         return -1;
588       }
589       /* parse_sign_sha256, if successful, consumes all remaining data. */
590       b->data = NULL;
591       b->len = 0;
592       break;
593     }
594
595     case TYPE_ENCR_AES256: {
596       int status = parse_encrypt_aes256(payload, sizeof(payload), opts);
597       if (status != 0) {
598         DEBUG("lcc_network_parse(): parse_encrypt_aes256() = %d\n", status);
599         return -1;
600       }
601       break;
602     }
603
604     default: {
605       DEBUG("lcc_network_parse(): ignoring unknown type %" PRIu16 "\n", type);
606       return EINVAL;
607     }
608     }
609   }
610
611   return 0;
612 }
613
614 int lcc_network_parse(void *data, size_t data_size,
615                       lcc_network_parse_options_t opts) {
616   if (opts.password_lookup) {
617 #if HAVE_GCRYPT_H
618     int status;
619     if ((status = init_gcrypt())) {
620       return status;
621     }
622 #else
623     return ENOTSUP;
624 #endif
625   }
626
627   return network_parse(data, data_size, NONE, &opts);
628 }