1 /*
2  * Copyright (c) 2018 Damien Miller <djm@mindrot.org>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16 
17 #include "includes.h"
18 
19 #ifdef WITH_OPENSSL
20 
21 #include <sys/types.h>
22 
23 #include <stdlib.h>
24 #include <string.h>
25 
26 #include <openssl/evp.h>
27 
28 #ifndef HAVE_EVP_CIPHER_CTX_GET_IV
29 int
30 EVP_CIPHER_CTX_get_iv(const EVP_CIPHER_CTX *ctx, unsigned char *iv, size_t len)
31 {
32 	if (ctx == NULL)
33 		return 0;
34 	if (EVP_CIPHER_CTX_iv_length(ctx) < 0)
35 		return 0;
36 	if (len != (size_t)EVP_CIPHER_CTX_iv_length(ctx))
37 		return 0;
38 	if (len > EVP_MAX_IV_LENGTH)
39 		return 0; /* sanity check; shouldn't happen */
40 	/*
41 	 * Skip the memcpy entirely when the requested IV length is zero,
42 	 * since the iv pointer may be NULL or invalid.
43 	 */
44 	if (len != 0) {
45 		if (iv == NULL)
46 			return 0;
47 # ifdef HAVE_EVP_CIPHER_CTX_IV
48 		memcpy(iv, EVP_CIPHER_CTX_iv(ctx), len);
49 # else
50 		memcpy(iv, ctx->iv, len);
51 # endif /* HAVE_EVP_CIPHER_CTX_IV */
52 	}
53 	return 1;
54 }
55 #endif /* HAVE_EVP_CIPHER_CTX_GET_IV */
56 
57 #ifndef HAVE_EVP_CIPHER_CTX_SET_IV
58 int
59 EVP_CIPHER_CTX_set_iv(EVP_CIPHER_CTX *ctx, const unsigned char *iv, size_t len)
60 {
61 	if (ctx == NULL)
62 		return 0;
63 	if (EVP_CIPHER_CTX_iv_length(ctx) < 0)
64 		return 0;
65 	if (len != (size_t)EVP_CIPHER_CTX_iv_length(ctx))
66 		return 0;
67 	if (len > EVP_MAX_IV_LENGTH)
68 		return 0; /* sanity check; shouldn't happen */
69 	/*
70 	 * Skip the memcpy entirely when the requested IV length is zero,
71 	 * since the iv pointer may be NULL or invalid.
72 	 */
73 	if (len != 0) {
74 		if (iv == NULL)
75 			return 0;
76 # ifdef HAVE_EVP_CIPHER_CTX_IV_NOCONST
77 		memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iv, len);
78 # else
79 		memcpy(ctx->iv, iv, len);
80 # endif /* HAVE_EVP_CIPHER_CTX_IV_NOCONST */
81 	}
82 	return 1;
83 }
84 #endif /* HAVE_EVP_CIPHER_CTX_SET_IV */
85 
86 #endif /* WITH_OPENSSL */
87