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