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