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