GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: usr.sbin/ntpd/client.c Lines: 0 239 0.0 %
Date: 2017-11-13 Branches: 0 161 0.0 %

Line Branch Exec Source
1
/*	$OpenBSD: client.c,v 1.105 2017/05/30 23:30:48 benno 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
void	set_deadline(struct ntp_peer *, time_t);
33
34
void
35
set_next(struct ntp_peer *p, time_t t)
36
{
37
	p->next = getmonotime() + t;
38
	p->deadline = 0;
39
	p->poll = t;
40
}
41
42
void
43
set_deadline(struct ntp_peer *p, time_t t)
44
{
45
	p->deadline = getmonotime() + t;
46
	p->next = 0;
47
}
48
49
int
50
client_peer_init(struct ntp_peer *p)
51
{
52
	if ((p->query = calloc(1, sizeof(struct ntp_query))) == NULL)
53
		fatal("client_peer_init calloc");
54
	p->query->fd = -1;
55
	p->query->msg.status = MODE_CLIENT | (NTP_VERSION << 3);
56
	p->state = STATE_NONE;
57
	p->shift = 0;
58
	p->trustlevel = TRUSTLEVEL_PATHETIC;
59
	p->lasterror = 0;
60
	p->senderrors = 0;
61
62
	return (client_addr_init(p));
63
}
64
65
int
66
client_addr_init(struct ntp_peer *p)
67
{
68
	struct sockaddr_in	*sa_in;
69
	struct sockaddr_in6	*sa_in6;
70
	struct ntp_addr		*h;
71
72
	for (h = p->addr; h != NULL; h = h->next) {
73
		switch (h->ss.ss_family) {
74
		case AF_INET:
75
			sa_in = (struct sockaddr_in *)&h->ss;
76
			if (ntohs(sa_in->sin_port) == 0)
77
				sa_in->sin_port = htons(123);
78
			p->state = STATE_DNS_DONE;
79
			break;
80
		case AF_INET6:
81
			sa_in6 = (struct sockaddr_in6 *)&h->ss;
82
			if (ntohs(sa_in6->sin6_port) == 0)
83
				sa_in6->sin6_port = htons(123);
84
			p->state = STATE_DNS_DONE;
85
			break;
86
		default:
87
			fatalx("king bula sez: wrong AF in client_addr_init");
88
			/* NOTREACHED */
89
		}
90
	}
91
92
	p->query->fd = -1;
93
	set_next(p, 0);
94
95
	return (0);
96
}
97
98
int
99
client_nextaddr(struct ntp_peer *p)
100
{
101
	if (p->query->fd != -1) {
102
		close(p->query->fd);
103
		p->query->fd = -1;
104
	}
105
106
	if (p->state == STATE_DNS_INPROGRESS)
107
		return (-1);
108
109
	if (p->addr_head.a == NULL) {
110
		priv_dns(IMSG_HOST_DNS, p->addr_head.name, p->id);
111
		p->state = STATE_DNS_INPROGRESS;
112
		return (-1);
113
	}
114
115
	if (p->addr == NULL || (p->addr = p->addr->next) == NULL)
116
		p->addr = p->addr_head.a;
117
118
	p->shift = 0;
119
	p->trustlevel = TRUSTLEVEL_PATHETIC;
120
121
	return (0);
122
}
123
124
int
125
client_query(struct ntp_peer *p)
126
{
127
	int	val;
128
129
	if (p->addr == NULL && client_nextaddr(p) == -1) {
130
		set_next(p, MAXIMUM(SETTIME_TIMEOUT,
131
		    scale_interval(INTERVAL_QUERY_AGGRESSIVE)));
132
		return (0);
133
	}
134
135
	if (p->state < STATE_DNS_DONE || p->addr == NULL)
136
		return (-1);
137
138
	if (p->query->fd == -1) {
139
		struct sockaddr *sa = (struct sockaddr *)&p->addr->ss;
140
		struct sockaddr *qa4 = (struct sockaddr *)&p->query_addr4;
141
		struct sockaddr *qa6 = (struct sockaddr *)&p->query_addr6;
142
143
		if ((p->query->fd = socket(p->addr->ss.ss_family, SOCK_DGRAM,
144
		    0)) == -1)
145
			fatal("client_query socket");
146
147
		if (p->addr->ss.ss_family == qa4->sa_family) {
148
			if (bind(p->query->fd, qa4, SA_LEN(qa4)) == -1)
149
				fatal("couldn't bind to IPv4 query address: %s",
150
				    log_sockaddr(qa4));
151
		} else if (p->addr->ss.ss_family == qa6->sa_family) {
152
			if (bind(p->query->fd, qa6, SA_LEN(qa6)) == -1)
153
				fatal("couldn't bind to IPv6 query address: %s",
154
				    log_sockaddr(qa6));
155
		}
156
157
		if (connect(p->query->fd, sa, SA_LEN(sa)) == -1) {
158
			if (errno == ECONNREFUSED || errno == ENETUNREACH ||
159
			    errno == EHOSTUNREACH || errno == EADDRNOTAVAIL) {
160
				client_nextaddr(p);
161
				set_next(p, MAXIMUM(SETTIME_TIMEOUT,
162
				    scale_interval(INTERVAL_QUERY_AGGRESSIVE)));
163
				return (-1);
164
			} else
165
				fatal("client_query connect");
166
		}
167
		val = IPTOS_LOWDELAY;
168
		if (p->addr->ss.ss_family == AF_INET && setsockopt(p->query->fd,
169
		    IPPROTO_IP, IP_TOS, &val, sizeof(val)) == -1)
170
			log_warn("setsockopt IPTOS_LOWDELAY");
171
		val = 1;
172
		if (setsockopt(p->query->fd, SOL_SOCKET, SO_TIMESTAMP,
173
		    &val, sizeof(val)) == -1)
174
			fatal("setsockopt SO_TIMESTAMP");
175
	}
176
177
	/*
178
	 * Send out a random 64-bit number as our transmit time.  The NTP
179
	 * server will copy said number into the originate field on the
180
	 * response that it sends us.  This is totally legal per the SNTP spec.
181
	 *
182
	 * The impact of this is two fold: we no longer send out the current
183
	 * system time for the world to see (which may aid an attacker), and
184
	 * it gives us a (not very secure) way of knowing that we're not
185
	 * getting spoofed by an attacker that can't capture our traffic
186
	 * but can spoof packets from the NTP server we're communicating with.
187
	 *
188
	 * Save the real transmit timestamp locally.
189
	 */
190
191
	p->query->msg.xmttime.int_partl = arc4random();
192
	p->query->msg.xmttime.fractionl = arc4random();
193
	p->query->xmttime = gettime_corrected();
194
195
	if (ntp_sendmsg(p->query->fd, NULL, &p->query->msg) == -1) {
196
		p->senderrors++;
197
		set_next(p, INTERVAL_QUERY_PATHETIC);
198
		p->trustlevel = TRUSTLEVEL_PATHETIC;
199
		return (-1);
200
	}
201
202
	p->senderrors = 0;
203
	p->state = STATE_QUERY_SENT;
204
	set_deadline(p, QUERYTIME_MAX);
205
206
	return (0);
207
}
208
209
int
210
client_dispatch(struct ntp_peer *p, u_int8_t settime)
211
{
212
	struct ntp_msg		 msg;
213
	struct msghdr		 somsg;
214
	struct iovec		 iov[1];
215
	struct timeval		 tv;
216
	char			 buf[NTP_MSGSIZE];
217
	union {
218
		struct cmsghdr	hdr;
219
		char		buf[CMSG_SPACE(sizeof(tv))];
220
	} cmsgbuf;
221
	struct cmsghdr		*cmsg;
222
	ssize_t			 size;
223
	double			 T1, T2, T3, T4;
224
	time_t			 interval;
225
226
	memset(&somsg, 0, sizeof(somsg));
227
	iov[0].iov_base = buf;
228
	iov[0].iov_len = sizeof(buf);
229
	somsg.msg_iov = iov;
230
	somsg.msg_iovlen = 1;
231
	somsg.msg_control = cmsgbuf.buf;
232
	somsg.msg_controllen = sizeof(cmsgbuf.buf);
233
234
	T4 = getoffset();
235
	if ((size = recvmsg(p->query->fd, &somsg, 0)) == -1) {
236
		if (errno == EHOSTUNREACH || errno == EHOSTDOWN ||
237
		    errno == ENETUNREACH || errno == ENETDOWN ||
238
		    errno == ECONNREFUSED || errno == EADDRNOTAVAIL ||
239
		    errno == ENOPROTOOPT || errno == ENOENT) {
240
			client_log_error(p, "recvmsg", errno);
241
			set_next(p, error_interval());
242
			return (0);
243
		} else
244
			fatal("recvfrom");
245
	}
246
247
	if (somsg.msg_flags & MSG_TRUNC) {
248
		client_log_error(p, "recvmsg packet", EMSGSIZE);
249
		set_next(p, error_interval());
250
		return (0);
251
	}
252
253
	if (somsg.msg_flags & MSG_CTRUNC) {
254
		client_log_error(p, "recvmsg control data", E2BIG);
255
		set_next(p, error_interval());
256
		return (0);
257
	}
258
259
	for (cmsg = CMSG_FIRSTHDR(&somsg); cmsg != NULL;
260
	    cmsg = CMSG_NXTHDR(&somsg, cmsg)) {
261
		if (cmsg->cmsg_level == SOL_SOCKET &&
262
		    cmsg->cmsg_type == SCM_TIMESTAMP) {
263
			memcpy(&tv, CMSG_DATA(cmsg), sizeof(tv));
264
			T4 += gettime_from_timeval(&tv);
265
			break;
266
		}
267
	}
268
269
	if (T4 < JAN_1970) {
270
		client_log_error(p, "recvmsg control format", EBADF);
271
		set_next(p, error_interval());
272
		return (0);
273
	}
274
275
	ntp_getmsg((struct sockaddr *)&p->addr->ss, buf, size, &msg);
276
277
	if (msg.orgtime.int_partl != p->query->msg.xmttime.int_partl ||
278
	    msg.orgtime.fractionl != p->query->msg.xmttime.fractionl)
279
		return (0);
280
281
	if ((msg.status & LI_ALARM) == LI_ALARM || msg.stratum == 0 ||
282
	    msg.stratum > NTP_MAXSTRATUM) {
283
		char s[16];
284
285
		if ((msg.status & LI_ALARM) == LI_ALARM) {
286
			strlcpy(s, "alarm", sizeof(s));
287
		} else if (msg.stratum == 0) {
288
			/* Kiss-o'-Death (KoD) packet */
289
			strlcpy(s, "KoD", sizeof(s));
290
		} else if (msg.stratum > NTP_MAXSTRATUM) {
291
			snprintf(s, sizeof(s), "stratum %d", msg.stratum);
292
		}
293
		interval = error_interval();
294
		set_next(p, interval);
295
		log_info("reply from %s: not synced (%s), next query %llds",
296
		    log_sockaddr((struct sockaddr *)&p->addr->ss), s,
297
			(long long)interval);
298
		return (0);
299
	}
300
301
	/*
302
	 * From RFC 2030 (with a correction to the delay math):
303
	 *
304
	 *     Timestamp Name          ID   When Generated
305
	 *     ------------------------------------------------------------
306
	 *     Originate Timestamp     T1   time request sent by client
307
	 *     Receive Timestamp       T2   time request received by server
308
	 *     Transmit Timestamp      T3   time reply sent by server
309
	 *     Destination Timestamp   T4   time reply received by client
310
	 *
311
	 *  The roundtrip delay d and local clock offset t are defined as
312
	 *
313
	 *    d = (T4 - T1) - (T3 - T2)     t = ((T2 - T1) + (T3 - T4)) / 2.
314
	 */
315
316
	T1 = p->query->xmttime;
317
	T2 = lfp_to_d(msg.rectime);
318
	T3 = lfp_to_d(msg.xmttime);
319
320
	/*
321
	 * XXX workaround: time_t / tv_sec must never wrap.
322
	 * around 2020 we will need a solution (64bit time_t / tv_sec).
323
	 * consider every answer with a timestamp beyond january 2030 bogus.
324
	 */
325
	if (T2 > JAN_2030 || T3 > JAN_2030) {
326
		set_next(p, error_interval());
327
		return (0);
328
	}
329
330
	/* Detect liars */
331
	if (conf->constraint_median != 0 &&
332
	    (constraint_check(T2) != 0 || constraint_check(T3) != 0)) {
333
		log_info("reply from %s: constraint check failed",
334
		    log_sockaddr((struct sockaddr *)&p->addr->ss));
335
		set_next(p, error_interval());
336
		return (0);
337
	}
338
339
	p->reply[p->shift].offset = ((T2 - T1) + (T3 - T4)) / 2;
340
	p->reply[p->shift].delay = (T4 - T1) - (T3 - T2);
341
	p->reply[p->shift].status.stratum = msg.stratum;
342
	if (p->reply[p->shift].delay < 0) {
343
		interval = error_interval();
344
		set_next(p, interval);
345
		log_info("reply from %s: negative delay %fs, "
346
		    "next query %llds",
347
		    log_sockaddr((struct sockaddr *)&p->addr->ss),
348
		    p->reply[p->shift].delay, (long long)interval);
349
		return (0);
350
	}
351
	p->reply[p->shift].error = (T2 - T1) - (T3 - T4);
352
	p->reply[p->shift].rcvd = getmonotime();
353
	p->reply[p->shift].good = 1;
354
355
	p->reply[p->shift].status.leap = (msg.status & LIMASK);
356
	p->reply[p->shift].status.precision = msg.precision;
357
	p->reply[p->shift].status.rootdelay = sfp_to_d(msg.rootdelay);
358
	p->reply[p->shift].status.rootdispersion = sfp_to_d(msg.dispersion);
359
	p->reply[p->shift].status.refid = msg.refid;
360
	p->reply[p->shift].status.reftime = lfp_to_d(msg.reftime);
361
	p->reply[p->shift].status.poll = msg.ppoll;
362
363
	if (p->addr->ss.ss_family == AF_INET) {
364
		p->reply[p->shift].status.send_refid =
365
		    ((struct sockaddr_in *)&p->addr->ss)->sin_addr.s_addr;
366
	} else if (p->addr->ss.ss_family == AF_INET6) {
367
		MD5_CTX		context;
368
		u_int8_t	digest[MD5_DIGEST_LENGTH];
369
370
		MD5Init(&context);
371
		MD5Update(&context, ((struct sockaddr_in6 *)&p->addr->ss)->
372
		    sin6_addr.s6_addr, sizeof(struct in6_addr));
373
		MD5Final(digest, &context);
374
		memcpy((char *)&p->reply[p->shift].status.send_refid, digest,
375
		    sizeof(u_int32_t));
376
	} else
377
		p->reply[p->shift].status.send_refid = msg.xmttime.fractionl;
378
379
	if (p->trustlevel < TRUSTLEVEL_PATHETIC)
380
		interval = scale_interval(INTERVAL_QUERY_PATHETIC);
381
	else if (p->trustlevel < TRUSTLEVEL_AGGRESSIVE)
382
		interval = scale_interval(INTERVAL_QUERY_AGGRESSIVE);
383
	else
384
		interval = scale_interval(INTERVAL_QUERY_NORMAL);
385
386
	set_next(p, interval);
387
	p->state = STATE_REPLY_RECEIVED;
388
389
	/* every received reply which we do not discard increases trust */
390
	if (p->trustlevel < TRUSTLEVEL_MAX) {
391
		if (p->trustlevel < TRUSTLEVEL_BADPEER &&
392
		    p->trustlevel + 1 >= TRUSTLEVEL_BADPEER)
393
			log_info("peer %s now valid",
394
			    log_sockaddr((struct sockaddr *)&p->addr->ss));
395
		p->trustlevel++;
396
	}
397
398
	log_debug("reply from %s: offset %f delay %f, "
399
	    "next query %llds",
400
	    log_sockaddr((struct sockaddr *)&p->addr->ss),
401
	    p->reply[p->shift].offset, p->reply[p->shift].delay,
402
	    (long long)interval);
403
404
	client_update(p);
405
	if (settime)
406
		priv_settime(p->reply[p->shift].offset);
407
408
	if (++p->shift >= OFFSET_ARRAY_SIZE)
409
		p->shift = 0;
410
411
	return (0);
412
}
413
414
int
415
client_update(struct ntp_peer *p)
416
{
417
	int	i, best = 0, good = 0;
418
419
	/*
420
	 * clock filter
421
	 * find the offset which arrived with the lowest delay
422
	 * use that as the peer update
423
	 * invalidate it and all older ones
424
	 */
425
426
	for (i = 0; good == 0 && i < OFFSET_ARRAY_SIZE; i++)
427
		if (p->reply[i].good) {
428
			good++;
429
			best = i;
430
		}
431
432
	for (; i < OFFSET_ARRAY_SIZE; i++)
433
		if (p->reply[i].good) {
434
			good++;
435
			if (p->reply[i].delay < p->reply[best].delay)
436
				best = i;
437
		}
438
439
	if (good < 8)
440
		return (-1);
441
442
	memcpy(&p->update, &p->reply[best], sizeof(p->update));
443
	if (priv_adjtime() == 0) {
444
		for (i = 0; i < OFFSET_ARRAY_SIZE; i++)
445
			if (p->reply[i].rcvd <= p->reply[best].rcvd)
446
				p->reply[i].good = 0;
447
	}
448
	return (0);
449
}
450
451
void
452
client_log_error(struct ntp_peer *peer, const char *operation, int error)
453
{
454
	const char *address;
455
456
	address = log_sockaddr((struct sockaddr *)&peer->addr->ss);
457
	if (peer->lasterror == error) {
458
		log_debug("%s %s: %s", operation, address, strerror(error));
459
		return;
460
	}
461
	peer->lasterror = error;
462
	log_warn("%s %s", operation, address);
463
}