xref: /dragonfly/lib/libc/rpc/auth_time.c (revision 0302f53e78f8152d346f5a9ee1fbb6ec20f3527b)
1 /*
2  *        auth_time.c
3  *
4  * This module contains the private function __rpc_get_time_offset()
5  * which will return the difference in seconds between the local system's
6  * notion of time and a remote server's notion of time. This must be
7  * possible without calling any functions that may invoke the name
8  * service. (netdir_getbyxxx, getXbyY, etc). The function is used in the
9  * synchronize call of the authdes code to synchronize clocks between
10  * NIS+ clients and their servers.
11  *
12  * Note to minimize the amount of duplicate code, portions of the
13  * synchronize() function were folded into this code, and the synchronize
14  * call becomes simply a wrapper around this function. Further, if this
15  * function is called with a timehost it *DOES* recurse to the name
16  * server so don't use it in that mode if you are doing name service code.
17  *
18  *        Copyright (c) 1992 Sun Microsystems Inc.
19  *        All rights reserved.
20  *
21  * Side effects :
22  *        When called a client handle to a RPCBIND process is created
23  *        and destroyed. Two strings "netid" and "uaddr" are malloc'd
24  *        and returned. The SIGALRM processing is modified only if
25  *        needed to deal with TCP connections.
26  *
27  * @(#)auth_time.c  1.4       92/11/10 SMI
28  * $FreeBSD: src/lib/libc/rpc/auth_time.c,v 1.12 2007/09/20 22:35:24 matteo Exp $
29  */
30 
31 #include "namespace.h"
32 #include <stdio.h>
33 #include <syslog.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <unistd.h>
37 #include <netdb.h>
38 #include <sys/signal.h>
39 #include <sys/errno.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <arpa/inet.h>
43 #include <rpc/rpc.h>
44 #include <rpc/rpc_com.h>
45 #include <rpc/rpcb_prot.h>
46 #undef NIS
47 #include <rpcsvc/nis.h>
48 #include "un-namespace.h"
49 
50 int __rpc_get_time_offset(struct timeval *, nis_server *, char *, char **,
51           struct sockaddr_in *);
52 
53 extern int          _rpc_dtablesize(void);
54 
55 #ifdef TESTING
56 #define   msg(x)    printf("ERROR: %s\n", x)
57 /* #define msg(x) syslog(LOG_ERR, "%s", x) */
58 #else
59 #define   msg(x)
60 #endif
61 
62 static int saw_alarm = 0;
63 
64 static void
alarm_hndler(int s __unused)65 alarm_hndler(int s __unused)
66 {
67           saw_alarm = 1;
68           return;
69 }
70 
71 /*
72  * The internet time server defines the epoch to be Jan 1, 1900
73  * whereas UNIX defines it to be Jan 1, 1970. To adjust the result
74  * from internet time-service time, into UNIX time we subtract the
75  * following offset :
76  */
77 #define   NYEARS    (1970 - 1900)
78 #define   TOFFSET ((u_long)60*60*24*(365*NYEARS + (NYEARS/4)))
79 
80 
81 /*
82  * Stolen from rpc.nisd:
83  * Turn a 'universal address' into a struct sockaddr_in.
84  * Bletch.
85  */
86 static int
uaddr_to_sockaddr(char * uaddr,struct sockaddr_in * sin)87 uaddr_to_sockaddr(char *uaddr, struct sockaddr_in *sin)
88 {
89           unsigned char                 p_bytes[2];
90           int                           i;
91           unsigned long                 a[6];
92 
93           i = sscanf(uaddr, "%lu.%lu.%lu.%lu.%lu.%lu", &a[0], &a[1], &a[2],
94                                                             &a[3], &a[4], &a[5]);
95 
96           if (i < 6)
97                     return(1);
98 
99           for (i = 0; i < 4; i++)
100                     sin->sin_addr.s_addr |= (a[i] & 0x000000FF) << (8 * i);
101 
102           p_bytes[0] = (unsigned char)a[4] & 0x000000FF;
103           p_bytes[1] = (unsigned char)a[5] & 0x000000FF;
104 
105           sin->sin_family = AF_INET; /* always */
106           bcopy((char *)&p_bytes, (char *)&sin->sin_port, 2);
107 
108           return (0);
109 }
110 
111 /*
112  * free_eps()
113  *
114  * Free the strings that were strduped into the eps structure.
115  */
116 static void
free_eps(endpoint eps[],int num)117 free_eps(endpoint eps[], int num)
118 {
119           int                 i;
120 
121           for (i = 0; i < num; i++) {
122                     free(eps[i].uaddr);
123                     free(eps[i].proto);
124                     free(eps[i].family);
125           }
126           return;
127 }
128 
129 /*
130  * get_server()
131  *
132  * This function constructs a nis_server structure description for the
133  * indicated hostname.
134  *
135  * NOTE: There is a chance we may end up recursing here due to the
136  * fact that gethostbyname() could do an NIS search. Ideally, the
137  * NIS+ server will call __rpc_get_time_offset() with the nis_server
138  * structure already populated.
139  */
140 static nis_server *
get_server(struct sockaddr_in * sin,char * host,nis_server * srv,endpoint eps[],int maxep)141 get_server(struct sockaddr_in *sin,
142              char *host,                          /* name of the time host      */
143              nis_server *srv,           /* nis_server struct to use.  */
144              endpoint eps[],            /* array of endpoints                   */
145              int maxep)                           /* max array size             */
146 {
147           char                          hname[256];
148           int                           num_ep = 0, i;
149           struct hostent                *he;
150           struct hostent                dummy;
151           char                          *ptr[2];
152           endpoint            *ep;
153 
154           if (host == NULL && sin == NULL)
155                     return (NULL);
156 
157           if (sin == NULL) {
158                     he = gethostbyname(host);
159                     if (he == NULL)
160                               return(NULL);
161           } else {
162                     he = &dummy;
163                     ptr[0] = (char *)&sin->sin_addr.s_addr;
164                     ptr[1] = NULL;
165                     dummy.h_addr_list = ptr;
166           }
167 
168           /*
169            * This is lame. We go around once for TCP, then again
170            * for UDP.
171            */
172           for (i = 0, ep = eps; (he->h_addr_list[i] != NULL) && (num_ep < maxep);
173               i++, ep++, num_ep++) {
174                     struct in_addr *a;
175 
176                     a = (struct in_addr *)he->h_addr_list[i];
177                     snprintf(hname, sizeof(hname), "%s.0.111", inet_ntoa(*a));
178                     ep->uaddr = strdup(hname);
179                     ep->family = strdup("inet");
180                     ep->proto =  strdup("tcp");
181                     if (ep->uaddr == NULL || ep->family == NULL || ep->proto == NULL) {
182                               free_eps(eps, num_ep + 1);
183                               return (NULL);
184                     }
185           }
186 
187           for (i = 0; (he->h_addr_list[i] != NULL) && (num_ep < maxep);
188               i++, ep++, num_ep++) {
189                     struct in_addr *a;
190 
191                     a = (struct in_addr *)he->h_addr_list[i];
192                     snprintf(hname, sizeof(hname), "%s.0.111", inet_ntoa(*a));
193                     ep->uaddr = strdup(hname);
194                     ep->family = strdup("inet");
195                     ep->proto =  strdup("udp");
196                     if (ep->uaddr == NULL || ep->family == NULL || ep->proto == NULL) {
197                               free_eps(eps, num_ep + 1);
198                               return (NULL);
199                     }
200           }
201 
202           srv->name = (nis_name) host;
203           srv->ep.ep_len = num_ep;
204           srv->ep.ep_val = eps;
205           srv->key_type = NIS_PK_NONE;
206           srv->pkey.n_bytes = NULL;
207           srv->pkey.n_len = 0;
208           return (srv);
209 }
210 
211 /*
212  * __rpc_get_time_offset()
213  *
214  * This function uses a nis_server structure to contact the a remote
215  * machine (as named in that structure) and returns the offset in time
216  * between that machine and this one. This offset is returned in seconds
217  * and may be positive or negative.
218  *
219  * The first time through, a lot of fiddling is done with the netconfig
220  * stuff to find a suitable transport. The function is very aggressive
221  * about choosing UDP or at worst TCP if it can. This is because
222  * those transports support both the RCPBIND call and the internet
223  * time service.
224  *
225  * Once through, *uaddr is set to the universal address of
226  * the machine and *netid is set to the local netid for the transport
227  * that uaddr goes with. On the second call, the netconfig stuff
228  * is skipped and the uaddr/netid pair are used to fetch the netconfig
229  * structure and to then contact the machine for the time.
230  *
231  * td = "server" - "client"
232  */
233 int
__rpc_get_time_offset(struct timeval * td,nis_server * srv,char * thost,char ** uaddr,struct sockaddr_in * netid)234 __rpc_get_time_offset(struct timeval *td,         /* Time difference                      */
235                           nis_server *srv,                  /* NIS Server description               */
236                           char *thost,            /* if no server, this is the timehost   */
237                           char **uaddr,           /* known universal address              */
238                           struct sockaddr_in *netid)/* known network identifier           */
239 {
240           CLIENT                        *clnt;              /* Client handle    */
241           endpoint            *ep,                /* useful endpoints */
242                                         *useep = NULL;      /* endpoint of xp   */
243           char                          *useua = NULL;      /* uaddr of selected xp       */
244           int                           epl, i;             /* counters                   */
245           enum clnt_stat                status;             /* result of clnt_call        */
246           u_long                        thetime, delta;
247           int                           needfree = 0;
248           struct timeval                tv;
249           int                           time_valid;
250           int                           udp_ep = -1, tcp_ep = -1;
251           int                           a1, a2, a3, a4;
252           char                          ut[64], ipuaddr[64];
253           endpoint            teps[32];
254           nis_server                    tsrv;
255           sig_t                         oldsig = NULL; /* old alarm handler */
256           struct sockaddr_in  sin;
257           socklen_t           len;
258           int                           s = RPC_ANYSOCK;
259           int                           type = 0;
260 
261           td->tv_sec = 0;
262           td->tv_usec = 0;
263 
264           /*
265            * First check to see if we need to find and address for this
266            * server.
267            */
268           if (*uaddr == NULL) {
269                     if ((srv != NULL) && (thost != NULL)) {
270                               msg("both timehost and srv pointer used!");
271                               return (0);
272                     }
273                     if (! srv) {
274                               srv = get_server(netid, thost, &tsrv, teps, 32);
275                               if (srv == NULL) {
276                                         msg("unable to contruct server data.");
277                                         return (0);
278                               }
279                               needfree = 1;       /* need to free data in endpoints */
280                     }
281 
282                     ep = srv->ep.ep_val;
283                     epl = srv->ep.ep_len;
284 
285                     /* Identify the TCP and UDP endpoints */
286                     for (i = 0;
287                               (i < epl) && ((udp_ep == -1) || (tcp_ep == -1)); i++) {
288                               if (strcasecmp(ep[i].proto, "udp") == 0)
289                                         udp_ep = i;
290                               if (strcasecmp(ep[i].proto, "tcp") == 0)
291                                         tcp_ep = i;
292                     }
293 
294                     /* Check to see if it is UDP or TCP */
295                     if (tcp_ep > -1) {
296                               useep = &ep[tcp_ep];
297                               useua = ep[tcp_ep].uaddr;
298                               type = SOCK_STREAM;
299                     } else if (udp_ep > -1) {
300                               useep = &ep[udp_ep];
301                               useua = ep[udp_ep].uaddr;
302                               type = SOCK_DGRAM;
303                     }
304 
305                     if (useep == NULL) {
306                               msg("no acceptable transport endpoints.");
307                               if (needfree)
308                                         free_eps(teps, tsrv.ep.ep_len);
309                               return (0);
310                     }
311           }
312 
313           /*
314            * Create a sockaddr from the uaddr.
315            */
316           if (*uaddr != NULL)
317                     useua = *uaddr;
318 
319           /* Fixup test for NIS+ */
320           sscanf(useua, "%d.%d.%d.%d.", &a1, &a2, &a3, &a4);
321           sprintf(ipuaddr, "%d.%d.%d.%d.0.111", a1, a2, a3, a4);
322           useua = &ipuaddr[0];
323 
324           bzero((char *)&sin, sizeof(sin));
325           if (uaddr_to_sockaddr(useua, &sin)) {
326                     msg("unable to translate uaddr to sockaddr.");
327                     if (needfree)
328                               free_eps(teps, tsrv.ep.ep_len);
329                     return (0);
330           }
331 
332           /*
333            * Create the client handle to rpcbind. Note we always try
334            * version 3 since that is the earliest version that supports
335            * the RPCB_GETTIME call. Also it is the version that comes
336            * standard with SVR4. Since most everyone supports TCP/IP
337            * we could consider trying the rtime call first.
338            */
339           clnt = clnttcp_create(&sin, RPCBPROG, RPCBVERS, &s, 0, 0);
340           if (clnt == NULL) {
341                     msg("unable to create client handle to rpcbind.");
342                     if (needfree)
343                               free_eps(teps, tsrv.ep.ep_len);
344                     return (0);
345           }
346 
347           tv.tv_sec = 5;
348           tv.tv_usec = 0;
349           time_valid = 0;
350           status = clnt_call(clnt, RPCBPROC_GETTIME, (xdrproc_t)xdr_void, NULL,
351                                                   (xdrproc_t)xdr_u_long, &thetime, tv);
352           /*
353            * The only error we check for is anything but success. In
354            * fact we could have seen PROGMISMATCH if talking to a 4.1
355            * machine (pmap v2) or TIMEDOUT if the net was busy.
356            */
357           if (status == RPC_SUCCESS)
358                     time_valid = 1;
359           else {
360                     int save;
361 
362                     /* Blow away possible stale CLNT handle. */
363                     if (clnt != NULL) {
364                               clnt_destroy(clnt);
365                               clnt = NULL;
366                     }
367 
368                     /*
369                      * Convert PMAP address into timeservice address
370                      * We take advantage of the fact that we "know" what
371                      * the universal address looks like for inet transports.
372                      *
373                      * We also know that the internet timeservice is always
374                      * listening on port 37.
375                      */
376                     sscanf(useua, "%d.%d.%d.%d.", &a1, &a2, &a3, &a4);
377                     sprintf(ut, "%d.%d.%d.%d.0.37", a1, a2, a3, a4);
378 
379                     if (uaddr_to_sockaddr(ut, &sin)) {
380                               msg("cannot convert timeservice uaddr to sockaddr.");
381                               goto error;
382                     }
383 
384                     s = _socket(AF_INET, type, 0);
385                     if (s == -1) {
386                               msg("unable to open fd to network.");
387                               goto error;
388                     }
389 
390                     /*
391                      * Now depending on whether or not we're talking to
392                      * UDP we set a timeout or not.
393                      */
394                     if (type == SOCK_DGRAM) {
395                               struct timeval timeout = { 20, 0 };
396                               struct sockaddr_in from;
397                               fd_set readfds;
398                               int res;
399 
400                               if (_sendto(s, &thetime, sizeof(thetime), 0,
401                                         (struct sockaddr *)&sin, sizeof(sin)) == -1) {
402                                         msg("udp : sendto failed.");
403                                         goto error;
404                               }
405                               do {
406                                         FD_ZERO(&readfds);
407                                         FD_SET(s, &readfds);
408                                         res = _select(_rpc_dtablesize(), &readfds,
409                                              NULL, NULL, &timeout);
410                               } while (res < 0 && errno == EINTR);
411                               if (res <= 0)
412                                         goto error;
413                               len = sizeof(from);
414                               res = _recvfrom(s, (char *)&thetime, sizeof(thetime), 0,
415                                                (struct sockaddr *)&from, &len);
416                               if (res == -1) {
417                                         msg("recvfrom failed on udp transport.");
418                                         goto error;
419                               }
420                               time_valid = 1;
421                     } else {
422                               int res;
423 
424                               oldsig = signal(SIGALRM, alarm_hndler);
425                               saw_alarm = 0; /* global tracking the alarm */
426                               alarm(20); /* only wait 20 seconds */
427                               res = _connect(s, (struct sockaddr *)&sin, sizeof(sin));
428                               if (res == -1) {
429                                         msg("failed to connect to tcp endpoint.");
430                                         goto error;
431                               }
432                               if (saw_alarm) {
433                                         msg("alarm caught it, must be unreachable.");
434                                         goto error;
435                               }
436                               res = _read(s, (char *)&thetime, sizeof(thetime));
437                               if (res != sizeof(thetime)) {
438                                         if (saw_alarm) {
439                                                   msg("timed out TCP call.");
440                                         } else {
441                                                   msg("wrong size of results returned");
442                                         }
443 
444                                         goto error;
445                               }
446                               time_valid = 1;
447                     }
448                     save = errno;
449                     _close(s);
450                     errno = save;
451                     s = RPC_ANYSOCK;
452 
453                     if (time_valid) {
454                               thetime = ntohl(thetime);
455                               thetime = thetime - TOFFSET; /* adjust to UNIX time */
456                     } else
457                               thetime = 0;
458           }
459 
460           gettimeofday(&tv, 0);
461 
462 error:
463           /*
464            * clean up our allocated data structures.
465            */
466 
467           if (s != RPC_ANYSOCK)
468                     _close(s);
469 
470           if (clnt != NULL)
471                     clnt_destroy(clnt);
472 
473           alarm(0); /* reset that alarm if its outstanding */
474           if (oldsig) {
475                     signal(SIGALRM, oldsig);
476           }
477 
478           /*
479            * note, don't free uaddr strings until after we've made a
480            * copy of them.
481            */
482           if (time_valid) {
483                     if (*uaddr == NULL)
484                               *uaddr = strdup(useua);
485 
486                     /* Round to the nearest second */
487                     tv.tv_sec += (tv.tv_sec > 500000) ? 1 : 0;
488                     delta = (thetime > tv.tv_sec) ? thetime - tv.tv_sec :
489                                                             tv.tv_sec - thetime;
490                     td->tv_sec = (thetime < tv.tv_sec) ? - delta : delta;
491                     td->tv_usec = 0;
492           } else {
493                     msg("unable to get the server's time.");
494           }
495 
496           if (needfree)
497                     free_eps(teps, tsrv.ep.ep_len);
498 
499           return (time_valid);
500 }
501