fe733424242e15bd3908a7567d3b861e2a611ac1
[platform/upstream/glibc.git] / inet / rcmd.c
1 /*
2  * Copyright (c) 1983, 1993, 1994
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
34 #if defined(LIBC_SCCS) && !defined(lint)
35 static char sccsid[] = "@(#)rcmd.c      8.3 (Berkeley) 3/26/94";
36 #endif /* LIBC_SCCS and not lint */
37
38 #include <sys/param.h>
39 #include <sys/poll.h>
40 #include <sys/socket.h>
41 #include <sys/stat.h>
42
43 #include <netinet/in.h>
44 #include <arpa/inet.h>
45
46 #include <alloca.h>
47 #include <signal.h>
48 #include <fcntl.h>
49 #include <netdb.h>
50 #include <unistd.h>
51 #include <pwd.h>
52 #include <errno.h>
53 #include <stdio.h>
54 #include <ctype.h>
55 #include <string.h>
56
57
58 int __ivaliduser __P ((FILE *, u_int32_t, const char *, const char *));
59 static int __ivaliduser2 __P ((FILE *, u_int32_t, const char *, const char *,
60                                const char *));
61
62
63 int
64 rcmd(ahost, rport, locuser, remuser, cmd, fd2p)
65         char **ahost;
66         u_short rport;
67         const char *locuser, *remuser, *cmd;
68         int *fd2p;
69 {
70         struct hostent hostbuf, *hp;
71         size_t hstbuflen;
72         char *tmphstbuf;
73         struct sockaddr_in sin, from;
74         struct pollfd pfd[2];
75         int32_t oldmask;
76         pid_t pid;
77         int s, lport, timo;
78         char c;
79         int herr;
80
81         pid = __getpid();
82
83         hstbuflen = 1024;
84         tmphstbuf = __alloca (hstbuflen);
85         while (__gethostbyname_r (*ahost, &hostbuf, tmphstbuf, hstbuflen,
86                                   &hp, &herr) < 0)
87           if (herr != NETDB_INTERNAL || errno != ERANGE)
88             {
89               __set_h_errno (herr);
90               herror(*ahost);
91               return -1;
92             }
93           else
94             {
95               /* Enlarge the buffer.  */
96               hstbuflen *= 2;
97               tmphstbuf = __alloca (hstbuflen);
98             }
99
100         pfd[0].events = POLLIN;
101         pfd[1].events = POLLIN;
102
103         *ahost = hp->h_name;
104         oldmask = __sigblock(sigmask(SIGURG));
105         for (timo = 1, lport = IPPORT_RESERVED - 1;;) {
106                 s = rresvport(&lport);
107                 if (s < 0) {
108                         if (errno == EAGAIN)
109                                 (void)fprintf(stderr,
110                                     _("rcmd: socket: All ports in use\n"));
111                         else
112                                 (void)fprintf(stderr, "rcmd: socket: %m\n");
113                         __sigsetmask(oldmask);
114                         return -1;
115                 }
116                 __fcntl(s, F_SETOWN, pid);
117                 sin.sin_family = hp->h_addrtype;
118                 bcopy(hp->h_addr_list[0], &sin.sin_addr,
119                       MIN (sizeof (sin.sin_addr), hp->h_length));
120                 sin.sin_port = rport;
121                 if (__connect(s, (struct sockaddr *)&sin, sizeof(sin)) >= 0)
122                         break;
123                 (void)__close(s);
124                 if (errno == EADDRINUSE) {
125                         lport--;
126                         continue;
127                 }
128                 if (errno == ECONNREFUSED && timo <= 16) {
129                         (void)__sleep(timo);
130                         timo *= 2;
131                         continue;
132                 }
133                 if (hp->h_addr_list[1] != NULL) {
134                         int oerrno = errno;
135
136                         (void)fprintf(stderr, _("connect to address %s: "),
137                             inet_ntoa(sin.sin_addr));
138                         __set_errno (oerrno);
139                         perror(0);
140                         hp->h_addr_list++;
141                         bcopy(hp->h_addr_list[0], &sin.sin_addr,
142                               MIN (sizeof (sin.sin_addr), hp->h_length));
143                         (void)fprintf(stderr, _("Trying %s...\n"),
144                             inet_ntoa(sin.sin_addr));
145                         continue;
146                 }
147                 (void)fprintf(stderr, "%s: %m\n", hp->h_name);
148                 __sigsetmask(oldmask);
149                 return -1;
150         }
151         lport--;
152         if (fd2p == 0) {
153                 __write(s, "", 1);
154                 lport = 0;
155         } else {
156                 char num[8];
157                 int s2 = rresvport(&lport), s3;
158                 size_t len = sizeof(from);
159
160                 if (s2 < 0)
161                         goto bad;
162                 listen(s2, 1);
163                 (void)__snprintf(num, sizeof(num), "%d", lport);
164                 if (__write(s, num, strlen(num)+1) != strlen(num)+1) {
165                         (void)fprintf(stderr,
166                             _("rcmd: write (setting up stderr): %m\n"));
167                         (void)__close(s2);
168                         goto bad;
169                 }
170                 pfd[0].fd = s;
171                 pfd[1].fd = s2;
172                 __set_errno (0);
173                 if (__poll (pfd, 2, -1) < 1 || (pfd[1].revents & POLLIN) == 0){
174                         if (errno != 0)
175                                 (void)fprintf(stderr,
176                                   _("rcmd: poll (setting up stderr): %m\n"));
177                         else
178                                 (void)fprintf(stderr,
179                              _("poll: protocol failure in circuit setup\n"));
180                         (void)__close(s2);
181                         goto bad;
182                 }
183                 s3 = accept(s2, (struct sockaddr *)&from, &len);
184                 (void)__close(s2);
185                 if (s3 < 0) {
186                         (void)fprintf(stderr,
187                             "rcmd: accept: %m\n");
188                         lport = 0;
189                         goto bad;
190                 }
191                 *fd2p = s3;
192                 from.sin_port = ntohs((u_short)from.sin_port);
193                 if (from.sin_family != AF_INET ||
194                     from.sin_port >= IPPORT_RESERVED ||
195                     from.sin_port < IPPORT_RESERVED / 2) {
196                         (void)fprintf(stderr,
197                             _("socket: protocol failure in circuit setup\n"));
198                         goto bad2;
199                 }
200         }
201         (void)__write(s, locuser, strlen(locuser)+1);
202         (void)__write(s, remuser, strlen(remuser)+1);
203         (void)__write(s, cmd, strlen(cmd)+1);
204         if (__read(s, &c, 1) != 1) {
205                 (void)fprintf(stderr,
206                     "rcmd: %s: %m\n", *ahost);
207                 goto bad2;
208         }
209         if (c != 0) {
210                 while (__read(s, &c, 1) == 1) {
211                         (void)__write(STDERR_FILENO, &c, 1);
212                         if (c == '\n')
213                                 break;
214                 }
215                 goto bad2;
216         }
217         __sigsetmask(oldmask);
218         return s;
219 bad2:
220         if (lport)
221                 (void)__close(*fd2p);
222 bad:
223         (void)__close(s);
224         __sigsetmask(oldmask);
225         return -1;
226 }
227
228 int
229 rresvport(alport)
230         int *alport;
231 {
232         struct sockaddr_in sin;
233         int s;
234
235         sin.sin_family = AF_INET;
236         sin.sin_addr.s_addr = INADDR_ANY;
237         s = __socket(AF_INET, SOCK_STREAM, 0);
238         if (s < 0)
239                 return -1;
240         for (;;) {
241                 sin.sin_port = htons((u_short)*alport);
242                 if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) >= 0)
243                         return s;
244                 if (errno != EADDRINUSE) {
245                         (void)__close(s);
246                         return -1;
247                 }
248                 (*alport)--;
249                 if (*alport == IPPORT_RESERVED/2) {
250                         (void)__close(s);
251                         __set_errno (EAGAIN);           /* close */
252                         return -1;
253                 }
254         }
255 }
256
257 int     __check_rhosts_file = 1;
258 char    *__rcmd_errstr;
259
260 int
261 ruserok(rhost, superuser, ruser, luser)
262         const char *rhost, *ruser, *luser;
263         int superuser;
264 {
265         struct hostent hostbuf, *hp;
266         size_t buflen;
267         char *buffer;
268         u_int32_t addr;
269         char **ap;
270         int herr;
271
272         buflen = 1024;
273         buffer = __alloca (buflen);
274
275         while (__gethostbyname_r (rhost, &hostbuf, buffer, buflen, &hp, &herr)
276                < 0)
277           if (herr != NETDB_INTERNAL || errno != ERANGE)
278             return -1;
279           else
280             {
281               /* Enlarge the buffer.  */
282               buflen *= 2;
283               buffer = __alloca (buflen);
284             }
285
286         for (ap = hp->h_addr_list; *ap; ++ap) {
287                 bcopy(*ap, &addr, sizeof(addr));
288                 if (iruserok(addr, superuser, ruser, luser, rhost) == 0)
289                         return 0;
290         }
291         return -1;
292 }
293
294 /* Extremely paranoid file open function. */
295 static FILE *
296 iruserfopen (char *file, uid_t okuser)
297 {
298   struct stat st;
299   char *cp = NULL;
300   FILE *res = NULL;
301
302   /* If not a regular file, if owned by someone other than user or
303      root, if writeable by anyone but the owner, or if hardlinked
304      anywhere, quit.  */
305   cp = NULL;
306   if (__lxstat (_STAT_VER, file, &st))
307     cp = _("lstat failed");
308   else if (!S_ISREG (st.st_mode))
309     cp = _("not regular file");
310   else
311     {
312       res = fopen (file, "r");
313       if (!res)
314         cp = _("cannot open");
315       else if (__fxstat (_STAT_VER, fileno (res), &st) < 0)
316         cp = _("fstat failed");
317       else if (st.st_uid && st.st_uid != okuser)
318         cp = _("bad owner");
319       else if (st.st_mode & (S_IWGRP|S_IWOTH))
320         cp = _("writeable by other than owner");
321       else if (st.st_nlink > 1)
322         cp = _("hard linked somewhere");
323     }
324
325   /* If there were any problems, quit.  */
326   if (cp != NULL)
327     {
328       __rcmd_errstr = cp;
329       if (res)
330         fclose (res);
331       return NULL;
332     }
333
334   return res;
335 }
336
337 /*
338  * New .rhosts strategy: We are passed an ip address. We spin through
339  * hosts.equiv and .rhosts looking for a match. When the .rhosts only
340  * has ip addresses, we don't have to trust a nameserver.  When it
341  * contains hostnames, we spin through the list of addresses the nameserver
342  * gives us and look for a match.
343  *
344  * Returns 0 if ok, -1 if not ok.
345  */
346 static int
347 iruserok2 (raddr, superuser, ruser, luser, rhost)
348      u_int32_t raddr;
349      int superuser;
350      const char *ruser, *luser, *rhost;
351 {
352   FILE *hostf = NULL;
353   int isbad;
354
355   if (!superuser)
356     hostf = iruserfopen (_PATH_HEQUIV, 0);
357
358   if (hostf)
359     {
360       isbad = __ivaliduser2 (hostf, raddr, luser, ruser, rhost);
361       fclose (hostf);
362
363       if (!isbad)
364         return 0;
365     }
366
367   if (__check_rhosts_file || superuser)
368     {
369       char *pbuf;
370       struct passwd pwdbuf, *pwd;
371       size_t dirlen;
372       size_t buflen = __sysconf (_SC_GETPW_R_SIZE_MAX);
373       char *buffer = __alloca (buflen);
374       uid_t uid;
375
376       if (__getpwnam_r (luser, &pwdbuf, buffer, buflen, &pwd))
377         return -1;
378
379       dirlen = strlen (pwd->pw_dir);
380       pbuf = alloca (dirlen + sizeof "/.rhosts");
381       __mempcpy (__mempcpy (pbuf, pwd->pw_dir, dirlen),
382                  "/.rhosts", sizeof "/.rhosts");
383
384        /* Change effective uid while reading .rhosts.  If root and
385           reading an NFS mounted file system, can't read files that
386           are protected read/write owner only.  */
387        uid = __geteuid ();
388        seteuid (pwd->pw_uid);
389        hostf = iruserfopen (pbuf, pwd->pw_uid);
390
391        if (hostf != NULL)
392          {
393            isbad = __ivaliduser2 (hostf, raddr, luser, ruser, rhost);
394            fclose (hostf);
395          }
396
397        seteuid (uid);
398        return isbad;
399     }
400   return -1;
401 }
402
403 /* This is the exported version.  */
404 int
405 iruserok (raddr, superuser, ruser, luser)
406      u_int32_t raddr;
407      int superuser;
408      const char *ruser, *luser;
409 {
410   return iruserok2 (raddr, superuser, ruser, luser, "-");
411 }
412
413 /*
414  * XXX
415  * Don't make static, used by lpd(8).
416  *
417  * This function is not used anymore. It is only present because lpd(8)
418  * calls it (!?!). We simply call __invaliduser2() with an illegal rhost
419  * argument. This means that netgroups won't work in .rhost/hosts.equiv
420  * files. If you want lpd to work with netgroups, fix lpd to use ruserok()
421  * or PAM.
422  * Returns 0 if ok, -1 if not ok.
423  */
424 int
425 __ivaliduser(hostf, raddr, luser, ruser)
426         FILE *hostf;
427         u_int32_t raddr;
428         const char *luser, *ruser;
429 {
430         return __ivaliduser2(hostf, raddr, luser, ruser, "-");
431 }
432
433
434 /* Returns 1 on positive match, 0 on no match, -1 on negative match.  */
435 static int
436 internal_function
437 __icheckhost (raddr, lhost, rhost)
438         u_int32_t raddr;
439         char *lhost;
440         const char *rhost;
441 {
442         struct hostent hostbuf, *hp;
443         size_t buflen;
444         char *buffer;
445         int herr;
446         int save_errno;
447         u_int32_t laddr;
448         int negate=1;    /* Multiply return with this to get -1 instead of 1 */
449         char **pp, *user;
450
451         /* Check nis netgroup.  */
452         if (strncmp ("+@", lhost, 2) == 0)
453                 return innetgr (&lhost[2], rhost, NULL, NULL);
454
455         if (strncmp ("-@", lhost, 2) == 0)
456                 return -innetgr (&lhost[2], rhost, NULL, NULL);
457
458         /* -host */
459         if (strncmp ("-", lhost,1) == 0) {
460                 negate = -1;
461                 lhost++;
462         } else if (strcmp ("+",lhost) == 0) {
463                 return 1;                    /* asking for trouble, but ok.. */
464         }
465
466         /* Try for raw ip address first. */
467         if (isdigit (*lhost) && (long) (laddr = inet_addr (lhost)) != -1)
468                 return negate * (! (raddr ^ laddr));
469
470         /* Better be a hostname. */
471         buflen = 1024;
472         buffer = __alloca (buflen);
473         save_errno = errno;
474         while (__gethostbyname_r (lhost, &hostbuf, buffer, buflen, &hp, &herr)
475                < 0)
476                 if (herr != NETDB_INTERNAL || errno != ERANGE)
477                         return (0);
478                 else {
479                         /* Enlarge the buffer.  */
480                         buflen *= 2;
481                         buffer = __alloca (buflen);
482                         __set_errno (0);
483                 }
484         __set_errno (save_errno);
485         if (hp == NULL)
486                 return 0;
487
488         /* Spin through ip addresses. */
489         for (pp = hp->h_addr_list; *pp; ++pp)
490                 if (!memcmp (&raddr, *pp, sizeof (u_int32_t)))
491                         return negate;
492
493         /* No match. */
494         return (0);
495 }
496
497 /* Returns 1 on positive match, 0 on no match, -1 on negative match.  */
498 static int
499 internal_function
500 __icheckuser (luser, ruser)
501         const char *luser, *ruser;
502 {
503     /*
504       luser is user entry from .rhosts/hosts.equiv file
505       ruser is user id on remote host
506       */
507     char *user;
508
509     /* [-+]@netgroup */
510     if (strncmp ("+@", luser, 2) == 0)
511         return innetgr (&luser[2], NULL, ruser, NULL);
512
513     if (strncmp ("-@", luser,2) == 0)
514         return -innetgr (&luser[2], NULL, ruser, NULL);
515
516     /* -user */
517     if (strncmp ("-", luser, 1) == 0)
518         return -(strcmp (&luser[1], ruser) == 0);
519
520     /* + */
521     if (strcmp ("+", luser) == 0)
522         return 1;
523
524     /* simple string match */
525     return strcmp (ruser, luser) == 0;
526 }
527
528 /*
529  * Returns 1 for blank lines (or only comment lines) and 0 otherwise
530  */
531 static int
532 __isempty(p)
533         char *p;
534 {
535     while (*p && isspace (*p)) {
536         ++p;
537     }
538
539     return (*p == '\0' || *p == '#') ? 1 : 0 ;
540 }
541
542 /*
543  * Returns 0 if positive match, -1 if _not_ ok.
544  */
545 static int
546 __ivaliduser2(hostf, raddr, luser, ruser, rhost)
547         FILE *hostf;
548         u_int32_t raddr;
549         const char *luser, *ruser, *rhost;
550 {
551     register const char *user;
552     register char *p;
553     int hcheck, ucheck;
554     char *buf = NULL;
555     size_t bufsize = 0;
556     int retval = -1;
557
558     while (__getline (&buf, &bufsize, hostf) > 0) {
559         buf[bufsize - 1] = '\0'; /* Make sure it's terminated.  */
560         p = buf;
561
562         /* Skip empty or comment lines */
563         if (__isempty (p)) {
564             continue;
565         }
566
567         /* Skip lines that are too long. */
568         if (strchr (p, '\n') == NULL) {
569             int ch = getc (hostf);
570
571             while (ch != '\n' && ch != EOF)
572                 ch = getc (hostf);
573             continue;
574         }
575
576         for (;*p && !isspace(*p); ++p) {
577             *p = tolower (*p);
578         }
579
580         /* Next we want to find the permitted name for the remote user.  */
581         if (*p == ' ' || *p == '\t') {
582             /* <nul> terminate hostname and skip spaces */
583             for (*p++='\0'; *p && isspace (*p); ++p);
584
585             user = p;                   /* this is the user's name */
586             while (*p && !isspace (*p))
587                 ++p;                    /* find end of user's name */
588         } else
589             user = p;
590
591         *p = '\0';              /* <nul> terminate username (+host?) */
592
593         /* buf -> host(?) ; user -> username(?) */
594
595         /* First check host part */
596         hcheck = __icheckhost (raddr, buf, rhost);
597
598         if (hcheck < 0)
599             break;
600
601         if (hcheck) {
602             /* Then check user part */
603             if (! (*user))
604                 user = luser;
605
606             ucheck = __icheckuser (user, ruser);
607
608             /* Positive 'host user' match? */
609             if (ucheck > 0) {
610                 retval = 0;
611                 break;
612             }
613
614             /* Negative 'host -user' match? */
615             if (ucheck < 0)
616                 break;
617
618             /* Neither, go on looking for match */
619         }
620     }
621
622     if (buf != NULL)
623       free (buf);
624
625     return retval;
626 }