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