xref: /freebsd/contrib/ntp/ntpd/ntp_crypto.c (revision d37ea99837e6ad50837fd9fe1771ddf1c3ba6002)
1 /*
2  * ntp_crypto.c - NTP version 4 public key routines
3  */
4 #ifdef HAVE_CONFIG_H
5 #include <config.h>
6 #endif
7 
8 #ifdef AUTOKEY
9 #include <stdio.h>
10 #include <sys/types.h>
11 #include <unistd.h>
12 #include <fcntl.h>
13 
14 #include "ntpd.h"
15 #include "ntp_stdlib.h"
16 #include "ntp_string.h"
17 #include "ntp_crypto.h"
18 
19 #ifdef KERNEL_PLL
20 #include "ntp_syscall.h"
21 #endif /* KERNEL_PLL */
22 
23 /*
24  * Extension field message formats
25  *
26  *   +-------+-------+   +-------+-------+   +-------+-------+
27  * 0 |   3   |  len  |   |  2,4  |  len  |   |  5-9  |  len  |
28  *   +-------+-------+   +-------+-------+   +-------+-------+
29  * 1 |    assocID    |   |    assocID    |   |    assocID    |
30  *   +---------------+   +---------------+   +---------------+
31  * 2 |   timestamp   |   |   timestamp   |   |   timestamp   |
32  *   +---------------+   +---------------+   +---------------+
33  * 3 |   final seq   |   |  cookie/flags |   |   filestamp   |
34  *   +---------------+   +---------------+   +---------------+
35  * 4 |   final key   |   | signature len |   |   value len   |
36  *   +---------------+   +---------------+   +---------------+
37  * 5 | signature len |   |               |   |               |
38  *   +---------------+   =   signature   =   =     value     =
39  * 6 |               |   |               |   |               |
40  *   =   signature   =   +---------------+   +---------------+
41  * 7 |               |   CRYPTO_ASSOC rsp    | signature len |
42  *   +---------------+   CRYPTO_PRIV rsp     +---------------+
43  *   CRYPTO_AUTO rsp                         |               |
44  *                                           =   signature   =
45  *                                           |               |
46  *                                           +---------------+
47  *                                           CRYPTO_DHPAR rsp
48  *                                           CRYPTO_DH rsp
49  *                                           CRYPTO_NAME rsp
50  *                                           CRYPTO_CERT rsp
51  *                                           CRYPTO_TAI rsp
52  *
53  *   CRYPTO_STAT  1  -    offer/select
54  *   CRYPTO_ASSOC 2  20   association ID
55  *   CRYPTO_AUTO  3  88   autokey values
56  *   CRYPTO_PRIV  4  84   cookie value
57  *   CRYPTO_DHPAR 5  220  agreement parameters
58  *   CRYPTO_DH    6  152  public value
59  *   CRYPTO_NAME  7  460  host name/public key
60  *   CRYPTO_CERT  8  ?    certificate
61  *   CRYPTO_TAI   9  144  leapseconds table
62  *
63  *   Note: requests carry the association ID of the receiver; responses
64  *   carry the association ID of the sender.
65  */
66 /*
67  * Minimum sizes of fields
68  */
69 #define COOKIE_LEN	(5 * 4)
70 #define AUTOKEY_LEN	(6 * 4)
71 #define VALUE_LEN	(6 * 4)
72 
73 /*
74  * Global cryptodata in host byte order.
75  */
76 u_int	crypto_flags;		/* status word */
77 u_int	sys_tai;		/* current UTC offset from TAI */
78 
79 #ifdef PUBKEY
80 /*
81  * Cryptodefines
82  */
83 #define TAI_1972	10	/* initial TAI offset */
84 #define MAX_LEAP	100	/* max UTC leapseconds */
85 #define MAX_LINLEN	1024	/* max line */
86 #define MAX_KEYLEN	1024	/* max key */
87 #define MAX_ENCLEN	(ENCODED_CONTENT_LEN(1024)) /* max enc key */
88 
89 /*
90  * Private cryptodata in network byte order.
91  */
92 static R_RSA_PRIVATE_KEY private_key; /* private key */
93 static R_RSA_PUBLIC_KEY public_key; /* public key */
94 static R_DH_PARAMS dh_params;	/* agreement parameters */
95 static u_char *dh_private;	/* private value */
96 static u_int dh_keyLen;		/* private value length */
97 static char *keysdir = NTP_KEYSDIR; /* crypto keys directory */
98 static char *private_key_file = NULL; /* private key file */
99 static char *public_key_file = NULL; /* public key file */
100 static char *certif_file = NULL; /* certificate file */
101 static char *dh_params_file = NULL; /* agreement parameters file */
102 static char *tai_leap_file = NULL; /* leapseconds file */
103 
104 /*
105  * Global cryptodata in network byte order
106  */
107 struct value host;		/* host name/public key */
108 struct value certif;		/* certificate */
109 struct value dhparam;		/* agreement parameters */
110 struct value dhpub;		/* public value */
111 struct value tai_leap;		/* leapseconds table */
112 
113 /*
114  * Cryptotypes
115  */
116 static	u_int	crypto_rsa	P((char *, u_char *, u_int));
117 static	void	crypto_cert	P((char *));
118 static	void	crypto_dh	P((char *));
119 static	void	crypto_tai	P((char *));
120 #endif /* PUBKEY */
121 
122 /*
123  * Autokey protocol status codes
124  */
125 #define RV_OK		0	/* success */
126 #define RV_LEN		1	/* invalid field length */
127 #define RV_TSP		2	/* invalid timestamp */
128 #define RV_FSP		3	/* invalid filestamp */
129 #define RV_PUB		4	/* missing public key */
130 #define RV_KEY		5	/* invalid RSA modulus */
131 #define RV_SIG		6	/* invalid signature length */
132 #define RV_DH		7	/* invalid agreement parameters */
133 #define RV_FIL		8	/* missing or corrupted key file */
134 #define RV_DAT		9	/* missing or corrupted data */
135 #define RV_DEC		10	/* PEM decoding error */
136 #define RV_DUP		11	/* duplicate flags */
137 #define RV_VN		12	/* incorrect version */
138 
139 /*
140  * session_key - generate session key
141  *
142  * This routine generates a session key from the source address,
143  * destination address, key ID and private value. The value of the
144  * session key is the MD5 hash of these values, while the next key ID is
145  * the first four octets of the hash.
146  */
147 keyid_t				/* returns next key ID */
148 session_key(
149 	struct sockaddr_in *srcadr, /* source address */
150 	struct sockaddr_in *dstadr, /* destination address */
151 	keyid_t keyno,		/* key ID */
152 	keyid_t private,	/* private value */
153 	u_long lifetime 	/* key lifetime */
154 	)
155 {
156 	MD5_CTX ctx;		/* MD5 context */
157 	keyid_t keyid;		/* key identifer */
158 	u_int32 header[4];	/* data in network byte order */
159 	u_char digest[16];	/* message digest */
160 
161 	/*
162 	 * Generate the session key and key ID. If the lifetime is
163 	 * greater than zero, install the key and call it trusted.
164 	 */
165 	header[0] = srcadr->sin_addr.s_addr;
166 	header[1] = dstadr->sin_addr.s_addr;
167 	header[2] = htonl(keyno);
168 	header[3] = htonl(private);
169 	MD5Init(&ctx);
170 	MD5Update(&ctx, (u_char *)header, sizeof(header));
171 	MD5Final(digest, &ctx);
172 	memcpy(&keyid, digest, 4);
173 	keyid = ntohl(keyid);
174 	if (lifetime != 0) {
175 		MD5auth_setkey(keyno, digest, 16);
176 		authtrust(keyno, lifetime);
177 	}
178 #ifdef DEBUG
179 	if (debug > 1)
180 		printf(
181 		    "session_key: %s > %s %08x %08x hash %08x life %lu\n",
182 		    numtoa(header[0]), numtoa(header[1]), keyno,
183 		    private, keyid, lifetime);
184 #endif
185 	return (keyid);
186 }
187 
188 
189 /*
190  * make_keylist - generate key list
191  *
192  * This routine constructs a pseudo-random sequence by repeatedly
193  * hashing the session key starting from a given source address,
194  * destination address, private value and the next key ID of the
195  * preceeding session key. The last entry on the list is saved along
196  * with its sequence number and public signature.
197  */
198 void
199 make_keylist(
200 	struct peer *peer,	/* peer structure pointer */
201 	struct interface *dstadr /* interface */
202 	)
203 {
204 	struct autokey *ap;	/* autokey pointer */
205 	keyid_t keyid;		/* next key ID */
206 	keyid_t cookie;		/* private value */
207 	l_fp tstamp;		/* NTP timestamp */
208 	u_long ltemp;
209 	int i;
210 #ifdef PUBKEY
211 	R_SIGNATURE_CTX ctx;	/* signature context */
212 	int rval;		/* return value */
213 	u_int len;
214 #endif /* PUBKEY */
215 
216 	/*
217 	 * Allocate the key list if necessary.
218 	 */
219 	L_CLR(&tstamp);
220 	if (sys_leap != LEAP_NOTINSYNC)
221 		get_systime(&tstamp);
222 	if (peer->keylist == NULL)
223 		peer->keylist = (keyid_t *)emalloc(sizeof(keyid_t) *
224 		    NTP_MAXSESSION);
225 
226 	/*
227 	 * Generate an initial key ID which is unique and greater than
228 	 * NTP_MAXKEY.
229 	 */
230 	while (1) {
231 		keyid = (u_long)RANDOM & 0xffffffff;
232 		if (keyid <= NTP_MAXKEY)
233 			continue;
234 		if (authhavekey(keyid))
235 			continue;
236 		break;
237 	}
238 
239 	/*
240 	 * Generate up to NTP_MAXSESSION session keys. Stop if the
241 	 * next one would not be unique or not a session key ID or if
242 	 * it would expire before the next poll. The private value
243 	 * included in the hash is zero if broadcast mode, the peer
244 	 * cookie if client mode or the host cookie if symmetric modes.
245 	 */
246 	ltemp = min(sys_automax, NTP_MAXSESSION * (1 << (peer->kpoll)));
247 	peer->hcookie = session_key(&dstadr->sin, &peer->srcadr, 0,
248 	    sys_private, 0);
249 	if (peer->hmode == MODE_BROADCAST)
250 		cookie = 0;
251 	else
252 		cookie = peer->pcookie.key;
253 	for (i = 0; i < NTP_MAXSESSION; i++) {
254 		peer->keylist[i] = keyid;
255 		peer->keynumber = i;
256 		keyid = session_key(&dstadr->sin, &peer->srcadr, keyid,
257 		    cookie, ltemp);
258 		ltemp -= 1 << peer->kpoll;
259 		if (auth_havekey(keyid) || keyid <= NTP_MAXKEY ||
260 		    ltemp <= (1 << (peer->kpoll)))
261 			break;
262 	}
263 
264 	/*
265 	 * Save the last session key ID, sequence number and timestamp,
266 	 * then sign these values for later retrieval by the clients. Be
267 	 * careful not to use invalid key media.
268 	 */
269 	ap = &peer->sndauto;
270 	ap->tstamp = htonl(tstamp.l_ui);
271 	ap->seq = htonl(peer->keynumber);
272 	ap->key = htonl(keyid);
273 	ap->siglen = 0;
274 #if DEBUG
275 	if (debug)
276 		printf("make_keys: %d %08x %08x ts %u poll %d\n",
277 		    ntohl(ap->seq), ntohl(ap->key), cookie,
278 		    ntohl(ap->tstamp), peer->kpoll);
279 #endif
280 #ifdef PUBKEY
281 	if(!crypto_flags)
282 		return;
283 	if (ap->sig == NULL)
284 		ap->sig = emalloc(private_key.bits / 8);
285 	EVP_SignInit(&ctx, DA_MD5);
286 	EVP_SignUpdate(&ctx, (u_char *)ap, 12);
287 	rval = EVP_SignFinal(&ctx, ap->sig, &len, &private_key);
288 	if (rval != RV_OK)
289 		msyslog(LOG_ERR, "crypto: keylist signature fails %x",
290 		    rval);
291 	else
292 		ap->siglen = htonl(len);
293 	peer->flags |= FLAG_ASSOC;
294 #endif /* PUBKEY */
295 }
296 
297 
298 /*
299  * crypto_recv - parse extension fields
300  *
301  * This routine is called when the packet has been matched to an
302  * association and passed sanity, format and MAC checks. We believe the
303  * extension field values only if the field has proper format and
304  * length, the timestamp and filestamp are valid and the signature has
305  * valid length and is verified. There are a few cases where some values
306  * are believed even if the signature fails, but only if the authentic
307  * bit is not set.
308  */
309 void
310 crypto_recv(
311 	struct peer *peer,	/* peer structure pointer */
312 	struct recvbuf *rbufp	/* packet buffer pointer */
313 	)
314 {
315 	u_int32 *pkt;		/* packet pointer */
316 	struct autokey *ap;	/* autokey pointer */
317 	struct cookie *cp;	/* cookie pointer */
318 	int has_mac;		/* length of MAC field */
319 	int authlen;		/* offset of MAC field */
320 	int len;		/* extension field length */
321 	u_int code;		/* extension field opcode */
322 	tstamp_t tstamp;	/* timestamp */
323 	int i, rval;
324 	u_int temp;
325 #ifdef PUBKEY
326 	R_SIGNATURE_CTX ctx;	/* signature context */
327 	struct value *vp;	/* value pointer */
328 	u_char dh_key[MAX_KEYLEN]; /* agreed key */
329 	R_RSA_PUBLIC_KEY *kp;	/* temporary public key pointer */
330 	tstamp_t fstamp;	/* filestamp */
331 	u_int32 *pp;		/* packet pointer */
332 	u_int rsalen = sizeof(R_RSA_PUBLIC_KEY) - sizeof(u_int) + 4;
333 	u_int bits;
334 	int j;
335 #ifdef KERNEL_PLL
336 #if NTP_API > 3
337 	struct timex ntv;	/* kernel interface structure */
338 #endif /* NTP_API */
339 #endif /* KERNEL_PLL */
340 #endif /* PUBKEY */
341 
342 	/*
343 	 * Initialize. Note that the packet has already been checked for
344 	 * valid format and extension field lengths. We first extract
345 	 * the field length, command code and timestamp in host byte
346 	 * order. These are used with all commands and modes. We discard
347 	 * old timestamps and filestamps; but, for duplicate timestamps
348 	 * we discard only if the authentic bit is set. Cute.
349 	 */
350 	pkt = (u_int32 *)&rbufp->recv_pkt;
351 	authlen = LEN_PKT_NOMAC;
352 	while ((has_mac = rbufp->recv_length - authlen) > MAX_MAC_LEN) {
353 		i = authlen / 4;
354 		len = ntohl(pkt[i]) & 0xffff;
355 		code = (ntohl(pkt[i]) >> 16) & 0xffff;
356 		temp = (code >> 8) & 0x3f;
357 		if (temp != CRYPTO_VN) {
358 			sys_unknownversion++;
359 #ifdef DEBUG
360 			if (debug)
361 				printf(
362 				    "crypto_recv: incorrect version %d should be %d\n",
363 				    temp, CRYPTO_VN);
364 #endif
365 			return;
366 		}
367 		tstamp = ntohl(pkt[i + 2]);
368 #ifdef DEBUG
369 		if (debug)
370 			printf(
371 			    "crypto_recv: ext offset %d len %d code %x assocID %d\n",
372 			    authlen, len, code, (u_int32)ntohl(pkt[i +
373 			    1]));
374 #endif
375 		switch (code) {
376 
377 		/*
378 		 * Install association ID and status word.
379 		 */
380 		case CRYPTO_ASSOC | CRYPTO_RESP:
381 			cp = (struct cookie *)&pkt[i + 2];
382 			temp = ntohl(cp->key);
383 			if (len < COOKIE_LEN) {
384 				rval = RV_LEN;
385 			} else if (tstamp == 0) {
386 				rval = RV_TSP;
387 			} else {
388 				if (!peer->crypto)
389 					peer->crypto = temp;
390 				if (ntohl(pkt[i + 1]) != 0)
391 					peer->assoc = ntohl(pkt[i + 1]);
392 				rval = RV_OK;
393 			}
394 #ifdef DEBUG
395 			if (debug)
396 				printf(
397 				    "crypto_recv: verify %d flags 0x%x ts %u\n",
398 				    rval, temp, tstamp);
399 #endif
400 			break;
401 
402 		/*
403 		 * Install autokey values in broadcast client and
404 		 * symmetric modes.
405 		 */
406 		case CRYPTO_AUTO | CRYPTO_RESP:
407 			if (!(peer->flags & FLAG_AUTOKEY) &&
408 			    ntohl(pkt[i + 1]) != 0)
409 				peer->assoc = ntohl(pkt[i + 1]);
410 			ap = (struct autokey *)&pkt[i + 2];
411 #ifdef PUBKEY
412 			temp = ntohl(ap->siglen);
413 			kp = (R_RSA_PUBLIC_KEY *)peer->pubkey.ptr;
414 			if (len < AUTOKEY_LEN) {
415 				rval = RV_LEN;
416 			} else if (tstamp == 0 || tstamp <
417 			    peer->recauto.tstamp || (tstamp ==
418 			    peer->recauto.tstamp && (peer->flags &
419 			    FLAG_AUTOKEY))) {
420 				rval = RV_TSP;
421 			} else if (!crypto_flags) {
422 				rval = RV_OK;
423 			} else if (kp == NULL) {
424 				rval = RV_PUB;
425 			} else if (temp != kp->bits / 8) {
426 				rval = RV_SIG;
427 			} else {
428 				EVP_VerifyInit(&ctx, DA_MD5);
429 				EVP_VerifyUpdate(&ctx, (u_char *)ap,
430 				    12);
431 				rval = EVP_VerifyFinal(&ctx,
432 				    (u_char *)ap->pkt, temp, kp);
433 			}
434 #else /* PUBKEY */
435 			if (tstamp < peer->recauto.tstamp || (tstamp ==
436 			    peer->recauto.tstamp && (peer->flags &
437 			    FLAG_AUTOKEY)))
438 				rval = RV_TSP;
439 			else
440 				rval = RV_OK;
441 #endif /* PUBKEY */
442 #ifdef DEBUG
443 			if (debug)
444 				printf(
445 				    "crypto_recv: verify %x autokey %d %08x ts %u (%u)\n",
446 				    rval, ntohl(ap->seq),
447 				    ntohl(ap->key), tstamp,
448 				    peer->recauto.tstamp);
449 #endif
450 			if (rval != RV_OK) {
451 				if (rval != RV_TSP)
452 					msyslog(LOG_ERR,
453 					    "crypto: %x autokey %d %08x ts %u (%u)\n",
454 					    rval, ntohl(ap->seq),
455 					    ntohl(ap->key), tstamp,
456 					    peer->recauto.tstamp);
457 				break;
458 			}
459 			peer->flags |= FLAG_AUTOKEY;
460 			peer->flash &= ~TEST10;
461 			peer->assoc = ntohl(pkt[i + 1]);
462 			peer->recauto.tstamp = tstamp;
463 			peer->recauto.seq = ntohl(ap->seq);
464 			peer->recauto.key = ntohl(ap->key);
465 			peer->pkeyid = peer->recauto.key;
466 			break;
467 
468 		/*
469 		 * Install session cookie in client mode. Use this also
470 		 * in symmetric modes for test when rsaref20 has not
471 		 * been installed.
472 		 */
473 		case CRYPTO_PRIV:
474 			peer->cmmd = ntohl(pkt[i]);
475 			/* fall through */
476 
477 		case CRYPTO_PRIV | CRYPTO_RESP:
478 			cp = (struct cookie *)&pkt[i + 2];
479 #ifdef PUBKEY
480 			temp = ntohl(cp->siglen);
481 			kp = (R_RSA_PUBLIC_KEY *)peer->pubkey.ptr;
482 			if (len < COOKIE_LEN) {
483 				rval = RV_LEN;
484 			} else if (tstamp == 0 || tstamp <
485 			    peer->pcookie.tstamp || (tstamp ==
486 			    peer->pcookie.tstamp && (peer->flags &
487 			    FLAG_AUTOKEY))) {
488 				rval = RV_TSP;
489 			} else if (!crypto_flags) {
490 				rval = RV_OK;
491 			} else if (kp == NULL) {
492 				rval = RV_PUB;
493 			} else if (temp != kp->bits / 8) {
494 				rval = RV_SIG;
495 			} else {
496 				EVP_VerifyInit(&ctx, DA_MD5);
497 				EVP_VerifyUpdate(&ctx, (u_char *)cp, 8);
498 				rval = EVP_VerifyFinal(&ctx,
499 				    (u_char *)cp->pkt, temp, kp);
500 			}
501 #else /* PUBKEY */
502 			if (tstamp <= peer->pcookie.tstamp || (tstamp ==
503 			    peer->pcookie.tstamp && (peer->flags &
504 			    FLAG_AUTOKEY)))
505 				rval = RV_TSP;
506 			else
507 				rval = RV_OK;
508 #endif /* PUBKEY */
509 
510 			/*
511 			 * Tricky here. If in client mode, use the
512 			 * server cookie; otherwise, use EXOR of both
513 			 * peer cookies. We call this Daffy-Hooligan
514 			 * agreement.
515 			 */
516 			if (peer->hmode == MODE_CLIENT)
517 				temp = ntohl(cp->key);
518 			else
519 				temp = ntohl(cp->key) ^ peer->hcookie;
520 #ifdef DEBUG
521 			if (debug)
522 				printf(
523 				    "crypto_recv: verify %x cookie %08x ts %u (%u)\n",
524 				    rval, temp, tstamp,
525 				    peer->pcookie.tstamp);
526 #endif
527 			if (rval != RV_OK) {
528 				if (rval != RV_TSP)
529 					msyslog(LOG_ERR,
530 					    "crypto: %x cookie %08x ts %u (%u)\n",
531 					    rval, temp, tstamp,
532 					    peer->pcookie.tstamp);
533 					peer->cmmd |= CRYPTO_ERROR;
534 				break;
535 			}
536 			if (!(peer->cast_flags & MDF_BCLNT))
537 				peer->flags |= FLAG_AUTOKEY;
538 			peer->flash &= ~TEST10;
539 			peer->assoc = ntohl(pkt[i + 1]);
540 			peer->pcookie.tstamp = tstamp;
541 			if (temp != peer->pcookie.key) {
542 				peer->pcookie.key = temp;
543 				key_expire(peer);
544 			}
545 			break;
546 
547 		/*
548 		 * The following commands and responses work only when
549 		 * public-key cryptography has been configured. If
550 		 * configured, but disabled due to no crypto command in
551 		 * the configuration file, they are ignored.
552 		 */
553 #ifdef PUBKEY
554 		/*
555 		 * Install public key and host name.
556 		 */
557 		case CRYPTO_NAME | CRYPTO_RESP:
558 			if (!crypto_flags)
559 				break;
560 			vp = (struct value *)&pkt[i + 2];
561 			fstamp = ntohl(vp->fstamp);
562 			temp = ntohl(vp->vallen);
563 			j = i + 5 + ntohl(vp->vallen) / 4;
564 			bits = ntohl(pkt[i + 5]);
565 			if (len < VALUE_LEN) {
566 				rval = RV_LEN;
567 			} else if (temp < rsalen || bits <
568 			    MIN_RSA_MODULUS_BITS || bits >
569 			    MAX_RSA_MODULUS_BITS) {
570 				rval = RV_KEY;
571 			} else if (ntohl(pkt[j]) != bits / 8) {
572 				rval = RV_SIG;
573 			} else if (tstamp == 0 || tstamp <
574 			    peer->pubkey.tstamp || (tstamp ==
575 			    peer->pubkey.tstamp && (peer->flags &
576 			    FLAG_AUTOKEY))) {
577 				rval = RV_TSP;
578 			} else if (tstamp < peer->pubkey.fstamp ||
579 			    fstamp < peer->pubkey.fstamp) {
580 				rval = RV_FSP;
581 			} else if (fstamp == peer->pubkey.fstamp &&
582 			    (peer->flags & FLAG_AUTOKEY)) {
583 				rval = RV_FSP;
584 			} else {
585 				EVP_VerifyInit(&ctx, DA_MD5);
586 				EVP_VerifyUpdate(&ctx, (u_char *)vp,
587 				    temp + 12);
588 				kp = emalloc(sizeof(R_RSA_PUBLIC_KEY));
589 				kp->bits = bits;
590 				memcpy(kp->modulus, &pkt[i + 6],
591 				    rsalen - 4);
592 				rval = EVP_VerifyFinal(&ctx,
593 				    (u_char *)&pkt[j + 1],
594 				    ntohl(pkt[j]), kp);
595 				if (rval != 0) {
596 					free(kp);
597 				} else {
598 					j = i + 5 + rsalen / 4;
599 					peer->pubkey.ptr = (u_char *)kp;
600 					temp = strlen((char *)&pkt[j]);
601 					peer->keystr = emalloc(temp +
602 					    1);
603 					strcpy(peer->keystr,
604 					    (char *)&pkt[j]);
605 					peer->pubkey.tstamp = tstamp;
606 					peer->pubkey.fstamp = fstamp;
607 					peer->flash &= ~TEST10;
608 					if (!(peer->crypto &
609 					    CRYPTO_FLAG_CERT))
610 						peer->flags |=
611 						    FLAG_PROVEN;
612 				}
613 			}
614 #ifdef DEBUG
615 			if (debug)
616 
617 				printf(
618 				    "crypto_recv: verify %x host %s ts %u fs %u\n",
619 				    rval, (char *)&pkt[i + 5 + rsalen /
620 				    4], tstamp, fstamp);
621 #endif
622 			if (rval != RV_OK) {
623 				if (rval != RV_TSP)
624 					msyslog(LOG_ERR,
625 					    "crypto: %x host %s ts %u fs %u\n",
626 					    rval, (char *)&pkt[i + 5 +
627 					    rsalen / 4], tstamp,
628 					    fstamp);
629 			}
630 			break;
631 
632 		/*
633 		 * Install certificate.
634 		 */
635 		case CRYPTO_CERT | CRYPTO_RESP:
636 			if (!crypto_flags)
637 				break;
638 			vp = (struct value *)&pkt[i + 2];
639 			fstamp = ntohl(vp->fstamp);
640 			temp = ntohl(vp->vallen);
641 			kp = (R_RSA_PUBLIC_KEY *)peer->pubkey.ptr;
642 			j = i + 5 + temp / 4;
643 			if (len < VALUE_LEN) {
644 				rval = RV_LEN;
645 			} else if (kp == NULL) {
646 				rval = RV_PUB;
647 			} else if (ntohl(pkt[j]) != kp->bits / 8) {
648 				rval = RV_SIG;
649 			} else if (tstamp == 0) {
650 				rval = RV_TSP;
651 			} else if (tstamp <
652 			    ntohl(peer->certif.fstamp) || fstamp <
653 			    ntohl(peer->certif.fstamp)) {
654 				rval = RV_FSP;
655 			} else if (fstamp ==
656 			    ntohl(peer->certif.fstamp) && (peer->flags &
657 			    FLAG_AUTOKEY)) {
658 				peer->crypto &= ~CRYPTO_FLAG_CERT;
659 				rval = RV_FSP;
660 			} else {
661 				EVP_VerifyInit(&ctx, DA_MD5);
662 				EVP_VerifyUpdate(&ctx, (u_char *)vp,
663 				    temp + 12);
664 				rval = EVP_VerifyFinal(&ctx,
665 				    (u_char *)&pkt[j + 1],
666 				    ntohl(pkt[j]), kp);
667 			}
668 #ifdef DEBUG
669 			if (debug)
670 				printf(
671 				    "crypto_recv: verify %x certificate %u ts %u fs %u\n",
672 				    rval, temp, tstamp, fstamp);
673 #endif
674 
675 			/*
676 			 * If the peer data are newer than the host
677 			 * data, replace the host data. Otherwise,
678 			 * wait for the peer to fetch the host data.
679 			 */
680 			if (rval != RV_OK || temp == 0) {
681 				if (rval != RV_TSP)
682 					msyslog(LOG_ERR,
683 					    "crypto: %x certificate %u ts %u fs %u\n",
684 					    rval, temp, tstamp, fstamp);
685 				break;
686 			}
687 			peer->flash &= ~TEST10;
688 			peer->flags |= FLAG_PROVEN;
689 			peer->crypto &= ~CRYPTO_FLAG_CERT;
690 
691 			/*
692 			 * Initialize agreement parameters and extension
693 			 * field in network byte order. Note the private
694 			 * key length is set arbitrarily at half the
695 			 * prime length.
696 			 */
697 			peer->certif.tstamp = vp->tstamp;
698 			peer->certif.fstamp = vp->fstamp;
699 			peer->certif.vallen = vp->vallen;
700 			if (peer->certif.ptr == NULL)
701 				free(peer->certif.ptr);
702 			peer->certif.ptr = emalloc(temp);
703 			memcpy(peer->certif.ptr, vp->pkt, temp);
704 			crypto_agree();
705 			break;
706 
707 		/*
708 		 * Install agreement parameters in symmetric modes.
709 		 */
710 		case CRYPTO_DHPAR | CRYPTO_RESP:
711 			if (!crypto_flags)
712 				break;
713 			vp = (struct value *)&pkt[i + 2];
714 			fstamp = ntohl(vp->fstamp);
715 			temp = ntohl(vp->vallen);
716 			kp = (R_RSA_PUBLIC_KEY *)peer->pubkey.ptr;
717 			j = i + 5 + temp / 4;
718 			if (len < VALUE_LEN) {
719 				rval = RV_LEN;
720 			} else if (kp == NULL) {
721 				rval = RV_PUB;
722 			} else if (ntohl(pkt[j]) != kp->bits / 8) {
723 				rval = RV_SIG;
724 			} else if (tstamp == 0) {
725 				rval = RV_TSP;
726 			} else if (tstamp < ntohl(dhparam.fstamp) ||
727 			    fstamp < ntohl(dhparam.fstamp)) {
728 				rval = RV_FSP;
729 			} else if (fstamp == ntohl(dhparam.fstamp) &&
730 			    (peer->flags & FLAG_AUTOKEY)) {
731 				peer->crypto &= ~CRYPTO_FLAG_DH;
732 				rval = RV_FSP;
733 			} else {
734 				EVP_VerifyInit(&ctx, DA_MD5);
735 				EVP_VerifyUpdate(&ctx, (u_char *)vp,
736 				    temp + 12);
737 				rval = EVP_VerifyFinal(&ctx,
738 				    (u_char *)&pkt[j + 1],
739 				    ntohl(pkt[j]), kp);
740 			}
741 #ifdef DEBUG
742 			if (debug)
743 				printf(
744 				    "crypto_recv: verify %x parameters %u ts %u fs %u\n",
745 				    rval, temp, tstamp, fstamp);
746 #endif
747 
748 			/*
749 			 * If the peer data are newer than the host
750 			 * data, replace the host data. Otherwise,
751 			 * wait for the peer to fetch the host data.
752 			 */
753 			if (rval != RV_OK || temp == 0) {
754 				if (rval != RV_TSP)
755 					msyslog(LOG_ERR,
756 					    "crypto: %x parameters %u ts %u fs %u\n",
757 					    rval, temp, tstamp, fstamp);
758 				break;
759 			}
760 			peer->flash &= ~TEST10;
761 			crypto_flags |= CRYPTO_FLAG_DH;
762 			peer->crypto &= ~CRYPTO_FLAG_DH;
763 
764 			/*
765 			 * Initialize agreement parameters and extension
766 			 * field in network byte order. Note the private
767 			 * key length is set arbitrarily at half the
768 			 * prime length.
769 			 */
770 			dhparam.tstamp = vp->tstamp;
771 			dhparam.fstamp = vp->fstamp;
772 			dhparam.vallen = vp->vallen;
773 			if (dhparam.ptr != NULL)
774 				free(dhparam.ptr);
775 			pp = emalloc(temp);
776 			dhparam.ptr = (u_char *)pp;
777 			memcpy(pp, vp->pkt, temp);
778 			dh_params.primeLen = ntohl(*pp++);
779 			dh_params.prime = (u_char *)pp;
780 			pp += dh_params.primeLen / 4;
781 			dh_params.generatorLen = ntohl(*pp++);
782 			dh_params.generator = (u_char *)pp;
783 			dh_keyLen = dh_params.primeLen / 2;
784 			if (dh_private != NULL)
785 				free(dh_private);
786 			dh_private = emalloc(dh_keyLen);
787 			if (dhparam.sig == NULL)
788 				dhparam.sig = emalloc(private_key.bits /
789 				    8);
790 
791 			/*
792 			 * Initialize public value extension field.
793 			 */
794 			dhpub.tstamp = vp->tstamp;
795 			dhpub.fstamp = vp->fstamp;
796 			dhpub.vallen = htonl(dh_params.primeLen);
797 			if (dhpub.ptr != NULL)
798 				free(dhpub.ptr);
799 			dhpub.ptr = emalloc(dh_params.primeLen);
800 			if (dhpub.sig == NULL)
801 				dhpub.sig = emalloc(private_key.bits /
802 				    8);
803 			crypto_agree();
804 			break;
805 
806 		/*
807 		 * Verify public value and compute agreed key in
808 		 * symmetric modes.
809 		 */
810 		case CRYPTO_DH:
811 			peer->cmmd = ntohl(pkt[i]);
812 			if (!crypto_flags)
813 				peer->cmmd |= CRYPTO_ERROR;
814 			/* fall through */
815 
816 		case CRYPTO_DH | CRYPTO_RESP:
817 			if (!crypto_flags)
818 				break;
819 			vp = (struct value *)&pkt[i + 2];
820 			fstamp = ntohl(vp->fstamp);
821 			temp = ntohl(vp->vallen);
822 			kp = (R_RSA_PUBLIC_KEY *)peer->pubkey.ptr;
823 			j = i + 5 + temp / 4;
824 			if (len < VALUE_LEN) {
825 				rval = RV_LEN;
826 			} else if (temp != dh_params.primeLen) {
827 				rval = RV_DH;
828 			} else if (kp == NULL) {
829 				rval = RV_PUB;
830 			} else if (ntohl(pkt[j]) != kp->bits / 8) {
831 				rval = RV_SIG;
832 			} else if (tstamp == 0 || tstamp <
833 			    peer->pcookie.tstamp || (tstamp ==
834 			    peer->pcookie.tstamp && (peer->flags &
835 			    FLAG_AUTOKEY))) {
836 				rval = RV_TSP;
837 			} else {
838 				EVP_VerifyInit(&ctx, DA_MD5);
839 				EVP_VerifyUpdate(&ctx, (u_char *)vp,
840 				    temp + 12);
841 				rval = EVP_VerifyFinal(&ctx,
842 				    (u_char *)&pkt[j + 1],
843 				    ntohl(pkt[j]), kp);
844 			}
845 
846 			/*
847 			 * Run the agreement algorithm and stash the key
848 			 * value. We use only the first u_int32 for the
849 			 * host cookie. Wasteful. If the association ID
850 			 * is zero, the other guy hasn't seen us as
851 			 * synchronized, in which case both of us should
852 			 * be using a zero cookie.
853 			 */
854 			if (rval != RV_OK) {
855 				temp = 0;
856 			} else if (fstamp > dhparam.fstamp) {
857 				crypto_flags &= ~CRYPTO_FLAG_DH;
858 				rval = RV_FSP;
859 			} else {
860 				rval = R_ComputeDHAgreedKey(dh_key,
861 				    (u_char *)&pkt[i + 5], dh_private,
862 				    dh_keyLen, &dh_params);
863 				temp = ntohl(*(u_int32 *)dh_key);
864 			}
865 #ifdef DEBUG
866 			if (debug)
867 				printf(
868 				    "crypto_recv: verify %x agreement %08x ts %u (%u) fs %u\n",
869 				    rval, temp, tstamp,
870 				    peer->pcookie.tstamp, fstamp);
871 #endif
872 			if (rval != RV_OK) {
873 				if (rval != RV_TSP)
874 					msyslog(LOG_ERR,
875 					    "crypto: %x agreement %08x ts %u (%u) fs %u\n",
876 					    rval, temp, tstamp,
877 					    peer->pcookie.tstamp,
878 					    fstamp);
879 					peer->cmmd |= CRYPTO_ERROR;
880 				break;
881 			}
882 			peer->flash &= ~TEST10;
883 			peer->flags &= ~FLAG_AUTOKEY;
884 			peer->assoc = ntohl(pkt[i + 1]);
885 			peer->pcookie.tstamp = tstamp;
886 			if (temp != peer->pcookie.key) {
887 				peer->pcookie.key = temp;
888 				key_expire(peer);
889 			}
890 			break;
891 
892 		/*
893 		 * Install leapseconds table.
894 		 */
895 		case CRYPTO_TAI | CRYPTO_RESP:
896 			if (!crypto_flags)
897 				break;
898 			vp = (struct value *)&pkt[i + 2];
899 			fstamp = ntohl(vp->fstamp);
900 			temp = ntohl(vp->vallen);
901 			kp = (R_RSA_PUBLIC_KEY *)peer->pubkey.ptr;
902 			j = i + 5 + temp / 4;
903 			if (len < VALUE_LEN) {
904 				rval = RV_LEN;
905 			} if (kp == NULL) {
906 				rval = RV_PUB;
907 			} else if (ntohl(pkt[j]) != kp->bits / 8) {
908 				rval = RV_SIG;
909 			} else if (tstamp == 0) {
910 				rval = RV_TSP;
911 			} else if (tstamp < ntohl(tai_leap.fstamp) ||
912 			    fstamp < ntohl(tai_leap.fstamp)) {
913 				rval = RV_FSP;
914 			} else if (fstamp == ntohl(tai_leap.fstamp) &&
915 			    (peer->flags & FLAG_AUTOKEY)) {
916 				peer->crypto &= ~CRYPTO_FLAG_TAI;
917 				rval = RV_FSP;
918 			} else {
919 				EVP_VerifyInit(&ctx, DA_MD5);
920 				EVP_VerifyUpdate(&ctx, (u_char *)vp,
921 				    temp + 12);
922 				rval = EVP_VerifyFinal(&ctx,
923 				    (u_char *)&pkt[j + 1],
924 				    ntohl(pkt[j]), kp);
925 			}
926 #ifdef DEBUG
927 			if (debug)
928 				printf(
929 				    "crypto_recv: verify %x leapseconds %u ts %u fs %u\n",
930 				    rval, temp, tstamp, fstamp);
931 #endif
932 
933 			/*
934 			 * If the peer data are newer than the host
935 			 * data, replace the host data. Otherwise,
936 			 * wait for the peer to fetch the host data.
937 			 */
938 			if (rval != RV_OK || temp == 0) {
939 				if (rval != RV_TSP)
940 					msyslog(LOG_ERR,
941 					    "crypto: %x leapseconds %u ts %u fs %u\n",
942 					    rval, temp, tstamp, fstamp);
943 				break;
944 			}
945 			peer->flash &= ~TEST10;
946 			crypto_flags |= CRYPTO_FLAG_TAI;
947 			peer->crypto &= ~CRYPTO_FLAG_TAI;
948 			sys_tai = temp / 4 + TAI_1972 - 1;
949 #ifdef KERNEL_PLL
950 #if NTP_API > 3
951 			ntv.modes = MOD_TAI;
952 			ntv.constant = sys_tai;
953 			(void)ntp_adjtime(&ntv);
954 #endif /* NTP_API */
955 #endif /* KERNEL_PLL */
956 
957 			/*
958 			 * Initialize leapseconds table and extension
959 			 * field in network byte order.
960 			 */
961 			tai_leap.tstamp = vp->tstamp;
962 			tai_leap.fstamp = vp->fstamp;
963 			tai_leap.vallen = vp->vallen;
964 			if (tai_leap.ptr == NULL)
965 				free(tai_leap.ptr);
966 			tai_leap.ptr = emalloc(temp);
967 			memcpy(tai_leap.ptr, vp->pkt, temp);
968 			if (tai_leap.sig == NULL)
969 				tai_leap.sig =
970 				    emalloc(private_key.bits / 8);
971 			crypto_agree();
972 			break;
973 #endif /* PUBKEY */
974 
975 		/*
976 		 * For other requests, save the request code for later;
977 		 * for unknown responses or errors, just ignore for now.
978 		 */
979 		default:
980 			if (code & (CRYPTO_RESP | CRYPTO_ERROR))
981 				break;
982 			peer->cmmd = ntohl(pkt[i]);
983 			break;
984 
985 		}
986 		authlen += len;
987 	}
988 }
989 
990 
991 /*
992  * crypto_xmit - construct extension fields
993  *
994  * This routine is called both when an association is configured and
995  * when one is not. The only case where this matters now is to retrieve
996  * the autokey information, in which case the caller has to provide the
997  * association ID to match the association.
998  */
999 int				/* return length of extension field */
1000 crypto_xmit(
1001 	u_int32 *xpkt,		/* packet pointer */
1002 	int start,		/* offset to extension field */
1003 	u_int code,		/* extension field code */
1004 	keyid_t cookie,		/* session cookie */
1005 	u_int associd		/* association ID */
1006 	)
1007 {
1008 	struct peer *peer;	/* peer structure pointer */
1009 	struct autokey *ap;	/* autokey pointer */
1010 	struct cookie *cp;	/* cookie pointer */
1011 	int len;		/* extension field length */
1012 	u_int opcode;		/* extension field opcode */
1013 	int i;
1014 #ifdef PUBKEY
1015 	R_SIGNATURE_CTX ctx;	/* signature context */
1016 	struct value *vp;	/* value pointer */
1017 	int rval;		/* return value */
1018 	u_int temp;
1019 	int j;
1020 #endif /* PUBKEY */
1021 
1022 	/*
1023 	 * Generate the requested extension field request code, length
1024 	 * and association ID. Note that several extension fields are
1025 	 * used with and without public-key cryptography. If public-key
1026 	 * cryptography has not been configured, we do the same thing,
1027 	 * but leave off the signature.
1028 	 */
1029 	i = start / 4;
1030 	opcode = code;
1031 	xpkt[i + 1] = htonl(associd);
1032 	len = 8;
1033 	switch (opcode) {
1034 
1035 	/*
1036 	 * Send association ID, timestamp and status word.
1037 	 */
1038 	case CRYPTO_ASSOC | CRYPTO_RESP:
1039 		cp = (struct cookie *)&xpkt[i + 2];
1040 #ifdef PUBKEY
1041 		cp->tstamp = host.tstamp;
1042 #else
1043 		cp->tstamp = 0;
1044 #endif /* PUBKEY */
1045 		cp->key = htonl(crypto_flags);
1046 		cp->siglen = 0;
1047 		len += 12;
1048 		break;
1049 
1050 	/*
1051 	 * Find peer and send autokey data and signature in broadcast
1052 	 * server and symmetric modes. If no association is found,
1053 	 * either the server has restarted with new associations or some
1054 	 * perp has replayed an old message.
1055 	 */
1056 	case CRYPTO_AUTO | CRYPTO_RESP:
1057 		peer = findpeerbyassoc(associd);
1058 		if (peer == NULL) {
1059 			opcode |= CRYPTO_ERROR;
1060 			break;
1061 		}
1062 		peer->flags &= ~FLAG_ASSOC;
1063 		ap = (struct autokey *)&xpkt[i + 2];
1064 		ap->tstamp = peer->sndauto.tstamp;
1065 		ap->seq = peer->sndauto.seq;
1066 		ap->key = peer->sndauto.key;
1067 		ap->siglen = peer->sndauto.siglen;
1068 		len += 16;
1069 #ifdef PUBKEY
1070 		if (!crypto_flags)
1071 			break;
1072 		temp = ntohl(ap->siglen);
1073 		if (temp != 0)
1074 			memcpy(ap->pkt, peer->sndauto.sig, temp);
1075 		len += temp;
1076 #endif /* PUBKEY */
1077 		break;
1078 
1079 	/*
1080 	 * Send peer cookie and signature in server mode.
1081 	 */
1082 	case CRYPTO_PRIV:
1083 	case CRYPTO_PRIV | CRYPTO_RESP:
1084 		cp = (struct cookie *)&xpkt[i + 2];
1085 		cp->key = htonl(cookie);
1086 		cp->siglen = 0;
1087 		len += 12;
1088 #ifdef PUBKEY
1089 		cp->tstamp = host.tstamp;
1090 		if (!crypto_flags)
1091 			break;
1092 		EVP_SignInit(&ctx, DA_MD5);
1093 		EVP_SignUpdate(&ctx, (u_char *)cp, 8);
1094 		rval = EVP_SignFinal(&ctx, (u_char *)cp->pkt, &temp,
1095 		    &private_key);
1096 		if (rval != RV_OK) {
1097 			msyslog(LOG_ERR,
1098 			    "crypto: cookie signature fails %x", rval);
1099 			break;
1100 		}
1101 		cp->siglen = htonl(temp);
1102 		len += temp;
1103 #endif /* PUBKEY */
1104 		break;
1105 
1106 #ifdef PUBKEY
1107 	/*
1108 	 * The following commands and responses work only when public-
1109 	 * key cryptography has been configured. If configured, but
1110 	 * disabled due to no crypto command in the configuration file,
1111 	 * they are ignored and an error response is returned.
1112 	 */
1113 	/*
1114 	 * Send certificate, timestamp and signature.
1115 	 */
1116 	case CRYPTO_CERT | CRYPTO_RESP:
1117 		if (!crypto_flags) {
1118 			opcode |= CRYPTO_ERROR;
1119 			break;
1120 		}
1121 		vp = (struct value *)&xpkt[i + 2];
1122 		vp->tstamp = certif.tstamp;
1123 		vp->fstamp = certif.fstamp;
1124 		vp->vallen = 0;
1125 		len += 12;
1126 		temp = ntohl(certif.vallen);
1127 		if (temp == 0)
1128 			break;
1129 		vp->vallen = htonl(temp);
1130 		memcpy(vp->pkt, certif.ptr, temp);
1131 		len += temp;
1132 		j = i + 5 + temp / 4;
1133 		temp = public_key.bits / 8;
1134 		xpkt[j++] = htonl(temp);
1135 		memcpy(&xpkt[j], certif.sig, temp);
1136 		len += temp + 4;
1137 		break;
1138 
1139 	/*
1140 	 * Send agreement parameters, timestamp and signature.
1141 	 */
1142 	case CRYPTO_DHPAR | CRYPTO_RESP:
1143 		if (!crypto_flags) {
1144 			opcode |= CRYPTO_ERROR;
1145 			break;
1146 		}
1147 		vp = (struct value *)&xpkt[i + 2];
1148 		vp->tstamp = dhparam.tstamp;
1149 		vp->fstamp = dhparam.fstamp;
1150 		vp->vallen = 0;
1151 		len += 12;
1152 		temp = ntohl(dhparam.vallen);
1153 		if (temp == 0)
1154 			break;
1155 		vp->vallen = htonl(temp);
1156 		memcpy(vp->pkt, dhparam.ptr, temp);
1157 		len += temp;
1158 		j = i + 5 + temp / 4;
1159 		temp = public_key.bits / 8;
1160 		xpkt[j++] = htonl(temp);
1161 		memcpy(&xpkt[j], dhparam.sig, temp);
1162 		len += temp + 4;
1163 		break;
1164 
1165 	/*
1166 	 * Send public value, timestamp and signature.
1167 	 */
1168 	case CRYPTO_DH:
1169 	case CRYPTO_DH | CRYPTO_RESP:
1170 		if (!crypto_flags) {
1171 			opcode |= CRYPTO_ERROR;
1172 			break;
1173 		}
1174 		vp = (struct value *)&xpkt[i + 2];
1175 		vp->tstamp = dhpub.tstamp;
1176 		vp->fstamp = dhpub.fstamp;
1177 		vp->vallen = 0;
1178 		len += 12;
1179 		temp = ntohl(dhpub.vallen);
1180 		if (temp == 0)
1181 			break;
1182 		vp->vallen = htonl(temp);
1183 		memcpy(vp->pkt, dhpub.ptr, temp);
1184 		len += temp;
1185 		j = i + 5 + temp / 4;
1186 		temp = public_key.bits / 8;
1187 		xpkt[j++] = htonl(temp);
1188 		memcpy(&xpkt[j], dhpub.sig, temp);
1189 		len += temp + 4;
1190 		break;
1191 
1192 	/*
1193 	 * Send public key, host name, timestamp and signature.
1194 	 */
1195 	case CRYPTO_NAME | CRYPTO_RESP:
1196 		if (!crypto_flags) {
1197 			opcode |= CRYPTO_ERROR;
1198 			break;
1199 		}
1200 		vp = (struct value *)&xpkt[i + 2];
1201 		vp->tstamp = host.tstamp;
1202 		vp->fstamp = host.fstamp;
1203 		vp->vallen = 0;
1204 		len += 12;
1205 		temp = ntohl(host.vallen);
1206 		if (temp == 0)
1207 			break;
1208 		vp->vallen = htonl(temp);
1209 		memcpy(vp->pkt, host.ptr, temp);
1210 		len += temp;
1211 		j = i + 5 + temp / 4;
1212 		temp = public_key.bits / 8;
1213 		xpkt[j++] = htonl(temp);
1214 		memcpy(&xpkt[j], host.sig, temp);
1215 		len += temp + 4;
1216 		break;
1217 
1218 	/*
1219 	 * Send leapseconds table, timestamp and signature.
1220 	 */
1221 	case CRYPTO_TAI | CRYPTO_RESP:
1222 		if (!crypto_flags) {
1223 			opcode |= CRYPTO_ERROR;
1224 			break;
1225 		}
1226 		vp = (struct value *)&xpkt[i + 2];
1227 		vp->tstamp = tai_leap.tstamp;
1228 		vp->fstamp = tai_leap.fstamp;
1229 		vp->vallen = 0;
1230 		len += 12;
1231 		temp = ntohl(tai_leap.vallen);
1232 		if (temp == 0)
1233 			break;
1234 		vp->vallen = htonl(temp);
1235 		memcpy(vp->pkt, tai_leap.ptr, temp);
1236 		len += temp;
1237 		j = i + 5 + temp / 4;
1238 		temp = public_key.bits / 8;
1239 		xpkt[j++] = htonl(temp);
1240 		memcpy(&xpkt[j], tai_leap.sig, temp);
1241 		len += temp + 4;
1242 		break;
1243 #endif /* PUBKEY */
1244 
1245 	/*
1246 	 * Default - Fall through for requests; for unknown responses,
1247 	 * flag as error.
1248 	 */
1249 	default:
1250 		if (opcode & CRYPTO_RESP)
1251 			opcode |= CRYPTO_ERROR;
1252 		break;
1253 	}
1254 
1255 	/*
1256 	 * Round up the field length to a multiple of 8 octets and save
1257 	 * the request code and length.
1258 	 */
1259 	len = ((len + 7) / 8) * 8;
1260 	if (len >= 4) {
1261 		xpkt[i] = htonl((u_int32)((opcode << 16) | len));
1262 #ifdef DEBUG
1263 		if (debug)
1264 			printf(
1265 			    "crypto_xmit: ext offset %d len %d code %x assocID %d\n",
1266 			    start, len, code, associd);
1267 #endif
1268 	}
1269 	return (len);
1270 }
1271 
1272 #ifdef PUBKEY
1273 /*
1274  * crypto_setup - load private key, public key, optional agreement
1275  * parameters and optional leapseconds table, then initialize extension
1276  * fields for later signatures.
1277  */
1278 void
1279 crypto_setup(void)
1280 {
1281 	char filename[MAXFILENAME];
1282 	u_int fstamp;			/* filestamp */
1283 	u_int len, temp;
1284 	u_int32 *pp;
1285 
1286 	/*
1287 	 * Initialize structures.
1288 	 */
1289 	memset(&private_key, 0, sizeof(private_key));
1290 	memset(&public_key, 0, sizeof(public_key));
1291 	memset(&certif, 0, sizeof(certif));
1292 	memset(&dh_params, 0, sizeof(dh_params));
1293 	memset(&host, 0, sizeof(host));
1294 	memset(&dhparam, 0, sizeof(dhparam));
1295 	memset(&dhpub, 0, sizeof(dhpub));
1296 	memset(&tai_leap, 0, sizeof(tai_leap));
1297 	if (!crypto_flags)
1298 		return;
1299 
1300 	/*
1301 	 * Load required private key from file, default "ntpkey".
1302 	 */
1303 	if (private_key_file == NULL)
1304 		private_key_file = "ntpkey";
1305 	host.fstamp = htonl(crypto_rsa(private_key_file,
1306 	    (u_char *)&private_key, sizeof(R_RSA_PRIVATE_KEY)));
1307 
1308 	/*
1309 	 * Load required public key from file, default
1310 	 * "ntpkey_host", where "host" is the canonical name of this
1311 	 * machine.
1312 	 */
1313 	if (public_key_file == NULL) {
1314 		snprintf(filename, MAXFILENAME, "ntpkey_%s",
1315 		    sys_hostname);
1316 		public_key_file = emalloc(strlen(filename) + 1);
1317 		strcpy(public_key_file, filename);
1318 	}
1319 	fstamp = htonl(crypto_rsa(public_key_file,
1320 	    (u_char *)&public_key, sizeof(R_RSA_PUBLIC_KEY)));
1321 	if (fstamp != host.fstamp || strstr(public_key_file,
1322 	    sys_hostname) == NULL) {
1323 		msyslog(LOG_ERR,
1324 		    "crypto: public/private key files mismatch");
1325 		exit (-1);
1326 	}
1327 	crypto_flags |= CRYPTO_FLAG_RSA;
1328 
1329 	/*
1330 	 * Assemble public key and host name in network byte order.
1331 	 * These data will later be signed and sent in response to
1332 	 * a client request. Note that the modulus must be a u_int32 in
1333 	 * network byte order independent of the host order or u_int
1334 	 * size.
1335 	 */
1336 	strcpy(filename, sys_hostname);
1337 	for (len = strlen(filename) + 1; len % 4 != 0; len++)
1338 		filename[len - 1] = 0;
1339 	temp = sizeof(R_RSA_PUBLIC_KEY) - sizeof(u_int) + 4;
1340 	host.vallen = htonl(temp + len);
1341 	pp = emalloc(temp + len);
1342 	host.ptr = (u_char *)pp;
1343 	*pp++ = htonl(public_key.bits);
1344 	memcpy(pp--, public_key.modulus, temp - 4);
1345 	pp += temp / 4;
1346 	memcpy(pp, filename, len);
1347 	host.sig = emalloc(private_key.bits / 8);
1348 
1349 	/*
1350 	 * Load optional certificate from file, default "ntpkey_certif".
1351 	 * If the file is missing or defective, the values can later be
1352 	 * retrieved from a server.
1353 	 */
1354 	if (certif_file == NULL)
1355 		snprintf(filename, MAXFILENAME, "ntpkey_certif_%s",
1356 		    sys_hostname);
1357 		certif_file = emalloc(strlen(filename) + 1);
1358 		strcpy(certif_file, filename);
1359 	crypto_cert(certif_file);
1360 
1361 	/*
1362 	 * Load optional agreement parameters from file, default
1363 	 * "ntpkey_dh". If the file is missing or defective, the values
1364 	 * can later be retrieved from a server.
1365 	 */
1366 	if (dh_params_file == NULL)
1367 		dh_params_file = "ntpkey_dh";
1368 	crypto_dh(dh_params_file);
1369 
1370 	/*
1371 	 * Load optional leapseconds from file, default "ntpkey_leap".
1372 	 * If the file is missing or defective, the values can later be
1373 	 * retrieved from a server.
1374 	 */
1375 	if (tai_leap_file == NULL)
1376 		tai_leap_file = "ntpkey_leap";
1377 	crypto_tai(tai_leap_file);
1378 }
1379 
1380 
1381 /*
1382  * crypto_agree - compute new public value and sign extension fields.
1383  */
1384 void
1385 crypto_agree(void)
1386 {
1387 	R_RANDOM_STRUCT randomstr; /* wiggle bits */
1388 	R_SIGNATURE_CTX ctx;	/* signature context */
1389 	l_fp lstamp;		/* NTP time */
1390 	tstamp_t tstamp;	/* seconds timestamp */
1391 	u_int len, temp;
1392 	int rval, i;
1393 
1394 	/*
1395 	 * Sign host name and timestamps, but only if the clock is
1396 	 * synchronized.
1397 	 */
1398 	if (sys_leap == LEAP_NOTINSYNC)
1399 		return;
1400 	get_systime(&lstamp);
1401 	tstamp = lstamp.l_ui;
1402 	host.tstamp = htonl(tstamp);
1403 	if (!crypto_flags)
1404 		return;
1405 	EVP_SignInit(&ctx, DA_MD5);
1406 	EVP_SignUpdate(&ctx, (u_char *)&host, 12);
1407 	EVP_SignUpdate(&ctx, host.ptr, ntohl(host.vallen));
1408 	rval = EVP_SignFinal(&ctx, host.sig, &len, &private_key);
1409 	if (rval != RV_OK || len != private_key.bits / 8) {
1410 		msyslog(LOG_ERR, "crypto: host signature fails %x",
1411 		    rval);
1412 		exit (-1);
1413 	}
1414 	host.siglen = ntohl(len);
1415 
1416 	/*
1417 	 * Sign certificate and timestamps.
1418 	 */
1419 	if (certif.vallen != 0) {
1420 		certif.tstamp = htonl(tstamp);
1421 		EVP_SignInit(&ctx, DA_MD5);
1422 		EVP_SignUpdate(&ctx, (u_char *)&certif, 12);
1423 		EVP_SignUpdate(&ctx, certif.ptr,
1424 		    ntohl(certif.vallen));
1425 		rval = EVP_SignFinal(&ctx, certif.sig, &len,
1426 		    &private_key);
1427 		if (rval != RV_OK || len != private_key.bits / 8) {
1428 			msyslog(LOG_ERR,
1429 			    "crypto: certificate signature fails %x",
1430 			    rval);
1431 			exit (-1);
1432 		}
1433 		certif.siglen = ntohl(len);
1434 	}
1435 
1436 	/*
1437 	 * Sign agreement parameters and timestamps.
1438 	 */
1439 	if (dhparam.vallen != 0) {
1440 		dhparam.tstamp = htonl(tstamp);
1441 		EVP_SignInit(&ctx, DA_MD5);
1442 		EVP_SignUpdate(&ctx, (u_char *)&dhparam, 12);
1443 		EVP_SignUpdate(&ctx, dhparam.ptr,
1444 		    ntohl(dhparam.vallen));
1445 		rval = EVP_SignFinal(&ctx, dhparam.sig, &len,
1446 		    &private_key);
1447 		if (rval != RV_OK || len != private_key.bits / 8) {
1448 			msyslog(LOG_ERR,
1449 			    "crypto: parameters signature fails %x",
1450 			    rval);
1451 			exit (-11);
1452 		}
1453 		dhparam.siglen = ntohl(len);
1454 
1455 		/*
1456 		 * Compute public value.
1457 		 */
1458 		R_RandomInit(&randomstr);
1459 		R_GetRandomBytesNeeded(&len, &randomstr);
1460 		for (i = 0; i < len; i++) {
1461 			temp = RANDOM;
1462 			R_RandomUpdate(&randomstr, (u_char *)&temp, 1);
1463 		}
1464 		rval = R_SetupDHAgreement(dhpub.ptr, dh_private,
1465 		    dh_keyLen, &dh_params, &randomstr);
1466 		if (rval != RV_OK) {
1467 			msyslog(LOG_ERR,
1468 			    "crypto: invalid public value");
1469 			exit (-1);
1470 		}
1471 
1472 		/*
1473 		 * Sign public value and timestamps.
1474 		 */
1475 		dhpub.tstamp = htonl(tstamp);
1476 		EVP_SignInit(&ctx, DA_MD5);
1477 		EVP_SignUpdate(&ctx, (u_char *)&dhpub, 12);
1478 		EVP_SignUpdate(&ctx, dhpub.ptr, ntohl(dhpub.vallen));
1479 		rval = EVP_SignFinal(&ctx, dhpub.sig, &len,
1480 		    &private_key);
1481 		if (rval != RV_OK || len != private_key.bits / 8) {
1482 			msyslog(LOG_ERR,
1483 			    "crypto: public value signature fails %x",
1484 			    rval);
1485 			exit (-1);
1486 		}
1487 		dhpub.siglen = ntohl(len);
1488 	}
1489 
1490 	/*
1491 	 * Sign leapseconds table and timestamps.
1492 	 */
1493 	if (tai_leap.vallen != 0) {
1494 		tai_leap.tstamp = htonl(tstamp);
1495 		EVP_SignInit(&ctx, DA_MD5);
1496 		EVP_SignUpdate(&ctx, (u_char *)&tai_leap, 12);
1497 		EVP_SignUpdate(&ctx, tai_leap.ptr,
1498 		    ntohl(tai_leap.vallen));
1499 		rval = EVP_SignFinal(&ctx, tai_leap.sig, &len,
1500 		    &private_key);
1501 		if (rval != RV_OK || len != private_key.bits / 8) {
1502 			msyslog(LOG_ERR,
1503 			    "crypto: leapseconds signature fails %x",
1504 			    rval);
1505 			exit (-1);
1506 		}
1507 		tai_leap.siglen = ntohl(len);
1508 	}
1509 #ifdef DEBUG
1510 	if (debug)
1511 		printf(
1512 		    "cypto_agree: ts %u host %u par %u pub %u leap %u\n",
1513 		    tstamp, ntohl(host.fstamp), ntohl(dhparam.fstamp),
1514 		    ntohl(dhpub.fstamp), ntohl(tai_leap.fstamp));
1515 #endif
1516 }
1517 
1518 
1519 /*
1520  * crypto_rsa - read RSA key, decode and check for errors.
1521  */
1522 static u_int
1523 crypto_rsa(
1524 	char *cp,		/* file name */
1525 	u_char *key,		/* key pointer */
1526 	u_int keylen		/* key length */
1527 	)
1528 {
1529 	FILE *str;		/* file handle */
1530 	u_char buf[MAX_LINLEN];	/* file line buffer */
1531 	u_char encoded_key[MAX_ENCLEN]; /* encoded key buffer */
1532 	char filename[MAXFILENAME]; /* name of parameter file */
1533 	char linkname[MAXFILENAME]; /* file link (for filestamp) */
1534 	u_int fstamp;		/* filestamp */
1535 	u_int bits, len;
1536 	char *rptr;
1537 	int rval;
1538 
1539 	/*
1540 	 * Open the file and discard comment lines. If the first
1541 	 * character of the file name is not '/', prepend the keys
1542 	 * directory string.
1543 	 */
1544 	if (*cp == '/')
1545 		strcpy(filename, cp);
1546 	else
1547 		snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
1548 	str = fopen(filename, "r");
1549 	if (str == NULL) {
1550 		msyslog(LOG_ERR, "crypto: RSA file %s not found",
1551 		    filename);
1552 		exit (-1);
1553 	}
1554 
1555 	/*
1556 	 * Ignore initial comments and empty lines.
1557 	 */
1558 	while ((rptr = fgets(buf, MAX_LINLEN - 1, str)) != NULL) {
1559 		len = strlen(buf);
1560 		if (len < 1)
1561 			continue;
1562 		if (*buf == '#' || *buf == '\r' || *buf == '\0')
1563 			continue;
1564 		break;
1565 	}
1566 
1567 	/*
1568 	 * We are rather paranoid here, since an intruder might cause a
1569 	 * coredump by infiltrating a naughty key. The line must contain
1570 	 * a single integer followed by a PEM encoded, null-terminated
1571 	 * string.
1572 	 */
1573 	if (rptr == NULL)
1574 		rval = RV_DAT;
1575 	else if (sscanf(buf, "%d %s", &bits, encoded_key) != 2)
1576 		rval = RV_DAT;
1577 	else if (R_DecodePEMBlock(&buf[sizeof(u_int)], &len,
1578 		    encoded_key, strlen(encoded_key)))
1579 		rval = RV_DEC;
1580 	else if ((len += sizeof(u_int)) != keylen)
1581 		rval = RV_KEY;
1582 	else if (bits < MIN_RSA_MODULUS_BITS || bits >
1583 	    MAX_RSA_MODULUS_BITS)
1584 		rval = RV_KEY;
1585 	else
1586 		rval = RV_OK;
1587 	if (rval != RV_OK) {
1588 		fclose(str);
1589 		msyslog(LOG_ERR, "crypto: RSA file %s error %x", cp,
1590 		    rval);
1591 		exit (-1);
1592 	}
1593 	fclose(str);
1594 	*(u_int *)buf = bits;
1595 	memcpy(key, buf, keylen);
1596 
1597 	/*
1598 	 * Extract filestamp if present.
1599 	 */
1600 	rval = readlink(filename, linkname, MAXFILENAME - 1);
1601 	if (rval > 0) {
1602 		linkname[rval] = '\0';
1603 		rptr = strrchr(linkname, '.');
1604 	} else {
1605 		rptr = strrchr(filename, '.');
1606 	}
1607 	if (rptr != NULL)
1608 		sscanf(++rptr, "%u", &fstamp);
1609 	else
1610 		fstamp = 0;
1611 #ifdef DEBUG
1612 	if (debug)
1613 		printf(
1614 		    "crypto_rsa: key file %s link %d fs %u modulus %d\n",
1615 		    cp, rval, fstamp, bits);
1616 #endif
1617 	return (fstamp);
1618 }
1619 
1620 
1621 /*
1622  * crypto_cert - read certificate
1623  */
1624 static void
1625 crypto_cert(
1626 	char *cp		/* file name */
1627 	)
1628 {
1629 	u_char buf[5000];	/* file line buffer */
1630 	char filename[MAXFILENAME]; /* name of certificate file */
1631 	char linkname[MAXFILENAME]; /* file link (for filestamp) */
1632 	u_int fstamp;		/* filestamp */
1633 	u_int32 *pp;
1634 	u_int len;
1635 	char *rptr;
1636 	int rval, fd;
1637 
1638 	/*
1639 	 * Open the file and discard comment lines. If the first
1640 	 * character of the file name is not '/', prepend the keys
1641 	 * directory string. If the file is not found, not to worry; it
1642 	 * can be retrieved over the net. But, if it is found with
1643 	 * errors, we crash and burn.
1644 	 */
1645 	if (*cp == '/')
1646 		strcpy(filename, cp);
1647 	else
1648 		snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
1649 	fd = open(filename, O_RDONLY, 0777);
1650 	if (fd <= 0) {
1651 		msyslog(LOG_INFO,
1652 		    "crypto: certificate file %s not found",
1653 		    filename);
1654 		return;
1655 	}
1656 
1657 	/*
1658 	 * We are rather paranoid here, since an intruder might cause a
1659 	 * coredump by infiltrating naughty values.
1660 	 */
1661 	rval = RV_OK;
1662 	len = read(fd, buf, 5000);
1663 	close(fd);
1664 	if (rval != RV_OK) {
1665 		msyslog(LOG_ERR,
1666 		    "crypto: certificate file %s error %d", cp,
1667 		    rval);
1668 		exit (-1);
1669 	}
1670 
1671 	/*
1672 	 * The extension field entry consists of the raw certificate.
1673 	 */
1674 	certif.vallen = htonl(200);	/* xxxxxxxxxxxxxxxxxx */
1675 	pp = emalloc(len);
1676 	certif.ptr = (u_char *)pp;
1677 	memcpy(pp, buf, len);
1678 	certif.sig = emalloc(private_key.bits / 8);
1679 	crypto_flags |= CRYPTO_FLAG_CERT;
1680 
1681 	/*
1682 	 * Extract filestamp if present.
1683 	 */
1684 	rval = readlink(filename, linkname, MAXFILENAME - 1);
1685 	if (rval > 0) {
1686 		linkname[rval] = '\0';
1687 		rptr = strrchr(linkname, '.');
1688 	} else {
1689 		rptr = strrchr(filename, '.');
1690 	}
1691 	if (rptr != NULL)
1692 		sscanf(++rptr, "%u", &fstamp);
1693 	else
1694 		fstamp = 0;
1695 	certif.fstamp = htonl(fstamp);
1696 #ifdef DEBUG
1697 	if (debug)
1698 		printf(
1699 		    "crypto_cert: certif file %s link %d fs %u len %d\n",
1700 		    cp, rval, fstamp, len);
1701 #endif
1702 }
1703 
1704 
1705 /*
1706  * crypto_dh - read agreement parameters, decode and check for errors.
1707  */
1708 static void
1709 crypto_dh(
1710 	char *cp		/* file name */
1711 	)
1712 {
1713 	FILE *str;		/* file handle */
1714 	u_char buf[MAX_LINLEN];	/* file line buffer */
1715 	u_char encoded_key[MAX_ENCLEN]; /* encoded key buffer */
1716 	u_char prime[MAX_KEYLEN]; /* decoded prime */
1717 	u_char generator[MAX_KEYLEN]; /* decode generator */
1718 	u_int primelen;		/* prime length (octets) */
1719 	u_int generatorlen;	/* generator length (octets) */
1720 	char filename[MAXFILENAME]; /* name of parameter file */
1721 	char linkname[MAXFILENAME]; /* file link (for filestamp) */
1722 	u_int fstamp;		/* filestamp */
1723 	u_int32 *pp;
1724 	u_int len;
1725 	char *rptr;
1726 	int rval;
1727 
1728 	/*
1729 	 * Open the file and discard comment lines. If the first
1730 	 * character of the file name is not '/', prepend the keys
1731 	 * directory string. If the file is not found, not to worry; it
1732 	 * can be retrieved over the net. But, if it is found with
1733 	 * errors, we crash and burn.
1734 	 */
1735 	if (*cp == '/')
1736 		strcpy(filename, cp);
1737 	else
1738 		snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
1739 	str = fopen(filename, "r");
1740 	if (str == NULL) {
1741 		msyslog(LOG_INFO,
1742 		    "crypto: parameters file %s not found", filename);
1743 		return;
1744 	}
1745 
1746 	/*
1747 	 * Ignore initial comments and empty lines.
1748 	 */
1749 	while ((rptr = fgets(buf, MAX_LINLEN - 1, str)) != NULL) {
1750 		if (strlen(buf) < 1)
1751 			continue;
1752 		if (*buf == '#' || *buf == '\r' || *buf == '\0')
1753 			continue;
1754 		break;
1755 	}
1756 
1757 	/*
1758 	 * We are rather paranoid here, since an intruder might cause a
1759 	 * coredump by infiltrating a naughty key. There must be two
1760 	 * lines; the first contains the prime, the second the
1761 	 * generator. Each line must contain a single integer followed
1762 	 * by a PEM encoded, null-terminated string.
1763 	 */
1764 	if (rptr == NULL)
1765 		rval = RV_DAT;
1766 	else if (sscanf(buf, "%u %s", &primelen, encoded_key) != 2)
1767 		rval = RV_DAT;
1768 	else if (primelen > MAX_KEYLEN)
1769 		rval = RV_KEY;
1770 	else if (R_DecodePEMBlock(prime, &len, encoded_key,
1771 	    strlen(encoded_key)))
1772 		rval = RV_DEC;
1773 	else if (primelen != len || primelen >
1774 	    DECODED_CONTENT_LEN(strlen(encoded_key)))
1775 		rval = RV_DAT;
1776 	else if (fscanf(str, "%u %s", &generatorlen, encoded_key) != 2)
1777 		rval = RV_DAT;
1778 	else if (generatorlen > MAX_KEYLEN)
1779 		rval = RV_KEY;
1780 	else if (R_DecodePEMBlock(generator, &len, encoded_key,
1781 	    strlen(encoded_key)))
1782 		rval = RV_DEC;
1783 	else if (generatorlen != len || generatorlen >
1784 	    DECODED_CONTENT_LEN(strlen(encoded_key)))
1785 		rval = RV_DAT;
1786 	else
1787 		rval = RV_OK;
1788 	if (rval != RV_OK) {
1789 		msyslog(LOG_ERR,
1790 		    "crypto: parameters file %s error %x", cp,
1791 		    rval);
1792 		exit (-1);
1793 	}
1794 	fclose(str);
1795 
1796 	/*
1797 	 * Initialize agreement parameters and extension field in
1798 	 * network byte order. Note the private key length is set
1799 	 * arbitrarily at half the prime length.
1800 	 */
1801 	len = 4 + primelen + 4 + generatorlen;
1802 	dhparam.vallen = htonl(len);
1803 	pp = emalloc(len);
1804 	dhparam.ptr = (u_char *)pp;
1805 	*pp++ = htonl(primelen);
1806 	memcpy(pp, prime, primelen);
1807 	dh_params.prime = (u_char *)pp;
1808 	pp += primelen / 4;
1809 	*pp++ = htonl(generatorlen);
1810 	memcpy(pp, &generator, generatorlen);
1811 	dh_params.generator = (u_char *)pp;
1812 
1813 	dh_params.primeLen = primelen;
1814 	dh_params.generatorLen = generatorlen;
1815 	dh_keyLen = primelen / 2;
1816 	dh_private = emalloc(dh_keyLen);
1817 	dhparam.sig = emalloc(private_key.bits / 8);
1818 	crypto_flags |= CRYPTO_FLAG_DH;
1819 
1820 	/*
1821 	 * Initialize public value extension field.
1822 	 */
1823 	dhpub.vallen = htonl(dh_params.primeLen);
1824 	dhpub.ptr = emalloc(dh_params.primeLen);
1825 	dhpub.sig = emalloc(private_key.bits / 8);
1826 
1827 	/*
1828 	 * Extract filestamp if present.
1829 	 */
1830 	rval = readlink(filename, linkname, MAXFILENAME - 1);
1831 	if (rval > 0) {
1832 		linkname[rval] = '\0';
1833 		rptr = strrchr(linkname, '.');
1834 	} else {
1835 		rptr = strrchr(filename, '.');
1836 	}
1837 	if (rptr != NULL)
1838 		sscanf(++rptr, "%u", &fstamp);
1839 	else
1840 		fstamp = 0;
1841 	dhparam.fstamp = htonl(fstamp);
1842 	dhpub.fstamp = htonl(fstamp);
1843 #ifdef DEBUG
1844 	if (debug)
1845 		printf(
1846 		    "crypto_dh: pars file %s link %d fs %u prime %u gen %u\n",
1847 		    cp, rval, fstamp, dh_params.primeLen,
1848 		    dh_params.generatorLen);
1849 #endif
1850 }
1851 
1852 
1853 /*
1854  * crypto_tai - read leapseconds table and check for errors.
1855  */
1856 static void
1857 crypto_tai(
1858 	char *cp		/* file name */
1859 	)
1860 {
1861 	FILE *str;		/* file handle */
1862 	u_char buf[MAX_LINLEN];	/* file line buffer */
1863 	u_int leapsec[MAX_LEAP]; /* NTP time at leaps */
1864 	u_int offset;		/* offset at leap (s) */
1865 	char filename[MAXFILENAME]; /* name of leapseconds file */
1866 	char linkname[MAXFILENAME]; /* file link (for filestamp) */
1867 	u_int fstamp;		/* filestamp */
1868 	u_int32 *pp;
1869 	u_int len;
1870 	char *rptr;
1871 	int rval, i;
1872 #ifdef KERNEL_PLL
1873 #if NTP_API > 3
1874 	struct timex ntv;	/* kernel interface structure */
1875 #endif /* NTP_API */
1876 #endif /* KERNEL_PLL */
1877 
1878 	/*
1879 	 * Open the file and discard comment lines. If the first
1880 	 * character of the file name is not '/', prepend the keys
1881 	 * directory string. If the file is not found, not to worry; it
1882 	 * can be retrieved over the net. But, if it is found with
1883 	 * errors, we crash and burn.
1884 	 */
1885 	if (*cp == '/')
1886 		strcpy(filename, cp);
1887 	else
1888 		snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
1889 	str = fopen(filename, "r");
1890 	if (str == NULL) {
1891 		msyslog(LOG_INFO,
1892 		    "crypto: leapseconds file %s not found",
1893 		    filename);
1894 		return;
1895 	}
1896 
1897 	/*
1898 	 * We are rather paranoid here, since an intruder might cause a
1899 	 * coredump by infiltrating naughty values. Empty lines and
1900 	 * comments are ignored. Other lines must begin with two
1901 	 * integers followed by junk or comments. The first integer is
1902 	 * the NTP seconds of leap insertion, the second is the offset
1903 	 * of TAI relative to UTC after that insertion. The second word
1904 	 * must equal the initial insertion of ten seconds on 1 January
1905 	 * 1972 plus one second for each succeeding insertion.
1906 	 */
1907 	i = 0;
1908 	rval = RV_OK;
1909 	while (i < MAX_LEAP) {
1910 		rptr = fgets(buf, MAX_LINLEN - 1, str);
1911 		if (rptr == NULL)
1912 			break;
1913 		if (strlen(buf) < 1)
1914 			continue;
1915 		if (*buf == '#')
1916 			continue;
1917 		if (sscanf(buf, "%u %u", &leapsec[i], &offset) != 2)
1918 			continue;
1919 		if (i != offset - TAI_1972) {
1920 			rval = RV_DAT;
1921 			break;
1922 		}
1923 		i++;
1924 	}
1925 	fclose(str);
1926 	if (rval != RV_OK || i == 0) {
1927 		msyslog(LOG_ERR,
1928 		    "crypto: leapseconds file %s error %d", cp,
1929 		    rval);
1930 		exit (-1);
1931 	}
1932 
1933 	/*
1934 	 * The extension field table entries consists of the NTP seconds
1935 	 * of leap insertion in reverse order, so that the most recent
1936 	 * insertion is the first entry in the table.
1937 	 */
1938 	len = i * 4;
1939 	tai_leap.vallen = htonl(len);
1940 	pp = emalloc(len);
1941 	tai_leap.ptr = (u_char *)pp;
1942 	for (; i >= 0; i--) {
1943 		*pp++ = htonl(leapsec[i]);
1944 	}
1945 	tai_leap.sig = emalloc(private_key.bits / 8);
1946 	crypto_flags |= CRYPTO_FLAG_TAI;
1947 	sys_tai = len / 4 + TAI_1972 - 1;
1948 #ifdef KERNEL_PLL
1949 #if NTP_API > 3
1950 	ntv.modes = MOD_TAI;
1951 	ntv.constant = sys_tai;
1952 	if (ntp_adjtime(&ntv) == TIME_ERROR)
1953 		msyslog(LOG_ERR,
1954 		    "crypto: kernel TAI update failed");
1955 #endif /* NTP_API */
1956 #endif /* KERNEL_PLL */
1957 
1958 
1959 	/*
1960 	 * Extract filestamp if present.
1961 	 */
1962 	rval = readlink(filename, linkname, MAXFILENAME - 1);
1963 	if (rval > 0) {
1964 		linkname[rval] = '\0';
1965 		rptr = strrchr(linkname, '.');
1966 	} else {
1967 		rptr = strrchr(filename, '.');
1968 	}
1969 	if (rptr != NULL)
1970 		sscanf(++rptr, "%u", &fstamp);
1971 	else
1972 		fstamp = 0;
1973 	tai_leap.fstamp = htonl(fstamp);
1974 #ifdef DEBUG
1975 	if (debug)
1976 		printf(
1977 		    "crypto_tai: leapseconds file %s link %d fs %u offset %u\n",
1978 		    cp, rval, fstamp, ntohl(tai_leap.vallen) / 4 +
1979 		    TAI_1972);
1980 #endif
1981 }
1982 
1983 
1984 /*
1985  * crypto_config - configure crypto data from crypto configuration
1986  * command.
1987  */
1988 void
1989 crypto_config(
1990 	int item,		/* configuration item */
1991 	char *cp		/* file name */
1992 	)
1993 {
1994 	switch (item) {
1995 
1996 	/*
1997 	 * Initialize flags
1998 	 */
1999 	case CRYPTO_CONF_FLAGS:
2000 		sscanf(cp, "%x", &crypto_flags);
2001 		break;
2002 
2003 	/*
2004 	 * Set private key file name.
2005 	 */
2006 	case CRYPTO_CONF_PRIV:
2007 		private_key_file = emalloc(strlen(cp) + 1);
2008 		strcpy(private_key_file, cp);
2009 		break;
2010 
2011 	/*
2012 	 * Set public key file name.
2013 	 */
2014 	case CRYPTO_CONF_PUBL:
2015 		public_key_file = emalloc(strlen(cp) + 1);
2016 		strcpy(public_key_file, cp);
2017 		break;
2018 
2019 	/*
2020 	 * Set certificate file name.
2021 	 */
2022 	case CRYPTO_CONF_CERT:
2023 		certif_file = emalloc(strlen(cp) + 1);
2024 		strcpy(certif_file, cp);
2025 		break;
2026 
2027 	/*
2028 	 * Set agreement parameter file name.
2029 	 */
2030 	case CRYPTO_CONF_DH:
2031 		dh_params_file = emalloc(strlen(cp) + 1);
2032 		strcpy(dh_params_file, cp);
2033 		break;
2034 
2035 	/*
2036 	 * Set leapseconds table file name.
2037 	 */
2038 	case CRYPTO_CONF_LEAP:
2039 		tai_leap_file = emalloc(strlen(cp) + 1);
2040 		strcpy(tai_leap_file, cp);
2041 		break;
2042 
2043 	/*
2044 	 * Set crypto keys directory.
2045 	 */
2046 	case CRYPTO_CONF_KEYS:
2047 		keysdir = emalloc(strlen(cp) + 1);
2048 		strcpy(keysdir, cp);
2049 		break;
2050 	}
2051 	crypto_flags |= CRYPTO_FLAG_ENAB;
2052 }
2053 # else
2054 int ntp_crypto_bs_pubkey;
2055 # endif /* PUBKEY */
2056 #else
2057 int ntp_crypto_bs_autokey;
2058 #endif /* AUTOKEY */
2059