xref: /openbsd-src/usr.sbin/ntpd/client.c (revision 7350f337b9e3eb4461d99580e625c7ef148d107c)
1 /*	$OpenBSD: client.c,v 1.109 2019/06/20 07:28:18 otto Exp $ */
2 
3 /*
4  * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
5  * Copyright (c) 2004 Alexander Guy <alexander.guy@andern.org>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/types.h>
21 #include <errno.h>
22 #include <md5.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <time.h>
27 #include <unistd.h>
28 
29 #include "ntpd.h"
30 
31 int	client_update(struct ntp_peer *);
32 int	auto_cmp(const void *, const void *);
33 void	handle_auto(double);
34 void	set_deadline(struct ntp_peer *, time_t);
35 
36 void
37 set_next(struct ntp_peer *p, time_t t)
38 {
39 	p->next = getmonotime() + t;
40 	p->deadline = 0;
41 	p->poll = t;
42 }
43 
44 void
45 set_deadline(struct ntp_peer *p, time_t t)
46 {
47 	p->deadline = getmonotime() + t;
48 	p->next = 0;
49 }
50 
51 int
52 client_peer_init(struct ntp_peer *p)
53 {
54 	if ((p->query = calloc(1, sizeof(struct ntp_query))) == NULL)
55 		fatal("client_peer_init calloc");
56 	p->query->fd = -1;
57 	p->query->msg.status = MODE_CLIENT | (NTP_VERSION << 3);
58 	p->state = STATE_NONE;
59 	p->shift = 0;
60 	p->trustlevel = TRUSTLEVEL_PATHETIC;
61 	p->lasterror = 0;
62 	p->senderrors = 0;
63 
64 	return (client_addr_init(p));
65 }
66 
67 int
68 client_addr_init(struct ntp_peer *p)
69 {
70 	struct sockaddr_in	*sa_in;
71 	struct sockaddr_in6	*sa_in6;
72 	struct ntp_addr		*h;
73 
74 	for (h = p->addr; h != NULL; h = h->next) {
75 		switch (h->ss.ss_family) {
76 		case AF_INET:
77 			sa_in = (struct sockaddr_in *)&h->ss;
78 			if (ntohs(sa_in->sin_port) == 0)
79 				sa_in->sin_port = htons(123);
80 			p->state = STATE_DNS_DONE;
81 			break;
82 		case AF_INET6:
83 			sa_in6 = (struct sockaddr_in6 *)&h->ss;
84 			if (ntohs(sa_in6->sin6_port) == 0)
85 				sa_in6->sin6_port = htons(123);
86 			p->state = STATE_DNS_DONE;
87 			break;
88 		default:
89 			fatalx("king bula sez: wrong AF in client_addr_init");
90 			/* NOTREACHED */
91 		}
92 	}
93 
94 	p->query->fd = -1;
95 	set_next(p, 0);
96 
97 	return (0);
98 }
99 
100 int
101 client_nextaddr(struct ntp_peer *p)
102 {
103 	if (p->query->fd != -1) {
104 		close(p->query->fd);
105 		p->query->fd = -1;
106 	}
107 
108 	if (p->state == STATE_DNS_INPROGRESS)
109 		return (-1);
110 
111 	if (p->addr_head.a == NULL) {
112 		priv_dns(IMSG_HOST_DNS, p->addr_head.name, p->id);
113 		p->state = STATE_DNS_INPROGRESS;
114 		return (-1);
115 	}
116 
117 	if (p->addr == NULL || (p->addr = p->addr->next) == NULL)
118 		p->addr = p->addr_head.a;
119 
120 	p->shift = 0;
121 	p->trustlevel = TRUSTLEVEL_PATHETIC;
122 
123 	return (0);
124 }
125 
126 int
127 client_query(struct ntp_peer *p)
128 {
129 	int	val;
130 
131 	if (p->addr == NULL && client_nextaddr(p) == -1) {
132 		if (conf->settime)
133 			set_next(p, INTERVAL_AUIO_DNSFAIL);
134 		else
135 			set_next(p, MAXIMUM(SETTIME_TIMEOUT,
136 			    scale_interval(INTERVAL_QUERY_AGGRESSIVE)));
137 		return (0);
138 	}
139 
140 	if (conf->status.synced && p->addr->notauth) {
141 		peer_addr_head_clear(p);
142 		client_nextaddr(p);
143 		return (0);
144 	}
145 
146 	if (p->state < STATE_DNS_DONE || p->addr == NULL)
147 		return (-1);
148 
149 	if (p->query->fd == -1) {
150 		struct sockaddr *sa = (struct sockaddr *)&p->addr->ss;
151 		struct sockaddr *qa4 = (struct sockaddr *)&p->query_addr4;
152 		struct sockaddr *qa6 = (struct sockaddr *)&p->query_addr6;
153 
154 		if ((p->query->fd = socket(p->addr->ss.ss_family, SOCK_DGRAM,
155 		    0)) == -1)
156 			fatal("client_query socket");
157 
158 		if (p->addr->ss.ss_family == qa4->sa_family) {
159 			if (bind(p->query->fd, qa4, SA_LEN(qa4)) == -1)
160 				fatal("couldn't bind to IPv4 query address: %s",
161 				    log_sockaddr(qa4));
162 		} else if (p->addr->ss.ss_family == qa6->sa_family) {
163 			if (bind(p->query->fd, qa6, SA_LEN(qa6)) == -1)
164 				fatal("couldn't bind to IPv6 query address: %s",
165 				    log_sockaddr(qa6));
166 		}
167 
168 		if (connect(p->query->fd, sa, SA_LEN(sa)) == -1) {
169 			if (errno == ECONNREFUSED || errno == ENETUNREACH ||
170 			    errno == EHOSTUNREACH || errno == EADDRNOTAVAIL) {
171 				client_nextaddr(p);
172 				set_next(p, MAXIMUM(SETTIME_TIMEOUT,
173 				    scale_interval(INTERVAL_QUERY_AGGRESSIVE)));
174 				return (-1);
175 			} else
176 				fatal("client_query connect");
177 		}
178 		val = IPTOS_LOWDELAY;
179 		if (p->addr->ss.ss_family == AF_INET && setsockopt(p->query->fd,
180 		    IPPROTO_IP, IP_TOS, &val, sizeof(val)) == -1)
181 			log_warn("setsockopt IPTOS_LOWDELAY");
182 		val = 1;
183 		if (setsockopt(p->query->fd, SOL_SOCKET, SO_TIMESTAMP,
184 		    &val, sizeof(val)) == -1)
185 			fatal("setsockopt SO_TIMESTAMP");
186 	}
187 
188 	/*
189 	 * Send out a random 64-bit number as our transmit time.  The NTP
190 	 * server will copy said number into the originate field on the
191 	 * response that it sends us.  This is totally legal per the SNTP spec.
192 	 *
193 	 * The impact of this is two fold: we no longer send out the current
194 	 * system time for the world to see (which may aid an attacker), and
195 	 * it gives us a (not very secure) way of knowing that we're not
196 	 * getting spoofed by an attacker that can't capture our traffic
197 	 * but can spoof packets from the NTP server we're communicating with.
198 	 *
199 	 * Save the real transmit timestamp locally.
200 	 */
201 
202 	p->query->msg.xmttime.int_partl = arc4random();
203 	p->query->msg.xmttime.fractionl = arc4random();
204 	p->query->xmttime = gettime_corrected();
205 
206 	if (ntp_sendmsg(p->query->fd, NULL, &p->query->msg) == -1) {
207 		p->senderrors++;
208 		set_next(p, INTERVAL_QUERY_PATHETIC);
209 		p->trustlevel = TRUSTLEVEL_PATHETIC;
210 		return (-1);
211 	}
212 
213 	p->senderrors = 0;
214 	p->state = STATE_QUERY_SENT;
215 	set_deadline(p, QUERYTIME_MAX);
216 
217 	return (0);
218 }
219 
220 int
221 auto_cmp(const void *a, const void *b)
222 {
223 	double at = *(const double *)a;
224 	double bt = *(const double *)b;
225 	return at < bt ? -1 : (at > bt ? 1 : 0);
226 }
227 
228 void
229 handle_auto(double offset)
230 {
231 	static int count;
232 	static double v[AUTO_REPLIES];
233 
234 	/*
235 	 * It happens the (constraint) resolves initially fail, don't give up
236 	 * but see if we get validatd replies later.
237 	 */
238 	if (conf->constraint_median == 0)
239 		return;
240 
241 	if (offset < AUTO_THRESHOLD) {
242 		/* don't bother */
243 		priv_settime(0, "offset is negative or close enough");
244 		return;
245 	}
246 	/* collect some more */
247 	v[count++] = offset;
248 	if (count < AUTO_REPLIES)
249 		return;
250 
251 	/* we have enough */
252 	qsort(v, count, sizeof(double), auto_cmp);
253 	if (AUTO_REPLIES % 2 == 0)
254 		offset = (v[AUTO_REPLIES / 2 - 1] + v[AUTO_REPLIES / 2]) / 2;
255 	else
256 		offset = v[AUTO_REPLIES / 2];
257 	priv_settime(offset, "");
258 }
259 
260 int
261 client_dispatch(struct ntp_peer *p, u_int8_t settime, u_int8_t automatic)
262 {
263 	struct ntp_msg		 msg;
264 	struct msghdr		 somsg;
265 	struct iovec		 iov[1];
266 	struct timeval		 tv;
267 	char			 buf[NTP_MSGSIZE];
268 	union {
269 		struct cmsghdr	hdr;
270 		char		buf[CMSG_SPACE(sizeof(tv))];
271 	} cmsgbuf;
272 	struct cmsghdr		*cmsg;
273 	ssize_t			 size;
274 	double			 T1, T2, T3, T4;
275 	time_t			 interval;
276 
277 	memset(&somsg, 0, sizeof(somsg));
278 	iov[0].iov_base = buf;
279 	iov[0].iov_len = sizeof(buf);
280 	somsg.msg_iov = iov;
281 	somsg.msg_iovlen = 1;
282 	somsg.msg_control = cmsgbuf.buf;
283 	somsg.msg_controllen = sizeof(cmsgbuf.buf);
284 
285 	T4 = getoffset();
286 	if ((size = recvmsg(p->query->fd, &somsg, 0)) == -1) {
287 		if (errno == EHOSTUNREACH || errno == EHOSTDOWN ||
288 		    errno == ENETUNREACH || errno == ENETDOWN ||
289 		    errno == ECONNREFUSED || errno == EADDRNOTAVAIL ||
290 		    errno == ENOPROTOOPT || errno == ENOENT) {
291 			client_log_error(p, "recvmsg", errno);
292 			set_next(p, error_interval());
293 			return (0);
294 		} else
295 			fatal("recvfrom");
296 	}
297 
298 	if (somsg.msg_flags & MSG_TRUNC) {
299 		client_log_error(p, "recvmsg packet", EMSGSIZE);
300 		set_next(p, error_interval());
301 		return (0);
302 	}
303 
304 	if (somsg.msg_flags & MSG_CTRUNC) {
305 		client_log_error(p, "recvmsg control data", E2BIG);
306 		set_next(p, error_interval());
307 		return (0);
308 	}
309 
310 	for (cmsg = CMSG_FIRSTHDR(&somsg); cmsg != NULL;
311 	    cmsg = CMSG_NXTHDR(&somsg, cmsg)) {
312 		if (cmsg->cmsg_level == SOL_SOCKET &&
313 		    cmsg->cmsg_type == SCM_TIMESTAMP) {
314 			memcpy(&tv, CMSG_DATA(cmsg), sizeof(tv));
315 			T4 += gettime_from_timeval(&tv);
316 			break;
317 		}
318 	}
319 
320 	if (T4 < JAN_1970) {
321 		client_log_error(p, "recvmsg control format", EBADF);
322 		set_next(p, error_interval());
323 		return (0);
324 	}
325 
326 	ntp_getmsg((struct sockaddr *)&p->addr->ss, buf, size, &msg);
327 
328 	if (msg.orgtime.int_partl != p->query->msg.xmttime.int_partl ||
329 	    msg.orgtime.fractionl != p->query->msg.xmttime.fractionl)
330 		return (0);
331 
332 	if ((msg.status & LI_ALARM) == LI_ALARM || msg.stratum == 0 ||
333 	    msg.stratum > NTP_MAXSTRATUM) {
334 		char s[16];
335 
336 		if ((msg.status & LI_ALARM) == LI_ALARM) {
337 			strlcpy(s, "alarm", sizeof(s));
338 		} else if (msg.stratum == 0) {
339 			/* Kiss-o'-Death (KoD) packet */
340 			strlcpy(s, "KoD", sizeof(s));
341 		} else if (msg.stratum > NTP_MAXSTRATUM) {
342 			snprintf(s, sizeof(s), "stratum %d", msg.stratum);
343 		}
344 		interval = error_interval();
345 		set_next(p, interval);
346 		log_info("reply from %s: not synced (%s), next query %llds",
347 		    log_sockaddr((struct sockaddr *)&p->addr->ss), s,
348 			(long long)interval);
349 		return (0);
350 	}
351 
352 	/*
353 	 * From RFC 2030 (with a correction to the delay math):
354 	 *
355 	 *     Timestamp Name          ID   When Generated
356 	 *     ------------------------------------------------------------
357 	 *     Originate Timestamp     T1   time request sent by client
358 	 *     Receive Timestamp       T2   time request received by server
359 	 *     Transmit Timestamp      T3   time reply sent by server
360 	 *     Destination Timestamp   T4   time reply received by client
361 	 *
362 	 *  The roundtrip delay d and local clock offset t are defined as
363 	 *
364 	 *    d = (T4 - T1) - (T3 - T2)     t = ((T2 - T1) + (T3 - T4)) / 2.
365 	 */
366 
367 	T1 = p->query->xmttime;
368 	T2 = lfp_to_d(msg.rectime);
369 	T3 = lfp_to_d(msg.xmttime);
370 
371 	/*
372 	 * XXX workaround: time_t / tv_sec must never wrap.
373 	 * around 2020 we will need a solution (64bit time_t / tv_sec).
374 	 * consider every answer with a timestamp beyond january 2030 bogus.
375 	 */
376 	if (T2 > JAN_2030 || T3 > JAN_2030) {
377 		set_next(p, error_interval());
378 		return (0);
379 	}
380 
381 	/* Detect liars */
382 	if (conf->constraint_median != 0 &&
383 	    (constraint_check(T2) != 0 || constraint_check(T3) != 0)) {
384 		log_info("reply from %s: constraint check failed",
385 		    log_sockaddr((struct sockaddr *)&p->addr->ss));
386 		set_next(p, error_interval());
387 		return (0);
388 	}
389 
390 	p->reply[p->shift].offset = ((T2 - T1) + (T3 - T4)) / 2;
391 	p->reply[p->shift].delay = (T4 - T1) - (T3 - T2);
392 	p->reply[p->shift].status.stratum = msg.stratum;
393 	if (p->reply[p->shift].delay < 0) {
394 		interval = error_interval();
395 		set_next(p, interval);
396 		log_info("reply from %s: negative delay %fs, "
397 		    "next query %llds",
398 		    log_sockaddr((struct sockaddr *)&p->addr->ss),
399 		    p->reply[p->shift].delay, (long long)interval);
400 		return (0);
401 	}
402 	p->reply[p->shift].error = (T2 - T1) - (T3 - T4);
403 	p->reply[p->shift].rcvd = getmonotime();
404 	p->reply[p->shift].good = 1;
405 
406 	p->reply[p->shift].status.leap = (msg.status & LIMASK);
407 	p->reply[p->shift].status.precision = msg.precision;
408 	p->reply[p->shift].status.rootdelay = sfp_to_d(msg.rootdelay);
409 	p->reply[p->shift].status.rootdispersion = sfp_to_d(msg.dispersion);
410 	p->reply[p->shift].status.refid = msg.refid;
411 	p->reply[p->shift].status.reftime = lfp_to_d(msg.reftime);
412 	p->reply[p->shift].status.poll = msg.ppoll;
413 
414 	if (p->addr->ss.ss_family == AF_INET) {
415 		p->reply[p->shift].status.send_refid =
416 		    ((struct sockaddr_in *)&p->addr->ss)->sin_addr.s_addr;
417 	} else if (p->addr->ss.ss_family == AF_INET6) {
418 		MD5_CTX		context;
419 		u_int8_t	digest[MD5_DIGEST_LENGTH];
420 
421 		MD5Init(&context);
422 		MD5Update(&context, ((struct sockaddr_in6 *)&p->addr->ss)->
423 		    sin6_addr.s6_addr, sizeof(struct in6_addr));
424 		MD5Final(digest, &context);
425 		memcpy((char *)&p->reply[p->shift].status.send_refid, digest,
426 		    sizeof(u_int32_t));
427 	} else
428 		p->reply[p->shift].status.send_refid = msg.xmttime.fractionl;
429 
430 	if (p->trustlevel < TRUSTLEVEL_PATHETIC)
431 		interval = scale_interval(INTERVAL_QUERY_PATHETIC);
432 	else if (p->trustlevel < TRUSTLEVEL_AGGRESSIVE)
433 		interval = (conf->settime && conf->automatic) ?
434 		    INTERVAL_QUERY_ULTRA_VIOLENCE :
435 		    scale_interval(INTERVAL_QUERY_AGGRESSIVE);
436 	else
437 		interval = scale_interval(INTERVAL_QUERY_NORMAL);
438 
439 	set_next(p, interval);
440 	p->state = STATE_REPLY_RECEIVED;
441 
442 	/* every received reply which we do not discard increases trust */
443 	if (p->trustlevel < TRUSTLEVEL_MAX) {
444 		if (p->trustlevel < TRUSTLEVEL_BADPEER &&
445 		    p->trustlevel + 1 >= TRUSTLEVEL_BADPEER)
446 			log_info("peer %s now valid",
447 			    log_sockaddr((struct sockaddr *)&p->addr->ss));
448 		p->trustlevel++;
449 	}
450 
451 	log_debug("reply from %s: offset %f delay %f, "
452 	    "next query %llds",
453 	    log_sockaddr((struct sockaddr *)&p->addr->ss),
454 	    p->reply[p->shift].offset, p->reply[p->shift].delay,
455 	    (long long)interval);
456 
457 	client_update(p);
458 	if (settime) {
459 		if (automatic)
460 			handle_auto(p->reply[p->shift].offset);
461 		else
462 			priv_settime(p->reply[p->shift].offset, "");
463 	}
464 
465 	if (++p->shift >= OFFSET_ARRAY_SIZE)
466 		p->shift = 0;
467 
468 	return (0);
469 }
470 
471 int
472 client_update(struct ntp_peer *p)
473 {
474 	int	i, best = 0, good = 0;
475 
476 	/*
477 	 * clock filter
478 	 * find the offset which arrived with the lowest delay
479 	 * use that as the peer update
480 	 * invalidate it and all older ones
481 	 */
482 
483 	for (i = 0; good == 0 && i < OFFSET_ARRAY_SIZE; i++)
484 		if (p->reply[i].good) {
485 			good++;
486 			best = i;
487 		}
488 
489 	for (; i < OFFSET_ARRAY_SIZE; i++)
490 		if (p->reply[i].good) {
491 			good++;
492 			if (p->reply[i].delay < p->reply[best].delay)
493 				best = i;
494 		}
495 
496 	if (good < 8)
497 		return (-1);
498 
499 	memcpy(&p->update, &p->reply[best], sizeof(p->update));
500 	if (priv_adjtime() == 0) {
501 		for (i = 0; i < OFFSET_ARRAY_SIZE; i++)
502 			if (p->reply[i].rcvd <= p->reply[best].rcvd)
503 				p->reply[i].good = 0;
504 	}
505 	return (0);
506 }
507 
508 void
509 client_log_error(struct ntp_peer *peer, const char *operation, int error)
510 {
511 	const char *address;
512 
513 	address = log_sockaddr((struct sockaddr *)&peer->addr->ss);
514 	if (peer->lasterror == error) {
515 		log_debug("%s %s: %s", operation, address, strerror(error));
516 		return;
517 	}
518 	peer->lasterror = error;
519 	log_warn("%s %s", operation, address);
520 }
521