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