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