xref: /freebsd/crypto/openssh/cipher.c (revision b71a5db306ab1ad1e23c7f9e3c949c6218f43455)
1 /* $OpenBSD: cipher.c,v 1.111 2018/02/23 15:58:37 markus 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 
55 struct sshcipher_ctx {
56 	int	plaintext;
57 	int	encrypt;
58 	EVP_CIPHER_CTX *evp;
59 	struct chachapoly_ctx cp_ctx; /* XXX union with evp? */
60 	struct aesctr_ctx ac_ctx; /* XXX union with evp? */
61 	const struct sshcipher *cipher;
62 };
63 
64 struct sshcipher {
65 	char	*name;
66 	u_int	block_size;
67 	u_int	key_len;
68 	u_int	iv_len;		/* defaults to block_size */
69 	u_int	auth_len;
70 	u_int	flags;
71 #define CFLAG_CBC		(1<<0)
72 #define CFLAG_CHACHAPOLY	(1<<1)
73 #define CFLAG_AESCTR		(1<<2)
74 #define CFLAG_NONE		(1<<3)
75 #define CFLAG_INTERNAL		CFLAG_NONE /* Don't use "none" for packets */
76 #ifdef WITH_OPENSSL
77 	const EVP_CIPHER	*(*evptype)(void);
78 #else
79 	void	*ignored;
80 #endif
81 };
82 
83 static const struct sshcipher ciphers[] = {
84 #ifdef WITH_OPENSSL
85 	{ "3des-cbc",		8, 24, 0, 0, CFLAG_CBC, EVP_des_ede3_cbc },
86 	{ "aes128-cbc",		16, 16, 0, 0, CFLAG_CBC, EVP_aes_128_cbc },
87 	{ "aes192-cbc",		16, 24, 0, 0, CFLAG_CBC, EVP_aes_192_cbc },
88 	{ "aes256-cbc",		16, 32, 0, 0, CFLAG_CBC, EVP_aes_256_cbc },
89 	{ "rijndael-cbc@lysator.liu.se",
90 				16, 32, 0, 0, CFLAG_CBC, EVP_aes_256_cbc },
91 	{ "aes128-ctr",		16, 16, 0, 0, 0, EVP_aes_128_ctr },
92 	{ "aes192-ctr",		16, 24, 0, 0, 0, EVP_aes_192_ctr },
93 	{ "aes256-ctr",		16, 32, 0, 0, 0, EVP_aes_256_ctr },
94 # ifdef OPENSSL_HAVE_EVPGCM
95 	{ "aes128-gcm@openssh.com",
96 				16, 16, 12, 16, 0, EVP_aes_128_gcm },
97 	{ "aes256-gcm@openssh.com",
98 				16, 32, 12, 16, 0, EVP_aes_256_gcm },
99 # endif /* OPENSSL_HAVE_EVPGCM */
100 #else
101 	{ "aes128-ctr",		16, 16, 0, 0, CFLAG_AESCTR, NULL },
102 	{ "aes192-ctr",		16, 24, 0, 0, CFLAG_AESCTR, NULL },
103 	{ "aes256-ctr",		16, 32, 0, 0, CFLAG_AESCTR, NULL },
104 #endif
105 	{ "chacha20-poly1305@openssh.com",
106 				8, 64, 0, 16, CFLAG_CHACHAPOLY, NULL },
107 	{ "none",		8, 0, 0, 0, CFLAG_NONE, NULL },
108 
109 	{ NULL,			0, 0, 0, 0, 0, NULL }
110 };
111 
112 /*--*/
113 
114 /* Returns a comma-separated list of supported ciphers. */
115 char *
116 cipher_alg_list(char sep, int auth_only)
117 {
118 	char *tmp, *ret = NULL;
119 	size_t nlen, rlen = 0;
120 	const struct sshcipher *c;
121 
122 	for (c = ciphers; c->name != NULL; c++) {
123 		if ((c->flags & CFLAG_INTERNAL) != 0)
124 			continue;
125 		if (auth_only && c->auth_len == 0)
126 			continue;
127 		if (ret != NULL)
128 			ret[rlen++] = sep;
129 		nlen = strlen(c->name);
130 		if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
131 			free(ret);
132 			return NULL;
133 		}
134 		ret = tmp;
135 		memcpy(ret + rlen, c->name, nlen + 1);
136 		rlen += nlen;
137 	}
138 	return ret;
139 }
140 
141 u_int
142 cipher_blocksize(const struct sshcipher *c)
143 {
144 	return (c->block_size);
145 }
146 
147 u_int
148 cipher_keylen(const struct sshcipher *c)
149 {
150 	return (c->key_len);
151 }
152 
153 u_int
154 cipher_seclen(const struct sshcipher *c)
155 {
156 	if (strcmp("3des-cbc", c->name) == 0)
157 		return 14;
158 	return cipher_keylen(c);
159 }
160 
161 u_int
162 cipher_authlen(const struct sshcipher *c)
163 {
164 	return (c->auth_len);
165 }
166 
167 u_int
168 cipher_ivlen(const struct sshcipher *c)
169 {
170 	/*
171 	 * Default is cipher block size, except for chacha20+poly1305 that
172 	 * needs no IV. XXX make iv_len == -1 default?
173 	 */
174 	return (c->iv_len != 0 || (c->flags & CFLAG_CHACHAPOLY) != 0) ?
175 	    c->iv_len : c->block_size;
176 }
177 
178 u_int
179 cipher_is_cbc(const struct sshcipher *c)
180 {
181 	return (c->flags & CFLAG_CBC) != 0;
182 }
183 
184 u_int
185 cipher_ctx_is_plaintext(struct sshcipher_ctx *cc)
186 {
187 	return cc->plaintext;
188 }
189 
190 const struct sshcipher *
191 cipher_by_name(const char *name)
192 {
193 	const struct sshcipher *c;
194 	for (c = ciphers; c->name != NULL; c++)
195 		if (strcmp(c->name, name) == 0)
196 			return c;
197 	return NULL;
198 }
199 
200 #define	CIPHER_SEP	","
201 int
202 ciphers_valid(const char *names)
203 {
204 	const struct sshcipher *c;
205 	char *cipher_list, *cp;
206 	char *p;
207 
208 	if (names == NULL || strcmp(names, "") == 0)
209 		return 0;
210 	if ((cipher_list = cp = strdup(names)) == NULL)
211 		return 0;
212 	for ((p = strsep(&cp, CIPHER_SEP)); p && *p != '\0';
213 	    (p = strsep(&cp, CIPHER_SEP))) {
214 		c = cipher_by_name(p);
215 		if (c == NULL || (c->flags & CFLAG_INTERNAL) != 0) {
216 			free(cipher_list);
217 			return 0;
218 		}
219 	}
220 	free(cipher_list);
221 	return 1;
222 }
223 
224 const char *
225 cipher_warning_message(const struct sshcipher_ctx *cc)
226 {
227 	if (cc == NULL || cc->cipher == NULL)
228 		return NULL;
229 	/* XXX repurpose for CBC warning */
230 	return NULL;
231 }
232 
233 int
234 cipher_init(struct sshcipher_ctx **ccp, const struct sshcipher *cipher,
235     const u_char *key, u_int keylen, const u_char *iv, u_int ivlen,
236     int do_encrypt)
237 {
238 	struct sshcipher_ctx *cc = NULL;
239 	int ret = SSH_ERR_INTERNAL_ERROR;
240 #ifdef WITH_OPENSSL
241 	const EVP_CIPHER *type;
242 	int klen;
243 #endif
244 
245 	*ccp = NULL;
246 	if ((cc = calloc(sizeof(*cc), 1)) == NULL)
247 		return SSH_ERR_ALLOC_FAIL;
248 
249 	cc->plaintext = (cipher->flags & CFLAG_NONE) != 0;
250 	cc->encrypt = do_encrypt;
251 
252 	if (keylen < cipher->key_len ||
253 	    (iv != NULL && ivlen < cipher_ivlen(cipher))) {
254 		ret = SSH_ERR_INVALID_ARGUMENT;
255 		goto out;
256 	}
257 
258 	cc->cipher = cipher;
259 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0) {
260 		ret = chachapoly_init(&cc->cp_ctx, key, keylen);
261 		goto out;
262 	}
263 	if ((cc->cipher->flags & CFLAG_NONE) != 0) {
264 		ret = 0;
265 		goto out;
266 	}
267 #ifndef WITH_OPENSSL
268 	if ((cc->cipher->flags & CFLAG_AESCTR) != 0) {
269 		aesctr_keysetup(&cc->ac_ctx, key, 8 * keylen, 8 * ivlen);
270 		aesctr_ivsetup(&cc->ac_ctx, iv);
271 		ret = 0;
272 		goto out;
273 	}
274 	ret = SSH_ERR_INVALID_ARGUMENT;
275 	goto out;
276 #else /* WITH_OPENSSL */
277 	type = (*cipher->evptype)();
278 	if ((cc->evp = EVP_CIPHER_CTX_new()) == NULL) {
279 		ret = SSH_ERR_ALLOC_FAIL;
280 		goto out;
281 	}
282 	if (EVP_CipherInit(cc->evp, type, NULL, (u_char *)iv,
283 	    (do_encrypt == CIPHER_ENCRYPT)) == 0) {
284 		ret = SSH_ERR_LIBCRYPTO_ERROR;
285 		goto out;
286 	}
287 	if (cipher_authlen(cipher) &&
288 	    !EVP_CIPHER_CTX_ctrl(cc->evp, EVP_CTRL_GCM_SET_IV_FIXED,
289 	    -1, (u_char *)iv)) {
290 		ret = SSH_ERR_LIBCRYPTO_ERROR;
291 		goto out;
292 	}
293 	klen = EVP_CIPHER_CTX_key_length(cc->evp);
294 	if (klen > 0 && keylen != (u_int)klen) {
295 		if (EVP_CIPHER_CTX_set_key_length(cc->evp, keylen) == 0) {
296 			ret = SSH_ERR_LIBCRYPTO_ERROR;
297 			goto out;
298 		}
299 	}
300 	if (EVP_CipherInit(cc->evp, NULL, (u_char *)key, NULL, -1) == 0) {
301 		ret = SSH_ERR_LIBCRYPTO_ERROR;
302 		goto out;
303 	}
304 	ret = 0;
305 #endif /* WITH_OPENSSL */
306  out:
307 	if (ret == 0) {
308 		/* success */
309 		*ccp = cc;
310 	} else {
311 		if (cc != NULL) {
312 #ifdef WITH_OPENSSL
313 			EVP_CIPHER_CTX_free(cc->evp);
314 #endif /* WITH_OPENSSL */
315 			explicit_bzero(cc, sizeof(*cc));
316 			free(cc);
317 		}
318 	}
319 	return ret;
320 }
321 
322 /*
323  * cipher_crypt() operates as following:
324  * Copy 'aadlen' bytes (without en/decryption) from 'src' to 'dest'.
325  * Theses bytes are treated as additional authenticated data for
326  * authenticated encryption modes.
327  * En/Decrypt 'len' bytes at offset 'aadlen' from 'src' to 'dest'.
328  * Use 'authlen' bytes at offset 'len'+'aadlen' as the authentication tag.
329  * This tag is written on encryption and verified on decryption.
330  * Both 'aadlen' and 'authlen' can be set to 0.
331  */
332 int
333 cipher_crypt(struct sshcipher_ctx *cc, u_int seqnr, u_char *dest,
334    const u_char *src, u_int len, u_int aadlen, u_int authlen)
335 {
336 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0) {
337 		return chachapoly_crypt(&cc->cp_ctx, seqnr, dest, src,
338 		    len, aadlen, authlen, cc->encrypt);
339 	}
340 	if ((cc->cipher->flags & CFLAG_NONE) != 0) {
341 		memcpy(dest, src, aadlen + len);
342 		return 0;
343 	}
344 #ifndef WITH_OPENSSL
345 	if ((cc->cipher->flags & CFLAG_AESCTR) != 0) {
346 		if (aadlen)
347 			memcpy(dest, src, aadlen);
348 		aesctr_encrypt_bytes(&cc->ac_ctx, src + aadlen,
349 		    dest + aadlen, len);
350 		return 0;
351 	}
352 	return SSH_ERR_INVALID_ARGUMENT;
353 #else
354 	if (authlen) {
355 		u_char lastiv[1];
356 
357 		if (authlen != cipher_authlen(cc->cipher))
358 			return SSH_ERR_INVALID_ARGUMENT;
359 		/* increment IV */
360 		if (!EVP_CIPHER_CTX_ctrl(cc->evp, EVP_CTRL_GCM_IV_GEN,
361 		    1, lastiv))
362 			return SSH_ERR_LIBCRYPTO_ERROR;
363 		/* set tag on decyption */
364 		if (!cc->encrypt &&
365 		    !EVP_CIPHER_CTX_ctrl(cc->evp, EVP_CTRL_GCM_SET_TAG,
366 		    authlen, (u_char *)src + aadlen + len))
367 			return SSH_ERR_LIBCRYPTO_ERROR;
368 	}
369 	if (aadlen) {
370 		if (authlen &&
371 		    EVP_Cipher(cc->evp, NULL, (u_char *)src, aadlen) < 0)
372 			return SSH_ERR_LIBCRYPTO_ERROR;
373 		memcpy(dest, src, aadlen);
374 	}
375 	if (len % cc->cipher->block_size)
376 		return SSH_ERR_INVALID_ARGUMENT;
377 	if (EVP_Cipher(cc->evp, dest + aadlen, (u_char *)src + aadlen,
378 	    len) < 0)
379 		return SSH_ERR_LIBCRYPTO_ERROR;
380 	if (authlen) {
381 		/* compute tag (on encrypt) or verify tag (on decrypt) */
382 		if (EVP_Cipher(cc->evp, NULL, NULL, 0) < 0)
383 			return cc->encrypt ?
384 			    SSH_ERR_LIBCRYPTO_ERROR : SSH_ERR_MAC_INVALID;
385 		if (cc->encrypt &&
386 		    !EVP_CIPHER_CTX_ctrl(cc->evp, EVP_CTRL_GCM_GET_TAG,
387 		    authlen, dest + aadlen + len))
388 			return SSH_ERR_LIBCRYPTO_ERROR;
389 	}
390 	return 0;
391 #endif
392 }
393 
394 /* Extract the packet length, including any decryption necessary beforehand */
395 int
396 cipher_get_length(struct sshcipher_ctx *cc, u_int *plenp, u_int seqnr,
397     const u_char *cp, u_int len)
398 {
399 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0)
400 		return chachapoly_get_length(&cc->cp_ctx, plenp, seqnr,
401 		    cp, len);
402 	if (len < 4)
403 		return SSH_ERR_MESSAGE_INCOMPLETE;
404 	*plenp = PEEK_U32(cp);
405 	return 0;
406 }
407 
408 void
409 cipher_free(struct sshcipher_ctx *cc)
410 {
411 	if (cc == NULL)
412 		return;
413 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0)
414 		explicit_bzero(&cc->cp_ctx, sizeof(cc->cp_ctx));
415 	else if ((cc->cipher->flags & CFLAG_AESCTR) != 0)
416 		explicit_bzero(&cc->ac_ctx, sizeof(cc->ac_ctx));
417 #ifdef WITH_OPENSSL
418 	EVP_CIPHER_CTX_free(cc->evp);
419 	cc->evp = NULL;
420 #endif
421 	explicit_bzero(cc, sizeof(*cc));
422 	free(cc);
423 }
424 
425 /*
426  * Exports an IV from the sshcipher_ctx required to export the key
427  * state back from the unprivileged child to the privileged parent
428  * process.
429  */
430 int
431 cipher_get_keyiv_len(const struct sshcipher_ctx *cc)
432 {
433 	const struct sshcipher *c = cc->cipher;
434 
435 	if ((c->flags & CFLAG_CHACHAPOLY) != 0)
436 		return 0;
437 	else if ((c->flags & CFLAG_AESCTR) != 0)
438 		return sizeof(cc->ac_ctx.ctr);
439 #ifdef WITH_OPENSSL
440 	return EVP_CIPHER_CTX_iv_length(cc->evp);
441 #else
442 	return 0;
443 #endif
444 }
445 
446 int
447 cipher_get_keyiv(struct sshcipher_ctx *cc, u_char *iv, u_int len)
448 {
449 #ifdef WITH_OPENSSL
450 	const struct sshcipher *c = cc->cipher;
451 	int evplen;
452 #endif
453 
454 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0) {
455 		if (len != 0)
456 			return SSH_ERR_INVALID_ARGUMENT;
457 		return 0;
458 	}
459 	if ((cc->cipher->flags & CFLAG_AESCTR) != 0) {
460 		if (len != sizeof(cc->ac_ctx.ctr))
461 			return SSH_ERR_INVALID_ARGUMENT;
462 		memcpy(iv, cc->ac_ctx.ctr, len);
463 		return 0;
464 	}
465 	if ((cc->cipher->flags & CFLAG_NONE) != 0)
466 		return 0;
467 
468 #ifdef WITH_OPENSSL
469 	evplen = EVP_CIPHER_CTX_iv_length(cc->evp);
470 	if (evplen == 0)
471 		return 0;
472 	else if (evplen < 0)
473 		return SSH_ERR_LIBCRYPTO_ERROR;
474 	if ((u_int)evplen != len)
475 		return SSH_ERR_INVALID_ARGUMENT;
476 #ifndef OPENSSL_HAVE_EVPCTR
477 	if (c->evptype == evp_aes_128_ctr)
478 		ssh_aes_ctr_iv(cc->evp, 0, iv, len);
479 	else
480 #endif
481 	if (cipher_authlen(c)) {
482 		if (!EVP_CIPHER_CTX_ctrl(cc->evp, EVP_CTRL_GCM_IV_GEN,
483 		   len, iv))
484 		       return SSH_ERR_LIBCRYPTO_ERROR;
485 	} else
486 		memcpy(iv, cc->evp->iv, len);
487 #endif
488 	return 0;
489 }
490 
491 int
492 cipher_set_keyiv(struct sshcipher_ctx *cc, const u_char *iv)
493 {
494 #ifdef WITH_OPENSSL
495 	const struct sshcipher *c = cc->cipher;
496 	int evplen = 0;
497 #endif
498 
499 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0)
500 		return 0;
501 	if ((cc->cipher->flags & CFLAG_NONE) != 0)
502 		return 0;
503 
504 #ifdef WITH_OPENSSL
505 	evplen = EVP_CIPHER_CTX_iv_length(cc->evp);
506 	if (evplen <= 0)
507 		return SSH_ERR_LIBCRYPTO_ERROR;
508 #ifndef OPENSSL_HAVE_EVPCTR
509 	/* XXX iv arg is const, but ssh_aes_ctr_iv isn't */
510 	if (c->evptype == evp_aes_128_ctr)
511 		ssh_aes_ctr_iv(cc->evp, 1, (u_char *)iv, evplen);
512 	else
513 #endif
514 	if (cipher_authlen(c)) {
515 		/* XXX iv arg is const, but EVP_CIPHER_CTX_ctrl isn't */
516 		if (!EVP_CIPHER_CTX_ctrl(cc->evp,
517 		    EVP_CTRL_GCM_SET_IV_FIXED, -1, (void *)iv))
518 			return SSH_ERR_LIBCRYPTO_ERROR;
519 	} else
520 		memcpy(cc->evp->iv, iv, evplen);
521 #endif
522 	return 0;
523 }
524 
525 #ifdef WITH_OPENSSL
526 #define EVP_X_STATE(evp)	(evp)->cipher_data
527 #define EVP_X_STATE_LEN(evp)	(evp)->cipher->ctx_size
528 #endif
529 
530 int
531 cipher_get_keycontext(const struct sshcipher_ctx *cc, u_char *dat)
532 {
533 #if defined(WITH_OPENSSL) && !defined(OPENSSL_NO_RC4)
534 	const struct sshcipher *c = cc->cipher;
535 	int plen = 0;
536 
537 	if (c->evptype == EVP_rc4) {
538 		plen = EVP_X_STATE_LEN(cc->evp);
539 		if (dat == NULL)
540 			return (plen);
541 		memcpy(dat, EVP_X_STATE(cc->evp), plen);
542 	}
543 	return (plen);
544 #else
545 	return 0;
546 #endif
547 }
548 
549 void
550 cipher_set_keycontext(struct sshcipher_ctx *cc, const u_char *dat)
551 {
552 #if defined(WITH_OPENSSL) && !defined(OPENSSL_NO_RC4)
553 	const struct sshcipher *c = cc->cipher;
554 	int plen;
555 
556 	if (c->evptype == EVP_rc4) {
557 		plen = EVP_X_STATE_LEN(cc->evp);
558 		memcpy(EVP_X_STATE(cc->evp), dat, plen);
559 	}
560 #endif
561 }
562