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