xref: /freebsd/contrib/telnet/libtelnet/encrypt.c (revision 8fa113e5fc65fe6abc757f0089f477a87ee4d185)
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 <sys/cdefs.h>
35 
36 __FBSDID("$FreeBSD$");
37 
38 #ifndef lint
39 #if 0
40 static const char sccsid[] = "@(#)encrypt.c	8.2 (Berkeley) 5/30/95";
41 #endif
42 #endif /* not lint */
43 
44 /*
45  * Copyright (C) 1990 by the Massachusetts Institute of Technology
46  *
47  * Export of this software from the United States of America is assumed
48  * to require a specific license from the United States Government.
49  * It is the responsibility of any person or organization contemplating
50  * export to obtain such a license before exporting.
51  *
52  * WITHIN THAT CONSTRAINT, permission to use, copy, modify, and
53  * distribute this software and its documentation for any purpose and
54  * without fee is hereby granted, provided that the above copyright
55  * notice appear in all copies and that both that copyright notice and
56  * this permission notice appear in supporting documentation, and that
57  * the name of M.I.T. not be used in advertising or publicity pertaining
58  * to distribution of the software without specific, written prior
59  * permission.  M.I.T. makes no representations about the suitability of
60  * this software for any purpose.  It is provided "as is" without express
61  * or implied warranty.
62  */
63 
64 #ifdef	ENCRYPTION
65 
66 #define	ENCRYPT_NAMES
67 #include <arpa/telnet.h>
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 
72 #include "encrypt.h"
73 #include "misc.h"
74 
75 /*
76  * These functions pointers point to the current routines
77  * for encrypting and decrypting data.
78  */
79 void	(*encrypt_output) P((unsigned char *, int));
80 int	(*decrypt_input) P((int));
81 
82 int EncryptType(char *type, char *mode);
83 int EncryptStart(char *mode);
84 int EncryptStop(char *mode);
85 int EncryptStartInput(void);
86 int EncryptStartOutput(void);
87 int EncryptStopInput(void);
88 int EncryptStopOutput(void);
89 
90 int encrypt_debug_mode = 0;
91 static int decrypt_mode = 0;
92 static int encrypt_mode = 0;
93 static int encrypt_verbose = 0;
94 static int autoencrypt = 0;
95 static int autodecrypt = 0;
96 static int havesessionkey = 0;
97 static int Server = 0;
98 static const char *Name = "Noname";
99 
100 #define	typemask(x)	((x) > 0 ? 1 << ((x)-1) : 0)
101 
102 static long i_support_encrypt = 0
103  | typemask(ENCTYPE_DES_CFB64) | typemask(ENCTYPE_DES_OFB64)
104  |0;
105 static long i_support_decrypt = 0
106  | typemask(ENCTYPE_DES_CFB64) | typemask(ENCTYPE_DES_OFB64)
107  |0;
108 
109 static long i_wont_support_encrypt = 0;
110 static long i_wont_support_decrypt = 0;
111 #define	I_SUPPORT_ENCRYPT	(i_support_encrypt & ~i_wont_support_encrypt)
112 #define	I_SUPPORT_DECRYPT	(i_support_decrypt & ~i_wont_support_decrypt)
113 
114 static long remote_supports_encrypt = 0;
115 static long remote_supports_decrypt = 0;
116 
117 static Encryptions encryptions[] = {
118     { "DES_CFB64",	ENCTYPE_DES_CFB64,
119 			cfb64_encrypt,
120 			cfb64_decrypt,
121 			cfb64_init,
122 			cfb64_start,
123 			cfb64_is,
124 			cfb64_reply,
125 			cfb64_session,
126 			cfb64_keyid,
127 			cfb64_printsub },
128     { "DES_OFB64",	ENCTYPE_DES_OFB64,
129 			ofb64_encrypt,
130 			ofb64_decrypt,
131 			ofb64_init,
132 			ofb64_start,
133 			ofb64_is,
134 			ofb64_reply,
135 			ofb64_session,
136 			ofb64_keyid,
137 			ofb64_printsub },
138     { NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
139 };
140 
141 static unsigned char str_send[64] = { IAC, SB, TELOPT_ENCRYPT,
142 					 ENCRYPT_SUPPORT };
143 static unsigned char str_suplen = 0;
144 static unsigned char str_start[72] = { IAC, SB, TELOPT_ENCRYPT };
145 static unsigned char str_end[] = { IAC, SB, TELOPT_ENCRYPT, 0, IAC, SE };
146 
147 Encryptions *
148 findencryption(int type)
149 {
150 	Encryptions *ep = encryptions;
151 
152 	if (!(I_SUPPORT_ENCRYPT & remote_supports_decrypt & (unsigned)typemask(type)))
153 		return(0);
154 	while (ep->type && ep->type != type)
155 		++ep;
156 	return(ep->type ? ep : 0);
157 }
158 
159 static Encryptions *
160 finddecryption(int type)
161 {
162 	Encryptions *ep = encryptions;
163 
164 	if (!(I_SUPPORT_DECRYPT & remote_supports_encrypt & (unsigned)typemask(type)))
165 		return(0);
166 	while (ep->type && ep->type != type)
167 		++ep;
168 	return(ep->type ? ep : 0);
169 }
170 
171 #define	MAXKEYLEN 64
172 
173 static struct key_info {
174 	unsigned char keyid[MAXKEYLEN];
175 	int keylen;
176 	int dir;
177 	int *modep;
178 	Encryptions *(*getcrypt)(int);
179 } ki[2] = {
180 	{ { 0 }, 0, DIR_ENCRYPT, &encrypt_mode, findencryption },
181 	{ { 0 }, 0, DIR_DECRYPT, &decrypt_mode, finddecryption },
182 };
183 
184 static void encrypt_keyid(struct key_info *kp, unsigned char *keyid, int len);
185 
186 void
187 encrypt_init(const char *name, int server)
188 {
189 	Encryptions *ep = encryptions;
190 
191 	Name = name;
192 	Server = server;
193 	i_support_encrypt = i_support_decrypt = 0;
194 	remote_supports_encrypt = remote_supports_decrypt = 0;
195 	encrypt_mode = 0;
196 	decrypt_mode = 0;
197 	encrypt_output = 0;
198 	decrypt_input = 0;
199 
200 	str_suplen = 4;
201 
202 	while (ep->type) {
203 		if (encrypt_debug_mode)
204 			printf(">>>%s: I will support %s\r\n",
205 				Name, ENCTYPE_NAME(ep->type));
206 		i_support_encrypt |= typemask(ep->type);
207 		i_support_decrypt |= typemask(ep->type);
208 		if ((i_wont_support_decrypt & typemask(ep->type)) == 0)
209 			if ((str_send[str_suplen++] = ep->type) == IAC)
210 				str_send[str_suplen++] = IAC;
211 		if (ep->init)
212 			(*ep->init)(Server);
213 		++ep;
214 	}
215 	str_send[str_suplen++] = IAC;
216 	str_send[str_suplen++] = SE;
217 }
218 
219 static void
220 encrypt_list_types(void)
221 {
222 	Encryptions *ep = encryptions;
223 
224 	printf("Valid encryption types:\n");
225 	while (ep->type) {
226 		printf("\t%s (%d)\r\n", ENCTYPE_NAME(ep->type), ep->type);
227 		++ep;
228 	}
229 }
230 
231 int
232 EncryptEnable(char *type, char *mode)
233 {
234 	if (isprefix(type, "help") || isprefix(type, "?")) {
235 		printf("Usage: encrypt enable <type> [input|output]\n");
236 		encrypt_list_types();
237 		return(0);
238 	}
239 	if (EncryptType(type, mode))
240 		return(EncryptStart(mode));
241 	return(0);
242 }
243 
244 int
245 EncryptDisable(char *type, char *mode)
246 {
247 	Encryptions *ep;
248 	int ret = 0;
249 
250 	if (isprefix(type, "help") || isprefix(type, "?")) {
251 		printf("Usage: encrypt disable <type> [input|output]\n");
252 		encrypt_list_types();
253 	} else if ((ep = (Encryptions *)genget(type, (char **)encryptions,
254 						sizeof(Encryptions))) == 0) {
255 		printf("%s: invalid encryption type\n", type);
256 	} else if (Ambiguous((char **)ep)) {
257 		printf("Ambiguous type '%s'\n", type);
258 	} else {
259 		if ((mode == 0) || (isprefix(mode, "input") ? 1 : 0)) {
260 			if (decrypt_mode == ep->type)
261 				EncryptStopInput();
262 			i_wont_support_decrypt |= typemask(ep->type);
263 			ret = 1;
264 		}
265 		if ((mode == 0) || (isprefix(mode, "output"))) {
266 			if (encrypt_mode == ep->type)
267 				EncryptStopOutput();
268 			i_wont_support_encrypt |= typemask(ep->type);
269 			ret = 1;
270 		}
271 		if (ret == 0)
272 			printf("%s: invalid encryption mode\n", mode);
273 	}
274 	return(ret);
275 }
276 
277 int
278 EncryptType(char *type, char *mode)
279 {
280 	Encryptions *ep;
281 	int ret = 0;
282 
283 	if (isprefix(type, "help") || isprefix(type, "?")) {
284 		printf("Usage: encrypt type <type> [input|output]\n");
285 		encrypt_list_types();
286 	} else if ((ep = (Encryptions *)genget(type, (char **)encryptions,
287 						sizeof(Encryptions))) == 0) {
288 		printf("%s: invalid encryption type\n", type);
289 	} else if (Ambiguous((char **)ep)) {
290 		printf("Ambiguous type '%s'\n", type);
291 	} else {
292 		if ((mode == 0) || isprefix(mode, "input")) {
293 			decrypt_mode = ep->type;
294 			i_wont_support_decrypt &= ~typemask(ep->type);
295 			ret = 1;
296 		}
297 		if ((mode == 0) || isprefix(mode, "output")) {
298 			encrypt_mode = ep->type;
299 			i_wont_support_encrypt &= ~typemask(ep->type);
300 			ret = 1;
301 		}
302 		if (ret == 0)
303 			printf("%s: invalid encryption mode\n", mode);
304 	}
305 	return(ret);
306 }
307 
308 int
309 EncryptStart(char *mode)
310 {
311 	int ret = 0;
312 	if (mode) {
313 		if (isprefix(mode, "input"))
314 			return(EncryptStartInput());
315 		if (isprefix(mode, "output"))
316 			return(EncryptStartOutput());
317 		if (isprefix(mode, "help") || isprefix(mode, "?")) {
318 			printf("Usage: encrypt start [input|output]\n");
319 			return(0);
320 		}
321 		printf("%s: invalid encryption mode 'encrypt start ?' for help\n", mode);
322 		return(0);
323 	}
324 	ret += EncryptStartInput();
325 	ret += EncryptStartOutput();
326 	return(ret);
327 }
328 
329 int
330 EncryptStartInput(void)
331 {
332 	if (decrypt_mode) {
333 		encrypt_send_request_start();
334 		return(1);
335 	}
336 	printf("No previous decryption mode, decryption not enabled\r\n");
337 	return(0);
338 }
339 
340 int
341 EncryptStartOutput(void)
342 {
343 	if (encrypt_mode) {
344 		encrypt_start_output(encrypt_mode);
345 		return(1);
346 	}
347 	printf("No previous encryption mode, encryption not enabled\r\n");
348 	return(0);
349 }
350 
351 int
352 EncryptStop(char *mode)
353 {
354 	int ret = 0;
355 	if (mode) {
356 		if (isprefix(mode, "input"))
357 			return(EncryptStopInput());
358 		if (isprefix(mode, "output"))
359 			return(EncryptStopOutput());
360 		if (isprefix(mode, "help") || isprefix(mode, "?")) {
361 			printf("Usage: encrypt stop [input|output]\n");
362 			return(0);
363 		}
364 		printf("%s: invalid encryption mode 'encrypt stop ?' for help\n", mode);
365 		return(0);
366 	}
367 	ret += EncryptStopInput();
368 	ret += EncryptStopOutput();
369 	return(ret);
370 }
371 
372 int
373 EncryptStopInput(void)
374 {
375 	encrypt_send_request_end();
376 	return(1);
377 }
378 
379 int
380 EncryptStopOutput(void)
381 {
382 	encrypt_send_end();
383 	return(1);
384 }
385 
386 void
387 encrypt_display(void)
388 {
389 	if (encrypt_output)
390 		printf("Currently encrypting output with %s\r\n",
391 			ENCTYPE_NAME(encrypt_mode));
392 	if (decrypt_input)
393 		printf("Currently decrypting input with %s\r\n",
394 			ENCTYPE_NAME(decrypt_mode));
395 }
396 
397 int
398 EncryptStatus(void)
399 {
400 	if (encrypt_output)
401 		printf("Currently encrypting output with %s\r\n",
402 			ENCTYPE_NAME(encrypt_mode));
403 	else if (encrypt_mode) {
404 		printf("Currently output is clear text.\r\n");
405 		printf("Last encryption mode was %s\r\n",
406 			ENCTYPE_NAME(encrypt_mode));
407 	}
408 	if (decrypt_input) {
409 		printf("Currently decrypting input with %s\r\n",
410 			ENCTYPE_NAME(decrypt_mode));
411 	} else if (decrypt_mode) {
412 		printf("Currently input is clear text.\r\n");
413 		printf("Last decryption mode was %s\r\n",
414 			ENCTYPE_NAME(decrypt_mode));
415 	}
416 	return 1;
417 }
418 
419 void
420 encrypt_send_support(void)
421 {
422 	if (str_suplen) {
423 		/*
424 		 * If the user has requested that decryption start
425 		 * immediatly, then send a "REQUEST START" before
426 		 * we negotiate the type.
427 		 */
428 		if (!Server && autodecrypt)
429 			encrypt_send_request_start();
430 		net_write(str_send, str_suplen);
431 		printsub('>', &str_send[2], str_suplen - 2);
432 		str_suplen = 0;
433 	}
434 }
435 
436 int
437 EncryptDebug(int on)
438 {
439 	if (on < 0)
440 		encrypt_debug_mode ^= 1;
441 	else
442 		encrypt_debug_mode = on;
443 	printf("Encryption debugging %s\r\n",
444 		encrypt_debug_mode ? "enabled" : "disabled");
445 	return(1);
446 }
447 
448 int
449 EncryptVerbose(int on)
450 {
451 	if (on < 0)
452 		encrypt_verbose ^= 1;
453 	else
454 		encrypt_verbose = on;
455 	printf("Encryption %s verbose\r\n",
456 		encrypt_verbose ? "is" : "is not");
457 	return(1);
458 }
459 
460 int
461 EncryptAutoEnc(int on)
462 {
463 	encrypt_auto(on);
464 	printf("Automatic encryption of output is %s\r\n",
465 		autoencrypt ? "enabled" : "disabled");
466 	return(1);
467 }
468 
469 int
470 EncryptAutoDec(int on)
471 {
472 	decrypt_auto(on);
473 	printf("Automatic decryption of input is %s\r\n",
474 		autodecrypt ? "enabled" : "disabled");
475 	return(1);
476 }
477 
478 /*
479  * Called when ENCRYPT SUPPORT is received.
480  */
481 void
482 encrypt_support(unsigned char *typelist, int cnt)
483 {
484 	int type, use_type = 0;
485 	Encryptions *ep;
486 
487 	/*
488 	 * Forget anything the other side has previously told us.
489 	 */
490 	remote_supports_decrypt = 0;
491 
492 	while (cnt-- > 0) {
493 		type = *typelist++;
494 		if (encrypt_debug_mode)
495 			printf(">>>%s: He is supporting %s (%d)\r\n",
496 				Name,
497 				ENCTYPE_NAME(type), type);
498 		if ((type < ENCTYPE_CNT) &&
499 		    (I_SUPPORT_ENCRYPT & typemask(type))) {
500 			remote_supports_decrypt |= typemask(type);
501 			if (use_type == 0)
502 				use_type = type;
503 		}
504 	}
505 	if (use_type) {
506 		ep = findencryption(use_type);
507 		if (!ep)
508 			return;
509 		type = ep->start ? (*ep->start)(DIR_ENCRYPT, Server) : 0;
510 		if (encrypt_debug_mode)
511 			printf(">>>%s: (*ep->start)() returned %d\r\n",
512 					Name, type);
513 		if (type < 0)
514 			return;
515 		encrypt_mode = use_type;
516 		if (type == 0)
517 			encrypt_start_output(use_type);
518 	}
519 }
520 
521 void
522 encrypt_is(unsigned char *data, int cnt)
523 {
524 	Encryptions *ep;
525 	int type, ret;
526 
527 	if (--cnt < 0)
528 		return;
529 	type = *data++;
530 	if (type < ENCTYPE_CNT)
531 		remote_supports_encrypt |= typemask(type);
532 	if (!(ep = finddecryption(type))) {
533 		if (encrypt_debug_mode)
534 			printf(">>>%s: Can't find type %s (%d) for initial negotiation\r\n",
535 				Name,
536 				ENCTYPE_NAME_OK(type)
537 					? ENCTYPE_NAME(type) : "(unknown)",
538 				type);
539 		return;
540 	}
541 	if (!ep->is) {
542 		if (encrypt_debug_mode)
543 			printf(">>>%s: No initial negotiation needed for type %s (%d)\r\n",
544 				Name,
545 				ENCTYPE_NAME_OK(type)
546 					? ENCTYPE_NAME(type) : "(unknown)",
547 				type);
548 		ret = 0;
549 	} else {
550 		ret = (*ep->is)(data, cnt);
551 		if (encrypt_debug_mode)
552 			printf("(*ep->is)(%p, %d) returned %s(%d)\n", data, cnt,
553 				(ret < 0) ? "FAIL " :
554 				(ret == 0) ? "SUCCESS " : "MORE_TO_DO ", ret);
555 	}
556 	if (ret < 0) {
557 		autodecrypt = 0;
558 	} else {
559 		decrypt_mode = type;
560 		if (ret == 0 && autodecrypt)
561 			encrypt_send_request_start();
562 	}
563 }
564 
565 void
566 encrypt_reply(unsigned char *data, int cnt)
567 {
568 	Encryptions *ep;
569 	int ret, type;
570 
571 	if (--cnt < 0)
572 		return;
573 	type = *data++;
574 	if (!(ep = findencryption(type))) {
575 		if (encrypt_debug_mode)
576 			printf(">>>%s: Can't find type %s (%d) for initial negotiation\r\n",
577 				Name,
578 				ENCTYPE_NAME_OK(type)
579 					? ENCTYPE_NAME(type) : "(unknown)",
580 				type);
581 		return;
582 	}
583 	if (!ep->reply) {
584 		if (encrypt_debug_mode)
585 			printf(">>>%s: No initial negotiation needed for type %s (%d)\r\n",
586 				Name,
587 				ENCTYPE_NAME_OK(type)
588 					? ENCTYPE_NAME(type) : "(unknown)",
589 				type);
590 		ret = 0;
591 	} else {
592 		ret = (*ep->reply)(data, cnt);
593 		if (encrypt_debug_mode)
594 			printf("(*ep->reply)(%p, %d) returned %s(%d)\n",
595 				data, cnt,
596 				(ret < 0) ? "FAIL " :
597 				(ret == 0) ? "SUCCESS " : "MORE_TO_DO ", ret);
598 	}
599 	if (encrypt_debug_mode)
600 		printf(">>>%s: encrypt_reply returned %d\n", Name, ret);
601 	if (ret < 0) {
602 		autoencrypt = 0;
603 	} else {
604 		encrypt_mode = type;
605 		if (ret == 0 && autoencrypt)
606 			encrypt_start_output(type);
607 	}
608 }
609 
610 /*
611  * Called when a ENCRYPT START command is received.
612  */
613 void
614 encrypt_start(unsigned char *data __unused, int cnt __unused)
615 {
616 	Encryptions *ep;
617 
618 	if (!decrypt_mode) {
619 		/*
620 		 * Something is wrong.  We should not get a START
621 		 * command without having already picked our
622 		 * decryption scheme.  Send a REQUEST-END to
623 		 * attempt to clear the channel...
624 		 */
625 		printf("%s: Warning, Cannot decrypt input stream!!!\r\n", Name);
626 		encrypt_send_request_end();
627 		return;
628 	}
629 
630 	if ((ep = finddecryption(decrypt_mode))) {
631 		decrypt_input = ep->input;
632 		if (encrypt_verbose)
633 			printf("[ Input is now decrypted with type %s ]\r\n",
634 				ENCTYPE_NAME(decrypt_mode));
635 		if (encrypt_debug_mode)
636 			printf(">>>%s: Start to decrypt input with type %s\r\n",
637 				Name, ENCTYPE_NAME(decrypt_mode));
638 	} else {
639 		printf("%s: Warning, Cannot decrypt type %s (%d)!!!\r\n",
640 				Name,
641 				ENCTYPE_NAME_OK(decrypt_mode)
642 					? ENCTYPE_NAME(decrypt_mode)
643 					: "(unknown)",
644 				decrypt_mode);
645 		encrypt_send_request_end();
646 	}
647 }
648 
649 void
650 encrypt_session_key( Session_Key *key, int server)
651 {
652 	Encryptions *ep = encryptions;
653 
654 	havesessionkey = 1;
655 
656 	while (ep->type) {
657 		if (ep->session)
658 			(*ep->session)(key, server);
659 		++ep;
660 	}
661 }
662 
663 /*
664  * Called when ENCRYPT END is received.
665  */
666 void
667 encrypt_end(void)
668 {
669 	decrypt_input = 0;
670 	if (encrypt_debug_mode)
671 		printf(">>>%s: Input is back to clear text\r\n", Name);
672 	if (encrypt_verbose)
673 		printf("[ Input is now clear text ]\r\n");
674 }
675 
676 /*
677  * Called when ENCRYPT REQUEST-END is received.
678  */
679 void
680 encrypt_request_end(void)
681 {
682 	encrypt_send_end();
683 }
684 
685 /*
686  * Called when ENCRYPT REQUEST-START is received.  If we receive
687  * this before a type is picked, then that indicates that the
688  * other side wants us to start encrypting data as soon as we
689  * can.
690  */
691 void
692 encrypt_request_start(unsigned char *data __unused, int cnt __unused)
693 {
694 	if (encrypt_mode == 0)  {
695 		if (Server)
696 			autoencrypt = 1;
697 		return;
698 	}
699 	encrypt_start_output(encrypt_mode);
700 }
701 
702 static unsigned char str_keyid[(MAXKEYLEN*2)+5] = { IAC, SB, TELOPT_ENCRYPT };
703 
704 void
705 encrypt_enc_keyid(unsigned char *keyid, int len)
706 {
707 	encrypt_keyid(&ki[1], keyid, len);
708 }
709 
710 void
711 encrypt_dec_keyid(unsigned char *keyid, int len)
712 {
713 	encrypt_keyid(&ki[0], keyid, len);
714 }
715 
716 void
717 encrypt_keyid(struct key_info *kp, unsigned char *keyid, int len)
718 {
719 	Encryptions *ep;
720 	int dir = kp->dir;
721 	int ret = 0;
722 
723 	if (!(ep = (*kp->getcrypt)(*kp->modep))) {
724 		if (len == 0)
725 			return;
726 		kp->keylen = 0;
727 	} else if (len == 0) {
728 		/*
729 		 * Empty option, indicates a failure.
730 		 */
731 		if (kp->keylen == 0)
732 			return;
733 		kp->keylen = 0;
734 		if (ep->keyid)
735 			(void)(*ep->keyid)(dir, kp->keyid, &kp->keylen);
736 
737 	} else if ((len != kp->keylen) ||
738 		   (memcmp(keyid, kp->keyid, len) != 0)) {
739 		/*
740 		 * Length or contents are different
741 		 */
742 		kp->keylen = len;
743 		memmove(kp->keyid, keyid, len);
744 		if (ep->keyid)
745 			(void)(*ep->keyid)(dir, kp->keyid, &kp->keylen);
746 	} else {
747 		if (ep->keyid)
748 			ret = (*ep->keyid)(dir, kp->keyid, &kp->keylen);
749 		if ((ret == 0) && (dir == DIR_ENCRYPT) && autoencrypt)
750 			encrypt_start_output(*kp->modep);
751 		return;
752 	}
753 
754 	encrypt_send_keyid(dir, kp->keyid, kp->keylen, 0);
755 }
756 
757 void
758 encrypt_send_keyid(int dir, const char *keyid, int keylen, int saveit)
759 {
760 	unsigned char *strp;
761 
762 	str_keyid[3] = (dir == DIR_ENCRYPT)
763 			? ENCRYPT_ENC_KEYID : ENCRYPT_DEC_KEYID;
764 	if (saveit) {
765 		struct key_info *kp = &ki[(dir == DIR_ENCRYPT) ? 0 : 1];
766 		memmove(kp->keyid, keyid, keylen);
767 		kp->keylen = keylen;
768 	}
769 
770 	for (strp = &str_keyid[4]; keylen > 0; --keylen) {
771 		if ((*strp++ = *keyid++) == IAC)
772 			*strp++ = IAC;
773 	}
774 	*strp++ = IAC;
775 	*strp++ = SE;
776 	net_write(str_keyid, strp - str_keyid);
777 	printsub('>', &str_keyid[2], strp - str_keyid - 2);
778 }
779 
780 void
781 encrypt_auto(int on)
782 {
783 	if (on < 0)
784 		autoencrypt ^= 1;
785 	else
786 		autoencrypt = on ? 1 : 0;
787 }
788 
789 void
790 decrypt_auto(int on)
791 {
792 	if (on < 0)
793 		autodecrypt ^= 1;
794 	else
795 		autodecrypt = on ? 1 : 0;
796 }
797 
798 void
799 encrypt_start_output(int type)
800 {
801 	Encryptions *ep;
802 	unsigned char *p;
803 	int i;
804 
805 	if (!(ep = findencryption(type))) {
806 		if (encrypt_debug_mode) {
807 			printf(">>>%s: Can't encrypt with type %s (%d)\r\n",
808 				Name,
809 				ENCTYPE_NAME_OK(type)
810 					? ENCTYPE_NAME(type) : "(unknown)",
811 				type);
812 		}
813 		return;
814 	}
815 	if (ep->start) {
816 		i = (*ep->start)(DIR_ENCRYPT, Server);
817 		if (encrypt_debug_mode) {
818 			printf(">>>%s: Encrypt start: %s (%d) %s\r\n",
819 				Name,
820 				(i < 0) ? "failed" :
821 					"initial negotiation in progress",
822 				i, ENCTYPE_NAME(type));
823 		}
824 		if (i)
825 			return;
826 	}
827 	p = str_start + 3;
828 	*p++ = ENCRYPT_START;
829 	for (i = 0; i < ki[0].keylen; ++i) {
830 		if ((*p++ = ki[0].keyid[i]) == IAC)
831 			*p++ = IAC;
832 	}
833 	*p++ = IAC;
834 	*p++ = SE;
835 	net_write(str_start, p - str_start);
836 	net_encrypt();
837 	printsub('>', &str_start[2], p - &str_start[2]);
838 	/*
839 	 * If we are already encrypting in some mode, then
840 	 * encrypt the ring (which includes our request) in
841 	 * the old mode, mark it all as "clear text" and then
842 	 * switch to the new mode.
843 	 */
844 	encrypt_output = ep->output;
845 	encrypt_mode = type;
846 	if (encrypt_debug_mode)
847 		printf(">>>%s: Started to encrypt output with type %s\r\n",
848 			Name, ENCTYPE_NAME(type));
849 	if (encrypt_verbose)
850 		printf("[ Output is now encrypted with type %s ]\r\n",
851 			ENCTYPE_NAME(type));
852 }
853 
854 void
855 encrypt_send_end(void)
856 {
857 	if (!encrypt_output)
858 		return;
859 
860 	str_end[3] = ENCRYPT_END;
861 	net_write(str_end, sizeof(str_end));
862 	net_encrypt();
863 	printsub('>', &str_end[2], sizeof(str_end) - 2);
864 	/*
865 	 * Encrypt the output buffer now because it will not be done by
866 	 * netflush...
867 	 */
868 	encrypt_output = 0;
869 	if (encrypt_debug_mode)
870 		printf(">>>%s: Output is back to clear text\r\n", Name);
871 	if (encrypt_verbose)
872 		printf("[ Output is now clear text ]\r\n");
873 }
874 
875 void
876 encrypt_send_request_start(void)
877 {
878 	unsigned char *p;
879 	int i;
880 
881 	p = &str_start[3];
882 	*p++ = ENCRYPT_REQSTART;
883 	for (i = 0; i < ki[1].keylen; ++i) {
884 		if ((*p++ = ki[1].keyid[i]) == IAC)
885 			*p++ = IAC;
886 	}
887 	*p++ = IAC;
888 	*p++ = SE;
889 	net_write(str_start, p - str_start);
890 	printsub('>', &str_start[2], p - &str_start[2]);
891 	if (encrypt_debug_mode)
892 		printf(">>>%s: Request input to be encrypted\r\n", Name);
893 }
894 
895 void
896 encrypt_send_request_end(void)
897 {
898 	str_end[3] = ENCRYPT_REQEND;
899 	net_write(str_end, sizeof(str_end));
900 	printsub('>', &str_end[2], sizeof(str_end) - 2);
901 
902 	if (encrypt_debug_mode)
903 		printf(">>>%s: Request input to be clear text\r\n", Name);
904 }
905 
906 void
907 encrypt_wait(void)
908 {
909 	if (encrypt_debug_mode)
910 		printf(">>>%s: in encrypt_wait\r\n", Name);
911 	if (!havesessionkey || !(I_SUPPORT_ENCRYPT & remote_supports_decrypt))
912 		return;
913 	while (autoencrypt && !encrypt_output)
914 		if (telnet_spin())
915 			return;
916 }
917 
918 void
919 encrypt_gen_printsub(unsigned char *data, int cnt, unsigned char *buf, int buflen)
920 {
921 	char tbuf[16], *cp;
922 
923 	cnt -= 2;
924 	data += 2;
925 	buf[buflen-1] = '\0';
926 	buf[buflen-2] = '*';
927 	buflen -= 2;;
928 	for (; cnt > 0; cnt--, data++) {
929 		sprintf(tbuf, " %d", *data);
930 		for (cp = tbuf; *cp && buflen > 0; --buflen)
931 			*buf++ = *cp++;
932 		if (buflen <= 0)
933 			return;
934 	}
935 	*buf = '\0';
936 }
937 
938 void
939 encrypt_printsub(unsigned char *data, int cnt, unsigned char *buf, int buflen)
940 {
941 	Encryptions *ep;
942 	int type = data[1];
943 
944 	for (ep = encryptions; ep->type && ep->type != type; ep++)
945 		;
946 
947 	if (ep->printsub)
948 		(*ep->printsub)(data, cnt, buf, buflen);
949 	else
950 		encrypt_gen_printsub(data, cnt, buf, buflen);
951 }
952 #endif	/* ENCRYPTION */
953