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