Source code pulled from OpenBSD for OpenNTPD. The place to contribute to this code is via the OpenBSD CVS tree.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

439 lines
12 KiB

20 years ago
20 years ago
20 years ago
  1. /* $OpenBSD: client.c,v 1.88 2009/06/24 17:34:32 henning Exp $ */
  2. /*
  3. * Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
  4. * Copyright (c) 2004 Alexander Guy <alexander.guy@andern.org>
  5. *
  6. * Permission to use, copy, modify, and distribute this software for any
  7. * purpose with or without fee is hereby granted, provided that the above
  8. * copyright notice and this permission notice appear in all copies.
  9. *
  10. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  11. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  12. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  13. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  14. * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
  15. * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
  16. * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  17. */
  18. #include <sys/param.h>
  19. #include <errno.h>
  20. #include <md5.h>
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include <time.h>
  25. #include <unistd.h>
  26. #include "ntpd.h"
  27. int client_update(struct ntp_peer *);
  28. void set_deadline(struct ntp_peer *, time_t);
  29. void
  30. set_next(struct ntp_peer *p, time_t t)
  31. {
  32. p->next = getmonotime() + t;
  33. p->deadline = 0;
  34. }
  35. void
  36. set_deadline(struct ntp_peer *p, time_t t)
  37. {
  38. p->deadline = getmonotime() + t;
  39. p->next = 0;
  40. }
  41. int
  42. client_peer_init(struct ntp_peer *p)
  43. {
  44. if ((p->query = calloc(1, sizeof(struct ntp_query))) == NULL)
  45. fatal("client_peer_init calloc");
  46. p->query->fd = -1;
  47. p->query->msg.status = MODE_CLIENT | (NTP_VERSION << 3);
  48. p->state = STATE_NONE;
  49. p->shift = 0;
  50. p->trustlevel = TRUSTLEVEL_PATHETIC;
  51. p->lasterror = 0;
  52. p->senderrors = 0;
  53. return (client_addr_init(p));
  54. }
  55. int
  56. client_addr_init(struct ntp_peer *p)
  57. {
  58. struct sockaddr_in *sa_in;
  59. struct sockaddr_in6 *sa_in6;
  60. struct ntp_addr *h;
  61. for (h = p->addr; h != NULL; h = h->next) {
  62. switch (h->ss.ss_family) {
  63. case AF_INET:
  64. sa_in = (struct sockaddr_in *)&h->ss;
  65. if (ntohs(sa_in->sin_port) == 0)
  66. sa_in->sin_port = htons(123);
  67. p->state = STATE_DNS_DONE;
  68. break;
  69. case AF_INET6:
  70. sa_in6 = (struct sockaddr_in6 *)&h->ss;
  71. if (ntohs(sa_in6->sin6_port) == 0)
  72. sa_in6->sin6_port = htons(123);
  73. p->state = STATE_DNS_DONE;
  74. break;
  75. default:
  76. fatalx("king bula sez: wrong AF in client_addr_init");
  77. /* not reached */
  78. }
  79. }
  80. p->query->fd = -1;
  81. set_next(p, 0);
  82. return (0);
  83. }
  84. int
  85. client_nextaddr(struct ntp_peer *p)
  86. {
  87. if (p->query->fd != -1) {
  88. close(p->query->fd);
  89. p->query->fd = -1;
  90. }
  91. if (p->state == STATE_DNS_INPROGRESS)
  92. return (-1);
  93. if (p->addr_head.a == NULL) {
  94. priv_host_dns(p->addr_head.name, p->id);
  95. p->state = STATE_DNS_INPROGRESS;
  96. return (-1);
  97. }
  98. if ((p->addr = p->addr->next) == NULL)
  99. p->addr = p->addr_head.a;
  100. p->shift = 0;
  101. p->trustlevel = TRUSTLEVEL_PATHETIC;
  102. return (0);
  103. }
  104. int
  105. client_query(struct ntp_peer *p)
  106. {
  107. int val;
  108. if (p->addr == NULL && client_nextaddr(p) == -1) {
  109. set_next(p, MAX(SETTIME_TIMEOUT,
  110. scale_interval(INTERVAL_QUERY_AGGRESSIVE)));
  111. return (0);
  112. }
  113. if (p->state < STATE_DNS_DONE || p->addr == NULL)
  114. return (-1);
  115. if (p->query->fd == -1) {
  116. struct sockaddr *sa = (struct sockaddr *)&p->addr->ss;
  117. if ((p->query->fd = socket(p->addr->ss.ss_family, SOCK_DGRAM,
  118. 0)) == -1)
  119. fatal("client_query socket");
  120. if (connect(p->query->fd, sa, SA_LEN(sa)) == -1) {
  121. if (errno == ECONNREFUSED || errno == ENETUNREACH ||
  122. errno == EHOSTUNREACH || errno == EADDRNOTAVAIL) {
  123. client_nextaddr(p);
  124. set_next(p, MAX(SETTIME_TIMEOUT,
  125. scale_interval(INTERVAL_QUERY_AGGRESSIVE)));
  126. return (-1);
  127. } else
  128. fatal("client_query connect");
  129. }
  130. val = IPTOS_LOWDELAY;
  131. if (p->addr->ss.ss_family == AF_INET && setsockopt(p->query->fd,
  132. IPPROTO_IP, IP_TOS, &val, sizeof(val)) == -1)
  133. log_warn("setsockopt IPTOS_LOWDELAY");
  134. val = 1;
  135. if (setsockopt(p->query->fd, SOL_SOCKET, SO_TIMESTAMP,
  136. &val, sizeof(val)) == -1)
  137. fatal("setsockopt SO_TIMESTAMP");
  138. }
  139. /*
  140. * Send out a random 64-bit number as our transmit time. The NTP
  141. * server will copy said number into the originate field on the
  142. * response that it sends us. This is totally legal per the SNTP spec.
  143. *
  144. * The impact of this is two fold: we no longer send out the current
  145. * system time for the world to see (which may aid an attacker), and
  146. * it gives us a (not very secure) way of knowing that we're not
  147. * getting spoofed by an attacker that can't capture our traffic
  148. * but can spoof packets from the NTP server we're communicating with.
  149. *
  150. * Save the real transmit timestamp locally.
  151. */
  152. p->query->msg.xmttime.int_partl = arc4random();
  153. p->query->msg.xmttime.fractionl = arc4random();
  154. p->query->xmttime = gettime_corrected();
  155. if (ntp_sendmsg(p->query->fd, NULL, &p->query->msg,
  156. NTP_MSGSIZE_NOAUTH, 0) == -1) {
  157. p->senderrors++;
  158. set_next(p, INTERVAL_QUERY_PATHETIC);
  159. p->trustlevel = TRUSTLEVEL_PATHETIC;
  160. return (-1);
  161. }
  162. p->senderrors = 0;
  163. p->state = STATE_QUERY_SENT;
  164. set_deadline(p, QUERYTIME_MAX);
  165. return (0);
  166. }
  167. int
  168. client_dispatch(struct ntp_peer *p, u_int8_t settime)
  169. {
  170. struct ntp_msg msg;
  171. struct msghdr somsg;
  172. struct iovec iov[1];
  173. struct timeval tv;
  174. char buf[NTP_MSGSIZE];
  175. union {
  176. struct cmsghdr hdr;
  177. char buf[CMSG_SPACE(sizeof(tv))];
  178. } cmsgbuf;
  179. struct cmsghdr *cmsg;
  180. ssize_t size;
  181. double T1, T2, T3, T4;
  182. time_t interval;
  183. bzero(&somsg, sizeof(somsg));
  184. iov[0].iov_base = buf;
  185. iov[0].iov_len = sizeof(buf);
  186. somsg.msg_iov = iov;
  187. somsg.msg_iovlen = 1;
  188. somsg.msg_control = cmsgbuf.buf;
  189. somsg.msg_controllen = sizeof(cmsgbuf.buf);
  190. T4 = getoffset();
  191. if ((size = recvmsg(p->query->fd, &somsg, 0)) == -1) {
  192. if (errno == EHOSTUNREACH || errno == EHOSTDOWN ||
  193. errno == ENETUNREACH || errno == ENETDOWN ||
  194. errno == ECONNREFUSED || errno == EADDRNOTAVAIL ||
  195. errno == ENOPROTOOPT || errno == ENOENT) {
  196. client_log_error(p, "recvmsg", errno);
  197. set_next(p, error_interval());
  198. return (0);
  199. } else
  200. fatal("recvfrom");
  201. }
  202. if (somsg.msg_flags & MSG_TRUNC) {
  203. client_log_error(p, "recvmsg packet", EMSGSIZE);
  204. set_next(p, error_interval());
  205. return (0);
  206. }
  207. if (somsg.msg_flags & MSG_CTRUNC) {
  208. client_log_error(p, "recvmsg control data", E2BIG);
  209. set_next(p, error_interval());
  210. return (0);
  211. }
  212. for (cmsg = CMSG_FIRSTHDR(&somsg); cmsg != NULL;
  213. cmsg = CMSG_NXTHDR(&somsg, cmsg)) {
  214. if (cmsg->cmsg_level == SOL_SOCKET &&
  215. cmsg->cmsg_type == SCM_TIMESTAMP) {
  216. memcpy(&tv, CMSG_DATA(cmsg), sizeof(tv));
  217. T4 += tv.tv_sec + JAN_1970 + 1.0e-6 * tv.tv_usec;
  218. break;
  219. }
  220. }
  221. if (T4 < JAN_1970) {
  222. client_log_error(p, "recvmsg control format", EBADF);
  223. set_next(p, error_interval());
  224. return (0);
  225. }
  226. ntp_getmsg((struct sockaddr *)&p->addr->ss, buf, size, &msg);
  227. if (msg.orgtime.int_partl != p->query->msg.xmttime.int_partl ||
  228. msg.orgtime.fractionl != p->query->msg.xmttime.fractionl)
  229. return (0);
  230. if ((msg.status & LI_ALARM) == LI_ALARM || msg.stratum == 0 ||
  231. msg.stratum > NTP_MAXSTRATUM) {
  232. char s[16];
  233. if ((msg.status & LI_ALARM) == LI_ALARM) {
  234. strlcpy(s, "alarm", sizeof(s));
  235. } else if (msg.stratum == 0) {
  236. /* Kiss-o'-Death (KoD) packet */
  237. strlcpy(s, "KoD", sizeof(s));
  238. } else if (msg.stratum > NTP_MAXSTRATUM) {
  239. snprintf(s, sizeof(s), "stratum %d", msg.stratum);
  240. }
  241. interval = error_interval();
  242. set_next(p, interval);
  243. log_info("reply from %s: not synced (%s), next query %ds",
  244. log_sockaddr((struct sockaddr *)&p->addr->ss), s,
  245. interval);
  246. return (0);
  247. }
  248. /*
  249. * From RFC 2030 (with a correction to the delay math):
  250. *
  251. * Timestamp Name ID When Generated
  252. * ------------------------------------------------------------
  253. * Originate Timestamp T1 time request sent by client
  254. * Receive Timestamp T2 time request received by server
  255. * Transmit Timestamp T3 time reply sent by server
  256. * Destination Timestamp T4 time reply received by client
  257. *
  258. * The roundtrip delay d and local clock offset t are defined as
  259. *
  260. * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2.
  261. */
  262. T1 = p->query->xmttime;
  263. T2 = lfp_to_d(msg.rectime);
  264. T3 = lfp_to_d(msg.xmttime);
  265. /*
  266. * XXX workaround: time_t / tv_sec must never wrap.
  267. * around 2020 we will need a solution (64bit time_t / tv_sec).
  268. * consider every answer with a timestamp beyond january 2030 bogus.
  269. */
  270. if (T2 > JAN_2030 || T3 > JAN_2030) {
  271. set_next(p, error_interval());
  272. return (0);
  273. }
  274. p->reply[p->shift].offset = ((T2 - T1) + (T3 - T4)) / 2;
  275. p->reply[p->shift].delay = (T4 - T1) - (T3 - T2);
  276. if (p->reply[p->shift].delay < 0) {
  277. interval = error_interval();
  278. set_next(p, interval);
  279. log_info("reply from %s: negative delay %fs, "
  280. "next query %ds",
  281. log_sockaddr((struct sockaddr *)&p->addr->ss),
  282. p->reply[p->shift].delay, interval);
  283. return (0);
  284. }
  285. p->reply[p->shift].error = (T2 - T1) - (T3 - T4);
  286. p->reply[p->shift].rcvd = getmonotime();
  287. p->reply[p->shift].good = 1;
  288. p->reply[p->shift].status.leap = (msg.status & LIMASK);
  289. p->reply[p->shift].status.precision = msg.precision;
  290. p->reply[p->shift].status.rootdelay = sfp_to_d(msg.rootdelay);
  291. p->reply[p->shift].status.rootdispersion = sfp_to_d(msg.dispersion);
  292. p->reply[p->shift].status.refid = msg.refid;
  293. p->reply[p->shift].status.reftime = lfp_to_d(msg.reftime);
  294. p->reply[p->shift].status.poll = msg.ppoll;
  295. p->reply[p->shift].status.stratum = msg.stratum;
  296. if (p->addr->ss.ss_family == AF_INET) {
  297. p->reply[p->shift].status.send_refid =
  298. ((struct sockaddr_in *)&p->addr->ss)->sin_addr.s_addr;
  299. } else if (p->addr->ss.ss_family == AF_INET6) {
  300. MD5_CTX context;
  301. u_int8_t digest[MD5_DIGEST_LENGTH];
  302. MD5Init(&context);
  303. MD5Update(&context, ((struct sockaddr_in6 *)&p->addr->ss)->
  304. sin6_addr.s6_addr, sizeof(struct in6_addr));
  305. MD5Final(digest, &context);
  306. memcpy((char *)&p->reply[p->shift].status.send_refid, digest,
  307. sizeof(u_int32_t));
  308. } else
  309. p->reply[p->shift].status.send_refid = msg.xmttime.fractionl;
  310. if (p->trustlevel < TRUSTLEVEL_PATHETIC)
  311. interval = scale_interval(INTERVAL_QUERY_PATHETIC);
  312. else if (p->trustlevel < TRUSTLEVEL_AGGRESSIVE)
  313. interval = scale_interval(INTERVAL_QUERY_AGGRESSIVE);
  314. else
  315. interval = scale_interval(INTERVAL_QUERY_NORMAL);
  316. set_next(p, interval);
  317. p->state = STATE_REPLY_RECEIVED;
  318. /* every received reply which we do not discard increases trust */
  319. if (p->trustlevel < TRUSTLEVEL_MAX) {
  320. if (p->trustlevel < TRUSTLEVEL_BADPEER &&
  321. p->trustlevel + 1 >= TRUSTLEVEL_BADPEER)
  322. log_info("peer %s now valid",
  323. log_sockaddr((struct sockaddr *)&p->addr->ss));
  324. p->trustlevel++;
  325. }
  326. log_debug("reply from %s: offset %f delay %f, "
  327. "next query %ds", log_sockaddr((struct sockaddr *)&p->addr->ss),
  328. p->reply[p->shift].offset, p->reply[p->shift].delay, interval);
  329. client_update(p);
  330. if (settime)
  331. priv_settime(p->reply[p->shift].offset);
  332. if (++p->shift >= OFFSET_ARRAY_SIZE)
  333. p->shift = 0;
  334. return (0);
  335. }
  336. int
  337. client_update(struct ntp_peer *p)
  338. {
  339. int i, best = 0, good = 0;
  340. /*
  341. * clock filter
  342. * find the offset which arrived with the lowest delay
  343. * use that as the peer update
  344. * invalidate it and all older ones
  345. */
  346. for (i = 0; good == 0 && i < OFFSET_ARRAY_SIZE; i++)
  347. if (p->reply[i].good) {
  348. good++;
  349. best = i;
  350. }
  351. for (; i < OFFSET_ARRAY_SIZE; i++)
  352. if (p->reply[i].good) {
  353. good++;
  354. if (p->reply[i].delay < p->reply[best].delay)
  355. best = i;
  356. }
  357. if (good < 8)
  358. return (-1);
  359. memcpy(&p->update, &p->reply[best], sizeof(p->update));
  360. if (priv_adjtime() == 0) {
  361. for (i = 0; i < OFFSET_ARRAY_SIZE; i++)
  362. if (p->reply[i].rcvd <= p->reply[best].rcvd)
  363. p->reply[i].good = 0;
  364. }
  365. return (0);
  366. }
  367. void
  368. client_log_error(struct ntp_peer *peer, const char *operation, int error)
  369. {
  370. const char *address;
  371. address = log_sockaddr((struct sockaddr *)&peer->addr->ss);
  372. if (peer->lasterror == error) {
  373. log_debug("%s %s: %s", operation, address, strerror(error));
  374. return;
  375. }
  376. peer->lasterror = error;
  377. log_warn("%s %s", operation, address);
  378. }