xref: /openbsd-src/usr.bin/ssh/cipher.c (revision 91f110e064cd7c194e59e019b83bb7496c1c84d4)
1 /* $OpenBSD: cipher.c,v 1.97 2014/02/07 06:55:54 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 "xmalloc.h"
45 #include "log.h"
46 #include "misc.h"
47 #include "cipher.h"
48 #include "buffer.h"
49 #include "digest.h"
50 
51 extern const EVP_CIPHER *evp_ssh1_bf(void);
52 extern const EVP_CIPHER *evp_ssh1_3des(void);
53 extern void ssh1_3des_iv(EVP_CIPHER_CTX *, int, u_char *, int);
54 
55 struct Cipher {
56 	char	*name;
57 	int	number;		/* for ssh1 only */
58 	u_int	block_size;
59 	u_int	key_len;
60 	u_int	iv_len;		/* defaults to block_size */
61 	u_int	auth_len;
62 	u_int	discard_len;
63 	u_int	flags;
64 #define CFLAG_CBC		(1<<0)
65 #define CFLAG_CHACHAPOLY	(1<<1)
66 	const EVP_CIPHER	*(*evptype)(void);
67 };
68 
69 static const struct Cipher ciphers[] = {
70 	{ "none",	SSH_CIPHER_NONE, 8, 0, 0, 0, 0, 0, EVP_enc_null },
71 	{ "des",	SSH_CIPHER_DES, 8, 8, 0, 0, 0, 1, EVP_des_cbc },
72 	{ "3des",	SSH_CIPHER_3DES, 8, 16, 0, 0, 0, 1, evp_ssh1_3des },
73 	{ "blowfish",	SSH_CIPHER_BLOWFISH, 8, 32, 0, 0, 0, 1, evp_ssh1_bf },
74 
75 	{ "3des-cbc",	SSH_CIPHER_SSH2, 8, 24, 0, 0, 0, 1, EVP_des_ede3_cbc },
76 	{ "blowfish-cbc",
77 			SSH_CIPHER_SSH2, 8, 16, 0, 0, 0, 1, EVP_bf_cbc },
78 	{ "cast128-cbc",
79 			SSH_CIPHER_SSH2, 8, 16, 0, 0, 0, 1, EVP_cast5_cbc },
80 	{ "arcfour",	SSH_CIPHER_SSH2, 8, 16, 0, 0, 0, 0, EVP_rc4 },
81 	{ "arcfour128",	SSH_CIPHER_SSH2, 8, 16, 0, 0, 1536, 0, EVP_rc4 },
82 	{ "arcfour256",	SSH_CIPHER_SSH2, 8, 32, 0, 0, 1536, 0, EVP_rc4 },
83 	{ "aes128-cbc",	SSH_CIPHER_SSH2, 16, 16, 0, 0, 0, 1, EVP_aes_128_cbc },
84 	{ "aes192-cbc",	SSH_CIPHER_SSH2, 16, 24, 0, 0, 0, 1, EVP_aes_192_cbc },
85 	{ "aes256-cbc",	SSH_CIPHER_SSH2, 16, 32, 0, 0, 0, 1, EVP_aes_256_cbc },
86 	{ "rijndael-cbc@lysator.liu.se",
87 			SSH_CIPHER_SSH2, 16, 32, 0, 0, 0, 1, EVP_aes_256_cbc },
88 	{ "aes128-ctr",	SSH_CIPHER_SSH2, 16, 16, 0, 0, 0, 0, EVP_aes_128_ctr },
89 	{ "aes192-ctr",	SSH_CIPHER_SSH2, 16, 24, 0, 0, 0, 0, EVP_aes_192_ctr },
90 	{ "aes256-ctr",	SSH_CIPHER_SSH2, 16, 32, 0, 0, 0, 0, EVP_aes_256_ctr },
91 	{ "aes128-gcm@openssh.com",
92 			SSH_CIPHER_SSH2, 16, 16, 12, 16, 0, 0, EVP_aes_128_gcm },
93 	{ "aes256-gcm@openssh.com",
94 			SSH_CIPHER_SSH2, 16, 32, 12, 16, 0, 0, EVP_aes_256_gcm },
95 	{ "chacha20-poly1305@openssh.com",
96 			SSH_CIPHER_SSH2, 8, 64, 0, 16, 0, CFLAG_CHACHAPOLY, NULL },
97 
98 	{ NULL,		SSH_CIPHER_INVALID, 0, 0, 0, 0, 0, 0, NULL }
99 };
100 
101 /*--*/
102 
103 /* Returns a list of supported ciphers separated by the specified char. */
104 char *
105 cipher_alg_list(char sep, int auth_only)
106 {
107 	char *ret = NULL;
108 	size_t nlen, rlen = 0;
109 	const Cipher *c;
110 
111 	for (c = ciphers; c->name != NULL; c++) {
112 		if (c->number != SSH_CIPHER_SSH2)
113 			continue;
114 		if (auth_only && c->auth_len == 0)
115 			continue;
116 		if (ret != NULL)
117 			ret[rlen++] = sep;
118 		nlen = strlen(c->name);
119 		ret = xrealloc(ret, 1, rlen + nlen + 2);
120 		memcpy(ret + rlen, c->name, nlen + 1);
121 		rlen += nlen;
122 	}
123 	return ret;
124 }
125 
126 u_int
127 cipher_blocksize(const Cipher *c)
128 {
129 	return (c->block_size);
130 }
131 
132 u_int
133 cipher_keylen(const Cipher *c)
134 {
135 	return (c->key_len);
136 }
137 
138 u_int
139 cipher_seclen(const Cipher *c)
140 {
141 	if (strcmp("3des-cbc", c->name) == 0)
142 		return 14;
143 	return cipher_keylen(c);
144 }
145 
146 u_int
147 cipher_authlen(const Cipher *c)
148 {
149 	return (c->auth_len);
150 }
151 
152 u_int
153 cipher_ivlen(const Cipher *c)
154 {
155 	/*
156 	 * Default is cipher block size, except for chacha20+poly1305 that
157 	 * needs no IV. XXX make iv_len == -1 default?
158 	 */
159 	return (c->iv_len != 0 || (c->flags & CFLAG_CHACHAPOLY) != 0) ?
160 	    c->iv_len : c->block_size;
161 }
162 
163 u_int
164 cipher_get_number(const Cipher *c)
165 {
166 	return (c->number);
167 }
168 
169 u_int
170 cipher_is_cbc(const Cipher *c)
171 {
172 	return (c->flags & CFLAG_CBC) != 0;
173 }
174 
175 u_int
176 cipher_mask_ssh1(int client)
177 {
178 	u_int mask = 0;
179 	mask |= 1 << SSH_CIPHER_3DES;		/* Mandatory */
180 	mask |= 1 << SSH_CIPHER_BLOWFISH;
181 	if (client) {
182 		mask |= 1 << SSH_CIPHER_DES;
183 	}
184 	return mask;
185 }
186 
187 const Cipher *
188 cipher_by_name(const char *name)
189 {
190 	const Cipher *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 const Cipher *
198 cipher_by_number(int id)
199 {
200 	const Cipher *c;
201 	for (c = ciphers; c->name != NULL; c++)
202 		if (c->number == id)
203 			return c;
204 	return NULL;
205 }
206 
207 #define	CIPHER_SEP	","
208 int
209 ciphers_valid(const char *names)
210 {
211 	const Cipher *c;
212 	char *cipher_list, *cp;
213 	char *p;
214 
215 	if (names == NULL || strcmp(names, "") == 0)
216 		return 0;
217 	cipher_list = cp = xstrdup(names);
218 	for ((p = strsep(&cp, CIPHER_SEP)); p && *p != '\0';
219 	    (p = strsep(&cp, CIPHER_SEP))) {
220 		c = cipher_by_name(p);
221 		if (c == NULL || c->number != SSH_CIPHER_SSH2) {
222 			debug("bad cipher %s [%s]", p, names);
223 			free(cipher_list);
224 			return 0;
225 		}
226 	}
227 	debug3("ciphers ok: [%s]", names);
228 	free(cipher_list);
229 	return 1;
230 }
231 
232 /*
233  * Parses the name of the cipher.  Returns the number of the corresponding
234  * cipher, or -1 on error.
235  */
236 
237 int
238 cipher_number(const char *name)
239 {
240 	const Cipher *c;
241 	if (name == NULL)
242 		return -1;
243 	for (c = ciphers; c->name != NULL; c++)
244 		if (strcasecmp(c->name, name) == 0)
245 			return c->number;
246 	return -1;
247 }
248 
249 char *
250 cipher_name(int id)
251 {
252 	const Cipher *c = cipher_by_number(id);
253 	return (c==NULL) ? "<unknown>" : c->name;
254 }
255 
256 void
257 cipher_init(CipherContext *cc, const Cipher *cipher,
258     const u_char *key, u_int keylen, const u_char *iv, u_int ivlen,
259     int do_encrypt)
260 {
261 	static int dowarn = 1;
262 	const EVP_CIPHER *type;
263 	int klen;
264 	u_char *junk, *discard;
265 
266 	if (cipher->number == SSH_CIPHER_DES) {
267 		if (dowarn) {
268 			error("Warning: use of DES is strongly discouraged "
269 			    "due to cryptographic weaknesses");
270 			dowarn = 0;
271 		}
272 		if (keylen > 8)
273 			keylen = 8;
274 	}
275 	cc->plaintext = (cipher->number == SSH_CIPHER_NONE);
276 	cc->encrypt = do_encrypt;
277 
278 	if (keylen < cipher->key_len)
279 		fatal("cipher_init: key length %d is insufficient for %s.",
280 		    keylen, cipher->name);
281 	if (iv != NULL && ivlen < cipher_ivlen(cipher))
282 		fatal("cipher_init: iv length %d is insufficient for %s.",
283 		    ivlen, cipher->name);
284 	cc->cipher = cipher;
285 
286 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0) {
287 		chachapoly_init(&cc->cp_ctx, key, keylen);
288 		return;
289 	}
290 	type = (*cipher->evptype)();
291 	EVP_CIPHER_CTX_init(&cc->evp);
292 	if (EVP_CipherInit(&cc->evp, type, NULL, (u_char *)iv,
293 	    (do_encrypt == CIPHER_ENCRYPT)) == 0)
294 		fatal("cipher_init: EVP_CipherInit failed for %s",
295 		    cipher->name);
296 	if (cipher_authlen(cipher) &&
297 	    !EVP_CIPHER_CTX_ctrl(&cc->evp, EVP_CTRL_GCM_SET_IV_FIXED,
298 	    -1, (u_char *)iv))
299 		fatal("cipher_init: EVP_CTRL_GCM_SET_IV_FIXED failed for %s",
300 		    cipher->name);
301 	klen = EVP_CIPHER_CTX_key_length(&cc->evp);
302 	if (klen > 0 && keylen != (u_int)klen) {
303 		debug2("cipher_init: set keylen (%d -> %d)", klen, keylen);
304 		if (EVP_CIPHER_CTX_set_key_length(&cc->evp, keylen) == 0)
305 			fatal("cipher_init: set keylen failed (%d -> %d)",
306 			    klen, keylen);
307 	}
308 	if (EVP_CipherInit(&cc->evp, NULL, (u_char *)key, NULL, -1) == 0)
309 		fatal("cipher_init: EVP_CipherInit: set key failed for %s",
310 		    cipher->name);
311 
312 	if (cipher->discard_len > 0) {
313 		junk = xmalloc(cipher->discard_len);
314 		discard = xmalloc(cipher->discard_len);
315 		if (EVP_Cipher(&cc->evp, discard, junk,
316 		    cipher->discard_len) == 0)
317 			fatal("evp_crypt: EVP_Cipher failed during discard");
318 		explicit_bzero(discard, cipher->discard_len);
319 		free(junk);
320 		free(discard);
321 	}
322 }
323 
324 /*
325  * cipher_crypt() operates as following:
326  * Copy 'aadlen' bytes (without en/decryption) from 'src' to 'dest'.
327  * Theses bytes are treated as additional authenticated data for
328  * authenticated encryption modes.
329  * En/Decrypt 'len' bytes at offset 'aadlen' from 'src' to 'dest'.
330  * Use 'authlen' bytes at offset 'len'+'aadlen' as the authentication tag.
331  * This tag is written on encryption and verified on decryption.
332  * Both 'aadlen' and 'authlen' can be set to 0.
333  * cipher_crypt() returns 0 on success and -1 if the decryption integrity
334  * check fails.
335  */
336 int
337 cipher_crypt(CipherContext *cc, u_int seqnr, u_char *dest, const u_char *src,
338     u_int len, u_int aadlen, u_int authlen)
339 {
340 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0)
341 		return chachapoly_crypt(&cc->cp_ctx, seqnr, dest, src, len,
342 		    aadlen, authlen, cc->encrypt);
343 	if (authlen) {
344 		u_char lastiv[1];
345 
346 		if (authlen != cipher_authlen(cc->cipher))
347 			fatal("%s: authlen mismatch %d", __func__, authlen);
348 		/* increment IV */
349 		if (!EVP_CIPHER_CTX_ctrl(&cc->evp, EVP_CTRL_GCM_IV_GEN,
350 		    1, lastiv))
351 			fatal("%s: EVP_CTRL_GCM_IV_GEN", __func__);
352 		/* set tag on decyption */
353 		if (!cc->encrypt &&
354 		    !EVP_CIPHER_CTX_ctrl(&cc->evp, EVP_CTRL_GCM_SET_TAG,
355 		    authlen, (u_char *)src + aadlen + len))
356 			fatal("%s: EVP_CTRL_GCM_SET_TAG", __func__);
357 	}
358 	if (aadlen) {
359 		if (authlen &&
360 		    EVP_Cipher(&cc->evp, NULL, (u_char *)src, aadlen) < 0)
361 			fatal("%s: EVP_Cipher(aad) failed", __func__);
362 		memcpy(dest, src, aadlen);
363 	}
364 	if (len % cc->cipher->block_size)
365 		fatal("%s: bad plaintext length %d", __func__, len);
366 	if (EVP_Cipher(&cc->evp, dest + aadlen, (u_char *)src + aadlen,
367 	    len) < 0)
368 		fatal("%s: EVP_Cipher failed", __func__);
369 	if (authlen) {
370 		/* compute tag (on encrypt) or verify tag (on decrypt) */
371 		if (EVP_Cipher(&cc->evp, NULL, NULL, 0) < 0) {
372 			if (cc->encrypt)
373 				fatal("%s: EVP_Cipher(final) failed", __func__);
374 			else
375 				return -1;
376 		}
377 		if (cc->encrypt &&
378 		    !EVP_CIPHER_CTX_ctrl(&cc->evp, EVP_CTRL_GCM_GET_TAG,
379 		    authlen, dest + aadlen + len))
380 			fatal("%s: EVP_CTRL_GCM_GET_TAG", __func__);
381 	}
382 	return 0;
383 }
384 
385 /* Extract the packet length, including any decryption necessary beforehand */
386 int
387 cipher_get_length(CipherContext *cc, u_int *plenp, u_int seqnr,
388     const u_char *cp, u_int len)
389 {
390 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0)
391 		return chachapoly_get_length(&cc->cp_ctx, plenp, seqnr,
392 		    cp, len);
393 	if (len < 4)
394 		return -1;
395 	*plenp = get_u32(cp);
396 	return 0;
397 }
398 
399 void
400 cipher_cleanup(CipherContext *cc)
401 {
402 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0)
403 		explicit_bzero(&cc->cp_ctx, sizeof(cc->cp_ctx));
404 	else if (EVP_CIPHER_CTX_cleanup(&cc->evp) == 0)
405 		error("cipher_cleanup: EVP_CIPHER_CTX_cleanup failed");
406 }
407 
408 /*
409  * Selects the cipher, and keys if by computing the MD5 checksum of the
410  * passphrase and using the resulting 16 bytes as the key.
411  */
412 
413 void
414 cipher_set_key_string(CipherContext *cc, const Cipher *cipher,
415     const char *passphrase, int do_encrypt)
416 {
417 	u_char digest[16];
418 
419 	if (ssh_digest_memory(SSH_DIGEST_MD5, passphrase, strlen(passphrase),
420 	    digest, sizeof(digest)) < 0)
421 		fatal("%s: md5 failed", __func__);
422 
423 	cipher_init(cc, cipher, digest, 16, NULL, 0, do_encrypt);
424 
425 	explicit_bzero(digest, sizeof(digest));
426 }
427 
428 /*
429  * Exports an IV from the CipherContext required to export the key
430  * state back from the unprivileged child to the privileged parent
431  * process.
432  */
433 
434 int
435 cipher_get_keyiv_len(const CipherContext *cc)
436 {
437 	const Cipher *c = cc->cipher;
438 	int ivlen;
439 
440 	if (c->number == SSH_CIPHER_3DES)
441 		ivlen = 24;
442 	else if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0)
443 		ivlen = 0;
444 	else
445 		ivlen = EVP_CIPHER_CTX_iv_length(&cc->evp);
446 	return (ivlen);
447 }
448 
449 void
450 cipher_get_keyiv(CipherContext *cc, u_char *iv, u_int len)
451 {
452 	const Cipher *c = cc->cipher;
453 	int evplen;
454 
455 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0) {
456 		if (len != 0)
457 			fatal("%s: wrong iv length %d != %d", __func__, len, 0);
458 		return;
459 	}
460 
461 	switch (c->number) {
462 	case SSH_CIPHER_SSH2:
463 	case SSH_CIPHER_DES:
464 	case SSH_CIPHER_BLOWFISH:
465 		evplen = EVP_CIPHER_CTX_iv_length(&cc->evp);
466 		if (evplen <= 0)
467 			return;
468 		if ((u_int)evplen != len)
469 			fatal("%s: wrong iv length %d != %d", __func__,
470 			    evplen, len);
471 		if (cipher_authlen(c)) {
472 			if (!EVP_CIPHER_CTX_ctrl(&cc->evp, EVP_CTRL_GCM_IV_GEN,
473 			   len, iv))
474 			       fatal("%s: EVP_CTRL_GCM_IV_GEN", __func__);
475 		} else
476 			memcpy(iv, cc->evp.iv, len);
477 		break;
478 	case SSH_CIPHER_3DES:
479 		ssh1_3des_iv(&cc->evp, 0, iv, 24);
480 		break;
481 	default:
482 		fatal("%s: bad cipher %d", __func__, c->number);
483 	}
484 }
485 
486 void
487 cipher_set_keyiv(CipherContext *cc, u_char *iv)
488 {
489 	const Cipher *c = cc->cipher;
490 	int evplen = 0;
491 
492 	if ((cc->cipher->flags & CFLAG_CHACHAPOLY) != 0)
493 		return;
494 
495 	switch (c->number) {
496 	case SSH_CIPHER_SSH2:
497 	case SSH_CIPHER_DES:
498 	case SSH_CIPHER_BLOWFISH:
499 		evplen = EVP_CIPHER_CTX_iv_length(&cc->evp);
500 		if (evplen == 0)
501 			return;
502 		if (cipher_authlen(c)) {
503 			if (!EVP_CIPHER_CTX_ctrl(&cc->evp,
504 			    EVP_CTRL_GCM_SET_IV_FIXED, -1, iv))
505 				fatal("%s: EVP_CTRL_GCM_SET_IV_FIXED failed",
506 				    __func__);
507 		} else
508 			memcpy(cc->evp.iv, iv, evplen);
509 		break;
510 	case SSH_CIPHER_3DES:
511 		ssh1_3des_iv(&cc->evp, 1, iv, 24);
512 		break;
513 	default:
514 		fatal("%s: bad cipher %d", __func__, c->number);
515 	}
516 }
517 
518 #define EVP_X_STATE(evp)	(evp).cipher_data
519 #define EVP_X_STATE_LEN(evp)	(evp).cipher->ctx_size
520 
521 int
522 cipher_get_keycontext(const CipherContext *cc, u_char *dat)
523 {
524 	const Cipher *c = cc->cipher;
525 	int plen = 0;
526 
527 	if (c->evptype == EVP_rc4) {
528 		plen = EVP_X_STATE_LEN(cc->evp);
529 		if (dat == NULL)
530 			return (plen);
531 		memcpy(dat, EVP_X_STATE(cc->evp), plen);
532 	}
533 	return (plen);
534 }
535 
536 void
537 cipher_set_keycontext(CipherContext *cc, u_char *dat)
538 {
539 	const Cipher *c = cc->cipher;
540 	int plen;
541 
542 	if (c->evptype == EVP_rc4) {
543 		plen = EVP_X_STATE_LEN(cc->evp);
544 		memcpy(EVP_X_STATE(cc->evp), dat, plen);
545 	}
546 }
547