2 * Copyright 2017 Florian Forster
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:
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
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
23 * Florian octo Forster <octo at collectd.org>
30 #if !defined(__GNUC__) || !__GNUC__
31 #define __attribute__(x) /**/
34 #include "collectd/lcc_features.h"
35 #include "collectd/server.h"
37 #include <arpa/inet.h>
47 #include <sys/socket.h>
48 #include <sys/types.h>
51 #define GCRYPT_NO_DEPRECATED
55 #define DEBUG(...) printf(__VA_ARGS__)
57 GCRY_THREAD_OPTION_PTHREAD_IMPL;
59 /* forward declaration because parse_sign_sha256()/parse_encrypt_aes256() and
60 * network_parse() need to call each other. */
61 static int network_parse(void *data, size_t data_size, lcc_security_level_t sl,
62 lcc_network_parse_options_t const *opts);
64 static _Bool is_multicast(struct addrinfo const *ai) {
65 if (ai->ai_family == AF_INET) {
66 struct sockaddr_in *addr = (struct sockaddr_in *)ai->ai_addr;
67 return IN_MULTICAST(ntohl(addr->sin_addr.s_addr));
68 } else if (ai->ai_family == AF_INET6) {
69 struct sockaddr_in6 *addr = (struct sockaddr_in6 *)ai->ai_addr;
70 return IN6_IS_ADDR_MULTICAST(&addr->sin6_addr);
75 static int server_multicast_join(lcc_listener_t *srv,
76 struct sockaddr_storage *group, int loop_back,
78 if (group->ss_family == AF_INET) {
79 struct sockaddr_in *sa = (struct sockaddr_in *)group;
81 int status = setsockopt(srv->conn, IPPROTO_IP, IP_MULTICAST_LOOP,
82 &loop_back, sizeof(loop_back));
84 DEBUG("setsockopt(IP_MULTICAST_LOOP, %d) = %d\n", loop_back, errno);
89 setsockopt(srv->conn, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
93 #if HAVE_STRUCT_IP_MREQN_IMR_IFINDEX
94 struct ip_mreqn mreq = {
95 .imr_address.s_addr = INADDR_ANY,
96 .imr_multiaddr.s_addr = sa->sin_addr.s_addr,
97 .imr_ifindex = if_nametoindex(srv->interface),
100 struct ip_mreq mreq = {
101 .imr_address.s_addr = INADDR_ANY, .imr_multiaddr.s_addr = sa->s_addr,
104 status = setsockopt(srv->conn, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq,
108 } else if (group->ss_family == AF_INET6) {
109 struct sockaddr_in6 *sa = (struct sockaddr_in6 *)group;
111 int status = setsockopt(srv->conn, IPPROTO_IPV6, IPV6_MULTICAST_LOOP,
112 &loop_back, sizeof(loop_back));
116 status = setsockopt(srv->conn, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &ttl,
121 struct ipv6_mreq mreq6 = {
122 .ipv6mr_interface = if_nametoindex(srv->interface),
124 memcpy(&mreq6.ipv6mr_multiaddr, &sa->sin6_addr, sizeof(struct in6_addr));
126 status = setsockopt(srv->conn, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, &mreq6,
137 static int server_bind_socket(lcc_listener_t *srv, struct addrinfo const *ai) {
138 /* allow multiple sockets to use the same PORT number */
139 if (setsockopt(srv->conn, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) ==
144 if (bind(srv->conn, ai->ai_addr, ai->ai_addrlen) == -1) {
148 if (is_multicast(ai)) {
149 int status = server_multicast_join(srv, (void *)ai->ai_addr, /* loop = */ 1,
158 static int server_open(lcc_listener_t *srv) {
159 struct addrinfo *res = NULL;
160 int status = getaddrinfo(srv->node ? srv->node : "::",
161 srv->service ? srv->service : LCC_DEFAULT_PORT,
163 .ai_flags = AI_ADDRCONFIG,
164 .ai_family = AF_UNSPEC,
165 .ai_socktype = SOCK_DGRAM,
171 for (struct addrinfo *ai = res; ai != NULL; ai = ai->ai_next) {
172 srv->conn = socket(ai->ai_family, ai->ai_socktype, 0);
176 status = server_bind_socket(srv, ai);
190 return status != 0 ? status : -1;
193 static int init_gcrypt() {
194 /* http://lists.gnupg.org/pipermail/gcrypt-devel/2003-August/000458.html
195 * Because you can't know in a library whether another library has
196 * already initialized the library */
197 if (gcry_control(GCRYCTL_ANY_INITIALIZATION_P))
200 /* http://www.gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html
201 * To ensure thread-safety, it's important to set GCRYCTL_SET_THREAD_CBS
202 * *before* initalizing Libgcrypt with gcry_check_version(), which itself must
203 * be called before any other gcry_* function. GCRYCTL_ANY_INITIALIZATION_P
204 * above doesn't count, as it doesn't implicitly initalize Libgcrypt.
206 * tl;dr: keep all these gry_* statements in this exact order please. */
207 #if GCRYPT_VERSION_NUMBER < 0x010600
208 if (gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread)) {
213 gcry_check_version(NULL);
215 if (gcry_control(GCRYCTL_INIT_SECMEM, 32768)) {
219 gcry_control(GCRYCTL_INITIALIZATION_FINISHED);
223 int lcc_listen_and_write(lcc_listener_t srv) {
224 _Bool close_socket = 0;
226 if (srv.password_lookup) {
227 int status = init_gcrypt();
233 int status = server_open(&srv);
239 if (srv.buffer_size == 0)
240 /* TODO(octo): this should be a define. */
241 srv.buffer_size = 1452;
245 char buffer[srv.buffer_size];
246 ssize_t len = recv(srv.conn, buffer, sizeof(buffer), /* flags = */ 0);
250 } else if (len == 0) {
254 /* TODO(octo): implement parse(). */
255 (void)lcc_network_parse(buffer, (size_t)len,
256 (lcc_network_parse_options_t){
257 .writer = srv.writer,
258 .password_lookup = srv.password_lookup,
259 .security_level = srv.security_level,
276 static int buffer_next(buffer_t *b, void *out, size_t n) {
280 memmove(out, b->data, n);
288 static int buffer_uint16(buffer_t *b, uint16_t *out) {
290 if (buffer_next(b, &tmp, sizeof(tmp)) != 0)
297 #define TYPE_HOST 0x0000
298 #define TYPE_TIME 0x0001
299 #define TYPE_TIME_HR 0x0008
300 #define TYPE_PLUGIN 0x0002
301 #define TYPE_PLUGIN_INSTANCE 0x0003
302 #define TYPE_TYPE 0x0004
303 #define TYPE_TYPE_INSTANCE 0x0005
304 #define TYPE_VALUES 0x0006
305 #define TYPE_INTERVAL 0x0007
306 #define TYPE_INTERVAL_HR 0x0009
307 #define TYPE_SIGN_SHA256 0x0200
308 #define TYPE_ENCR_AES256 0x0210
310 static int parse_int(void *payload, size_t payload_size, uint64_t *out) {
313 if (payload_size != sizeof(tmp))
316 memmove(&tmp, payload, sizeof(tmp));
321 static int parse_string(void *payload, size_t payload_size, char *out,
325 if ((payload_size < 1) || (in[payload_size - 1] != 0) ||
326 (payload_size > out_size))
329 strncpy(out, in, out_size);
333 static int parse_identifier(uint16_t type, void *payload, size_t payload_size,
334 lcc_value_list_t *state) {
335 char buf[LCC_NAME_LEN];
337 if (parse_string(payload, payload_size, buf, sizeof(buf)) != 0)
342 memmove(state->identifier.host, buf, LCC_NAME_LEN);
345 memmove(state->identifier.plugin, buf, LCC_NAME_LEN);
347 case TYPE_PLUGIN_INSTANCE:
348 memmove(state->identifier.plugin_instance, buf, LCC_NAME_LEN);
351 memmove(state->identifier.type, buf, LCC_NAME_LEN);
353 case TYPE_TYPE_INSTANCE:
354 memmove(state->identifier.type_instance, buf, LCC_NAME_LEN);
363 static int parse_time(uint16_t type, void *payload, size_t payload_size,
364 lcc_value_list_t *state) {
366 if (parse_int(payload, payload_size, &tmp))
369 double t = (double)tmp;
374 case TYPE_INTERVAL_HR:
375 state->interval = t / 1073741824.0;
381 state->time = t / 1073741824.0;
390 static double ntohd(double val) /* {{{ */
392 static int config = 0;
408 double d = 8.642135e130;
411 memcpy(b, &d, sizeof(b));
413 if ((b[0] == 0x2f) && (b[1] == 0x25) && (b[2] == 0xc0) && (b[3] == 0xc7) &&
414 (b[4] == 0x43) && (b[5] == 0x2b) && (b[6] == 0x1f) && (b[7] == 0x5b))
415 config = 1; /* need nothing */
416 else if ((b[7] == 0x2f) && (b[6] == 0x25) && (b[5] == 0xc0) &&
417 (b[4] == 0xc7) && (b[3] == 0x43) && (b[2] == 0x2b) &&
418 (b[1] == 0x1f) && (b[0] == 0x5b))
419 config = 2; /* endian flip */
420 else if ((b[4] == 0x2f) && (b[5] == 0x25) && (b[6] == 0xc0) &&
421 (b[7] == 0xc7) && (b[0] == 0x43) && (b[1] == 0x2b) &&
422 (b[2] == 0x1f) && (b[3] == 0x5b))
423 config = 3; /* int swap */
428 if (memcmp((char[]){0, 0, 0, 0, 0, 0, 0xf8, 0x7f}, in.byte, 8) == 0) {
430 } else if (config == 1) {
432 } else if (config == 2) {
434 out.byte[0] = in.byte[7];
435 out.byte[1] = in.byte[6];
436 out.byte[2] = in.byte[5];
437 out.byte[3] = in.byte[4];
438 out.byte[4] = in.byte[3];
439 out.byte[5] = in.byte[2];
440 out.byte[6] = in.byte[1];
441 out.byte[7] = in.byte[0];
442 return (out.floating);
443 } else if (config == 3) {
445 out.byte[0] = in.byte[4];
446 out.byte[1] = in.byte[5];
447 out.byte[2] = in.byte[6];
448 out.byte[3] = in.byte[7];
449 out.byte[4] = in.byte[0];
450 out.byte[5] = in.byte[1];
451 out.byte[6] = in.byte[2];
452 out.byte[7] = in.byte[3];
455 /* If in doubt, just copy the value back to the caller. */
458 } /* }}} double ntohd */
460 static int parse_values(void *payload, size_t payload_size,
461 lcc_value_list_t *state) {
462 buffer_t *b = &(buffer_t){
463 .data = payload, .len = payload_size,
467 if (buffer_uint16(b, &n))
470 if (((size_t)n * 9) != b->len)
473 state->values_len = (size_t)n;
474 state->values = calloc(sizeof(*state->values), state->values_len);
475 state->values_types = calloc(sizeof(*state->values_types), state->values_len);
476 if ((state->values == NULL) || (state->values_types == NULL)) {
478 free(state->values_types);
482 for (uint16_t i = 0; i < n; i++) {
484 if (buffer_next(b, &tmp, sizeof(tmp)))
486 state->values_types[i] = (int)tmp;
489 for (uint16_t i = 0; i < n; i++) {
491 if (buffer_next(b, &tmp, sizeof(tmp)))
494 if (state->values_types[i] == LCC_TYPE_GAUGE) {
499 state->values[i].gauge = ntohd(conv.d);
504 switch (state->values_types[i]) {
505 case LCC_TYPE_COUNTER:
506 state->values[i].counter = (counter_t)tmp;
508 case LCC_TYPE_DERIVE:
509 state->values[i].derive = (derive_t)tmp;
511 case LCC_TYPE_ABSOLUTE:
512 state->values[i].absolute = (absolute_t)tmp;
522 static int verify_sha256(void *payload, size_t payload_size,
523 char const *username, char const *password,
524 uint8_t hash_provided[32]) {
525 gcry_md_hd_t hd = NULL;
527 gcry_error_t err = gcry_md_open(&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
529 /* TODO(octo): use gcry_strerror(err) to create an error string. */
533 err = gcry_md_setkey(hd, password, strlen(password));
539 gcry_md_write(hd, username, strlen(username));
540 gcry_md_write(hd, payload, payload_size);
542 unsigned char *hash_calculated = gcry_md_read(hd, GCRY_MD_SHA256);
543 if (!hash_calculated) {
548 int ret = memcmp(hash_provided, hash_calculated, 32);
551 hash_calculated = NULL;
556 static int parse_sign_sha256(void *signature, size_t signature_len,
557 void *payload, size_t payload_size,
558 lcc_network_parse_options_t const *opts) {
559 if (opts->password_lookup == NULL) {
560 /* TODO(octo): print warning */
561 return network_parse(payload, payload_size, NONE, opts);
564 buffer_t *b = &(buffer_t){
565 .data = signature, .len = signature_len,
569 if (buffer_next(b, hash, sizeof(hash)))
572 char username[b->len + 1];
573 memset(username, 0, sizeof(username));
574 if (buffer_next(b, username, sizeof(username) - 1)) {
578 char const *password = opts->password_lookup(username);
580 return network_parse(payload, payload_size, NONE, opts);
582 int status = verify_sha256(payload, payload_size, username, password, hash);
586 return network_parse(payload, payload_size, SIGN, opts);
589 static int decrypt_aes256(buffer_t *b, void *iv, size_t iv_size,
590 char const *password) {
591 gcry_cipher_hd_t cipher = NULL;
593 if (gcry_cipher_open(&cipher, GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB,
597 uint8_t pwhash[32] = {0};
598 gcry_md_hash_buffer(GCRY_MD_SHA256, pwhash, password, strlen(password));
600 fprintf(stderr, "sizeof(iv) = %zu\n", sizeof(iv));
601 if (gcry_cipher_setkey(cipher, pwhash, sizeof(pwhash)) ||
602 gcry_cipher_setiv(cipher, iv, iv_size) ||
603 gcry_cipher_decrypt(cipher, b->data, b->len, /* in = */ NULL,
604 /* in_size = */ 0)) {
605 gcry_cipher_close(cipher);
609 gcry_cipher_close(cipher);
613 static int parse_encrypt_aes256(void *data, size_t data_size,
614 lcc_network_parse_options_t const *opts) {
615 if (opts->password_lookup == NULL) {
616 /* TODO(octo): print warning */
620 buffer_t *b = &(buffer_t){
621 .data = data, .len = data_size,
624 uint16_t username_len;
625 if (buffer_uint16(b, &username_len))
627 if ((size_t)username_len > data_size)
629 char username[((size_t)username_len) + 1];
630 memset(username, 0, sizeof(username));
631 if (buffer_next(b, username, sizeof(username)))
634 char const *password = opts->password_lookup(username);
639 if (buffer_next(b, iv, sizeof(iv)))
642 int status = decrypt_aes256(b, iv, sizeof(iv), password);
646 uint8_t hash_provided[20];
647 if (buffer_next(b, hash_provided, sizeof(hash_provided))) {
651 uint8_t hash_calculated[20];
652 gcry_md_hash_buffer(GCRY_MD_SHA1, hash_calculated, b->data, b->len);
654 if (memcmp(hash_provided, hash_calculated, sizeof(hash_provided)) != 0) {
658 return network_parse(b->data, b->len, ENCRYPT, opts);
661 static int network_parse(void *data, size_t data_size, lcc_security_level_t sl,
662 lcc_network_parse_options_t const *opts) {
663 buffer_t *b = &(buffer_t){
664 .data = data, .len = data_size,
667 lcc_value_list_t state = {0};
670 uint16_t type = 0, sz = 0;
671 if (buffer_uint16(b, &type) || buffer_uint16(b, &sz)) {
672 DEBUG("lcc_network_parse(): reading type and/or length failed.\n");
676 if ((sz < 5) || (((size_t)sz - 4) > b->len)) {
677 DEBUG("lcc_network_parse(): invalid 'sz' field: sz = %" PRIu16
685 if (buffer_next(b, payload, sizeof(payload)))
691 case TYPE_PLUGIN_INSTANCE:
693 case TYPE_TYPE_INSTANCE: {
694 if (parse_identifier(type, payload, sizeof(payload), &state)) {
695 DEBUG("lcc_network_parse(): parse_identifier failed.\n");
702 case TYPE_INTERVAL_HR:
705 if (parse_time(type, payload, sizeof(payload), &state)) {
706 DEBUG("lcc_network_parse(): parse_time failed.\n");
713 lcc_value_list_t vl = state;
714 if (parse_values(payload, sizeof(payload), &vl)) {
715 DEBUG("lcc_network_parse(): parse_values failed.\n");
719 /* TODO(octo): skip if current_security_level < required_security_level */
721 int status = opts->writer(&vl);
724 free(vl.values_types);
731 case TYPE_SIGN_SHA256: {
733 parse_sign_sha256(payload, sizeof(payload), b->data, b->len, opts);
735 DEBUG("lcc_network_parse(): parse_sign_sha256() = %d\n", status);
738 /* parse_sign_sha256, if successful, consumes all remaining data. */
744 case TYPE_ENCR_AES256: {
745 int status = parse_encrypt_aes256(payload, sizeof(payload), opts);
747 DEBUG("lcc_network_parse(): parse_encrypt_aes256() = %d\n", status);
754 DEBUG("lcc_network_parse(): ignoring unknown type %" PRIu16 "\n", type);
763 int lcc_network_parse(void *data, size_t data_size,
764 lcc_network_parse_options_t opts) {
765 if (opts.password_lookup) {
767 if ((status = init_gcrypt())) {
772 return network_parse(data, data_size, NONE, &opts);