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