1/*-
2 * Copyright (c) 1991, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#include <config.h>
35
36RCSID("$Id: enc_des.c 14681 2005-03-23 16:19:31Z lha $");
37
38#if	defined(AUTHENTICATION) && defined(ENCRYPTION) && defined(DES_ENCRYPTION)
39#include <arpa/telnet.h>
40#include <stdio.h>
41#ifdef	__STDC__
42#include <stdlib.h>
43#include <string.h>
44#endif
45#include <roken.h>
46#ifdef SOCKS
47#include <socks.h>
48#endif
49
50#include "encrypt.h"
51#include "misc-proto.h"
52
53#include "crypto-headers.h"
54
55extern int encrypt_debug_mode;
56
57#define	CFB	0
58#define	OFB	1
59
60#define	NO_SEND_IV	1
61#define	NO_RECV_IV	2
62#define	NO_KEYID	4
63#define	IN_PROGRESS	(NO_SEND_IV|NO_RECV_IV|NO_KEYID)
64#define	SUCCESS		0
65#define	FAILED		-1
66
67
68struct stinfo {
69  DES_cblock	str_output;
70  DES_cblock	str_feed;
71  DES_cblock	str_iv;
72  DES_cblock	str_ikey;
73  DES_key_schedule str_sched;
74  int		str_index;
75  int		str_flagshift;
76};
77
78struct fb {
79	DES_cblock krbdes_key;
80	DES_key_schedule krbdes_sched;
81	DES_cblock temp_feed;
82	unsigned char fb_feed[64];
83	int need_start;
84	int state[2];
85	int keyid[2];
86	int once;
87	struct stinfo streams[2];
88};
89
90static struct fb fb[2];
91
92struct keyidlist {
93	char	*keyid;
94	int	keyidlen;
95	char	*key;
96	int	keylen;
97	int	flags;
98} keyidlist [] = {
99	{ "\0", 1, 0, 0, 0 },		/* default key of zero */
100	{ 0, 0, 0, 0, 0 }
101};
102
103#define	KEYFLAG_MASK	03
104
105#define	KEYFLAG_NOINIT	00
106#define	KEYFLAG_INIT	01
107#define	KEYFLAG_OK	02
108#define	KEYFLAG_BAD	03
109
110#define	KEYFLAG_SHIFT	2
111
112#define	SHIFT_VAL(a,b)	(KEYFLAG_SHIFT*((a)+((b)*2)))
113
114#define	FB64_IV		1
115#define	FB64_IV_OK	2
116#define	FB64_IV_BAD	3
117
118
119void fb64_stream_iv (DES_cblock, struct stinfo *);
120void fb64_init (struct fb *);
121static int fb64_start (struct fb *, int, int);
122int fb64_is (unsigned char *, int, struct fb *);
123int fb64_reply (unsigned char *, int, struct fb *);
124static void fb64_session (Session_Key *, int, struct fb *);
125void fb64_stream_key (DES_cblock, struct stinfo *);
126int fb64_keyid (int, unsigned char *, int *, struct fb *);
127void fb64_printsub(unsigned char *, int ,
128		   unsigned char *, int , char *);
129
130void cfb64_init(int server)
131{
132	fb64_init(&fb[CFB]);
133	fb[CFB].fb_feed[4] = ENCTYPE_DES_CFB64;
134	fb[CFB].streams[0].str_flagshift = SHIFT_VAL(0, CFB);
135	fb[CFB].streams[1].str_flagshift = SHIFT_VAL(1, CFB);
136}
137
138
139void ofb64_init(int server)
140{
141	fb64_init(&fb[OFB]);
142	fb[OFB].fb_feed[4] = ENCTYPE_DES_OFB64;
143	fb[CFB].streams[0].str_flagshift = SHIFT_VAL(0, OFB);
144	fb[CFB].streams[1].str_flagshift = SHIFT_VAL(1, OFB);
145}
146
147void fb64_init(struct fb *fbp)
148{
149	memset(fbp,0, sizeof(*fbp));
150	fbp->state[0] = fbp->state[1] = FAILED;
151	fbp->fb_feed[0] = IAC;
152	fbp->fb_feed[1] = SB;
153	fbp->fb_feed[2] = TELOPT_ENCRYPT;
154	fbp->fb_feed[3] = ENCRYPT_IS;
155}
156
157/*
158 * Returns:
159 *	-1: some error.  Negotiation is done, encryption not ready.
160 *	 0: Successful, initial negotiation all done.
161 *	 1: successful, negotiation not done yet.
162 *	 2: Not yet.  Other things (like getting the key from
163 *	    Kerberos) have to happen before we can continue.
164 */
165int cfb64_start(int dir, int server)
166{
167	return(fb64_start(&fb[CFB], dir, server));
168}
169
170int ofb64_start(int dir, int server)
171{
172	return(fb64_start(&fb[OFB], dir, server));
173}
174
175static int fb64_start(struct fb *fbp, int dir, int server)
176{
177	int x;
178	unsigned char *p;
179	int state;
180
181	switch (dir) {
182	case DIR_DECRYPT:
183		/*
184		 * This is simply a request to have the other side
185		 * start output (our input).  He will negotiate an
186		 * IV so we need not look for it.
187		 */
188		state = fbp->state[dir-1];
189		if (state == FAILED)
190			state = IN_PROGRESS;
191		break;
192
193	case DIR_ENCRYPT:
194		state = fbp->state[dir-1];
195		if (state == FAILED)
196			state = IN_PROGRESS;
197		else if ((state & NO_SEND_IV) == 0) {
198			break;
199		}
200
201		if (!VALIDKEY(fbp->krbdes_key)) {
202		        fbp->need_start = 1;
203			break;
204		}
205
206		state &= ~NO_SEND_IV;
207		state |= NO_RECV_IV;
208		if (encrypt_debug_mode)
209			printf("Creating new feed\r\n");
210		/*
211		 * Create a random feed and send it over.
212		 */
213#ifndef OLD_DES_RANDOM_KEY
214		DES_random_key(&fbp->temp_feed);
215#else
216		/*
217		 * From des_cryp.man "If the des_check_key flag is non-zero,
218		 *  des_set_key will check that the key passed is
219		 *  of odd parity and is not a week or semi-weak key."
220		 */
221		do {
222			DES_random_key(fbp->temp_feed);
223			DES_set_odd_parity(fbp->temp_feed);
224		} while (DES_is_weak_key(fbp->temp_feed));
225#endif
226		DES_ecb_encrypt(&fbp->temp_feed,
227				&fbp->temp_feed,
228				&fbp->krbdes_sched, 1);
229		p = fbp->fb_feed + 3;
230		*p++ = ENCRYPT_IS;
231		p++;
232		*p++ = FB64_IV;
233		for (x = 0; x < sizeof(DES_cblock); ++x) {
234			if ((*p++ = fbp->temp_feed[x]) == IAC)
235				*p++ = IAC;
236		}
237		*p++ = IAC;
238		*p++ = SE;
239		printsub('>', &fbp->fb_feed[2], p - &fbp->fb_feed[2]);
240		telnet_net_write(fbp->fb_feed, p - fbp->fb_feed);
241		break;
242	default:
243		return(FAILED);
244	}
245	return(fbp->state[dir-1] = state);
246}
247
248/*
249 * Returns:
250 *	-1: some error.  Negotiation is done, encryption not ready.
251 *	 0: Successful, initial negotiation all done.
252 *	 1: successful, negotiation not done yet.
253 */
254
255int cfb64_is(unsigned char *data, int cnt)
256{
257	return(fb64_is(data, cnt, &fb[CFB]));
258}
259
260int ofb64_is(unsigned char *data, int cnt)
261{
262	return(fb64_is(data, cnt, &fb[OFB]));
263}
264
265
266int fb64_is(unsigned char *data, int cnt, struct fb *fbp)
267{
268	unsigned char *p;
269	int state = fbp->state[DIR_DECRYPT-1];
270
271	if (cnt-- < 1)
272		goto failure;
273
274	switch (*data++) {
275	case FB64_IV:
276		if (cnt != sizeof(DES_cblock)) {
277			if (encrypt_debug_mode)
278				printf("CFB64: initial vector failed on size\r\n");
279			state = FAILED;
280			goto failure;
281		}
282
283		if (encrypt_debug_mode)
284			printf("CFB64: initial vector received\r\n");
285
286		if (encrypt_debug_mode)
287			printf("Initializing Decrypt stream\r\n");
288
289		fb64_stream_iv(data, &fbp->streams[DIR_DECRYPT-1]);
290
291		p = fbp->fb_feed + 3;
292		*p++ = ENCRYPT_REPLY;
293		p++;
294		*p++ = FB64_IV_OK;
295		*p++ = IAC;
296		*p++ = SE;
297		printsub('>', &fbp->fb_feed[2], p - &fbp->fb_feed[2]);
298		telnet_net_write(fbp->fb_feed, p - fbp->fb_feed);
299
300		state = fbp->state[DIR_DECRYPT-1] = IN_PROGRESS;
301		break;
302
303	default:
304		if (encrypt_debug_mode) {
305			printf("Unknown option type: %d\r\n", *(data-1));
306			printd(data, cnt);
307			printf("\r\n");
308		}
309		/* FALL THROUGH */
310	failure:
311		/*
312		 * We failed.  Send an FB64_IV_BAD option
313		 * to the other side so it will know that
314		 * things failed.
315		 */
316		p = fbp->fb_feed + 3;
317		*p++ = ENCRYPT_REPLY;
318		p++;
319		*p++ = FB64_IV_BAD;
320		*p++ = IAC;
321		*p++ = SE;
322		printsub('>', &fbp->fb_feed[2], p - &fbp->fb_feed[2]);
323		telnet_net_write(fbp->fb_feed, p - fbp->fb_feed);
324
325		break;
326	}
327	return(fbp->state[DIR_DECRYPT-1] = state);
328}
329
330/*
331 * Returns:
332 *	-1: some error.  Negotiation is done, encryption not ready.
333 *	 0: Successful, initial negotiation all done.
334 *	 1: successful, negotiation not done yet.
335 */
336
337int cfb64_reply(unsigned char *data, int cnt)
338{
339	return(fb64_reply(data, cnt, &fb[CFB]));
340}
341
342int ofb64_reply(unsigned char *data, int cnt)
343{
344	return(fb64_reply(data, cnt, &fb[OFB]));
345}
346
347
348int fb64_reply(unsigned char *data, int cnt, struct fb *fbp)
349{
350	int state = fbp->state[DIR_ENCRYPT-1];
351
352	if (cnt-- < 1)
353		goto failure;
354
355	switch (*data++) {
356	case FB64_IV_OK:
357		fb64_stream_iv(fbp->temp_feed, &fbp->streams[DIR_ENCRYPT-1]);
358		if (state == FAILED)
359			state = IN_PROGRESS;
360		state &= ~NO_RECV_IV;
361		encrypt_send_keyid(DIR_ENCRYPT, (unsigned char *)"\0", 1, 1);
362		break;
363
364	case FB64_IV_BAD:
365		memset(fbp->temp_feed, 0, sizeof(DES_cblock));
366		fb64_stream_iv(fbp->temp_feed, &fbp->streams[DIR_ENCRYPT-1]);
367		state = FAILED;
368		break;
369
370	default:
371		if (encrypt_debug_mode) {
372			printf("Unknown option type: %d\r\n", data[-1]);
373			printd(data, cnt);
374			printf("\r\n");
375		}
376		/* FALL THROUGH */
377	failure:
378		state = FAILED;
379		break;
380	}
381	return(fbp->state[DIR_ENCRYPT-1] = state);
382}
383
384void cfb64_session(Session_Key *key, int server)
385{
386	fb64_session(key, server, &fb[CFB]);
387}
388
389void ofb64_session(Session_Key *key, int server)
390{
391	fb64_session(key, server, &fb[OFB]);
392}
393
394static void fb64_session(Session_Key *key, int server, struct fb *fbp)
395{
396
397	if (!key || key->type != SK_DES) {
398		if (encrypt_debug_mode)
399			printf("Can't set krbdes's session key (%d != %d)\r\n",
400				key ? key->type : -1, SK_DES);
401		return;
402	}
403	memcpy(fbp->krbdes_key, key->data, sizeof(DES_cblock));
404
405	fb64_stream_key(fbp->krbdes_key, &fbp->streams[DIR_ENCRYPT-1]);
406	fb64_stream_key(fbp->krbdes_key, &fbp->streams[DIR_DECRYPT-1]);
407
408	if (fbp->once == 0) {
409#if !defined(OLD_DES_RANDOM_KEY) && !defined(HAVE_OPENSSL)
410		DES_init_random_number_generator(&fbp->krbdes_key);
411#endif
412		fbp->once = 1;
413	}
414	DES_set_key_checked((DES_cblock *)&fbp->krbdes_key,
415			    &fbp->krbdes_sched);
416	/*
417	 * Now look to see if krbdes_start() was was waiting for
418	 * the key to show up.  If so, go ahead an call it now
419	 * that we have the key.
420	 */
421	if (fbp->need_start) {
422		fbp->need_start = 0;
423		fb64_start(fbp, DIR_ENCRYPT, server);
424	}
425}
426
427/*
428 * We only accept a keyid of 0.  If we get a keyid of
429 * 0, then mark the state as SUCCESS.
430 */
431
432int cfb64_keyid(int dir, unsigned char *kp, int *lenp)
433{
434	return(fb64_keyid(dir, kp, lenp, &fb[CFB]));
435}
436
437int ofb64_keyid(int dir, unsigned char *kp, int *lenp)
438{
439	return(fb64_keyid(dir, kp, lenp, &fb[OFB]));
440}
441
442int fb64_keyid(int dir, unsigned char *kp, int *lenp, struct fb *fbp)
443{
444	int state = fbp->state[dir-1];
445
446	if (*lenp != 1 || (*kp != '\0')) {
447		*lenp = 0;
448		return(state);
449	}
450
451	if (state == FAILED)
452		state = IN_PROGRESS;
453
454	state &= ~NO_KEYID;
455
456	return(fbp->state[dir-1] = state);
457}
458
459void fb64_printsub(unsigned char *data, int cnt,
460		   unsigned char *buf, int buflen, char *type)
461{
462	char lbuf[32];
463	int i;
464	char *cp;
465
466	buf[buflen-1] = '\0';		/* make sure it's NULL terminated */
467	buflen -= 1;
468
469	switch(data[2]) {
470	case FB64_IV:
471		snprintf(lbuf, sizeof(lbuf), "%s_IV", type);
472		cp = lbuf;
473		goto common;
474
475	case FB64_IV_OK:
476		snprintf(lbuf, sizeof(lbuf), "%s_IV_OK", type);
477		cp = lbuf;
478		goto common;
479
480	case FB64_IV_BAD:
481		snprintf(lbuf, sizeof(lbuf), "%s_IV_BAD", type);
482		cp = lbuf;
483		goto common;
484
485	default:
486		snprintf(lbuf, sizeof(lbuf), " %d (unknown)", data[2]);
487		cp = lbuf;
488	common:
489		for (; (buflen > 0) && (*buf = *cp++); buf++)
490			buflen--;
491		for (i = 3; i < cnt; i++) {
492			snprintf(lbuf, sizeof(lbuf), " %d", data[i]);
493			for (cp = lbuf; (buflen > 0) && (*buf = *cp++); buf++)
494				buflen--;
495		}
496		break;
497	}
498}
499
500void cfb64_printsub(unsigned char *data, int cnt,
501		    unsigned char *buf, int buflen)
502{
503	fb64_printsub(data, cnt, buf, buflen, "CFB64");
504}
505
506void ofb64_printsub(unsigned char *data, int cnt,
507		    unsigned char *buf, int buflen)
508{
509	fb64_printsub(data, cnt, buf, buflen, "OFB64");
510}
511
512void fb64_stream_iv(DES_cblock seed, struct stinfo *stp)
513{
514
515	memcpy(stp->str_iv, seed,sizeof(DES_cblock));
516	memcpy(stp->str_output, seed, sizeof(DES_cblock));
517
518	DES_set_key_checked(&stp->str_ikey, &stp->str_sched);
519
520	stp->str_index = sizeof(DES_cblock);
521}
522
523void fb64_stream_key(DES_cblock key, struct stinfo *stp)
524{
525	memcpy(stp->str_ikey, key, sizeof(DES_cblock));
526	DES_set_key_checked((DES_cblock*)key, &stp->str_sched);
527
528	memcpy(stp->str_output, stp->str_iv, sizeof(DES_cblock));
529
530	stp->str_index = sizeof(DES_cblock);
531}
532
533/*
534 * DES 64 bit Cipher Feedback
535 *
536 *     key --->+-----+
537 *          +->| DES |--+
538 *          |  +-----+  |
539 *	    |           v
540 *  INPUT --(--------->(+)+---> DATA
541 *          |             |
542 *	    +-------------+
543 *
544 *
545 * Given:
546 *	iV: Initial vector, 64 bits (8 bytes) long.
547 *	Dn: the nth chunk of 64 bits (8 bytes) of data to encrypt (decrypt).
548 *	On: the nth chunk of 64 bits (8 bytes) of encrypted (decrypted) output.
549 *
550 *	V0 = DES(iV, key)
551 *	On = Dn ^ Vn
552 *	V(n+1) = DES(On, key)
553 */
554
555void cfb64_encrypt(unsigned char *s, int c)
556{
557	struct stinfo *stp = &fb[CFB].streams[DIR_ENCRYPT-1];
558	int index;
559
560	index = stp->str_index;
561	while (c-- > 0) {
562		if (index == sizeof(DES_cblock)) {
563			DES_cblock b;
564			DES_ecb_encrypt(&stp->str_output, &b,&stp->str_sched, 1);
565			memcpy(stp->str_feed, b, sizeof(DES_cblock));
566			index = 0;
567		}
568
569		/* On encryption, we store (feed ^ data) which is cypher */
570		*s = stp->str_output[index] = (stp->str_feed[index] ^ *s);
571		s++;
572		index++;
573	}
574	stp->str_index = index;
575}
576
577int cfb64_decrypt(int data)
578{
579	struct stinfo *stp = &fb[CFB].streams[DIR_DECRYPT-1];
580	int index;
581
582	if (data == -1) {
583		/*
584		 * Back up one byte.  It is assumed that we will
585		 * never back up more than one byte.  If we do, this
586		 * may or may not work.
587		 */
588		if (stp->str_index)
589			--stp->str_index;
590		return(0);
591	}
592
593	index = stp->str_index++;
594	if (index == sizeof(DES_cblock)) {
595		DES_cblock b;
596		DES_ecb_encrypt(&stp->str_output,&b, &stp->str_sched, 1);
597		memcpy(stp->str_feed, b, sizeof(DES_cblock));
598		stp->str_index = 1;	/* Next time will be 1 */
599		index = 0;		/* But now use 0 */
600	}
601
602	/* On decryption we store (data) which is cypher. */
603	stp->str_output[index] = data;
604	return(data ^ stp->str_feed[index]);
605}
606
607/*
608 * DES 64 bit Output Feedback
609 *
610 * key --->+-----+
611 *	+->| DES |--+
612 *	|  +-----+  |
613 *	+-----------+
614 *	            v
615 *  INPUT -------->(+) ----> DATA
616 *
617 * Given:
618 *	iV: Initial vector, 64 bits (8 bytes) long.
619 *	Dn: the nth chunk of 64 bits (8 bytes) of data to encrypt (decrypt).
620 *	On: the nth chunk of 64 bits (8 bytes) of encrypted (decrypted) output.
621 *
622 *	V0 = DES(iV, key)
623 *	V(n+1) = DES(Vn, key)
624 *	On = Dn ^ Vn
625 */
626
627void ofb64_encrypt(unsigned char *s, int c)
628{
629	struct stinfo *stp = &fb[OFB].streams[DIR_ENCRYPT-1];
630	int index;
631
632	index = stp->str_index;
633	while (c-- > 0) {
634		if (index == sizeof(DES_cblock)) {
635			DES_cblock b;
636			DES_ecb_encrypt(&stp->str_feed,&b, &stp->str_sched, 1);
637			memcpy(stp->str_feed, b, sizeof(DES_cblock));
638			index = 0;
639		}
640		*s++ ^= stp->str_feed[index];
641		index++;
642	}
643	stp->str_index = index;
644}
645
646int ofb64_decrypt(int data)
647{
648	struct stinfo *stp = &fb[OFB].streams[DIR_DECRYPT-1];
649	int index;
650
651	if (data == -1) {
652		/*
653		 * Back up one byte.  It is assumed that we will
654		 * never back up more than one byte.  If we do, this
655		 * may or may not work.
656		 */
657		if (stp->str_index)
658			--stp->str_index;
659		return(0);
660	}
661
662	index = stp->str_index++;
663	if (index == sizeof(DES_cblock)) {
664		DES_cblock b;
665		DES_ecb_encrypt(&stp->str_feed,&b,&stp->str_sched, 1);
666		memcpy(stp->str_feed, b, sizeof(DES_cblock));
667		stp->str_index = 1;	/* Next time will be 1 */
668		index = 0;		/* But now use 0 */
669	}
670
671	return(data ^ stp->str_feed[index]);
672}
673#endif
674
675