Debian Codegraph @

telnetd/telnetd.c

raw
1 /*
2 Copyright (C) 1993-2026 Free Software Foundation, Inc.
3
4 This file is part of GNU Inetutils.
5
6 GNU Inetutils is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or (at
9 your option) any later version.
10
11 GNU Inetutils is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see `http://www.gnu.org/licenses/'. */
18
19 #include <config.h>
20
21 #include "telnetd.h"
22
23 #include <sys/utsname.h>
24 #include <argp.h>
25 #include <progname.h>
26 #include <error.h>
27 #include <attribute.h>
28 #include <libinetutils.h>
29
30 #if defined AUTHENTICATION || defined ENCRYPTION
31 # include <libtelnet/misc.h>
32 #endif
33
34 #ifdef AUTHENTICATION
35 static void parse_authmode (char *str);
36 #endif
37
38 static void parse_linemode (char *str);
39 static void telnetd_setup (int fd);
40 static int telnetd_run (void);
41 static void print_hostinfo (void);
42 static void chld_is_done (int sig);
43
44 /* Template command line for invoking login program. */
45
46 char *login_invocation =
47 #ifdef SOLARIS10
48 /* TODO: `-s telnet' or `-s ktelnet'.
49 * `-u' takes the Kerberos principal name
50 * of the authenticating, remote user.
51 */
52 PATH_LOGIN " -p -h %h %?T{-t %T} -d %L %?u{-u %u}{%U}"
53 #elif defined SOLARIS
54 /* At least for SunOS 5.8. */
55 PATH_LOGIN " -h %h %?T{%T} %?u{-- %u}{%U}"
56 #else /* !SOLARIS */
57 PATH_LOGIN " -p -h %h %?u{-f -- %u}{-- %U}"
58 #endif
59 ;
60
61 int keepalive = 1; /* Should the TCP keepalive bit be set */
62 int reverse_lookup = 0; /* Reject connects from hosts which IP numbers
63 cannot be reverse mapped to their hostnames */
64 int alwayslinemode; /* Always set the linemode (1) */
65 int lmodetype; /* Type of linemode (2) */
66 int hostinfo = 1; /* Print the host-specific information before
67 login */
68
69 int pending_sigchld = 0; /* Needed to drain pty input. */
70
71 int net; /* Network connection socket */
72 int pty; /* PTY master descriptor */
73 #if defined AUTHENTICATION || defined ENCRYPTION
74 char *principal = NULL;
75 #endif
76 char *remote_hostname;
77 char *local_hostname;
78 char *user_name;
79 char line[256];
80
81 char options[256];
82 char do_dont_resp[256];
83 char will_wont_resp[256];
84 int linemode; /* linemode on/off */
85 int uselinemode; /* what linemode to use (on/off) */
86 int editmode; /* edit modes in use */
87 int useeditmode; /* edit modes to use */
88 int alwayslinemode; /* command line option */
89 int lmodetype; /* Client support for linemode */
90 int flowmode; /* current flow control state */
91 int restartany; /* restart output on any character state */
92 int diagnostic; /* telnet diagnostic capabilities */
93 #if defined AUTHENTICATION
94 int auth_level = 0; /* Authentication level */
95 int autologin;
96 #endif
97
98 slcfun slctab[NSLC + 1]; /* slc mapping table */
99
100 char *terminaltype;
101
102 int SYNCHing; /* we are in TELNET SYNCH mode */
103 struct telnetd_clocks clocks;
104
105 /* Set of environment variables that we do not remove from clients. */
106 gl_set_t accept_env_set = NULL;
107
108 static size_t
109 string_hashcode (const void *s)
110 {
111 return hash_string (s, strlen (s));
112 }
113
114 static bool
115 string_equals (const void *a, const void *b)
116 {
117 return strcmp (a, b) == 0;
118 }
119
120 /* List of long options without short option counterparts. */
121 enum
122 {
123 ACCEPT_ENV_OPTION = UCHAR_MAX + 1
124 };
125
126 static struct argp_option argp_options[] = {
127 #define GRID 10
128 {"accept-env", ACCEPT_ENV_OPTION, "NAME", 0,
129 "accept the environment variable from clients", GRID},
130 {"exec-login", 'E', "STRING", 0,
131 "set program to be executed instead of standard login(1)", GRID},
132 {"no-hostinfo", 'h', NULL, 0,
133 "do not print host information before login has been completed", GRID},
134 {"linemode", 'l', "MODE", OPTION_ARG_OPTIONAL,
135 "set line mode", GRID},
136 {"no-keepalive", 'n', NULL, 0,
137 "disable TCP keep-alive", GRID},
138 {"reverse-lookup", 'U', NULL, 0,
139 "refuse connections from addresses that "
140 "cannot be mapped back into a symbolic name", GRID},
141 #undef GRID
142
143 #ifdef AUTHENTICATION
144 # define GRID 20
145 {NULL, 0, NULL, 0, "Authentication control:", GRID},
146 {"authmode", 'a', "MODE", 0,
147 "specify what mode to use for authentication", GRID},
148 {"server-principal", 'S', "NAME", 0,
149 "set Kerberos principal name for this server instance, "
150 "with or without explicit realm", GRID},
151 {"disable-auth-type", 'X', "TYPE", 0,
152 "disable the use of given authentication option", GRID},
153 # undef GRID
154 #endif /* AUTHENTICATION */
155 {NULL, 0, NULL, 0, NULL, 0}
156 };
157
158 static error_t
159 parse_opt (int key, char *arg, struct argp_state *state MAYBE_UNUSED)
160 {
161 switch (key)
162 {
163
164 case ACCEPT_ENV_OPTION:
165 if (!accept_env_set)
166 accept_env_set = gl_set_create_empty (GL_HASH_SET, string_equals,
167 string_hashcode, NULL);
168 gl_set_add (accept_env_set, arg);
169 break;
170
171 #ifdef AUTHENTICATION
172 case 'a':
173 parse_authmode (arg);
174 break;
175 #endif
176
177 case 'E':
178 login_invocation = arg;
179 break;
180
181 case 'h':
182 hostinfo = 0;
183 break;
184
185 case 'l':
186 parse_linemode (arg);
187 break;
188
189 case 'n':
190 keepalive = 0;
191 break;
192
193 #if defined AUTHENTICATION || defined ENCRYPTION
194 case 'S':
195 principal = arg;
196 break;
197 #endif
198
199 case 'U':
200 reverse_lookup = 1;
201 break;
202
203 #ifdef AUTHENTICATION
204 case 'X':
205 auth_disable_name (arg);
206 break;
207 #endif
208
209 default:
210 return ARGP_ERR_UNKNOWN;
211 }
212
213 return 0;
214 }
215
216 static struct argp argp = {
217 argp_options,
218 parse_opt,
219 NULL,
220 "DARPA telnet protocol server",
221 NULL, NULL, NULL
222 };
223
224
225
226 int
227 main (int argc, char **argv)
228 {
229 int index;
230
231 set_program_name (argv[0]);
232 iu_argp_init ("telnetd", default_program_authors);
233
234 openlog ("telnetd", LOG_PID | LOG_ODELAY, LOG_DAEMON);
235
236 argp_parse (&argp, argc, argv, 0, &index, NULL);
237
238 if (argc != index)
239 error (EXIT_FAILURE, 0, "junk arguments in the command line");
240
241 telnetd_setup (0);
242 return telnetd_run (); /* Never returning. */
243 }
244
245 void
246 parse_linemode (char *str)
247 {
248 if (!str)
249 alwayslinemode = 1;
250 else if (strcmp (str, "nokludge") == 0)
251 lmodetype = NO_AUTOKLUDGE;
252 else
253 syslog (LOG_NOTICE, "invalid argument to --linemode: %s", str);
254 }
255
256 #ifdef AUTHENTICATION
257 void
258 parse_authmode (char *str)
259 {
260 if (strcasecmp (str, "none") == 0)
261 auth_level = 0;
262 else if (strcasecmp (str, "other") == 0)
263 auth_level = AUTH_OTHER;
264 else if (strcasecmp (str, "user") == 0)
265 auth_level = AUTH_USER;
266 else if (strcasecmp (str, "valid") == 0)
267 auth_level = AUTH_VALID;
268 else if (strcasecmp (str, "off") == 0)
269 auth_level = -1;
270 else
271 syslog (LOG_NOTICE, "unknown authorization level for -a: %s", str);
272 }
273 #endif /* AUTHENTICATION */
274
275 typedef unsigned int ip_addr_t;
276 /*FIXME*/ void
277 telnetd_setup (int fd)
278 {
279 #ifdef IPV6
280 struct sockaddr_storage saddr;
281 char buf[256], buf2[256]; /* FIXME: We should use dynamic allocation. */
282 int err;
283 #else
284 struct sockaddr_in saddr;
285 struct hostent *hp;
286 #endif
287 int on = 1;
288 socklen_t len;
289 char uname[256];
290 /*FIXME*/ int level;
291
292 len = sizeof (saddr);
293 if (getpeername (fd, (struct sockaddr *) &saddr, &len) < 0)
294 {
295 syslog (LOG_ERR, "getpeername: %m");
296 exit (EXIT_FAILURE);
297 }
298
299 #ifdef IPV6
300 err = getnameinfo ((struct sockaddr *) &saddr, len, buf,
301 sizeof (buf), NULL, 0, NI_NUMERICHOST);
302 if (err)
303 {
304 const char *errmsg;
305
306 if (err == EAI_SYSTEM)
307 errmsg = strerror (errno);
308 else
309 errmsg = gai_strerror (err);
310
311 syslog (LOG_AUTH | LOG_NOTICE, "Cannot get address: %s", errmsg);
312 fatal (fd, "Cannot get address.");
313 }
314
315 /* We use a second buffer so we don't have to call getnameinfo again
316 if we need the numeric host below. */
317 err = getnameinfo ((struct sockaddr *) &saddr, len, buf2,
318 sizeof (buf2), NULL, 0, NI_NAMEREQD);
319
320 if (reverse_lookup)
321 {
322 struct addrinfo *result, *aip;
323
324 if (err)
325 {
326 const char *errmsg;
327
328 if (err == EAI_SYSTEM)
329 errmsg = strerror (errno);
330 else
331 errmsg = gai_strerror (err);
332
333 syslog (LOG_AUTH | LOG_NOTICE, "Can't resolve %s: %s", buf, errmsg);
334 fatal (fd, "Cannot resolve address.");
335 }
336
337 remote_hostname = xstrdup (buf2);
338
339 err = getaddrinfo (remote_hostname, NULL, NULL, &result);
340 if (err)
341 {
342 const char *errmsg;
343
344 if (err == EAI_SYSTEM)
345 errmsg = strerror (errno);
346 else
347 errmsg = gai_strerror (err);
348
349 syslog (LOG_AUTH | LOG_NOTICE, "Forward resolve of %s failed: %s",
350 remote_hostname, errmsg);
351 fatal (fd, "Cannot resolve address.");
352 }
353
354 for (aip = result; aip; aip = aip->ai_next)
355 {
356 if (aip->ai_family != saddr.ss_family)
357 continue;
358
359 /* Must compare the address part only.
360 * The ports are almost surely different!
361 */
362 if (aip->ai_family == AF_INET
363 && !memcmp (&((struct sockaddr_in *) aip->ai_addr)->sin_addr,
364 &((struct sockaddr_in *) &saddr)->sin_addr,
365 sizeof (struct in_addr)))
366 break;
367 if (aip->ai_family == AF_INET6
368 && !memcmp (&((struct sockaddr_in6 *) aip->ai_addr)->sin6_addr,
369 &((struct sockaddr_in6 *) &saddr)->sin6_addr,
370 sizeof (struct in6_addr)))
371 break;
372 }
373
374 if (aip == NULL)
375 {
376 syslog (LOG_AUTH | LOG_NOTICE,
377 "No address of %s matched %s", remote_hostname, buf);
378 fatal (fd, "Cannot resolve address.");
379 }
380
381 freeaddrinfo (result);
382 }
383 else
384 {
385 if (!err)
386 remote_hostname = xstrdup (buf2);
387 else
388 remote_hostname = xstrdup (buf);
389 }
390 #else
391 hp = gethostbyaddr ((char *) &saddr.sin_addr.s_addr,
392 sizeof (saddr.sin_addr.s_addr), AF_INET);
393 if (reverse_lookup)
394 {
395 char **ap;
396
397 if (!hp)
398 {
399 syslog (LOG_AUTH | LOG_NOTICE,
400 "Can't resolve %s: %s",
401 inet_ntoa (saddr.sin_addr), hstrerror (h_errno));
402 fatal (fd, "Cannot resolve address.");
403 }
404
405 remote_hostname = xstrdup (hp->h_name);
406
407 hp = gethostbyname (remote_hostname);
408 if (!hp)
409 {
410 syslog (LOG_AUTH | LOG_NOTICE,
411 "Forward resolve of %s failed: %s",
412 remote_hostname, hstrerror (h_errno));
413 fatal (fd, "Cannot resolve address.");
414 }
415
416 for (ap = hp->h_addr_list; *ap; ap++)
417 if (*(ip_addr_t *) ap == saddr.sin_addr.s_addr)
418 break;
419
420 if (ap == NULL)
421 {
422 syslog (LOG_AUTH | LOG_NOTICE,
423 "No address of %s matched %s",
424 remote_hostname, inet_ntoa (saddr.sin_addr));
425 fatal (fd, "Cannot resolve address.");
426 }
427 }
428 else
429 {
430 if (hp)
431 remote_hostname = xstrdup (hp->h_name);
432 else
433 remote_hostname = xstrdup (inet_ntoa (saddr.sin_addr));
434 }
435 #endif
436
437 /* Set socket options */
438
439 if (keepalive
440 && setsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
441 (char *) &on, sizeof (on)) < 0)
442 syslog (LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
443
444 net = fd;
445
446 local_hostname = localhost ();
447 #if defined AUTHENTICATION || defined ENCRYPTION
448 auth_encrypt_init (local_hostname, remote_hostname, principal,
449 "TELNETD", 1);
450 #endif
451
452 io_setup ();
453
454 /* Clear the environment of all variables before doing anything. This avoids
455 many ways of escalating privileges. Environment variable options sent by
456 the client will be checked against ACCEPT_ENV_SET. */
457 static char *dummy_environ[] = { NULL };
458 environ = dummy_environ;
459
460 /* get terminal type. */
461 uname[0] = 0;
462 level = getterminaltype (uname, sizeof (uname));
463 setenv ("TERM", terminaltype ? terminaltype : "network", 1);
464 if (uname[0])
465 user_name = xstrdup (uname);
466 pty = startslave (remote_hostname, level, user_name);
467
468 #ifndef HAVE_STREAMSPTY
469 /* Turn on packet mode */
470 ioctl (pty, TIOCPKT, (char *) &on);
471 #endif
472 ioctl (pty, FIONBIO, (char *) &on);
473 ioctl (net, FIONBIO, (char *) &on);
474
475 #if defined SO_OOBINLINE
476 setsockopt (net, SOL_SOCKET, SO_OOBINLINE, (char *) &on, sizeof on);
477 #endif
478
479 #ifdef SIGTSTP
480 signal (SIGTSTP, SIG_IGN);
481 #endif
482 #ifdef SIGTTOU
483 signal (SIGTTOU, SIG_IGN);
484 #endif
485
486 /* Activate SA_RESTART whenever available. */
487 setsig (SIGCHLD, chld_is_done);
488 }
489
490 int
491 telnetd_run (void)
492 {
493 int nfd;
494
495 get_slc_defaults ();
496
497 if (my_state_is_wont (TELOPT_SGA))
498 send_will (TELOPT_SGA, 1);
499
500 /* Old BSD 4.2 clients are unable to deal with TCP out-of-band data.
501 To find out, we send out a "DO ECHO". If the remote side is
502 a BSD 4.2 it will answer "WILL ECHO". See the response processing
503 below. */
504 send_do (TELOPT_ECHO, 1);
505 if (his_state_is_wont (TELOPT_LINEMODE))
506 {
507 /* Query the peer for linemode support by trying to negotiate
508 the linemode option. */
509 linemode = 0;
510 editmode = 0;
511 send_do (TELOPT_LINEMODE, 1); /* send do linemode */
512 }
513
514 send_do (TELOPT_NAWS, 1);
515 send_will (TELOPT_STATUS, 1);
516 flowmode = 1; /* default flow control state */
517 restartany = -1; /* uninitialized... */
518 send_do (TELOPT_LFLOW, 1);
519
520 /* Wait for a response from the DO ECHO. Reportedly, some broken
521 clients might not respond to it. To work around this, we wait
522 for a response to NAWS, which should have been processed after
523 DO ECHO (most dumb telnets respond with WONT for a DO that
524 they don't understand).
525 On the other hand, the client might have sent WILL NAWS as
526 part of its startup code, in this case it surely should have
527 answered our DO ECHO, so the second loop is waiting for
528 the ECHO to settle down. */
529 ttloop (his_will_wont_is_changing (TELOPT_NAWS));
530
531 if (his_want_state_is_will (TELOPT_ECHO) && his_state_is_will (TELOPT_NAWS))
532 ttloop (his_will_wont_is_changing (TELOPT_ECHO));
533
534 /* If the remote client is badly broken and did not respond to our
535 DO ECHO, we simulate the receipt of a will echo. This will also
536 send a WONT ECHO to the client, since we assume that the client
537 failed to respond because it believes that it is already in DO ECHO
538 mode, which we do not want. */
539
540 if (his_want_state_is_will (TELOPT_ECHO))
541 willoption (TELOPT_ECHO);
542
543 /* Turn on our echo */
544 if (my_state_is_wont (TELOPT_ECHO))
545 send_will (TELOPT_ECHO, 1);
546
547 /* Continuing line mode support. If client does not support
548 real linemode, attempt to negotiate kludge linemode by sending
549 the do timing mark sequence. */
550 if (lmodetype < REAL_LINEMODE)
551 send_do (TELOPT_TM, 1);
552
553 /* Pick up anything received during the negotiations */
554 telrcv ();
555
556 if (hostinfo)
557 print_hostinfo ();
558
559 init_termbuf ();
560 localstat ();
561
562 nfd = ((net > pty) ? net : pty) + 1;
563
564 for (;;)
565 {
566 fd_set ibits, obits, xbits;
567 int c;
568
569 if (net_input_level () < 0 && pty_input_level () < 0)
570 break;
571
572 FD_ZERO (&ibits);
573 FD_ZERO (&obits);
574 FD_ZERO (&xbits);
575
576 /* Never look for input if there's still stuff in the corresponding
577 output buffer */
578 if (net_output_level () || pty_input_level () > 0)
579 FD_SET (net, &obits);
580 else
581 FD_SET (pty, &ibits);
582
583 if (pty_output_level () || net_input_level () > 0)
584 FD_SET (pty, &obits);
585 else
586 FD_SET (net, &ibits);
587
588 if (!SYNCHing)
589 FD_SET (net, &xbits);
590
591 if ((c = select (nfd, &ibits, &obits, &xbits, NULL)) <= 0)
592 {
593 if (c == -1 && errno == EINTR)
594 continue;
595 sleep (5);
596 continue;
597 }
598
599 if (FD_ISSET (net, &xbits))
600 SYNCHing = 1;
601
602 if (FD_ISSET (net, &ibits))
603 {
604 /* Something to read from the network... */
605 /*FIXME: handle !defined(SO_OOBINLINE) */
606 net_read ();
607 }
608
609 if (FD_ISSET (pty, &ibits))
610 {
611 /* Something to read from the pty... */
612
613 /* Observe that pty_read() is masking a few select
614 * read errors with the return value 0. Let them
615 * pass for further manipulation. Issue reported in
616 * http://lists.gnu.org/archive/html/bug-inetutils/2015-07/msg00006.html
617 */
618 if (pty_read () < 0)
619 break;
620
621 /* The first byte is now TIOCPKT data. Peek at it. */
622 c = pty_get_char (1);
623
624 #if defined TIOCPKT_IOCTL
625 if (c & TIOCPKT_IOCTL)
626 {
627 pty_get_char (0);
628 copy_termbuf (); /* Pty buffer is now emptied. */
629 localstat ();
630 }
631 #endif
632 if (c & TIOCPKT_FLUSHWRITE)
633 {
634 static char flushdata[] = { IAC, DM };
635 pty_get_char (0);
636 netclear (); /* clear buffer back */
637 net_output_datalen (flushdata, sizeof (flushdata));
638 set_neturg ();
639 }
640
641 if (his_state_is_will (TELOPT_LFLOW)
642 && (c & (TIOCPKT_NOSTOP | TIOCPKT_DOSTOP)))
643 {
644 int newflow = (c & TIOCPKT_DOSTOP) ? 1 : 0;
645 if (newflow != flowmode)
646 {
647 char data[7];
648
649 sprintf (data, "%c%c%c%c%c%c",
650 IAC, SB, TELOPT_LFLOW,
651 flowmode ? LFLOW_ON : LFLOW_OFF, IAC, SE);
652 net_output_datalen (data, sizeof (data));
653 }
654 }
655
656 pty_get_char (0); /* Discard the TIOCPKT preamble. */
657 }
658
659 while (pty_input_level () > 0)
660 {
661 if (net_buffer_is_full ())
662 break;
663 c = pty_get_char (0);
664 if (c == IAC)
665 net_output_byte (c);
666 net_output_byte (c);
667 if (c == '\r' && my_state_is_wont (TELOPT_BINARY))
668 {
669 if (pty_input_level () > 0 && pty_get_char (1) == '\n')
670 net_output_byte (pty_get_char (0));
671 else
672 net_output_byte (0);
673 }
674 }
675
676 if (FD_ISSET (net, &obits) && net_output_level () > 0)
677 netflush ();
678 if (net_input_level () > 0)
679 telrcv ();
680
681 if (FD_ISSET (pty, &obits) && pty_output_level () > 0)
682 ptyflush ();
683
684 /* Attending to the child must come last in the loop,
685 * so as to let pending data be flushed, mainly to the
686 * benefit of the remote and expecting client.
687 */
688 if (pending_sigchld)
689 {
690 /* Check for pending output, independently of OBITS. */
691 if (net_output_level () > 0)
692 netflush ();
693
694 cleanup (SIGCHLD); /* Not returning from this. */
695 }
696 }
697
698 cleanup (0);
699 /* NOT REACHED */
700
701 return 0;
702 }
703
704 void
705 print_hostinfo (void)
706 {
707 char *im = NULL;
708 char *str;
709 #ifdef HAVE_UNAME
710 struct utsname u;
711
712 if (uname (&u) >= 0)
713 {
714 im = malloc (strlen (UNAME_IM_PREFIX)
715 + strlen (u.sysname)
716 + 1 + strlen (u.release) + strlen (UNAME_IM_SUFFIX) + 1);
717 if (im)
718 sprintf (im, "%s%s %s%s",
719 UNAME_IM_PREFIX, u.sysname, u.release, UNAME_IM_SUFFIX);
720 }
721 #endif /* HAVE_UNAME */
722 if (!im)
723 im = xstrdup ("\r\n\r\nUNIX (%l) (%t)\r\n\r\n");
724
725 str = expand_line (im);
726 free (im);
727
728 pty_input_putback (str, strlen (str));
729 free (str);
730 }
731
732 static void
733 chld_is_done (int sig MAYBE_UNUSED)
734 {
735 pending_sigchld = 1;
736 }