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