Merge branch 'collectd-4.6'
[collectd.git] / src / network.c
index ca63e96..7023eaa 100644 (file)
 /*
  * Maximum size required for encryption / signing:
  * Type/length:       4
+ * IV                16
  * Hash/orig length: 22
  * Padding (up to):  15
  * --------------------
- *                   41
+ *                   57
  */
-#define BUFF_SIG_SIZE 41
+#define BUFF_SIG_SIZE 57
 
 /*
  * Private data types
@@ -89,6 +90,7 @@ typedef struct sockent
 # define SECURITY_LEVEL_ENCRYPT 2
        int security_level;
        char *shared_secret;
+       unsigned char shared_secret_hash[32];
        gcry_cipher_hd_t cypher;
 #endif /* HAVE_GCRYPT_H */
 
@@ -171,10 +173,11 @@ typedef struct part_values_s part_values_t;
  * ! Hash (Bits 224 - 255)                                         !
  * +---------------------------------------------------------------+
  */
+#define PART_SIGNATURE_SHA256_SIZE 36
 struct part_signature_sha256_s
 {
   part_header_t head;
-  char hash[32];
+  unsigned char hash[32];
 };
 typedef struct part_signature_sha256_s part_signature_sha256_t;
 
@@ -190,12 +193,16 @@ typedef struct part_signature_sha256_s part_signature_sha256_t;
  * ! Hash (Bits 128 - 159)                                         !
  * +---------------------------------------------------------------+
  */
+/* Size without padding */
+#define PART_ENCRYPTION_AES256_SIZE 42
+#define PART_ENCRYPTION_AES256_UNENCR_SIZE 20
 struct part_encryption_aes256_s
 {
   part_header_t head;
+  unsigned char iv[16];
   uint16_t orig_length;
-  char padding[15];
-  char hash[20];
+  unsigned char hash[20];
+  unsigned char padding[15];
 };
 typedef struct part_encryption_aes256_s part_encryption_aes256_t;
 
@@ -362,6 +369,55 @@ static int cache_check (const value_list_t *vl)
        return (retval);
 } /* int cache_check */
 
+#if HAVE_GCRYPT_H
+static gcry_cipher_hd_t network_get_aes256_cypher (sockent_t *se, /* {{{ */
+    const void *iv, size_t iv_size)
+{
+  gcry_error_t err;
+
+  if (se->cypher == NULL)
+  {
+    err = gcry_cipher_open (&se->cypher,
+        GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, /* flags = */ 0);
+    if (err != 0)
+    {
+      ERROR ("network plugin: gcry_cipher_open returned: %s",
+          gcry_strerror (err));
+      se->cypher = NULL;
+      return (NULL);
+    }
+  }
+  else
+  {
+    gcry_cipher_reset (se->cypher);
+  }
+  assert (se->cypher != NULL);
+
+  err = gcry_cipher_setkey (se->cypher,
+      se->shared_secret_hash, sizeof (se->shared_secret_hash));
+  if (err != 0)
+  {
+    ERROR ("network plugin: gcry_cipher_setkey returned: %s",
+        gcry_strerror (err));
+    gcry_cipher_close (se->cypher);
+    se->cypher = NULL;
+    return (NULL);
+  }
+
+  err = gcry_cipher_setiv (se->cypher, iv, iv_size);
+  if (err != 0)
+  {
+    ERROR ("network plugin: gcry_cipher_setkey returned: %s",
+        gcry_strerror (err));
+    gcry_cipher_close (se->cypher);
+    se->cypher = NULL;
+    return (NULL);
+  }
+
+  return (se->cypher);
+} /* }}} int network_get_aes256_cypher */
+#endif /* HAVE_GCRYPT_H */
+
 static int write_part_values (char **ret_buffer, int *ret_buffer_len,
                const data_set_t *ds, const value_list_t *vl)
 {
@@ -518,11 +574,11 @@ static int write_part_string (char **ret_buffer, int *ret_buffer_len,
        return (0);
 } /* int write_part_string */
 
-static int parse_part_values (void **ret_buffer, int *ret_buffer_len,
+static int parse_part_values (void **ret_buffer, size_t *ret_buffer_len,
                value_t **ret_values, int *ret_num_values)
 {
        char *buffer = *ret_buffer;
-       int   buffer_len = *ret_buffer_len;
+       size_t buffer_len = *ret_buffer_len;
 
        uint16_t tmp16;
        size_t exp_size;
@@ -535,10 +591,10 @@ static int parse_part_values (void **ret_buffer, int *ret_buffer_len,
        uint8_t *pkg_types;
        value_t *pkg_values;
 
-       if (buffer_len < (15))
+       if (buffer_len < 15)
        {
-               DEBUG ("network plugin: packet is too short: buffer_len = %i",
-                               buffer_len);
+               NOTICE ("network plugin: packet is too short: "
+                               "buffer_len = %zu", buffer_len);
                return (-1);
        }
 
@@ -558,13 +614,13 @@ static int parse_part_values (void **ret_buffer, int *ret_buffer_len,
 
        exp_size = 3 * sizeof (uint16_t)
                + pkg_numval * (sizeof (uint8_t) + sizeof (value_t));
-       if ((buffer_len < 0) || ((size_t) buffer_len < exp_size))
+       if ((buffer_len < 0) || (buffer_len < exp_size))
        {
                WARNING ("network plugin: parse_part_values: "
                                "Packet too short: "
-                               "Chunk of size %u expected, "
-                               "but buffer has only %i bytes left.",
-                               (unsigned int) exp_size, buffer_len);
+                               "Chunk of size %zu expected, "
+                               "but buffer has only %zu bytes left.",
+                               exp_size, buffer_len);
                return (-1);
        }
 
@@ -609,11 +665,11 @@ static int parse_part_values (void **ret_buffer, int *ret_buffer_len,
        return (0);
 } /* int parse_part_values */
 
-static int parse_part_number (void **ret_buffer, int *ret_buffer_len,
+static int parse_part_number (void **ret_buffer, size_t *ret_buffer_len,
                uint64_t *value)
 {
        char *buffer = *ret_buffer;
-       int buffer_len = *ret_buffer_len;
+       size_t buffer_len = *ret_buffer_len;
 
        uint16_t tmp16;
        uint64_t tmp64;
@@ -626,9 +682,9 @@ static int parse_part_number (void **ret_buffer, int *ret_buffer_len,
        {
                WARNING ("network plugin: parse_part_number: "
                                "Packet too short: "
-                               "Chunk of size %u expected, "
-                               "but buffer has only %i bytes left.",
-                               (unsigned int) exp_size, buffer_len);
+                               "Chunk of size %zu expected, "
+                               "but buffer has only %zu bytes left.",
+                               exp_size, buffer_len);
                return (-1);
        }
 
@@ -650,11 +706,11 @@ static int parse_part_number (void **ret_buffer, int *ret_buffer_len,
        return (0);
 } /* int parse_part_number */
 
-static int parse_part_string (void **ret_buffer, int *ret_buffer_len,
+static int parse_part_string (void **ret_buffer, size_t *ret_buffer_len,
                char *output, int output_len)
 {
        char *buffer = *ret_buffer;
-       int   buffer_len = *ret_buffer_len;
+       size_t buffer_len = *ret_buffer_len;
 
        uint16_t tmp16;
        size_t header_size = 2 * sizeof (uint16_t);
@@ -662,13 +718,13 @@ static int parse_part_string (void **ret_buffer, int *ret_buffer_len,
        uint16_t pkg_length;
        uint16_t pkg_type;
 
-       if ((buffer_len < 0) || ((size_t) buffer_len < header_size))
+       if ((buffer_len < 0) || (buffer_len < header_size))
        {
                WARNING ("network plugin: parse_part_string: "
                                "Packet too short: "
-                               "Chunk of at least size %u expected, "
-                               "but buffer has only %i bytes left.",
-                               (unsigned int) header_size, buffer_len);
+                               "Chunk of at least size %zu expected, "
+                               "but buffer has only %zu bytes left.",
+                               header_size, buffer_len);
                return (-1);
        }
 
@@ -685,8 +741,8 @@ static int parse_part_string (void **ret_buffer, int *ret_buffer_len,
        {
                WARNING ("network plugin: parse_part_string: "
                                "Packet too big: "
-                               "Chunk of size %hu received, "
-                               "but buffer has only %i bytes left.",
+                               "Chunk of size %"PRIu16" received, "
+                               "but buffer has only %zu bytes left.",
                                pkg_length, buffer_len);
                return (-1);
        }
@@ -733,20 +789,37 @@ static int parse_part_string (void **ret_buffer, int *ret_buffer_len,
        return (0);
 } /* int parse_part_string */
 
+/* Forward declaration: parse_part_sign_sha256 and parse_part_encr_aes256 call
+ * parse_packet and vice versa. */
+#define PP_SIGNED    0x01
+#define PP_ENCRYPTED 0x02
+static int parse_packet (sockent_t *se,
+               void *buffer, size_t buffer_size, int flags);
+
+#define BUFFER_READ(p,s) do { \
+  memcpy ((p), buffer + buffer_offset, (s)); \
+  buffer_offset += (s); \
+} while (0)
+
 #if HAVE_GCRYPT_H
 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
-    void **ret_buffer, int *ret_buffer_len)
+    void **ret_buffer, size_t *ret_buffer_len, int flags)
 {
-  char *buffer = *ret_buffer;
-  size_t buffer_len = (size_t) *ret_buffer_len;
+  char *buffer;
+  size_t buffer_len;
+  size_t buffer_offset;
 
-  part_signature_sha256_t ps_received;
-  char hash[sizeof (ps_received.hash)];
+  part_signature_sha256_t pss;
+  char hash[sizeof (pss.hash)];
 
   gcry_md_hd_t hd;
   gcry_error_t err;
   unsigned char *hash_ptr;
 
+  buffer = *ret_buffer;
+  buffer_len = *ret_buffer_len;
+  buffer_offset = 0;
+
   if (se->shared_secret == NULL)
   {
     NOTICE ("network plugin: Received signed network packet but can't verify "
@@ -754,9 +827,21 @@ static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
     return (0);
   }
 
-  if (buffer_len < sizeof (ps_received))
+  if (buffer_len < PART_SIGNATURE_SHA256_SIZE)
     return (-ENOMEM);
 
+  BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
+  BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
+  BUFFER_READ (pss.hash, sizeof (pss.hash));
+
+  assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
+
+  if (ntohs (pss.head.length) != PART_SIGNATURE_SHA256_SIZE)
+  {
+    ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
+    return (-1);
+  }
+
   hd = NULL;
   err = gcry_md_open (&hd, GCRY_MD_SHA256, GCRY_MD_FLAG_HMAC);
   if (err != 0)
@@ -776,13 +861,7 @@ static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
     return (-1);
   }
 
-  memcpy (&ps_received, buffer, sizeof (ps_received));
-  /* TODO: Check ps_received.head.length! */
-
-  buffer += sizeof (ps_received);
-  buffer_len -= sizeof (ps_received);
-
-  gcry_md_write (hd, buffer, buffer_len);
+  gcry_md_write (hd, buffer + buffer_offset, buffer_len - buffer_offset);
   hash_ptr = gcry_md_read (hd, GCRY_MD_SHA256);
   if (hash_ptr == NULL)
   {
@@ -795,41 +874,88 @@ static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
   gcry_md_close (hd);
   hd = NULL;
 
-  *ret_buffer += sizeof (ps_received);
-  *ret_buffer_len -= sizeof (ps_received);
+  if (memcmp (pss.hash, hash, sizeof (pss.hash)) != 0)
+  {
+    WARNING ("network plugin: Verifying HMAC-SHA-256 signature failed: "
+        "Hash mismatch.");
+  }
+  else
+  {
+    parse_packet (se, buffer + buffer_offset, buffer_len - buffer_offset,
+        flags | PP_SIGNED);
+  }
 
-  if (memcmp (ps_received.hash, hash,
-        sizeof (ps_received.hash)) == 0)
-    return (0);
-  else /* hashes do not match. */
-    return (1);
+  *ret_buffer = buffer + buffer_len;
+  *ret_buffer_len = 0;
+
+  return (0);
 } /* }}} int parse_part_sign_sha256 */
 /* #endif HAVE_GCRYPT_H */
 
 #else /* if !HAVE_GCRYPT_H */
 static int parse_part_sign_sha256 (sockent_t *se, /* {{{ */
-    void **ret_buffer, int *ret_buffer_len)
+    void **ret_buffer, size_t *ret_buffer_size, int flags)
 {
-  INFO ("network plugin: Received signed packet, but the network "
-      "plugin was not linked with libgcrypt, so I cannot "
-      "verify the signature. The packet will be accepted.");
+  static int warning_has_been_printed = 0;
+
+  char *buffer;
+  size_t buffer_size;
+  size_t buffer_offset;
+
+  part_signature_sha256_t pss;
+
+  buffer = *ret_buffer;
+  buffer_size = *ret_buffer_size;
+  buffer_offset = 0;
+
+  if (buffer_size < PART_SIGNATURE_SHA256_SIZE)
+    return (-ENOMEM);
+
+  BUFFER_READ (&pss.head.type, sizeof (pss.head.type));
+  BUFFER_READ (&pss.head.length, sizeof (pss.head.length));
+  BUFFER_READ (pss.hash, sizeof (pss.hash));
+
+  assert (buffer_offset == PART_SIGNATURE_SHA256_SIZE);
+
+  if (ntohs (pss.head.length) != PART_SIGNATURE_SHA256_SIZE)
+  {
+    ERROR ("network plugin: HMAC-SHA-256 with invalid length received.");
+    return (-1);
+  }
+
+  if (warning_has_been_printed == 0)
+  {
+    WARNING ("network plugin: Received signed packet, but the network "
+        "plugin was not linked with libgcrypt, so I cannot "
+        "verify the signature. The packet will be accepted.");
+    warning_has_been_printed = 1;
+  }
+
+  parse_packet (se, buffer + buffer_offset, buffer_size - buffer_offset,
+      flags);
+
+  *ret_buffer = buffer + buffer_size;
+  *ret_buffer_size = 0;
+
   return (0);
 } /* }}} int parse_part_sign_sha256 */
 #endif /* !HAVE_GCRYPT_H */
 
 #if HAVE_GCRYPT_H
 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
-               void **ret_buffer, int *ret_buffer_len)
+               void **ret_buffer, size_t *ret_buffer_len,
+               int flags)
 {
   char  *buffer = *ret_buffer;
-  size_t buffer_len = (size_t) *ret_buffer_len;
+  size_t buffer_len = *ret_buffer_len;
   size_t orig_buffer_len;
   size_t part_size;
-  size_t buffer_offset = 0;
+  size_t buffer_offset;
   size_t padding_size;
   part_encryption_aes256_t pea;
-  size_t pea_size;
-  char hash[sizeof (pea.hash)];
+  unsigned char hash[sizeof (pea.hash)];
+
+  gcry_cipher_hd_t cypher;
   gcry_error_t err;
 
   /* Make sure at least the header if available. */
@@ -840,21 +966,13 @@ static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
     return (-1);
   }
 
-  if (se->cypher == NULL)
-  {
-    NOTICE ("network plugin: Unable to decrypt packet, because no cypher "
-        "instance is present.");
-    return (-1);
-  }
+  buffer_offset = 0;
 
-  /* Size of `pea' without padding. */
-  pea_size = sizeof (pea.head.type) + sizeof (pea.head.length)
-    + sizeof (pea.orig_length) + sizeof (pea.hash);
+  /* Copy the unencrypted information into `pea'. */
+  BUFFER_READ (&pea.head.type, sizeof (pea.head.type));
+  BUFFER_READ (&pea.head.length, sizeof (pea.head.length));
+  BUFFER_READ (pea.iv, sizeof (pea.iv));
 
-  /* Copy the header information to `pea' */
-  memcpy (&pea.head, buffer, sizeof (pea.head));
-  buffer_offset += sizeof (pea.head);
-  
   /* Check the `part size'. */
   part_size = ntohs (pea.head.length);
   if (part_size > buffer_len)
@@ -864,11 +982,15 @@ static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
     return (-1);
   }
 
+  cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv));
+  if (cypher == NULL)
+    return (-1);
+
   /* Decrypt the packet in-place */
-  err = gcry_cipher_decrypt (se->cypher,
-      buffer + sizeof (pea.head), part_size - sizeof (pea.head),
+  err = gcry_cipher_decrypt (cypher,
+      buffer    + PART_ENCRYPTION_AES256_UNENCR_SIZE,
+      part_size - PART_ENCRYPTION_AES256_UNENCR_SIZE,
       /* in = */ NULL, /* in len = */ 0);
-  gcry_cipher_reset (se->cypher);
   if (err != 0)
   {
     ERROR ("network plugin: gcry_cipher_decrypt returned: %s",
@@ -877,27 +999,28 @@ static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
   }
 
   /* Figure out the length of the payload and the length of the padding. */
-  memcpy (&pea.orig_length, buffer + buffer_offset, sizeof (pea.orig_length));
-  buffer_offset += sizeof (pea.orig_length);
+  BUFFER_READ (&pea.orig_length, sizeof (pea.orig_length));
+
   orig_buffer_len = ntohs (pea.orig_length);
-  if (orig_buffer_len > (part_size - pea_size))
+  if (orig_buffer_len > (part_size - PART_ENCRYPTION_AES256_SIZE))
   {
     ERROR ("network plugin: Decryption failed: Invalid original length.");
     return (-1);
   }
 
   /* Calculate the size of the `padding' field. */
-  padding_size = part_size - (orig_buffer_len + pea_size);
+  padding_size = part_size - (orig_buffer_len + PART_ENCRYPTION_AES256_SIZE);
   if (padding_size > sizeof (pea.padding))
   {
     ERROR ("network plugin: Part- and original length "
         "differ more than %zu bytes.", sizeof (pea.padding));
     return (-1);
   }
-  buffer_offset += padding_size;
 
-  memcpy (pea.hash, buffer + buffer_offset, sizeof (pea.hash));
-  buffer_offset += sizeof (pea.hash);
+  BUFFER_READ (pea.hash, sizeof (pea.hash));
+
+  /* Read the padding. */
+  BUFFER_READ (pea.padding, padding_size);
 
   /* Check hash sum */
   memset (hash, 0, sizeof (hash));
@@ -910,17 +1033,15 @@ static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
     return (-1);
   }
 
-  assert ((buffer_offset + orig_buffer_len) <= buffer_len);
-  if ((buffer_offset + orig_buffer_len) < buffer_len)
-  {
-    NOTICE ("network plugin: Trailing, potentially unencrypted data "
-        "(%zu bytes) will be ignored.",
-        buffer_len - (buffer_offset + orig_buffer_len));
-  }
+  assert ((PART_ENCRYPTION_AES256_SIZE + padding_size + orig_buffer_len)
+                 == part_size);
+
+  parse_packet (se, buffer + PART_ENCRYPTION_AES256_SIZE + padding_size,
+                 orig_buffer_len, flags | PP_ENCRYPTED);
 
   /* Update return values */
-  *ret_buffer = buffer + buffer_offset;
-  *ret_buffer_len = (int) orig_buffer_len;
+  *ret_buffer =     buffer     + part_size;
+  *ret_buffer_len = buffer_len - part_size;
 
   return (0);
 } /* }}} int parse_part_encr_aes256 */
@@ -928,54 +1049,74 @@ static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
 
 #else /* if !HAVE_GCRYPT_H */
 static int parse_part_encr_aes256 (sockent_t *se, /* {{{ */
-    void **ret_buffer, int *ret_buffer_len)
+    void **ret_buffer, size_t *ret_buffer_size, int flags)
 {
-  INFO ("network plugin: Received encrypted packet, but the network "
-      "plugin was not linked with libgcrypt, so I cannot "
-      "decrypt it. The packet will be discarded.");
-  return (-1);
+  static int warning_has_been_printed = 0;
+
+  char *buffer;
+  size_t buffer_size;
+  size_t buffer_offset;
+
+  part_header_t ph;
+  size_t ph_length;
+
+  buffer = *ret_buffer;
+  buffer_size = *ret_buffer_size;
+  buffer_offset = 0;
+
+  /* parse_packet assures this minimum size. */
+  assert (buffer_size >= (sizeof (ph.type) + sizeof (ph.length)));
+
+  BUFFER_READ (&ph.type, sizeof (ph.type));
+  BUFFER_READ (&ph.length, sizeof (ph.length));
+  ph_length = ntohs (ph.length);
+
+  if ((ph_length < PART_ENCRYPTION_AES256_SIZE)
+      || (ph_length > buffer_size))
+  {
+    ERROR ("network plugin: AES-256 encrypted part "
+        "with invalid length received.");
+    return (-1);
+  }
+
+  if (warning_has_been_printed == 0)
+  {
+    WARNING ("network plugin: Received encrypted packet, but the network "
+        "plugin was not linked with libgcrypt, so I cannot "
+        "decrypt it. The part will be discarded.");
+    warning_has_been_printed = 1;
+  }
+
+  *ret_buffer += ph_length;
+  *ret_buffer_size -= ph_length;
+
+  return (0);
 } /* }}} int parse_part_encr_aes256 */
 #endif /* !HAVE_GCRYPT_H */
 
-static int parse_packet (receive_list_entry_t *rle) /* {{{ */
+#undef BUFFER_READ
+
+static int parse_packet (sockent_t *se, /* {{{ */
+               void *buffer, size_t buffer_size, int flags)
 {
        int status;
 
-       void *buffer;
-       int buffer_len;
-       sockent_t *se;
-
        value_list_t vl = VALUE_LIST_INIT;
        notification_t n;
 
-       int packet_was_encrypted = 0;
-       int packet_was_signed = 0;
 #if HAVE_GCRYPT_H
+       int packet_was_signed = (flags & PP_SIGNED);
+        int packet_was_encrypted = (flags & PP_ENCRYPTED);
        int printed_ignore_warning = 0;
 #endif /* HAVE_GCRYPT_H */
 
-       buffer = rle->data;
-       buffer_len = rle->data_len;
-
-       /* Look for the correct `sockent_t' */
-       se = listen_sockets;
-       while ((se != NULL) && (se->fd != rle->fd))
-               se = se->next;
-
-       if (se == NULL)
-       {
-               ERROR ("network plugin: Got packet from FD %i, but can't "
-                               "find an appropriate socket entry.",
-                               rle->fd);
-               return (-1);
-       }
 
        memset (&vl, '\0', sizeof (vl));
        memset (&n, '\0', sizeof (n));
        status = 0;
 
-       while ((status == 0) && (0 < buffer_len)
-                       && ((unsigned int) buffer_len > sizeof (part_header_t)))
+       while ((status == 0) && (0 < buffer_size)
+                       && ((unsigned int) buffer_size > sizeof (part_header_t)))
        {
                uint16_t pkg_length;
                uint16_t pkg_type;
@@ -990,7 +1131,7 @@ static int parse_packet (receive_list_entry_t *rle) /* {{{ */
                pkg_length = ntohs (pkg_length);
                pkg_type = ntohs (pkg_type);
 
-               if (pkg_length > buffer_len)
+               if (pkg_length > buffer_size)
                        break;
                /* Ensure that this loop terminates eventually */
                if (pkg_length < (2 * sizeof (uint16_t)))
@@ -998,7 +1139,8 @@ static int parse_packet (receive_list_entry_t *rle) /* {{{ */
 
                if (pkg_type == TYPE_ENCR_AES256)
                {
-                       status = parse_part_encr_aes256 (se, &buffer, &buffer_len);
+                       status = parse_part_encr_aes256 (se,
+                                       &buffer, &buffer_size, flags);
                        if (status != 0)
                        {
                                ERROR ("network plugin: Decrypting AES256 "
@@ -1006,10 +1148,6 @@ static int parse_packet (receive_list_entry_t *rle) /* {{{ */
                                                "with status %i.", status);
                                break;
                        }
-                       else
-                       {
-                               packet_was_encrypted = 1;
-                       }
                }
 #if HAVE_GCRYPT_H
                else if ((se->security_level == SECURITY_LEVEL_ENCRYPT)
@@ -1027,24 +1165,15 @@ static int parse_packet (receive_list_entry_t *rle) /* {{{ */
 #endif /* HAVE_GCRYPT_H */
                else if (pkg_type == TYPE_SIGN_SHA256)
                {
-                       status = parse_part_sign_sha256 (se, &buffer, &buffer_len);
-                       if (status < 0)
+                       status = parse_part_sign_sha256 (se,
+                                        &buffer, &buffer_size, flags);
+                       if (status != 0)
                        {
                                ERROR ("network plugin: Verifying HMAC-SHA-256 "
                                                "signature failed "
                                                "with status %i.", status);
                                break;
                        }
-                       else if (status > 0)
-                       {
-                               ERROR ("network plugin: Ignoring packet with "
-                                               "invalid HMAC-SHA-256 signature.");
-                               break;
-                       }
-                       else
-                       {
-                               packet_was_signed = 1;
-                       }
                }
 #if HAVE_GCRYPT_H
                else if ((se->security_level == SECURITY_LEVEL_SIGN)
@@ -1063,7 +1192,7 @@ static int parse_packet (receive_list_entry_t *rle) /* {{{ */
 #endif /* HAVE_GCRYPT_H */
                else if (pkg_type == TYPE_VALUES)
                {
-                       status = parse_part_values (&buffer, &buffer_len,
+                       status = parse_part_values (&buffer, &buffer_size,
                                        &vl.values, &vl.values_len);
 
                        if (status != 0)
@@ -1088,7 +1217,7 @@ static int parse_packet (receive_list_entry_t *rle) /* {{{ */
                else if (pkg_type == TYPE_TIME)
                {
                        uint64_t tmp = 0;
-                       status = parse_part_number (&buffer, &buffer_len,
+                       status = parse_part_number (&buffer, &buffer_size,
                                        &tmp);
                        if (status == 0)
                        {
@@ -1099,21 +1228,21 @@ static int parse_packet (receive_list_entry_t *rle) /* {{{ */
                else if (pkg_type == TYPE_INTERVAL)
                {
                        uint64_t tmp = 0;
-                       status = parse_part_number (&buffer, &buffer_len,
+                       status = parse_part_number (&buffer, &buffer_size,
                                        &tmp);
                        if (status == 0)
                                vl.interval = (int) tmp;
                }
                else if (pkg_type == TYPE_HOST)
                {
-                       status = parse_part_string (&buffer, &buffer_len,
+                       status = parse_part_string (&buffer, &buffer_size,
                                        vl.host, sizeof (vl.host));
                        if (status == 0)
                                sstrncpy (n.host, vl.host, sizeof (n.host));
                }
                else if (pkg_type == TYPE_PLUGIN)
                {
-                       status = parse_part_string (&buffer, &buffer_len,
+                       status = parse_part_string (&buffer, &buffer_size,
                                        vl.plugin, sizeof (vl.plugin));
                        if (status == 0)
                                sstrncpy (n.plugin, vl.plugin,
@@ -1121,7 +1250,7 @@ static int parse_packet (receive_list_entry_t *rle) /* {{{ */
                }
                else if (pkg_type == TYPE_PLUGIN_INSTANCE)
                {
-                       status = parse_part_string (&buffer, &buffer_len,
+                       status = parse_part_string (&buffer, &buffer_size,
                                        vl.plugin_instance,
                                        sizeof (vl.plugin_instance));
                        if (status == 0)
@@ -1131,14 +1260,14 @@ static int parse_packet (receive_list_entry_t *rle) /* {{{ */
                }
                else if (pkg_type == TYPE_TYPE)
                {
-                       status = parse_part_string (&buffer, &buffer_len,
+                       status = parse_part_string (&buffer, &buffer_size,
                                        vl.type, sizeof (vl.type));
                        if (status == 0)
                                sstrncpy (n.type, vl.type, sizeof (n.type));
                }
                else if (pkg_type == TYPE_TYPE_INSTANCE)
                {
-                       status = parse_part_string (&buffer, &buffer_len,
+                       status = parse_part_string (&buffer, &buffer_size,
                                        vl.type_instance,
                                        sizeof (vl.type_instance));
                        if (status == 0)
@@ -1147,7 +1276,7 @@ static int parse_packet (receive_list_entry_t *rle) /* {{{ */
                }
                else if (pkg_type == TYPE_MESSAGE)
                {
-                       status = parse_part_string (&buffer, &buffer_len,
+                       status = parse_part_string (&buffer, &buffer_size,
                                        n.message, sizeof (n.message));
 
                        if (status != 0)
@@ -1183,7 +1312,7 @@ static int parse_packet (receive_list_entry_t *rle) /* {{{ */
                else if (pkg_type == TYPE_SEVERITY)
                {
                        uint64_t tmp = 0;
-                       status = parse_part_number (&buffer, &buffer_len,
+                       status = parse_part_number (&buffer, &buffer_size,
                                        &tmp);
                        if (status == 0)
                                n.severity = (int) tmp;
@@ -1194,7 +1323,7 @@ static int parse_packet (receive_list_entry_t *rle) /* {{{ */
                                        " type: 0x%04hx", pkg_type);
                        buffer = ((char *) buffer) + pkg_length;
                }
-       } /* while (buffer_len > sizeof (part_header_t)) */
+       } /* while (buffer_size > sizeof (part_header_t)) */
 
        return (status);
 } /* }}} int parse_packet */
@@ -1285,50 +1414,6 @@ static int network_set_ttl (const sockent_t *se, const struct addrinfo *ai)
        return (0);
 } /* int network_set_ttl */
 
-#if HAVE_GCRYPT_H
-static int network_set_encryption (sockent_t *se, /* {{{ */
-               const char *shared_secret)
-{
-  char hash[32];
-  gcry_error_t err;
-
-  se->shared_secret = sstrdup (shared_secret);
-
-  /*
-   * We use CBC *without* an initialization vector: The cipher is reset after
-   * each packet and we would have to re-set the IV each time. The first
-   * encrypted block will contain the SHA-224 checksum anyway, so this should
-   * be quite unpredictable. Also, there's a 2 byte field in the header that's
-   * being filled with random numbers. So we only use CBC so the blocks
-   * *within* one packet are chained.
-   */
-  err = gcry_cipher_open (&se->cypher,
-      GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, /* flags = */ 0);
-  if (err != 0)
-  {
-    ERROR ("network plugin: gcry_cipher_open returned: %s",
-        gcry_strerror (err));
-    return (-1);
-  }
-
-  assert (se->shared_secret != NULL);
-  gcry_md_hash_buffer (GCRY_MD_SHA256, hash,
-      se->shared_secret, strlen (se->shared_secret));
-
-  err = gcry_cipher_setkey (se->cypher, hash, sizeof (hash));
-  if (err != 0)
-  {
-    DEBUG ("network plugin: gcry_cipher_setkey returned: %s",
-        gcry_strerror (err));
-    gcry_cipher_close (se->cypher);
-    se->cypher = NULL;
-    return (-1);
-  }
-
-  return (0);
-} /* }}} int network_set_encryption */
-#endif /* HAVE_GCRYPT_H */
-
 static int network_bind_socket (const sockent_t *se, const struct addrinfo *ai)
 {
        int loop = 0;
@@ -1544,28 +1629,16 @@ static sockent_t *network_create_socket (const char *node, /* {{{ */
                se->cypher = NULL;
                if (shared_secret != NULL)
                {
-                       status = network_set_encryption (se, shared_secret);
-                       if ((status != 0) && (security_level <= SECURITY_LEVEL_SIGN))
-                       {
-                               WARNING ("network plugin: Starting cryptograp"
-                                               "hic subsystem failed. Since "
-                                               "security level `Sign' or "
-                                               "`None' is configured I will "
-                                               "continue.");
-                       }
-                       else if (status != 0)
-                       {
-                               ERROR ("network plugin: Starting cryptograp"
-                                               "hic subsystem failed. "
-                                               "Because the security level "
-                                               "is set to `Encrypt' I will "
-                                               "not continue!");
-                               close (se->fd);
-                               free (se->addr);
-                               free (se);
-                               continue;
-                       }
-               } /* if (shared_secret != NULL) */
+                       se->shared_secret = sstrdup (shared_secret);
+                       assert (se->shared_secret != NULL);
+
+                       memset (se->shared_secret_hash, 0,
+                                       sizeof (se->shared_secret_hash));
+                       gcry_md_hash_buffer (GCRY_MD_SHA256,
+                                       se->shared_secret_hash,
+                                       se->shared_secret,
+                                       strlen (se->shared_secret));
+               }
 #else
                /* Make compiler happy */
                security_level = 0;
@@ -1708,11 +1781,12 @@ static int network_add_sending_socket (const char *node, /* {{{ */
        return (0);
 } /* }}} int network_add_sending_socket */
 
-static void *dispatch_thread (void __attribute__((unused)) *arg)
+static void *dispatch_thread (void __attribute__((unused)) *arg) /* {{{ */
 {
   while (42)
   {
     receive_list_entry_t *ent;
+    sockent_t *se;
 
     /* Lock and wait for more data to come in */
     pthread_mutex_lock (&receive_list_lock);
@@ -1731,13 +1805,26 @@ static void *dispatch_thread (void __attribute__((unused)) *arg)
     if (ent == NULL)
       break;
 
-    parse_packet (ent);
+    /* Look for the correct `sockent_t' */
+    se = listen_sockets;
+    while ((se != NULL) && (se->fd != ent->fd))
+           se = se->next;
 
+    if (se == NULL)
+    {
+           ERROR ("network plugin: Got packet from FD %i, but can't "
+                           "find an appropriate socket entry.",
+                           ent->fd);
+           sfree (ent);
+           continue;
+    }
+
+    parse_packet (se, ent->data, ent->data_len, /* flags = */ 0);
     sfree (ent);
   } /* while (42) */
 
   return (NULL);
-} /* void *dispatch_thread */
+} /* }}} void *dispatch_thread */
 
 static int network_receive (void)
 {
@@ -1962,7 +2049,7 @@ static void networt_send_buffer_signed (const sockent_t *se, /* {{{ */
        networt_send_buffer_plain (se, buffer, sizeof (buffer));
 } /* }}} void networt_send_buffer_signed */
 
-static void networt_send_buffer_encrypted (const sockent_t *se, /* {{{ */
+static void networt_send_buffer_encrypted (sockent_t *se, /* {{{ */
                const char *in_buffer, size_t in_buffer_size)
 {
   part_encryption_aes256_t pea;
@@ -1971,16 +2058,21 @@ static void networt_send_buffer_encrypted (const sockent_t *se, /* {{{ */
   size_t buffer_offset;
   size_t padding_size;
   gcry_error_t err;
+  gcry_cipher_hd_t cypher;
 
   /* Round to the next multiple of 16, because AES has a block size of 128 bit.
-   * the first four bytes of `pea' are not encrypted and must be subtracted. */
-  buffer_size = sizeof (pea.orig_length) + sizeof (pea.hash) + in_buffer_size;
+   * the first 20 bytes of `pea' are not encrypted and must be subtracted. */
+  buffer_size = in_buffer_size + 
+    (PART_ENCRYPTION_AES256_SIZE - PART_ENCRYPTION_AES256_UNENCR_SIZE);
   padding_size = buffer_size;
+  /* Round to the next multiple of 16. */
   buffer_size = (buffer_size + 15) / 16;
   buffer_size = buffer_size * 16;
+  /* Calculate padding_size */
   padding_size = buffer_size - padding_size;
   assert (padding_size <= sizeof (pea.padding));
-  buffer_size += sizeof (pea.head);
+  /* Now add the unencrypted bytes. */
+  buffer_size += PART_ENCRYPTION_AES256_UNENCR_SIZE;
 
   DEBUG ("network plugin: networt_send_buffer_encrypted: "
       "buffer_size = %zu;", buffer_size);
@@ -1991,43 +2083,48 @@ static void networt_send_buffer_encrypted (const sockent_t *se, /* {{{ */
   pea.head.length = htons ((uint16_t) buffer_size);
   pea.orig_length = htons ((uint16_t) in_buffer_size);
 
-  /* Fill the extra field with random values. Some entropy in the encrypted
-   * data is usually not a bad thing, I hope. */
-  if (padding_size > 0)
-    gcry_randomize (&pea.padding, padding_size, GCRY_STRONG_RANDOM);
+  /* Chose a random initialization vector. */
+  gcry_randomize ((void *) &pea.iv, sizeof (pea.iv), GCRY_STRONG_RANDOM);
 
   /* Create hash of the payload */
   gcry_md_hash_buffer (GCRY_MD_SHA1, pea.hash, in_buffer, in_buffer_size);
 
+  /* Fill the extra field with random values. Some entropy in the encrypted
+   * data is usually not a bad thing, I hope. */
+  if (padding_size > 0)
+    gcry_randomize ((void *) &pea.padding, padding_size, GCRY_STRONG_RANDOM);
+
   /* Initialize the buffer */
   buffer_offset = 0;
   memset (buffer, 0, sizeof (buffer));
 
-  memcpy (buffer + buffer_offset, &pea.head, sizeof (pea.head));
-  buffer_offset += sizeof (pea.head);
+#define BUFFER_ADD(p,s) do { \
+  memcpy (buffer + buffer_offset, (p), (s)); \
+  buffer_offset += (s); \
+} while (0)
 
-  memcpy (buffer + buffer_offset, &pea.orig_length, sizeof (pea.orig_length));
-  buffer_offset += sizeof (pea.orig_length);
+  BUFFER_ADD (&pea.head.type, sizeof (pea.head.type));
+  BUFFER_ADD (&pea.head.length, sizeof (pea.head.length));
+  BUFFER_ADD (pea.iv, sizeof (pea.iv));
+  BUFFER_ADD (&pea.orig_length, sizeof (pea.orig_length));
+  BUFFER_ADD (pea.hash, sizeof (pea.hash));
 
   if (padding_size > 0)
-  {
-    memcpy (buffer + buffer_offset, &pea.padding, padding_size);
-    buffer_offset += padding_size;
-  }
-
-  memcpy (buffer + buffer_offset, &pea.hash, sizeof (pea.hash));
-  buffer_offset += sizeof (pea.hash);
+    BUFFER_ADD (pea.padding, padding_size);
 
-  memcpy (buffer + buffer_offset, in_buffer, in_buffer_size);
-  buffer_offset += in_buffer_size;
+  BUFFER_ADD (in_buffer, in_buffer_size);
 
   assert (buffer_offset == buffer_size);
 
+  cypher = network_get_aes256_cypher (se, pea.iv, sizeof (pea.iv));
+  if (cypher == NULL)
+    return;
+
   /* Encrypt the buffer in-place */
-  err = gcry_cipher_encrypt (se->cypher,
-      buffer + sizeof (pea.head), buffer_size - sizeof (pea.head),
+  err = gcry_cipher_encrypt (cypher,
+      buffer      + PART_ENCRYPTION_AES256_UNENCR_SIZE,
+      buffer_size - PART_ENCRYPTION_AES256_UNENCR_SIZE,
       /* in = */ NULL, /* in len = */ 0);
-  gcry_cipher_reset (se->cypher);
   if (err != 0)
   {
     ERROR ("network plugin: gcry_cipher_encrypt returned: %s",
@@ -2037,6 +2134,7 @@ static void networt_send_buffer_encrypted (const sockent_t *se, /* {{{ */
 
   /* Send it out without further modifications */
   networt_send_buffer_plain (se, buffer, buffer_size);
+#undef BUFFER_ADD
 } /* }}} void networt_send_buffer_encrypted */
 #endif /* HAVE_GCRYPT_H */