- EVP_CipherInit(ctx, NULL, NULL, p, 0);
- len = ep - (p + ivlen);
-
- /* We need a block size */
- block_size = EVP_CIPHER_CTX_block_size(ctx);
- /* We need the buffer size to be multiple of a block size */
- output_buffer_size = len + (block_size - len % block_size);
- output_buffer = (u_char *)calloc(output_buffer_size, sizeof(u_char));
- /* EVP_Cipher output buffer should be different from the input one.
- * Also it should be of size that is multiple of cipher block size. */
- EVP_Cipher(ctx, output_buffer, p + ivlen, len);
+ set_cipher_parameters(ctx, NULL, NULL, p, 0);
+ len = ep - (p + ivlen);
+
+ /*
+ * Allocate buffers for the encrypted and decrypted
+ * data. Both buffers' sizes must be a multiple of
+ * the cipher block size, and the output buffer must
+ * be separate from the input buffer.
+ */
+ block_size = (unsigned int)EVP_CIPHER_CTX_block_size(ctx);
+ buffer_size = len + (block_size - len % block_size);
+
+ /*
+ * Attempt to allocate the input buffer.
+ */
+ input_buffer = (u_char *)malloc(buffer_size);
+ if (input_buffer == NULL) {
+ EVP_CIPHER_CTX_free(ctx);
+ (*ndo->ndo_error)(ndo, S_ERR_ND_MEM_ALLOC,
+ "esp_print: can't allocate memory for encrypted data buffer");
+ }
+ /*
+ * Copy the input data to the encrypted data buffer,
+ * and pad it with zeroes.
+ */
+ memcpy(input_buffer, p + ivlen, len);
+ memset(input_buffer + len, 0, buffer_size - len);
+
+ /*
+ * Attempt to allocate the output buffer.
+ */
+ output_buffer = (u_char *)malloc(buffer_size);
+ if (output_buffer == NULL) {
+ free(input_buffer);
+ EVP_CIPHER_CTX_free(ctx);
+ (*ndo->ndo_error)(ndo, S_ERR_ND_MEM_ALLOC,
+ "esp_print: can't allocate memory for decryption buffer");
+ }
+
+ EVP_Cipher(ctx, output_buffer, input_buffer, len);
+ free(input_buffer);