xref: /openbsd-src/usr.sbin/ntpd/client.c (revision a0747c9f67a4ae71ccb71e62a28d1ea19e06a63c)
1 /*	$OpenBSD: client.c,v 1.116 2021/04/21 09:38:11 bluhm 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(u_int8_t, 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 	p->shift = 0;
118 	p->trustlevel = TRUSTLEVEL_PATHETIC;
119 
120 	if (p->addr == NULL)
121 		p->addr = p->addr_head.a;
122 	else if ((p->addr = p->addr->next) == NULL)
123 		return (1);
124 
125 	return (0);
126 }
127 
128 int
129 client_query(struct ntp_peer *p)
130 {
131 	int	val;
132 
133 	if (p->addr == NULL && client_nextaddr(p) == -1) {
134 		if (conf->settime)
135 			set_next(p, INTERVAL_AUIO_DNSFAIL);
136 		else
137 			set_next(p, MAXIMUM(SETTIME_TIMEOUT,
138 			    scale_interval(INTERVAL_QUERY_AGGRESSIVE)));
139 		return (0);
140 	}
141 
142 	if (conf->status.synced && p->addr->notauth) {
143 		peer_addr_head_clear(p);
144 		client_nextaddr(p);
145 		return (0);
146 	}
147 
148 	if (p->state < STATE_DNS_DONE || p->addr == NULL)
149 		return (-1);
150 
151 	if (p->query->fd == -1) {
152 		struct sockaddr *sa = (struct sockaddr *)&p->addr->ss;
153 		struct sockaddr *qa4 = (struct sockaddr *)&p->query_addr4;
154 		struct sockaddr *qa6 = (struct sockaddr *)&p->query_addr6;
155 
156 		if ((p->query->fd = socket(p->addr->ss.ss_family, SOCK_DGRAM,
157 		    0)) == -1)
158 			fatal("client_query socket");
159 
160 		if (p->addr->ss.ss_family == qa4->sa_family) {
161 			if (bind(p->query->fd, qa4, SA_LEN(qa4)) == -1)
162 				fatal("couldn't bind to IPv4 query address: %s",
163 				    log_sockaddr(qa4));
164 		} else if (p->addr->ss.ss_family == qa6->sa_family) {
165 			if (bind(p->query->fd, qa6, SA_LEN(qa6)) == -1)
166 				fatal("couldn't bind to IPv6 query address: %s",
167 				    log_sockaddr(qa6));
168 		}
169 
170 		if (connect(p->query->fd, sa, SA_LEN(sa)) == -1) {
171 			if (errno == ECONNREFUSED || errno == ENETUNREACH ||
172 			    errno == EHOSTUNREACH || errno == EADDRNOTAVAIL) {
173 				/* cycle through addresses, but do increase
174 				   senderrors */
175 				client_nextaddr(p);
176 				if (p->addr == NULL)
177 					p->addr = p->addr_head.a;
178 				set_next(p, MAXIMUM(SETTIME_TIMEOUT,
179 				    scale_interval(INTERVAL_QUERY_AGGRESSIVE)));
180 				p->senderrors++;
181 				return (-1);
182 			} else
183 				fatal("client_query connect");
184 		}
185 		val = IPTOS_LOWDELAY;
186 		if (p->addr->ss.ss_family == AF_INET && setsockopt(p->query->fd,
187 		    IPPROTO_IP, IP_TOS, &val, sizeof(val)) == -1)
188 			log_warn("setsockopt IPTOS_LOWDELAY");
189 		val = 1;
190 		if (setsockopt(p->query->fd, SOL_SOCKET, SO_TIMESTAMP,
191 		    &val, sizeof(val)) == -1)
192 			fatal("setsockopt SO_TIMESTAMP");
193 	}
194 
195 	/*
196 	 * Send out a random 64-bit number as our transmit time.  The NTP
197 	 * server will copy said number into the originate field on the
198 	 * response that it sends us.  This is totally legal per the SNTP spec.
199 	 *
200 	 * The impact of this is two fold: we no longer send out the current
201 	 * system time for the world to see (which may aid an attacker), and
202 	 * it gives us a (not very secure) way of knowing that we're not
203 	 * getting spoofed by an attacker that can't capture our traffic
204 	 * but can spoof packets from the NTP server we're communicating with.
205 	 *
206 	 * Save the real transmit timestamp locally.
207 	 */
208 
209 	p->query->msg.xmttime.int_partl = arc4random();
210 	p->query->msg.xmttime.fractionl = arc4random();
211 	p->query->xmttime = gettime();
212 
213 	if (ntp_sendmsg(p->query->fd, NULL, &p->query->msg) == -1) {
214 		p->senderrors++;
215 		set_next(p, INTERVAL_QUERY_PATHETIC);
216 		p->trustlevel = TRUSTLEVEL_PATHETIC;
217 		return (-1);
218 	}
219 
220 	p->senderrors = 0;
221 	p->state = STATE_QUERY_SENT;
222 	set_deadline(p, QUERYTIME_MAX);
223 
224 	return (0);
225 }
226 
227 int
228 auto_cmp(const void *a, const void *b)
229 {
230 	double at = *(const double *)a;
231 	double bt = *(const double *)b;
232 	return at < bt ? -1 : (at > bt ? 1 : 0);
233 }
234 
235 void
236 handle_auto(uint8_t trusted, double offset)
237 {
238 	static int count;
239 	static double v[AUTO_REPLIES];
240 
241 	/*
242 	 * It happens the (constraint) resolves initially fail, don't give up
243 	 * but see if we get validated replies later.
244 	 */
245 	if (!trusted && conf->constraint_median == 0)
246 		return;
247 
248 	if (offset < AUTO_THRESHOLD) {
249 		/* don't bother */
250 		priv_settime(0, "offset is negative or close enough");
251 		return;
252 	}
253 	/* collect some more */
254 	v[count++] = offset;
255 	if (count < AUTO_REPLIES)
256 		return;
257 
258 	/* we have enough */
259 	qsort(v, count, sizeof(double), auto_cmp);
260 	if (AUTO_REPLIES % 2 == 0)
261 		offset = (v[AUTO_REPLIES / 2 - 1] + v[AUTO_REPLIES / 2]) / 2;
262 	else
263 		offset = v[AUTO_REPLIES / 2];
264 	priv_settime(offset, "");
265 }
266 
267 
268 /*
269  * -1: Not processed, not an NTP message (e.g. icmp induced  ECONNREFUSED)
270  *  0: Not prrocessed due to validation issues
271  *  1: NTP message validated and processed
272  */
273 int
274 client_dispatch(struct ntp_peer *p, u_int8_t settime, u_int8_t automatic)
275 {
276 	struct ntp_msg		 msg;
277 	struct msghdr		 somsg;
278 	struct iovec		 iov[1];
279 	struct timeval		 tv;
280 	char			 buf[NTP_MSGSIZE];
281 	union {
282 		struct cmsghdr	hdr;
283 		char		buf[CMSG_SPACE(sizeof(tv))];
284 	} cmsgbuf;
285 	struct cmsghdr		*cmsg;
286 	ssize_t			 size;
287 	double			 T1, T2, T3, T4, offset, delay;
288 	time_t			 interval;
289 
290 	memset(&somsg, 0, sizeof(somsg));
291 	iov[0].iov_base = buf;
292 	iov[0].iov_len = sizeof(buf);
293 	somsg.msg_iov = iov;
294 	somsg.msg_iovlen = 1;
295 	somsg.msg_control = cmsgbuf.buf;
296 	somsg.msg_controllen = sizeof(cmsgbuf.buf);
297 
298 	if ((size = recvmsg(p->query->fd, &somsg, 0)) == -1) {
299 		if (errno == EHOSTUNREACH || errno == EHOSTDOWN ||
300 		    errno == ENETUNREACH || errno == ENETDOWN ||
301 		    errno == ECONNREFUSED || errno == EADDRNOTAVAIL ||
302 		    errno == ENOPROTOOPT || errno == ENOENT) {
303 			client_log_error(p, "recvmsg", errno);
304 			set_next(p, error_interval());
305 			return (-1);
306 		} else
307 			fatal("recvfrom");
308 	}
309 
310 	if (somsg.msg_flags & MSG_TRUNC) {
311 		client_log_error(p, "recvmsg packet", EMSGSIZE);
312 		set_next(p, error_interval());
313 		return (0);
314 	}
315 
316 	if (somsg.msg_flags & MSG_CTRUNC) {
317 		client_log_error(p, "recvmsg control data", E2BIG);
318 		set_next(p, error_interval());
319 		return (0);
320 	}
321 
322 	for (cmsg = CMSG_FIRSTHDR(&somsg); cmsg != NULL;
323 	    cmsg = CMSG_NXTHDR(&somsg, cmsg)) {
324 		if (cmsg->cmsg_level == SOL_SOCKET &&
325 		    cmsg->cmsg_type == SCM_TIMESTAMP) {
326 			memcpy(&tv, CMSG_DATA(cmsg), sizeof(tv));
327 			T4 = gettime_from_timeval(&tv);
328 			break;
329 		}
330 	}
331 	if (cmsg == NULL)
332 		fatal("SCM_TIMESTAMP");
333 
334 	ntp_getmsg((struct sockaddr *)&p->addr->ss, buf, size, &msg);
335 
336 	if (msg.orgtime.int_partl != p->query->msg.xmttime.int_partl ||
337 	    msg.orgtime.fractionl != p->query->msg.xmttime.fractionl)
338 		return (0);
339 
340 	if ((msg.status & LI_ALARM) == LI_ALARM || msg.stratum == 0 ||
341 	    msg.stratum > NTP_MAXSTRATUM) {
342 		char s[16];
343 
344 		if ((msg.status & LI_ALARM) == LI_ALARM) {
345 			strlcpy(s, "alarm", sizeof(s));
346 		} else if (msg.stratum == 0) {
347 			/* Kiss-o'-Death (KoD) packet */
348 			strlcpy(s, "KoD", sizeof(s));
349 		} else if (msg.stratum > NTP_MAXSTRATUM) {
350 			snprintf(s, sizeof(s), "stratum %d", msg.stratum);
351 		}
352 		interval = error_interval();
353 		set_next(p, interval);
354 		log_info("reply from %s: not synced (%s), next query %llds",
355 		    log_sockaddr((struct sockaddr *)&p->addr->ss), s,
356 			(long long)interval);
357 		return (0);
358 	}
359 
360 	/*
361 	 * From RFC 2030 (with a correction to the delay math):
362 	 *
363 	 *     Timestamp Name          ID   When Generated
364 	 *     ------------------------------------------------------------
365 	 *     Originate Timestamp     T1   time request sent by client
366 	 *     Receive Timestamp       T2   time request received by server
367 	 *     Transmit Timestamp      T3   time reply sent by server
368 	 *     Destination Timestamp   T4   time reply received by client
369 	 *
370 	 *  The roundtrip delay d and local clock offset t are defined as
371 	 *
372 	 *    d = (T4 - T1) - (T3 - T2)     t = ((T2 - T1) + (T3 - T4)) / 2.
373 	 */
374 
375 	T1 = p->query->xmttime;
376 	T2 = lfp_to_d(msg.rectime);
377 	T3 = lfp_to_d(msg.xmttime);
378 
379 	/* Detect liars */
380 	if (!p->trusted && conf->constraint_median != 0 &&
381 	    (constraint_check(T2) != 0 || constraint_check(T3) != 0)) {
382 		log_info("reply from %s: constraint check failed",
383 		    log_sockaddr((struct sockaddr *)&p->addr->ss));
384 		set_next(p, error_interval());
385 		return (0);
386 	}
387 
388 	p->reply[p->shift].offset = ((T2 - T1) + (T3 - T4)) / 2 - getoffset();
389 	p->reply[p->shift].delay = (T4 - T1) - (T3 - T2);
390 	p->reply[p->shift].status.stratum = msg.stratum;
391 	if (p->reply[p->shift].delay < 0) {
392 		interval = error_interval();
393 		set_next(p, interval);
394 		log_info("reply from %s: negative delay %fs, "
395 		    "next query %llds",
396 		    log_sockaddr((struct sockaddr *)&p->addr->ss),
397 		    p->reply[p->shift].delay, (long long)interval);
398 		return (0);
399 	}
400 	p->reply[p->shift].error = (T2 - T1) - (T3 - T4);
401 	p->reply[p->shift].rcvd = getmonotime();
402 	p->reply[p->shift].good = 1;
403 
404 	p->reply[p->shift].status.leap = (msg.status & LIMASK);
405 	p->reply[p->shift].status.precision = msg.precision;
406 	p->reply[p->shift].status.rootdelay = sfp_to_d(msg.rootdelay);
407 	p->reply[p->shift].status.rootdispersion = sfp_to_d(msg.dispersion);
408 	p->reply[p->shift].status.refid = msg.refid;
409 	p->reply[p->shift].status.reftime = lfp_to_d(msg.reftime);
410 	p->reply[p->shift].status.poll = msg.ppoll;
411 
412 	if (p->addr->ss.ss_family == AF_INET) {
413 		p->reply[p->shift].status.send_refid =
414 		    ((struct sockaddr_in *)&p->addr->ss)->sin_addr.s_addr;
415 	} else if (p->addr->ss.ss_family == AF_INET6) {
416 		MD5_CTX		context;
417 		u_int8_t	digest[MD5_DIGEST_LENGTH];
418 
419 		MD5Init(&context);
420 		MD5Update(&context, ((struct sockaddr_in6 *)&p->addr->ss)->
421 		    sin6_addr.s6_addr, sizeof(struct in6_addr));
422 		MD5Final(digest, &context);
423 		memcpy((char *)&p->reply[p->shift].status.send_refid, digest,
424 		    sizeof(u_int32_t));
425 	} else
426 		p->reply[p->shift].status.send_refid = msg.xmttime.fractionl;
427 
428 	p->state = STATE_REPLY_RECEIVED;
429 
430 	/* every received reply which we do not discard increases trust */
431 	if (p->trustlevel < TRUSTLEVEL_MAX) {
432 		if (p->trustlevel < TRUSTLEVEL_BADPEER &&
433 		    p->trustlevel + 1 >= TRUSTLEVEL_BADPEER)
434 			log_info("peer %s now valid",
435 			    log_sockaddr((struct sockaddr *)&p->addr->ss));
436 		p->trustlevel++;
437 	}
438 
439 	offset = p->reply[p->shift].offset;
440 	delay = p->reply[p->shift].delay;
441 
442 	client_update(p);
443 	if (settime) {
444 		if (automatic)
445 			handle_auto(p->trusted, p->reply[p->shift].offset);
446 		else
447 			priv_settime(p->reply[p->shift].offset, "");
448 	}
449 
450 	if (p->trustlevel < TRUSTLEVEL_PATHETIC)
451 		interval = scale_interval(INTERVAL_QUERY_PATHETIC);
452 	else if (p->trustlevel < TRUSTLEVEL_AGGRESSIVE)
453 		interval = (conf->settime && conf->automatic) ?
454 		    INTERVAL_QUERY_ULTRA_VIOLENCE :
455 		    scale_interval(INTERVAL_QUERY_AGGRESSIVE);
456 	else
457 		interval = scale_interval(INTERVAL_QUERY_NORMAL);
458 
459 	log_debug("reply from %s: offset %f delay %f, "
460 	    "next query %llds",
461 	    log_sockaddr((struct sockaddr *)&p->addr->ss),
462 	    offset, delay,
463 	    (long long)interval);
464 
465 	set_next(p, interval);
466 
467 	if (++p->shift >= OFFSET_ARRAY_SIZE)
468 		p->shift = 0;
469 
470 	return (1);
471 }
472 
473 int
474 client_update(struct ntp_peer *p)
475 {
476 	int	shift, best = -1, good = 0;
477 
478 	/*
479 	 * clock filter
480 	 * find the offset which arrived with the lowest delay
481 	 * use that as the peer update
482 	 * invalidate it and all older ones
483 	 */
484 
485 	for (shift = 0; shift < OFFSET_ARRAY_SIZE; shift++)
486 		if (p->reply[shift].good) {
487 			good++;
488 			if (best == -1 ||
489 			    p->reply[shift].delay < p->reply[best].delay)
490 				best = shift;
491 		}
492 
493 	if (best == -1 || good < 8)
494 		return (-1);
495 
496 	p->update = p->reply[best];
497 	if (priv_adjtime() == 0) {
498 		for (shift = 0; shift < OFFSET_ARRAY_SIZE; shift++)
499 			if (p->reply[shift].rcvd <= p->reply[best].rcvd)
500 				p->reply[shift].good = 0;
501 	}
502 	return (0);
503 }
504 
505 void
506 client_log_error(struct ntp_peer *peer, const char *operation, int error)
507 {
508 	const char *address;
509 
510 	address = log_sockaddr((struct sockaddr *)&peer->addr->ss);
511 	if (peer->lasterror == error) {
512 		log_debug("%s %s: %s", operation, address, strerror(error));
513 		return;
514 	}
515 	peer->lasterror = error;
516 	log_warn("%s %s", operation, address);
517 }
518