xref: /freebsd/contrib/ntp/ntpd/ntp_crypto.c (revision b52b9d56d4e96089873a75f9e29062eec19fabba)
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 			if (ntp_adjtime(&ntv) == TIME_ERROR)
954 				msyslog(LOG_ERR,
955 				    "kernel TAI update failed");
956 #endif /* NTP_API */
957 #endif /* KERNEL_PLL */
958 
959 			/*
960 			 * Initialize leapseconds table and extension
961 			 * field in network byte order.
962 			 */
963 			tai_leap.tstamp = vp->tstamp;
964 			tai_leap.fstamp = vp->fstamp;
965 			tai_leap.vallen = vp->vallen;
966 			if (tai_leap.ptr == NULL)
967 				free(tai_leap.ptr);
968 			tai_leap.ptr = emalloc(temp);
969 			memcpy(tai_leap.ptr, vp->pkt, temp);
970 			if (tai_leap.sig == NULL)
971 				tai_leap.sig =
972 				    emalloc(private_key.bits / 8);
973 			crypto_agree();
974 			break;
975 #endif /* PUBKEY */
976 
977 		/*
978 		 * For other requests, save the request code for later;
979 		 * for unknown responses or errors, just ignore for now.
980 		 */
981 		default:
982 			if (code & (CRYPTO_RESP | CRYPTO_ERROR))
983 				break;
984 			peer->cmmd = ntohl(pkt[i]);
985 			break;
986 
987 		}
988 		authlen += len;
989 	}
990 }
991 
992 
993 /*
994  * crypto_xmit - construct extension fields
995  *
996  * This routine is called both when an association is configured and
997  * when one is not. The only case where this matters now is to retrieve
998  * the autokey information, in which case the caller has to provide the
999  * association ID to match the association.
1000  */
1001 int				/* return length of extension field */
1002 crypto_xmit(
1003 	u_int32 *xpkt,		/* packet pointer */
1004 	int start,		/* offset to extension field */
1005 	u_int code,		/* extension field code */
1006 	keyid_t cookie,		/* session cookie */
1007 	u_int associd		/* association ID */
1008 	)
1009 {
1010 	struct peer *peer;	/* peer structure pointer */
1011 	struct autokey *ap;	/* autokey pointer */
1012 	struct cookie *cp;	/* cookie pointer */
1013 	int len;		/* extension field length */
1014 	u_int opcode;		/* extension field opcode */
1015 	int i;
1016 #ifdef PUBKEY
1017 	R_SIGNATURE_CTX ctx;	/* signature context */
1018 	struct value *vp;	/* value pointer */
1019 	int rval;		/* return value */
1020 	u_int temp;
1021 	int j;
1022 #endif /* PUBKEY */
1023 
1024 	/*
1025 	 * Generate the requested extension field request code, length
1026 	 * and association ID. Note that several extension fields are
1027 	 * used with and without public-key cryptography. If public-key
1028 	 * cryptography has not been configured, we do the same thing,
1029 	 * but leave off the signature.
1030 	 */
1031 	i = start / 4;
1032 	opcode = code;
1033 	xpkt[i + 1] = htonl(associd);
1034 	len = 8;
1035 	switch (opcode) {
1036 
1037 	/*
1038 	 * Send association ID, timestamp and status word.
1039 	 */
1040 	case CRYPTO_ASSOC | CRYPTO_RESP:
1041 		cp = (struct cookie *)&xpkt[i + 2];
1042 #ifdef PUBKEY
1043 		cp->tstamp = host.tstamp;
1044 #else
1045 		cp->tstamp = 0;
1046 #endif /* PUBKEY */
1047 		cp->key = htonl(crypto_flags);
1048 		cp->siglen = 0;
1049 		len += 12;
1050 		break;
1051 
1052 	/*
1053 	 * Find peer and send autokey data and signature in broadcast
1054 	 * server and symmetric modes. If no association is found,
1055 	 * either the server has restarted with new associations or some
1056 	 * perp has replayed an old message.
1057 	 */
1058 	case CRYPTO_AUTO | CRYPTO_RESP:
1059 		peer = findpeerbyassoc(associd);
1060 		if (peer == NULL) {
1061 			opcode |= CRYPTO_ERROR;
1062 			break;
1063 		}
1064 		peer->flags &= ~FLAG_ASSOC;
1065 		ap = (struct autokey *)&xpkt[i + 2];
1066 		ap->tstamp = peer->sndauto.tstamp;
1067 		ap->seq = peer->sndauto.seq;
1068 		ap->key = peer->sndauto.key;
1069 		ap->siglen = peer->sndauto.siglen;
1070 		len += 16;
1071 #ifdef PUBKEY
1072 		if (!crypto_flags)
1073 			break;
1074 		temp = ntohl(ap->siglen);
1075 		if (temp != 0)
1076 			memcpy(ap->pkt, peer->sndauto.sig, temp);
1077 		len += temp;
1078 #endif /* PUBKEY */
1079 		break;
1080 
1081 	/*
1082 	 * Send peer cookie and signature in server mode.
1083 	 */
1084 	case CRYPTO_PRIV:
1085 	case CRYPTO_PRIV | CRYPTO_RESP:
1086 		cp = (struct cookie *)&xpkt[i + 2];
1087 		cp->key = htonl(cookie);
1088 		cp->siglen = 0;
1089 		len += 12;
1090 #ifdef PUBKEY
1091 		cp->tstamp = host.tstamp;
1092 		if (!crypto_flags)
1093 			break;
1094 		EVP_SignInit(&ctx, DA_MD5);
1095 		EVP_SignUpdate(&ctx, (u_char *)cp, 8);
1096 		rval = EVP_SignFinal(&ctx, (u_char *)cp->pkt, &temp,
1097 		    &private_key);
1098 		if (rval != RV_OK) {
1099 			msyslog(LOG_ERR,
1100 			    "crypto: cookie signature fails %x", rval);
1101 			break;
1102 		}
1103 		cp->siglen = htonl(temp);
1104 		len += temp;
1105 #endif /* PUBKEY */
1106 		break;
1107 
1108 #ifdef PUBKEY
1109 	/*
1110 	 * The following commands and responses work only when public-
1111 	 * key cryptography has been configured. If configured, but
1112 	 * disabled due to no crypto command in the configuration file,
1113 	 * they are ignored and an error response is returned.
1114 	 */
1115 	/*
1116 	 * Send certificate, timestamp and signature.
1117 	 */
1118 	case CRYPTO_CERT | CRYPTO_RESP:
1119 		if (!crypto_flags) {
1120 			opcode |= CRYPTO_ERROR;
1121 			break;
1122 		}
1123 		vp = (struct value *)&xpkt[i + 2];
1124 		vp->tstamp = certif.tstamp;
1125 		vp->fstamp = certif.fstamp;
1126 		vp->vallen = 0;
1127 		len += 12;
1128 		temp = ntohl(certif.vallen);
1129 		if (temp == 0)
1130 			break;
1131 		vp->vallen = htonl(temp);
1132 		memcpy(vp->pkt, certif.ptr, temp);
1133 		len += temp;
1134 		j = i + 5 + temp / 4;
1135 		temp = public_key.bits / 8;
1136 		xpkt[j++] = htonl(temp);
1137 		memcpy(&xpkt[j], certif.sig, temp);
1138 		len += temp + 4;
1139 		break;
1140 
1141 	/*
1142 	 * Send agreement parameters, timestamp and signature.
1143 	 */
1144 	case CRYPTO_DHPAR | CRYPTO_RESP:
1145 		if (!crypto_flags) {
1146 			opcode |= CRYPTO_ERROR;
1147 			break;
1148 		}
1149 		vp = (struct value *)&xpkt[i + 2];
1150 		vp->tstamp = dhparam.tstamp;
1151 		vp->fstamp = dhparam.fstamp;
1152 		vp->vallen = 0;
1153 		len += 12;
1154 		temp = ntohl(dhparam.vallen);
1155 		if (temp == 0)
1156 			break;
1157 		vp->vallen = htonl(temp);
1158 		memcpy(vp->pkt, dhparam.ptr, temp);
1159 		len += temp;
1160 		j = i + 5 + temp / 4;
1161 		temp = public_key.bits / 8;
1162 		xpkt[j++] = htonl(temp);
1163 		memcpy(&xpkt[j], dhparam.sig, temp);
1164 		len += temp + 4;
1165 		break;
1166 
1167 	/*
1168 	 * Send public value, timestamp and signature.
1169 	 */
1170 	case CRYPTO_DH:
1171 	case CRYPTO_DH | CRYPTO_RESP:
1172 		if (!crypto_flags) {
1173 			opcode |= CRYPTO_ERROR;
1174 			break;
1175 		}
1176 		vp = (struct value *)&xpkt[i + 2];
1177 		vp->tstamp = dhpub.tstamp;
1178 		vp->fstamp = dhpub.fstamp;
1179 		vp->vallen = 0;
1180 		len += 12;
1181 		temp = ntohl(dhpub.vallen);
1182 		if (temp == 0)
1183 			break;
1184 		vp->vallen = htonl(temp);
1185 		memcpy(vp->pkt, dhpub.ptr, temp);
1186 		len += temp;
1187 		j = i + 5 + temp / 4;
1188 		temp = public_key.bits / 8;
1189 		xpkt[j++] = htonl(temp);
1190 		memcpy(&xpkt[j], dhpub.sig, temp);
1191 		len += temp + 4;
1192 		break;
1193 
1194 	/*
1195 	 * Send public key, host name, timestamp and signature.
1196 	 */
1197 	case CRYPTO_NAME | CRYPTO_RESP:
1198 		if (!crypto_flags) {
1199 			opcode |= CRYPTO_ERROR;
1200 			break;
1201 		}
1202 		vp = (struct value *)&xpkt[i + 2];
1203 		vp->tstamp = host.tstamp;
1204 		vp->fstamp = host.fstamp;
1205 		vp->vallen = 0;
1206 		len += 12;
1207 		temp = ntohl(host.vallen);
1208 		if (temp == 0)
1209 			break;
1210 		vp->vallen = htonl(temp);
1211 		memcpy(vp->pkt, host.ptr, temp);
1212 		len += temp;
1213 		j = i + 5 + temp / 4;
1214 		temp = public_key.bits / 8;
1215 		xpkt[j++] = htonl(temp);
1216 		memcpy(&xpkt[j], host.sig, temp);
1217 		len += temp + 4;
1218 		break;
1219 
1220 	/*
1221 	 * Send leapseconds table, timestamp and signature.
1222 	 */
1223 	case CRYPTO_TAI | CRYPTO_RESP:
1224 		if (!crypto_flags) {
1225 			opcode |= CRYPTO_ERROR;
1226 			break;
1227 		}
1228 		vp = (struct value *)&xpkt[i + 2];
1229 		vp->tstamp = tai_leap.tstamp;
1230 		vp->fstamp = tai_leap.fstamp;
1231 		vp->vallen = 0;
1232 		len += 12;
1233 		temp = ntohl(tai_leap.vallen);
1234 		if (temp == 0)
1235 			break;
1236 		vp->vallen = htonl(temp);
1237 		memcpy(vp->pkt, tai_leap.ptr, temp);
1238 		len += temp;
1239 		j = i + 5 + temp / 4;
1240 		temp = public_key.bits / 8;
1241 		xpkt[j++] = htonl(temp);
1242 		memcpy(&xpkt[j], tai_leap.sig, temp);
1243 		len += temp + 4;
1244 		break;
1245 #endif /* PUBKEY */
1246 
1247 	/*
1248 	 * Default - Fall through for requests; for unknown responses,
1249 	 * flag as error.
1250 	 */
1251 	default:
1252 		if (opcode & CRYPTO_RESP)
1253 			opcode |= CRYPTO_ERROR;
1254 		break;
1255 	}
1256 
1257 	/*
1258 	 * Round up the field length to a multiple of 8 octets and save
1259 	 * the request code and length.
1260 	 */
1261 	len = ((len + 7) / 8) * 8;
1262 	if (len >= 4) {
1263 		xpkt[i] = htonl((u_int32)((opcode << 16) | len));
1264 #ifdef DEBUG
1265 		if (debug)
1266 			printf(
1267 			    "crypto_xmit: ext offset %d len %d code %x assocID %d\n",
1268 			    start, len, code, associd);
1269 #endif
1270 	}
1271 	return (len);
1272 }
1273 
1274 #ifdef PUBKEY
1275 /*
1276  * crypto_setup - load private key, public key, optional agreement
1277  * parameters and optional leapseconds table, then initialize extension
1278  * fields for later signatures.
1279  */
1280 void
1281 crypto_setup(void)
1282 {
1283 	char filename[MAXFILENAME];
1284 	u_int fstamp;			/* filestamp */
1285 	u_int len, temp;
1286 	u_int32 *pp;
1287 
1288 	/*
1289 	 * Initialize structures.
1290 	 */
1291 	memset(&private_key, 0, sizeof(private_key));
1292 	memset(&public_key, 0, sizeof(public_key));
1293 	memset(&certif, 0, sizeof(certif));
1294 	memset(&dh_params, 0, sizeof(dh_params));
1295 	memset(&host, 0, sizeof(host));
1296 	memset(&dhparam, 0, sizeof(dhparam));
1297 	memset(&dhpub, 0, sizeof(dhpub));
1298 	memset(&tai_leap, 0, sizeof(tai_leap));
1299 	if (!crypto_flags)
1300 		return;
1301 
1302 	/*
1303 	 * Load required private key from file, default "ntpkey".
1304 	 */
1305 	if (private_key_file == NULL)
1306 		private_key_file = "ntpkey";
1307 	host.fstamp = htonl(crypto_rsa(private_key_file,
1308 	    (u_char *)&private_key, sizeof(R_RSA_PRIVATE_KEY)));
1309 
1310 	/*
1311 	 * Load required public key from file, default
1312 	 * "ntpkey_host", where "host" is the canonical name of this
1313 	 * machine.
1314 	 */
1315 	if (public_key_file == NULL) {
1316 		snprintf(filename, MAXFILENAME, "ntpkey_%s",
1317 		    sys_hostname);
1318 		public_key_file = emalloc(strlen(filename) + 1);
1319 		strcpy(public_key_file, filename);
1320 	}
1321 	fstamp = htonl(crypto_rsa(public_key_file,
1322 	    (u_char *)&public_key, sizeof(R_RSA_PUBLIC_KEY)));
1323 	if (fstamp != host.fstamp || strstr(public_key_file,
1324 	    sys_hostname) == NULL) {
1325 		msyslog(LOG_ERR,
1326 		    "crypto: public/private key files mismatch");
1327 		exit (-1);
1328 	}
1329 	crypto_flags |= CRYPTO_FLAG_RSA;
1330 
1331 	/*
1332 	 * Assemble public key and host name in network byte order.
1333 	 * These data will later be signed and sent in response to
1334 	 * a client request. Note that the modulus must be a u_int32 in
1335 	 * network byte order independent of the host order or u_int
1336 	 * size.
1337 	 */
1338 	strcpy(filename, sys_hostname);
1339 	for (len = strlen(filename) + 1; len % 4 != 0; len++)
1340 		filename[len - 1] = 0;
1341 	temp = sizeof(R_RSA_PUBLIC_KEY) - sizeof(u_int) + 4;
1342 	host.vallen = htonl(temp + len);
1343 	pp = emalloc(temp + len);
1344 	host.ptr = (u_char *)pp;
1345 	*pp++ = htonl(public_key.bits);
1346 	memcpy(pp--, public_key.modulus, temp - 4);
1347 	pp += temp / 4;
1348 	memcpy(pp, filename, len);
1349 	host.sig = emalloc(private_key.bits / 8);
1350 
1351 	/*
1352 	 * Load optional certificate from file, default "ntpkey_certif".
1353 	 * If the file is missing or defective, the values can later be
1354 	 * retrieved from a server.
1355 	 */
1356 	if (certif_file == NULL)
1357 		snprintf(filename, MAXFILENAME, "ntpkey_certif_%s",
1358 		    sys_hostname);
1359 		certif_file = emalloc(strlen(filename) + 1);
1360 		strcpy(certif_file, filename);
1361 	crypto_cert(certif_file);
1362 
1363 	/*
1364 	 * Load optional agreement parameters from file, default
1365 	 * "ntpkey_dh". If the file is missing or defective, the values
1366 	 * can later be retrieved from a server.
1367 	 */
1368 	if (dh_params_file == NULL)
1369 		dh_params_file = "ntpkey_dh";
1370 	crypto_dh(dh_params_file);
1371 
1372 	/*
1373 	 * Load optional leapseconds from file, default "ntpkey_leap".
1374 	 * If the file is missing or defective, the values can later be
1375 	 * retrieved from a server.
1376 	 */
1377 	if (tai_leap_file == NULL)
1378 		tai_leap_file = "ntpkey_leap";
1379 	crypto_tai(tai_leap_file);
1380 }
1381 
1382 
1383 /*
1384  * crypto_agree - compute new public value and sign extension fields.
1385  */
1386 void
1387 crypto_agree(void)
1388 {
1389 	R_RANDOM_STRUCT randomstr; /* wiggle bits */
1390 	R_SIGNATURE_CTX ctx;	/* signature context */
1391 	l_fp lstamp;		/* NTP time */
1392 	tstamp_t tstamp;	/* seconds timestamp */
1393 	u_int len, temp;
1394 	int rval, i;
1395 
1396 	/*
1397 	 * Sign host name and timestamps, but only if the clock is
1398 	 * synchronized.
1399 	 */
1400 	if (sys_leap == LEAP_NOTINSYNC)
1401 		return;
1402 	get_systime(&lstamp);
1403 	tstamp = lstamp.l_ui;
1404 	host.tstamp = htonl(tstamp);
1405 	if (!crypto_flags)
1406 		return;
1407 	EVP_SignInit(&ctx, DA_MD5);
1408 	EVP_SignUpdate(&ctx, (u_char *)&host, 12);
1409 	EVP_SignUpdate(&ctx, host.ptr, ntohl(host.vallen));
1410 	rval = EVP_SignFinal(&ctx, host.sig, &len, &private_key);
1411 	if (rval != RV_OK || len != private_key.bits / 8) {
1412 		msyslog(LOG_ERR, "crypto: host signature fails %x",
1413 		    rval);
1414 		exit (-1);
1415 	}
1416 	host.siglen = ntohl(len);
1417 
1418 	/*
1419 	 * Sign certificate and timestamps.
1420 	 */
1421 	if (certif.vallen != 0) {
1422 		certif.tstamp = htonl(tstamp);
1423 		EVP_SignInit(&ctx, DA_MD5);
1424 		EVP_SignUpdate(&ctx, (u_char *)&certif, 12);
1425 		EVP_SignUpdate(&ctx, certif.ptr,
1426 		    ntohl(certif.vallen));
1427 		rval = EVP_SignFinal(&ctx, certif.sig, &len,
1428 		    &private_key);
1429 		if (rval != RV_OK || len != private_key.bits / 8) {
1430 			msyslog(LOG_ERR,
1431 			    "crypto: certificate signature fails %x",
1432 			    rval);
1433 			exit (-1);
1434 		}
1435 		certif.siglen = ntohl(len);
1436 	}
1437 
1438 	/*
1439 	 * Sign agreement parameters and timestamps.
1440 	 */
1441 	if (dhparam.vallen != 0) {
1442 		dhparam.tstamp = htonl(tstamp);
1443 		EVP_SignInit(&ctx, DA_MD5);
1444 		EVP_SignUpdate(&ctx, (u_char *)&dhparam, 12);
1445 		EVP_SignUpdate(&ctx, dhparam.ptr,
1446 		    ntohl(dhparam.vallen));
1447 		rval = EVP_SignFinal(&ctx, dhparam.sig, &len,
1448 		    &private_key);
1449 		if (rval != RV_OK || len != private_key.bits / 8) {
1450 			msyslog(LOG_ERR,
1451 			    "crypto: parameters signature fails %x",
1452 			    rval);
1453 			exit (-11);
1454 		}
1455 		dhparam.siglen = ntohl(len);
1456 
1457 		/*
1458 		 * Compute public value.
1459 		 */
1460 		R_RandomInit(&randomstr);
1461 		R_GetRandomBytesNeeded(&len, &randomstr);
1462 		for (i = 0; i < len; i++) {
1463 			temp = RANDOM;
1464 			R_RandomUpdate(&randomstr, (u_char *)&temp, 1);
1465 		}
1466 		rval = R_SetupDHAgreement(dhpub.ptr, dh_private,
1467 		    dh_keyLen, &dh_params, &randomstr);
1468 		if (rval != RV_OK) {
1469 			msyslog(LOG_ERR,
1470 			    "crypto: invalid public value");
1471 			exit (-1);
1472 		}
1473 
1474 		/*
1475 		 * Sign public value and timestamps.
1476 		 */
1477 		dhpub.tstamp = htonl(tstamp);
1478 		EVP_SignInit(&ctx, DA_MD5);
1479 		EVP_SignUpdate(&ctx, (u_char *)&dhpub, 12);
1480 		EVP_SignUpdate(&ctx, dhpub.ptr, ntohl(dhpub.vallen));
1481 		rval = EVP_SignFinal(&ctx, dhpub.sig, &len,
1482 		    &private_key);
1483 		if (rval != RV_OK || len != private_key.bits / 8) {
1484 			msyslog(LOG_ERR,
1485 			    "crypto: public value signature fails %x",
1486 			    rval);
1487 			exit (-1);
1488 		}
1489 		dhpub.siglen = ntohl(len);
1490 	}
1491 
1492 	/*
1493 	 * Sign leapseconds table and timestamps.
1494 	 */
1495 	if (tai_leap.vallen != 0) {
1496 		tai_leap.tstamp = htonl(tstamp);
1497 		EVP_SignInit(&ctx, DA_MD5);
1498 		EVP_SignUpdate(&ctx, (u_char *)&tai_leap, 12);
1499 		EVP_SignUpdate(&ctx, tai_leap.ptr,
1500 		    ntohl(tai_leap.vallen));
1501 		rval = EVP_SignFinal(&ctx, tai_leap.sig, &len,
1502 		    &private_key);
1503 		if (rval != RV_OK || len != private_key.bits / 8) {
1504 			msyslog(LOG_ERR,
1505 			    "crypto: leapseconds signature fails %x",
1506 			    rval);
1507 			exit (-1);
1508 		}
1509 		tai_leap.siglen = ntohl(len);
1510 	}
1511 #ifdef DEBUG
1512 	if (debug)
1513 		printf(
1514 		    "cypto_agree: ts %u host %u par %u pub %u leap %u\n",
1515 		    tstamp, ntohl(host.fstamp), ntohl(dhparam.fstamp),
1516 		    ntohl(dhpub.fstamp), ntohl(tai_leap.fstamp));
1517 #endif
1518 }
1519 
1520 
1521 /*
1522  * crypto_rsa - read RSA key, decode and check for errors.
1523  */
1524 static u_int
1525 crypto_rsa(
1526 	char *cp,		/* file name */
1527 	u_char *key,		/* key pointer */
1528 	u_int keylen		/* key length */
1529 	)
1530 {
1531 	FILE *str;		/* file handle */
1532 	u_char buf[MAX_LINLEN];	/* file line buffer */
1533 	u_char encoded_key[MAX_ENCLEN]; /* encoded key buffer */
1534 	char filename[MAXFILENAME]; /* name of parameter file */
1535 	char linkname[MAXFILENAME]; /* file link (for filestamp) */
1536 	u_int fstamp;		/* filestamp */
1537 	u_int bits, len;
1538 	char *rptr;
1539 	int rval;
1540 
1541 	/*
1542 	 * Open the file and discard comment lines. If the first
1543 	 * character of the file name is not '/', prepend the keys
1544 	 * directory string.
1545 	 */
1546 	if (*cp == '/')
1547 		strcpy(filename, cp);
1548 	else
1549 		snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
1550 	str = fopen(filename, "r");
1551 	if (str == NULL) {
1552 		msyslog(LOG_ERR, "crypto: RSA file %s not found",
1553 		    filename);
1554 		exit (-1);
1555 	}
1556 
1557 	/*
1558 	 * Ignore initial comments and empty lines.
1559 	 */
1560 	while ((rptr = fgets(buf, MAX_LINLEN - 1, str)) != NULL) {
1561 		len = strlen(buf);
1562 		if (len < 1)
1563 			continue;
1564 		if (*buf == '#' || *buf == '\r' || *buf == '\0')
1565 			continue;
1566 		break;
1567 	}
1568 
1569 	/*
1570 	 * We are rather paranoid here, since an intruder might cause a
1571 	 * coredump by infiltrating a naughty key. The line must contain
1572 	 * a single integer followed by a PEM encoded, null-terminated
1573 	 * string.
1574 	 */
1575 	if (rptr == NULL)
1576 		rval = RV_DAT;
1577 	else if (sscanf(buf, "%d %s", &bits, encoded_key) != 2)
1578 		rval = RV_DAT;
1579 	else if (R_DecodePEMBlock(&buf[sizeof(u_int)], &len,
1580 		    encoded_key, strlen(encoded_key)))
1581 		rval = RV_DEC;
1582 	else if ((len += sizeof(u_int)) != keylen)
1583 		rval = RV_KEY;
1584 	else if (bits < MIN_RSA_MODULUS_BITS || bits >
1585 	    MAX_RSA_MODULUS_BITS)
1586 		rval = RV_KEY;
1587 	else
1588 		rval = RV_OK;
1589 	if (rval != RV_OK) {
1590 		fclose(str);
1591 		msyslog(LOG_ERR, "crypto: RSA file %s error %x", cp,
1592 		    rval);
1593 		exit (-1);
1594 	}
1595 	fclose(str);
1596 	*(u_int *)buf = bits;
1597 	memcpy(key, buf, keylen);
1598 
1599 	/*
1600 	 * Extract filestamp if present.
1601 	 */
1602 	rval = readlink(filename, linkname, MAXFILENAME - 1);
1603 	if (rval > 0) {
1604 		linkname[rval] = '\0';
1605 		rptr = strrchr(linkname, '.');
1606 	} else {
1607 		rptr = strrchr(filename, '.');
1608 	}
1609 	if (rptr != NULL)
1610 		sscanf(++rptr, "%u", &fstamp);
1611 	else
1612 		fstamp = 0;
1613 #ifdef DEBUG
1614 	if (debug)
1615 		printf(
1616 		    "crypto_rsa: key file %s link %d fs %u modulus %d\n",
1617 		    cp, rval, fstamp, bits);
1618 #endif
1619 	return (fstamp);
1620 }
1621 
1622 
1623 /*
1624  * crypto_cert - read certificate
1625  */
1626 static void
1627 crypto_cert(
1628 	char *cp		/* file name */
1629 	)
1630 {
1631 	u_char buf[5000];	/* file line buffer */
1632 	char filename[MAXFILENAME]; /* name of certificate file */
1633 	char linkname[MAXFILENAME]; /* file link (for filestamp) */
1634 	u_int fstamp;		/* filestamp */
1635 	u_int32 *pp;
1636 	u_int len;
1637 	char *rptr;
1638 	int rval, fd;
1639 
1640 	/*
1641 	 * Open the file and discard comment lines. If the first
1642 	 * character of the file name is not '/', prepend the keys
1643 	 * directory string. If the file is not found, not to worry; it
1644 	 * can be retrieved over the net. But, if it is found with
1645 	 * errors, we crash and burn.
1646 	 */
1647 	if (*cp == '/')
1648 		strcpy(filename, cp);
1649 	else
1650 		snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
1651 	fd = open(filename, O_RDONLY, 0777);
1652 	if (fd <= 0) {
1653 		msyslog(LOG_INFO,
1654 		    "crypto: certificate file %s not found",
1655 		    filename);
1656 		return;
1657 	}
1658 
1659 	/*
1660 	 * We are rather paranoid here, since an intruder might cause a
1661 	 * coredump by infiltrating naughty values.
1662 	 */
1663 	rval = RV_OK;
1664 	len = read(fd, buf, 5000);
1665 	close(fd);
1666 	if (rval != RV_OK) {
1667 		msyslog(LOG_ERR,
1668 		    "crypto: certificate file %s error %d", cp,
1669 		    rval);
1670 		exit (-1);
1671 	}
1672 
1673 	/*
1674 	 * The extension field entry consists of the raw certificate.
1675 	 */
1676 	certif.vallen = htonl(200);	/* xxxxxxxxxxxxxxxxxx */
1677 	pp = emalloc(len);
1678 	certif.ptr = (u_char *)pp;
1679 	memcpy(pp, buf, len);
1680 	certif.sig = emalloc(private_key.bits / 8);
1681 	crypto_flags |= CRYPTO_FLAG_CERT;
1682 
1683 	/*
1684 	 * Extract filestamp if present.
1685 	 */
1686 	rval = readlink(filename, linkname, MAXFILENAME - 1);
1687 	if (rval > 0) {
1688 		linkname[rval] = '\0';
1689 		rptr = strrchr(linkname, '.');
1690 	} else {
1691 		rptr = strrchr(filename, '.');
1692 	}
1693 	if (rptr != NULL)
1694 		sscanf(++rptr, "%u", &fstamp);
1695 	else
1696 		fstamp = 0;
1697 	certif.fstamp = htonl(fstamp);
1698 #ifdef DEBUG
1699 	if (debug)
1700 		printf(
1701 		    "crypto_cert: certif file %s link %d fs %u len %d\n",
1702 		    cp, rval, fstamp, len);
1703 #endif
1704 }
1705 
1706 
1707 /*
1708  * crypto_dh - read agreement parameters, decode and check for errors.
1709  */
1710 static void
1711 crypto_dh(
1712 	char *cp		/* file name */
1713 	)
1714 {
1715 	FILE *str;		/* file handle */
1716 	u_char buf[MAX_LINLEN];	/* file line buffer */
1717 	u_char encoded_key[MAX_ENCLEN]; /* encoded key buffer */
1718 	u_char prime[MAX_KEYLEN]; /* decoded prime */
1719 	u_char generator[MAX_KEYLEN]; /* decode generator */
1720 	u_int primelen;		/* prime length (octets) */
1721 	u_int generatorlen;	/* generator length (octets) */
1722 	char filename[MAXFILENAME]; /* name of parameter file */
1723 	char linkname[MAXFILENAME]; /* file link (for filestamp) */
1724 	u_int fstamp;		/* filestamp */
1725 	u_int32 *pp;
1726 	u_int len;
1727 	char *rptr;
1728 	int rval;
1729 
1730 	/*
1731 	 * Open the file and discard comment lines. If the first
1732 	 * character of the file name is not '/', prepend the keys
1733 	 * directory string. If the file is not found, not to worry; it
1734 	 * can be retrieved over the net. But, if it is found with
1735 	 * errors, we crash and burn.
1736 	 */
1737 	if (*cp == '/')
1738 		strcpy(filename, cp);
1739 	else
1740 		snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
1741 	str = fopen(filename, "r");
1742 	if (str == NULL) {
1743 		msyslog(LOG_INFO,
1744 		    "crypto: parameters file %s not found", filename);
1745 		return;
1746 	}
1747 
1748 	/*
1749 	 * Ignore initial comments and empty lines.
1750 	 */
1751 	while ((rptr = fgets(buf, MAX_LINLEN - 1, str)) != NULL) {
1752 		if (strlen(buf) < 1)
1753 			continue;
1754 		if (*buf == '#' || *buf == '\r' || *buf == '\0')
1755 			continue;
1756 		break;
1757 	}
1758 
1759 	/*
1760 	 * We are rather paranoid here, since an intruder might cause a
1761 	 * coredump by infiltrating a naughty key. There must be two
1762 	 * lines; the first contains the prime, the second the
1763 	 * generator. Each line must contain a single integer followed
1764 	 * by a PEM encoded, null-terminated string.
1765 	 */
1766 	if (rptr == NULL)
1767 		rval = RV_DAT;
1768 	else if (sscanf(buf, "%u %s", &primelen, encoded_key) != 2)
1769 		rval = RV_DAT;
1770 	else if (primelen > MAX_KEYLEN)
1771 		rval = RV_KEY;
1772 	else if (R_DecodePEMBlock(prime, &len, encoded_key,
1773 	    strlen(encoded_key)))
1774 		rval = RV_DEC;
1775 	else if (primelen != len || primelen >
1776 	    DECODED_CONTENT_LEN(strlen(encoded_key)))
1777 		rval = RV_DAT;
1778 	else if (fscanf(str, "%u %s", &generatorlen, encoded_key) != 2)
1779 		rval = RV_DAT;
1780 	else if (generatorlen > MAX_KEYLEN)
1781 		rval = RV_KEY;
1782 	else if (R_DecodePEMBlock(generator, &len, encoded_key,
1783 	    strlen(encoded_key)))
1784 		rval = RV_DEC;
1785 	else if (generatorlen != len || generatorlen >
1786 	    DECODED_CONTENT_LEN(strlen(encoded_key)))
1787 		rval = RV_DAT;
1788 	else
1789 		rval = RV_OK;
1790 	if (rval != RV_OK) {
1791 		msyslog(LOG_ERR,
1792 		    "crypto: parameters file %s error %x", cp,
1793 		    rval);
1794 		exit (-1);
1795 	}
1796 	fclose(str);
1797 
1798 	/*
1799 	 * Initialize agreement parameters and extension field in
1800 	 * network byte order. Note the private key length is set
1801 	 * arbitrarily at half the prime length.
1802 	 */
1803 	len = 4 + primelen + 4 + generatorlen;
1804 	dhparam.vallen = htonl(len);
1805 	pp = emalloc(len);
1806 	dhparam.ptr = (u_char *)pp;
1807 	*pp++ = htonl(primelen);
1808 	memcpy(pp, prime, primelen);
1809 	dh_params.prime = (u_char *)pp;
1810 	pp += primelen / 4;
1811 	*pp++ = htonl(generatorlen);
1812 	memcpy(pp, &generator, generatorlen);
1813 	dh_params.generator = (u_char *)pp;
1814 
1815 	dh_params.primeLen = primelen;
1816 	dh_params.generatorLen = generatorlen;
1817 	dh_keyLen = primelen / 2;
1818 	dh_private = emalloc(dh_keyLen);
1819 	dhparam.sig = emalloc(private_key.bits / 8);
1820 	crypto_flags |= CRYPTO_FLAG_DH;
1821 
1822 	/*
1823 	 * Initialize public value extension field.
1824 	 */
1825 	dhpub.vallen = htonl(dh_params.primeLen);
1826 	dhpub.ptr = emalloc(dh_params.primeLen);
1827 	dhpub.sig = emalloc(private_key.bits / 8);
1828 
1829 	/*
1830 	 * Extract filestamp if present.
1831 	 */
1832 	rval = readlink(filename, linkname, MAXFILENAME - 1);
1833 	if (rval > 0) {
1834 		linkname[rval] = '\0';
1835 		rptr = strrchr(linkname, '.');
1836 	} else {
1837 		rptr = strrchr(filename, '.');
1838 	}
1839 	if (rptr != NULL)
1840 		sscanf(++rptr, "%u", &fstamp);
1841 	else
1842 		fstamp = 0;
1843 	dhparam.fstamp = htonl(fstamp);
1844 	dhpub.fstamp = htonl(fstamp);
1845 #ifdef DEBUG
1846 	if (debug)
1847 		printf(
1848 		    "crypto_dh: pars file %s link %d fs %u prime %u gen %u\n",
1849 		    cp, rval, fstamp, dh_params.primeLen,
1850 		    dh_params.generatorLen);
1851 #endif
1852 }
1853 
1854 
1855 /*
1856  * crypto_tai - read leapseconds table and check for errors.
1857  */
1858 static void
1859 crypto_tai(
1860 	char *cp		/* file name */
1861 	)
1862 {
1863 	FILE *str;		/* file handle */
1864 	u_char buf[MAX_LINLEN];	/* file line buffer */
1865 	u_int leapsec[MAX_LEAP]; /* NTP time at leaps */
1866 	u_int offset;		/* offset at leap (s) */
1867 	char filename[MAXFILENAME]; /* name of leapseconds file */
1868 	char linkname[MAXFILENAME]; /* file link (for filestamp) */
1869 	u_int fstamp;		/* filestamp */
1870 	u_int32 *pp;
1871 	u_int len;
1872 	char *rptr;
1873 	int rval, i;
1874 #ifdef KERNEL_PLL
1875 #if NTP_API > 3
1876 	struct timex ntv;	/* kernel interface structure */
1877 #endif /* NTP_API */
1878 #endif /* KERNEL_PLL */
1879 
1880 	/*
1881 	 * Open the file and discard comment lines. If the first
1882 	 * character of the file name is not '/', prepend the keys
1883 	 * directory string. If the file is not found, not to worry; it
1884 	 * can be retrieved over the net. But, if it is found with
1885 	 * errors, we crash and burn.
1886 	 */
1887 	if (*cp == '/')
1888 		strcpy(filename, cp);
1889 	else
1890 		snprintf(filename, MAXFILENAME, "%s/%s", keysdir, cp);
1891 	str = fopen(filename, "r");
1892 	if (str == NULL) {
1893 		msyslog(LOG_INFO,
1894 		    "crypto: leapseconds file %s not found",
1895 		    filename);
1896 		return;
1897 	}
1898 
1899 	/*
1900 	 * We are rather paranoid here, since an intruder might cause a
1901 	 * coredump by infiltrating naughty values. Empty lines and
1902 	 * comments are ignored. Other lines must begin with two
1903 	 * integers followed by junk or comments. The first integer is
1904 	 * the NTP seconds of leap insertion, the second is the offset
1905 	 * of TAI relative to UTC after that insertion. The second word
1906 	 * must equal the initial insertion of ten seconds on 1 January
1907 	 * 1972 plus one second for each succeeding insertion.
1908 	 */
1909 	i = 0;
1910 	rval = RV_OK;
1911 	while (i < MAX_LEAP) {
1912 		rptr = fgets(buf, MAX_LINLEN - 1, str);
1913 		if (rptr == NULL)
1914 			break;
1915 		if (strlen(buf) < 1)
1916 			continue;
1917 		if (*buf == '#')
1918 			continue;
1919 		if (sscanf(buf, "%u %u", &leapsec[i], &offset) != 2)
1920 			continue;
1921 		if (i != offset - TAI_1972) {
1922 			rval = RV_DAT;
1923 			break;
1924 		}
1925 		i++;
1926 	}
1927 	fclose(str);
1928 	if (rval != RV_OK || i == 0) {
1929 		msyslog(LOG_ERR,
1930 		    "crypto: leapseconds file %s error %d", cp,
1931 		    rval);
1932 		exit (-1);
1933 	}
1934 
1935 	/*
1936 	 * The extension field table entries consists of the NTP seconds
1937 	 * of leap insertion in reverse order, so that the most recent
1938 	 * insertion is the first entry in the table.
1939 	 */
1940 	len = i * 4;
1941 	tai_leap.vallen = htonl(len);
1942 	pp = emalloc(len);
1943 	tai_leap.ptr = (u_char *)pp;
1944 	for (; i >= 0; i--) {
1945 		*pp++ = htonl(leapsec[i]);
1946 	}
1947 	tai_leap.sig = emalloc(private_key.bits / 8);
1948 	crypto_flags |= CRYPTO_FLAG_TAI;
1949 	sys_tai = len / 4 + TAI_1972 - 1;
1950 #ifdef KERNEL_PLL
1951 #if NTP_API > 3
1952 	ntv.modes = MOD_TAI;
1953 	ntv.constant = sys_tai;
1954 	if (ntp_adjtime(&ntv) == TIME_ERROR)
1955 		msyslog(LOG_ERR,
1956 		    "crypto: kernel TAI update failed");
1957 #endif /* NTP_API */
1958 #endif /* KERNEL_PLL */
1959 
1960 
1961 	/*
1962 	 * Extract filestamp if present.
1963 	 */
1964 	rval = readlink(filename, linkname, MAXFILENAME - 1);
1965 	if (rval > 0) {
1966 		linkname[rval] = '\0';
1967 		rptr = strrchr(linkname, '.');
1968 	} else {
1969 		rptr = strrchr(filename, '.');
1970 	}
1971 	if (rptr != NULL)
1972 		sscanf(++rptr, "%u", &fstamp);
1973 	else
1974 		fstamp = 0;
1975 	tai_leap.fstamp = htonl(fstamp);
1976 #ifdef DEBUG
1977 	if (debug)
1978 		printf(
1979 		    "crypto_tai: leapseconds file %s link %d fs %u offset %u\n",
1980 		    cp, rval, fstamp, ntohl(tai_leap.vallen) / 4 +
1981 		    TAI_1972);
1982 #endif
1983 }
1984 
1985 
1986 /*
1987  * crypto_config - configure crypto data from crypto configuration
1988  * command.
1989  */
1990 void
1991 crypto_config(
1992 	int item,		/* configuration item */
1993 	char *cp		/* file name */
1994 	)
1995 {
1996 	switch (item) {
1997 
1998 	/*
1999 	 * Initialize flags
2000 	 */
2001 	case CRYPTO_CONF_FLAGS:
2002 		sscanf(cp, "%x", &crypto_flags);
2003 		break;
2004 
2005 	/*
2006 	 * Set private key file name.
2007 	 */
2008 	case CRYPTO_CONF_PRIV:
2009 		private_key_file = emalloc(strlen(cp) + 1);
2010 		strcpy(private_key_file, cp);
2011 		break;
2012 
2013 	/*
2014 	 * Set public key file name.
2015 	 */
2016 	case CRYPTO_CONF_PUBL:
2017 		public_key_file = emalloc(strlen(cp) + 1);
2018 		strcpy(public_key_file, cp);
2019 		break;
2020 
2021 	/*
2022 	 * Set certificate file name.
2023 	 */
2024 	case CRYPTO_CONF_CERT:
2025 		certif_file = emalloc(strlen(cp) + 1);
2026 		strcpy(certif_file, cp);
2027 		break;
2028 
2029 	/*
2030 	 * Set agreement parameter file name.
2031 	 */
2032 	case CRYPTO_CONF_DH:
2033 		dh_params_file = emalloc(strlen(cp) + 1);
2034 		strcpy(dh_params_file, cp);
2035 		break;
2036 
2037 	/*
2038 	 * Set leapseconds table file name.
2039 	 */
2040 	case CRYPTO_CONF_LEAP:
2041 		tai_leap_file = emalloc(strlen(cp) + 1);
2042 		strcpy(tai_leap_file, cp);
2043 		break;
2044 
2045 	/*
2046 	 * Set crypto keys directory.
2047 	 */
2048 	case CRYPTO_CONF_KEYS:
2049 		keysdir = emalloc(strlen(cp) + 1);
2050 		strcpy(keysdir, cp);
2051 		break;
2052 	}
2053 	crypto_flags |= CRYPTO_FLAG_ENAB;
2054 }
2055 # else
2056 int ntp_crypto_bs_pubkey;
2057 # endif /* PUBKEY */
2058 #else
2059 int ntp_crypto_bs_autokey;
2060 #endif /* AUTOKEY */
2061