xref: /netbsd-src/usr.bin/rsh/rsh.c (revision fd5cb0acea84d278e04e640d37ca2398f894991f)
1 /*	$NetBSD: rsh.c,v 1.25 2005/01/13 23:02:28 ginsbach 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.25 2005/01/13 23:02:28 ginsbach 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 	if (!nflag && pid == 0) {
451 		(void)close(remerr);
452 
453 		fdp->events = POLLOUT|POLLNVAL|POLLERR|POLLHUP;
454 		fdp->fd = rem;
455 		nr = 0;
456 		bp = buf;
457 
458 		for (;;) {
459 			errno = 0;
460 
461 			if (nr == 0) {
462 				if ((nr = read(0, buf, sizeof buf)) == 0)
463 					goto done;
464 				if (nr == -1) {
465 					if (errno == EIO)
466 						goto done;
467 					if (errno == EINTR)
468 						continue;
469 					err(1, "read");
470 				}
471 				bp = buf;
472 			}
473 
474 rewrite:		if (poll(fdp, 1, INFTIM) == -1) {
475 				if (errno != EINTR)
476 					err(1, "poll");
477 				goto rewrite;
478 			}
479 
480 			if (fdp->revents & (POLLNVAL|POLLERR|POLLHUP))
481 				err(1, "poll");
482 
483 			if ((fdp->revents & POLLOUT) == 0)
484 				goto rewrite;
485 
486 #if defined(KERBEROS) && defined(CRYPT)
487 			if (doencrypt)
488 				nw = des_write(rem, bp, nr);
489 			else
490 #endif
491 				nw = write(rem, bp, nr);
492 
493 			if (nw < 0) {
494 				if (errno == EAGAIN)
495 					continue;
496 				err(1, "write");
497 			}
498 			bp += nw;
499 			nr -= nw;
500 		}
501 done:
502 		(void)shutdown(rem, 1);
503 		exit(0);
504 	}
505 
506 	(void)sigprocmask(SIG_SETMASK, oset, NULL);
507 	fds[0].events = fds[1].events = POLLIN|POLLNVAL|POLLERR|POLLHUP;
508 	fds[0].fd = remerr;
509 	fds[1].fd = rem;
510 	fdp = &fds[0];
511 	nfds = 2;
512 	do {
513 		if (poll(fdp, nfds, INFTIM) == -1) {
514 			if (errno != EINTR)
515 				err(1, "poll");
516 			continue;
517 		}
518 		if (fds[0].events != 0 && checkfd(&fds[0], 2) == -1) {
519 			nfds--;
520 			fds[0].events = 0;
521 			fdp = &fds[1];
522 		}
523 		if (fds[1].events != 0 && checkfd(&fds[1], 1) == -1) {
524 			nfds--;
525 			fds[1].events = 0;
526 		}
527 	}
528 	while (nfds);
529 }
530 
531 void
532 sendsig(int sig)
533 {
534 	char signo;
535 
536 	signo = sig;
537 #ifdef KERBEROS
538 #ifdef CRYPT
539 	if (doencrypt)
540 		(void)des_write(remerr, &signo, 1);
541 	else
542 #endif
543 #endif
544 		(void)write(remerr, &signo, 1);
545 }
546 
547 #ifdef KERBEROS
548 /* VARARGS */
549 void
550 warning(const char *fmt, ...)
551 {
552 	va_list ap;
553 
554 	va_start(ap, fmt);
555 	(void)fprintf(stderr, "%s: warning, using standard rsh: ",
556 	    getprogname());
557 	(void)vfprintf(stderr, fmt, ap);
558 	va_end(ap);
559 	(void)fprintf(stderr, ".\n");
560 }
561 #endif
562 
563 char *
564 copyargs(char **argv)
565 {
566 	int cc;
567 	char **ap, *args, *p, *ep;
568 
569 	cc = 0;
570 	for (ap = argv; *ap; ++ap)
571 		cc += strlen(*ap) + 1;
572 	if (!(args = malloc((u_int)cc)))
573 		err(1, "malloc");
574 	ep = args + cc;
575 	for (p = args, *p = '\0', ap = argv; *ap; ++ap) {
576 		(void)strlcpy(p, *ap, ep - p);
577 		p += strlen(p);
578 		if (ap[1])
579 			*p++ = ' ';
580 	}
581 	*p = '\0';
582 	return (args);
583 }
584 
585 void
586 usage(void)
587 {
588 
589 	(void)fprintf(stderr,
590 	    "usage: %s [-nd%s]%s[-l login] [-p port]%s [login@]host %s\n", getprogname(),
591 #ifdef KERBEROS
592 #ifdef CRYPT
593 	    "x", " [-k realm] ",
594 #else
595 	    "", " [-k realm] ",
596 #endif
597 #else
598 	    "", " ",
599 #endif
600 #ifdef IN_RCMD
601 	    " [-u locuser]", "command"
602 #else
603 	    "", "[command]"
604 #endif
605 	    );
606 	exit(1);
607 }
608