xref: /freebsd/crypto/openssh/cipher.c (revision 96f262dcacdbfb56e94c60985b07f9f8ee2d046b)
1 /* $OpenBSD: cipher.c,v 1.125 2025/09/02 11:08:34 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  *
7  * As far as I am concerned, the code I have written for this software
8  * can be used freely for any purpose.  Any derived versions of this
9  * software must be clearly marked as such, and if the derived work is
10  * incompatible with the protocol description in the RFC file, it must be
11  * called by a name other than "ssh" or "Secure Shell".
12  *
13  *
14  * Copyright (c) 1999 Niels Provos.  All rights reserved.
15  * Copyright (c) 1999, 2000 Markus Friedl.  All rights reserved.
16  *
17  * Redistribution and use in source and binary forms, with or without
18  * modification, are permitted provided that the following conditions
19  * are met:
20  * 1. Redistributions of source code must retain the above copyright
21  *    notice, this list of conditions and the following disclaimer.
22  * 2. Redistributions in binary form must reproduce the above copyright
23  *    notice, this list of conditions and the following disclaimer in the
24  *    documentation and/or other materials provided with the distribution.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
27  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
28  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
29  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
30  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
31  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
32  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
33  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
34  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
35  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36  */
37 
38 #include "includes.h"
39 
40 #include <sys/types.h>
41 
42 #include <string.h>
43 #include <stdarg.h>
44 #include <stdio.h>
45 
46 #include "cipher.h"
47 #include "misc.h"
48 #include "sshbuf.h"
49 #include "ssherr.h"
50 #include "digest.h"
51 
52 #include "openbsd-compat/openssl-compat.h"
53 
54 #ifndef WITH_OPENSSL
55 #define EVP_CIPHER_CTX void
56 #endif
57 
58 struct sshcipher_ctx {
59 	int	plaintext;
60 	int	encrypt;
61 	EVP_CIPHER_CTX *evp;
62 	struct chachapoly_ctx *cp_ctx;
63 	struct aesctr_ctx ac_ctx; /* XXX union with evp? */
64 	const struct sshcipher *cipher;
65 };
66 
67 struct sshcipher {
68 	char	*name;
69 	u_int	block_size;
70 	u_int	key_len;
71 	u_int	iv_len;		/* defaults to block_size */
72 	u_int	auth_len;
73 	u_int	flags;
74 #define CFLAG_CBC		(1<<0)
75 #define CFLAG_CHACHAPOLY	(1<<1)
76 #define CFLAG_AESCTR		(1<<2)
77 #define CFLAG_NONE		(1<<3)
78 #define CFLAG_INTERNAL		CFLAG_NONE /* Don't use "none" for packets */
79 #ifdef WITH_OPENSSL
80 	const EVP_CIPHER	*(*evptype)(void);
81 #else
82 	void	*ignored;
83 #endif
84 };
85 
86 static const struct sshcipher ciphers[] = {
87 #ifdef WITH_OPENSSL
88 #ifndef OPENSSL_NO_DES
89 	{ "3des-cbc",		8, 24, 0, 0, CFLAG_CBC, EVP_des_ede3_cbc },
90 #endif
91 	{ "aes128-cbc",		16, 16, 0, 0, CFLAG_CBC, EVP_aes_128_cbc },
92 	{ "aes192-cbc",		16, 24, 0, 0, CFLAG_CBC, EVP_aes_192_cbc },
93 	{ "aes256-cbc",		16, 32, 0, 0, CFLAG_CBC, EVP_aes_256_cbc },
94 	{ "aes128-ctr",		16, 16, 0, 0, 0, EVP_aes_128_ctr },
95 	{ "aes192-ctr",		16, 24, 0, 0, 0, EVP_aes_192_ctr },
96 	{ "aes256-ctr",		16, 32, 0, 0, 0, EVP_aes_256_ctr },
97 	{ "aes128-gcm@openssh.com",
98 				16, 16, 12, 16, 0, EVP_aes_128_gcm },
99 	{ "aes256-gcm@openssh.com",
100 				16, 32, 12, 16, 0, EVP_aes_256_gcm },
101 #else
102 	{ "aes128-ctr",		16, 16, 0, 0, CFLAG_AESCTR, NULL },
103 	{ "aes192-ctr",		16, 24, 0, 0, CFLAG_AESCTR, NULL },
104 	{ "aes256-ctr",		16, 32, 0, 0, CFLAG_AESCTR, NULL },
105 #endif
106 	{ "chacha20-poly1305@openssh.com",
107 				8, 64, 0, 16, CFLAG_CHACHAPOLY, NULL },
108 	{ "none",		8, 0, 0, 0, CFLAG_NONE, NULL },
109 
110 	{ NULL,			0, 0, 0, 0, 0, NULL }
111 };
112 
113 /*--*/
114 
115 /* Returns a comma-separated list of supported ciphers. */
116 char *
117 cipher_alg_list(char sep, int auth_only)
118 {
119 	char *ret = NULL;
120 	const struct sshcipher *c;
121 	char sep_str[2] = {sep, '\0'};
122 
123 	for (c = ciphers; c->name != NULL; c++) {
124 		if ((c->flags & CFLAG_INTERNAL) != 0)
125 			continue;
126 		if (auth_only && c->auth_len == 0)
127 			continue;
128 		xextendf(&ret, sep_str, "%s", c->name);
129 	}
130 	return ret;
131 }
132 
133 const char *
134 compression_alg_list(int compression)
135 {
136 #ifdef WITH_ZLIB
137 	return compression ? "zlib@openssh.com,none" :
138 	    "none,zlib@openssh.com";
139 #else
140 	return "none";
141 #endif
142 }
143 
144 u_int
145 cipher_blocksize(const struct sshcipher *c)
146 {
147 	return (c->block_size);
148 }
149 
150 u_int
151 cipher_keylen(const struct sshcipher *c)
152 {
153 	return (c->key_len);
154 }
155 
156 u_int
157 cipher_seclen(const struct sshcipher *c)
158 {
159 	if (strcmp("3des-cbc", c->name) == 0)
160 		return 14;
161 	return cipher_keylen(c);
162 }
163 
164 u_int
165 cipher_authlen(const struct sshcipher *c)
166 {
167 	return (c->auth_len);
168 }
169 
170 u_int
171 cipher_ivlen(const struct sshcipher *c)
172 {
173 	/*
174 	 * Default is cipher block size, except for chacha20+poly1305 that
175 	 * needs no IV. XXX make iv_len == -1 default?
176 	 */
177 	return (c->iv_len != 0 || (c->flags & CFLAG_CHACHAPOLY) != 0) ?
178 	    c->iv_len : c->block_size;
179 }
180 
181 u_int
182 cipher_is_cbc(const struct sshcipher *c)
183 {
184 	return (c->flags & CFLAG_CBC) != 0;
185 }
186 
187 u_int
188 cipher_ctx_is_plaintext(struct sshcipher_ctx *cc)
189 {
190 	return cc->plaintext;
191 }
192 
193 const struct sshcipher *
194 cipher_by_name(const char *name)
195 {
196 	const struct sshcipher *c;
197 	for (c = ciphers; c->name != NULL; c++)
198 		if (strcmp(c->name, name) == 0)
199 			return c;
200 	return NULL;
201 }
202 
203 #define	CIPHER_SEP	","
204 int
205 ciphers_valid(const char *names)
206 {
207 	const struct sshcipher *c;
208 	char *cipher_list, *cp;
209 	char *p;
210 
211 	if (names == NULL || strcmp(names, "") == 0)
212 		return 0;
213 	if ((cipher_list = cp = strdup(names)) == NULL)
214 		return 0;
215 	for ((p = strsep(&cp, CIPHER_SEP)); p && *p != '\0';
216 	    (p = strsep(&cp, CIPHER_SEP))) {
217 		c = cipher_by_name(p);
218 		if (c == NULL || (c->flags & CFLAG_INTERNAL) != 0) {
219 			free(cipher_list);
220 			return 0;
221 		}
222 	}
223 	free(cipher_list);
224 	return 1;
225 }
226 
227 const char *
228 cipher_warning_message(const struct sshcipher_ctx *cc)
229 {
230 	if (cc == NULL || cc->cipher == NULL)
231 		return NULL;
232 	/* XXX repurpose for CBC warning */
233 	return NULL;
234 }
235 
236 int
237 cipher_init(struct sshcipher_ctx **ccp, const struct sshcipher *cipher,
238     const u_char *key, u_int keylen, const u_char *iv, u_int ivlen,
239     int do_encrypt)
240 {
241 	struct sshcipher_ctx *cc = NULL;
242 	int ret = SSH_ERR_INTERNAL_ERROR;
243 #ifdef WITH_OPENSSL
244 	const EVP_CIPHER *type;
245 	int klen;
246 #endif
247 
248 	*ccp = NULL;
249 	if ((cc = calloc(1, sizeof(*cc))) == NULL)
250 		return SSH_ERR_ALLOC_FAIL;
251 
252 	cc->plaintext = (cipher->flags & CFLAG_NONE) != 0;
253 	cc->encrypt = do_encrypt;
254 
255 	if (keylen < cipher->key_len ||
256 	    (iv != NULL && ivlen < cipher_ivlen(cipher))) {
257 		ret = SSH_ERR_INVALID_ARGUMENT;
258 		goto out;
259 	}
260 
261 	cc->cipher = cipher;
262 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0) {
263 		cc->cp_ctx = chachapoly_new(key, keylen);
264 		ret = cc->cp_ctx != NULL ? 0 : SSH_ERR_INVALID_ARGUMENT;
265 		goto out;
266 	}
267 	if ((cc->cipher->flags & CFLAG_NONE) != 0) {
268 		ret = 0;
269 		goto out;
270 	}
271 #ifndef WITH_OPENSSL
272 	if ((cc->cipher->flags & CFLAG_AESCTR) != 0) {
273 		aesctr_keysetup(&cc->ac_ctx, key, 8 * keylen, 8 * ivlen);
274 		aesctr_ivsetup(&cc->ac_ctx, iv);
275 		ret = 0;
276 		goto out;
277 	}
278 	ret = SSH_ERR_INVALID_ARGUMENT;
279 	goto out;
280 #else /* WITH_OPENSSL */
281 	type = (*cipher->evptype)();
282 	if ((cc->evp = EVP_CIPHER_CTX_new()) == NULL) {
283 		ret = SSH_ERR_ALLOC_FAIL;
284 		goto out;
285 	}
286 	if (EVP_CipherInit(cc->evp, type, NULL, (u_char *)iv,
287 	    (do_encrypt == CIPHER_ENCRYPT)) == 0) {
288 		ret = SSH_ERR_LIBCRYPTO_ERROR;
289 		goto out;
290 	}
291 	if (cipher_authlen(cipher) &&
292 	    EVP_CIPHER_CTX_ctrl(cc->evp, EVP_CTRL_GCM_SET_IV_FIXED,
293 	    -1, (u_char *)iv) <= 0) {
294 		ret = SSH_ERR_LIBCRYPTO_ERROR;
295 		goto out;
296 	}
297 	klen = EVP_CIPHER_CTX_key_length(cc->evp);
298 	if (klen > 0 && keylen != (u_int)klen) {
299 		if (EVP_CIPHER_CTX_set_key_length(cc->evp, keylen) == 0) {
300 			ret = SSH_ERR_LIBCRYPTO_ERROR;
301 			goto out;
302 		}
303 	}
304 	if (EVP_CipherInit(cc->evp, NULL, (u_char *)key, NULL, -1) == 0) {
305 		ret = SSH_ERR_LIBCRYPTO_ERROR;
306 		goto out;
307 	}
308 	ret = 0;
309 #endif /* WITH_OPENSSL */
310  out:
311 	if (ret == 0) {
312 		/* success */
313 		*ccp = cc;
314 	} else {
315 		if (cc != NULL) {
316 #ifdef WITH_OPENSSL
317 			EVP_CIPHER_CTX_free(cc->evp);
318 #endif /* WITH_OPENSSL */
319 			freezero(cc, sizeof(*cc));
320 		}
321 	}
322 	return ret;
323 }
324 
325 /*
326  * cipher_crypt() operates as following:
327  * Copy 'aadlen' bytes (without en/decryption) from 'src' to 'dest'.
328  * These bytes are treated as additional authenticated data for
329  * authenticated encryption modes.
330  * En/Decrypt 'len' bytes at offset 'aadlen' from 'src' to 'dest'.
331  * Use 'authlen' bytes at offset 'len'+'aadlen' as the authentication tag.
332  * This tag is written on encryption and verified on decryption.
333  * Both 'aadlen' and 'authlen' can be set to 0.
334  */
335 int
336 cipher_crypt(struct sshcipher_ctx *cc, u_int seqnr, u_char *dest,
337    const u_char *src, u_int len, u_int aadlen, u_int authlen)
338 {
339 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0) {
340 		return chachapoly_crypt(cc->cp_ctx, seqnr, dest, src,
341 		    len, aadlen, authlen, cc->encrypt);
342 	}
343 	if ((cc->cipher->flags & CFLAG_NONE) != 0) {
344 		memcpy(dest, src, aadlen + len);
345 		return 0;
346 	}
347 #ifndef WITH_OPENSSL
348 	if ((cc->cipher->flags & CFLAG_AESCTR) != 0) {
349 		if (aadlen)
350 			memcpy(dest, src, aadlen);
351 		aesctr_encrypt_bytes(&cc->ac_ctx, src + aadlen,
352 		    dest + aadlen, len);
353 		return 0;
354 	}
355 	return SSH_ERR_INVALID_ARGUMENT;
356 #else
357 	if (authlen) {
358 		u_char lastiv[1];
359 
360 		if (authlen != cipher_authlen(cc->cipher))
361 			return SSH_ERR_INVALID_ARGUMENT;
362 		/* increment IV */
363 		if (EVP_CIPHER_CTX_ctrl(cc->evp, EVP_CTRL_GCM_IV_GEN,
364 		    1, lastiv) <= 0)
365 			return SSH_ERR_LIBCRYPTO_ERROR;
366 		/* set tag on decryption */
367 		if (!cc->encrypt &&
368 		    EVP_CIPHER_CTX_ctrl(cc->evp, EVP_CTRL_GCM_SET_TAG,
369 		    authlen, (u_char *)src + aadlen + len) <= 0)
370 			return SSH_ERR_LIBCRYPTO_ERROR;
371 	}
372 	if (aadlen) {
373 		if (authlen &&
374 		    EVP_Cipher(cc->evp, NULL, (u_char *)src, aadlen) < 0)
375 			return SSH_ERR_LIBCRYPTO_ERROR;
376 		memcpy(dest, src, aadlen);
377 	}
378 	if (len % cc->cipher->block_size)
379 		return SSH_ERR_INVALID_ARGUMENT;
380 	if (EVP_Cipher(cc->evp, dest + aadlen, (u_char *)src + aadlen,
381 	    len) < 0)
382 		return SSH_ERR_LIBCRYPTO_ERROR;
383 	if (authlen) {
384 		/* compute tag (on encrypt) or verify tag (on decrypt) */
385 		if (EVP_Cipher(cc->evp, NULL, NULL, 0) < 0)
386 			return cc->encrypt ?
387 			    SSH_ERR_LIBCRYPTO_ERROR : SSH_ERR_MAC_INVALID;
388 		if (cc->encrypt &&
389 		    EVP_CIPHER_CTX_ctrl(cc->evp, EVP_CTRL_GCM_GET_TAG,
390 		    authlen, dest + aadlen + len) <= 0)
391 			return SSH_ERR_LIBCRYPTO_ERROR;
392 	}
393 	return 0;
394 #endif
395 }
396 
397 /* Extract the packet length, including any decryption necessary beforehand */
398 int
399 cipher_get_length(struct sshcipher_ctx *cc, u_int *plenp, u_int seqnr,
400     const u_char *cp, u_int len)
401 {
402 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0)
403 		return chachapoly_get_length(cc->cp_ctx, plenp, seqnr,
404 		    cp, len);
405 	if (len < 4)
406 		return SSH_ERR_MESSAGE_INCOMPLETE;
407 	*plenp = PEEK_U32(cp);
408 	return 0;
409 }
410 
411 void
412 cipher_free(struct sshcipher_ctx *cc)
413 {
414 	if (cc == NULL)
415 		return;
416 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0) {
417 		chachapoly_free(cc->cp_ctx);
418 		cc->cp_ctx = NULL;
419 	} else if ((cc->cipher->flags & CFLAG_AESCTR) != 0)
420 		explicit_bzero(&cc->ac_ctx, sizeof(cc->ac_ctx));
421 #ifdef WITH_OPENSSL
422 	EVP_CIPHER_CTX_free(cc->evp);
423 	cc->evp = NULL;
424 #endif
425 	freezero(cc, sizeof(*cc));
426 }
427 
428 int
429 cipher_get_keyiv(struct sshcipher_ctx *cc, u_char *iv, size_t len)
430 {
431 #ifdef WITH_OPENSSL
432 	const struct sshcipher *c = cc->cipher;
433 	int evplen;
434 #endif
435 
436 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0) {
437 		if (len != 0)
438 			return SSH_ERR_INVALID_ARGUMENT;
439 		return 0;
440 	}
441 	if ((cc->cipher->flags & CFLAG_AESCTR) != 0) {
442 		if (len != sizeof(cc->ac_ctx.ctr))
443 			return SSH_ERR_INVALID_ARGUMENT;
444 		memcpy(iv, cc->ac_ctx.ctr, len);
445 		return 0;
446 	}
447 	if ((cc->cipher->flags & CFLAG_NONE) != 0)
448 		return 0;
449 
450 #ifdef WITH_OPENSSL
451 	evplen = EVP_CIPHER_CTX_iv_length(cc->evp);
452 	if (evplen == 0)
453 		return 0;
454 	else if (evplen < 0)
455 		return SSH_ERR_LIBCRYPTO_ERROR;
456 	if ((size_t)evplen != len)
457 		return SSH_ERR_INVALID_ARGUMENT;
458 	if (cipher_authlen(c)) {
459 		if (EVP_CIPHER_CTX_ctrl(cc->evp, EVP_CTRL_GCM_IV_GEN, len,
460 		    iv) <= 0)
461 			return SSH_ERR_LIBCRYPTO_ERROR;
462 	} else if (EVP_CIPHER_CTX_get_iv(cc->evp, iv, len) <= 0)
463 		return SSH_ERR_LIBCRYPTO_ERROR;
464 #endif
465 	return 0;
466 }
467 
468 int
469 cipher_set_keyiv(struct sshcipher_ctx *cc, const u_char *iv, size_t len)
470 {
471 #ifdef WITH_OPENSSL
472 	const struct sshcipher *c = cc->cipher;
473 	int evplen = 0;
474 #endif
475 
476 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0)
477 		return 0;
478 	if ((cc->cipher->flags & CFLAG_NONE) != 0)
479 		return 0;
480 
481 #ifdef WITH_OPENSSL
482 	evplen = EVP_CIPHER_CTX_iv_length(cc->evp);
483 	if (evplen <= 0)
484 		return SSH_ERR_LIBCRYPTO_ERROR;
485 	if ((size_t)evplen != len)
486 		return SSH_ERR_INVALID_ARGUMENT;
487 	if (cipher_authlen(c)) {
488 		/* XXX iv arg is const, but EVP_CIPHER_CTX_ctrl isn't */
489 		if (EVP_CIPHER_CTX_ctrl(cc->evp,
490 		    EVP_CTRL_GCM_SET_IV_FIXED, -1, (void *)iv) <= 0)
491 			return SSH_ERR_LIBCRYPTO_ERROR;
492 	} else if (!EVP_CIPHER_CTX_set_iv(cc->evp, iv, evplen))
493 		return SSH_ERR_LIBCRYPTO_ERROR;
494 #endif
495 	return 0;
496 }
497