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