Try hard to restore the termios state on exit/reboot.
[dragonfly.git] / libexec / rlogind / rlogind.c
1 /*-
2  * Copyright (c) 1983, 1988, 1989, 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  * @(#) Copyright (c) 1983, 1988, 1989, 1993 The Regents of the University of California.  All rights reserved.
34  * @(#)rlogind.c        8.1 (Berkeley) 6/4/93
35  * $FreeBSD: src/libexec/rlogind/rlogind.c,v 1.29.2.5 2000/12/07 15:02:31 ru Exp $
36  * $DragonFly: src/libexec/rlogind/rlogind.c,v 1.5 2007/05/18 17:05:12 dillon Exp $
37  */
38
39 /*
40  * remote login server:
41  *      \0
42  *      remuser\0
43  *      locuser\0
44  *      terminal_type/speed\0
45  *      data
46  */
47
48 #define FD_SETSIZE      16              /* don't need many bits for select */
49 #include <sys/types.h>
50 #include <sys/param.h>
51 #include <sys/stat.h>
52 #include <sys/ioctl.h>
53 #include <signal.h>
54 #include <termios.h>
55
56 #include <sys/socket.h>
57 #include <netinet/in.h>
58 #include <netinet/in_systm.h>
59 #include <netinet/ip.h>
60 #include <netinet/tcp.h>
61 #include <arpa/inet.h>
62 #include <netdb.h>
63
64 #include <errno.h>
65 #include <libutil.h>
66 #include <pwd.h>
67 #include <syslog.h>
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <unistd.h>
72 #include "pathnames.h"
73
74
75 #ifndef TIOCPKT_WINDOW
76 #define TIOCPKT_WINDOW 0x80
77 #endif
78
79 #define         ARGSTR                  "Dalnx"
80
81 /* wrapper for KAME-special getnameinfo() */
82 #ifndef NI_WITHSCOPEID
83 #define NI_WITHSCOPEID  0
84 #endif
85
86 extern int __check_rhosts_file;
87 extern  char **environ;
88
89 char    *env[2];
90 #define NMAX 30
91 char    lusername[NMAX+1], rusername[NMAX+1];
92 static  char term[64] = "TERM=";
93 #define ENVSIZE (sizeof("TERM=")-1)     /* skip null for concatenation */
94 int     keepalive = 1;
95 int     check_all = 0;
96 int     no_delay;
97
98 struct  passwd *pwd;
99
100 union sockunion {
101         struct sockinet {
102                 u_char si_len;
103                 u_char si_family;
104                 u_short si_port;
105         } su_si;
106         struct sockaddr_in  su_sin;
107         struct sockaddr_in6 su_sin6;
108 };
109 #define su_len          su_si.si_len
110 #define su_family       su_si.si_family
111 #define su_port         su_si.si_port
112
113 void    doit(int, union sockunion *);
114 int     control(int, char *, int);
115 void    protocol(int, int);
116 void    cleanup(int);
117 void    fatal(int, const char *, int);
118 int     do_rlogin(union sockunion *);
119 void    getstr(char *, int, const char *);
120 void    setup_term(int);
121 int     do_krb_login(struct sockaddr_in *);
122 void    usage(void);
123
124
125 int
126 main(int argc, char *argv[])
127 {
128         union sockunion from;
129         socklen_t fromlen;
130         int ch, on;
131
132         openlog("rlogind", LOG_PID | LOG_CONS, LOG_AUTH);
133
134         opterr = 0;
135         while ((ch = getopt(argc, argv, ARGSTR)) != -1)
136                 switch (ch) {
137                 case 'D':
138                         no_delay = 1;
139                         break;
140                 case 'a':
141                         check_all = 1;
142                         break;
143                 case 'l':
144                         __check_rhosts_file = 0;
145                         break;
146                 case 'n':
147                         keepalive = 0;
148                         break;
149 #ifdef CRYPT
150                 case 'x':
151                         doencrypt = 1;
152                         break;
153 #endif
154                 case '?':
155                 default:
156                         usage();
157                         break;
158                 }
159         argc -= optind;
160         argv += optind;
161
162         fromlen = sizeof (from);
163         if (getpeername(0, (struct sockaddr *)&from, &fromlen) < 0) {
164                 syslog(LOG_ERR,"Can't get peer name of remote host: %m");
165                 fatal(STDERR_FILENO, "Can't get peer name of remote host", 1);
166         }
167         on = 1;
168         if (keepalive &&
169             setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof (on)) < 0)
170                 syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m");
171         if (no_delay &&
172             setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0)
173                 syslog(LOG_WARNING, "setsockopt (TCP_NODELAY): %m");
174         if (from.su_family == AF_INET)
175       {
176         on = IPTOS_LOWDELAY;
177         if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&on, sizeof(int)) < 0)
178                 syslog(LOG_WARNING, "setsockopt (IP_TOS): %m");
179       }
180
181         doit(0, &from);
182         return 0;
183 }
184
185 int     child;
186 int     netf;
187 char    line[MAXPATHLEN];
188 int     confirmed;
189
190 struct winsize win = { 0, 0, 0, 0 };
191
192
193 void
194 doit(int f, union sockunion *fromp)
195 {
196         int master, pid, on = 1;
197         int authenticated = 0;
198         char hostname[2 * MAXHOSTNAMELEN + 1];
199         char nameinfo[2 * INET6_ADDRSTRLEN + 1];
200         u_char c;
201
202         alarm(60);
203         read(f, &c, 1);
204
205         if (c != 0)
206                 exit(1);
207
208         alarm(0);
209
210         realhostname_sa(hostname, sizeof(hostname) - 1,
211                             (struct sockaddr *)fromp, fromp->su_len);
212         /* error check ? */
213         fromp->su_port = ntohs((u_short)fromp->su_port);
214         hostname[sizeof(hostname) - 1] = '\0';
215
216         {
217                 if ((fromp->su_family != AF_INET
218 #ifdef INET6
219                   && fromp->su_family != AF_INET6
220 #endif
221                      ) ||
222                     fromp->su_port >= IPPORT_RESERVED ||
223                     fromp->su_port < IPPORT_RESERVED/2) {
224                         getnameinfo((struct sockaddr *)fromp,
225                                     fromp->su_len,
226                                     nameinfo, sizeof(nameinfo), NULL, 0,
227                                     NI_NUMERICHOST|NI_WITHSCOPEID);
228                         /* error check ? */
229                         syslog(LOG_NOTICE, "Connection from %s on illegal port",
230                                nameinfo);
231                         fatal(f, "Permission denied", 0);
232                 }
233 #ifdef IP_OPTIONS
234                 if (fromp->su_family == AF_INET)
235               {
236                 u_char optbuf[BUFSIZ/3];
237                 socklen_t optsize = sizeof(optbuf), i;
238                 int ipproto;
239                 struct protoent *ip;
240
241                 if ((ip = getprotobyname("ip")) != NULL)
242                         ipproto = ip->p_proto;
243                 else
244                         ipproto = IPPROTO_IP;
245                 if (getsockopt(0, ipproto, IP_OPTIONS, (char *)optbuf,
246                     &optsize) == 0 && optsize != 0) {
247                         for (i = 0; i < optsize; ) {
248                                 c = optbuf[i];
249                                 if (c == IPOPT_LSRR || c == IPOPT_SSRR) {
250                                         syslog(LOG_NOTICE,
251                                                 "Connection refused from %s with IP option %s",
252                                                 inet_ntoa(fromp->su_sin.sin_addr),
253                                                 c == IPOPT_LSRR ? "LSRR" : "SSRR");
254                                         exit(1);
255                                 }
256                                 if (c == IPOPT_EOL)
257                                         break;
258                                 i += (c == IPOPT_NOP) ? 1 : optbuf[i+1];
259                         }
260                 }
261               }
262 #endif
263                 if (do_rlogin(fromp) == 0)
264                         authenticated++;
265         }
266         if (confirmed == 0) {
267                 write(f, "", 1);
268                 confirmed = 1;          /* we sent the null! */
269         }
270 #ifdef  CRYPT
271         if (doencrypt) {
272                 des_enc_write(f, SECURE_MESSAGE, strlen(SECURE_MESSAGE),
273                     schedule, &kdata->session);
274         }
275 #endif
276         netf = f;
277
278         pid = forkpty(&master, line, NULL, &win);
279         if (pid < 0) {
280                 if (errno == ENOENT)
281                         fatal(f, "Out of ptys", 0);
282                 else
283                         fatal(f, "Forkpty", 1);
284         }
285         if (pid == 0) {
286                 if (f > 2)      /* f should always be 0, but... */
287                         close(f);
288                 setup_term(0);
289                  if (*lusername=='-') {
290                         syslog(LOG_ERR, "tried to pass user \"%s\" to login",
291                                lusername);
292                         fatal(STDERR_FILENO, "invalid user", 0);
293                 }
294                 if (authenticated) {
295                         execl(_PATH_LOGIN, "login", "-p",
296                             "-h", hostname, "-f", lusername, (char *)NULL);
297                 } else
298                         execl(_PATH_LOGIN, "login", "-p",
299                             "-h", hostname, lusername, (char *)NULL);
300                 fatal(STDERR_FILENO, _PATH_LOGIN, 1);
301                 /*NOTREACHED*/
302         }
303 #ifdef  CRYPT
304         /*
305          * If encrypted, don't turn on NBIO or the des read/write
306          * routines will croak.
307          */
308
309         if (!doencrypt)
310 #endif
311                 ioctl(f, FIONBIO, &on);
312         ioctl(master, FIONBIO, &on);
313         ioctl(master, TIOCPKT, &on);
314         signal(SIGCHLD, cleanup);
315         protocol(f, master);
316         signal(SIGCHLD, SIG_IGN);
317         cleanup(0);
318 }
319
320 char    magic[2] = { 0377, 0377 };
321 char    oobdata[] = {TIOCPKT_WINDOW};
322
323 /*
324  * Handle a "control" request (signaled by magic being present)
325  * in the data stream.  For now, we are only willing to handle
326  * window size changes.
327  */
328 int
329 control(int pty, char *cp, int n)
330 {
331         struct winsize w;
332
333         if (n < 4 + (int)sizeof(w) || cp[2] != 's' || cp[3] != 's')
334                 return (0);
335         oobdata[0] &= ~TIOCPKT_WINDOW;  /* we know he heard */
336         bcopy(cp+4, (char *)&w, sizeof(w));
337         w.ws_row = ntohs(w.ws_row);
338         w.ws_col = ntohs(w.ws_col);
339         w.ws_xpixel = ntohs(w.ws_xpixel);
340         w.ws_ypixel = ntohs(w.ws_ypixel);
341         ioctl(pty, TIOCSWINSZ, &w);
342         return (4+sizeof (w));
343 }
344
345 /*
346  * rlogin "protocol" machine.
347  */
348 void
349 protocol(int f, int p)
350 {
351         char pibuf[1024+1], fibuf[1024], *pbp = NULL, *fbp = NULL;
352         int pcc = 0, fcc = 0;
353         int cc, nfd, n;
354         char cntl;
355
356         /*
357          * Must ignore SIGTTOU, otherwise we'll stop
358          * when we try and set slave pty's window shape
359          * (our controlling tty is the master pty).
360          */
361         signal(SIGTTOU, SIG_IGN);
362         send(f, oobdata, 1, MSG_OOB);   /* indicate new rlogin */
363         if (f > p)
364                 nfd = f + 1;
365         else
366                 nfd = p + 1;
367         if (nfd > FD_SETSIZE) {
368                 syslog(LOG_ERR, "select mask too small, increase FD_SETSIZE");
369                 fatal(f, "internal error (select mask too small)", 0);
370         }
371         for (;;) {
372                 fd_set ibits, obits, ebits, *omask;
373
374                 FD_ZERO(&ebits);
375                 FD_ZERO(&ibits);
376                 FD_ZERO(&obits);
377                 omask = (fd_set *)NULL;
378                 if (fcc) {
379                         FD_SET(p, &obits);
380                         omask = &obits;
381                 } else
382                         FD_SET(f, &ibits);
383                 if (pcc >= 0) {
384                         if (pcc) {
385                                 FD_SET(f, &obits);
386                                 omask = &obits;
387                         } else
388                                 FD_SET(p, &ibits);
389                 }
390                 FD_SET(p, &ebits);
391                 if ((n = select(nfd, &ibits, omask, &ebits, 0)) < 0) {
392                         if (errno == EINTR)
393                                 continue;
394                         fatal(f, "select", 1);
395                 }
396                 if (n == 0) {
397                         /* shouldn't happen... */
398                         sleep(5);
399                         continue;
400                 }
401 #define pkcontrol(c)    ((c)&(TIOCPKT_FLUSHWRITE|TIOCPKT_NOSTOP|TIOCPKT_DOSTOP))
402                 if (FD_ISSET(p, &ebits)) {
403                         cc = read(p, &cntl, 1);
404                         if (cc == 1 && pkcontrol(cntl)) {
405                                 cntl |= oobdata[0];
406                                 send(f, &cntl, 1, MSG_OOB);
407                                 if (cntl & TIOCPKT_FLUSHWRITE) {
408                                         pcc = 0;
409                                         FD_CLR(p, &ibits);
410                                 }
411                         }
412                 }
413                 if (FD_ISSET(f, &ibits)) {
414 #ifdef  CRYPT
415                         if (doencrypt)
416                                 fcc = des_enc_read(f, fibuf, sizeof(fibuf),
417                                         schedule, &kdata->session);
418                         else
419 #endif
420                                 fcc = read(f, fibuf, sizeof(fibuf));
421                         if (fcc < 0 && errno == EWOULDBLOCK)
422                                 fcc = 0;
423                         else {
424                                 register char *cp;
425                                 int left;
426
427                                 if (fcc <= 0)
428                                         break;
429                                 fbp = fibuf;
430
431                         top:
432                                 for (cp = fibuf; cp < fibuf+fcc-1; cp++)
433                                         if (cp[0] == magic[0] &&
434                                             cp[1] == magic[1]) {
435                                                 left = fcc - (cp-fibuf);
436                                                 n = control(p, cp, left);
437                                                 if (n) {
438                                                         left -= n;
439                                                         if (left > 0)
440                                                                 bcopy(cp+n, cp, left);
441                                                         fcc -= n;
442                                                         goto top; /* n^2 */
443                                                 }
444                                         }
445                                 FD_SET(p, &obits);              /* try write */
446                         }
447                 }
448
449                 if (FD_ISSET(p, &obits) && fcc > 0) {
450                         cc = write(p, fbp, fcc);
451                         if (cc > 0) {
452                                 fcc -= cc;
453                                 fbp += cc;
454                         }
455                 }
456
457                 if (FD_ISSET(p, &ibits)) {
458                         pcc = read(p, pibuf, sizeof (pibuf));
459                         pbp = pibuf;
460                         if (pcc < 0 && errno == EWOULDBLOCK)
461                                 pcc = 0;
462                         else if (pcc <= 0)
463                                 break;
464                         else if (pibuf[0] == 0) {
465                                 pbp++, pcc--;
466 #ifdef  CRYPT
467                                 if (!doencrypt)
468 #endif
469                                         FD_SET(f, &obits);      /* try write */
470                         } else {
471                                 if (pkcontrol(pibuf[0])) {
472                                         pibuf[0] |= oobdata[0];
473                                         send(f, &pibuf[0], 1, MSG_OOB);
474                                 }
475                                 pcc = 0;
476                         }
477                 }
478                 if ((FD_ISSET(f, &obits)) && pcc > 0) {
479 #ifdef  CRYPT
480                         if (doencrypt)
481                                 cc = des_enc_write(f, pbp, pcc,
482                                         schedule, &kdata->session);
483                         else
484 #endif
485                                 cc = write(f, pbp, pcc);
486                         if (cc < 0 && errno == EWOULDBLOCK) {
487                                 /*
488                                  * This happens when we try write after read
489                                  * from p, but some old kernels balk at large
490                                  * writes even when select returns true.
491                                  */
492                                 if (!FD_ISSET(p, &ibits))
493                                         sleep(5);
494                                 continue;
495                         }
496                         if (cc > 0) {
497                                 pcc -= cc;
498                                 pbp += cc;
499                         }
500                 }
501         }
502 }
503
504 void
505 cleanup(int signo __unused)
506 {
507         char *p;
508
509         p = line + sizeof(_PATH_DEV) - 1;
510         if (logout(p))
511                 logwtmp(p, "", "");
512         chflags(line, 0);
513         chmod(line, 0666);
514         chown(line, 0, 0);
515         *p = 'p';
516         chflags(line, 0);
517         chmod(line, 0666);
518         chown(line, 0, 0);
519         shutdown(netf, SHUT_RDWR);
520         exit(1);
521 }
522
523 void
524 fatal(int f, const char *msg, int syserr)
525 {
526         int len;
527         char buf[BUFSIZ], *bp = buf;
528
529         /*
530          * Prepend binary one to message if we haven't sent
531          * the magic null as confirmation.
532          */
533         if (!confirmed)
534                 *bp++ = '\01';          /* error indicator */
535         if (syserr)
536                 len = snprintf(bp, sizeof(buf), "rlogind: %s: %s.\r\n",
537                     msg, strerror(errno));
538         else
539                 len = snprintf(bp, sizeof(buf), "rlogind: %s.\r\n", msg);
540         write(f, buf, bp + len - buf);
541         exit(1);
542 }
543
544 int
545 do_rlogin(union sockunion *dest)
546 {
547
548         getstr(rusername, sizeof(rusername), "remuser too long");
549         getstr(lusername, sizeof(lusername), "locuser too long");
550         getstr(term+ENVSIZE, sizeof(term)-ENVSIZE, "Terminal type too long");
551
552         pwd = getpwnam(lusername);
553         if (pwd == NULL)
554                 return (-1);
555         /* XXX why don't we syslog() failure? */
556
557         return (iruserok_sa(dest, dest->su_len, pwd->pw_uid == 0, rusername,
558                             lusername));
559 }
560
561 void
562 getstr(char *buf, int cnt, const char *errmsg)
563 {
564         char c;
565
566         do {
567                 if (read(0, &c, 1) != 1)
568                         exit(1);
569                 if (--cnt < 0)
570                         fatal(STDOUT_FILENO, errmsg, 0);
571                 *buf++ = c;
572         } while (c != 0);
573 }
574
575 void
576 setup_term(int fd)
577 {
578         register char *cp = index(term+ENVSIZE, '/');
579         char *speed;
580         struct termios tt;
581
582 #ifndef notyet
583         tcgetattr(fd, &tt);
584         if (cp) {
585                 *cp++ = '\0';
586                 speed = cp;
587                 cp = index(speed, '/');
588                 if (cp)
589                         *cp++ = '\0';
590                 cfsetspeed(&tt, atoi(speed));
591         }
592
593         tt.c_iflag = TTYDEF_IFLAG;
594         tt.c_oflag = TTYDEF_OFLAG;
595         tt.c_lflag = TTYDEF_LFLAG;
596         tcsetattr(fd, TCSAFLUSH, &tt);
597 #else
598         if (cp) {
599                 *cp++ = '\0';
600                 speed = cp;
601                 cp = index(speed, '/');
602                 if (cp)
603                         *cp++ = '\0';
604                 tcgetattr(fd, &tt);
605                 cfsetspeed(&tt, atoi(speed));
606                 tcsetattr(fd, TCSAFLUSH, &tt);
607         }
608 #endif
609
610         env[0] = term;
611         env[1] = 0;
612         environ = env;
613 }
614
615 void
616 usage(void)
617 {
618         syslog(LOG_ERR, "usage: rlogind [-" ARGSTR "]");
619 }