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