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