xref: /netbsd-src/usr.bin/rsh/rsh.c (revision 23c8222edbfb0f0932d88a8351d3a0cf817dfb9e)
1 /*	$NetBSD: rsh.c,v 1.24 2004/10/16 07:36:08 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 1983, 1990, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 __COPYRIGHT("@(#) Copyright (c) 1983, 1990, 1993, 1994\n\
35 	The Regents of the University of California.  All rights reserved.\n");
36 #endif /* not lint */
37 
38 #ifndef lint
39 #if 0
40 static char sccsid[] = "@(#)rsh.c	8.4 (Berkeley) 4/29/95";
41 #else
42 __RCSID("$NetBSD: rsh.c,v 1.24 2004/10/16 07:36:08 christos Exp $");
43 #endif
44 #endif /* not lint */
45 
46 #include <sys/types.h>
47 #include <sys/socket.h>
48 #include <sys/ioctl.h>
49 #include <sys/file.h>
50 #include <poll.h>
51 
52 #include <netinet/in.h>
53 #include <netinet/tcp.h>
54 #include <netdb.h>
55 
56 #include <err.h>
57 #include <errno.h>
58 #include <limits.h>
59 #include <pwd.h>
60 #include <signal.h>
61 #include <stdarg.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <unistd.h>
66 
67 #include "pathnames.h"
68 #include "getport.h"
69 
70 #ifdef KERBEROS
71 #include <des.h>
72 #include <kerberosIV/krb.h>
73 
74 CREDENTIALS cred;
75 Key_schedule schedule;
76 int use_kerberos = 1, doencrypt;
77 char dst_realm_buf[REALM_SZ], *dest_realm;
78 
79 void	warning(const char *, ...);
80 #endif
81 
82 /*
83  * rsh - remote shell
84  */
85 int	remerr;
86 
87 static int sigs[] = { SIGINT, SIGTERM, SIGQUIT };
88 
89 char   *copyargs(char **);
90 void	sendsig(int);
91 int	checkfd(struct pollfd *, int);
92 void	talk(int, sigset_t *, pid_t, int);
93 void	usage(void);
94 int	main(int, char **);
95 #ifdef IN_RCMD
96 int	 orcmd(char **, int, const char *,
97     const char *, const char *, int *);
98 int	 orcmd_af(char **, int, const char *,
99     const char *, const char *, int *, int);
100 #endif
101 
102 int
103 main(int argc, char **argv)
104 {
105 	struct passwd *pw;
106 	struct servent *sp;
107 	sigset_t oset, nset;
108 	struct protoent *proto;
109 
110 #ifdef IN_RCMD
111 	char	*locuser = 0, *loop;
112 #endif /* IN_RCMD */
113 	int argoff, asrsh, ch, dflag, nflag, one, rem, i;
114 	pid_t pid;
115 	uid_t uid;
116 	char *args, *host, *p, *user, *name;
117 
118 	argoff = asrsh = dflag = nflag = 0;
119 	one = 1;
120 	host = user = NULL;
121 	sp = NULL;
122 
123 #ifndef IN_RCMD
124 	/*
125 	 * If called as something other than "rsh" use it as the host name,
126 	 * only for rsh.
127 	 */
128 	if (strcmp(getprogname(), "rsh") == 0)
129 		asrsh = 1;
130 	else {
131 		host = strdup(getprogname());
132 		if (host == NULL)
133 			err(1, NULL);
134 	}
135 #endif /* IN_RCMD */
136 
137 	/* handle "rsh host flags" */
138 	if (!host && argc > 2 && argv[1][0] != '-') {
139 		host = argv[1];
140 		argoff = 1;
141 	}
142 
143 #ifdef IN_RCMD
144 	if ((loop = getenv("RCMD_LOOP")) && strcmp(loop, "YES") == 0)
145 		warnx("rcmd appears to be looping!");
146 
147 	putenv("RCMD_LOOP=YES");
148 
149 # ifdef KERBEROS
150 #  ifdef CRYPT
151 #   define	OPTIONS	"8KLdek:l:np:u:wx"
152 #  else
153 #   define	OPTIONS	"8KLdek:l:np:u:w"
154 #  endif
155 # else
156 #  define	OPTIONS	"8KLdel:np:u:w"
157 # endif
158 
159 #else /* IN_RCMD */
160 
161 # ifdef KERBEROS
162 #  ifdef CRYPT
163 #   define	OPTIONS	"8KLdek:l:np:wx"
164 #  else
165 #   define	OPTIONS	"8KLdek:l:np:w"
166 #  endif
167 # else
168 #  define	OPTIONS	"8KLdel:np:w"
169 # endif
170 
171 #endif /* IN_RCMD */
172 
173 	if (!(pw = getpwuid(uid = getuid())))
174 		errx(1, "unknown user id");
175 
176 	if ((name = strdup(pw->pw_name)) == NULL)
177 		err(1, "malloc");
178 	while ((ch = getopt(argc - argoff, argv + argoff, OPTIONS)) != -1)
179 		switch(ch) {
180 		case 'K':
181 #ifdef KERBEROS
182 			use_kerberos = 0;
183 #endif
184 			break;
185 		case 'L':	/* -8Lew are ignored to allow rlogin aliases */
186 		case 'e':
187 		case 'w':
188 		case '8':
189 			break;
190 		case 'd':
191 			dflag = 1;
192 			break;
193 		case 'l':
194 			user = optarg;
195 			break;
196 #ifdef KERBEROS
197 		case 'k':
198 			strlcpy(dest_realm_buf, optarg, sizeof(dest_realm_buf));
199 			dest_realm = dst_realm_buf;
200 			break;
201 #endif
202 		case 'n':
203 			nflag = 1;
204 			break;
205 		case 'p':
206 			sp = getport(optarg, "tcp");
207 			break;
208 #ifdef IN_RCMD
209 		case 'u':
210 			if (getuid() != 0 && optarg && name &&
211 			    strcmp(name, optarg) != 0)
212 				errx(1,"only super user can use the -u option");
213 			locuser = optarg;
214 			break;
215 #endif /* IN_RCMD */
216 #ifdef KERBEROS
217 #ifdef CRYPT
218 		case 'x':
219 			doencrypt = 1;
220 			des_set_key((des_cblock *) cred.session, schedule);
221 			break;
222 #endif
223 #endif
224 		case '?':
225 		default:
226 			usage();
227 		}
228 	optind += argoff;
229 
230 	/* if haven't gotten a host yet, do so */
231 	if (!host && !(host = argv[optind++]))
232 		usage();
233 
234 	/* if no further arguments, must have been called as rlogin. */
235 	if (!argv[optind]) {
236 #ifdef IN_RCMD
237 		usage();
238 #else
239 		if (asrsh)
240 			*argv = __UNCONST("rlogin");
241 		execv(_PATH_RLOGIN, argv);
242 		err(1, "can't exec %s", _PATH_RLOGIN);
243 #endif
244 	}
245 
246 	argc -= optind;
247 	argv += optind;
248 
249 	/* Accept user1@host format, though "-l user2" overrides user1 */
250 	p = strchr(host, '@');
251 	if (p) {
252 		*p = '\0';
253 		if (!user && p > host)
254 			user = host;
255 		host = p + 1;
256 		if (*host == '\0')
257 			usage();
258 	}
259 	if (!user)
260 		user = name;
261 
262 #ifdef KERBEROS
263 #ifdef CRYPT
264 	/* -x turns off -n */
265 	if (doencrypt)
266 		nflag = 0;
267 #endif
268 #endif
269 
270 	args = copyargs(argv);
271 
272 #ifdef KERBEROS
273 	if (use_kerberos) {
274 		if (sp == NULL) {
275 			sp = getservbyname((doencrypt ? "ekshell" : "kshell"), "tcp");
276 		}
277 		if (sp == NULL) {
278 			use_kerberos = 0;
279 			warning("can't get entry for %s/tcp service",
280 			    doencrypt ? "ekshell" : "kshell");
281 		}
282 	}
283 #endif
284 	if (sp == NULL)
285 		sp = getservbyname("shell", "tcp");
286 	if (sp == NULL)
287 		errx(1, "shell/tcp: unknown service");
288 
289 #ifdef KERBEROS
290 try_connect:
291 	if (use_kerberos) {
292 #if 1
293 		struct hostent *hp;
294 
295 		/* fully qualify hostname (needed for krb_realmofhost) */
296 		hp = gethostbyname(host);
297 		if (hp != NULL && !(host = strdup(hp->h_name)))
298 			err(1, "strdup");
299 #endif
300 
301 		rem = KSUCCESS;
302 		errno = 0;
303 		if (dest_realm == NULL)
304 			dest_realm = krb_realmofhost(host);
305 
306 #ifdef CRYPT
307 		if (doencrypt)
308 			rem = krcmd_mutual(&host, sp->s_port, user, args,
309 			    &remerr, dest_realm, &cred, schedule);
310 		else
311 #endif
312 			rem = krcmd(&host, sp->s_port, user, args, &remerr,
313 			    dest_realm);
314 		if (rem < 0) {
315 			use_kerberos = 0;
316 			sp = getservbyname("shell", "tcp");
317 			if (sp == NULL)
318 				errx(1, "shell/tcp: unknown service");
319 			if (errno == ECONNREFUSED)
320 				warning("remote host doesn't support Kerberos");
321 			if (errno == ENOENT)
322 				warning("can't provide Kerberos auth data");
323 			goto try_connect;
324 		}
325 	} else {
326 		if (doencrypt)
327 			errx(1, "the -x flag requires Kerberos authentication.");
328 #ifdef IN_RCMD
329 		rem = orcmd_af(&host, sp->s_port, locuser ? locuser :
330 #else
331 		rem = rcmd_af(&host, sp->s_port,
332 #endif
333 		    name,
334 		    user, args, &remerr, PF_UNSPEC);
335 	}
336 #else /* KERBEROS */
337 
338 #ifdef IN_RCMD
339 	rem = orcmd_af(&host, sp->s_port, locuser ? locuser :
340 #else
341 	rem = rcmd_af(&host, sp->s_port,
342 #endif
343 	    name, user, args, &remerr, PF_UNSPEC);
344 #endif /* KERBEROS */
345 	(void)free(name);
346 
347 	if (rem < 0)
348 		exit(1);
349 
350 	if (remerr < 0)
351 		errx(1, "can't establish stderr");
352 	if (dflag) {
353 		if (setsockopt(rem, SOL_SOCKET, SO_DEBUG, &one,
354 		    sizeof(one)) < 0)
355 			warn("setsockopt remote");
356 		if (setsockopt(remerr, SOL_SOCKET, SO_DEBUG, &one,
357 		    sizeof(one)) < 0)
358 			warn("setsockopt stderr");
359 	}
360 	proto = getprotobyname("tcp");
361 	setsockopt(rem, proto->p_proto, TCP_NODELAY, &one, sizeof(one));
362 	setsockopt(remerr, proto->p_proto, TCP_NODELAY, &one, sizeof(one));
363 
364 
365 	(void) setuid(uid);
366 
367 	(void) sigemptyset(&nset);
368 	for (i = 0; i < sizeof(sigs) / sizeof(sigs[0]); i++)
369 		(void) sigaddset(&nset, sigs[i]);
370 
371 	(void) sigprocmask(SIG_BLOCK, &nset, &oset);
372 
373 	for (i = 0; i < sizeof(sigs) / sizeof(sigs[0]); i++) {
374 		struct sigaction sa;
375 
376 		if (sa.sa_handler != SIG_IGN) {
377 			sa.sa_handler = sendsig;
378 			(void) sigaction(sigs[i], &sa, NULL);
379 		}
380 	}
381 
382 	if (!nflag) {
383 		pid = fork();
384 		if (pid < 0)
385 			err(1, "fork");
386 	}
387 	else
388 		pid = -1;
389 
390 #if defined(KERBEROS) && defined(CRYPT)
391 	if (!doencrypt)
392 #endif
393 	{
394 		(void)ioctl(remerr, FIONBIO, &one);
395 		(void)ioctl(rem, FIONBIO, &one);
396 	}
397 
398 	talk(nflag, &oset, pid, rem);
399 
400 	if (!nflag)
401 		(void)kill(pid, SIGKILL);
402 	exit(0);
403 }
404 
405 int
406 checkfd(struct pollfd *fdp, int outfd)
407 {
408 	int nr, nw;
409 	char buf[BUFSIZ];
410 
411 	if (fdp->revents & (POLLNVAL|POLLERR|POLLHUP))
412 		return -1;
413 
414 	if ((fdp->revents & POLLIN) == 0)
415 		return 0;
416 
417 	errno = 0;
418 #if defined(KERBEROS) && defined(CRYPT)
419 	if (doencrypt)
420 		nr = des_read(fdp->fd, buf, sizeof buf);
421 	else
422 #endif
423 		nr = read(fdp->fd, buf, sizeof buf);
424 
425 	if (nr <= 0) {
426 		if (errno != EAGAIN)
427 			return -1;
428 		else
429 			return 0;
430 	}
431 	else {
432 		char *bc = buf;
433 		while (nr) {
434 			if ((nw = write(outfd, bc, nr)) <= 0)
435 				return -1;
436 			nr -= nw;
437 			bc += nw;
438 		}
439 		return 0;
440 	}
441 }
442 
443 void
444 talk(int nflag, sigset_t *oset, __pid_t pid, int rem)
445 {
446 	int nr, nw, nfds;
447 	struct pollfd fds[2], *fdp = &fds[0];
448 	char *bp, buf[BUFSIZ];
449 
450 
451 	if (!nflag && pid == 0) {
452 		(void)close(remerr);
453 
454 		fdp->events = POLLOUT|POLLNVAL|POLLERR|POLLHUP;
455 		fdp->fd = rem;
456 		nr = 0;
457 		bp = buf;
458 
459 		for (;;) {
460 			errno = 0;
461 
462 			if (nr == 0) {
463 				if ((nr = read(0, buf, sizeof buf)) == 0)
464 					goto done;
465 				if (nr == -1) {
466 					if (errno == EIO)
467 						goto done;
468 					if (errno == EINTR)
469 						continue;
470 					err(1, "read");
471 				}
472 				bp = buf;
473 			}
474 
475 rewrite:		if (poll(fdp, 1, INFTIM) == -1) {
476 				if (errno != EINTR)
477 					err(1, "poll");
478 				goto rewrite;
479 			}
480 
481 			if (fdp->revents & (POLLNVAL|POLLERR|POLLHUP))
482 				err(1, "poll");
483 
484 			if ((fdp->revents & POLLOUT) == 0)
485 				goto rewrite;
486 
487 #if defined(KERBEROS) && defined(CRYPT)
488 			if (doencrypt)
489 				nw = des_write(rem, bp, nr);
490 			else
491 #endif
492 				nw = write(rem, bp, nr);
493 
494 			if (nw < 0) {
495 				if (errno == EAGAIN)
496 					continue;
497 				err(1, "write");
498 			}
499 			bp += nw;
500 			nr -= nw;
501 		}
502 done:
503 		(void)shutdown(rem, 1);
504 		exit(0);
505 	}
506 
507 	(void) sigprocmask(SIG_SETMASK, oset, NULL);
508 	fds[0].events = fds[1].events = POLLIN|POLLNVAL|POLLERR|POLLHUP;
509 	fds[0].fd = remerr;
510 	fds[1].fd = rem;
511 	fdp = &fds[0];
512 	nfds = 2;
513 	do {
514 		if (poll(fdp, nfds, INFTIM) == -1) {
515 			if (errno != EINTR)
516 				err(1, "poll");
517 			continue;
518 		}
519 		if (fds[0].events != 0 && checkfd(&fds[0], 2) == -1) {
520 			nfds--;
521 			fds[0].events = 0;
522 			fdp = &fds[1];
523 		}
524 		if (fds[1].events != 0 && checkfd(&fds[1], 1) == -1) {
525 			nfds--;
526 			fds[1].events = 0;
527 		}
528 	}
529 	while (nfds);
530 }
531 
532 void
533 sendsig(int sig)
534 {
535 	char signo;
536 
537 	signo = sig;
538 #ifdef KERBEROS
539 #ifdef CRYPT
540 	if (doencrypt)
541 		(void)des_write(remerr, &signo, 1);
542 	else
543 #endif
544 #endif
545 		(void)write(remerr, &signo, 1);
546 }
547 
548 #ifdef KERBEROS
549 /* VARARGS */
550 void
551 warning(const char *fmt, ...)
552 {
553 	va_list ap;
554 
555 	va_start(ap, fmt);
556 	(void) fprintf(stderr, "%s: warning, using standard rsh: ",
557 	    getprogname());
558 	(void) vfprintf(stderr, fmt, ap);
559 	va_end(ap);
560 	(void) fprintf(stderr, ".\n");
561 }
562 #endif
563 
564 char *
565 copyargs(char **argv)
566 {
567 	int cc;
568 	char **ap, *args, *p, *ep;
569 
570 	cc = 0;
571 	for (ap = argv; *ap; ++ap)
572 		cc += strlen(*ap) + 1;
573 	if (!(args = malloc((u_int)cc)))
574 		err(1, "malloc");
575 	ep = args + cc;
576 	for (p = args, *p = '\0', ap = argv; *ap; ++ap) {
577 		(void)strlcpy(p, *ap, ep - p);
578 		p += strlen(p);
579 		if (ap[1])
580 			*p++ = ' ';
581 	}
582 	*p = '\0';
583 	return (args);
584 }
585 
586 void
587 usage(void)
588 {
589 
590 	(void)fprintf(stderr,
591 	    "usage: %s [-nd%s]%s[-l login] [-p port]%s [login@]host %s\n", getprogname(),
592 #ifdef KERBEROS
593 #ifdef CRYPT
594 	    "x", " [-k realm] ",
595 #else
596 	    "", " [-k realm] ",
597 #endif
598 #else
599 	    "", " ",
600 #endif
601 #ifdef IN_RCMD
602 	    " [-u locuser]", "command"
603 #else
604 	    "", "[command]"
605 #endif
606 	    );
607 	exit(1);
608 }
609