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