openssl: Allocate our own buffer for i2d_* wrapper macro
authorTobias Brunner <tobias@strongswan.org>
Wed, 10 Feb 2021 16:55:06 +0000 (17:55 +0100)
committerTobias Brunner <tobias@strongswan.org>
Thu, 11 Feb 2021 15:40:58 +0000 (16:40 +0100)
If we pass a pointer to NULL, the memory allocated by OpenSSL has to be
freed with OPENSSL_free().  Otherwise, this can lead to random
crashes/freezes for Windows builds as seen on AppVeyor.  To not
complicate things for callers of this macro, we allocate our own memory,
which we already do for other i2d_* calls.

src/libstrongswan/plugins/openssl/openssl_util.h

index eb2a378..f226fef 100644 (file)
@@ -101,9 +101,14 @@ bool openssl_bn2chunk(const BIGNUM *bn, chunk_t *chunk);
  * @returns                    allocated chunk of the object, or chunk_empty
  */
 #define openssl_i2chunk(type, obj) ({ \
-                                       unsigned char *ptr = NULL; \
-                                       int len = i2d_##type(obj, &ptr); \
-                                       len < 0 ? chunk_empty : chunk_create(ptr, len);})
+                                       chunk_t chunk = chunk_empty; \
+                                       int len = i2d_##type(obj, NULL); \
+                                       if (len >= 0) { \
+                                               chunk = chunk_alloc(len); \
+                                               u_char *p = chunk.ptr; \
+                                               i2d_##type(obj, &p); \
+                                       } \
+                                       chunk; })
 
 /**
  * Convert an OpenSSL ASN1_OBJECT to a chunk.