xref: /freebsd/crypto/openssh/openbsd-compat/libressl-api-compat.c (revision cb2887746f8b9dd4ad6b1e757cdc053a08b25a2e)
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 # ifndef HAVE_EVP_CIPHER_CTX_GET_UPDATED_IV
30 int
31 EVP_CIPHER_CTX_get_iv(const EVP_CIPHER_CTX *ctx, unsigned char *iv, size_t len)
32 {
33 	if (ctx == NULL)
34 		return 0;
35 	if (EVP_CIPHER_CTX_iv_length(ctx) < 0)
36 		return 0;
37 	if (len != (size_t)EVP_CIPHER_CTX_iv_length(ctx))
38 		return 0;
39 	if (len > EVP_MAX_IV_LENGTH)
40 		return 0; /* sanity check; shouldn't happen */
41 	/*
42 	 * Skip the memcpy entirely when the requested IV length is zero,
43 	 * since the iv pointer may be NULL or invalid.
44 	 */
45 	if (len != 0) {
46 		if (iv == NULL)
47 			return 0;
48 #  ifdef HAVE_EVP_CIPHER_CTX_IV
49 		memcpy(iv, EVP_CIPHER_CTX_iv(ctx), len);
50 #  else
51 		memcpy(iv, ctx->iv, len);
52 #  endif /* HAVE_EVP_CIPHER_CTX_IV */
53 	}
54 	return 1;
55 }
56 # endif /* HAVE_EVP_CIPHER_CTX_GET_UPDATED_IV */
57 #endif /* HAVE_EVP_CIPHER_CTX_GET_IV */
58 
59 #ifndef HAVE_EVP_CIPHER_CTX_SET_IV
60 int
61 EVP_CIPHER_CTX_set_iv(EVP_CIPHER_CTX *ctx, const unsigned char *iv, size_t len)
62 {
63 	if (ctx == NULL)
64 		return 0;
65 	if (EVP_CIPHER_CTX_iv_length(ctx) < 0)
66 		return 0;
67 	if (len != (size_t)EVP_CIPHER_CTX_iv_length(ctx))
68 		return 0;
69 	if (len > EVP_MAX_IV_LENGTH)
70 		return 0; /* sanity check; shouldn't happen */
71 	/*
72 	 * Skip the memcpy entirely when the requested IV length is zero,
73 	 * since the iv pointer may be NULL or invalid.
74 	 */
75 	if (len != 0) {
76 		if (iv == NULL)
77 			return 0;
78 # ifdef HAVE_EVP_CIPHER_CTX_IV_NOCONST
79 		memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iv, len);
80 # else
81 		memcpy(ctx->iv, iv, len);
82 # endif /* HAVE_EVP_CIPHER_CTX_IV_NOCONST */
83 	}
84 	return 1;
85 }
86 #endif /* HAVE_EVP_CIPHER_CTX_SET_IV */
87 
88 #endif /* WITH_OPENSSL */
89