xref: /openbsd-src/usr.bin/ssh/cipher.c (revision 8e0c768258d4632c51876b4397034bc3152bf8db)
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 <sys/types.h>
39 
40 #include <string.h>
41 #include <stdarg.h>
42 #include <stdio.h>
43 
44 #include "cipher.h"
45 #include "misc.h"
46 #include "sshbuf.h"
47 #include "ssherr.h"
48 #include "digest.h"
49 
50 #ifndef WITH_OPENSSL
51 #define EVP_CIPHER_CTX void
52 #endif
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 	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) != 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, (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, (u_char *)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 	if (EVP_CipherInit(cc->evp, NULL, (u_char *)key, NULL, -1) == 0) {
298 		ret = SSH_ERR_LIBCRYPTO_ERROR;
299 		goto out;
300 	}
301 	ret = 0;
302 #endif /* WITH_OPENSSL */
303  out:
304 	if (ret == 0) {
305 		/* success */
306 		*ccp = cc;
307 	} else {
308 		if (cc != NULL) {
309 #ifdef WITH_OPENSSL
310 			EVP_CIPHER_CTX_free(cc->evp);
311 #endif /* WITH_OPENSSL */
312 			explicit_bzero(cc, sizeof(*cc));
313 			free(cc);
314 		}
315 	}
316 	return ret;
317 }
318 
319 /*
320  * cipher_crypt() operates as following:
321  * Copy 'aadlen' bytes (without en/decryption) from 'src' to 'dest'.
322  * Theses bytes are treated as additional authenticated data for
323  * authenticated encryption modes.
324  * En/Decrypt 'len' bytes at offset 'aadlen' from 'src' to 'dest'.
325  * Use 'authlen' bytes at offset 'len'+'aadlen' as the authentication tag.
326  * This tag is written on encryption and verified on decryption.
327  * Both 'aadlen' and 'authlen' can be set to 0.
328  */
329 int
330 cipher_crypt(struct sshcipher_ctx *cc, u_int seqnr, u_char *dest,
331    const u_char *src, u_int len, u_int aadlen, u_int authlen)
332 {
333 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0) {
334 		return chachapoly_crypt(&cc->cp_ctx, seqnr, dest, src,
335 		    len, aadlen, authlen, cc->encrypt);
336 	}
337 	if ((cc->cipher->flags & CFLAG_NONE) != 0) {
338 		memcpy(dest, src, aadlen + len);
339 		return 0;
340 	}
341 #ifndef WITH_OPENSSL
342 	if ((cc->cipher->flags & CFLAG_AESCTR) != 0) {
343 		if (aadlen)
344 			memcpy(dest, src, aadlen);
345 		aesctr_encrypt_bytes(&cc->ac_ctx, src + aadlen,
346 		    dest + aadlen, len);
347 		return 0;
348 	}
349 	return SSH_ERR_INVALID_ARGUMENT;
350 #else
351 	if (authlen) {
352 		u_char lastiv[1];
353 
354 		if (authlen != cipher_authlen(cc->cipher))
355 			return SSH_ERR_INVALID_ARGUMENT;
356 		/* increment IV */
357 		if (!EVP_CIPHER_CTX_ctrl(cc->evp, EVP_CTRL_GCM_IV_GEN,
358 		    1, lastiv))
359 			return SSH_ERR_LIBCRYPTO_ERROR;
360 		/* set tag on decyption */
361 		if (!cc->encrypt &&
362 		    !EVP_CIPHER_CTX_ctrl(cc->evp, EVP_CTRL_GCM_SET_TAG,
363 		    authlen, (u_char *)src + aadlen + len))
364 			return SSH_ERR_LIBCRYPTO_ERROR;
365 	}
366 	if (aadlen) {
367 		if (authlen &&
368 		    EVP_Cipher(cc->evp, NULL, (u_char *)src, aadlen) < 0)
369 			return SSH_ERR_LIBCRYPTO_ERROR;
370 		memcpy(dest, src, aadlen);
371 	}
372 	if (len % cc->cipher->block_size)
373 		return SSH_ERR_INVALID_ARGUMENT;
374 	if (EVP_Cipher(cc->evp, dest + aadlen, (u_char *)src + aadlen,
375 	    len) < 0)
376 		return SSH_ERR_LIBCRYPTO_ERROR;
377 	if (authlen) {
378 		/* compute tag (on encrypt) or verify tag (on decrypt) */
379 		if (EVP_Cipher(cc->evp, NULL, NULL, 0) < 0)
380 			return cc->encrypt ?
381 			    SSH_ERR_LIBCRYPTO_ERROR : SSH_ERR_MAC_INVALID;
382 		if (cc->encrypt &&
383 		    !EVP_CIPHER_CTX_ctrl(cc->evp, EVP_CTRL_GCM_GET_TAG,
384 		    authlen, dest + aadlen + len))
385 			return SSH_ERR_LIBCRYPTO_ERROR;
386 	}
387 	return 0;
388 #endif
389 }
390 
391 /* Extract the packet length, including any decryption necessary beforehand */
392 int
393 cipher_get_length(struct sshcipher_ctx *cc, u_int *plenp, u_int seqnr,
394     const u_char *cp, u_int len)
395 {
396 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0)
397 		return chachapoly_get_length(&cc->cp_ctx, plenp, seqnr,
398 		    cp, len);
399 	if (len < 4)
400 		return SSH_ERR_MESSAGE_INCOMPLETE;
401 	*plenp = PEEK_U32(cp);
402 	return 0;
403 }
404 
405 void
406 cipher_free(struct sshcipher_ctx *cc)
407 {
408 	if (cc == NULL)
409 		return;
410 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0)
411 		explicit_bzero(&cc->cp_ctx, sizeof(cc->cp_ctx));
412 	else if ((cc->cipher->flags & CFLAG_AESCTR) != 0)
413 		explicit_bzero(&cc->ac_ctx, sizeof(cc->ac_ctx));
414 #ifdef WITH_OPENSSL
415 	EVP_CIPHER_CTX_free(cc->evp);
416 	cc->evp = NULL;
417 #endif
418 	explicit_bzero(cc, sizeof(*cc));
419 	free(cc);
420 }
421 
422 /*
423  * Exports an IV from the sshcipher_ctx required to export the key
424  * state back from the unprivileged child to the privileged parent
425  * process.
426  */
427 int
428 cipher_get_keyiv_len(const struct sshcipher_ctx *cc)
429 {
430 	const struct sshcipher *c = cc->cipher;
431 
432 	if ((c->flags & CFLAG_CHACHAPOLY) != 0)
433 		return 0;
434 	else if ((c->flags & CFLAG_AESCTR) != 0)
435 		return sizeof(cc->ac_ctx.ctr);
436 #ifdef WITH_OPENSSL
437 	return EVP_CIPHER_CTX_iv_length(cc->evp);
438 #else
439 	return 0;
440 #endif
441 }
442 
443 int
444 cipher_get_keyiv(struct sshcipher_ctx *cc, u_char *iv, size_t len)
445 {
446 #ifdef WITH_OPENSSL
447 	const struct sshcipher *c = cc->cipher;
448 	int evplen;
449 #endif
450 
451 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0) {
452 		if (len != 0)
453 			return SSH_ERR_INVALID_ARGUMENT;
454 		return 0;
455 	}
456 	if ((cc->cipher->flags & CFLAG_AESCTR) != 0) {
457 		if (len != sizeof(cc->ac_ctx.ctr))
458 			return SSH_ERR_INVALID_ARGUMENT;
459 		memcpy(iv, cc->ac_ctx.ctr, len);
460 		return 0;
461 	}
462 	if ((cc->cipher->flags & CFLAG_NONE) != 0)
463 		return 0;
464 
465 #ifdef WITH_OPENSSL
466 	evplen = EVP_CIPHER_CTX_iv_length(cc->evp);
467 	if (evplen == 0)
468 		return 0;
469 	else if (evplen < 0)
470 		return SSH_ERR_LIBCRYPTO_ERROR;
471 	if ((size_t)evplen != len)
472 		return SSH_ERR_INVALID_ARGUMENT;
473 	if (cipher_authlen(c)) {
474 		if (!EVP_CIPHER_CTX_ctrl(cc->evp, EVP_CTRL_GCM_IV_GEN,
475 		   len, iv))
476 		       return SSH_ERR_LIBCRYPTO_ERROR;
477 	} else if (!EVP_CIPHER_CTX_get_iv(cc->evp, iv, len))
478 	       return SSH_ERR_LIBCRYPTO_ERROR;
479 #endif
480 	return 0;
481 }
482 
483 int
484 cipher_set_keyiv(struct sshcipher_ctx *cc, const u_char *iv, size_t len)
485 {
486 #ifdef WITH_OPENSSL
487 	const struct sshcipher *c = cc->cipher;
488 	int evplen = 0;
489 #endif
490 
491 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0)
492 		return 0;
493 	if ((cc->cipher->flags & CFLAG_NONE) != 0)
494 		return 0;
495 
496 #ifdef WITH_OPENSSL
497 	evplen = EVP_CIPHER_CTX_iv_length(cc->evp);
498 	if (evplen <= 0)
499 		return SSH_ERR_LIBCRYPTO_ERROR;
500 	if ((size_t)evplen != len)
501 		return SSH_ERR_INVALID_ARGUMENT;
502 	if (cipher_authlen(c)) {
503 		/* XXX iv arg is const, but EVP_CIPHER_CTX_ctrl isn't */
504 		if (!EVP_CIPHER_CTX_ctrl(cc->evp,
505 		    EVP_CTRL_GCM_SET_IV_FIXED, -1, (void *)iv))
506 			return SSH_ERR_LIBCRYPTO_ERROR;
507 	} else if (!EVP_CIPHER_CTX_set_iv(cc->evp, iv, evplen))
508 		return SSH_ERR_LIBCRYPTO_ERROR;
509 #endif
510 	return 0;
511 }
512 
513